Skip to main content

uor_foundation/
enforcement.rs

1// @generated by uor-crate from uor-ontology — do not edit manually
2
3//! Declarative enforcement types.
4//!
5//! This module contains the opaque witness types, declarative builders,
6//! the Term AST, and the v0.2.1 ergonomics surface (sealed `Grounded<T>`,
7//! the `Certify` trait, `PipelineFailure`, ring-op phantom wrappers,
8//! fragment markers, dispatch tables, and the `prelude` module).
9//!
10//! # Layers
11//!
12//! - **Layer 1** \[Opaque Witnesses\]: `Datum`, `Validated<T>`, `Derivation`,
13//!   `FreeRank` \[private fields, no public constructors\]
14//! - **Layer 2** \[Declarative Builders\]: `CompileUnitBuilder`,
15//!   `EffectDeclarationBuilder`, etc. \[produce `Validated<T>` on success\]
16//! - **Term AST**: `Term`, `TermArena`, `Binding`, `Assertion`, etc.
17//! - **v0.2.1 Ergonomics**: `OntologyTarget`, `GroundedShape`, `Grounded<T>`,
18//!   `Certify`, `PipelineFailure`, `RingOp<L>`, fragment markers,
19//!   `INHABITANCE_DISPATCH_TABLE`, and the `prelude` module.
20
21use crate::{
22    DecimalTranscendental, HostTypes, MetricAxis, PrimitiveOp, VerificationDomain, ViolationKind,
23    WittLevel,
24};
25use core::marker::PhantomData;
26
27/// Private sealed module preventing downstream implementations.
28/// Only `GroundedCoord` and `GroundedTuple<N>` implement `Sealed`.
29mod sealed {
30    /// Sealed trait. Not publicly implementable because this module is private.
31    pub trait Sealed {}
32    impl Sealed for super::GroundedCoord {}
33    impl<const N: usize> Sealed for super::GroundedTuple<N> {}
34}
35
36/// Internal level-tagged ring value. Width determined by the Witt level.
37/// Variants are emitted parametrically from `schema:WittLevel` individuals
38/// in the ontology; adding a new level to the ontology regenerates this enum.
39/// Not publicly constructible \[sealed within the crate\].
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[allow(clippy::large_enum_variant, dead_code)]
42pub(crate) enum DatumInner {
43    /// W8: 8-bit ring Z/(2^8)Z.
44    W8([u8; 1]),
45    /// W16: 16-bit ring Z/(2^16)Z.
46    W16([u8; 2]),
47    /// W24: 24-bit ring Z/(2^24)Z.
48    W24([u8; 3]),
49    /// W32: 32-bit ring Z/(2^32)Z.
50    W32([u8; 4]),
51    /// W40: 40-bit ring Z/(2^40)Z.
52    W40([u8; 5]),
53    /// W48: 48-bit ring Z/(2^48)Z.
54    W48([u8; 6]),
55    /// W56: 56-bit ring Z/(2^56)Z.
56    W56([u8; 7]),
57    /// W64: 64-bit ring Z/(2^64)Z.
58    W64([u8; 8]),
59    /// W72: 72-bit ring Z/(2^72)Z.
60    W72([u8; 9]),
61    /// W80: 80-bit ring Z/(2^80)Z.
62    W80([u8; 10]),
63    /// W88: 88-bit ring Z/(2^88)Z.
64    W88([u8; 11]),
65    /// W96: 96-bit ring Z/(2^96)Z.
66    W96([u8; 12]),
67    /// W104: 104-bit ring Z/(2^104)Z.
68    W104([u8; 13]),
69    /// W112: 112-bit ring Z/(2^112)Z.
70    W112([u8; 14]),
71    /// W120: 120-bit ring Z/(2^120)Z.
72    W120([u8; 15]),
73    /// W128: 128-bit ring Z/(2^128)Z.
74    W128([u8; 16]),
75}
76
77/// A ring element at its minting Witt level.
78/// Cannot be constructed outside the `uor_foundation` crate.
79/// The only way to obtain a `Datum` is through reduction evaluation
80/// or the two-phase minting boundary (`validate_and_mint_coord` /
81/// `validate_and_mint_tuple`).
82/// # Examples
83/// ```no_run
84/// // A Datum is produced by reduction evaluation or the minting boundary —
85/// // you never construct one directly.
86/// fn inspect_datum(d: &uor_foundation::enforcement::Datum) {
87///     // Query its Witt level (W8 = 8-bit, W32 = 32-bit, etc.)
88///     let _level = d.level();
89///     // Datum width is determined by its level:
90///     //   W8 → 1 byte,  W16 → 2 bytes,  W24 → 3 bytes,  W32 → 4 bytes.
91///     let _bytes = d.as_bytes();
92/// }
93/// ```
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Datum {
96    /// Level-tagged ring value \[sealed\].
97    inner: DatumInner,
98}
99
100impl Datum {
101    /// Returns the Witt level at which this datum was minted.
102    #[inline]
103    #[must_use]
104    pub const fn level(&self) -> WittLevel {
105        match self.inner {
106            DatumInner::W8(_) => WittLevel::W8,
107            DatumInner::W16(_) => WittLevel::W16,
108            DatumInner::W24(_) => WittLevel::new(24),
109            DatumInner::W32(_) => WittLevel::new(32),
110            DatumInner::W40(_) => WittLevel::new(40),
111            DatumInner::W48(_) => WittLevel::new(48),
112            DatumInner::W56(_) => WittLevel::new(56),
113            DatumInner::W64(_) => WittLevel::new(64),
114            DatumInner::W72(_) => WittLevel::new(72),
115            DatumInner::W80(_) => WittLevel::new(80),
116            DatumInner::W88(_) => WittLevel::new(88),
117            DatumInner::W96(_) => WittLevel::new(96),
118            DatumInner::W104(_) => WittLevel::new(104),
119            DatumInner::W112(_) => WittLevel::new(112),
120            DatumInner::W120(_) => WittLevel::new(120),
121            DatumInner::W128(_) => WittLevel::new(128),
122        }
123    }
124
125    /// Returns the raw byte representation of this datum.
126    #[inline]
127    #[must_use]
128    pub fn as_bytes(&self) -> &[u8] {
129        match &self.inner {
130            DatumInner::W8(b) => b,
131            DatumInner::W16(b) => b,
132            DatumInner::W24(b) => b,
133            DatumInner::W32(b) => b,
134            DatumInner::W40(b) => b,
135            DatumInner::W48(b) => b,
136            DatumInner::W56(b) => b,
137            DatumInner::W64(b) => b,
138            DatumInner::W72(b) => b,
139            DatumInner::W80(b) => b,
140            DatumInner::W88(b) => b,
141            DatumInner::W96(b) => b,
142            DatumInner::W104(b) => b,
143            DatumInner::W112(b) => b,
144            DatumInner::W120(b) => b,
145            DatumInner::W128(b) => b,
146        }
147    }
148}
149
150/// Internal level-tagged coordinate value for grounding intermediates.
151/// Variant set mirrors `DatumInner`: one per `schema:WittLevel`.
152#[derive(Debug, Clone, PartialEq, Eq)]
153#[allow(clippy::large_enum_variant, dead_code)]
154pub(crate) enum GroundedCoordInner {
155    /// W8: 8-bit coordinate.
156    W8([u8; 1]),
157    /// W16: 16-bit coordinate.
158    W16([u8; 2]),
159    /// W24: 24-bit coordinate.
160    W24([u8; 3]),
161    /// W32: 32-bit coordinate.
162    W32([u8; 4]),
163    /// W40: 40-bit coordinate.
164    W40([u8; 5]),
165    /// W48: 48-bit coordinate.
166    W48([u8; 6]),
167    /// W56: 56-bit coordinate.
168    W56([u8; 7]),
169    /// W64: 64-bit coordinate.
170    W64([u8; 8]),
171    /// W72: 72-bit coordinate.
172    W72([u8; 9]),
173    /// W80: 80-bit coordinate.
174    W80([u8; 10]),
175    /// W88: 88-bit coordinate.
176    W88([u8; 11]),
177    /// W96: 96-bit coordinate.
178    W96([u8; 12]),
179    /// W104: 104-bit coordinate.
180    W104([u8; 13]),
181    /// W112: 112-bit coordinate.
182    W112([u8; 14]),
183    /// W120: 120-bit coordinate.
184    W120([u8; 15]),
185    /// W128: 128-bit coordinate.
186    W128([u8; 16]),
187}
188
189/// A single grounded coordinate value.
190/// Not a `Datum` \[this is the narrow intermediate that a `Grounding`
191/// impl produces\]. The foundation validates and mints it into a `Datum`.
192/// Uses the same closed level-tagged family as `Datum`, ensuring that
193/// coordinate width matches the target Witt level.
194/// # Examples
195/// ```rust
196/// use uor_foundation::enforcement::GroundedCoord;
197///
198/// // W8: 8-bit ring Z/256Z — lightweight, exhaustive-verification baseline
199/// let byte_coord = GroundedCoord::w8(42);
200///
201/// // W16: 16-bit ring Z/65536Z — audio samples, small indices
202/// let short_coord = GroundedCoord::w16(1000);
203///
204/// // W32: 32-bit ring Z/2^32Z — pixel data, general-purpose integers
205/// let word_coord = GroundedCoord::w32(70_000);
206/// ```
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct GroundedCoord {
209    /// Level-tagged coordinate bytes.
210    pub(crate) inner: GroundedCoordInner,
211}
212
213impl GroundedCoord {
214    /// Construct a W8 coordinate from a `u8` value (little-endian).
215    #[inline]
216    #[must_use]
217    pub const fn w8(value: u8) -> Self {
218        Self {
219            inner: GroundedCoordInner::W8(value.to_le_bytes()),
220        }
221    }
222
223    /// Construct a W16 coordinate from a `u16` value (little-endian).
224    #[inline]
225    #[must_use]
226    pub const fn w16(value: u16) -> Self {
227        Self {
228            inner: GroundedCoordInner::W16(value.to_le_bytes()),
229        }
230    }
231
232    /// Construct a W24 coordinate from a `u32` value (little-endian).
233    #[inline]
234    #[must_use]
235    pub const fn w24(value: u32) -> Self {
236        let full = value.to_le_bytes();
237        let mut out = [0u8; 3];
238        let mut i = 0;
239        while i < 3 {
240            out[i] = full[i];
241            i += 1;
242        }
243        Self {
244            inner: GroundedCoordInner::W24(out),
245        }
246    }
247
248    /// Construct a W32 coordinate from a `u32` value (little-endian).
249    #[inline]
250    #[must_use]
251    pub const fn w32(value: u32) -> Self {
252        Self {
253            inner: GroundedCoordInner::W32(value.to_le_bytes()),
254        }
255    }
256
257    /// Construct a W40 coordinate from a `u64` value (little-endian).
258    #[inline]
259    #[must_use]
260    pub const fn w40(value: u64) -> Self {
261        let full = value.to_le_bytes();
262        let mut out = [0u8; 5];
263        let mut i = 0;
264        while i < 5 {
265            out[i] = full[i];
266            i += 1;
267        }
268        Self {
269            inner: GroundedCoordInner::W40(out),
270        }
271    }
272
273    /// Construct a W48 coordinate from a `u64` value (little-endian).
274    #[inline]
275    #[must_use]
276    pub const fn w48(value: u64) -> Self {
277        let full = value.to_le_bytes();
278        let mut out = [0u8; 6];
279        let mut i = 0;
280        while i < 6 {
281            out[i] = full[i];
282            i += 1;
283        }
284        Self {
285            inner: GroundedCoordInner::W48(out),
286        }
287    }
288
289    /// Construct a W56 coordinate from a `u64` value (little-endian).
290    #[inline]
291    #[must_use]
292    pub const fn w56(value: u64) -> Self {
293        let full = value.to_le_bytes();
294        let mut out = [0u8; 7];
295        let mut i = 0;
296        while i < 7 {
297            out[i] = full[i];
298            i += 1;
299        }
300        Self {
301            inner: GroundedCoordInner::W56(out),
302        }
303    }
304
305    /// Construct a W64 coordinate from a `u64` value (little-endian).
306    #[inline]
307    #[must_use]
308    pub const fn w64(value: u64) -> Self {
309        Self {
310            inner: GroundedCoordInner::W64(value.to_le_bytes()),
311        }
312    }
313
314    /// Construct a W72 coordinate from a `u128` value (little-endian).
315    #[inline]
316    #[must_use]
317    pub const fn w72(value: u128) -> Self {
318        let full = value.to_le_bytes();
319        let mut out = [0u8; 9];
320        let mut i = 0;
321        while i < 9 {
322            out[i] = full[i];
323            i += 1;
324        }
325        Self {
326            inner: GroundedCoordInner::W72(out),
327        }
328    }
329
330    /// Construct a W80 coordinate from a `u128` value (little-endian).
331    #[inline]
332    #[must_use]
333    pub const fn w80(value: u128) -> Self {
334        let full = value.to_le_bytes();
335        let mut out = [0u8; 10];
336        let mut i = 0;
337        while i < 10 {
338            out[i] = full[i];
339            i += 1;
340        }
341        Self {
342            inner: GroundedCoordInner::W80(out),
343        }
344    }
345
346    /// Construct a W88 coordinate from a `u128` value (little-endian).
347    #[inline]
348    #[must_use]
349    pub const fn w88(value: u128) -> Self {
350        let full = value.to_le_bytes();
351        let mut out = [0u8; 11];
352        let mut i = 0;
353        while i < 11 {
354            out[i] = full[i];
355            i += 1;
356        }
357        Self {
358            inner: GroundedCoordInner::W88(out),
359        }
360    }
361
362    /// Construct a W96 coordinate from a `u128` value (little-endian).
363    #[inline]
364    #[must_use]
365    pub const fn w96(value: u128) -> Self {
366        let full = value.to_le_bytes();
367        let mut out = [0u8; 12];
368        let mut i = 0;
369        while i < 12 {
370            out[i] = full[i];
371            i += 1;
372        }
373        Self {
374            inner: GroundedCoordInner::W96(out),
375        }
376    }
377
378    /// Construct a W104 coordinate from a `u128` value (little-endian).
379    #[inline]
380    #[must_use]
381    pub const fn w104(value: u128) -> Self {
382        let full = value.to_le_bytes();
383        let mut out = [0u8; 13];
384        let mut i = 0;
385        while i < 13 {
386            out[i] = full[i];
387            i += 1;
388        }
389        Self {
390            inner: GroundedCoordInner::W104(out),
391        }
392    }
393
394    /// Construct a W112 coordinate from a `u128` value (little-endian).
395    #[inline]
396    #[must_use]
397    pub const fn w112(value: u128) -> Self {
398        let full = value.to_le_bytes();
399        let mut out = [0u8; 14];
400        let mut i = 0;
401        while i < 14 {
402            out[i] = full[i];
403            i += 1;
404        }
405        Self {
406            inner: GroundedCoordInner::W112(out),
407        }
408    }
409
410    /// Construct a W120 coordinate from a `u128` value (little-endian).
411    #[inline]
412    #[must_use]
413    pub const fn w120(value: u128) -> Self {
414        let full = value.to_le_bytes();
415        let mut out = [0u8; 15];
416        let mut i = 0;
417        while i < 15 {
418            out[i] = full[i];
419            i += 1;
420        }
421        Self {
422            inner: GroundedCoordInner::W120(out),
423        }
424    }
425
426    /// Construct a W128 coordinate from a `u128` value (little-endian).
427    #[inline]
428    #[must_use]
429    pub const fn w128(value: u128) -> Self {
430        let full = value.to_le_bytes();
431        let mut out = [0u8; 16];
432        let mut i = 0;
433        while i < 16 {
434            out[i] = full[i];
435            i += 1;
436        }
437        Self {
438            inner: GroundedCoordInner::W128(out),
439        }
440    }
441}
442
443/// A grounded tuple: a fixed-size array of `GroundedCoord` values.
444/// Represents a structured type (e.g., the 8 coordinates of an E8
445/// lattice point). Not a `Datum` until the foundation validates and
446/// mints it. Stack-resident, no heap allocation.
447/// # Examples
448/// ```rust
449/// use uor_foundation::enforcement::{GroundedCoord, GroundedTuple};
450///
451/// // A 2D pixel: (red, green) at W8 (8-bit per channel)
452/// let pixel = GroundedTuple::new([
453///     GroundedCoord::w8(255), // red channel
454///     GroundedCoord::w8(128), // green channel
455/// ]);
456///
457/// // An E8 lattice point: 8 coordinates at W8
458/// let lattice_point = GroundedTuple::new([
459///     GroundedCoord::w8(2), GroundedCoord::w8(0),
460///     GroundedCoord::w8(0), GroundedCoord::w8(0),
461///     GroundedCoord::w8(0), GroundedCoord::w8(0),
462///     GroundedCoord::w8(0), GroundedCoord::w8(0),
463/// ]);
464/// ```
465#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct GroundedTuple<const N: usize> {
467    /// The coordinate array.
468    pub(crate) coords: [GroundedCoord; N],
469}
470
471impl<const N: usize> GroundedTuple<N> {
472    /// Construct a tuple from a fixed-size array of coordinates.
473    #[inline]
474    #[must_use]
475    pub const fn new(coords: [GroundedCoord; N]) -> Self {
476        Self { coords }
477    }
478}
479
480/// Sealed marker trait for grounded intermediates.
481/// Implemented only for `GroundedCoord` and `GroundedTuple<N>`.
482/// Prism code cannot implement this \[the sealed module pattern
483/// prevents it\].
484pub trait GroundedValue: sealed::Sealed {}
485impl GroundedValue for GroundedCoord {}
486impl<const N: usize> GroundedValue for GroundedTuple<N> {}
487
488/// Target §3: sealed marker trait shared by all morphism kinds.
489/// `GroundingMapKind` (inbound) and `ProjectionMapKind` (outbound) both
490/// extend this trait; the four structural markers (`Total`, `Invertible`,
491/// `PreservesStructure`, `PreservesMetric`) are bounded on `MorphismKind`.
492pub trait MorphismKind: morphism_kind_sealed::Sealed {
493    /// The ontology IRI of this morphism kind.
494    const ONTOLOGY_IRI: &'static str;
495}
496
497/// v0.2.2 W4: sealed marker trait for the kind of a `Grounding` map.
498/// Implemented by exactly the `morphism:GroundingMap` individuals declared in
499/// the ontology; downstream cannot extend the kind set.
500pub trait GroundingMapKind: MorphismKind + grounding_map_kind_sealed::Sealed {}
501
502/// Target §3: sealed marker trait for the kind of a `Sinking` projection.
503/// Implemented by exactly the `morphism:ProjectionMap` individuals declared
504/// in the ontology; downstream cannot extend the kind set.
505pub trait ProjectionMapKind: MorphismKind + projection_map_kind_sealed::Sealed {}
506
507/// v0.2.2 W4: kinds whose image is total over the input domain
508/// (every input maps successfully).
509pub trait Total: MorphismKind {}
510
511/// v0.2.2 W4: kinds whose map is injective and admits an inverse on its image.
512pub trait Invertible: MorphismKind {}
513
514/// v0.2.2 W4: kinds whose map preserves the algebraic structure of the
515/// source domain (homomorphism-like).
516pub trait PreservesStructure: MorphismKind {}
517
518/// v0.2.2 W4: kinds whose map preserves the metric of the source domain
519/// (isometry-like).
520pub trait PreservesMetric: MorphismKind {}
521
522/// v0.2.2 W4: kind for raw byte ingestion. Total and invertible; preserves bit identity only.
523#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
524pub struct BinaryGroundingMap;
525
526/// v0.2.2 W4: kind for one-way digest functions (e.g., SHA-256). Total but not invertible; preserves no structure.
527#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
528pub struct DigestGroundingMap;
529
530/// v0.2.2 W4: kind for integer surface symbols. Total, invertible, structure-preserving.
531#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
532pub struct IntegerGroundingMap;
533
534/// v0.2.2 W4: kind for JSON host strings. Invertible on its image, structure-preserving.
535#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
536pub struct JsonGroundingMap;
537
538/// v0.2.2 W4: kind for UTF-8 host strings. Invertible on its image, structure-preserving.
539#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
540pub struct Utf8GroundingMap;
541
542/// Target §3: kind for raw byte projections. Total and invertible; preserves bit identity only.
543#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
544pub struct BinaryProjectionMap;
545
546/// Target §3: kind for fixed-size digests projected outward. Total but not invertible; preserves no structure.
547#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
548pub struct DigestProjectionMap;
549
550/// Target §3: kind for integer surface symbols projected outward. Invertible, structure-preserving.
551#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
552pub struct IntegerProjectionMap;
553
554/// Target §3: kind for JSON host strings projected outward. Invertible, structure-preserving.
555#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
556pub struct JsonProjectionMap;
557
558/// Target §3: kind for UTF-8 host strings projected outward. Invertible, structure-preserving.
559#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
560pub struct Utf8ProjectionMap;
561
562mod morphism_kind_sealed {
563    /// Private supertrait for MorphismKind. Not implementable outside this crate.
564    pub trait Sealed {}
565    impl Sealed for super::BinaryGroundingMap {}
566    impl Sealed for super::DigestGroundingMap {}
567    impl Sealed for super::IntegerGroundingMap {}
568    impl Sealed for super::JsonGroundingMap {}
569    impl Sealed for super::Utf8GroundingMap {}
570    impl Sealed for super::BinaryProjectionMap {}
571    impl Sealed for super::DigestProjectionMap {}
572    impl Sealed for super::IntegerProjectionMap {}
573    impl Sealed for super::JsonProjectionMap {}
574    impl Sealed for super::Utf8ProjectionMap {}
575}
576
577mod grounding_map_kind_sealed {
578    /// Private supertrait. Not implementable outside this crate.
579    pub trait Sealed {}
580    impl Sealed for super::BinaryGroundingMap {}
581    impl Sealed for super::DigestGroundingMap {}
582    impl Sealed for super::IntegerGroundingMap {}
583    impl Sealed for super::JsonGroundingMap {}
584    impl Sealed for super::Utf8GroundingMap {}
585}
586
587mod projection_map_kind_sealed {
588    /// Private supertrait. Not implementable outside this crate.
589    pub trait Sealed {}
590    impl Sealed for super::BinaryProjectionMap {}
591    impl Sealed for super::DigestProjectionMap {}
592    impl Sealed for super::IntegerProjectionMap {}
593    impl Sealed for super::JsonProjectionMap {}
594    impl Sealed for super::Utf8ProjectionMap {}
595}
596
597impl MorphismKind for BinaryGroundingMap {
598    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/BinaryGroundingMap";
599}
600
601impl MorphismKind for DigestGroundingMap {
602    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/DigestGroundingMap";
603}
604
605impl MorphismKind for IntegerGroundingMap {
606    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/IntegerGroundingMap";
607}
608
609impl MorphismKind for JsonGroundingMap {
610    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/JsonGroundingMap";
611}
612
613impl MorphismKind for Utf8GroundingMap {
614    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/Utf8GroundingMap";
615}
616
617impl MorphismKind for BinaryProjectionMap {
618    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/BinaryProjectionMap";
619}
620
621impl MorphismKind for DigestProjectionMap {
622    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/DigestProjectionMap";
623}
624
625impl MorphismKind for IntegerProjectionMap {
626    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/IntegerProjectionMap";
627}
628
629impl MorphismKind for JsonProjectionMap {
630    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/JsonProjectionMap";
631}
632
633impl MorphismKind for Utf8ProjectionMap {
634    const ONTOLOGY_IRI: &'static str = "https://uor.foundation/morphism/Utf8ProjectionMap";
635}
636
637impl GroundingMapKind for BinaryGroundingMap {}
638impl GroundingMapKind for DigestGroundingMap {}
639impl GroundingMapKind for IntegerGroundingMap {}
640impl GroundingMapKind for JsonGroundingMap {}
641impl GroundingMapKind for Utf8GroundingMap {}
642
643impl ProjectionMapKind for BinaryProjectionMap {}
644impl ProjectionMapKind for DigestProjectionMap {}
645impl ProjectionMapKind for IntegerProjectionMap {}
646impl ProjectionMapKind for JsonProjectionMap {}
647impl ProjectionMapKind for Utf8ProjectionMap {}
648
649impl Total for IntegerGroundingMap {}
650impl Invertible for IntegerGroundingMap {}
651impl PreservesStructure for IntegerGroundingMap {}
652
653impl Invertible for Utf8GroundingMap {}
654impl PreservesStructure for Utf8GroundingMap {}
655
656impl Invertible for JsonGroundingMap {}
657impl PreservesStructure for JsonGroundingMap {}
658
659impl Total for DigestGroundingMap {}
660
661impl Total for BinaryGroundingMap {}
662impl Invertible for BinaryGroundingMap {}
663
664impl Invertible for IntegerProjectionMap {}
665impl PreservesStructure for IntegerProjectionMap {}
666
667impl Invertible for Utf8ProjectionMap {}
668impl PreservesStructure for Utf8ProjectionMap {}
669
670impl Invertible for JsonProjectionMap {}
671impl PreservesStructure for JsonProjectionMap {}
672
673impl Total for DigestProjectionMap {}
674
675impl Total for BinaryProjectionMap {}
676impl Invertible for BinaryProjectionMap {}
677
678/// Open trait for boundary crossing: external data to grounded intermediate.
679/// The foundation validates the returned value against the declared
680/// `GroundingShape` and mints it into a `Datum` if conformant.
681/// v0.2.2 W4 adds the `Map: GroundingMapKind` associated type — every impl
682/// must declare what *kind* of grounding map it is. Foundation operations
683/// that require structure preservation gate on `<G as Grounding>::Map: PreservesStructure`,
684/// and a digest-style impl is rejected at the call site.
685/// # Examples
686/// ```no_run
687/// use uor_foundation::enforcement::{
688///     Grounding, GroundedCoord, GroundingProgram, BinaryGroundingMap, combinators,
689/// };
690///
691/// /// Byte-passthrough grounding: reads the first byte of input as a W8 Datum.
692/// struct PassthroughGrounding;
693///
694/// impl Grounding for PassthroughGrounding {
695///     type Output = GroundedCoord;
696///     type Map = BinaryGroundingMap;
697///
698///     // Phase K: provide the combinator program; the type system verifies
699///     // at compile time that its marker tuple matches Self::Map via
700///     // GroundingProgram::from_primitive's MarkersImpliedBy<Map> bound.
701///     fn program(&self) -> GroundingProgram<GroundedCoord, BinaryGroundingMap> {
702///         GroundingProgram::from_primitive(combinators::read_bytes::<GroundedCoord>())
703///     }
704///     // Foundation supplies `ground()` via the sealed `GroundingExt`
705///     // extension trait — downstream implementers provide only `program()`.
706/// }
707/// ```
708pub trait Grounding {
709    /// The grounded intermediate type. Bounded by `GroundedValue`,
710    /// which is sealed \[only `GroundedCoord` and `GroundedTuple<N>`
711    /// are permitted\].
712    type Output: GroundedValue;
713
714    /// v0.2.2 W4: the kind of grounding map this impl is. Sealed to the
715    /// set of `morphism:GroundingMap` individuals declared in the
716    /// ontology. Every impl must declare the kind explicitly; if no kind
717    /// applies, use `BinaryGroundingMap` (the most permissive — total +
718    /// invertible, no structure preservation).
719    type Map: GroundingMapKind;
720
721    /// Phase K / W4 closure (target §4.3 + §9 criterion 1): the combinator
722    /// program that decomposes this grounding. The program's `Map` parameter
723    /// equals the impl's `Map` associated type, so the kind discriminator is
724    /// mechanically verifiable from the combinator decomposition — not a
725    /// promise. This is the only required method; `ground` is foundation-
726    /// supplied via `GroundingExt`.
727    fn program(&self) -> GroundingProgram<Self::Output, Self::Map>;
728}
729
730/// W4 closure (target §4.3 + §9 criterion 1): foundation-authored
731/// extension trait that supplies `ground()` for every `Grounding`
732/// impl. Downstream implementers provide only `program()`;
733/// the foundation runs it via the blanket `impl<G: Grounding>`
734/// below. The sealed supertrait prevents downstream from
735/// implementing `GroundingExt` directly — there is no second path.
736mod grounding_ext_sealed {
737    /// Private supertrait. Not implementable outside this crate.
738    pub trait Sealed {}
739    impl<G: super::Grounding> Sealed for G {}
740}
741
742/// Crate-internal bridge from `GroundingProgram` to `Option<Out>`.
743/// Blanket-impl'd for the two `GroundedValue` members
744/// (`GroundedCoord` and `GroundedTuple<N>`) so the `GroundingExt`
745/// blanket compiles for any output in the closed set.
746pub trait GroundingProgramRun<Out> {
747    /// Run the program on external bytes.
748    fn run_program(&self, external: &[u8]) -> Option<Out>;
749}
750
751impl<Map: GroundingMapKind> GroundingProgramRun<GroundedCoord>
752    for GroundingProgram<GroundedCoord, Map>
753{
754    #[inline]
755    fn run_program(&self, external: &[u8]) -> Option<GroundedCoord> {
756        self.run(external)
757    }
758}
759
760impl<const N: usize, Map: GroundingMapKind> GroundingProgramRun<GroundedTuple<N>>
761    for GroundingProgram<GroundedTuple<N>, Map>
762{
763    #[inline]
764    fn run_program(&self, external: &[u8]) -> Option<GroundedTuple<N>> {
765        self.run(external)
766    }
767}
768
769/// Foundation-supplied `ground()` for every `Grounding` impl.
770/// The blanket `impl<G: Grounding> GroundingExt for G` below
771/// routes every call of `.ground(bytes)` through
772/// `self.program().run_program(bytes)`. Downstream cannot
773/// override this path: `GroundingExt` has a sealed supertrait
774/// and downstream cannot impl `GroundingExt` directly.
775pub trait GroundingExt: Grounding + grounding_ext_sealed::Sealed {
776    /// Map external bytes into a grounded value via this impl's combinator program.
777    /// Returns `None` when the combinator chain rejects the input (e.g. empty slice
778    /// for `ReadBytes`, malformed UTF-8 for `DecodeUtf8`).
779    fn ground(&self, external: &[u8]) -> Option<Self::Output>;
780}
781
782impl<G: Grounding> GroundingExt for G
783where
784    GroundingProgram<G::Output, G::Map>: GroundingProgramRun<G::Output>,
785{
786    #[inline]
787    fn ground(&self, external: &[u8]) -> Option<Self::Output> {
788        self.program().run_program(external)
789    }
790}
791
792/// Target §3 + §4.6: the foundation-owned operational contract for outbound
793/// boundary crossings. Dual of `Grounding`.
794/// A `Sinking` impl projects a `Grounded<Source>` value to a host-side
795/// `Output` through a specific `ProjectionMap` kind. The `&Grounded<Source>`
796/// input is structurally unforgeable (sealed per §2) — no raw data can be
797/// laundered through this contract. Downstream authors implement `Sinking`
798/// for their projection types; the foundation guarantees the input pedigree.
799/// # Examples
800/// ```no_run
801/// use uor_foundation::enforcement::{
802///     Grounded, Sinking, Utf8ProjectionMap, ConstrainedTypeInput,
803/// };
804///
805/// // ADR-060: `Sinking` and `Grounded` carry an `INLINE_BYTES`
806/// // const-generic the application derives from its `HostBounds`; this
807/// // example fixes a concrete width.
808/// const N: usize = 32;
809/// struct MyJsonSink;
810///
811/// impl Sinking<N> for MyJsonSink {
812///     type Source = ConstrainedTypeInput;
813///     type ProjectionMap = Utf8ProjectionMap;
814///     type Output = String;
815///
816///     fn project(&self, grounded: &Grounded<ConstrainedTypeInput, N>) -> String {
817///         format!("{:?}", grounded.unit_address())
818///     }
819/// }
820/// ```
821pub trait Sinking<const INLINE_BYTES: usize> {
822    /// The ring-side shape `T` carried by the `Grounded<T>` being projected.
823    /// Sealed via `GroundedShape` — downstream cannot forge an admissible Source.
824    type Source: GroundedShape;
825
826    /// The ontology-declared ProjectionMap kind this impl serves. Sealed to
827    /// the closed set of `morphism:ProjectionMap` individuals.
828    type ProjectionMap: ProjectionMapKind;
829
830    /// The host-side output type of this projection. Intentionally generic —
831    /// downstream chooses `String`, `Vec<u8>`, `serde_json::Value`, or any
832    /// host-appropriate carrier.
833    type Output;
834
835    /// Project a grounded ring value to the host output. The `&Grounded<Source>`
836    /// input is unforgeable (Grounded is sealed per §2) — no raw data can be
837    /// laundered through this contract.
838    fn project(&self, grounded: &Grounded<'_, Self::Source, INLINE_BYTES>) -> Self::Output;
839}
840
841/// Target §4.6: extension trait tying `EmitEffect<H>` (ontology-declarative)
842/// to `Sinking` (Rust-operational). Emit-effect implementations carry a
843/// specific `Sinking` impl; the emit operation threads a sealed
844/// `Grounded<Source>` through the projection.
845pub trait EmitThrough<const INLINE_BYTES: usize, H: crate::HostTypes>:
846    crate::bridge::boundary::EmitEffect<H>
847{
848    /// The `Sinking` implementation this emit-effect routes through.
849    type Sinking: Sinking<INLINE_BYTES>;
850
851    /// Emit a grounded value through this effect's bound `Sinking`. The
852    /// input type is the sealed `Grounded<Source>` of the bound `Sinking`;
853    /// nothing else is admissible.
854    fn emit(
855        &self,
856        grounded: &Grounded<'_, <Self::Sinking as Sinking<INLINE_BYTES>>::Source, INLINE_BYTES>,
857    ) -> <Self::Sinking as Sinking<INLINE_BYTES>>::Output;
858}
859
860/// v0.2.2 W13: sealed marker trait for the validation phase at which a
861/// `Validated<T, Phase>` was witnessed. Implemented only by `CompileTime`
862/// and `Runtime`; downstream cannot extend.
863pub trait ValidationPhase: validation_phase_sealed::Sealed {}
864
865mod validation_phase_sealed {
866    /// Private supertrait. Not implementable outside this crate.
867    pub trait Sealed {}
868    impl Sealed for super::CompileTime {}
869    impl Sealed for super::Runtime {}
870}
871
872/// v0.2.2 W13: marker for compile-time validated witnesses produced by
873/// `validate_const()` and usable in `const` contexts. Convertible to
874/// `Validated<T, Runtime>` via `From`.
875#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
876pub struct CompileTime;
877impl ValidationPhase for CompileTime {}
878
879/// v0.2.2 W13: marker for runtime-validated witnesses produced by
880/// `validate()`. The default phase of `Validated<T>` so v0.2.1 call
881/// sites continue to compile.
882#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
883pub struct Runtime;
884impl ValidationPhase for Runtime {}
885
886/// Proof that a value was produced by the conformance checker,
887/// not fabricated by Prism code.
888/// The inner value and `_sealed` field are private, so `Validated<T>`
889/// can only be constructed within this crate.
890/// v0.2.2 W13: parameterized by a `Phase: ValidationPhase` discriminator.
891/// `Validated<T, CompileTime>` was witnessed by `validate_const()` and is
892/// usable in const contexts. `Validated<T, Runtime>` (the default) was
893/// witnessed by `validate()`. A `CompileTime` witness is convertible to
894/// a `Runtime` witness via `From`.
895/// # Examples
896/// ```no_run
897/// use uor_foundation::enforcement::{CompileUnitBuilder, ConstrainedTypeInput, Term};
898/// use uor_foundation::{WittLevel, VerificationDomain};
899///
900/// // Validated<T> proves that a value passed conformance checking.
901/// // You cannot construct one directly — only builder validate() methods
902/// // and the minting boundary produce them.
903/// // ADR-060: `Term` carries an `INLINE_BYTES` const-generic the
904/// // application derives from its `HostBounds`; fix a concrete width.
905/// const N: usize = 32;
906/// let terms: [Term<'static, N>; 1] =
907///     [uor_foundation::pipeline::literal_u64(1, WittLevel::W8)];
908/// let domains = [VerificationDomain::Enumerative];
909///
910/// let validated = CompileUnitBuilder::new()
911///     .root_term(&terms)
912///     .witt_level_ceiling(WittLevel::W8)
913///     .thermodynamic_budget(1024)
914///     .target_domains(&domains)
915///     .result_type::<ConstrainedTypeInput>()
916///     .validate()
917///     .expect("all fields set");
918///
919/// // Access the inner value through the proof wrapper:
920/// let _compile_unit = validated.inner();
921/// ```
922#[derive(Debug, Clone, PartialEq, Eq)]
923pub struct Validated<T, Phase: ValidationPhase = Runtime> {
924    /// The validated inner value.
925    inner: T,
926    /// Phantom marker for the validation phase (`CompileTime` or `Runtime`).
927    _phase: PhantomData<Phase>,
928    /// Prevents external construction.
929    _sealed: (),
930}
931
932impl<T, Phase: ValidationPhase> Validated<T, Phase> {
933    /// Returns a reference to the validated inner value.
934    #[inline]
935    #[must_use]
936    pub const fn inner(&self) -> &T {
937        &self.inner
938    }
939
940    /// Creates a new `Validated<T, Phase>` wrapper. Only callable within the crate.
941    #[inline]
942    #[allow(dead_code)]
943    pub(crate) const fn new(inner: T) -> Self {
944        Self {
945            inner,
946            _phase: PhantomData,
947            _sealed: (),
948        }
949    }
950}
951
952/// v0.2.2 W13: a compile-time witness is usable wherever a runtime witness is required.
953impl<T> From<Validated<T, CompileTime>> for Validated<T, Runtime> {
954    #[inline]
955    fn from(value: Validated<T, CompileTime>) -> Self {
956        Self {
957            inner: value.inner,
958            _phase: PhantomData,
959            _sealed: (),
960        }
961    }
962}
963
964/// An opaque derivation trace that can only be extended by the rewrite engine.
965/// Records the rewrite-step count, the source `witt_level_bits`, and the
966/// parametric `content_fingerprint`. Private fields prevent external
967/// construction; produced exclusively by `Grounded::derivation()` so the
968/// verify path can re-derive the source certificate via
969/// `Derivation::replay() -> Trace -> verify_trace`.
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct Derivation {
972    /// Number of rewrite steps in this derivation.
973    step_count: u32,
974    /// v0.2.2 T5: Witt level the source grounding was minted at. Carried
975    /// through replay so the verifier can reconstruct the certificate.
976    witt_level_bits: u16,
977    /// v0.2.2 T5: parametric content fingerprint of the source unit's
978    /// full state, computed at grounding time by the consumer-supplied
979    /// `Hasher`. Carried through replay so the verifier can reproduce
980    /// the source certificate via passthrough.
981    content_fingerprint: ContentFingerprint,
982}
983
984impl Derivation {
985    /// Returns the number of rewrite steps.
986    #[inline]
987    #[must_use]
988    pub const fn step_count(&self) -> u32 {
989        self.step_count
990    }
991
992    /// v0.2.2 T5: returns the Witt level the source grounding was minted at.
993    #[inline]
994    #[must_use]
995    pub const fn witt_level_bits(&self) -> u16 {
996        self.witt_level_bits
997    }
998
999    /// v0.2.2 T5: returns the parametric content fingerprint of the source
1000    /// unit, computed at grounding time by the consumer-supplied `Hasher`.
1001    #[inline]
1002    #[must_use]
1003    pub const fn content_fingerprint(&self) -> ContentFingerprint {
1004        self.content_fingerprint
1005    }
1006
1007    /// Creates a new derivation. Only callable within the crate.
1008    #[inline]
1009    #[must_use]
1010    #[allow(dead_code)]
1011    pub(crate) const fn new(
1012        step_count: u32,
1013        witt_level_bits: u16,
1014        content_fingerprint: ContentFingerprint,
1015    ) -> Self {
1016        Self {
1017            step_count,
1018            witt_level_bits,
1019            content_fingerprint,
1020        }
1021    }
1022}
1023
1024/// An opaque free rank that can only be decremented by `PinningEffect`
1025/// and incremented by `UnbindingEffect` \[never by direct mutation\].
1026#[derive(Debug, Clone, PartialEq, Eq)]
1027pub struct FreeRank {
1028    /// Total site capacity at the Witt level.
1029    total: u32,
1030    /// Currently pinned sites.
1031    pinned: u32,
1032}
1033
1034impl FreeRank {
1035    /// Returns the total site capacity.
1036    #[inline]
1037    #[must_use]
1038    pub const fn total(&self) -> u32 {
1039        self.total
1040    }
1041
1042    /// Returns the number of currently pinned sites.
1043    #[inline]
1044    #[must_use]
1045    pub const fn pinned(&self) -> u32 {
1046        self.pinned
1047    }
1048
1049    /// Returns the number of remaining (unpinned) sites.
1050    #[inline]
1051    #[must_use]
1052    pub const fn remaining(&self) -> u32 {
1053        self.total - self.pinned
1054    }
1055
1056    /// Creates a new free rank. Only callable within the crate.
1057    #[inline]
1058    #[allow(dead_code)]
1059    pub(crate) const fn new(total: u32, pinned: u32) -> Self {
1060        Self { total, pinned }
1061    }
1062}
1063
1064/// v0.2.2 Phase A: sealed `H::Decimal`-backed newtype carrying the
1065/// `observable:LandauerCost` accumulator in `observable:Nats`.
1066/// Monotonic within a pipeline invocation. The UOR ring operates
1067/// at the Landauer temperature (β* = ln 2), so this observable is
1068/// a direct measure of irreversible bit-erasure performed.
1069/// Phase 9: parameterized over `H: HostTypes` so the underlying
1070/// decimal type tracks the host's chosen precision.
1071#[derive(Debug)]
1072pub struct LandauerBudget<H: HostTypes = crate::DefaultHostTypes> {
1073    /// Accumulated Landauer cost in nats. Non-negative, finite.
1074    nats: H::Decimal,
1075    /// Phantom marker pinning the host type.
1076    _phantom: core::marker::PhantomData<H>,
1077    /// Prevents external construction.
1078    _sealed: (),
1079}
1080
1081impl<H: HostTypes> LandauerBudget<H> {
1082    /// Returns the accumulated Landauer cost in nats.
1083    #[inline]
1084    #[must_use]
1085    pub const fn nats(&self) -> H::Decimal {
1086        self.nats
1087    }
1088
1089    /// Crate-internal constructor. Caller guarantees `nats` is
1090    /// non-negative and finite (i.e. not NaN, not infinite).
1091    #[inline]
1092    #[must_use]
1093    #[allow(dead_code)]
1094    pub(crate) const fn new(nats: H::Decimal) -> Self {
1095        Self {
1096            nats,
1097            _phantom: core::marker::PhantomData,
1098            _sealed: (),
1099        }
1100    }
1101
1102    /// Crate-internal constructor for the zero-cost initial budget.
1103    #[inline]
1104    #[must_use]
1105    #[allow(dead_code)]
1106    pub(crate) const fn zero() -> Self {
1107        Self {
1108            nats: H::EMPTY_DECIMAL,
1109            _phantom: core::marker::PhantomData,
1110            _sealed: (),
1111        }
1112    }
1113}
1114
1115impl<H: HostTypes> Copy for LandauerBudget<H> {}
1116impl<H: HostTypes> Clone for LandauerBudget<H> {
1117    #[inline]
1118    fn clone(&self) -> Self {
1119        *self
1120    }
1121}
1122impl<H: HostTypes> PartialEq for LandauerBudget<H> {
1123    #[inline]
1124    fn eq(&self, other: &Self) -> bool {
1125        self.nats == other.nats
1126    }
1127}
1128impl<H: HostTypes> Eq for LandauerBudget<H> {}
1129impl<H: HostTypes> PartialOrd for LandauerBudget<H> {
1130    #[inline]
1131    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1132        Some(self.cmp(other))
1133    }
1134}
1135impl<H: HostTypes> Ord for LandauerBudget<H> {
1136    #[inline]
1137    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1138        // Total order on H::Decimal with NaN excluded by construction.
1139        self.nats
1140            .partial_cmp(&other.nats)
1141            .unwrap_or(core::cmp::Ordering::Equal)
1142    }
1143}
1144impl<H: HostTypes> core::hash::Hash for LandauerBudget<H> {
1145    #[inline]
1146    fn hash<S: core::hash::Hasher>(&self, state: &mut S) {
1147        // DecimalTranscendental::to_bits gives a stable u64 fingerprint
1148        // for any in-range Decimal value.
1149        self.nats.to_bits().hash(state);
1150    }
1151}
1152
1153/// v0.2.2 Phase A: foundation-internal deterministic two-clock value
1154/// carried by every `Grounded<T>` and `Certified<C>`. The two clocks are
1155/// `landauer_nats` (a `LandauerBudget` value backed by `observable:LandauerCost`)
1156/// and `rewrite_steps` (a `u64` backed by `derivation:stepCount` on
1157/// `derivation:TermMetrics`). Each clock is monotonic within a pipeline
1158/// invocation, content-deterministic, ontology-grounded, and binds to a
1159/// physical wall-clock lower bound through established physics (Landauer's
1160/// principle for nats; Margolus-Levitin for rewrite steps). Two clocks
1161/// because exactly two physical lower-bound theorems are grounded; adding
1162/// a third clock would require grounding a third physical theorem.
1163/// `PartialOrd` is component-wise: `a < b` iff every field of `a` is `<=`
1164/// the corresponding field of `b` and at least one is strictly `<`. Two
1165/// `UorTime` values from unrelated computations are genuinely incomparable,
1166/// so `UorTime` is `PartialOrd` but **not** `Ord`.
1167#[derive(Debug)]
1168pub struct UorTime<H: HostTypes = crate::DefaultHostTypes> {
1169    /// Landauer budget consumed, in `observable:Nats`.
1170    landauer_nats: LandauerBudget<H>,
1171    /// Total rewrite steps taken (`derivation:stepCount`).
1172    rewrite_steps: u64,
1173    /// Prevents external construction.
1174    _sealed: (),
1175}
1176
1177impl<H: HostTypes> UorTime<H> {
1178    /// Returns the Landauer budget consumed, in `observable:Nats`.
1179    /// Maps to `observable:LandauerCost`.
1180    #[inline]
1181    #[must_use]
1182    pub const fn landauer_nats(&self) -> LandauerBudget<H> {
1183        self.landauer_nats
1184    }
1185
1186    /// Returns the total rewrite steps taken.
1187    /// Maps to `derivation:stepCount` on `derivation:TermMetrics`.
1188    #[inline]
1189    #[must_use]
1190    pub const fn rewrite_steps(&self) -> u64 {
1191        self.rewrite_steps
1192    }
1193
1194    /// Crate-internal constructor. Reachable only from the pipeline at witness mint time.
1195    #[inline]
1196    #[must_use]
1197    #[allow(dead_code)]
1198    pub(crate) const fn new(landauer_nats: LandauerBudget<H>, rewrite_steps: u64) -> Self {
1199        Self {
1200            landauer_nats,
1201            rewrite_steps,
1202            _sealed: (),
1203        }
1204    }
1205
1206    /// Crate-internal constructor for the zero initial value.
1207    #[inline]
1208    #[must_use]
1209    #[allow(dead_code)]
1210    pub(crate) const fn zero() -> Self {
1211        Self {
1212            landauer_nats: LandauerBudget::<H>::zero(),
1213            rewrite_steps: 0,
1214            _sealed: (),
1215        }
1216    }
1217
1218    /// Returns the provable minimum wall-clock duration that the
1219    /// computation producing this witness could have taken under the
1220    /// given calibration. Returns `max(Landauer-bound, Margolus-Levitin-bound)`.
1221    /// The Landauer bound is `landauer_nats × k_B·T / thermal_power`.
1222    /// The Margolus-Levitin bound is `π·ℏ·rewrite_steps / (2·characteristic_energy)`.
1223    /// Pure arithmetic — no transcendentals, no state. Const-evaluable
1224    /// where the `UorTime` value is known at compile time.
1225    #[inline]
1226    #[must_use]
1227    pub fn min_wall_clock(&self, cal: &Calibration<H>) -> Nanos {
1228        // Landauer bound: nats × k_B·T / thermal_power = seconds.
1229        let landauer_seconds = self.landauer_nats.nats() * cal.k_b_t() / cal.thermal_power();
1230        // Margolus-Levitin bound: π·ℏ / (2·E) per orthogonal state transition.
1231        // π·ℏ ≈ 3.31194e-34 J·s; encoded as the f64 bit pattern of
1232        // `core::f64::consts::PI * 1.054_571_817e-34` so the constant is
1233        // representable across host Decimal types.
1234        let pi_times_h_bar =
1235            <H::Decimal as DecimalTranscendental>::from_bits(crate::PI_TIMES_H_BAR_BITS);
1236        let two = <H::Decimal as DecimalTranscendental>::from_u32(2);
1237        let ml_seconds_per_step = pi_times_h_bar / (two * cal.characteristic_energy());
1238        let steps = <H::Decimal as DecimalTranscendental>::from_u64(self.rewrite_steps);
1239        let ml_seconds = ml_seconds_per_step * steps;
1240        let max_seconds = if landauer_seconds > ml_seconds {
1241            landauer_seconds
1242        } else {
1243            ml_seconds
1244        };
1245        // Convert seconds to nanoseconds, saturate on overflow.
1246        let nanos_per_second =
1247            <H::Decimal as DecimalTranscendental>::from_bits(crate::NANOS_PER_SECOND_BITS);
1248        let nanos = max_seconds * nanos_per_second;
1249        Nanos {
1250            ns: <H::Decimal as DecimalTranscendental>::as_u64_saturating(nanos),
1251            _sealed: (),
1252        }
1253    }
1254}
1255
1256impl<H: HostTypes> Copy for UorTime<H> {}
1257impl<H: HostTypes> Clone for UorTime<H> {
1258    #[inline]
1259    fn clone(&self) -> Self {
1260        *self
1261    }
1262}
1263impl<H: HostTypes> PartialEq for UorTime<H> {
1264    #[inline]
1265    fn eq(&self, other: &Self) -> bool {
1266        self.landauer_nats == other.landauer_nats && self.rewrite_steps == other.rewrite_steps
1267    }
1268}
1269impl<H: HostTypes> Eq for UorTime<H> {}
1270impl<H: HostTypes> core::hash::Hash for UorTime<H> {
1271    #[inline]
1272    fn hash<S: core::hash::Hasher>(&self, state: &mut S) {
1273        self.landauer_nats.hash(state);
1274        self.rewrite_steps.hash(state);
1275    }
1276}
1277impl<H: HostTypes> PartialOrd for UorTime<H> {
1278    #[inline]
1279    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1280        let l = self.landauer_nats.cmp(&other.landauer_nats);
1281        let r = self.rewrite_steps.cmp(&other.rewrite_steps);
1282        match (l, r) {
1283            (core::cmp::Ordering::Equal, core::cmp::Ordering::Equal) => {
1284                Some(core::cmp::Ordering::Equal)
1285            }
1286            (core::cmp::Ordering::Less, core::cmp::Ordering::Less)
1287            | (core::cmp::Ordering::Less, core::cmp::Ordering::Equal)
1288            | (core::cmp::Ordering::Equal, core::cmp::Ordering::Less) => {
1289                Some(core::cmp::Ordering::Less)
1290            }
1291            (core::cmp::Ordering::Greater, core::cmp::Ordering::Greater)
1292            | (core::cmp::Ordering::Greater, core::cmp::Ordering::Equal)
1293            | (core::cmp::Ordering::Equal, core::cmp::Ordering::Greater) => {
1294                Some(core::cmp::Ordering::Greater)
1295            }
1296            _ => None,
1297        }
1298    }
1299}
1300
1301/// v0.2.2 Phase A: sealed lower-bound carrier for wall-clock duration.
1302/// Produced only by `UorTime::min_wall_clock` and similar foundation
1303/// time conversions. The sealing guarantees that any `Nanos` value is
1304/// a provable physical bound, not a raw integer. Developers who need
1305/// the underlying `u64` call `.as_u64()`; the sealing prevents
1306/// accidentally passing a host-measured duration where the type system
1307/// expects "a provable minimum".
1308#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1309pub struct Nanos {
1310    /// The provable lower-bound duration in nanoseconds.
1311    ns: u64,
1312    /// Prevents external construction.
1313    _sealed: (),
1314}
1315
1316impl Nanos {
1317    /// Returns the underlying nanosecond count. The value is a provable
1318    /// physical lower bound under whatever calibration produced it.
1319    #[inline]
1320    #[must_use]
1321    pub const fn as_u64(self) -> u64 {
1322        self.ns
1323    }
1324}
1325
1326/// v0.2.2 Phase A: error returned by `Calibration::new` when the supplied
1327/// physical parameters fail plausibility validation.
1328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1329pub enum CalibrationError {
1330    /// `k_b_t` was non-positive, NaN, or outside the known-universe
1331    /// temperature range (`1e-30 ≤ k_b_t ≤ 1e-15` joules).
1332    ThermalEnergy,
1333    /// `thermal_power` was non-positive, NaN, or above the thermodynamic maximum (`1e9` W).
1334    ThermalPower,
1335    /// `characteristic_energy` was non-positive, NaN, or above the
1336    /// k_B·T × Avogadro-class bound (`1e3` joules).
1337    CharacteristicEnergy,
1338}
1339
1340impl core::fmt::Display for CalibrationError {
1341    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1342        match self {
1343            Self::ThermalEnergy => {
1344                f.write_str("calibration k_b_t out of range (must be in [1e-30, 1e-15] joules)")
1345            }
1346            Self::ThermalPower => {
1347                f.write_str("calibration thermal_power out of range (must be > 0 and <= 1e9 W)")
1348            }
1349            Self::CharacteristicEnergy => f.write_str(
1350                "calibration characteristic_energy out of range (must be > 0 and <= 1e3 J)",
1351            ),
1352        }
1353    }
1354}
1355
1356impl core::error::Error for CalibrationError {}
1357
1358/// v0.2.2 Phase A: physical-substrate calibration for wall-clock binding.
1359/// Construction is open via [`Calibration::new`], but the fields are
1360/// private and validated for physical plausibility. Used to convert
1361/// `UorTime` to a provable wall-clock lower bound via
1362/// [`UorTime::min_wall_clock`].
1363/// **A `Calibration` is never passed into `pipeline::run`,
1364/// `resolver::*::certify`, `validate_const`, or any other foundation entry
1365/// point.** The foundation computes `UorTime` without physical
1366/// interpretation; the developer applies a `Calibration` after the fact.
1367#[derive(Debug)]
1368pub struct Calibration<H: HostTypes = crate::DefaultHostTypes> {
1369    /// Boltzmann constant times temperature, in joules.
1370    k_b_t: H::Decimal,
1371    /// Sustained dissipation in watts.
1372    thermal_power: H::Decimal,
1373    /// Mean energy above ground state, in joules.
1374    characteristic_energy: H::Decimal,
1375    /// Phantom marker pinning the host type.
1376    _phantom: core::marker::PhantomData<H>,
1377}
1378
1379impl<H: HostTypes> Copy for Calibration<H> {}
1380impl<H: HostTypes> Clone for Calibration<H> {
1381    #[inline]
1382    fn clone(&self) -> Self {
1383        *self
1384    }
1385}
1386impl<H: HostTypes> PartialEq for Calibration<H> {
1387    #[inline]
1388    fn eq(&self, other: &Self) -> bool {
1389        self.k_b_t == other.k_b_t
1390            && self.thermal_power == other.thermal_power
1391            && self.characteristic_energy == other.characteristic_energy
1392    }
1393}
1394
1395impl<H: HostTypes> Calibration<H> {
1396    /// Construct a calibration with physically plausible parameters.
1397    /// Validation: every parameter must be positive and finite. `k_b_t`
1398    /// must lie within the known-universe temperature range
1399    /// (`1e-30 <= k_b_t <= 1e-15` joules covers ~1 nK to ~1e8 K).
1400    /// `thermal_power` must be at most `1e9` W (gigawatt class — far above
1401    /// any plausible single-compute envelope). `characteristic_energy`
1402    /// must be at most `1e3` J (kilojoule class — astronomically generous).
1403    /// # Errors
1404    /// Returns `CalibrationError::InvalidThermalEnergy` when `k_b_t` is
1405    /// non-positive, NaN, or outside the temperature range.
1406    /// Returns `CalibrationError::InvalidThermalPower` when `thermal_power`
1407    /// is non-positive, NaN, or above the maximum.
1408    /// Returns `CalibrationError::InvalidCharacteristicEnergy` when
1409    /// `characteristic_energy` is non-positive, NaN, or above the maximum.
1410    /// # Example
1411    /// ```
1412    /// use uor_foundation::enforcement::Calibration;
1413    /// use uor_foundation::DefaultHostTypes;
1414    /// // X86 server-class envelope at room temperature.
1415    /// // k_B·T at 300 K = 4.14e-21 J; 85 W sustained TDP; ~1e-15 J/op.
1416    /// let cal = Calibration::<DefaultHostTypes>::new(4.14e-21, 85.0, 1.0e-15)
1417    ///     .expect("physically plausible server calibration");
1418    /// # let _ = cal;
1419    /// ```
1420    #[inline]
1421    pub fn new(
1422        k_b_t: H::Decimal,
1423        thermal_power: H::Decimal,
1424        characteristic_energy: H::Decimal,
1425    ) -> Result<Self, CalibrationError> {
1426        // Bit-pattern bounds for the validation envelope. Reading them
1427        // through `from_bits` lets the host's chosen Decimal precision
1428        // resolve the comparison without any hardcoded f64 in source.
1429        let zero = <H::Decimal as Default>::default();
1430        let kbt_lo =
1431            <H::Decimal as DecimalTranscendental>::from_bits(crate::CALIBRATION_KBT_LO_BITS);
1432        let kbt_hi =
1433            <H::Decimal as DecimalTranscendental>::from_bits(crate::CALIBRATION_KBT_HI_BITS);
1434        let tp_hi = <H::Decimal as DecimalTranscendental>::from_bits(
1435            crate::CALIBRATION_THERMAL_POWER_HI_BITS,
1436        );
1437        let ce_hi = <H::Decimal as DecimalTranscendental>::from_bits(
1438            crate::CALIBRATION_CHAR_ENERGY_HI_BITS,
1439        );
1440        // NaN identity: NaN != NaN. PartialEq is the defining bound.
1441        #[allow(clippy::eq_op)]
1442        let k_b_t_nan = k_b_t != k_b_t;
1443        if k_b_t_nan || k_b_t <= zero || k_b_t < kbt_lo || k_b_t > kbt_hi {
1444            return Err(CalibrationError::ThermalEnergy);
1445        }
1446        #[allow(clippy::eq_op)]
1447        let tp_nan = thermal_power != thermal_power;
1448        if tp_nan || thermal_power <= zero || thermal_power > tp_hi {
1449            return Err(CalibrationError::ThermalPower);
1450        }
1451        #[allow(clippy::eq_op)]
1452        let ce_nan = characteristic_energy != characteristic_energy;
1453        if ce_nan || characteristic_energy <= zero || characteristic_energy > ce_hi {
1454            return Err(CalibrationError::CharacteristicEnergy);
1455        }
1456        Ok(Self {
1457            k_b_t,
1458            thermal_power,
1459            characteristic_energy,
1460            _phantom: core::marker::PhantomData,
1461        })
1462    }
1463
1464    /// Returns the Boltzmann constant times temperature, in joules.
1465    #[inline]
1466    #[must_use]
1467    pub const fn k_b_t(&self) -> H::Decimal {
1468        self.k_b_t
1469    }
1470
1471    /// Returns the sustained thermal power dissipation, in watts.
1472    #[inline]
1473    #[must_use]
1474    pub const fn thermal_power(&self) -> H::Decimal {
1475        self.thermal_power
1476    }
1477
1478    /// Returns the characteristic energy above ground state, in joules.
1479    #[inline]
1480    #[must_use]
1481    pub const fn characteristic_energy(&self) -> H::Decimal {
1482        self.characteristic_energy
1483    }
1484
1485    /// v0.2.2 T5.5: zero sentinel. All three fields are 0.0 — physically
1486    /// meaningless but safely constructible. Used as the unreachable-branch
1487    /// placeholder in the const-context preset literals (`X86_SERVER`,
1488    /// `ARM_MOBILE`, `CORTEX_M_EMBEDDED`, `CONSERVATIVE_WORST_CASE`). The
1489    /// `meta/calibration_presets_valid` conformance check verifies the
1490    /// preset literals always succeed in `Calibration::new`, so this
1491    /// sentinel is never produced in practice. Do not use it directly;
1492    /// it is exposed only because Rust's const-eval needs a fallback for
1493    /// the impossible `Err` arm of the preset match.
1494    pub const ZERO_SENTINEL: Calibration<H> = Self {
1495        k_b_t: H::EMPTY_DECIMAL,
1496        thermal_power: H::EMPTY_DECIMAL,
1497        characteristic_energy: H::EMPTY_DECIMAL,
1498        _phantom: core::marker::PhantomData,
1499    };
1500}
1501
1502impl Calibration<crate::DefaultHostTypes> {
1503    /// Const constructor for the default-host (f64) path. Bypasses runtime validation; use only for the spec-shipped preset literals where the envelope is statically guaranteed. Parameter types are written as `<DefaultHostTypes as HostTypes>::Decimal` so no `: f64` annotation appears in the public-API surface — the host-type alias is the canonical name; downstream that swaps the host gets the matching decimal automatically.
1504    #[inline]
1505    #[must_use]
1506    pub(crate) const fn from_f64_unchecked(
1507        k_b_t: <crate::DefaultHostTypes as crate::HostTypes>::Decimal,
1508        thermal_power: <crate::DefaultHostTypes as crate::HostTypes>::Decimal,
1509        characteristic_energy: <crate::DefaultHostTypes as crate::HostTypes>::Decimal,
1510    ) -> Self {
1511        Self {
1512            k_b_t,
1513            thermal_power,
1514            characteristic_energy,
1515            _phantom: core::marker::PhantomData,
1516        }
1517    }
1518}
1519
1520/// v0.2.2 Phase A: foundation-shipped preset calibrations covering common
1521/// substrates. The values are derived from published substrate thermals at
1522/// T=300 K (room temperature, where k_B·T ≈ 4.14e-21 J).
1523pub mod calibrations {
1524    use super::Calibration;
1525    use crate::DefaultHostTypes;
1526
1527    /// Server-class x86 (Xeon/EPYC sustained envelope).
1528    /// k_B·T = 4.14e-21 J (T = 300 K), thermal_power = 85 W (typical TDP),
1529    /// characteristic_energy = 1e-15 J/op (~1 fJ/op for modern CMOS).
1530    pub const X86_SERVER: Calibration<DefaultHostTypes> =
1531        Calibration::<DefaultHostTypes>::from_f64_unchecked(4.14e-21, 85.0, 1.0e-15);
1532
1533    /// Mobile ARM SoC (Apple M-series, Snapdragon 8-series sustained envelope).
1534    /// k_B·T = 4.14e-21 J, thermal_power = 5 W, characteristic_energy = 1e-16 J/op.
1535    pub const ARM_MOBILE: Calibration<DefaultHostTypes> =
1536        Calibration::<DefaultHostTypes>::from_f64_unchecked(4.14e-21, 5.0, 1.0e-16);
1537
1538    /// Cortex-M embedded (STM32/nRF52 at 80 MHz).
1539    /// k_B·T = 4.14e-21 J, thermal_power = 0.1 W, characteristic_energy = 1e-17 J/op.
1540    pub const CORTEX_M_EMBEDDED: Calibration<DefaultHostTypes> =
1541        Calibration::<DefaultHostTypes>::from_f64_unchecked(4.14e-21, 0.1, 1.0e-17);
1542
1543    /// The tightest provable lower bound that requires no trust in the
1544    /// issuer's claimed substrate. Values are physically sound but maximally
1545    /// generous: k_B·T at 300 K floor, thermal_power at 1 GW (above any
1546    /// plausible single-compute envelope), characteristic_energy at 1 J
1547    /// (astronomically generous).
1548    /// Applying this calibration yields the smallest `Nanos` physically
1549    /// possible for the computation regardless of substrate claims.
1550    pub const CONSERVATIVE_WORST_CASE: Calibration<DefaultHostTypes> =
1551        Calibration::<DefaultHostTypes>::from_f64_unchecked(4.14e-21, 1.0e9, 1.0);
1552}
1553
1554/// v0.2.2 Phase B (target §1.7): timing-policy carrier. Parametric over host tuning.
1555/// Supplies the preflight / runtime Nanos budgets (canonical values from
1556/// `reduction:PreflightTimingBound` and `reduction:RuntimeTimingBound`) plus
1557/// the `Calibration` used to convert an input's a-priori `UorTime` estimate
1558/// into a Nanos lower bound for comparison against the budget.
1559/// The foundation-canonical default [`CanonicalTimingPolicy`] uses
1560/// `calibrations::CONSERVATIVE_WORST_CASE` (the tightest provable lower-bound
1561/// calibration) and the 10 ms budget from the ontology. Host code overrides by
1562/// implementing `TimingPolicy` on a marker struct and substituting at the
1563/// preflight-function call site.
1564pub trait TimingPolicy {
1565    /// Preflight Nanos budget. Inputs whose a-priori UorTime → min_wall_clock
1566    /// under `Self::CALIBRATION` exceeds this value are rejected at preflight.
1567    const PREFLIGHT_BUDGET_NS: u64;
1568    /// Runtime Nanos budget for post-admission reduction.
1569    const RUNTIME_BUDGET_NS: u64;
1570    /// Canonical Calibration used to convert a-priori UorTime estimates to Nanos.
1571    /// Phase 9: pinned to `Calibration<DefaultHostTypes>` because the trait's `const` slot can't carry a non-DefaultHost generic. Polymorphic consumers build a `Calibration<H>` at runtime via `Calibration::new`.
1572    const CALIBRATION: &'static Calibration<crate::DefaultHostTypes>;
1573}
1574
1575/// v0.2.2 Phase B: foundation-canonical [`TimingPolicy`]. Budget values mirror
1576/// `reduction:PreflightTimingBound` and `reduction:RuntimeTimingBound`; calibration
1577/// is `calibrations::CONSERVATIVE_WORST_CASE` so the Nanos lower bound from any
1578/// input UorTime is the tightest physically-defensible value.
1579#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
1580pub struct CanonicalTimingPolicy;
1581
1582impl TimingPolicy for CanonicalTimingPolicy {
1583    const PREFLIGHT_BUDGET_NS: u64 = 10_000_000;
1584    const RUNTIME_BUDGET_NS: u64 = 10_000_000;
1585    const CALIBRATION: &'static Calibration<crate::DefaultHostTypes> =
1586        &calibrations::CONSERVATIVE_WORST_CASE;
1587}
1588
1589/// Phase H (target §1.6): foundation-owned transcendental-arithmetic entry points.
1590/// Routes through the always-on `libm` dependency so every build — std, alloc,
1591/// and strict no_std — has access to `ln` / `exp` / `sqrt` for `xsd:decimal`
1592/// observables. Gating these behind an optional feature flag was considered and
1593/// rejected per target §1.6: an observable that exists in one build and not
1594/// another violates the foundation's "one surface" discipline.
1595/// Downstream code that needs transcendentals should call these wrappers —
1596/// they are the canonical entry point for the four observables target §3 enumerates
1597/// (`convergenceRate`, `residualEntropy`, `collapseAmplitude`, and `op:OA_5` pricing)
1598/// and for any future observable whose implementation admits transcendentals.
1599pub mod transcendentals {
1600    use crate::DecimalTranscendental;
1601
1602    /// Natural logarithm. Dispatches via `DecimalTranscendental::ln`; the foundation's f64 / f32 impls route through `libm::log` / `logf`.
1603    /// Returns `NaN` for `x <= 0.0`, preserving `libm`'s contract.
1604    #[inline]
1605    #[must_use]
1606    pub fn ln<D: DecimalTranscendental>(x: D) -> D {
1607        x.ln()
1608    }
1609
1610    /// Exponential `e^x`. Dispatches via `DecimalTranscendental::exp`.
1611    #[inline]
1612    #[must_use]
1613    pub fn exp<D: DecimalTranscendental>(x: D) -> D {
1614        x.exp()
1615    }
1616
1617    /// Square root. Dispatches via `DecimalTranscendental::sqrt`. Returns `NaN` for `x < 0.0`.
1618    #[inline]
1619    #[must_use]
1620    pub fn sqrt<D: DecimalTranscendental>(x: D) -> D {
1621        x.sqrt()
1622    }
1623
1624    /// Shannon entropy term `-p · ln(p)` in nats. Returns 0 for `p = 0` by
1625    /// continuous extension. Used by `observable:residualEntropy`.
1626    #[inline]
1627    #[must_use]
1628    pub fn entropy_term_nats<D: DecimalTranscendental>(p: D) -> D {
1629        let zero = <D as Default>::default();
1630        if p <= zero {
1631            zero
1632        } else {
1633            zero - p * p.ln()
1634        }
1635    }
1636}
1637
1638/// Fixed-capacity term list for `#![no_std]`. Indices into a `TermArena`.
1639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1640pub struct TermList {
1641    /// Start index in the arena.
1642    pub start: u32,
1643    /// Number of terms in this list.
1644    pub len: u32,
1645}
1646
1647/// Stack-resident arena for `Term` trees.
1648/// Fixed capacity determined by the const generic `CAP`.
1649/// All `Term` child references are `u32` indices into this arena.
1650/// `#![no_std]`-safe: no heap allocation.
1651/// # Examples
1652/// ```rust
1653/// use uor_foundation::enforcement::{TermArena, Term, TermList};
1654/// use uor_foundation::{WittLevel, PrimitiveOp};
1655///
1656/// // Build the expression `add(3, 5)` bottom-up in an arena.
1657/// // ADR-060: `TermArena` carries `<'a, INLINE_BYTES, CAP>`; the
1658/// // application derives `INLINE_BYTES` from its `HostBounds`. Here we
1659/// // fix a concrete inline width `N` and a capacity of 4.
1660/// const N: usize = 32;
1661/// let mut arena = TermArena::<N, 4>::new();
1662///
1663/// // Push leaves first:
1664/// let idx_3 = arena.push(uor_foundation::pipeline::literal_u64(3, WittLevel::W8));
1665/// let idx_5 = arena.push(uor_foundation::pipeline::literal_u64(5, WittLevel::W8));
1666///
1667/// // Push the application node, referencing the leaves by index:
1668/// let idx_add = arena.push(Term::Application {
1669///     operator: PrimitiveOp::Add,
1670///     args: TermList { start: idx_3.unwrap_or(0), len: 2 },
1671/// });
1672///
1673/// assert_eq!(arena.len(), 3);
1674/// // Retrieve a node by index:
1675/// let node = arena.get(idx_add.unwrap_or(0));
1676/// assert!(node.is_some());
1677/// ```
1678#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1679pub struct TermArena<'a, const INLINE_BYTES: usize, const CAP: usize> {
1680    /// Node storage. `None` slots are unused.
1681    nodes: [Option<Term<'a, INLINE_BYTES>>; CAP],
1682    /// Number of allocated nodes.
1683    len: u32,
1684}
1685
1686impl<'a, const INLINE_BYTES: usize, const CAP: usize> TermArena<'a, INLINE_BYTES, CAP> {
1687    /// Creates an empty arena.
1688    #[inline]
1689    #[must_use]
1690    pub const fn new() -> Self {
1691        // v0.2.2 T4.5.a: const-stable on MSRV 1.70 via the `[None; CAP]`
1692        // initializer (Term is Copy as of T4.5.a, so Option<Term> is Copy).
1693        Self {
1694            nodes: [None; CAP],
1695            len: 0,
1696        }
1697    }
1698
1699    /// Push a term into the arena and return its index.
1700    /// # Errors
1701    /// Returns `None` if the arena is full.
1702    #[must_use]
1703    pub fn push(&mut self, term: Term<'a, INLINE_BYTES>) -> Option<u32> {
1704        let idx = self.len;
1705        if (idx as usize) >= CAP {
1706            return None;
1707        }
1708        self.nodes[idx as usize] = Some(term);
1709        self.len = idx + 1;
1710        Some(idx)
1711    }
1712
1713    /// Returns a reference to the term at `index`, or `None` if out of bounds.
1714    #[inline]
1715    #[must_use]
1716    pub fn get(&self, index: u32) -> Option<&Term<'a, INLINE_BYTES>> {
1717        self.nodes
1718            .get(index as usize)
1719            .and_then(|slot| slot.as_ref())
1720    }
1721
1722    /// Returns the number of allocated nodes.
1723    #[inline]
1724    #[must_use]
1725    pub const fn len(&self) -> u32 {
1726        self.len
1727    }
1728
1729    /// Returns `true` if the arena has no allocated nodes.
1730    #[inline]
1731    #[must_use]
1732    pub const fn is_empty(&self) -> bool {
1733        self.len == 0
1734    }
1735
1736    /// v0.2.2 T4.5.b: returns the populated prefix of the arena as a slice.
1737    /// Each entry is `Some(term)` for the populated indices `0..len()`;
1738    /// downstream consumers index into this slice via `TermList::start` and
1739    /// `TermList::len` to walk the children of an Application/Match node.
1740    #[inline]
1741    #[must_use]
1742    pub fn as_slice(&self) -> &[Option<Term<'a, INLINE_BYTES>>] {
1743        &self.nodes[..self.len as usize]
1744    }
1745
1746    /// Wiki ADR-022 D2: const constructor that copies a static term slice
1747    /// into the arena. Used by the `prism_model!` proc-macro to emit a
1748    /// `const ROUTE: TermArena<CAP> = TermArena::from_slice(ROUTE_SLICE)`
1749    /// declaration alongside the model — the `const ROUTE_SLICE` carrying
1750    /// the term tree, this `from_slice` wrapping it into the arena form
1751    /// [`crate::pipeline::run_route`] consumes.
1752    /// `CAP` MUST be at least `slice.len()`; if the slice exceeds the
1753    /// arena's capacity the trailing terms are silently dropped (the
1754    /// `prism_model!` macro emits an arena sized to fit the route's term
1755    /// count plus headroom, so this case is unreachable from the macro's
1756    /// output).
1757    #[inline]
1758    #[must_use]
1759    pub const fn from_slice(slice: &'a [Term<'a, INLINE_BYTES>]) -> Self {
1760        let mut nodes: [Option<Term<'a, INLINE_BYTES>>; CAP] = [None; CAP];
1761        let mut i = 0usize;
1762        while i < slice.len() && i < CAP {
1763            nodes[i] = Some(slice[i]);
1764            i += 1;
1765        }
1766        // Cap at min(slice.len(), CAP) so a too-large slice doesn't
1767        // overrun. The macro emits arena CAP >= slice.len() so the
1768        // truncation branch is unreachable in practice.
1769        #[allow(clippy::cast_possible_truncation)]
1770        let len = if slice.len() > CAP {
1771            CAP as u32
1772        } else {
1773            slice.len() as u32
1774        };
1775        Self { nodes, len }
1776    }
1777}
1778
1779impl<'a, const INLINE_BYTES: usize, const CAP: usize> Default for TermArena<'a, INLINE_BYTES, CAP> {
1780    fn default() -> Self {
1781        Self::new()
1782    }
1783}
1784
1785/// Concrete AST node for the UOR term language.
1786/// Mirrors the EBNF grammar productions. All child references are
1787/// indices into a `TermArena`, keeping the AST stack-resident and
1788/// `#![no_std]`-safe.
1789/// # Examples
1790/// ```rust
1791/// use uor_foundation::enforcement::{Term, TermList};
1792/// use uor_foundation::{WittLevel, PrimitiveOp};
1793///
1794/// // ADR-060: `Term` carries `<'a, const INLINE_BYTES: usize>`. The
1795/// // application instantiates `INLINE_BYTES` from its selected
1796/// // `HostBounds` via `pipeline::carrier_inline_bytes::<B>()`; this
1797/// // example fixes a concrete width.
1798/// const N: usize = 32;
1799///
1800/// // Literal: an integer value tagged with a Witt level.
1801/// let lit: Term<'static, N> =
1802///     uor_foundation::pipeline::literal_u64(42, WittLevel::W8);
1803///
1804/// // Application: an operation applied to arguments.
1805/// // `args` is a TermList { start, len } pointing into a TermArena.
1806/// let app: Term<'static, N> = Term::Application {
1807///     operator: PrimitiveOp::Mul,
1808///     args: TermList { start: 0, len: 2 },
1809/// };
1810///
1811/// // Lift: canonical injection from a lower to a higher Witt level.
1812/// let lift: Term<'static, N> =
1813///     Term::Lift { operand_index: 0, target: WittLevel::new(32) };
1814///
1815/// // Project: canonical surjection from a higher to a lower level.
1816/// let proj: Term<'static, N> =
1817///     Term::Project { operand_index: 0, target: WittLevel::W8 };
1818/// let _ = (lit, app, lift, proj);
1819/// ```
1820#[allow(clippy::large_enum_variant)]
1821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1822pub enum Term<'a, const INLINE_BYTES: usize> {
1823    /// Integer literal with Witt level annotation. Per ADR-051 the value
1824    /// carrier is a `TermValue` byte sequence whose length matches the declared
1825    /// `level`'s byte width. Use `uor_foundation::pipeline::literal_u64(value, level)`
1826    /// to construct a literal from a `u64` value (the narrow form).
1827    Literal {
1828        /// The literal value as a source-polymorphic carrier (ADR-051 +
1829        /// ADR-060). Inline length equals `level.witt_length() / 8`. Wider
1830        /// widths (W128, W256, …) are natively representable without
1831        /// `Concat` composition.
1832        value: crate::pipeline::TermValue<'a, INLINE_BYTES>,
1833        /// The Witt level of this literal.
1834        level: WittLevel,
1835    },
1836    /// Variable reference by name index.
1837    Variable {
1838        /// Index into the name table.
1839        name_index: u32,
1840    },
1841    /// Operation application: operator applied to arguments.
1842    Application {
1843        /// The primitive operation to apply.
1844        operator: PrimitiveOp,
1845        /// Argument list (indices into arena).
1846        args: TermList,
1847    },
1848    /// Lift: canonical injection W_n to W_m (n < m, lossless).
1849    Lift {
1850        /// Index of the operand term in the arena.
1851        operand_index: u32,
1852        /// Target Witt level.
1853        target: WittLevel,
1854    },
1855    /// Project: canonical surjection W_m to W_n (m > n, lossy).
1856    Project {
1857        /// Index of the operand term in the arena.
1858        operand_index: u32,
1859        /// Target Witt level.
1860        target: WittLevel,
1861    },
1862    /// Match expression with pattern-result pairs.
1863    Match {
1864        /// Index of the scrutinee term in the arena.
1865        scrutinee_index: u32,
1866        /// Match arms (indices into arena).
1867        arms: TermList,
1868    },
1869    /// Bounded recursion with descent measure.
1870    Recurse {
1871        /// Index of the descent measure term.
1872        measure_index: u32,
1873        /// Index of the base case term.
1874        base_index: u32,
1875        /// Index of the recursive step term.
1876        step_index: u32,
1877    },
1878    /// Stream construction via unfold.
1879    Unfold {
1880        /// Index of the seed term.
1881        seed_index: u32,
1882        /// Index of the step function term.
1883        step_index: u32,
1884    },
1885    /// Try expression with failure recovery.
1886    Try {
1887        /// Index of the body term.
1888        body_index: u32,
1889        /// Index of the handler term.
1890        handler_index: u32,
1891    },
1892    /// Substitution-axis-realized verb projection (wiki ADR-029 + ADR-030).
1893    /// Delegates evaluation to the application's `AxisTuple` substitution-axis
1894    /// impl: the catamorphism evaluates the input subtree, dispatches the
1895    /// axis at `axis_index` to the kernel identified by `kernel_id`, and
1896    /// emits the kernel's output as the result. Emitted by
1897    /// `prism_model!` from the closure-body form `hash(input)` (ADR-026 G19,
1898    /// which lowers to AxisInvocation against the application's HashAxis).
1899    AxisInvocation {
1900        /// Position of the axis in the application's `AxisTuple`.
1901        axis_index: u32,
1902        /// Per-axis kernel id (the SDK macro emits per-method `KERNEL_*` consts).
1903        kernel_id: u32,
1904        /// Input subtree's arena index (single input — current axes are 1-arg).
1905        input_index: u32,
1906    },
1907    /// Field-access projection over a partition_product input (wiki
1908    /// ADR-033 G20). The catamorphism's fold-rule evaluates `source`
1909    /// and slices `[byte_offset .. byte_offset + byte_length]` from
1910    /// the resulting bytes. Emitted by `prism_model!` and `verb!`
1911    /// from the closure-body forms `<expr>.<index>` and
1912    /// `<expr>.<field_name>` (named-field access requires the
1913    /// `partition_product!` declaration to use the named-field form).
1914    /// Coproduct field-access is rejected at macro-expansion time.
1915    ProjectField {
1916        /// Arena index of the source expression's term tree.
1917        source_index: u32,
1918        /// Byte offset into the source's evaluated bytes (proc-
1919        /// macro-computed from the partition-product factor widths).
1920        byte_offset: u32,
1921        /// Length of the projected slice in bytes.
1922        byte_length: u32,
1923    },
1924    /// Bounded search with structural early termination (wiki ADR-034).
1925    /// The catamorphism iterates `idx` from 0 up to (but excluding) the
1926    /// evaluated `domain_size`; for each iteration it evaluates
1927    /// `predicate` with `FIRST_ADMIT_IDX_NAME_INDEX` bound to `idx`.
1928    /// On the first non-zero predicate result the fold emits the
1929    /// coproduct value `(0x01, idx_bytes)` and terminates iteration; if
1930    /// no `idx` admits, the fold emits `(0x00, idx-width zero bytes)`.
1931    /// Emitted by `prism_model!` and `verb!` from the closure-body
1932    /// form `first_admit(<DomainTy>, |idx| <pred>)` (ADR-026 G16; the
1933    /// lowering target shifted from `Term::Recurse` to `Term::FirstAdmit`
1934    /// per ADR-034's structural-search commitment).
1935    FirstAdmit {
1936        /// Arena index of the domain-cardinality term (typically a
1937        /// `Term::Literal` carrying `<DomainTy as ConstrainedTypeShape>::CYCLE_SIZE`).
1938        domain_size_index: u32,
1939        /// Arena index of the predicate body. Evaluation visits
1940        /// `predicate` with `FIRST_ADMIT_IDX_NAME_INDEX` bound to the
1941        /// current candidate `idx`.
1942        predicate_index: u32,
1943    },
1944    /// ψ_1 (wiki ADR-035): nerve construction — Constraints → SimplicialComplex.
1945    /// Lowered from the closure-body form `nerve(<value_expr>)` (G21).
1946    /// Resolver-bound: consults the ResolverTuple's NerveResolver per ADR-036.
1947    Nerve {
1948        /// Arena index of the value-bytes operand (typically a
1949        /// `Term::Variable` for the route input or a `Term::ProjectField`).
1950        value_index: u32,
1951    },
1952    /// ψ_2 (wiki ADR-035): chain functor — SimplicialComplex → ChainComplex.
1953    /// Lowered from `chain_complex(<simplicial_expr>)` (G22).
1954    /// Resolver-bound: ChainComplexResolver per ADR-036.
1955    ChainComplex { simplicial_index: u32 },
1956    /// ψ_3 (wiki ADR-035): homology functor — ChainComplex → HomologyGroups.
1957    /// `H_k(C) = ker(∂_k) / im(∂_{k+1})`.
1958    /// Lowered from `homology_groups(<chain_expr>)` (G23).
1959    /// Resolver-bound: HomologyGroupResolver per ADR-036.
1960    HomologyGroups { chain_index: u32 },
1961    /// ψ_4 (wiki ADR-035): Betti-number extraction — HomologyGroups → BettiNumbers.
1962    /// Pure computation on resolved homology groups; no resolver consultation.
1963    /// Lowered from `betti(<homology_expr>)` (G24).
1964    Betti { homology_index: u32 },
1965    /// ψ_5 (wiki ADR-035): dualization functor — ChainComplex → CochainComplex.
1966    /// `C^k = Hom(C_k, R)`.
1967    /// Lowered from `cochain_complex(<chain_expr>)` (G25).
1968    /// Resolver-bound: CochainComplexResolver per ADR-036.
1969    CochainComplex { chain_index: u32 },
1970    /// ψ_6 (wiki ADR-035): cohomology functor — CochainComplex → CohomologyGroups.
1971    /// `H^k(C) = ker(δ^k) / im(δ^{k-1})`.
1972    /// Lowered from `cohomology_groups(<cochain_expr>)` (G26).
1973    /// Resolver-bound: CohomologyGroupResolver per ADR-036.
1974    CohomologyGroups { cochain_index: u32 },
1975    /// ψ_7 (wiki ADR-035): Kan-completion + Postnikov truncation —
1976    /// SimplicialComplex → PostnikovTower. The PostnikovResolver performs
1977    /// the Kan-completion internally; verb authors do not need to construct
1978    /// KanComplex values explicitly.
1979    /// Lowered from `postnikov_tower(<simplicial_expr>)` (G27).
1980    /// Resolver-bound: PostnikovResolver per ADR-036.
1981    PostnikovTower { simplicial_index: u32 },
1982    /// ψ_8 (wiki ADR-035): homotopy extraction — PostnikovTower → HomotopyGroups.
1983    /// π_k from each truncation stage.
1984    /// Lowered from `homotopy_groups(<postnikov_expr>)` (G28).
1985    /// Resolver-bound: HomotopyGroupResolver per ADR-036.
1986    HomotopyGroups { postnikov_index: u32 },
1987    /// ψ_9 (wiki ADR-035): k-invariant computation — HomotopyGroups → KInvariants.
1988    /// κ_k classifying the Postnikov tower.
1989    /// Lowered from `k_invariants(<homotopy_expr>)` (G29).
1990    /// Resolver-bound: KInvariantResolver per ADR-036.
1991    KInvariants { homotopy_index: u32 },
1992}
1993
1994/// Wiki ADR-024 verb-graph compile-time inlining: shift the arena-index
1995/// fields of `term` by `offset`. Used by [`inline_verb_fragment`] to
1996/// inline a verb's term-tree fragment into a host arena at compile time.
1997/// `Term::Variable`'s `name_index` is a binding-name reference (not an
1998/// arena index) and is preserved unchanged. `Term::Try`'s `handler_index`
1999/// is preserved unchanged when it equals `u32::MAX` (the default-
2000/// propagation sentinel per ADR-022 D3 G9).
2001#[must_use]
2002pub const fn shift_term<'a, const INLINE_BYTES: usize>(
2003    term: Term<'a, INLINE_BYTES>,
2004    offset: u32,
2005) -> Term<'a, INLINE_BYTES> {
2006    match term {
2007        Term::Literal { value, level } => Term::Literal { value, level },
2008        // name_index is a binding-name reference, not an arena index.
2009        Term::Variable { name_index } => Term::Variable { name_index },
2010        Term::Application { operator, args } => Term::Application {
2011            operator,
2012            args: TermList {
2013                start: args.start + offset,
2014                len: args.len,
2015            },
2016        },
2017        Term::Lift {
2018            operand_index,
2019            target,
2020        } => Term::Lift {
2021            operand_index: operand_index + offset,
2022            target,
2023        },
2024        Term::Project {
2025            operand_index,
2026            target,
2027        } => Term::Project {
2028            operand_index: operand_index + offset,
2029            target,
2030        },
2031        Term::Match {
2032            scrutinee_index,
2033            arms,
2034        } => Term::Match {
2035            scrutinee_index: scrutinee_index + offset,
2036            arms: TermList {
2037                start: arms.start + offset,
2038                len: arms.len,
2039            },
2040        },
2041        Term::Recurse {
2042            measure_index,
2043            base_index,
2044            step_index,
2045        } => Term::Recurse {
2046            measure_index: measure_index + offset,
2047            base_index: base_index + offset,
2048            step_index: step_index + offset,
2049        },
2050        Term::Unfold {
2051            seed_index,
2052            step_index,
2053        } => Term::Unfold {
2054            seed_index: seed_index + offset,
2055            step_index: step_index + offset,
2056        },
2057        Term::Try {
2058            body_index,
2059            handler_index,
2060        } => Term::Try {
2061            body_index: body_index + offset,
2062            handler_index: if handler_index == u32::MAX {
2063                u32::MAX
2064            } else {
2065                handler_index + offset
2066            },
2067        },
2068        Term::AxisInvocation {
2069            axis_index,
2070            kernel_id,
2071            input_index,
2072        } => Term::AxisInvocation {
2073            axis_index,
2074            kernel_id,
2075            input_index: input_index + offset,
2076        },
2077        Term::ProjectField {
2078            source_index,
2079            byte_offset,
2080            byte_length,
2081        } => Term::ProjectField {
2082            source_index: source_index + offset,
2083            byte_offset,
2084            byte_length,
2085        },
2086        Term::FirstAdmit {
2087            domain_size_index,
2088            predicate_index,
2089        } => Term::FirstAdmit {
2090            domain_size_index: domain_size_index + offset,
2091            predicate_index: predicate_index + offset,
2092        },
2093        Term::Nerve { value_index } => Term::Nerve {
2094            value_index: value_index + offset,
2095        },
2096        Term::ChainComplex { simplicial_index } => Term::ChainComplex {
2097            simplicial_index: simplicial_index + offset,
2098        },
2099        Term::HomologyGroups { chain_index } => Term::HomologyGroups {
2100            chain_index: chain_index + offset,
2101        },
2102        Term::Betti { homology_index } => Term::Betti {
2103            homology_index: homology_index + offset,
2104        },
2105        Term::CochainComplex { chain_index } => Term::CochainComplex {
2106            chain_index: chain_index + offset,
2107        },
2108        Term::CohomologyGroups { cochain_index } => Term::CohomologyGroups {
2109            cochain_index: cochain_index + offset,
2110        },
2111        Term::PostnikovTower { simplicial_index } => Term::PostnikovTower {
2112            simplicial_index: simplicial_index + offset,
2113        },
2114        Term::HomotopyGroups { postnikov_index } => Term::HomotopyGroups {
2115            postnikov_index: postnikov_index + offset,
2116        },
2117        Term::KInvariants { homotopy_index } => Term::KInvariants {
2118            homotopy_index: homotopy_index + offset,
2119        },
2120    }
2121}
2122
2123/// Wiki ADR-024 compile-time verb-fragment inlining helper.
2124/// Copies the verb `fragment` slice into `buf` starting at `len` while applying
2125/// two simultaneous transformations per term so the verb body becomes part of
2126/// the calling route's flat arena: Variable(0) substitution (the verb's `input`
2127/// parameter binds to the caller's argument expression by replacing each
2128/// `Variable { name_index: 0 }` with a copy of `buf[arg_root_idx]`), and arena-
2129/// index shifting (every non-Variable(0) term has its arena-index fields shifted
2130/// by `len` so internal references resolve correctly within the host).
2131/// The combined transformation realises ADR-024's compile-time inlining: the
2132/// verb body lands in the host arena with its `input` bound to the caller's
2133/// argument expression — verb-graph acyclicity is checked at const-eval time,
2134/// no `Term::VerbReference` variant or runtime depth guard is required.
2135/// # Panics
2136/// Panics at const-eval time if `len + fragment.len() > CAP` or if
2137/// `arg_root_idx as usize >= len`.
2138#[must_use]
2139pub const fn inline_verb_fragment<'a, const INLINE_BYTES: usize, const CAP: usize>(
2140    mut buf: [Term<'a, INLINE_BYTES>; CAP],
2141    mut len: usize,
2142    fragment: &[Term<'a, INLINE_BYTES>],
2143    arg_root_idx: u32,
2144) -> ([Term<'a, INLINE_BYTES>; CAP], usize) {
2145    let offset = len as u32;
2146    // Capture a copy of the caller's argument root term; `Variable { name_index: 0 }`
2147    // occurrences in the fragment are replaced by this copy per ADR-024.
2148    let arg_root_term = buf[arg_root_idx as usize];
2149    let mut i = 0;
2150    while i < fragment.len() {
2151        let term = fragment[i];
2152        let new_term = match term {
2153            Term::Variable { name_index: 0 } => arg_root_term,
2154            other => shift_term(other, offset),
2155        };
2156        buf[len] = new_term;
2157        len += 1;
2158        i += 1;
2159    }
2160    (buf, len)
2161}
2162
2163/// A type declaration with constraint kinds.
2164#[derive(Debug, Clone, PartialEq, Eq)]
2165pub struct TypeDeclaration {
2166    /// Name index for this type.
2167    pub name_index: u32,
2168    /// Constraint terms (indices into arena).
2169    pub constraints: TermList,
2170}
2171
2172/// A named binding: `let name : Type = term`.
2173#[derive(Debug, Clone, PartialEq, Eq)]
2174pub struct Binding {
2175    /// Name index for this binding.
2176    pub name_index: u32,
2177    /// Index of the type declaration.
2178    pub type_index: u32,
2179    /// Index of the value term in the arena.
2180    pub value_index: u32,
2181    /// EBNF surface syntax (compile-time constant).
2182    pub surface: &'static str,
2183    /// FNV-1a content address (compile-time constant).
2184    pub content_address: u64,
2185}
2186
2187impl Binding {
2188    /// v0.2.2 Phase P.3: lift this binding to the `BindingEntry` shape consumed by
2189    /// `BindingsTable`. `address` is derived from `content_address` via
2190    /// `ContentAddress::from_u64_fingerprint`; `bytes` re-uses the `surface` slice.
2191    /// Content-deterministic; const-compatible since all fields are `'static`.
2192    #[inline]
2193    #[must_use]
2194    pub const fn to_binding_entry(&self) -> BindingEntry {
2195        BindingEntry {
2196            address: ContentAddress::from_u64_fingerprint(self.content_address),
2197            bytes: self.surface.as_bytes(),
2198        }
2199    }
2200}
2201
2202/// An assertion: `assert lhs = rhs`.
2203#[derive(Debug, Clone, PartialEq, Eq)]
2204pub struct Assertion {
2205    /// Index of the left-hand side term.
2206    pub lhs_index: u32,
2207    /// Index of the right-hand side term.
2208    pub rhs_index: u32,
2209    /// EBNF surface syntax (compile-time constant).
2210    pub surface: &'static str,
2211}
2212
2213/// Boundary source declaration: `source name : Type via grounding`.
2214#[derive(Debug, Clone, PartialEq, Eq)]
2215pub struct SourceDeclaration {
2216    /// Name index for the source.
2217    pub name_index: u32,
2218    /// Index of the type declaration.
2219    pub type_index: u32,
2220    /// Name index of the grounding map.
2221    pub grounding_name_index: u32,
2222}
2223
2224/// Boundary sink declaration: `sink name : Type via projection`.
2225#[derive(Debug, Clone, PartialEq, Eq)]
2226pub struct SinkDeclaration {
2227    /// Name index for the sink.
2228    pub name_index: u32,
2229    /// Index of the type declaration.
2230    pub type_index: u32,
2231    /// Name index of the projection map.
2232    pub projection_name_index: u32,
2233}
2234
2235/// Structured violation diagnostic carrying metadata from the
2236/// conformance namespace. Every field is machine-readable.
2237/// # Examples
2238/// ```rust
2239/// use uor_foundation::enforcement::ShapeViolation;
2240/// use uor_foundation::ViolationKind;
2241///
2242/// // ShapeViolation carries structured metadata from the ontology.
2243/// // Every field is machine-readable — IRIs, counts, and a typed kind.
2244/// let violation = ShapeViolation {
2245///     shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2246///     constraint_iri: "https://uor.foundation/conformance/compileUnit_rootTerm_constraint",
2247///     property_iri: "https://uor.foundation/reduction/rootTerm",
2248///     expected_range: "https://uor.foundation/schema/Term",
2249///     min_count: 1,
2250///     max_count: 1,
2251///     kind: ViolationKind::Missing,
2252/// };
2253///
2254/// // Machine-readable for tooling (IDE plugins, CI pipelines):
2255/// assert_eq!(violation.kind, ViolationKind::Missing);
2256/// assert!(violation.shape_iri.ends_with("CompileUnitShape"));
2257/// assert_eq!(violation.min_count, 1);
2258/// ```
2259#[derive(Debug, Clone, PartialEq, Eq)]
2260pub struct ShapeViolation {
2261    /// IRI of the `conformance:Shape` that was validated against.
2262    pub shape_iri: &'static str,
2263    /// IRI of the specific `conformance:PropertyConstraint` that failed.
2264    pub constraint_iri: &'static str,
2265    /// IRI of the property that was missing or invalid.
2266    pub property_iri: &'static str,
2267    /// The expected range class IRI.
2268    pub expected_range: &'static str,
2269    /// Minimum cardinality from the constraint.
2270    pub min_count: u32,
2271    /// Maximum cardinality (0 = unbounded).
2272    pub max_count: u32,
2273    /// What went wrong.
2274    pub kind: ViolationKind,
2275}
2276
2277impl core::fmt::Display for ShapeViolation {
2278    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2279        write!(
2280            f,
2281            "shape violation: {} (constraint {}, property {}, kind {:?})",
2282            self.shape_iri, self.constraint_iri, self.property_iri, self.kind,
2283        )
2284    }
2285}
2286
2287impl core::error::Error for ShapeViolation {}
2288
2289impl ShapeViolation {
2290    /// Phase C.3: returns the shape IRI as a `&'static str` suitable for
2291    /// `const fn` panic messages. The IRI uniquely identifies the violated
2292    /// constraint in the conformance catalog.
2293    #[inline]
2294    #[must_use]
2295    pub const fn const_message(&self) -> &'static str {
2296        self.shape_iri
2297    }
2298}
2299
2300/// Builder for `CompileUnit` admission into the reduction pipeline.
2301/// Collects `rootTerm`, `wittLevelCeiling`, `thermodynamicBudget`,
2302/// and `targetDomains`. The `validate()` method checks structural
2303/// constraints (Tier 1) and value-dependent constraints (Tier 2).
2304/// # Examples
2305/// ```rust
2306/// use uor_foundation::enforcement::{CompileUnitBuilder, ConstrainedTypeInput, Term};
2307/// use uor_foundation::{WittLevel, VerificationDomain, ViolationKind};
2308///
2309/// // A CompileUnit packages a term graph for reduction admission.
2310/// // The builder enforces that all required fields are present.
2311/// // ADR-060: `Term`/`CompileUnitBuilder` carry an `INLINE_BYTES`
2312/// // const-generic the application derives from its `HostBounds`; fix
2313/// // a concrete width.
2314/// const N: usize = 32;
2315/// let terms: [Term<'static, N>; 1] =
2316///     [uor_foundation::pipeline::literal_u64(1, WittLevel::W8)];
2317/// let domains = [VerificationDomain::Enumerative];
2318///
2319/// let unit = CompileUnitBuilder::<N>::new()
2320///     .root_term(&terms)
2321///     .witt_level_ceiling(WittLevel::W8)
2322///     .thermodynamic_budget(1024)
2323///     .target_domains(&domains)
2324///     .result_type::<ConstrainedTypeInput>()
2325///     .validate();
2326/// assert!(unit.is_ok());
2327///
2328/// // Omitting a required field produces a ShapeViolation
2329/// // with the exact conformance IRI that failed:
2330/// let err = CompileUnitBuilder::<N>::new()
2331///     .witt_level_ceiling(WittLevel::W8)
2332///     .thermodynamic_budget(1024)
2333///     .target_domains(&domains)
2334///     .result_type::<ConstrainedTypeInput>()
2335///     .validate();
2336/// assert!(err.is_err());
2337/// if let Err(violation) = err {
2338///     assert_eq!(violation.kind, ViolationKind::Missing);
2339///     assert!(violation.property_iri.contains("rootTerm"));
2340/// }
2341/// ```
2342#[derive(Debug, Clone)]
2343pub struct CompileUnitBuilder<'a, const INLINE_BYTES: usize> {
2344    /// The root term expression.
2345    root_term: Option<&'a [Term<'a, INLINE_BYTES>]>,
2346    /// v0.2.2 Phase H1: named bindings (`let name : Type = term` forms)
2347    /// declared by the compile unit. Stage 5 extracts these into a `BindingsTable`
2348    /// for grounding-aware and session resolvers; an empty slice declares no bindings.
2349    bindings: Option<&'a [Binding]>,
2350    /// The widest Witt level the computation may reference.
2351    witt_level_ceiling: Option<WittLevel>,
2352    /// Landauer-bounded energy budget.
2353    thermodynamic_budget: Option<u64>,
2354    /// Verification domains targeted.
2355    target_domains: Option<&'a [VerificationDomain]>,
2356    /// v0.2.2 T6.11: result-type IRI for ShapeMismatch detection.
2357    /// Set via `result_type::<T: ConstrainedTypeShape>()`. Required by
2358    /// `validate()` and `validate_compile_unit_const`. The pipeline checks
2359    /// `unit.result_type_iri() == T::IRI` at `pipeline::run` invocation
2360    /// time, returning `PipelineFailure::ShapeMismatch` on mismatch.
2361    result_type_iri: Option<&'static str>,
2362}
2363
2364/// A validated compile unit ready for reduction admission.
2365/// v0.2.2 Phase A (carrier widening): the lifetime parameter `'a` ties
2366/// the post-validation carrier to its builder's borrow. The `root_term`
2367/// and `target_domains` slices are retained through validation so
2368/// resolvers can inspect declared structure — previously these fields
2369/// were discarded at `validate()` and every resolver received a
2370/// 3-field scalar witness with no walkable structure.
2371/// Const-constructed compile units use the trivial specialization
2372/// `CompileUnit<'static>` — borrow-free and usable in const contexts.
2373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2374pub struct CompileUnit<'a, const INLINE_BYTES: usize> {
2375    /// The Witt level ceiling.
2376    level: WittLevel,
2377    /// The thermodynamic budget.
2378    budget: u64,
2379    /// v0.2.2 T6.11: result-type IRI. The pipeline matches this against
2380    /// the caller's `T::IRI` to detect shape mismatches.
2381    result_type_iri: &'static str,
2382    /// v0.2.2 Phase A: root term expression, retained from the builder.
2383    /// Stage 5 (extract bindings) and the grounding-aware resolver walk
2384    /// this slice. Empty slice for the trivial `CompileUnit<'static>`
2385    /// specialization produced by builders that don't carry a term AST.
2386    root_term: &'a [Term<'a, INLINE_BYTES>],
2387    /// v0.2.2 Phase H1: named bindings retained from the builder. Consumed by Stage 5
2388    /// (`bindings_from_unit`) to materialize the `BindingsTable` for grounding-aware,
2389    /// session, and superposition resolvers. Empty slice declares no bindings.
2390    bindings: &'a [Binding],
2391    /// v0.2.2 Phase A: verification domains targeted, retained from the builder.
2392    target_domains: &'a [VerificationDomain],
2393}
2394
2395impl<'a, const INLINE_BYTES: usize> CompileUnit<'a, INLINE_BYTES> {
2396    /// Returns the Witt level ceiling declared at validation time.
2397    #[inline]
2398    #[must_use]
2399    pub const fn witt_level(&self) -> WittLevel {
2400        self.level
2401    }
2402
2403    /// Returns the thermodynamic budget declared at validation time.
2404    #[inline]
2405    #[must_use]
2406    pub const fn thermodynamic_budget(&self) -> u64 {
2407        self.budget
2408    }
2409
2410    /// v0.2.2 T6.11: returns the result-type IRI declared at validation
2411    /// time. The pipeline matches this against the caller's `T::IRI` to
2412    /// detect shape mismatches.
2413    #[inline]
2414    #[must_use]
2415    pub const fn result_type_iri(&self) -> &'static str {
2416        self.result_type_iri
2417    }
2418
2419    /// v0.2.2 Phase A: returns the root term slice declared at validation time.
2420    /// Empty for builders that did not supply a term AST.
2421    #[inline]
2422    #[must_use]
2423    pub const fn root_term(&self) -> &'a [Term<'a, INLINE_BYTES>] {
2424        self.root_term
2425    }
2426
2427    /// v0.2.2 Phase H1: returns the named bindings declared at validation time.
2428    /// Consumed by Stage 5 (`bindings_from_unit`) to materialize the `BindingsTable`.
2429    /// Empty slice for compile units that declare no bindings.
2430    #[inline]
2431    #[must_use]
2432    pub const fn bindings(&self) -> &'a [Binding] {
2433        self.bindings
2434    }
2435
2436    /// v0.2.2 Phase A: returns the verification domains declared at validation time.
2437    #[inline]
2438    #[must_use]
2439    pub const fn target_domains(&self) -> &'a [VerificationDomain] {
2440        self.target_domains
2441    }
2442
2443    /// v0.2.2 Phase G / T2.8 + T6.11: const-constructible parts form used
2444    /// by `validate_compile_unit_const` — the const-fn path reads the
2445    /// builder's fields and packs them into the `Validated` result.
2446    /// v0.2.2 Phase H1: bindings slice is retained alongside root_term;
2447    /// empty slice declares no bindings.
2448    #[inline]
2449    #[must_use]
2450    pub(crate) const fn from_parts_const(
2451        level: WittLevel,
2452        budget: u64,
2453        result_type_iri: &'static str,
2454        root_term: &'a [Term<'a, INLINE_BYTES>],
2455        bindings: &'a [Binding],
2456        target_domains: &'a [VerificationDomain],
2457    ) -> Self {
2458        Self {
2459            level,
2460            budget,
2461            result_type_iri,
2462            root_term,
2463            bindings,
2464            target_domains,
2465        }
2466    }
2467}
2468
2469impl<'a, const INLINE_BYTES: usize> CompileUnitBuilder<'a, INLINE_BYTES> {
2470    /// Creates a new empty builder.
2471    #[must_use]
2472    pub const fn new() -> Self {
2473        Self {
2474            root_term: None,
2475            bindings: None,
2476            witt_level_ceiling: None,
2477            thermodynamic_budget: None,
2478            target_domains: None,
2479            result_type_iri: None,
2480        }
2481    }
2482
2483    /// Set the root term expression.
2484    #[must_use]
2485    pub const fn root_term(mut self, terms: &'a [Term<'a, INLINE_BYTES>]) -> Self {
2486        self.root_term = Some(terms);
2487        self
2488    }
2489
2490    /// v0.2.2 Phase H1: set the named bindings declared by this compile unit.
2491    /// Consumed by Stage 5 (`bindings_from_unit`) to materialize the
2492    /// `BindingsTable` for grounding-aware, session, and superposition resolvers.
2493    /// Omit for compile units without bindings; the default is the empty slice.
2494    #[must_use]
2495    pub const fn bindings(mut self, bindings: &'a [Binding]) -> Self {
2496        self.bindings = Some(bindings);
2497        self
2498    }
2499
2500    /// Set the Witt level ceiling.
2501    #[must_use]
2502    pub const fn witt_level_ceiling(mut self, level: WittLevel) -> Self {
2503        self.witt_level_ceiling = Some(level);
2504        self
2505    }
2506
2507    /// Set the thermodynamic budget.
2508    #[must_use]
2509    pub const fn thermodynamic_budget(mut self, budget: u64) -> Self {
2510        self.thermodynamic_budget = Some(budget);
2511        self
2512    }
2513
2514    /// Set the target verification domains.
2515    #[must_use]
2516    pub const fn target_domains(mut self, domains: &'a [VerificationDomain]) -> Self {
2517        self.target_domains = Some(domains);
2518        self
2519    }
2520
2521    /// v0.2.2 T6.11: set the result-type IRI from a `ConstrainedTypeShape`
2522    /// type parameter. The pipeline matches this against the caller's
2523    /// `T::IRI` at `pipeline::run` invocation time, returning
2524    /// `PipelineFailure::ShapeMismatch` on mismatch.
2525    /// Required: `validate()` and `validate_compile_unit_const` reject
2526    /// builders without a result type set.
2527    #[must_use]
2528    pub const fn result_type<T: crate::pipeline::ConstrainedTypeShape>(mut self) -> Self {
2529        self.result_type_iri = Some(T::IRI);
2530        self
2531    }
2532
2533    /// v0.2.2 T2.8: const-fn accessor exposing the stored Witt level
2534    /// ceiling (or `None` if unset). Used by `validate_compile_unit_const`.
2535    #[inline]
2536    #[must_use]
2537    pub const fn witt_level_option(&self) -> Option<WittLevel> {
2538        self.witt_level_ceiling
2539    }
2540
2541    /// v0.2.2 T2.8: const-fn accessor exposing the stored thermodynamic
2542    /// budget (or `None` if unset).
2543    #[inline]
2544    #[must_use]
2545    pub const fn budget_option(&self) -> Option<u64> {
2546        self.thermodynamic_budget
2547    }
2548
2549    /// v0.2.2 T6.13: const-fn accessor — `true` iff `root_term` is set.
2550    #[inline]
2551    #[must_use]
2552    pub const fn has_root_term_const(&self) -> bool {
2553        self.root_term.is_some()
2554    }
2555
2556    /// v0.2.2 T6.13: const-fn accessor — `true` iff `target_domains` is
2557    /// set and non-empty.
2558    #[inline]
2559    #[must_use]
2560    pub const fn has_target_domains_const(&self) -> bool {
2561        match self.target_domains {
2562            Some(d) => !d.is_empty(),
2563            None => false,
2564        }
2565    }
2566
2567    /// v0.2.2 T6.13: const-fn accessor exposing the stored result-type IRI
2568    /// (or `None` if unset). Used by `validate_compile_unit_const`.
2569    #[inline]
2570    #[must_use]
2571    pub const fn result_type_iri_const(&self) -> Option<&'static str> {
2572        self.result_type_iri
2573    }
2574
2575    /// v0.2.2 Phase A: const-fn accessor exposing the stored root-term slice,
2576    /// or an empty slice if unset. Used by `validate_compile_unit_const` to
2577    /// propagate the AST into the widened `CompileUnit<'a>` carrier.
2578    #[inline]
2579    #[must_use]
2580    pub const fn root_term_slice_const(&self) -> &'a [Term<'a, INLINE_BYTES>] {
2581        match self.root_term {
2582            Some(terms) => terms,
2583            None => &[],
2584        }
2585    }
2586
2587    /// v0.2.2 Phase H1: const-fn accessor exposing the stored bindings slice,
2588    /// or an empty slice if unset. Used by `validate_compile_unit_const` to
2589    /// propagate the bindings declaration into the widened `CompileUnit<'a>` carrier.
2590    #[inline]
2591    #[must_use]
2592    pub const fn bindings_slice_const(&self) -> &'a [Binding] {
2593        match self.bindings {
2594            Some(bindings) => bindings,
2595            None => &[],
2596        }
2597    }
2598
2599    /// v0.2.2 Phase A: const-fn accessor exposing the stored target-domains
2600    /// slice, or an empty slice if unset. Used by `validate_compile_unit_const`.
2601    #[inline]
2602    #[must_use]
2603    pub const fn target_domains_slice_const(&self) -> &'a [VerificationDomain] {
2604        match self.target_domains {
2605            Some(d) => d,
2606            None => &[],
2607        }
2608    }
2609
2610    /// Validate against `CompileUnitShape`.
2611    /// Tier 1: checks presence and cardinality of all required fields.
2612    /// Tier 2: checks budget solvency and level coherence.
2613    /// # Errors
2614    /// Returns `ShapeViolation` if any constraint is not satisfied.
2615    pub fn validate(self) -> Result<Validated<CompileUnit<'a, INLINE_BYTES>>, ShapeViolation> {
2616        let root_term = match self.root_term {
2617            Some(terms) => terms,
2618            None => {
2619                return Err(ShapeViolation {
2620                    shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2621                    constraint_iri:
2622                        "https://uor.foundation/conformance/compileUnit_rootTerm_constraint",
2623                    property_iri: "https://uor.foundation/reduction/rootTerm",
2624                    expected_range: "https://uor.foundation/schema/Term",
2625                    min_count: 1,
2626                    max_count: 1,
2627                    kind: ViolationKind::Missing,
2628                })
2629            }
2630        };
2631        let level =
2632            match self.witt_level_ceiling {
2633                Some(l) => l,
2634                None => return Err(ShapeViolation {
2635                    shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2636                    constraint_iri:
2637                        "https://uor.foundation/conformance/compileUnit_unitWittLevel_constraint",
2638                    property_iri: "https://uor.foundation/reduction/unitWittLevel",
2639                    expected_range: "https://uor.foundation/schema/WittLevel",
2640                    min_count: 1,
2641                    max_count: 1,
2642                    kind: ViolationKind::Missing,
2643                }),
2644            };
2645        let budget = match self.thermodynamic_budget {
2646            Some(b) => b,
2647            None => return Err(ShapeViolation {
2648                shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2649                constraint_iri:
2650                    "https://uor.foundation/conformance/compileUnit_thermodynamicBudget_constraint",
2651                property_iri: "https://uor.foundation/reduction/thermodynamicBudget",
2652                expected_range: "http://www.w3.org/2001/XMLSchema#decimal",
2653                min_count: 1,
2654                max_count: 1,
2655                kind: ViolationKind::Missing,
2656            }),
2657        };
2658        let target_domains =
2659            match self.target_domains {
2660                Some(d) if !d.is_empty() => d,
2661                _ => return Err(ShapeViolation {
2662                    shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2663                    constraint_iri:
2664                        "https://uor.foundation/conformance/compileUnit_targetDomains_constraint",
2665                    property_iri: "https://uor.foundation/reduction/targetDomains",
2666                    expected_range: "https://uor.foundation/op/VerificationDomain",
2667                    min_count: 1,
2668                    max_count: 0,
2669                    kind: ViolationKind::Missing,
2670                }),
2671            };
2672        let result_type_iri = match self.result_type_iri {
2673            Some(iri) => iri,
2674            None => {
2675                return Err(ShapeViolation {
2676                    shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
2677                    constraint_iri:
2678                        "https://uor.foundation/conformance/compileUnit_resultType_constraint",
2679                    property_iri: "https://uor.foundation/reduction/resultType",
2680                    expected_range: "https://uor.foundation/type/ConstrainedType",
2681                    min_count: 1,
2682                    max_count: 1,
2683                    kind: ViolationKind::Missing,
2684                })
2685            }
2686        };
2687        // v0.2.2 Phase H1: bindings is optional; absent declares no bindings.
2688        let bindings: &'a [Binding] = match self.bindings {
2689            Some(b) => b,
2690            None => &[],
2691        };
2692        Ok(Validated::new(CompileUnit {
2693            level,
2694            budget,
2695            result_type_iri,
2696            root_term,
2697            bindings,
2698            target_domains,
2699        }))
2700    }
2701}
2702
2703impl<'a, const INLINE_BYTES: usize> Default for CompileUnitBuilder<'a, INLINE_BYTES> {
2704    fn default() -> Self {
2705        Self::new()
2706    }
2707}
2708
2709/// Builder for `EffectDeclaration`. Validates against `EffectShape`.
2710#[derive(Debug, Clone)]
2711pub struct EffectDeclarationBuilder<'a> {
2712    /// The `name` field.
2713    name: Option<&'a str>,
2714    /// The `target_sites` field.
2715    target_sites: Option<&'a [u32]>,
2716    /// The `budget_delta` field.
2717    budget_delta: Option<i64>,
2718    /// The `commutes` field.
2719    commutes: Option<bool>,
2720}
2721
2722/// Declared effect validated against `EffectShape`.
2723#[derive(Debug, Clone, PartialEq, Eq)]
2724pub struct EffectDeclaration {
2725    /// Shape IRI this declaration was validated against.
2726    pub shape_iri: &'static str,
2727}
2728
2729impl EffectDeclaration {
2730    /// v0.2.2 Phase G: const-constructible empty form used by
2731    /// `validate_*_const` companion functions.
2732    #[inline]
2733    #[must_use]
2734    #[allow(dead_code)]
2735    pub(crate) const fn empty_const() -> Self {
2736        Self {
2737            shape_iri: "https://uor.foundation/conformance/EffectShape",
2738        }
2739    }
2740}
2741
2742impl<'a> EffectDeclarationBuilder<'a> {
2743    /// Creates a new empty builder.
2744    #[must_use]
2745    pub const fn new() -> Self {
2746        Self {
2747            name: None,
2748            target_sites: None,
2749            budget_delta: None,
2750            commutes: None,
2751        }
2752    }
2753
2754    /// Set the `name` field.
2755    #[must_use]
2756    pub const fn name(mut self, value: &'a str) -> Self {
2757        self.name = Some(value);
2758        self
2759    }
2760
2761    /// Set the `target_sites` field.
2762    #[must_use]
2763    pub const fn target_sites(mut self, value: &'a [u32]) -> Self {
2764        self.target_sites = Some(value);
2765        self
2766    }
2767
2768    /// Set the `budget_delta` field.
2769    #[must_use]
2770    pub const fn budget_delta(mut self, value: i64) -> Self {
2771        self.budget_delta = Some(value);
2772        self
2773    }
2774
2775    /// Set the `commutes` field.
2776    #[must_use]
2777    pub const fn commutes(mut self, value: bool) -> Self {
2778        self.commutes = Some(value);
2779        self
2780    }
2781
2782    /// Validate against `EffectShape`.
2783    /// # Errors
2784    /// Returns `ShapeViolation` if any required field is missing.
2785    pub fn validate(self) -> Result<Validated<EffectDeclaration>, ShapeViolation> {
2786        if self.name.is_none() {
2787            return Err(ShapeViolation {
2788                shape_iri: "https://uor.foundation/conformance/EffectShape",
2789                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2790                property_iri: "https://uor.foundation/conformance/name",
2791                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2792                min_count: 1,
2793                max_count: 1,
2794                kind: ViolationKind::Missing,
2795            });
2796        }
2797        if self.target_sites.is_none() {
2798            return Err(ShapeViolation {
2799                shape_iri: "https://uor.foundation/conformance/EffectShape",
2800                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2801                property_iri: "https://uor.foundation/conformance/target_sites",
2802                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2803                min_count: 1,
2804                max_count: 1,
2805                kind: ViolationKind::Missing,
2806            });
2807        }
2808        if self.budget_delta.is_none() {
2809            return Err(ShapeViolation {
2810                shape_iri: "https://uor.foundation/conformance/EffectShape",
2811                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2812                property_iri: "https://uor.foundation/conformance/budget_delta",
2813                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2814                min_count: 1,
2815                max_count: 1,
2816                kind: ViolationKind::Missing,
2817            });
2818        }
2819        if self.commutes.is_none() {
2820            return Err(ShapeViolation {
2821                shape_iri: "https://uor.foundation/conformance/EffectShape",
2822                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2823                property_iri: "https://uor.foundation/conformance/commutes",
2824                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2825                min_count: 1,
2826                max_count: 1,
2827                kind: ViolationKind::Missing,
2828            });
2829        }
2830        Ok(Validated::new(EffectDeclaration {
2831            shape_iri: "https://uor.foundation/conformance/EffectShape",
2832        }))
2833    }
2834
2835    /// Phase C.1: const-fn companion for `EffectDeclarationBuilder::validate`.
2836    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
2837    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
2838    /// # Errors
2839    /// Returns `ShapeViolation` if any required field is missing.
2840    pub const fn validate_const(
2841        &self,
2842    ) -> Result<Validated<EffectDeclaration, CompileTime>, ShapeViolation> {
2843        if self.name.is_none() {
2844            return Err(ShapeViolation {
2845                shape_iri: "https://uor.foundation/conformance/EffectShape",
2846                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2847                property_iri: "https://uor.foundation/conformance/name",
2848                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2849                min_count: 1,
2850                max_count: 1,
2851                kind: ViolationKind::Missing,
2852            });
2853        }
2854        if self.target_sites.is_none() {
2855            return Err(ShapeViolation {
2856                shape_iri: "https://uor.foundation/conformance/EffectShape",
2857                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2858                property_iri: "https://uor.foundation/conformance/target_sites",
2859                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2860                min_count: 1,
2861                max_count: 1,
2862                kind: ViolationKind::Missing,
2863            });
2864        }
2865        if self.budget_delta.is_none() {
2866            return Err(ShapeViolation {
2867                shape_iri: "https://uor.foundation/conformance/EffectShape",
2868                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2869                property_iri: "https://uor.foundation/conformance/budget_delta",
2870                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2871                min_count: 1,
2872                max_count: 1,
2873                kind: ViolationKind::Missing,
2874            });
2875        }
2876        if self.commutes.is_none() {
2877            return Err(ShapeViolation {
2878                shape_iri: "https://uor.foundation/conformance/EffectShape",
2879                constraint_iri: "https://uor.foundation/conformance/EffectShape",
2880                property_iri: "https://uor.foundation/conformance/commutes",
2881                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2882                min_count: 1,
2883                max_count: 1,
2884                kind: ViolationKind::Missing,
2885            });
2886        }
2887        Ok(Validated::new(EffectDeclaration {
2888            shape_iri: "https://uor.foundation/conformance/EffectShape",
2889        }))
2890    }
2891}
2892
2893impl<'a> Default for EffectDeclarationBuilder<'a> {
2894    fn default() -> Self {
2895        Self::new()
2896    }
2897}
2898
2899/// Builder for `GroundingDeclaration`. Validates against `GroundingShape`.
2900#[derive(Debug, Clone)]
2901pub struct GroundingDeclarationBuilder<'a> {
2902    /// The `source_type` field.
2903    source_type: Option<&'a str>,
2904    /// The `ring_mapping` field.
2905    ring_mapping: Option<&'a str>,
2906    /// The `invertibility` field.
2907    invertibility: Option<bool>,
2908}
2909
2910/// Declared grounding validated against `GroundingShape`.
2911#[derive(Debug, Clone, PartialEq, Eq)]
2912pub struct GroundingDeclaration {
2913    /// Shape IRI this declaration was validated against.
2914    pub shape_iri: &'static str,
2915}
2916
2917impl GroundingDeclaration {
2918    /// v0.2.2 Phase G: const-constructible empty form used by
2919    /// `validate_*_const` companion functions.
2920    #[inline]
2921    #[must_use]
2922    #[allow(dead_code)]
2923    pub(crate) const fn empty_const() -> Self {
2924        Self {
2925            shape_iri: "https://uor.foundation/conformance/GroundingShape",
2926        }
2927    }
2928}
2929
2930impl<'a> GroundingDeclarationBuilder<'a> {
2931    /// Creates a new empty builder.
2932    #[must_use]
2933    pub const fn new() -> Self {
2934        Self {
2935            source_type: None,
2936            ring_mapping: None,
2937            invertibility: None,
2938        }
2939    }
2940
2941    /// Set the `source_type` field.
2942    #[must_use]
2943    pub const fn source_type(mut self, value: &'a str) -> Self {
2944        self.source_type = Some(value);
2945        self
2946    }
2947
2948    /// Set the `ring_mapping` field.
2949    #[must_use]
2950    pub const fn ring_mapping(mut self, value: &'a str) -> Self {
2951        self.ring_mapping = Some(value);
2952        self
2953    }
2954
2955    /// Set the `invertibility` field.
2956    #[must_use]
2957    pub const fn invertibility(mut self, value: bool) -> Self {
2958        self.invertibility = Some(value);
2959        self
2960    }
2961
2962    /// Validate against `GroundingShape`.
2963    /// # Errors
2964    /// Returns `ShapeViolation` if any required field is missing.
2965    pub fn validate(self) -> Result<Validated<GroundingDeclaration>, ShapeViolation> {
2966        if self.source_type.is_none() {
2967            return Err(ShapeViolation {
2968                shape_iri: "https://uor.foundation/conformance/GroundingShape",
2969                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
2970                property_iri: "https://uor.foundation/conformance/source_type",
2971                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2972                min_count: 1,
2973                max_count: 1,
2974                kind: ViolationKind::Missing,
2975            });
2976        }
2977        if self.ring_mapping.is_none() {
2978            return Err(ShapeViolation {
2979                shape_iri: "https://uor.foundation/conformance/GroundingShape",
2980                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
2981                property_iri: "https://uor.foundation/conformance/ring_mapping",
2982                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2983                min_count: 1,
2984                max_count: 1,
2985                kind: ViolationKind::Missing,
2986            });
2987        }
2988        if self.invertibility.is_none() {
2989            return Err(ShapeViolation {
2990                shape_iri: "https://uor.foundation/conformance/GroundingShape",
2991                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
2992                property_iri: "https://uor.foundation/conformance/invertibility",
2993                expected_range: "http://www.w3.org/2002/07/owl#Thing",
2994                min_count: 1,
2995                max_count: 1,
2996                kind: ViolationKind::Missing,
2997            });
2998        }
2999        Ok(Validated::new(GroundingDeclaration {
3000            shape_iri: "https://uor.foundation/conformance/GroundingShape",
3001        }))
3002    }
3003
3004    /// Phase C.1: const-fn companion for `GroundingDeclarationBuilder::validate`.
3005    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3006    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3007    /// # Errors
3008    /// Returns `ShapeViolation` if any required field is missing.
3009    pub const fn validate_const(
3010        &self,
3011    ) -> Result<Validated<GroundingDeclaration, CompileTime>, ShapeViolation> {
3012        if self.source_type.is_none() {
3013            return Err(ShapeViolation {
3014                shape_iri: "https://uor.foundation/conformance/GroundingShape",
3015                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
3016                property_iri: "https://uor.foundation/conformance/source_type",
3017                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3018                min_count: 1,
3019                max_count: 1,
3020                kind: ViolationKind::Missing,
3021            });
3022        }
3023        if self.ring_mapping.is_none() {
3024            return Err(ShapeViolation {
3025                shape_iri: "https://uor.foundation/conformance/GroundingShape",
3026                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
3027                property_iri: "https://uor.foundation/conformance/ring_mapping",
3028                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3029                min_count: 1,
3030                max_count: 1,
3031                kind: ViolationKind::Missing,
3032            });
3033        }
3034        if self.invertibility.is_none() {
3035            return Err(ShapeViolation {
3036                shape_iri: "https://uor.foundation/conformance/GroundingShape",
3037                constraint_iri: "https://uor.foundation/conformance/GroundingShape",
3038                property_iri: "https://uor.foundation/conformance/invertibility",
3039                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3040                min_count: 1,
3041                max_count: 1,
3042                kind: ViolationKind::Missing,
3043            });
3044        }
3045        Ok(Validated::new(GroundingDeclaration {
3046            shape_iri: "https://uor.foundation/conformance/GroundingShape",
3047        }))
3048    }
3049}
3050
3051impl<'a> Default for GroundingDeclarationBuilder<'a> {
3052    fn default() -> Self {
3053        Self::new()
3054    }
3055}
3056
3057/// Builder for `DispatchDeclaration`. Validates against `DispatchShape`.
3058#[derive(Debug, Clone)]
3059pub struct DispatchDeclarationBuilder<'a, const INLINE_BYTES: usize> {
3060    /// The `predicate` field.
3061    predicate: Option<&'a [Term<'a, INLINE_BYTES>]>,
3062    /// The `target_resolver` field.
3063    target_resolver: Option<&'a str>,
3064    /// The `priority` field.
3065    priority: Option<u32>,
3066}
3067
3068/// Declared dispatch rule validated against `DispatchShape`.
3069#[derive(Debug, Clone, PartialEq, Eq)]
3070pub struct DispatchDeclaration {
3071    /// Shape IRI this declaration was validated against.
3072    pub shape_iri: &'static str,
3073}
3074
3075impl DispatchDeclaration {
3076    /// v0.2.2 Phase G: const-constructible empty form used by
3077    /// `validate_*_const` companion functions.
3078    #[inline]
3079    #[must_use]
3080    #[allow(dead_code)]
3081    pub(crate) const fn empty_const() -> Self {
3082        Self {
3083            shape_iri: "https://uor.foundation/conformance/DispatchShape",
3084        }
3085    }
3086}
3087
3088impl<'a, const INLINE_BYTES: usize> DispatchDeclarationBuilder<'a, INLINE_BYTES> {
3089    /// Creates a new empty builder.
3090    #[must_use]
3091    pub const fn new() -> Self {
3092        Self {
3093            predicate: None,
3094            target_resolver: None,
3095            priority: None,
3096        }
3097    }
3098
3099    /// Set the `predicate` field.
3100    #[must_use]
3101    pub const fn predicate(mut self, value: &'a [Term<'a, INLINE_BYTES>]) -> Self {
3102        self.predicate = Some(value);
3103        self
3104    }
3105
3106    /// Set the `target_resolver` field.
3107    #[must_use]
3108    pub const fn target_resolver(mut self, value: &'a str) -> Self {
3109        self.target_resolver = Some(value);
3110        self
3111    }
3112
3113    /// Set the `priority` field.
3114    #[must_use]
3115    pub const fn priority(mut self, value: u32) -> Self {
3116        self.priority = Some(value);
3117        self
3118    }
3119
3120    /// Validate against `DispatchShape`.
3121    /// # Errors
3122    /// Returns `ShapeViolation` if any required field is missing.
3123    pub fn validate(self) -> Result<Validated<DispatchDeclaration>, ShapeViolation> {
3124        if self.predicate.is_none() {
3125            return Err(ShapeViolation {
3126                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3127                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3128                property_iri: "https://uor.foundation/conformance/predicate",
3129                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3130                min_count: 1,
3131                max_count: 1,
3132                kind: ViolationKind::Missing,
3133            });
3134        }
3135        if self.target_resolver.is_none() {
3136            return Err(ShapeViolation {
3137                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3138                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3139                property_iri: "https://uor.foundation/conformance/target_resolver",
3140                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3141                min_count: 1,
3142                max_count: 1,
3143                kind: ViolationKind::Missing,
3144            });
3145        }
3146        if self.priority.is_none() {
3147            return Err(ShapeViolation {
3148                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3149                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3150                property_iri: "https://uor.foundation/conformance/priority",
3151                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3152                min_count: 1,
3153                max_count: 1,
3154                kind: ViolationKind::Missing,
3155            });
3156        }
3157        Ok(Validated::new(DispatchDeclaration {
3158            shape_iri: "https://uor.foundation/conformance/DispatchShape",
3159        }))
3160    }
3161
3162    /// Phase C.1: const-fn companion for `DispatchDeclarationBuilder::validate`.
3163    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3164    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3165    /// # Errors
3166    /// Returns `ShapeViolation` if any required field is missing.
3167    pub const fn validate_const(
3168        &self,
3169    ) -> Result<Validated<DispatchDeclaration, CompileTime>, ShapeViolation> {
3170        if self.predicate.is_none() {
3171            return Err(ShapeViolation {
3172                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3173                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3174                property_iri: "https://uor.foundation/conformance/predicate",
3175                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3176                min_count: 1,
3177                max_count: 1,
3178                kind: ViolationKind::Missing,
3179            });
3180        }
3181        if self.target_resolver.is_none() {
3182            return Err(ShapeViolation {
3183                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3184                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3185                property_iri: "https://uor.foundation/conformance/target_resolver",
3186                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3187                min_count: 1,
3188                max_count: 1,
3189                kind: ViolationKind::Missing,
3190            });
3191        }
3192        if self.priority.is_none() {
3193            return Err(ShapeViolation {
3194                shape_iri: "https://uor.foundation/conformance/DispatchShape",
3195                constraint_iri: "https://uor.foundation/conformance/DispatchShape",
3196                property_iri: "https://uor.foundation/conformance/priority",
3197                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3198                min_count: 1,
3199                max_count: 1,
3200                kind: ViolationKind::Missing,
3201            });
3202        }
3203        Ok(Validated::new(DispatchDeclaration {
3204            shape_iri: "https://uor.foundation/conformance/DispatchShape",
3205        }))
3206    }
3207}
3208
3209impl<'a, const INLINE_BYTES: usize> Default for DispatchDeclarationBuilder<'a, INLINE_BYTES> {
3210    fn default() -> Self {
3211        Self::new()
3212    }
3213}
3214
3215/// Builder for `LeaseDeclaration`. Validates against `LeaseShape`.
3216#[derive(Debug, Clone)]
3217pub struct LeaseDeclarationBuilder<'a> {
3218    /// The `linear_site` field.
3219    linear_site: Option<u32>,
3220    /// The `scope` field.
3221    scope: Option<&'a str>,
3222}
3223
3224/// Declared lease validated against `LeaseShape`.
3225#[derive(Debug, Clone, PartialEq, Eq)]
3226pub struct LeaseDeclaration {
3227    /// Shape IRI this declaration was validated against.
3228    pub shape_iri: &'static str,
3229}
3230
3231impl LeaseDeclaration {
3232    /// v0.2.2 Phase G: const-constructible empty form used by
3233    /// `validate_*_const` companion functions.
3234    #[inline]
3235    #[must_use]
3236    #[allow(dead_code)]
3237    pub(crate) const fn empty_const() -> Self {
3238        Self {
3239            shape_iri: "https://uor.foundation/conformance/LeaseShape",
3240        }
3241    }
3242}
3243
3244impl<'a> LeaseDeclarationBuilder<'a> {
3245    /// Creates a new empty builder.
3246    #[must_use]
3247    pub const fn new() -> Self {
3248        Self {
3249            linear_site: None,
3250            scope: None,
3251        }
3252    }
3253
3254    /// Set the `linear_site` field.
3255    #[must_use]
3256    pub const fn linear_site(mut self, value: u32) -> Self {
3257        self.linear_site = Some(value);
3258        self
3259    }
3260
3261    /// Set the `scope` field.
3262    #[must_use]
3263    pub const fn scope(mut self, value: &'a str) -> Self {
3264        self.scope = Some(value);
3265        self
3266    }
3267
3268    /// Validate against `LeaseShape`.
3269    /// # Errors
3270    /// Returns `ShapeViolation` if any required field is missing.
3271    pub fn validate(self) -> Result<Validated<LeaseDeclaration>, ShapeViolation> {
3272        if self.linear_site.is_none() {
3273            return Err(ShapeViolation {
3274                shape_iri: "https://uor.foundation/conformance/LeaseShape",
3275                constraint_iri: "https://uor.foundation/conformance/LeaseShape",
3276                property_iri: "https://uor.foundation/conformance/linear_site",
3277                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3278                min_count: 1,
3279                max_count: 1,
3280                kind: ViolationKind::Missing,
3281            });
3282        }
3283        if self.scope.is_none() {
3284            return Err(ShapeViolation {
3285                shape_iri: "https://uor.foundation/conformance/LeaseShape",
3286                constraint_iri: "https://uor.foundation/conformance/LeaseShape",
3287                property_iri: "https://uor.foundation/conformance/scope",
3288                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3289                min_count: 1,
3290                max_count: 1,
3291                kind: ViolationKind::Missing,
3292            });
3293        }
3294        Ok(Validated::new(LeaseDeclaration {
3295            shape_iri: "https://uor.foundation/conformance/LeaseShape",
3296        }))
3297    }
3298
3299    /// Phase C.1: const-fn companion for `LeaseDeclarationBuilder::validate`.
3300    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3301    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3302    /// # Errors
3303    /// Returns `ShapeViolation` if any required field is missing.
3304    pub const fn validate_const(
3305        &self,
3306    ) -> Result<Validated<LeaseDeclaration, CompileTime>, ShapeViolation> {
3307        if self.linear_site.is_none() {
3308            return Err(ShapeViolation {
3309                shape_iri: "https://uor.foundation/conformance/LeaseShape",
3310                constraint_iri: "https://uor.foundation/conformance/LeaseShape",
3311                property_iri: "https://uor.foundation/conformance/linear_site",
3312                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3313                min_count: 1,
3314                max_count: 1,
3315                kind: ViolationKind::Missing,
3316            });
3317        }
3318        if self.scope.is_none() {
3319            return Err(ShapeViolation {
3320                shape_iri: "https://uor.foundation/conformance/LeaseShape",
3321                constraint_iri: "https://uor.foundation/conformance/LeaseShape",
3322                property_iri: "https://uor.foundation/conformance/scope",
3323                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3324                min_count: 1,
3325                max_count: 1,
3326                kind: ViolationKind::Missing,
3327            });
3328        }
3329        Ok(Validated::new(LeaseDeclaration {
3330            shape_iri: "https://uor.foundation/conformance/LeaseShape",
3331        }))
3332    }
3333}
3334
3335impl<'a> Default for LeaseDeclarationBuilder<'a> {
3336    fn default() -> Self {
3337        Self::new()
3338    }
3339}
3340
3341/// Builder for `StreamDeclaration`. Validates against `StreamShape`.
3342#[derive(Debug, Clone)]
3343pub struct StreamDeclarationBuilder<'a, const INLINE_BYTES: usize> {
3344    /// The `seed` field.
3345    seed: Option<&'a [Term<'a, INLINE_BYTES>]>,
3346    /// The `step` field.
3347    step: Option<&'a [Term<'a, INLINE_BYTES>]>,
3348    /// The `productivity_witness` field.
3349    productivity_witness: Option<&'a str>,
3350}
3351
3352/// Declared stream validated against `StreamShape`.
3353#[derive(Debug, Clone, PartialEq, Eq)]
3354pub struct StreamDeclaration {
3355    /// Shape IRI this declaration was validated against.
3356    pub shape_iri: &'static str,
3357}
3358
3359impl StreamDeclaration {
3360    /// v0.2.2 Phase G: const-constructible empty form used by
3361    /// `validate_*_const` companion functions.
3362    #[inline]
3363    #[must_use]
3364    #[allow(dead_code)]
3365    pub(crate) const fn empty_const() -> Self {
3366        Self {
3367            shape_iri: "https://uor.foundation/conformance/StreamShape",
3368        }
3369    }
3370}
3371
3372impl<'a, const INLINE_BYTES: usize> StreamDeclarationBuilder<'a, INLINE_BYTES> {
3373    /// Creates a new empty builder.
3374    #[must_use]
3375    pub const fn new() -> Self {
3376        Self {
3377            seed: None,
3378            step: None,
3379            productivity_witness: None,
3380        }
3381    }
3382
3383    /// Set the `seed` field.
3384    #[must_use]
3385    pub const fn seed(mut self, value: &'a [Term<'a, INLINE_BYTES>]) -> Self {
3386        self.seed = Some(value);
3387        self
3388    }
3389
3390    /// Set the `step` field.
3391    #[must_use]
3392    pub const fn step(mut self, value: &'a [Term<'a, INLINE_BYTES>]) -> Self {
3393        self.step = Some(value);
3394        self
3395    }
3396
3397    /// Set the `productivity_witness` field.
3398    #[must_use]
3399    pub const fn productivity_witness(mut self, value: &'a str) -> Self {
3400        self.productivity_witness = Some(value);
3401        self
3402    }
3403
3404    /// Validate against `StreamShape`.
3405    /// # Errors
3406    /// Returns `ShapeViolation` if any required field is missing.
3407    pub fn validate(self) -> Result<Validated<StreamDeclaration>, ShapeViolation> {
3408        if self.seed.is_none() {
3409            return Err(ShapeViolation {
3410                shape_iri: "https://uor.foundation/conformance/StreamShape",
3411                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3412                property_iri: "https://uor.foundation/conformance/seed",
3413                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3414                min_count: 1,
3415                max_count: 1,
3416                kind: ViolationKind::Missing,
3417            });
3418        }
3419        if self.step.is_none() {
3420            return Err(ShapeViolation {
3421                shape_iri: "https://uor.foundation/conformance/StreamShape",
3422                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3423                property_iri: "https://uor.foundation/conformance/step",
3424                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3425                min_count: 1,
3426                max_count: 1,
3427                kind: ViolationKind::Missing,
3428            });
3429        }
3430        if self.productivity_witness.is_none() {
3431            return Err(ShapeViolation {
3432                shape_iri: "https://uor.foundation/conformance/StreamShape",
3433                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3434                property_iri: "https://uor.foundation/conformance/productivity_witness",
3435                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3436                min_count: 1,
3437                max_count: 1,
3438                kind: ViolationKind::Missing,
3439            });
3440        }
3441        Ok(Validated::new(StreamDeclaration {
3442            shape_iri: "https://uor.foundation/conformance/StreamShape",
3443        }))
3444    }
3445
3446    /// Phase C.1: const-fn companion for `StreamDeclarationBuilder::validate`.
3447    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3448    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3449    /// # Errors
3450    /// Returns `ShapeViolation` if any required field is missing.
3451    pub const fn validate_const(
3452        &self,
3453    ) -> Result<Validated<StreamDeclaration, CompileTime>, ShapeViolation> {
3454        if self.seed.is_none() {
3455            return Err(ShapeViolation {
3456                shape_iri: "https://uor.foundation/conformance/StreamShape",
3457                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3458                property_iri: "https://uor.foundation/conformance/seed",
3459                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3460                min_count: 1,
3461                max_count: 1,
3462                kind: ViolationKind::Missing,
3463            });
3464        }
3465        if self.step.is_none() {
3466            return Err(ShapeViolation {
3467                shape_iri: "https://uor.foundation/conformance/StreamShape",
3468                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3469                property_iri: "https://uor.foundation/conformance/step",
3470                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3471                min_count: 1,
3472                max_count: 1,
3473                kind: ViolationKind::Missing,
3474            });
3475        }
3476        if self.productivity_witness.is_none() {
3477            return Err(ShapeViolation {
3478                shape_iri: "https://uor.foundation/conformance/StreamShape",
3479                constraint_iri: "https://uor.foundation/conformance/StreamShape",
3480                property_iri: "https://uor.foundation/conformance/productivity_witness",
3481                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3482                min_count: 1,
3483                max_count: 1,
3484                kind: ViolationKind::Missing,
3485            });
3486        }
3487        Ok(Validated::new(StreamDeclaration {
3488            shape_iri: "https://uor.foundation/conformance/StreamShape",
3489        }))
3490    }
3491}
3492
3493impl<'a, const INLINE_BYTES: usize> Default for StreamDeclarationBuilder<'a, INLINE_BYTES> {
3494    fn default() -> Self {
3495        Self::new()
3496    }
3497}
3498
3499/// Builder for `PredicateDeclaration`. Validates against `PredicateShape`.
3500#[derive(Debug, Clone)]
3501pub struct PredicateDeclarationBuilder<'a, const INLINE_BYTES: usize> {
3502    /// The `input_type` field.
3503    input_type: Option<&'a str>,
3504    /// The `evaluator` field.
3505    evaluator: Option<&'a [Term<'a, INLINE_BYTES>]>,
3506    /// The `termination_witness` field.
3507    termination_witness: Option<&'a str>,
3508}
3509
3510/// Declared predicate validated against `PredicateShape`.
3511#[derive(Debug, Clone, PartialEq, Eq)]
3512pub struct PredicateDeclaration {
3513    /// Shape IRI this declaration was validated against.
3514    pub shape_iri: &'static str,
3515}
3516
3517impl PredicateDeclaration {
3518    /// v0.2.2 Phase G: const-constructible empty form used by
3519    /// `validate_*_const` companion functions.
3520    #[inline]
3521    #[must_use]
3522    #[allow(dead_code)]
3523    pub(crate) const fn empty_const() -> Self {
3524        Self {
3525            shape_iri: "https://uor.foundation/conformance/PredicateShape",
3526        }
3527    }
3528}
3529
3530impl<'a, const INLINE_BYTES: usize> PredicateDeclarationBuilder<'a, INLINE_BYTES> {
3531    /// Creates a new empty builder.
3532    #[must_use]
3533    pub const fn new() -> Self {
3534        Self {
3535            input_type: None,
3536            evaluator: None,
3537            termination_witness: None,
3538        }
3539    }
3540
3541    /// Set the `input_type` field.
3542    #[must_use]
3543    pub const fn input_type(mut self, value: &'a str) -> Self {
3544        self.input_type = Some(value);
3545        self
3546    }
3547
3548    /// Set the `evaluator` field.
3549    #[must_use]
3550    pub const fn evaluator(mut self, value: &'a [Term<'a, INLINE_BYTES>]) -> Self {
3551        self.evaluator = Some(value);
3552        self
3553    }
3554
3555    /// Set the `termination_witness` field.
3556    #[must_use]
3557    pub const fn termination_witness(mut self, value: &'a str) -> Self {
3558        self.termination_witness = Some(value);
3559        self
3560    }
3561
3562    /// Validate against `PredicateShape`.
3563    /// # Errors
3564    /// Returns `ShapeViolation` if any required field is missing.
3565    pub fn validate(self) -> Result<Validated<PredicateDeclaration>, ShapeViolation> {
3566        if self.input_type.is_none() {
3567            return Err(ShapeViolation {
3568                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3569                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3570                property_iri: "https://uor.foundation/conformance/input_type",
3571                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3572                min_count: 1,
3573                max_count: 1,
3574                kind: ViolationKind::Missing,
3575            });
3576        }
3577        if self.evaluator.is_none() {
3578            return Err(ShapeViolation {
3579                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3580                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3581                property_iri: "https://uor.foundation/conformance/evaluator",
3582                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3583                min_count: 1,
3584                max_count: 1,
3585                kind: ViolationKind::Missing,
3586            });
3587        }
3588        if self.termination_witness.is_none() {
3589            return Err(ShapeViolation {
3590                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3591                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3592                property_iri: "https://uor.foundation/conformance/termination_witness",
3593                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3594                min_count: 1,
3595                max_count: 1,
3596                kind: ViolationKind::Missing,
3597            });
3598        }
3599        Ok(Validated::new(PredicateDeclaration {
3600            shape_iri: "https://uor.foundation/conformance/PredicateShape",
3601        }))
3602    }
3603
3604    /// Phase C.1: const-fn companion for `PredicateDeclarationBuilder::validate`.
3605    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3606    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3607    /// # Errors
3608    /// Returns `ShapeViolation` if any required field is missing.
3609    pub const fn validate_const(
3610        &self,
3611    ) -> Result<Validated<PredicateDeclaration, CompileTime>, ShapeViolation> {
3612        if self.input_type.is_none() {
3613            return Err(ShapeViolation {
3614                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3615                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3616                property_iri: "https://uor.foundation/conformance/input_type",
3617                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3618                min_count: 1,
3619                max_count: 1,
3620                kind: ViolationKind::Missing,
3621            });
3622        }
3623        if self.evaluator.is_none() {
3624            return Err(ShapeViolation {
3625                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3626                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3627                property_iri: "https://uor.foundation/conformance/evaluator",
3628                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3629                min_count: 1,
3630                max_count: 1,
3631                kind: ViolationKind::Missing,
3632            });
3633        }
3634        if self.termination_witness.is_none() {
3635            return Err(ShapeViolation {
3636                shape_iri: "https://uor.foundation/conformance/PredicateShape",
3637                constraint_iri: "https://uor.foundation/conformance/PredicateShape",
3638                property_iri: "https://uor.foundation/conformance/termination_witness",
3639                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3640                min_count: 1,
3641                max_count: 1,
3642                kind: ViolationKind::Missing,
3643            });
3644        }
3645        Ok(Validated::new(PredicateDeclaration {
3646            shape_iri: "https://uor.foundation/conformance/PredicateShape",
3647        }))
3648    }
3649}
3650
3651impl<'a, const INLINE_BYTES: usize> Default for PredicateDeclarationBuilder<'a, INLINE_BYTES> {
3652    fn default() -> Self {
3653        Self::new()
3654    }
3655}
3656
3657/// Builder for `ParallelDeclaration`. Validates against `ParallelShape`.
3658#[derive(Debug, Clone)]
3659pub struct ParallelDeclarationBuilder<'a> {
3660    /// The `site_partition` field.
3661    site_partition: Option<&'a [u32]>,
3662    /// The `disjointness_witness` field.
3663    disjointness_witness: Option<&'a str>,
3664}
3665
3666/// Declared parallel composition validated against `ParallelShape`.
3667#[derive(Debug, Clone, PartialEq, Eq)]
3668pub struct ParallelDeclaration {
3669    /// Shape IRI this declaration was validated against.
3670    pub shape_iri: &'static str,
3671}
3672
3673impl ParallelDeclaration {
3674    /// v0.2.2 Phase G: const-constructible empty form used by
3675    /// `validate_*_const` companion functions.
3676    #[inline]
3677    #[must_use]
3678    #[allow(dead_code)]
3679    pub(crate) const fn empty_const() -> Self {
3680        Self {
3681            shape_iri: "https://uor.foundation/conformance/ParallelShape",
3682        }
3683    }
3684}
3685
3686impl<'a> ParallelDeclarationBuilder<'a> {
3687    /// Creates a new empty builder.
3688    #[must_use]
3689    pub const fn new() -> Self {
3690        Self {
3691            site_partition: None,
3692            disjointness_witness: None,
3693        }
3694    }
3695
3696    /// Set the `site_partition` field.
3697    #[must_use]
3698    pub const fn site_partition(mut self, value: &'a [u32]) -> Self {
3699        self.site_partition = Some(value);
3700        self
3701    }
3702
3703    /// Set the `disjointness_witness` field.
3704    #[must_use]
3705    pub const fn disjointness_witness(mut self, value: &'a str) -> Self {
3706        self.disjointness_witness = Some(value);
3707        self
3708    }
3709
3710    /// Validate against `ParallelShape`.
3711    /// # Errors
3712    /// Returns `ShapeViolation` if any required field is missing.
3713    pub fn validate(self) -> Result<Validated<ParallelDeclaration>, ShapeViolation> {
3714        if self.site_partition.is_none() {
3715            return Err(ShapeViolation {
3716                shape_iri: "https://uor.foundation/conformance/ParallelShape",
3717                constraint_iri: "https://uor.foundation/conformance/ParallelShape",
3718                property_iri: "https://uor.foundation/conformance/site_partition",
3719                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3720                min_count: 1,
3721                max_count: 1,
3722                kind: ViolationKind::Missing,
3723            });
3724        }
3725        if self.disjointness_witness.is_none() {
3726            return Err(ShapeViolation {
3727                shape_iri: "https://uor.foundation/conformance/ParallelShape",
3728                constraint_iri: "https://uor.foundation/conformance/ParallelShape",
3729                property_iri: "https://uor.foundation/conformance/disjointness_witness",
3730                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3731                min_count: 1,
3732                max_count: 1,
3733                kind: ViolationKind::Missing,
3734            });
3735        }
3736        Ok(Validated::new(ParallelDeclaration {
3737            shape_iri: "https://uor.foundation/conformance/ParallelShape",
3738        }))
3739    }
3740
3741    /// Phase C.1: const-fn companion for `ParallelDeclarationBuilder::validate`.
3742    /// Returns `Validated<_, CompileTime>` on success, allowing compile-time
3743    /// evidence via `const _V: Validated<_, CompileTime> = builder.validate_const().unwrap();`.
3744    /// # Errors
3745    /// Returns `ShapeViolation` if any required field is missing.
3746    pub const fn validate_const(
3747        &self,
3748    ) -> Result<Validated<ParallelDeclaration, CompileTime>, ShapeViolation> {
3749        if self.site_partition.is_none() {
3750            return Err(ShapeViolation {
3751                shape_iri: "https://uor.foundation/conformance/ParallelShape",
3752                constraint_iri: "https://uor.foundation/conformance/ParallelShape",
3753                property_iri: "https://uor.foundation/conformance/site_partition",
3754                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3755                min_count: 1,
3756                max_count: 1,
3757                kind: ViolationKind::Missing,
3758            });
3759        }
3760        if self.disjointness_witness.is_none() {
3761            return Err(ShapeViolation {
3762                shape_iri: "https://uor.foundation/conformance/ParallelShape",
3763                constraint_iri: "https://uor.foundation/conformance/ParallelShape",
3764                property_iri: "https://uor.foundation/conformance/disjointness_witness",
3765                expected_range: "http://www.w3.org/2002/07/owl#Thing",
3766                min_count: 1,
3767                max_count: 1,
3768                kind: ViolationKind::Missing,
3769            });
3770        }
3771        Ok(Validated::new(ParallelDeclaration {
3772            shape_iri: "https://uor.foundation/conformance/ParallelShape",
3773        }))
3774    }
3775}
3776
3777impl<'a> Default for ParallelDeclarationBuilder<'a> {
3778    fn default() -> Self {
3779        Self::new()
3780    }
3781}
3782
3783impl<'a> ParallelDeclarationBuilder<'a> {
3784    /// v0.2.2 T2.7: const-fn accessor returning the length of the
3785    /// declared site partition (or 0 if unset).
3786    #[inline]
3787    #[must_use]
3788    pub const fn site_partition_len(&self) -> usize {
3789        match self.site_partition {
3790            Some(p) => p.len(),
3791            None => 0,
3792        }
3793    }
3794
3795    /// v0.2.2 Phase A: const-fn accessor returning the declared site-partition
3796    /// slice, or an empty slice if unset. Used by `validate_parallel_const`
3797    /// to propagate the partition into the widened `ParallelDeclaration<'a>`.
3798    #[inline]
3799    #[must_use]
3800    pub const fn site_partition_slice_const(&self) -> &'a [u32] {
3801        match self.site_partition {
3802            Some(p) => p,
3803            None => &[],
3804        }
3805    }
3806
3807    /// v0.2.2 Phase A: const-fn accessor returning the declared disjointness-witness
3808    /// IRI string, or an empty string if unset.
3809    #[inline]
3810    #[must_use]
3811    pub const fn disjointness_witness_const(&self) -> &'a str {
3812        match self.disjointness_witness {
3813            Some(s) => s,
3814            None => "",
3815        }
3816    }
3817}
3818
3819impl<'a, const INLINE_BYTES: usize> StreamDeclarationBuilder<'a, INLINE_BYTES> {
3820    /// v0.2.2 canonical: productivity bound is 1 if a `productivityWitness`
3821    /// IRI is declared (the stream attests termination via a `proof:Proof`
3822    /// individual), 0 otherwise. The witness's IRI points to the termination
3823    /// proof; downstream resolvers dereference it for detailed bound
3824    /// information. This two-level split (presence flag here, IRI dereference
3825    /// elsewhere) is the canonical foundation-level shape.
3826    #[inline]
3827    #[must_use]
3828    pub const fn productivity_bound_const(&self) -> u64 {
3829        match self.productivity_witness {
3830            Some(_) => 1,
3831            None => 0,
3832        }
3833    }
3834
3835    /// v0.2.2 Phase A: const-fn accessor returning the declared seed term slice,
3836    /// or an empty slice if unset.
3837    #[inline]
3838    #[must_use]
3839    pub const fn seed_slice_const(&self) -> &'a [Term<'a, INLINE_BYTES>] {
3840        match self.seed {
3841            Some(t) => t,
3842            None => &[],
3843        }
3844    }
3845
3846    /// v0.2.2 Phase A: const-fn accessor returning the declared step term slice,
3847    /// or an empty slice if unset.
3848    #[inline]
3849    #[must_use]
3850    pub const fn step_slice_const(&self) -> &'a [Term<'a, INLINE_BYTES>] {
3851        match self.step {
3852            Some(t) => t,
3853            None => &[],
3854        }
3855    }
3856
3857    /// v0.2.2 Phase A: const-fn accessor returning the declared productivity-witness
3858    /// IRI, or an empty string if unset.
3859    #[inline]
3860    #[must_use]
3861    pub const fn productivity_witness_const(&self) -> &'a str {
3862        match self.productivity_witness {
3863            Some(s) => s,
3864            None => "",
3865        }
3866    }
3867}
3868
3869/// Builder for declaring a new Witt level beyond W32.
3870/// Validates against `WittLevelShape`.
3871#[derive(Debug, Clone)]
3872pub struct WittLevelDeclarationBuilder {
3873    /// The declared bit width.
3874    bit_width: Option<u32>,
3875    /// The declared cycle size.
3876    cycle_size: Option<u128>,
3877    /// The predecessor level.
3878    predecessor: Option<WittLevel>,
3879}
3880
3881/// Validated Witt level declaration.
3882#[derive(Debug, Clone, PartialEq, Eq)]
3883pub struct WittLevelDeclaration {
3884    /// The declared bit width.
3885    pub bit_width: u32,
3886    /// The predecessor level.
3887    pub predecessor: WittLevel,
3888}
3889
3890impl WittLevelDeclarationBuilder {
3891    /// Creates a new empty builder.
3892    #[must_use]
3893    pub const fn new() -> Self {
3894        Self {
3895            bit_width: None,
3896            cycle_size: None,
3897            predecessor: None,
3898        }
3899    }
3900
3901    /// Set the declared bit width.
3902    #[must_use]
3903    pub const fn bit_width(mut self, w: u32) -> Self {
3904        self.bit_width = Some(w);
3905        self
3906    }
3907
3908    /// Set the declared cycle size.
3909    #[must_use]
3910    pub const fn cycle_size(mut self, s: u128) -> Self {
3911        self.cycle_size = Some(s);
3912        self
3913    }
3914
3915    /// Set the predecessor Witt level.
3916    #[must_use]
3917    pub const fn predecessor(mut self, level: WittLevel) -> Self {
3918        self.predecessor = Some(level);
3919        self
3920    }
3921
3922    /// Validate against `WittLevelShape`.
3923    /// # Errors
3924    /// Returns `ShapeViolation` if any required field is missing.
3925    pub fn validate(self) -> Result<Validated<WittLevelDeclaration>, ShapeViolation> {
3926        let bw = match self.bit_width {
3927            Some(w) => w,
3928            None => {
3929                return Err(ShapeViolation {
3930                    shape_iri: "https://uor.foundation/conformance/WittLevelShape",
3931                    constraint_iri: "https://uor.foundation/conformance/WittLevelShape",
3932                    property_iri: "https://uor.foundation/conformance/declaredBitWidth",
3933                    expected_range: "http://www.w3.org/2001/XMLSchema#positiveInteger",
3934                    min_count: 1,
3935                    max_count: 1,
3936                    kind: ViolationKind::Missing,
3937                })
3938            }
3939        };
3940        let pred = match self.predecessor {
3941            Some(p) => p,
3942            None => {
3943                return Err(ShapeViolation {
3944                    shape_iri: "https://uor.foundation/conformance/WittLevelShape",
3945                    constraint_iri: "https://uor.foundation/conformance/WittLevelShape",
3946                    property_iri: "https://uor.foundation/conformance/predecessorLevel",
3947                    expected_range: "https://uor.foundation/schema/WittLevel",
3948                    min_count: 1,
3949                    max_count: 1,
3950                    kind: ViolationKind::Missing,
3951                })
3952            }
3953        };
3954        Ok(Validated::new(WittLevelDeclaration {
3955            bit_width: bw,
3956            predecessor: pred,
3957        }))
3958    }
3959
3960    /// Phase C.1: const-fn companion for `WittLevelDeclarationBuilder::validate`.
3961    /// # Errors
3962    /// Returns `ShapeViolation` if any required field is missing.
3963    pub const fn validate_const(
3964        &self,
3965    ) -> Result<Validated<WittLevelDeclaration, CompileTime>, ShapeViolation> {
3966        let bw = match self.bit_width {
3967            Some(w) => w,
3968            None => {
3969                return Err(ShapeViolation {
3970                    shape_iri: "https://uor.foundation/conformance/WittLevelShape",
3971                    constraint_iri: "https://uor.foundation/conformance/WittLevelShape",
3972                    property_iri: "https://uor.foundation/conformance/declaredBitWidth",
3973                    expected_range: "http://www.w3.org/2001/XMLSchema#positiveInteger",
3974                    min_count: 1,
3975                    max_count: 1,
3976                    kind: ViolationKind::Missing,
3977                })
3978            }
3979        };
3980        let pred = match self.predecessor {
3981            Some(p) => p,
3982            None => {
3983                return Err(ShapeViolation {
3984                    shape_iri: "https://uor.foundation/conformance/WittLevelShape",
3985                    constraint_iri: "https://uor.foundation/conformance/WittLevelShape",
3986                    property_iri: "https://uor.foundation/conformance/predecessorLevel",
3987                    expected_range: "https://uor.foundation/schema/WittLevel",
3988                    min_count: 1,
3989                    max_count: 1,
3990                    kind: ViolationKind::Missing,
3991                })
3992            }
3993        };
3994        Ok(Validated::new(WittLevelDeclaration {
3995            bit_width: bw,
3996            predecessor: pred,
3997        }))
3998    }
3999}
4000
4001impl Default for WittLevelDeclarationBuilder {
4002    fn default() -> Self {
4003        Self::new()
4004    }
4005}
4006
4007/// Boundary session state tracker for the two-phase minting boundary.
4008/// Records crossing count and idempotency flag. Private fields
4009/// prevent external construction.
4010#[derive(Debug, Clone, PartialEq, Eq)]
4011pub struct BoundarySession {
4012    /// Total boundary crossings in this session.
4013    crossing_count: u32,
4014    /// Whether the boundary effect is idempotent.
4015    is_idempotent: bool,
4016}
4017
4018impl BoundarySession {
4019    /// Creates a new boundary session. Only callable within the crate.
4020    #[inline]
4021    #[allow(dead_code)]
4022    pub(crate) const fn new(is_idempotent: bool) -> Self {
4023        Self {
4024            crossing_count: 0,
4025            is_idempotent,
4026        }
4027    }
4028
4029    /// Returns the total boundary crossings.
4030    #[inline]
4031    #[must_use]
4032    pub const fn crossing_count(&self) -> u32 {
4033        self.crossing_count
4034    }
4035
4036    /// Returns whether the boundary effect is idempotent.
4037    #[inline]
4038    #[must_use]
4039    pub const fn is_idempotent(&self) -> bool {
4040        self.is_idempotent
4041    }
4042}
4043
4044/// Validate a scalar grounding intermediate against a `GroundingShape`
4045/// and mint it into a `Datum`. Only callable within `uor-foundation`.
4046/// # Errors
4047/// Returns `ShapeViolation` if the coordinate fails validation.
4048#[allow(dead_code)]
4049pub(crate) fn validate_and_mint_coord(
4050    grounded: GroundedCoord,
4051    shape: &Validated<GroundingDeclaration>,
4052    session: &mut BoundarySession,
4053) -> Result<Datum, ShapeViolation> {
4054    // The Validated<GroundingDeclaration> proves the shape was already
4055    // validated at builder time. The coordinate's level is guaranteed
4056    // correct by the closed GroundedCoordInner enum — the type system
4057    // enforces that only supported levels can be constructed.
4058    let _ = shape; // shape validation passed at builder time
4059    session.crossing_count += 1;
4060    let inner = match grounded.inner {
4061        GroundedCoordInner::W8(b) => DatumInner::W8(b),
4062        GroundedCoordInner::W16(b) => DatumInner::W16(b),
4063        GroundedCoordInner::W24(b) => DatumInner::W24(b),
4064        GroundedCoordInner::W32(b) => DatumInner::W32(b),
4065        GroundedCoordInner::W40(b) => DatumInner::W40(b),
4066        GroundedCoordInner::W48(b) => DatumInner::W48(b),
4067        GroundedCoordInner::W56(b) => DatumInner::W56(b),
4068        GroundedCoordInner::W64(b) => DatumInner::W64(b),
4069        GroundedCoordInner::W72(b) => DatumInner::W72(b),
4070        GroundedCoordInner::W80(b) => DatumInner::W80(b),
4071        GroundedCoordInner::W88(b) => DatumInner::W88(b),
4072        GroundedCoordInner::W96(b) => DatumInner::W96(b),
4073        GroundedCoordInner::W104(b) => DatumInner::W104(b),
4074        GroundedCoordInner::W112(b) => DatumInner::W112(b),
4075        GroundedCoordInner::W120(b) => DatumInner::W120(b),
4076        GroundedCoordInner::W128(b) => DatumInner::W128(b),
4077    };
4078    Ok(Datum { inner })
4079}
4080
4081/// Validate a tuple grounding intermediate and mint into a `Datum`.
4082/// Only callable within `uor-foundation`.
4083/// Mints the first coordinate of the tuple as the representative `Datum`.
4084/// Composite multi-coordinate `Datum` construction depends on the target
4085/// type's site decomposition, which is resolved during reduction evaluation.
4086/// # Errors
4087/// Returns `ShapeViolation` if the tuple is empty or fails validation.
4088#[allow(dead_code)]
4089pub(crate) fn validate_and_mint_tuple<const N: usize>(
4090    grounded: GroundedTuple<N>,
4091    shape: &Validated<GroundingDeclaration>,
4092    session: &mut BoundarySession,
4093) -> Result<Datum, ShapeViolation> {
4094    if N == 0 {
4095        return Err(ShapeViolation {
4096            shape_iri: shape.inner().shape_iri,
4097            constraint_iri: shape.inner().shape_iri,
4098            property_iri: "https://uor.foundation/conformance/groundingSourceType",
4099            expected_range: "https://uor.foundation/type/TypeDefinition",
4100            min_count: 1,
4101            max_count: 0,
4102            kind: ViolationKind::CardinalityViolation,
4103        });
4104    }
4105    // Mint the first coordinate as the representative Datum.
4106    // The full tuple is decomposed during reduction evaluation,
4107    // where each coordinate maps to a site in the constrained type.
4108    validate_and_mint_coord(grounded.coords[0].clone(), shape, session)
4109}
4110
4111/// Wiki ADR-016 mint primitive: cross-crate construction surface for `Datum`.
4112/// Takes host bytes that have already passed the author's `Grounding` impl and
4113/// mints them into a sealed `Datum` at the supplied Witt level. The bytes are
4114/// decoded according to the level's byte width.
4115/// # Errors
4116/// Returns [`ShapeViolation`] if `bytes.len()` doesn't match the level's byte width
4117/// or if the level is unsupported.
4118pub fn mint_datum(level: crate::WittLevel, bytes: &[u8]) -> Result<Datum, ShapeViolation> {
4119    let expected_bytes = (level.witt_length() / 8) as usize;
4120    if bytes.len() != expected_bytes {
4121        return Err(ShapeViolation {
4122            shape_iri: "https://uor.foundation/u/Datum",
4123            constraint_iri: "https://uor.foundation/u/DatumByteWidth",
4124            property_iri: "https://uor.foundation/u/datumBytes",
4125            expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
4126            min_count: expected_bytes as u32,
4127            max_count: expected_bytes as u32,
4128            kind: crate::ViolationKind::CardinalityViolation,
4129        });
4130    }
4131    let inner = match level.witt_length() {
4132        8 => {
4133            let mut buf = [0u8; 1];
4134            let mut i = 0;
4135            while i < 1 {
4136                buf[i] = bytes[i];
4137                i += 1;
4138            }
4139            DatumInner::W8(buf)
4140        }
4141        16 => {
4142            let mut buf = [0u8; 2];
4143            let mut i = 0;
4144            while i < 2 {
4145                buf[i] = bytes[i];
4146                i += 1;
4147            }
4148            DatumInner::W16(buf)
4149        }
4150        24 => {
4151            let mut buf = [0u8; 3];
4152            let mut i = 0;
4153            while i < 3 {
4154                buf[i] = bytes[i];
4155                i += 1;
4156            }
4157            DatumInner::W24(buf)
4158        }
4159        32 => {
4160            let mut buf = [0u8; 4];
4161            let mut i = 0;
4162            while i < 4 {
4163                buf[i] = bytes[i];
4164                i += 1;
4165            }
4166            DatumInner::W32(buf)
4167        }
4168        40 => {
4169            let mut buf = [0u8; 5];
4170            let mut i = 0;
4171            while i < 5 {
4172                buf[i] = bytes[i];
4173                i += 1;
4174            }
4175            DatumInner::W40(buf)
4176        }
4177        48 => {
4178            let mut buf = [0u8; 6];
4179            let mut i = 0;
4180            while i < 6 {
4181                buf[i] = bytes[i];
4182                i += 1;
4183            }
4184            DatumInner::W48(buf)
4185        }
4186        56 => {
4187            let mut buf = [0u8; 7];
4188            let mut i = 0;
4189            while i < 7 {
4190                buf[i] = bytes[i];
4191                i += 1;
4192            }
4193            DatumInner::W56(buf)
4194        }
4195        64 => {
4196            let mut buf = [0u8; 8];
4197            let mut i = 0;
4198            while i < 8 {
4199                buf[i] = bytes[i];
4200                i += 1;
4201            }
4202            DatumInner::W64(buf)
4203        }
4204        72 => {
4205            let mut buf = [0u8; 9];
4206            let mut i = 0;
4207            while i < 9 {
4208                buf[i] = bytes[i];
4209                i += 1;
4210            }
4211            DatumInner::W72(buf)
4212        }
4213        80 => {
4214            let mut buf = [0u8; 10];
4215            let mut i = 0;
4216            while i < 10 {
4217                buf[i] = bytes[i];
4218                i += 1;
4219            }
4220            DatumInner::W80(buf)
4221        }
4222        88 => {
4223            let mut buf = [0u8; 11];
4224            let mut i = 0;
4225            while i < 11 {
4226                buf[i] = bytes[i];
4227                i += 1;
4228            }
4229            DatumInner::W88(buf)
4230        }
4231        96 => {
4232            let mut buf = [0u8; 12];
4233            let mut i = 0;
4234            while i < 12 {
4235                buf[i] = bytes[i];
4236                i += 1;
4237            }
4238            DatumInner::W96(buf)
4239        }
4240        104 => {
4241            let mut buf = [0u8; 13];
4242            let mut i = 0;
4243            while i < 13 {
4244                buf[i] = bytes[i];
4245                i += 1;
4246            }
4247            DatumInner::W104(buf)
4248        }
4249        112 => {
4250            let mut buf = [0u8; 14];
4251            let mut i = 0;
4252            while i < 14 {
4253                buf[i] = bytes[i];
4254                i += 1;
4255            }
4256            DatumInner::W112(buf)
4257        }
4258        120 => {
4259            let mut buf = [0u8; 15];
4260            let mut i = 0;
4261            while i < 15 {
4262                buf[i] = bytes[i];
4263                i += 1;
4264            }
4265            DatumInner::W120(buf)
4266        }
4267        128 => {
4268            let mut buf = [0u8; 16];
4269            let mut i = 0;
4270            while i < 16 {
4271                buf[i] = bytes[i];
4272                i += 1;
4273            }
4274            DatumInner::W128(buf)
4275        }
4276        _ => {
4277            return Err(ShapeViolation {
4278                shape_iri: "https://uor.foundation/u/Datum",
4279                constraint_iri: "https://uor.foundation/u/DatumLevel",
4280                property_iri: "https://uor.foundation/u/datumLevel",
4281                expected_range: "https://uor.foundation/schema/WittLevel",
4282                min_count: 1,
4283                max_count: 1,
4284                kind: crate::ViolationKind::ValueCheck,
4285            })
4286        }
4287    };
4288    Ok(Datum { inner })
4289}
4290
4291/// Wiki ADR-016 mint primitive: cross-crate construction surface for `Triad<L>`.
4292/// Takes three coordinate values that satisfy the Triad shape constraint and
4293/// mints them into a sealed `Triad<L>` at the level marker `L`.
4294#[must_use]
4295pub const fn mint_triad<L>(stratum: u64, spectrum: u64, address: u64) -> Triad<L> {
4296    Triad::new(stratum, spectrum, address)
4297}
4298
4299/// Wiki ADR-016 mint primitive: cross-crate construction surface for `Derivation`.
4300/// Takes the precursor's step count + Witt level + content fingerprint and mints
4301/// a sealed `Derivation` carrying the typed transition witness.
4302#[must_use]
4303pub const fn mint_derivation(
4304    step_count: u32,
4305    witt_level_bits: u16,
4306    content_fingerprint: ContentFingerprint,
4307) -> Derivation {
4308    Derivation::new(step_count, witt_level_bits, content_fingerprint)
4309}
4310
4311/// Wiki ADR-016 mint primitive: cross-crate construction surface for `FreeRank`.
4312/// Takes a natural-number rank witness (total site capacity at the Witt level plus
4313/// the number of currently pinned sites) and mints it into a sealed `FreeRank`.
4314#[must_use]
4315pub const fn mint_freerank(total: u32, pinned: u32) -> FreeRank {
4316    FreeRank::new(total, pinned)
4317}
4318
4319/// Evaluate a binary ring operation at compile time.
4320/// One helper is emitted per `schema:WittLevel` individual. The `uor!`
4321/// proc macro delegates to these helpers; it never performs ring
4322/// arithmetic itself.
4323/// # Examples
4324/// ```rust
4325/// use uor_foundation::enforcement::{const_ring_eval_w8, const_ring_eval_unary_w8};
4326/// use uor_foundation::PrimitiveOp;
4327///
4328/// // Ring arithmetic in Z/256Z: all operations wrap modulo 256.
4329///
4330/// // Addition wraps: 200 + 100 = 300 -> 300 - 256 = 44
4331/// assert_eq!(const_ring_eval_w8(PrimitiveOp::Add, 200, 100), 44);
4332///
4333/// // Multiplication: 3 * 5 = 15 (no wrap needed)
4334/// assert_eq!(const_ring_eval_w8(PrimitiveOp::Mul, 3, 5), 15);
4335///
4336/// // XOR: bitwise exclusive-or
4337/// assert_eq!(const_ring_eval_w8(PrimitiveOp::Xor, 0b1010, 0b1100), 0b0110);
4338///
4339/// // Negation: neg(x) = 256 - x (additive inverse in Z/256Z)
4340/// assert_eq!(const_ring_eval_unary_w8(PrimitiveOp::Neg, 1), 255);
4341///
4342/// // The critical identity: neg(bnot(x)) = succ(x) for all x
4343/// let x = 42u8;
4344/// let lhs = const_ring_eval_unary_w8(PrimitiveOp::Neg,
4345///     const_ring_eval_unary_w8(PrimitiveOp::Bnot, x));
4346/// let rhs = const_ring_eval_unary_w8(PrimitiveOp::Succ, x);
4347/// assert_eq!(lhs, rhs);
4348/// ```
4349#[inline]
4350#[must_use]
4351#[allow(clippy::manual_checked_ops)]
4352pub const fn const_ring_eval_w8(op: PrimitiveOp, a: u8, b: u8) -> u8 {
4353    match op {
4354        PrimitiveOp::Add => a.wrapping_add(b),
4355        PrimitiveOp::Sub => a.wrapping_sub(b),
4356        PrimitiveOp::Mul => a.wrapping_mul(b),
4357        PrimitiveOp::Xor => a ^ b,
4358        PrimitiveOp::And => a & b,
4359        PrimitiveOp::Or => a | b,
4360        PrimitiveOp::Le => (a <= b) as u8,
4361        PrimitiveOp::Lt => (a < b) as u8,
4362        PrimitiveOp::Ge => (a >= b) as u8,
4363        PrimitiveOp::Gt => (a > b) as u8,
4364        PrimitiveOp::Concat => 0,
4365        PrimitiveOp::Div => {
4366            if b == 0 {
4367                0
4368            } else {
4369                a / b
4370            }
4371        }
4372        PrimitiveOp::Mod => {
4373            if b == 0 {
4374                0
4375            } else {
4376                a % b
4377            }
4378        }
4379        PrimitiveOp::Pow => const_pow_w8(a, b),
4380        _ => 0,
4381    }
4382}
4383
4384#[inline]
4385#[must_use]
4386pub const fn const_pow_w8(base: u8, exp: u8) -> u8 {
4387    let mut result: u8 = 1;
4388    let mut b: u8 = base;
4389    let mut e: u8 = exp;
4390    while e > 0 {
4391        if (e & 1) == 1 {
4392            result = result.wrapping_mul(b);
4393        }
4394        b = b.wrapping_mul(b);
4395        e >>= 1;
4396    }
4397    result
4398}
4399
4400#[inline]
4401#[must_use]
4402pub const fn const_ring_eval_unary_w8(op: PrimitiveOp, a: u8) -> u8 {
4403    match op {
4404        PrimitiveOp::Neg => 0u8.wrapping_sub(a),
4405        PrimitiveOp::Bnot => !a,
4406        PrimitiveOp::Succ => a.wrapping_add(1),
4407        PrimitiveOp::Pred => a.wrapping_sub(1),
4408        _ => 0,
4409    }
4410}
4411
4412#[inline]
4413#[must_use]
4414#[allow(clippy::manual_checked_ops)]
4415pub const fn const_ring_eval_w16(op: PrimitiveOp, a: u16, b: u16) -> u16 {
4416    match op {
4417        PrimitiveOp::Add => a.wrapping_add(b),
4418        PrimitiveOp::Sub => a.wrapping_sub(b),
4419        PrimitiveOp::Mul => a.wrapping_mul(b),
4420        PrimitiveOp::Xor => a ^ b,
4421        PrimitiveOp::And => a & b,
4422        PrimitiveOp::Or => a | b,
4423        PrimitiveOp::Le => (a <= b) as u16,
4424        PrimitiveOp::Lt => (a < b) as u16,
4425        PrimitiveOp::Ge => (a >= b) as u16,
4426        PrimitiveOp::Gt => (a > b) as u16,
4427        PrimitiveOp::Concat => 0,
4428        PrimitiveOp::Div => {
4429            if b == 0 {
4430                0
4431            } else {
4432                a / b
4433            }
4434        }
4435        PrimitiveOp::Mod => {
4436            if b == 0 {
4437                0
4438            } else {
4439                a % b
4440            }
4441        }
4442        PrimitiveOp::Pow => const_pow_w16(a, b),
4443        _ => 0,
4444    }
4445}
4446
4447#[inline]
4448#[must_use]
4449pub const fn const_pow_w16(base: u16, exp: u16) -> u16 {
4450    let mut result: u16 = 1;
4451    let mut b: u16 = base;
4452    let mut e: u16 = exp;
4453    while e > 0 {
4454        if (e & 1) == 1 {
4455            result = result.wrapping_mul(b);
4456        }
4457        b = b.wrapping_mul(b);
4458        e >>= 1;
4459    }
4460    result
4461}
4462
4463#[inline]
4464#[must_use]
4465pub const fn const_ring_eval_unary_w16(op: PrimitiveOp, a: u16) -> u16 {
4466    match op {
4467        PrimitiveOp::Neg => 0u16.wrapping_sub(a),
4468        PrimitiveOp::Bnot => !a,
4469        PrimitiveOp::Succ => a.wrapping_add(1),
4470        PrimitiveOp::Pred => a.wrapping_sub(1),
4471        _ => 0,
4472    }
4473}
4474
4475#[inline]
4476#[must_use]
4477#[allow(clippy::manual_checked_ops)]
4478pub const fn const_ring_eval_w24(op: PrimitiveOp, a: u32, b: u32) -> u32 {
4479    const MASK: u32 = (u64::MAX >> (64 - 24)) as u32;
4480    match op {
4481        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4482        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4483        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4484        PrimitiveOp::Xor => (a ^ b) & MASK,
4485        PrimitiveOp::And => (a & b) & MASK,
4486        PrimitiveOp::Or => (a | b) & MASK,
4487        PrimitiveOp::Le => (a <= b) as u32,
4488        PrimitiveOp::Lt => (a < b) as u32,
4489        PrimitiveOp::Ge => (a >= b) as u32,
4490        PrimitiveOp::Gt => (a > b) as u32,
4491        PrimitiveOp::Concat => 0,
4492        PrimitiveOp::Div => {
4493            if b == 0 {
4494                0
4495            } else {
4496                (a / b) & MASK
4497            }
4498        }
4499        PrimitiveOp::Mod => {
4500            if b == 0 {
4501                0
4502            } else {
4503                (a % b) & MASK
4504            }
4505        }
4506        PrimitiveOp::Pow => (const_pow_w24(a, b)) & MASK,
4507        _ => 0,
4508    }
4509}
4510
4511#[inline]
4512#[must_use]
4513pub const fn const_pow_w24(base: u32, exp: u32) -> u32 {
4514    const MASK: u32 = (u64::MAX >> (64 - 24)) as u32;
4515    let mut result: u32 = 1;
4516    let mut b: u32 = (base) & MASK;
4517    let mut e: u32 = exp;
4518    while e > 0 {
4519        if (e & 1) == 1 {
4520            result = (result.wrapping_mul(b)) & MASK;
4521        }
4522        b = (b.wrapping_mul(b)) & MASK;
4523        e >>= 1;
4524    }
4525    result
4526}
4527
4528#[inline]
4529#[must_use]
4530pub const fn const_ring_eval_unary_w24(op: PrimitiveOp, a: u32) -> u32 {
4531    const MASK: u32 = (u64::MAX >> (64 - 24)) as u32;
4532    match op {
4533        PrimitiveOp::Neg => (0u32.wrapping_sub(a)) & MASK,
4534        PrimitiveOp::Bnot => (!a) & MASK,
4535        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4536        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4537        _ => 0,
4538    }
4539}
4540
4541#[inline]
4542#[must_use]
4543#[allow(clippy::manual_checked_ops)]
4544pub const fn const_ring_eval_w32(op: PrimitiveOp, a: u32, b: u32) -> u32 {
4545    match op {
4546        PrimitiveOp::Add => a.wrapping_add(b),
4547        PrimitiveOp::Sub => a.wrapping_sub(b),
4548        PrimitiveOp::Mul => a.wrapping_mul(b),
4549        PrimitiveOp::Xor => a ^ b,
4550        PrimitiveOp::And => a & b,
4551        PrimitiveOp::Or => a | b,
4552        PrimitiveOp::Le => (a <= b) as u32,
4553        PrimitiveOp::Lt => (a < b) as u32,
4554        PrimitiveOp::Ge => (a >= b) as u32,
4555        PrimitiveOp::Gt => (a > b) as u32,
4556        PrimitiveOp::Concat => 0,
4557        PrimitiveOp::Div => {
4558            if b == 0 {
4559                0
4560            } else {
4561                a / b
4562            }
4563        }
4564        PrimitiveOp::Mod => {
4565            if b == 0 {
4566                0
4567            } else {
4568                a % b
4569            }
4570        }
4571        PrimitiveOp::Pow => const_pow_w32(a, b),
4572        _ => 0,
4573    }
4574}
4575
4576#[inline]
4577#[must_use]
4578pub const fn const_pow_w32(base: u32, exp: u32) -> u32 {
4579    let mut result: u32 = 1;
4580    let mut b: u32 = base;
4581    let mut e: u32 = exp;
4582    while e > 0 {
4583        if (e & 1) == 1 {
4584            result = result.wrapping_mul(b);
4585        }
4586        b = b.wrapping_mul(b);
4587        e >>= 1;
4588    }
4589    result
4590}
4591
4592#[inline]
4593#[must_use]
4594pub const fn const_ring_eval_unary_w32(op: PrimitiveOp, a: u32) -> u32 {
4595    match op {
4596        PrimitiveOp::Neg => 0u32.wrapping_sub(a),
4597        PrimitiveOp::Bnot => !a,
4598        PrimitiveOp::Succ => a.wrapping_add(1),
4599        PrimitiveOp::Pred => a.wrapping_sub(1),
4600        _ => 0,
4601    }
4602}
4603
4604#[inline]
4605#[must_use]
4606#[allow(clippy::manual_checked_ops)]
4607pub const fn const_ring_eval_w40(op: PrimitiveOp, a: u64, b: u64) -> u64 {
4608    const MASK: u64 = u64::MAX >> (64 - 40);
4609    match op {
4610        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4611        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4612        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4613        PrimitiveOp::Xor => (a ^ b) & MASK,
4614        PrimitiveOp::And => (a & b) & MASK,
4615        PrimitiveOp::Or => (a | b) & MASK,
4616        PrimitiveOp::Le => (a <= b) as u64,
4617        PrimitiveOp::Lt => (a < b) as u64,
4618        PrimitiveOp::Ge => (a >= b) as u64,
4619        PrimitiveOp::Gt => (a > b) as u64,
4620        PrimitiveOp::Concat => 0,
4621        PrimitiveOp::Div => {
4622            if b == 0 {
4623                0
4624            } else {
4625                (a / b) & MASK
4626            }
4627        }
4628        PrimitiveOp::Mod => {
4629            if b == 0 {
4630                0
4631            } else {
4632                (a % b) & MASK
4633            }
4634        }
4635        PrimitiveOp::Pow => (const_pow_w40(a, b)) & MASK,
4636        _ => 0,
4637    }
4638}
4639
4640#[inline]
4641#[must_use]
4642pub const fn const_pow_w40(base: u64, exp: u64) -> u64 {
4643    const MASK: u64 = u64::MAX >> (64 - 40);
4644    let mut result: u64 = 1;
4645    let mut b: u64 = (base) & MASK;
4646    let mut e: u64 = exp;
4647    while e > 0 {
4648        if (e & 1) == 1 {
4649            result = (result.wrapping_mul(b)) & MASK;
4650        }
4651        b = (b.wrapping_mul(b)) & MASK;
4652        e >>= 1;
4653    }
4654    result
4655}
4656
4657#[inline]
4658#[must_use]
4659pub const fn const_ring_eval_unary_w40(op: PrimitiveOp, a: u64) -> u64 {
4660    const MASK: u64 = u64::MAX >> (64 - 40);
4661    match op {
4662        PrimitiveOp::Neg => (0u64.wrapping_sub(a)) & MASK,
4663        PrimitiveOp::Bnot => (!a) & MASK,
4664        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4665        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4666        _ => 0,
4667    }
4668}
4669
4670#[inline]
4671#[must_use]
4672#[allow(clippy::manual_checked_ops)]
4673pub const fn const_ring_eval_w48(op: PrimitiveOp, a: u64, b: u64) -> u64 {
4674    const MASK: u64 = u64::MAX >> (64 - 48);
4675    match op {
4676        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4677        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4678        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4679        PrimitiveOp::Xor => (a ^ b) & MASK,
4680        PrimitiveOp::And => (a & b) & MASK,
4681        PrimitiveOp::Or => (a | b) & MASK,
4682        PrimitiveOp::Le => (a <= b) as u64,
4683        PrimitiveOp::Lt => (a < b) as u64,
4684        PrimitiveOp::Ge => (a >= b) as u64,
4685        PrimitiveOp::Gt => (a > b) as u64,
4686        PrimitiveOp::Concat => 0,
4687        PrimitiveOp::Div => {
4688            if b == 0 {
4689                0
4690            } else {
4691                (a / b) & MASK
4692            }
4693        }
4694        PrimitiveOp::Mod => {
4695            if b == 0 {
4696                0
4697            } else {
4698                (a % b) & MASK
4699            }
4700        }
4701        PrimitiveOp::Pow => (const_pow_w48(a, b)) & MASK,
4702        _ => 0,
4703    }
4704}
4705
4706#[inline]
4707#[must_use]
4708pub const fn const_pow_w48(base: u64, exp: u64) -> u64 {
4709    const MASK: u64 = u64::MAX >> (64 - 48);
4710    let mut result: u64 = 1;
4711    let mut b: u64 = (base) & MASK;
4712    let mut e: u64 = exp;
4713    while e > 0 {
4714        if (e & 1) == 1 {
4715            result = (result.wrapping_mul(b)) & MASK;
4716        }
4717        b = (b.wrapping_mul(b)) & MASK;
4718        e >>= 1;
4719    }
4720    result
4721}
4722
4723#[inline]
4724#[must_use]
4725pub const fn const_ring_eval_unary_w48(op: PrimitiveOp, a: u64) -> u64 {
4726    const MASK: u64 = u64::MAX >> (64 - 48);
4727    match op {
4728        PrimitiveOp::Neg => (0u64.wrapping_sub(a)) & MASK,
4729        PrimitiveOp::Bnot => (!a) & MASK,
4730        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4731        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4732        _ => 0,
4733    }
4734}
4735
4736#[inline]
4737#[must_use]
4738#[allow(clippy::manual_checked_ops)]
4739pub const fn const_ring_eval_w56(op: PrimitiveOp, a: u64, b: u64) -> u64 {
4740    const MASK: u64 = u64::MAX >> (64 - 56);
4741    match op {
4742        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4743        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4744        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4745        PrimitiveOp::Xor => (a ^ b) & MASK,
4746        PrimitiveOp::And => (a & b) & MASK,
4747        PrimitiveOp::Or => (a | b) & MASK,
4748        PrimitiveOp::Le => (a <= b) as u64,
4749        PrimitiveOp::Lt => (a < b) as u64,
4750        PrimitiveOp::Ge => (a >= b) as u64,
4751        PrimitiveOp::Gt => (a > b) as u64,
4752        PrimitiveOp::Concat => 0,
4753        PrimitiveOp::Div => {
4754            if b == 0 {
4755                0
4756            } else {
4757                (a / b) & MASK
4758            }
4759        }
4760        PrimitiveOp::Mod => {
4761            if b == 0 {
4762                0
4763            } else {
4764                (a % b) & MASK
4765            }
4766        }
4767        PrimitiveOp::Pow => (const_pow_w56(a, b)) & MASK,
4768        _ => 0,
4769    }
4770}
4771
4772#[inline]
4773#[must_use]
4774pub const fn const_pow_w56(base: u64, exp: u64) -> u64 {
4775    const MASK: u64 = u64::MAX >> (64 - 56);
4776    let mut result: u64 = 1;
4777    let mut b: u64 = (base) & MASK;
4778    let mut e: u64 = exp;
4779    while e > 0 {
4780        if (e & 1) == 1 {
4781            result = (result.wrapping_mul(b)) & MASK;
4782        }
4783        b = (b.wrapping_mul(b)) & MASK;
4784        e >>= 1;
4785    }
4786    result
4787}
4788
4789#[inline]
4790#[must_use]
4791pub const fn const_ring_eval_unary_w56(op: PrimitiveOp, a: u64) -> u64 {
4792    const MASK: u64 = u64::MAX >> (64 - 56);
4793    match op {
4794        PrimitiveOp::Neg => (0u64.wrapping_sub(a)) & MASK,
4795        PrimitiveOp::Bnot => (!a) & MASK,
4796        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4797        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4798        _ => 0,
4799    }
4800}
4801
4802#[inline]
4803#[must_use]
4804#[allow(clippy::manual_checked_ops)]
4805pub const fn const_ring_eval_w64(op: PrimitiveOp, a: u64, b: u64) -> u64 {
4806    match op {
4807        PrimitiveOp::Add => a.wrapping_add(b),
4808        PrimitiveOp::Sub => a.wrapping_sub(b),
4809        PrimitiveOp::Mul => a.wrapping_mul(b),
4810        PrimitiveOp::Xor => a ^ b,
4811        PrimitiveOp::And => a & b,
4812        PrimitiveOp::Or => a | b,
4813        PrimitiveOp::Le => (a <= b) as u64,
4814        PrimitiveOp::Lt => (a < b) as u64,
4815        PrimitiveOp::Ge => (a >= b) as u64,
4816        PrimitiveOp::Gt => (a > b) as u64,
4817        PrimitiveOp::Concat => 0,
4818        PrimitiveOp::Div => {
4819            if b == 0 {
4820                0
4821            } else {
4822                a / b
4823            }
4824        }
4825        PrimitiveOp::Mod => {
4826            if b == 0 {
4827                0
4828            } else {
4829                a % b
4830            }
4831        }
4832        PrimitiveOp::Pow => const_pow_w64(a, b),
4833        _ => 0,
4834    }
4835}
4836
4837#[inline]
4838#[must_use]
4839pub const fn const_pow_w64(base: u64, exp: u64) -> u64 {
4840    let mut result: u64 = 1;
4841    let mut b: u64 = base;
4842    let mut e: u64 = exp;
4843    while e > 0 {
4844        if (e & 1) == 1 {
4845            result = result.wrapping_mul(b);
4846        }
4847        b = b.wrapping_mul(b);
4848        e >>= 1;
4849    }
4850    result
4851}
4852
4853#[inline]
4854#[must_use]
4855pub const fn const_ring_eval_unary_w64(op: PrimitiveOp, a: u64) -> u64 {
4856    match op {
4857        PrimitiveOp::Neg => 0u64.wrapping_sub(a),
4858        PrimitiveOp::Bnot => !a,
4859        PrimitiveOp::Succ => a.wrapping_add(1),
4860        PrimitiveOp::Pred => a.wrapping_sub(1),
4861        _ => 0,
4862    }
4863}
4864
4865#[inline]
4866#[must_use]
4867#[allow(clippy::manual_checked_ops)]
4868pub const fn const_ring_eval_w72(op: PrimitiveOp, a: u128, b: u128) -> u128 {
4869    const MASK: u128 = u128::MAX >> (128 - 72);
4870    match op {
4871        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4872        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4873        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4874        PrimitiveOp::Xor => (a ^ b) & MASK,
4875        PrimitiveOp::And => (a & b) & MASK,
4876        PrimitiveOp::Or => (a | b) & MASK,
4877        PrimitiveOp::Le => (a <= b) as u128,
4878        PrimitiveOp::Lt => (a < b) as u128,
4879        PrimitiveOp::Ge => (a >= b) as u128,
4880        PrimitiveOp::Gt => (a > b) as u128,
4881        PrimitiveOp::Concat => 0,
4882        PrimitiveOp::Div => {
4883            if b == 0 {
4884                0
4885            } else {
4886                (a / b) & MASK
4887            }
4888        }
4889        PrimitiveOp::Mod => {
4890            if b == 0 {
4891                0
4892            } else {
4893                (a % b) & MASK
4894            }
4895        }
4896        PrimitiveOp::Pow => (const_pow_w72(a, b)) & MASK,
4897        _ => 0,
4898    }
4899}
4900
4901#[inline]
4902#[must_use]
4903pub const fn const_pow_w72(base: u128, exp: u128) -> u128 {
4904    const MASK: u128 = u128::MAX >> (128 - 72);
4905    let mut result: u128 = 1;
4906    let mut b: u128 = (base) & MASK;
4907    let mut e: u128 = exp;
4908    while e > 0 {
4909        if (e & 1) == 1 {
4910            result = (result.wrapping_mul(b)) & MASK;
4911        }
4912        b = (b.wrapping_mul(b)) & MASK;
4913        e >>= 1;
4914    }
4915    result
4916}
4917
4918#[inline]
4919#[must_use]
4920pub const fn const_ring_eval_unary_w72(op: PrimitiveOp, a: u128) -> u128 {
4921    const MASK: u128 = u128::MAX >> (128 - 72);
4922    match op {
4923        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
4924        PrimitiveOp::Bnot => (!a) & MASK,
4925        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4926        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4927        _ => 0,
4928    }
4929}
4930
4931#[inline]
4932#[must_use]
4933#[allow(clippy::manual_checked_ops)]
4934pub const fn const_ring_eval_w80(op: PrimitiveOp, a: u128, b: u128) -> u128 {
4935    const MASK: u128 = u128::MAX >> (128 - 80);
4936    match op {
4937        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
4938        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
4939        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
4940        PrimitiveOp::Xor => (a ^ b) & MASK,
4941        PrimitiveOp::And => (a & b) & MASK,
4942        PrimitiveOp::Or => (a | b) & MASK,
4943        PrimitiveOp::Le => (a <= b) as u128,
4944        PrimitiveOp::Lt => (a < b) as u128,
4945        PrimitiveOp::Ge => (a >= b) as u128,
4946        PrimitiveOp::Gt => (a > b) as u128,
4947        PrimitiveOp::Concat => 0,
4948        PrimitiveOp::Div => {
4949            if b == 0 {
4950                0
4951            } else {
4952                (a / b) & MASK
4953            }
4954        }
4955        PrimitiveOp::Mod => {
4956            if b == 0 {
4957                0
4958            } else {
4959                (a % b) & MASK
4960            }
4961        }
4962        PrimitiveOp::Pow => (const_pow_w80(a, b)) & MASK,
4963        _ => 0,
4964    }
4965}
4966
4967#[inline]
4968#[must_use]
4969pub const fn const_pow_w80(base: u128, exp: u128) -> u128 {
4970    const MASK: u128 = u128::MAX >> (128 - 80);
4971    let mut result: u128 = 1;
4972    let mut b: u128 = (base) & MASK;
4973    let mut e: u128 = exp;
4974    while e > 0 {
4975        if (e & 1) == 1 {
4976            result = (result.wrapping_mul(b)) & MASK;
4977        }
4978        b = (b.wrapping_mul(b)) & MASK;
4979        e >>= 1;
4980    }
4981    result
4982}
4983
4984#[inline]
4985#[must_use]
4986pub const fn const_ring_eval_unary_w80(op: PrimitiveOp, a: u128) -> u128 {
4987    const MASK: u128 = u128::MAX >> (128 - 80);
4988    match op {
4989        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
4990        PrimitiveOp::Bnot => (!a) & MASK,
4991        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
4992        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
4993        _ => 0,
4994    }
4995}
4996
4997#[inline]
4998#[must_use]
4999#[allow(clippy::manual_checked_ops)]
5000pub const fn const_ring_eval_w88(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5001    const MASK: u128 = u128::MAX >> (128 - 88);
5002    match op {
5003        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
5004        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
5005        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
5006        PrimitiveOp::Xor => (a ^ b) & MASK,
5007        PrimitiveOp::And => (a & b) & MASK,
5008        PrimitiveOp::Or => (a | b) & MASK,
5009        PrimitiveOp::Le => (a <= b) as u128,
5010        PrimitiveOp::Lt => (a < b) as u128,
5011        PrimitiveOp::Ge => (a >= b) as u128,
5012        PrimitiveOp::Gt => (a > b) as u128,
5013        PrimitiveOp::Concat => 0,
5014        PrimitiveOp::Div => {
5015            if b == 0 {
5016                0
5017            } else {
5018                (a / b) & MASK
5019            }
5020        }
5021        PrimitiveOp::Mod => {
5022            if b == 0 {
5023                0
5024            } else {
5025                (a % b) & MASK
5026            }
5027        }
5028        PrimitiveOp::Pow => (const_pow_w88(a, b)) & MASK,
5029        _ => 0,
5030    }
5031}
5032
5033#[inline]
5034#[must_use]
5035pub const fn const_pow_w88(base: u128, exp: u128) -> u128 {
5036    const MASK: u128 = u128::MAX >> (128 - 88);
5037    let mut result: u128 = 1;
5038    let mut b: u128 = (base) & MASK;
5039    let mut e: u128 = exp;
5040    while e > 0 {
5041        if (e & 1) == 1 {
5042            result = (result.wrapping_mul(b)) & MASK;
5043        }
5044        b = (b.wrapping_mul(b)) & MASK;
5045        e >>= 1;
5046    }
5047    result
5048}
5049
5050#[inline]
5051#[must_use]
5052pub const fn const_ring_eval_unary_w88(op: PrimitiveOp, a: u128) -> u128 {
5053    const MASK: u128 = u128::MAX >> (128 - 88);
5054    match op {
5055        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
5056        PrimitiveOp::Bnot => (!a) & MASK,
5057        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
5058        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
5059        _ => 0,
5060    }
5061}
5062
5063#[inline]
5064#[must_use]
5065#[allow(clippy::manual_checked_ops)]
5066pub const fn const_ring_eval_w96(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5067    const MASK: u128 = u128::MAX >> (128 - 96);
5068    match op {
5069        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
5070        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
5071        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
5072        PrimitiveOp::Xor => (a ^ b) & MASK,
5073        PrimitiveOp::And => (a & b) & MASK,
5074        PrimitiveOp::Or => (a | b) & MASK,
5075        PrimitiveOp::Le => (a <= b) as u128,
5076        PrimitiveOp::Lt => (a < b) as u128,
5077        PrimitiveOp::Ge => (a >= b) as u128,
5078        PrimitiveOp::Gt => (a > b) as u128,
5079        PrimitiveOp::Concat => 0,
5080        PrimitiveOp::Div => {
5081            if b == 0 {
5082                0
5083            } else {
5084                (a / b) & MASK
5085            }
5086        }
5087        PrimitiveOp::Mod => {
5088            if b == 0 {
5089                0
5090            } else {
5091                (a % b) & MASK
5092            }
5093        }
5094        PrimitiveOp::Pow => (const_pow_w96(a, b)) & MASK,
5095        _ => 0,
5096    }
5097}
5098
5099#[inline]
5100#[must_use]
5101pub const fn const_pow_w96(base: u128, exp: u128) -> u128 {
5102    const MASK: u128 = u128::MAX >> (128 - 96);
5103    let mut result: u128 = 1;
5104    let mut b: u128 = (base) & MASK;
5105    let mut e: u128 = exp;
5106    while e > 0 {
5107        if (e & 1) == 1 {
5108            result = (result.wrapping_mul(b)) & MASK;
5109        }
5110        b = (b.wrapping_mul(b)) & MASK;
5111        e >>= 1;
5112    }
5113    result
5114}
5115
5116#[inline]
5117#[must_use]
5118pub const fn const_ring_eval_unary_w96(op: PrimitiveOp, a: u128) -> u128 {
5119    const MASK: u128 = u128::MAX >> (128 - 96);
5120    match op {
5121        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
5122        PrimitiveOp::Bnot => (!a) & MASK,
5123        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
5124        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
5125        _ => 0,
5126    }
5127}
5128
5129#[inline]
5130#[must_use]
5131#[allow(clippy::manual_checked_ops)]
5132pub const fn const_ring_eval_w104(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5133    const MASK: u128 = u128::MAX >> (128 - 104);
5134    match op {
5135        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
5136        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
5137        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
5138        PrimitiveOp::Xor => (a ^ b) & MASK,
5139        PrimitiveOp::And => (a & b) & MASK,
5140        PrimitiveOp::Or => (a | b) & MASK,
5141        PrimitiveOp::Le => (a <= b) as u128,
5142        PrimitiveOp::Lt => (a < b) as u128,
5143        PrimitiveOp::Ge => (a >= b) as u128,
5144        PrimitiveOp::Gt => (a > b) as u128,
5145        PrimitiveOp::Concat => 0,
5146        PrimitiveOp::Div => {
5147            if b == 0 {
5148                0
5149            } else {
5150                (a / b) & MASK
5151            }
5152        }
5153        PrimitiveOp::Mod => {
5154            if b == 0 {
5155                0
5156            } else {
5157                (a % b) & MASK
5158            }
5159        }
5160        PrimitiveOp::Pow => (const_pow_w104(a, b)) & MASK,
5161        _ => 0,
5162    }
5163}
5164
5165#[inline]
5166#[must_use]
5167pub const fn const_pow_w104(base: u128, exp: u128) -> u128 {
5168    const MASK: u128 = u128::MAX >> (128 - 104);
5169    let mut result: u128 = 1;
5170    let mut b: u128 = (base) & MASK;
5171    let mut e: u128 = exp;
5172    while e > 0 {
5173        if (e & 1) == 1 {
5174            result = (result.wrapping_mul(b)) & MASK;
5175        }
5176        b = (b.wrapping_mul(b)) & MASK;
5177        e >>= 1;
5178    }
5179    result
5180}
5181
5182#[inline]
5183#[must_use]
5184pub const fn const_ring_eval_unary_w104(op: PrimitiveOp, a: u128) -> u128 {
5185    const MASK: u128 = u128::MAX >> (128 - 104);
5186    match op {
5187        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
5188        PrimitiveOp::Bnot => (!a) & MASK,
5189        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
5190        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
5191        _ => 0,
5192    }
5193}
5194
5195#[inline]
5196#[must_use]
5197#[allow(clippy::manual_checked_ops)]
5198pub const fn const_ring_eval_w112(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5199    const MASK: u128 = u128::MAX >> (128 - 112);
5200    match op {
5201        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
5202        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
5203        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
5204        PrimitiveOp::Xor => (a ^ b) & MASK,
5205        PrimitiveOp::And => (a & b) & MASK,
5206        PrimitiveOp::Or => (a | b) & MASK,
5207        PrimitiveOp::Le => (a <= b) as u128,
5208        PrimitiveOp::Lt => (a < b) as u128,
5209        PrimitiveOp::Ge => (a >= b) as u128,
5210        PrimitiveOp::Gt => (a > b) as u128,
5211        PrimitiveOp::Concat => 0,
5212        PrimitiveOp::Div => {
5213            if b == 0 {
5214                0
5215            } else {
5216                (a / b) & MASK
5217            }
5218        }
5219        PrimitiveOp::Mod => {
5220            if b == 0 {
5221                0
5222            } else {
5223                (a % b) & MASK
5224            }
5225        }
5226        PrimitiveOp::Pow => (const_pow_w112(a, b)) & MASK,
5227        _ => 0,
5228    }
5229}
5230
5231#[inline]
5232#[must_use]
5233pub const fn const_pow_w112(base: u128, exp: u128) -> u128 {
5234    const MASK: u128 = u128::MAX >> (128 - 112);
5235    let mut result: u128 = 1;
5236    let mut b: u128 = (base) & MASK;
5237    let mut e: u128 = exp;
5238    while e > 0 {
5239        if (e & 1) == 1 {
5240            result = (result.wrapping_mul(b)) & MASK;
5241        }
5242        b = (b.wrapping_mul(b)) & MASK;
5243        e >>= 1;
5244    }
5245    result
5246}
5247
5248#[inline]
5249#[must_use]
5250pub const fn const_ring_eval_unary_w112(op: PrimitiveOp, a: u128) -> u128 {
5251    const MASK: u128 = u128::MAX >> (128 - 112);
5252    match op {
5253        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
5254        PrimitiveOp::Bnot => (!a) & MASK,
5255        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
5256        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
5257        _ => 0,
5258    }
5259}
5260
5261#[inline]
5262#[must_use]
5263#[allow(clippy::manual_checked_ops)]
5264pub const fn const_ring_eval_w120(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5265    const MASK: u128 = u128::MAX >> (128 - 120);
5266    match op {
5267        PrimitiveOp::Add => (a.wrapping_add(b)) & MASK,
5268        PrimitiveOp::Sub => (a.wrapping_sub(b)) & MASK,
5269        PrimitiveOp::Mul => (a.wrapping_mul(b)) & MASK,
5270        PrimitiveOp::Xor => (a ^ b) & MASK,
5271        PrimitiveOp::And => (a & b) & MASK,
5272        PrimitiveOp::Or => (a | b) & MASK,
5273        PrimitiveOp::Le => (a <= b) as u128,
5274        PrimitiveOp::Lt => (a < b) as u128,
5275        PrimitiveOp::Ge => (a >= b) as u128,
5276        PrimitiveOp::Gt => (a > b) as u128,
5277        PrimitiveOp::Concat => 0,
5278        PrimitiveOp::Div => {
5279            if b == 0 {
5280                0
5281            } else {
5282                (a / b) & MASK
5283            }
5284        }
5285        PrimitiveOp::Mod => {
5286            if b == 0 {
5287                0
5288            } else {
5289                (a % b) & MASK
5290            }
5291        }
5292        PrimitiveOp::Pow => (const_pow_w120(a, b)) & MASK,
5293        _ => 0,
5294    }
5295}
5296
5297#[inline]
5298#[must_use]
5299pub const fn const_pow_w120(base: u128, exp: u128) -> u128 {
5300    const MASK: u128 = u128::MAX >> (128 - 120);
5301    let mut result: u128 = 1;
5302    let mut b: u128 = (base) & MASK;
5303    let mut e: u128 = exp;
5304    while e > 0 {
5305        if (e & 1) == 1 {
5306            result = (result.wrapping_mul(b)) & MASK;
5307        }
5308        b = (b.wrapping_mul(b)) & MASK;
5309        e >>= 1;
5310    }
5311    result
5312}
5313
5314#[inline]
5315#[must_use]
5316pub const fn const_ring_eval_unary_w120(op: PrimitiveOp, a: u128) -> u128 {
5317    const MASK: u128 = u128::MAX >> (128 - 120);
5318    match op {
5319        PrimitiveOp::Neg => (0u128.wrapping_sub(a)) & MASK,
5320        PrimitiveOp::Bnot => (!a) & MASK,
5321        PrimitiveOp::Succ => (a.wrapping_add(1)) & MASK,
5322        PrimitiveOp::Pred => (a.wrapping_sub(1)) & MASK,
5323        _ => 0,
5324    }
5325}
5326
5327#[inline]
5328#[must_use]
5329#[allow(clippy::manual_checked_ops)]
5330pub const fn const_ring_eval_w128(op: PrimitiveOp, a: u128, b: u128) -> u128 {
5331    match op {
5332        PrimitiveOp::Add => a.wrapping_add(b),
5333        PrimitiveOp::Sub => a.wrapping_sub(b),
5334        PrimitiveOp::Mul => a.wrapping_mul(b),
5335        PrimitiveOp::Xor => a ^ b,
5336        PrimitiveOp::And => a & b,
5337        PrimitiveOp::Or => a | b,
5338        PrimitiveOp::Le => (a <= b) as u128,
5339        PrimitiveOp::Lt => (a < b) as u128,
5340        PrimitiveOp::Ge => (a >= b) as u128,
5341        PrimitiveOp::Gt => (a > b) as u128,
5342        PrimitiveOp::Concat => 0,
5343        PrimitiveOp::Div => {
5344            if b == 0 {
5345                0
5346            } else {
5347                a / b
5348            }
5349        }
5350        PrimitiveOp::Mod => {
5351            if b == 0 {
5352                0
5353            } else {
5354                a % b
5355            }
5356        }
5357        PrimitiveOp::Pow => const_pow_w128(a, b),
5358        _ => 0,
5359    }
5360}
5361
5362#[inline]
5363#[must_use]
5364pub const fn const_pow_w128(base: u128, exp: u128) -> u128 {
5365    let mut result: u128 = 1;
5366    let mut b: u128 = base;
5367    let mut e: u128 = exp;
5368    while e > 0 {
5369        if (e & 1) == 1 {
5370            result = result.wrapping_mul(b);
5371        }
5372        b = b.wrapping_mul(b);
5373        e >>= 1;
5374    }
5375    result
5376}
5377
5378#[inline]
5379#[must_use]
5380pub const fn const_ring_eval_unary_w128(op: PrimitiveOp, a: u128) -> u128 {
5381    match op {
5382        PrimitiveOp::Neg => 0u128.wrapping_sub(a),
5383        PrimitiveOp::Bnot => !a,
5384        PrimitiveOp::Succ => a.wrapping_add(1),
5385        PrimitiveOp::Pred => a.wrapping_sub(1),
5386        _ => 0,
5387    }
5388}
5389
5390/// v0.2.2 Phase C.3: foundation-internal generic backing for Witt
5391/// levels above W128. Holds an inline `[u64; N]` array with no heap
5392/// allocation, no global state, and `const fn` arithmetic throughout.
5393/// Constructors are `pub(crate)`; downstream cannot fabricate a `Limbs<N>`.
5394/// Multiplication is schoolbook-only at v0.2.2 Phase C.3; the Toom-Cook
5395/// framework with parametric splitting factor `R` ships in Phase C.4 via
5396/// the `resolver::multiplication::certify` resolver, which decides `R`
5397/// per call from a Landauer cost function constrained by stack budget.
5398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5399pub struct Limbs<const N: usize> {
5400    /// Little-endian limbs: `words[0]` is the low 64 bits.
5401    words: [u64; N],
5402    /// Prevents external construction.
5403    _sealed: (),
5404}
5405
5406impl<const N: usize> Limbs<N> {
5407    /// Crate-internal constructor from a fixed-size limb array.
5408    #[inline]
5409    #[must_use]
5410    #[allow(dead_code)]
5411    pub(crate) const fn from_words(words: [u64; N]) -> Self {
5412        Self { words, _sealed: () }
5413    }
5414
5415    /// All-zeros constructor.
5416    #[inline]
5417    #[must_use]
5418    #[allow(dead_code)]
5419    pub(crate) const fn zero() -> Self {
5420        Self {
5421            words: [0u64; N],
5422            _sealed: (),
5423        }
5424    }
5425
5426    /// Returns a reference to the underlying limb array.
5427    #[inline]
5428    #[must_use]
5429    pub const fn words(&self) -> &[u64; N] {
5430        &self.words
5431    }
5432
5433    /// Wrapping addition mod 2^(64*N). Const-fn schoolbook with carry.
5434    #[inline]
5435    #[must_use]
5436    #[allow(dead_code)]
5437    pub(crate) const fn wrapping_add(self, other: Self) -> Self {
5438        let mut out = [0u64; N];
5439        let mut carry: u64 = 0;
5440        let mut i = 0;
5441        while i < N {
5442            let (s1, c1) = self.words[i].overflowing_add(other.words[i]);
5443            let (s2, c2) = s1.overflowing_add(carry);
5444            out[i] = s2;
5445            carry = (c1 as u64) | (c2 as u64);
5446            i += 1;
5447        }
5448        Self {
5449            words: out,
5450            _sealed: (),
5451        }
5452    }
5453
5454    /// Wrapping subtraction mod 2^(64*N). Const-fn schoolbook with borrow.
5455    #[inline]
5456    #[must_use]
5457    #[allow(dead_code)]
5458    pub(crate) const fn wrapping_sub(self, other: Self) -> Self {
5459        let mut out = [0u64; N];
5460        let mut borrow: u64 = 0;
5461        let mut i = 0;
5462        while i < N {
5463            let (d1, b1) = self.words[i].overflowing_sub(other.words[i]);
5464            let (d2, b2) = d1.overflowing_sub(borrow);
5465            out[i] = d2;
5466            borrow = (b1 as u64) | (b2 as u64);
5467            i += 1;
5468        }
5469        Self {
5470            words: out,
5471            _sealed: (),
5472        }
5473    }
5474
5475    /// Wrapping schoolbook multiplication mod 2^(64*N). The high N limbs of
5476    /// the 2N-limb full product are discarded (mod 2^bits truncation).
5477    /// v0.2.2 Phase C.3: schoolbook only. Phase C.4 adds the Toom-Cook
5478    /// framework with parametric R via `resolver::multiplication::certify`.
5479    #[inline]
5480    #[must_use]
5481    #[allow(dead_code)]
5482    pub(crate) const fn wrapping_mul(self, other: Self) -> Self {
5483        let mut out = [0u64; N];
5484        let mut i = 0;
5485        while i < N {
5486            let mut carry: u128 = 0;
5487            let mut j = 0;
5488            while j < N - i {
5489                let prod = (self.words[i] as u128) * (other.words[j] as u128)
5490                    + (out[i + j] as u128)
5491                    + carry;
5492                out[i + j] = prod as u64;
5493                carry = prod >> 64;
5494                j += 1;
5495            }
5496            i += 1;
5497        }
5498        Self {
5499            words: out,
5500            _sealed: (),
5501        }
5502    }
5503
5504    /// Bitwise XOR.
5505    #[inline]
5506    #[must_use]
5507    #[allow(dead_code)]
5508    pub(crate) const fn xor(self, other: Self) -> Self {
5509        let mut out = [0u64; N];
5510        let mut i = 0;
5511        while i < N {
5512            out[i] = self.words[i] ^ other.words[i];
5513            i += 1;
5514        }
5515        Self {
5516            words: out,
5517            _sealed: (),
5518        }
5519    }
5520
5521    /// Bitwise AND.
5522    #[inline]
5523    #[must_use]
5524    #[allow(dead_code)]
5525    pub(crate) const fn and(self, other: Self) -> Self {
5526        let mut out = [0u64; N];
5527        let mut i = 0;
5528        while i < N {
5529            out[i] = self.words[i] & other.words[i];
5530            i += 1;
5531        }
5532        Self {
5533            words: out,
5534            _sealed: (),
5535        }
5536    }
5537
5538    /// Bitwise OR.
5539    #[inline]
5540    #[must_use]
5541    #[allow(dead_code)]
5542    pub(crate) const fn or(self, other: Self) -> Self {
5543        let mut out = [0u64; N];
5544        let mut i = 0;
5545        while i < N {
5546            out[i] = self.words[i] | other.words[i];
5547            i += 1;
5548        }
5549        Self {
5550            words: out,
5551            _sealed: (),
5552        }
5553    }
5554
5555    /// Bitwise NOT.
5556    #[inline]
5557    #[must_use]
5558    #[allow(dead_code)]
5559    pub(crate) const fn not(self) -> Self {
5560        let mut out = [0u64; N];
5561        let mut i = 0;
5562        while i < N {
5563            out[i] = !self.words[i];
5564            i += 1;
5565        }
5566        Self {
5567            words: out,
5568            _sealed: (),
5569        }
5570    }
5571
5572    /// Mask the high bits of the value to keep only the low `bits` bits.
5573    /// Used at the arithmetic boundary for non-exact-fit Witt widths (e.g.,
5574    /// W160 over `Limbs<3>`: 64+64+32 bits = mask the upper 32 bits of words[2]).
5575    #[inline]
5576    #[must_use]
5577    #[allow(dead_code)]
5578    pub(crate) const fn mask_high_bits(self, bits: u32) -> Self {
5579        let mut out = self.words;
5580        let high_word_idx = (bits / 64) as usize;
5581        let low_bits_in_high_word = bits % 64;
5582        if low_bits_in_high_word != 0 && high_word_idx < N {
5583            let mask = (1u64 << low_bits_in_high_word) - 1;
5584            out[high_word_idx] &= mask;
5585            // Zero everything above the high word.
5586            let mut i = high_word_idx + 1;
5587            while i < N {
5588                out[i] = 0;
5589                i += 1;
5590            }
5591        } else if low_bits_in_high_word == 0 && high_word_idx < N {
5592            // bits is exactly a multiple of 64; zero everything from high_word_idx.
5593            let mut i = high_word_idx;
5594            while i < N {
5595                out[i] = 0;
5596                i += 1;
5597            }
5598        }
5599        Self {
5600            words: out,
5601            _sealed: (),
5602        }
5603    }
5604}
5605
5606/// Sealed marker trait identifying types produced by the foundation crate's
5607/// conformance/reduction pipeline. v0.2.1 bounds `Validated<T>` on this trait
5608/// so downstream crates cannot fabricate `Validated<UserType>` — user types
5609/// cannot impl `OntologyTarget` because the supertrait is private.
5610pub trait OntologyTarget: ontology_target_sealed::Sealed {}
5611
5612/// Sealed shim for `cert:GroundingCertificate`. Produced by GroundingAwareResolver.
5613#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5614pub struct GroundingCertificate {
5615    witt_bits: u16,
5616    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5617    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5618    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5619    /// are never equal even when leading bytes coincide.
5620    content_fingerprint: ContentFingerprint,
5621}
5622
5623impl GroundingCertificate {
5624    /// Returns the Witt level the certificate was issued for. Sourced
5625    /// from the pipeline's substrate hash output at minting time.
5626    #[inline]
5627    #[must_use]
5628    pub const fn witt_bits(&self) -> u16 {
5629        self.witt_bits
5630    }
5631
5632    /// v0.2.2 T5: returns the parametric content fingerprint of the
5633    /// source state, computed at mint time by the consumer-supplied
5634    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5635    /// certificates from different hashers are never equal because
5636    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5637    #[inline]
5638    #[must_use]
5639    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5640        self.content_fingerprint
5641    }
5642
5643    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5644    /// witt-bits value AND the parametric content fingerprint. Used by
5645    /// `pipeline::run` and `certify_*_const` to mint a certificate
5646    /// carrying the substrate-computed fingerprint of the source state.
5647    #[inline]
5648    #[must_use]
5649    #[allow(dead_code)]
5650    pub(crate) const fn with_level_and_fingerprint_const(
5651        witt_bits: u16,
5652        content_fingerprint: ContentFingerprint,
5653    ) -> Self {
5654        Self {
5655            witt_bits,
5656            content_fingerprint,
5657        }
5658    }
5659}
5660
5661/// Sealed shim for `cert:LiftChainCertificate`. Carries the v0.2.1 `target_level()` accessor populated from the pipeline's StageOutcome.
5662#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5663pub struct LiftChainCertificate {
5664    witt_bits: u16,
5665    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5666    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5667    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5668    /// are never equal even when leading bytes coincide.
5669    content_fingerprint: ContentFingerprint,
5670}
5671
5672impl LiftChainCertificate {
5673    /// Returns the Witt level the certificate was issued for. Sourced
5674    /// from the pipeline's substrate hash output at minting time.
5675    #[inline]
5676    #[must_use]
5677    pub const fn witt_bits(&self) -> u16 {
5678        self.witt_bits
5679    }
5680
5681    /// v0.2.2 T5: returns the parametric content fingerprint of the
5682    /// source state, computed at mint time by the consumer-supplied
5683    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5684    /// certificates from different hashers are never equal because
5685    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5686    #[inline]
5687    #[must_use]
5688    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5689        self.content_fingerprint
5690    }
5691
5692    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5693    /// witt-bits value AND the parametric content fingerprint. Used by
5694    /// `pipeline::run` and `certify_*_const` to mint a certificate
5695    /// carrying the substrate-computed fingerprint of the source state.
5696    #[inline]
5697    #[must_use]
5698    #[allow(dead_code)]
5699    pub(crate) const fn with_level_and_fingerprint_const(
5700        witt_bits: u16,
5701        content_fingerprint: ContentFingerprint,
5702    ) -> Self {
5703        Self {
5704            witt_bits,
5705            content_fingerprint,
5706        }
5707    }
5708}
5709
5710/// Sealed shim for `cert:InhabitanceCertificate` (v0.2.1).
5711#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5712pub struct InhabitanceCertificate {
5713    witt_bits: u16,
5714    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5715    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5716    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5717    /// are never equal even when leading bytes coincide.
5718    content_fingerprint: ContentFingerprint,
5719}
5720
5721impl InhabitanceCertificate {
5722    /// Returns the Witt level the certificate was issued for. Sourced
5723    /// from the pipeline's substrate hash output at minting time.
5724    #[inline]
5725    #[must_use]
5726    pub const fn witt_bits(&self) -> u16 {
5727        self.witt_bits
5728    }
5729
5730    /// v0.2.2 T5: returns the parametric content fingerprint of the
5731    /// source state, computed at mint time by the consumer-supplied
5732    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5733    /// certificates from different hashers are never equal because
5734    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5735    #[inline]
5736    #[must_use]
5737    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5738        self.content_fingerprint
5739    }
5740
5741    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5742    /// witt-bits value AND the parametric content fingerprint. Used by
5743    /// `pipeline::run` and `certify_*_const` to mint a certificate
5744    /// carrying the substrate-computed fingerprint of the source state.
5745    #[inline]
5746    #[must_use]
5747    #[allow(dead_code)]
5748    pub(crate) const fn with_level_and_fingerprint_const(
5749        witt_bits: u16,
5750        content_fingerprint: ContentFingerprint,
5751    ) -> Self {
5752        Self {
5753            witt_bits,
5754            content_fingerprint,
5755        }
5756    }
5757}
5758
5759/// Sealed shim for `cert:CompletenessCertificate`.
5760#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5761pub struct CompletenessCertificate {
5762    witt_bits: u16,
5763    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5764    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5765    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5766    /// are never equal even when leading bytes coincide.
5767    content_fingerprint: ContentFingerprint,
5768}
5769
5770impl CompletenessCertificate {
5771    /// Returns the Witt level the certificate was issued for. Sourced
5772    /// from the pipeline's substrate hash output at minting time.
5773    #[inline]
5774    #[must_use]
5775    pub const fn witt_bits(&self) -> u16 {
5776        self.witt_bits
5777    }
5778
5779    /// v0.2.2 T5: returns the parametric content fingerprint of the
5780    /// source state, computed at mint time by the consumer-supplied
5781    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5782    /// certificates from different hashers are never equal because
5783    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5784    #[inline]
5785    #[must_use]
5786    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5787        self.content_fingerprint
5788    }
5789
5790    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5791    /// witt-bits value AND the parametric content fingerprint. Used by
5792    /// `pipeline::run` and `certify_*_const` to mint a certificate
5793    /// carrying the substrate-computed fingerprint of the source state.
5794    #[inline]
5795    #[must_use]
5796    #[allow(dead_code)]
5797    pub(crate) const fn with_level_and_fingerprint_const(
5798        witt_bits: u16,
5799        content_fingerprint: ContentFingerprint,
5800    ) -> Self {
5801        Self {
5802            witt_bits,
5803            content_fingerprint,
5804        }
5805    }
5806}
5807
5808/// Sealed shim for `cert:MultiplicationCertificate` (v0.2.2 Phase C.4). Carries the cost-optimal Toom-Cook splitting factor R, the recursive sub-multiplication count, and the accumulated Landauer cost in nats.
5809#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5810pub struct MultiplicationCertificate {
5811    witt_bits: u16,
5812    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5813    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5814    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5815    /// are never equal even when leading bytes coincide.
5816    content_fingerprint: ContentFingerprint,
5817}
5818
5819impl MultiplicationCertificate {
5820    /// Returns the Witt level the certificate was issued for. Sourced
5821    /// from the pipeline's substrate hash output at minting time.
5822    #[inline]
5823    #[must_use]
5824    pub const fn witt_bits(&self) -> u16 {
5825        self.witt_bits
5826    }
5827
5828    /// v0.2.2 T5: returns the parametric content fingerprint of the
5829    /// source state, computed at mint time by the consumer-supplied
5830    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5831    /// certificates from different hashers are never equal because
5832    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5833    #[inline]
5834    #[must_use]
5835    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5836        self.content_fingerprint
5837    }
5838
5839    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5840    /// witt-bits value AND the parametric content fingerprint. Used by
5841    /// `pipeline::run` and `certify_*_const` to mint a certificate
5842    /// carrying the substrate-computed fingerprint of the source state.
5843    #[inline]
5844    #[must_use]
5845    #[allow(dead_code)]
5846    pub(crate) const fn with_level_and_fingerprint_const(
5847        witt_bits: u16,
5848        content_fingerprint: ContentFingerprint,
5849    ) -> Self {
5850        Self {
5851            witt_bits,
5852            content_fingerprint,
5853        }
5854    }
5855}
5856
5857/// Sealed shim for `cert:PartitionCertificate` (v0.2.2 Phase E). Attests the partition component classification of a Datum.
5858#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5859pub struct PartitionCertificate {
5860    witt_bits: u16,
5861    /// v0.2.2 T5: parametric content fingerprint computed at mint time
5862    /// by the consumer-supplied `Hasher`. Bit-equality on the full
5863    /// buffer + width tag, so two certs with different `OUTPUT_BYTES`
5864    /// are never equal even when leading bytes coincide.
5865    content_fingerprint: ContentFingerprint,
5866}
5867
5868impl PartitionCertificate {
5869    /// Returns the Witt level the certificate was issued for. Sourced
5870    /// from the pipeline's substrate hash output at minting time.
5871    #[inline]
5872    #[must_use]
5873    pub const fn witt_bits(&self) -> u16 {
5874        self.witt_bits
5875    }
5876
5877    /// v0.2.2 T5: returns the parametric content fingerprint of the
5878    /// source state, computed at mint time by the consumer-supplied
5879    /// `Hasher`. Active width recoverable via `width_bytes()`. Two
5880    /// certificates from different hashers are never equal because
5881    /// `ContentFingerprint::Eq` compares the full buffer + width tag.
5882    #[inline]
5883    #[must_use]
5884    pub const fn content_fingerprint(&self) -> ContentFingerprint {
5885        self.content_fingerprint
5886    }
5887
5888    /// v0.2.2 T5 C3.g + T6.7: the only constructor — takes both the
5889    /// witt-bits value AND the parametric content fingerprint. Used by
5890    /// `pipeline::run` and `certify_*_const` to mint a certificate
5891    /// carrying the substrate-computed fingerprint of the source state.
5892    #[inline]
5893    #[must_use]
5894    #[allow(dead_code)]
5895    pub(crate) const fn with_level_and_fingerprint_const(
5896        witt_bits: u16,
5897        content_fingerprint: ContentFingerprint,
5898    ) -> Self {
5899        Self {
5900            witt_bits,
5901            content_fingerprint,
5902        }
5903    }
5904}
5905
5906/// Sealed shim for `proof:ImpossibilityWitness`. Returned by completeness and grounding resolvers on failure.
5907#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5908pub struct GenericImpossibilityWitness {
5909    /// Optional theorem / invariant IRI identifying the failed identity.
5910    /// `None` for legacy call sites minting via `Default::default()`;
5911    /// `Some(iri)` when the witness is constructed via `for_identity`
5912    /// (Product/Coproduct Completion Amendment §2.3a).
5913    identity: Option<&'static str>,
5914}
5915
5916impl Default for GenericImpossibilityWitness {
5917    #[inline]
5918    fn default() -> Self {
5919        Self { identity: None }
5920    }
5921}
5922
5923impl GenericImpossibilityWitness {
5924    /// Construct a witness citing a specific theorem / invariant IRI.
5925    /// Introduced by the Product/Coproduct Completion Amendment §2.3a
5926    /// so mint primitives can emit typed failures against `op/*` theorems
5927    /// and `foundation/*` layout invariants.
5928    #[inline]
5929    #[must_use]
5930    pub const fn for_identity(identity: &'static str) -> Self {
5931        Self {
5932            identity: Some(identity),
5933        }
5934    }
5935
5936    /// Returns the theorem / invariant IRI this witness cites, if any.
5937    #[inline]
5938    #[must_use]
5939    pub const fn identity(&self) -> Option<&'static str> {
5940        self.identity
5941    }
5942}
5943
5944/// Sealed shim for `proof:InhabitanceImpossibilityWitness` (v0.2.1).
5945#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
5946pub struct InhabitanceImpossibilityWitness {
5947    _private: (),
5948}
5949
5950/// Input shim for `type:ConstrainedType`. Used as `Certify::Input` for InhabitanceResolver, TowerCompletenessResolver, and IncrementalCompletenessResolver.
5951#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
5952pub struct ConstrainedTypeInput {
5953    _private: (),
5954}
5955
5956impl core::fmt::Display for GenericImpossibilityWitness {
5957    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5958        match self.identity {
5959            Some(iri) => write!(f, "GenericImpossibilityWitness({iri})"),
5960            None => f.write_str("GenericImpossibilityWitness"),
5961        }
5962    }
5963}
5964impl core::error::Error for GenericImpossibilityWitness {}
5965
5966impl core::fmt::Display for InhabitanceImpossibilityWitness {
5967    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5968        f.write_str("InhabitanceImpossibilityWitness")
5969    }
5970}
5971impl core::error::Error for InhabitanceImpossibilityWitness {}
5972
5973impl LiftChainCertificate {
5974    /// Returns the Witt level the certificate was issued for.
5975    #[inline]
5976    #[must_use]
5977    pub const fn target_level(&self) -> WittLevel {
5978        WittLevel::new(self.witt_bits as u32)
5979    }
5980}
5981
5982impl InhabitanceCertificate {
5983    /// Returns the witness value tuple bytes when `verified` is true.
5984    /// The sealed shim returns `None`; real witnesses flow through the
5985    /// macro back-door path.
5986    #[inline]
5987    #[must_use]
5988    pub const fn witness(&self) -> Option<&'static [u8]> {
5989        None
5990    }
5991}
5992
5993pub(crate) mod ontology_target_sealed {
5994    /// Private supertrait. Not implementable outside this crate.
5995    pub trait Sealed {}
5996    impl Sealed for super::GroundingCertificate {}
5997    impl Sealed for super::LiftChainCertificate {}
5998    impl Sealed for super::InhabitanceCertificate {}
5999    impl Sealed for super::CompletenessCertificate {}
6000    impl Sealed for super::MultiplicationCertificate {}
6001    impl Sealed for super::PartitionCertificate {}
6002    impl Sealed for super::GenericImpossibilityWitness {}
6003    impl Sealed for super::InhabitanceImpossibilityWitness {}
6004    impl Sealed for super::ConstrainedTypeInput {}
6005    impl Sealed for super::PartitionProductWitness {}
6006    impl Sealed for super::PartitionCoproductWitness {}
6007    impl Sealed for super::CartesianProductWitness {}
6008    impl<const INLINE_BYTES: usize> Sealed for super::CompileUnit<'_, INLINE_BYTES> {}
6009}
6010
6011impl OntologyTarget for GroundingCertificate {}
6012impl OntologyTarget for LiftChainCertificate {}
6013impl OntologyTarget for InhabitanceCertificate {}
6014impl OntologyTarget for CompletenessCertificate {}
6015impl OntologyTarget for MultiplicationCertificate {}
6016impl OntologyTarget for PartitionCertificate {}
6017impl OntologyTarget for GenericImpossibilityWitness {}
6018impl OntologyTarget for InhabitanceImpossibilityWitness {}
6019impl OntologyTarget for ConstrainedTypeInput {}
6020impl OntologyTarget for PartitionProductWitness {}
6021impl OntologyTarget for PartitionCoproductWitness {}
6022impl OntologyTarget for CartesianProductWitness {}
6023impl<const INLINE_BYTES: usize> OntologyTarget for CompileUnit<'_, INLINE_BYTES> {}
6024
6025/// v0.2.2 W11: supporting evidence type for `CompletenessCertificate`.
6026/// Linked from the certificate via the `Certificate::Evidence` associated type.
6027#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
6028pub struct CompletenessAuditTrail {
6029    _private: (),
6030}
6031
6032/// v0.2.2 W11: supporting evidence type for `LiftChainCertificate`.
6033#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
6034pub struct ChainAuditTrail {
6035    _private: (),
6036}
6037
6038/// v0.2.2 W11: supporting evidence type for `GeodesicCertificate`.
6039#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
6040pub struct GeodesicEvidenceBundle {
6041    _private: (),
6042}
6043
6044/// v0.2.2 W11: sealed carrier for `cert:TransformCertificate`.
6045/// Phase X.1: minted with a Witt level and content fingerprint so the
6046/// resolver whose `resolver:CertifyMapping` produces this class can fold
6047/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6048/// constructor matches every other `cert:Certificate` subclass.
6049#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6050pub struct TransformCertificate {
6051    witt_bits: u16,
6052    content_fingerprint: ContentFingerprint,
6053    _private: (),
6054}
6055
6056impl TransformCertificate {
6057    /// Phase X.1: content-addressed constructor. Mints a certificate
6058    /// carrying the Witt level and substrate-hasher fingerprint of the
6059    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6060    #[inline]
6061    #[must_use]
6062    #[allow(dead_code)]
6063    pub(crate) const fn with_level_and_fingerprint_const(
6064        witt_bits: u16,
6065        content_fingerprint: ContentFingerprint,
6066    ) -> Self {
6067        Self {
6068            witt_bits,
6069            content_fingerprint,
6070            _private: (),
6071        }
6072    }
6073
6074    /// Phase X.1: legacy zero-fingerprint constructor retained for
6075    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6076    #[inline]
6077    #[must_use]
6078    #[allow(dead_code)]
6079    pub(crate) const fn empty_const() -> Self {
6080        Self {
6081            witt_bits: 0,
6082            content_fingerprint: ContentFingerprint::zero(),
6083            _private: (),
6084        }
6085    }
6086
6087    /// Phase X.1: the Witt level at which this certificate was minted.
6088    #[inline]
6089    #[must_use]
6090    pub const fn witt_bits(&self) -> u16 {
6091        self.witt_bits
6092    }
6093
6094    /// Phase X.1: the content fingerprint of the resolver decision.
6095    #[inline]
6096    #[must_use]
6097    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6098        self.content_fingerprint
6099    }
6100}
6101
6102/// v0.2.2 W11: sealed carrier for `cert:IsometryCertificate`.
6103/// Phase X.1: minted with a Witt level and content fingerprint so the
6104/// resolver whose `resolver:CertifyMapping` produces this class can fold
6105/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6106/// constructor matches every other `cert:Certificate` subclass.
6107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6108pub struct IsometryCertificate {
6109    witt_bits: u16,
6110    content_fingerprint: ContentFingerprint,
6111    _private: (),
6112}
6113
6114impl IsometryCertificate {
6115    /// Phase X.1: content-addressed constructor. Mints a certificate
6116    /// carrying the Witt level and substrate-hasher fingerprint of the
6117    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6118    #[inline]
6119    #[must_use]
6120    #[allow(dead_code)]
6121    pub(crate) const fn with_level_and_fingerprint_const(
6122        witt_bits: u16,
6123        content_fingerprint: ContentFingerprint,
6124    ) -> Self {
6125        Self {
6126            witt_bits,
6127            content_fingerprint,
6128            _private: (),
6129        }
6130    }
6131
6132    /// Phase X.1: legacy zero-fingerprint constructor retained for
6133    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6134    #[inline]
6135    #[must_use]
6136    #[allow(dead_code)]
6137    pub(crate) const fn empty_const() -> Self {
6138        Self {
6139            witt_bits: 0,
6140            content_fingerprint: ContentFingerprint::zero(),
6141            _private: (),
6142        }
6143    }
6144
6145    /// Phase X.1: the Witt level at which this certificate was minted.
6146    #[inline]
6147    #[must_use]
6148    pub const fn witt_bits(&self) -> u16 {
6149        self.witt_bits
6150    }
6151
6152    /// Phase X.1: the content fingerprint of the resolver decision.
6153    #[inline]
6154    #[must_use]
6155    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6156        self.content_fingerprint
6157    }
6158}
6159
6160/// v0.2.2 W11: sealed carrier for `cert:InvolutionCertificate`.
6161/// Phase X.1: minted with a Witt level and content fingerprint so the
6162/// resolver whose `resolver:CertifyMapping` produces this class can fold
6163/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6164/// constructor matches every other `cert:Certificate` subclass.
6165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6166pub struct InvolutionCertificate {
6167    witt_bits: u16,
6168    content_fingerprint: ContentFingerprint,
6169    _private: (),
6170}
6171
6172impl InvolutionCertificate {
6173    /// Phase X.1: content-addressed constructor. Mints a certificate
6174    /// carrying the Witt level and substrate-hasher fingerprint of the
6175    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6176    #[inline]
6177    #[must_use]
6178    #[allow(dead_code)]
6179    pub(crate) const fn with_level_and_fingerprint_const(
6180        witt_bits: u16,
6181        content_fingerprint: ContentFingerprint,
6182    ) -> Self {
6183        Self {
6184            witt_bits,
6185            content_fingerprint,
6186            _private: (),
6187        }
6188    }
6189
6190    /// Phase X.1: legacy zero-fingerprint constructor retained for
6191    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6192    #[inline]
6193    #[must_use]
6194    #[allow(dead_code)]
6195    pub(crate) const fn empty_const() -> Self {
6196        Self {
6197            witt_bits: 0,
6198            content_fingerprint: ContentFingerprint::zero(),
6199            _private: (),
6200        }
6201    }
6202
6203    /// Phase X.1: the Witt level at which this certificate was minted.
6204    #[inline]
6205    #[must_use]
6206    pub const fn witt_bits(&self) -> u16 {
6207        self.witt_bits
6208    }
6209
6210    /// Phase X.1: the content fingerprint of the resolver decision.
6211    #[inline]
6212    #[must_use]
6213    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6214        self.content_fingerprint
6215    }
6216}
6217
6218/// v0.2.2 W11: sealed carrier for `cert:GeodesicCertificate`.
6219/// Phase X.1: minted with a Witt level and content fingerprint so the
6220/// resolver whose `resolver:CertifyMapping` produces this class can fold
6221/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6222/// constructor matches every other `cert:Certificate` subclass.
6223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6224pub struct GeodesicCertificate {
6225    witt_bits: u16,
6226    content_fingerprint: ContentFingerprint,
6227    _private: (),
6228}
6229
6230impl GeodesicCertificate {
6231    /// Phase X.1: content-addressed constructor. Mints a certificate
6232    /// carrying the Witt level and substrate-hasher fingerprint of the
6233    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6234    #[inline]
6235    #[must_use]
6236    #[allow(dead_code)]
6237    pub(crate) const fn with_level_and_fingerprint_const(
6238        witt_bits: u16,
6239        content_fingerprint: ContentFingerprint,
6240    ) -> Self {
6241        Self {
6242            witt_bits,
6243            content_fingerprint,
6244            _private: (),
6245        }
6246    }
6247
6248    /// Phase X.1: legacy zero-fingerprint constructor retained for
6249    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6250    #[inline]
6251    #[must_use]
6252    #[allow(dead_code)]
6253    pub(crate) const fn empty_const() -> Self {
6254        Self {
6255            witt_bits: 0,
6256            content_fingerprint: ContentFingerprint::zero(),
6257            _private: (),
6258        }
6259    }
6260
6261    /// Phase X.1: the Witt level at which this certificate was minted.
6262    #[inline]
6263    #[must_use]
6264    pub const fn witt_bits(&self) -> u16 {
6265        self.witt_bits
6266    }
6267
6268    /// Phase X.1: the content fingerprint of the resolver decision.
6269    #[inline]
6270    #[must_use]
6271    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6272        self.content_fingerprint
6273    }
6274}
6275
6276/// v0.2.2 W11: sealed carrier for `cert:MeasurementCertificate`.
6277/// Phase X.1: minted with a Witt level and content fingerprint so the
6278/// resolver whose `resolver:CertifyMapping` produces this class can fold
6279/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6280/// constructor matches every other `cert:Certificate` subclass.
6281#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6282pub struct MeasurementCertificate {
6283    witt_bits: u16,
6284    content_fingerprint: ContentFingerprint,
6285    _private: (),
6286}
6287
6288impl MeasurementCertificate {
6289    /// Phase X.1: content-addressed constructor. Mints a certificate
6290    /// carrying the Witt level and substrate-hasher fingerprint of the
6291    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6292    #[inline]
6293    #[must_use]
6294    #[allow(dead_code)]
6295    pub(crate) const fn with_level_and_fingerprint_const(
6296        witt_bits: u16,
6297        content_fingerprint: ContentFingerprint,
6298    ) -> Self {
6299        Self {
6300            witt_bits,
6301            content_fingerprint,
6302            _private: (),
6303        }
6304    }
6305
6306    /// Phase X.1: legacy zero-fingerprint constructor retained for
6307    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6308    #[inline]
6309    #[must_use]
6310    #[allow(dead_code)]
6311    pub(crate) const fn empty_const() -> Self {
6312        Self {
6313            witt_bits: 0,
6314            content_fingerprint: ContentFingerprint::zero(),
6315            _private: (),
6316        }
6317    }
6318
6319    /// Phase X.1: the Witt level at which this certificate was minted.
6320    #[inline]
6321    #[must_use]
6322    pub const fn witt_bits(&self) -> u16 {
6323        self.witt_bits
6324    }
6325
6326    /// Phase X.1: the content fingerprint of the resolver decision.
6327    #[inline]
6328    #[must_use]
6329    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6330        self.content_fingerprint
6331    }
6332}
6333
6334/// v0.2.2 W11: sealed carrier for `cert:BornRuleVerification`.
6335/// Phase X.1: minted with a Witt level and content fingerprint so the
6336/// resolver whose `resolver:CertifyMapping` produces this class can fold
6337/// its decision into a content-addressed witness. The `with_level_and_fingerprint_const`
6338/// constructor matches every other `cert:Certificate` subclass.
6339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6340pub struct BornRuleVerification {
6341    witt_bits: u16,
6342    content_fingerprint: ContentFingerprint,
6343    _private: (),
6344}
6345
6346impl BornRuleVerification {
6347    /// Phase X.1: content-addressed constructor. Mints a certificate
6348    /// carrying the Witt level and substrate-hasher fingerprint of the
6349    /// resolver decision. Crate-sealed so that only resolver kernels mint.
6350    #[inline]
6351    #[must_use]
6352    #[allow(dead_code)]
6353    pub(crate) const fn with_level_and_fingerprint_const(
6354        witt_bits: u16,
6355        content_fingerprint: ContentFingerprint,
6356    ) -> Self {
6357        Self {
6358            witt_bits,
6359            content_fingerprint,
6360            _private: (),
6361        }
6362    }
6363
6364    /// Phase X.1: legacy zero-fingerprint constructor retained for
6365    /// `certify_*_const` callers that pre-date the X.1 cert-discrimination pass.
6366    #[inline]
6367    #[must_use]
6368    #[allow(dead_code)]
6369    pub(crate) const fn empty_const() -> Self {
6370        Self {
6371            witt_bits: 0,
6372            content_fingerprint: ContentFingerprint::zero(),
6373            _private: (),
6374        }
6375    }
6376
6377    /// Phase X.1: the Witt level at which this certificate was minted.
6378    #[inline]
6379    #[must_use]
6380    pub const fn witt_bits(&self) -> u16 {
6381        self.witt_bits
6382    }
6383
6384    /// Phase X.1: the content fingerprint of the resolver decision.
6385    #[inline]
6386    #[must_use]
6387    pub const fn content_fingerprint(&self) -> ContentFingerprint {
6388        self.content_fingerprint
6389    }
6390}
6391
6392/// v0.2.2 W11: sealed marker trait for foundation-supplied certificate kinds.
6393/// Implemented by every `cert:Certificate` subclass via codegen; not
6394/// implementable outside this crate.
6395pub trait Certificate: certificate_sealed::Sealed {
6396    /// The ontology IRI of this certificate class.
6397    const IRI: &'static str;
6398    /// The structured evidence carried by this certificate (or `()` if none).
6399    type Evidence;
6400}
6401
6402pub(crate) mod certificate_sealed {
6403    /// Private supertrait. Not implementable outside this crate.
6404    pub trait Sealed {}
6405    impl Sealed for super::GroundingCertificate {}
6406    impl Sealed for super::LiftChainCertificate {}
6407    impl Sealed for super::InhabitanceCertificate {}
6408    impl Sealed for super::CompletenessCertificate {}
6409    impl Sealed for super::TransformCertificate {}
6410    impl Sealed for super::IsometryCertificate {}
6411    impl Sealed for super::InvolutionCertificate {}
6412    impl Sealed for super::GeodesicCertificate {}
6413    impl Sealed for super::MeasurementCertificate {}
6414    impl Sealed for super::BornRuleVerification {}
6415    impl Sealed for super::MultiplicationCertificate {}
6416    impl Sealed for super::PartitionCertificate {}
6417    impl Sealed for super::GenericImpossibilityWitness {}
6418    impl Sealed for super::InhabitanceImpossibilityWitness {}
6419    impl Sealed for super::PartitionProductWitness {}
6420    impl Sealed for super::PartitionCoproductWitness {}
6421    impl Sealed for super::CartesianProductWitness {}
6422}
6423
6424impl Certificate for GroundingCertificate {
6425    const IRI: &'static str = "https://uor.foundation/cert/GroundingCertificate";
6426    type Evidence = ();
6427}
6428
6429impl Certificate for LiftChainCertificate {
6430    const IRI: &'static str = "https://uor.foundation/cert/LiftChainCertificate";
6431    type Evidence = ChainAuditTrail;
6432}
6433
6434impl Certificate for InhabitanceCertificate {
6435    const IRI: &'static str = "https://uor.foundation/cert/InhabitanceCertificate";
6436    type Evidence = ();
6437}
6438
6439impl Certificate for CompletenessCertificate {
6440    const IRI: &'static str = "https://uor.foundation/cert/CompletenessCertificate";
6441    type Evidence = CompletenessAuditTrail;
6442}
6443
6444impl Certificate for TransformCertificate {
6445    const IRI: &'static str = "https://uor.foundation/cert/TransformCertificate";
6446    type Evidence = ();
6447}
6448
6449impl Certificate for IsometryCertificate {
6450    const IRI: &'static str = "https://uor.foundation/cert/IsometryCertificate";
6451    type Evidence = ();
6452}
6453
6454impl Certificate for InvolutionCertificate {
6455    const IRI: &'static str = "https://uor.foundation/cert/InvolutionCertificate";
6456    type Evidence = ();
6457}
6458
6459impl Certificate for GeodesicCertificate {
6460    const IRI: &'static str = "https://uor.foundation/cert/GeodesicCertificate";
6461    type Evidence = GeodesicEvidenceBundle;
6462}
6463
6464impl Certificate for MeasurementCertificate {
6465    const IRI: &'static str = "https://uor.foundation/cert/MeasurementCertificate";
6466    type Evidence = ();
6467}
6468
6469impl Certificate for BornRuleVerification {
6470    const IRI: &'static str = "https://uor.foundation/cert/BornRuleVerification";
6471    type Evidence = ();
6472}
6473
6474impl Certificate for MultiplicationCertificate {
6475    const IRI: &'static str = "https://uor.foundation/cert/MultiplicationCertificate";
6476    type Evidence = MultiplicationEvidence;
6477}
6478
6479impl Certificate for PartitionCertificate {
6480    const IRI: &'static str = "https://uor.foundation/cert/PartitionCertificate";
6481    type Evidence = ();
6482}
6483
6484impl Certificate for GenericImpossibilityWitness {
6485    const IRI: &'static str = "https://uor.foundation/cert/GenericImpossibilityCertificate";
6486    type Evidence = ();
6487}
6488
6489impl Certificate for InhabitanceImpossibilityWitness {
6490    const IRI: &'static str = "https://uor.foundation/cert/InhabitanceImpossibilityCertificate";
6491    type Evidence = ();
6492}
6493
6494/// Phase X.1: uniform mint interface over cert subclasses. Each
6495/// `Certificate` implementer that accepts `(witt_bits, ContentFingerprint)`
6496/// at construction time implements this trait. Lives inside a
6497/// `certify_const_mint` module so the symbol doesn't leak into top-level
6498/// documentation alongside `Certificate`.
6499pub(crate) mod certify_const_mint {
6500    use super::{Certificate, ContentFingerprint};
6501    pub trait MintWithLevelFingerprint: Certificate {
6502        fn mint_with_level_fingerprint(
6503            witt_bits: u16,
6504            content_fingerprint: ContentFingerprint,
6505        ) -> Self;
6506    }
6507    impl MintWithLevelFingerprint for super::GroundingCertificate {
6508        #[inline]
6509        fn mint_with_level_fingerprint(
6510            witt_bits: u16,
6511            content_fingerprint: ContentFingerprint,
6512        ) -> Self {
6513            super::GroundingCertificate::with_level_and_fingerprint_const(
6514                witt_bits,
6515                content_fingerprint,
6516            )
6517        }
6518    }
6519    impl MintWithLevelFingerprint for super::LiftChainCertificate {
6520        #[inline]
6521        fn mint_with_level_fingerprint(
6522            witt_bits: u16,
6523            content_fingerprint: ContentFingerprint,
6524        ) -> Self {
6525            super::LiftChainCertificate::with_level_and_fingerprint_const(
6526                witt_bits,
6527                content_fingerprint,
6528            )
6529        }
6530    }
6531    impl MintWithLevelFingerprint for super::InhabitanceCertificate {
6532        #[inline]
6533        fn mint_with_level_fingerprint(
6534            witt_bits: u16,
6535            content_fingerprint: ContentFingerprint,
6536        ) -> Self {
6537            super::InhabitanceCertificate::with_level_and_fingerprint_const(
6538                witt_bits,
6539                content_fingerprint,
6540            )
6541        }
6542    }
6543    impl MintWithLevelFingerprint for super::CompletenessCertificate {
6544        #[inline]
6545        fn mint_with_level_fingerprint(
6546            witt_bits: u16,
6547            content_fingerprint: ContentFingerprint,
6548        ) -> Self {
6549            super::CompletenessCertificate::with_level_and_fingerprint_const(
6550                witt_bits,
6551                content_fingerprint,
6552            )
6553        }
6554    }
6555    impl MintWithLevelFingerprint for super::MultiplicationCertificate {
6556        #[inline]
6557        fn mint_with_level_fingerprint(
6558            witt_bits: u16,
6559            content_fingerprint: ContentFingerprint,
6560        ) -> Self {
6561            super::MultiplicationCertificate::with_level_and_fingerprint_const(
6562                witt_bits,
6563                content_fingerprint,
6564            )
6565        }
6566    }
6567    impl MintWithLevelFingerprint for super::PartitionCertificate {
6568        #[inline]
6569        fn mint_with_level_fingerprint(
6570            witt_bits: u16,
6571            content_fingerprint: ContentFingerprint,
6572        ) -> Self {
6573            super::PartitionCertificate::with_level_and_fingerprint_const(
6574                witt_bits,
6575                content_fingerprint,
6576            )
6577        }
6578    }
6579    impl MintWithLevelFingerprint for super::TransformCertificate {
6580        #[inline]
6581        fn mint_with_level_fingerprint(
6582            witt_bits: u16,
6583            content_fingerprint: ContentFingerprint,
6584        ) -> Self {
6585            super::TransformCertificate::with_level_and_fingerprint_const(
6586                witt_bits,
6587                content_fingerprint,
6588            )
6589        }
6590    }
6591    impl MintWithLevelFingerprint for super::IsometryCertificate {
6592        #[inline]
6593        fn mint_with_level_fingerprint(
6594            witt_bits: u16,
6595            content_fingerprint: ContentFingerprint,
6596        ) -> Self {
6597            super::IsometryCertificate::with_level_and_fingerprint_const(
6598                witt_bits,
6599                content_fingerprint,
6600            )
6601        }
6602    }
6603    impl MintWithLevelFingerprint for super::InvolutionCertificate {
6604        #[inline]
6605        fn mint_with_level_fingerprint(
6606            witt_bits: u16,
6607            content_fingerprint: ContentFingerprint,
6608        ) -> Self {
6609            super::InvolutionCertificate::with_level_and_fingerprint_const(
6610                witt_bits,
6611                content_fingerprint,
6612            )
6613        }
6614    }
6615    impl MintWithLevelFingerprint for super::GeodesicCertificate {
6616        #[inline]
6617        fn mint_with_level_fingerprint(
6618            witt_bits: u16,
6619            content_fingerprint: ContentFingerprint,
6620        ) -> Self {
6621            super::GeodesicCertificate::with_level_and_fingerprint_const(
6622                witt_bits,
6623                content_fingerprint,
6624            )
6625        }
6626    }
6627    impl MintWithLevelFingerprint for super::MeasurementCertificate {
6628        #[inline]
6629        fn mint_with_level_fingerprint(
6630            witt_bits: u16,
6631            content_fingerprint: ContentFingerprint,
6632        ) -> Self {
6633            super::MeasurementCertificate::with_level_and_fingerprint_const(
6634                witt_bits,
6635                content_fingerprint,
6636            )
6637        }
6638    }
6639    impl MintWithLevelFingerprint for super::BornRuleVerification {
6640        #[inline]
6641        fn mint_with_level_fingerprint(
6642            witt_bits: u16,
6643            content_fingerprint: ContentFingerprint,
6644        ) -> Self {
6645            super::BornRuleVerification::with_level_and_fingerprint_const(
6646                witt_bits,
6647                content_fingerprint,
6648            )
6649        }
6650    }
6651}
6652
6653/// v0.2.2 W11: parametric carrier for any foundation-supplied certificate.
6654/// Replaces the v0.2.1 per-class shim duplication. The `Certificate` trait
6655/// is sealed and the `_private` field prevents external construction; only
6656/// the foundation's pipeline / resolver paths produce `Certified<C>` values.
6657#[derive(Debug, Clone)]
6658pub struct Certified<C: Certificate> {
6659    /// The certificate kind value carried by this wrapper.
6660    inner: C,
6661    /// Phase A.1: the foundation-internal two-clock value read at witness issuance.
6662    uor_time: UorTime,
6663    /// Prevents external construction.
6664    _private: (),
6665}
6666
6667impl<C: Certificate> Certified<C> {
6668    /// Returns a reference to the carried certificate kind value.
6669    #[inline]
6670    #[must_use]
6671    pub const fn certificate(&self) -> &C {
6672        &self.inner
6673    }
6674
6675    /// Returns the ontology IRI of this certificate's kind.
6676    #[inline]
6677    #[must_use]
6678    pub const fn iri(&self) -> &'static str {
6679        C::IRI
6680    }
6681
6682    /// Phase A.1: the foundation-internal two-clock value read at witness issuance.
6683    /// Maps `rewrite_steps` to `derivation:stepCount` and `landauer_nats` to
6684    /// `observable:LandauerCost`. Content-deterministic: same computation →
6685    /// same `UorTime`. Composable against wall-clock bounds via
6686    /// [`UorTime::min_wall_clock`] and a downstream-supplied `Calibration`.
6687    #[inline]
6688    #[must_use]
6689    pub const fn uor_time(&self) -> UorTime {
6690        self.uor_time
6691    }
6692
6693    /// Crate-internal constructor. Reachable only from the pipeline / resolver paths.
6694    /// The `uor_time` is computed deterministically from the certificate kind's `IRI`
6695    /// length: the rewrite-step count is the IRI byte length, and the Landauer cost
6696    /// is `rewrite_steps × ln 2` (the Landauer-temperature cost of traversing that
6697    /// many orthogonal states). Two `Certified<C>` values with the same `C` share the
6698    /// same `UorTime`, preserving content-determinism across pipeline invocations.
6699    #[inline]
6700    #[allow(dead_code)]
6701    pub(crate) const fn new(inner: C) -> Self {
6702        // IRI length is the deterministic proxy for the cert class's structural
6703        // complexity. Phase D threads real resolver-counted steps through.
6704        let steps = C::IRI.len() as u64;
6705        let landauer = LandauerBudget::new((steps as f64) * core::f64::consts::LN_2);
6706        let uor_time = UorTime::new(landauer, steps);
6707        Self {
6708            inner,
6709            uor_time,
6710            _private: (),
6711        }
6712    }
6713}
6714
6715/// v0.2.2 Phase C.4: call-site context consumed by the multiplication
6716/// resolver. Carries the stack budget (`linear:stackBudgetBytes`), the
6717/// const-eval regime, and the limb count of the operand's `Limbs<N>`
6718/// backing. The resolver picks the cost-optimal Toom-Cook splitting
6719/// factor R based on this context.
6720#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6721pub struct MulContext {
6722    /// Stack budget available at the call site, in bytes. Zero is
6723    /// inadmissible; the resolver returns an impossibility witness.
6724    pub stack_budget_bytes: u64,
6725    /// True if this call is in const-eval context. In const-eval, only
6726    /// R = 1 (schoolbook) is admissible because deeper recursion blows
6727    /// the const-eval depth limit.
6728    pub const_eval: bool,
6729    /// Number of 64-bit limbs in the operand's `Limbs<N>` backing.
6730    /// Schoolbook cost is proportional to `N^2`; Karatsuba cost is
6731    /// proportional to `3 · (N/2)^2`. For native-backed levels
6732    /// (W8..W128), pass the equivalent limb count.
6733    pub limb_count: usize,
6734}
6735
6736impl MulContext {
6737    /// Construct a new `MulContext` for the call site.
6738    #[inline]
6739    #[must_use]
6740    pub const fn new(stack_budget_bytes: u64, const_eval: bool, limb_count: usize) -> Self {
6741        Self {
6742            stack_budget_bytes,
6743            const_eval,
6744            limb_count,
6745        }
6746    }
6747}
6748
6749/// v0.2.2 Phase C.4: evidence returned alongside a `MultiplicationCertificate`.
6750/// The certificate is a sealed handle; its evidence (chosen splitting factor,
6751/// sub-multiplication count, accumulated Landauer cost in nats) lives here.
6752#[derive(Debug, Clone, Copy, PartialEq)]
6753pub struct MultiplicationEvidence {
6754    splitting_factor: u32,
6755    sub_multiplication_count: u32,
6756    landauer_cost_nats_bits: u64,
6757}
6758
6759impl MultiplicationEvidence {
6760    /// The Toom-Cook splitting factor R chosen by the resolver.
6761    #[inline]
6762    #[must_use]
6763    pub const fn splitting_factor(&self) -> u32 {
6764        self.splitting_factor
6765    }
6766
6767    /// The recursive sub-multiplication count for one multiplication.
6768    #[inline]
6769    #[must_use]
6770    pub const fn sub_multiplication_count(&self) -> u32 {
6771        self.sub_multiplication_count
6772    }
6773
6774    /// Accumulated Landauer cost in nats, priced per `op:OA_5`. Returned as the IEEE-754 bit pattern; project to `H::Decimal` at use sites via `<H::Decimal as DecimalTranscendental>::from_bits(_)`.
6775    #[inline]
6776    #[must_use]
6777    pub const fn landauer_cost_nats_bits(&self) -> u64 {
6778        self.landauer_cost_nats_bits
6779    }
6780}
6781
6782impl MultiplicationCertificate {
6783    /// v0.2.2 T6.7: construct a `MultiplicationCertificate` with substrate-
6784    /// computed evidence. Crate-internal only; downstream obtains certificates
6785    /// via `resolver::multiplication::certify::<H>`.
6786    #[inline]
6787    #[must_use]
6788    pub(crate) fn with_evidence(
6789        splitting_factor: u32,
6790        sub_multiplication_count: u32,
6791        landauer_cost_nats_bits: u64,
6792        content_fingerprint: ContentFingerprint,
6793    ) -> Self {
6794        let _ = MultiplicationEvidence {
6795            splitting_factor,
6796            sub_multiplication_count,
6797            landauer_cost_nats_bits,
6798        };
6799        Self::with_level_and_fingerprint_const(32, content_fingerprint)
6800    }
6801}
6802
6803/// v0.2.2 Phase E: maximum simplicial dimension tracked by the
6804/// constraint-nerve Betti-numbers vector. The bound is 8 for the
6805/// currently-supported WittLevel set per the existing partition:FreeRank
6806/// capacity properties; the constant is `pub` (part of the public-API
6807/// snapshot) so future expansions require explicit review.
6808/// Wiki ADR-037: a foundation-fixed conservative default for
6809/// [`crate::HostBounds::BETTI_DIMENSION_MAX`].
6810pub const MAX_BETTI_DIMENSION: usize = 8;
6811
6812/// Sealed newtype for the grounding completion ratio σ ∈
6813/// [0.0, 1.0]. σ = 1 indicates the ground state; σ = 0 the
6814/// unbound state. Backs observable:GroundingSigma. Phase 9: parametric over
6815/// the host's `H::Decimal` precision.
6816#[derive(Debug)]
6817pub struct SigmaValue<H: HostTypes = crate::DefaultHostTypes> {
6818    value: H::Decimal,
6819    _phantom: core::marker::PhantomData<H>,
6820    _sealed: (),
6821}
6822
6823impl<H: HostTypes> Copy for SigmaValue<H> {}
6824impl<H: HostTypes> Clone for SigmaValue<H> {
6825    #[inline]
6826    fn clone(&self) -> Self {
6827        *self
6828    }
6829}
6830impl<H: HostTypes> PartialEq for SigmaValue<H> {
6831    #[inline]
6832    fn eq(&self, other: &Self) -> bool {
6833        self.value == other.value
6834    }
6835}
6836
6837impl<H: HostTypes> SigmaValue<H> {
6838    /// Returns the stored σ value in the range [0.0, 1.0].
6839    #[inline]
6840    #[must_use]
6841    pub const fn value(&self) -> H::Decimal {
6842        self.value
6843    }
6844
6845    /// Crate-internal constructor. Caller guarantees `value` is in
6846    /// the closed range [0.0, 1.0] and is not NaN.
6847    #[inline]
6848    #[must_use]
6849    #[allow(dead_code)]
6850    pub(crate) const fn new_unchecked(value: H::Decimal) -> Self {
6851        Self {
6852            value,
6853            _phantom: core::marker::PhantomData,
6854            _sealed: (),
6855        }
6856    }
6857}
6858
6859/// Phase A.3: sealed stratum coordinate (the v₂ valuation of a `Datum` at level `L`).
6860/// Backs `schema:stratum`. The value is non-negative and bounded by `L`'s `bit_width`
6861/// per the ontology's `nonNegativeInteger` range. Constructed only by foundation code
6862/// at grounding time; no public constructor — the `Stratum<W8>` / `Stratum<W16>` / ...
6863/// type family is closed under the WittLevel individual set.
6864#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6865pub struct Stratum<L> {
6866    value: u32,
6867    _level: PhantomData<L>,
6868    _sealed: (),
6869}
6870
6871impl<L> Stratum<L> {
6872    /// Returns the raw v₂ valuation as a `u32`. The value is bounded by `L`'s bit_width.
6873    #[inline]
6874    #[must_use]
6875    pub const fn as_u32(&self) -> u32 {
6876        self.value
6877    }
6878
6879    /// Crate-internal constructor. Reachable only from grounding-time minting.
6880    #[inline]
6881    #[must_use]
6882    #[allow(dead_code)]
6883    pub(crate) const fn new(value: u32) -> Self {
6884        Self {
6885            value,
6886            _level: PhantomData,
6887            _sealed: (),
6888        }
6889    }
6890}
6891
6892/// Phase A.4: sealed carrier for `observable:d_delta_metric` (metric incompatibility).
6893#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6894pub struct DDeltaMetric {
6895    value: i64,
6896    _sealed: (),
6897}
6898
6899impl DDeltaMetric {
6900    /// Returns the signed incompatibility magnitude (ring distance minus Hamming distance).
6901    #[inline]
6902    #[must_use]
6903    pub const fn as_i64(&self) -> i64 {
6904        self.value
6905    }
6906
6907    /// Crate-internal constructor.
6908    #[inline]
6909    #[must_use]
6910    #[allow(dead_code)]
6911    pub(crate) const fn new(value: i64) -> Self {
6912        Self { value, _sealed: () }
6913    }
6914}
6915
6916/// Phase A.4: sealed carrier for `observable:euler_metric` (Euler characteristic).
6917#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6918pub struct EulerMetric {
6919    value: i64,
6920    _sealed: (),
6921}
6922
6923impl EulerMetric {
6924    /// Returns the Euler characteristic χ of the constraint nerve.
6925    #[inline]
6926    #[must_use]
6927    pub const fn as_i64(&self) -> i64 {
6928        self.value
6929    }
6930
6931    /// Crate-internal constructor.
6932    #[inline]
6933    #[must_use]
6934    #[allow(dead_code)]
6935    pub(crate) const fn new(value: i64) -> Self {
6936        Self { value, _sealed: () }
6937    }
6938}
6939
6940/// Phase A.4: sealed carrier for `observable:residual_metric` (free-site count r).
6941#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6942pub struct ResidualMetric {
6943    value: u32,
6944    _sealed: (),
6945}
6946
6947impl ResidualMetric {
6948    /// Returns the free-site count r at grounding time.
6949    #[inline]
6950    #[must_use]
6951    pub const fn as_u32(&self) -> u32 {
6952        self.value
6953    }
6954
6955    /// Crate-internal constructor.
6956    #[inline]
6957    #[must_use]
6958    #[allow(dead_code)]
6959    pub(crate) const fn new(value: u32) -> Self {
6960        Self { value, _sealed: () }
6961    }
6962}
6963
6964/// Phase A.4: sealed carrier for `observable:betti_metric` (Betti-number vector).
6965/// Fixed-capacity `[u32; MAX_BETTI_DIMENSION]` backing; no heap.
6966#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6967pub struct BettiMetric {
6968    values: [u32; MAX_BETTI_DIMENSION],
6969    _sealed: (),
6970}
6971
6972impl BettiMetric {
6973    /// Returns the Betti-number vector as a fixed-size array reference.
6974    #[inline]
6975    #[must_use]
6976    pub const fn as_array(&self) -> &[u32; MAX_BETTI_DIMENSION] {
6977        &self.values
6978    }
6979
6980    /// Returns the individual Betti number βₖ for dimension k.
6981    /// Returns 0 when k >= MAX_BETTI_DIMENSION.
6982    #[inline]
6983    #[must_use]
6984    pub const fn beta(&self, k: usize) -> u32 {
6985        if k < MAX_BETTI_DIMENSION {
6986            self.values[k]
6987        } else {
6988            0
6989        }
6990    }
6991
6992    /// Crate-internal constructor.
6993    #[inline]
6994    #[must_use]
6995    #[allow(dead_code)]
6996    pub(crate) const fn new(values: [u32; MAX_BETTI_DIMENSION]) -> Self {
6997        Self {
6998            values,
6999            _sealed: (),
7000        }
7001    }
7002}
7003
7004/// Maximum site count of the Jacobian row per Datum at any supported
7005/// WittLevel. Sourced from the partition:FreeRank capacity bound.
7006/// v0.2.2 T2.6 (cleanup): reduced from 64 to 8 to keep `Grounded` under
7007/// the 256-byte size budget enforced by `phantom_tag::grounded_sealed_field_count_unchanged`.
7008/// 8 matches `MAX_BETTI_DIMENSION` and is sufficient for the v0.2.2 partition rank set.
7009/// Wiki ADR-037: a foundation-fixed conservative default for
7010/// [`crate::HostBounds::JACOBIAN_SITES_MAX`].
7011pub const JACOBIAN_MAX_SITES: usize = 8;
7012
7013/// v0.2.2 Phase E: sealed Jacobian row carrier, parametric over the
7014/// WittLevel marker. Fixed-size `[i64; JACOBIAN_MAX_SITES]` backing; no
7015/// heap. The row records the per-site partial derivative of the ring
7016/// operation that produced the Datum. Backs observable:JacobianObservable.
7017#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7018pub struct JacobianMetric<L> {
7019    entries: [i64; JACOBIAN_MAX_SITES],
7020    len: u16,
7021    _level: PhantomData<L>,
7022    _sealed: (),
7023}
7024
7025impl<L> JacobianMetric<L> {
7026    /// Construct a zeroed Jacobian row with the given active length.
7027    #[inline]
7028    #[must_use]
7029    #[allow(dead_code)]
7030    pub(crate) const fn zero(len: u16) -> Self {
7031        Self {
7032            entries: [0i64; JACOBIAN_MAX_SITES],
7033            len,
7034            _level: PhantomData,
7035            _sealed: (),
7036        }
7037    }
7038
7039    /// v0.2.2 T2.6 (cleanup): crate-internal constructor used by the
7040    /// BaseMetric accessor on `Grounded` to return a `JacobianMetric`
7041    /// backed by stored field values.
7042    #[inline]
7043    #[must_use]
7044    #[allow(dead_code)]
7045    pub(crate) const fn from_entries(entries: [i64; JACOBIAN_MAX_SITES], len: u16) -> Self {
7046        Self {
7047            entries,
7048            len,
7049            _level: PhantomData,
7050            _sealed: (),
7051        }
7052    }
7053
7054    /// Access the Jacobian row entries.
7055    #[inline]
7056    #[must_use]
7057    pub const fn entries(&self) -> &[i64; JACOBIAN_MAX_SITES] {
7058        &self.entries
7059    }
7060
7061    /// Number of active sites (the row's logical length).
7062    #[inline]
7063    #[must_use]
7064    pub const fn len(&self) -> u16 {
7065        self.len
7066    }
7067
7068    /// Whether the Jacobian row is empty.
7069    #[inline]
7070    #[must_use]
7071    pub const fn is_empty(&self) -> bool {
7072        self.len == 0
7073    }
7074}
7075
7076/// v0.2.2 Phase E: sealed Partition component classification.
7077/// Closed enumeration mirroring the partition:PartitionComponent
7078/// ontology class.
7079#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7080#[non_exhaustive]
7081pub enum PartitionComponent {
7082    /// The irreducible component.
7083    Irreducible,
7084    /// The reducible component.
7085    Reducible,
7086    /// The unit component.
7087    Units,
7088    /// The exterior component.
7089    Exterior,
7090}
7091
7092/// Sealed marker trait identifying type:ConstrainedType subclasses that may
7093/// appear as the parameter of `Grounded<T>`.
7094/// Per wiki ADR-027, the seal is the same `__sdk_seal::Sealed` supertrait
7095/// foundation uses for `FoundationClosed`, `PrismModel`, and
7096/// `IntoBindingValue`: only foundation and the SDK shape macros emit
7097/// impls. The foundation-sanctioned identity output `ConstrainedTypeInput`
7098/// retains its direct impl; application authors declaring custom Output
7099/// shapes invoke the `output_shape!` SDK macro, which emits
7100/// `__sdk_seal::Sealed`, `GroundedShape`, `IntoBindingValue`, and
7101/// `ConstrainedTypeShape` together.
7102pub trait GroundedShape: crate::pipeline::__sdk_seal::Sealed {}
7103impl GroundedShape for ConstrainedTypeInput {}
7104
7105/// v0.2.2 T4.2: sealed content-addressed handle.
7106/// Wraps a 128-bit identity used for `BindingsTable` lookups and as a
7107/// compact identity handle for `Grounded` values. The underlying `u128`
7108/// is visible via `as_u128()` for interop. Distinct from
7109/// `ContentFingerprint` (the parametric-width fingerprint computed by
7110/// the substrate `Hasher` — see T5.C3.d below): `ContentAddress` is a
7111/// fixed 16-byte sortable handle, while `ContentFingerprint` is the full
7112/// substrate-computed identity that round-trips through `verify_trace`.
7113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7114pub struct ContentAddress {
7115    raw: u128,
7116    _sealed: (),
7117}
7118
7119impl ContentAddress {
7120    /// The zero content address. Used as the "unset" placeholder in
7121    /// `BindingsTable` lookups, the default state of an uninitialised
7122    /// `Grounded::unit_address`, and the initial seed of replay folds.
7123    #[inline]
7124    #[must_use]
7125    pub const fn zero() -> Self {
7126        Self {
7127            raw: 0,
7128            _sealed: (),
7129        }
7130    }
7131
7132    /// Returns the underlying 128-bit content hash.
7133    #[inline]
7134    #[must_use]
7135    pub const fn as_u128(&self) -> u128 {
7136        self.raw
7137    }
7138
7139    /// Whether this content address is the zero handle.
7140    #[inline]
7141    #[must_use]
7142    pub const fn is_zero(&self) -> bool {
7143        self.raw == 0
7144    }
7145
7146    /// v0.2.2 T5.C1: public ctor. Promoted from `pub(crate)` in T5 so
7147    /// downstream tests can construct deterministic `ContentAddress` values
7148    /// for fixture data without going through the foundation pipeline.
7149    #[inline]
7150    #[must_use]
7151    pub const fn from_u128(raw: u128) -> Self {
7152        Self { raw, _sealed: () }
7153    }
7154
7155    /// v0.2.2 Phase P.3: construct a `ContentAddress` from a `u64` FNV-1a fingerprint
7156    /// by right-padding the value into the 128-bit address space. Used by
7157    /// `Binding::to_binding_entry` to bridge the `Binding.content_address: u64`
7158    /// carrier to the `BindingEntry.address: ContentAddress` (`u128`-backed) shape.
7159    /// The lift is `raw = (fingerprint as u128) << 64` — upper 64 bits carry the
7160    /// FNV-1a value; lower 64 bits are zero. Content-deterministic; round-trips via
7161    /// `ContentAddress::as_u128() >> 64` back to the original `u64`.
7162    #[inline]
7163    #[must_use]
7164    pub const fn from_u64_fingerprint(fingerprint: u64) -> Self {
7165        Self {
7166            raw: (fingerprint as u128) << 64,
7167            _sealed: (),
7168        }
7169    }
7170}
7171
7172impl Default for ContentAddress {
7173    #[inline]
7174    fn default() -> Self {
7175        Self::zero()
7176    }
7177}
7178
7179/// Trace wire-format identifier. Per the wiki's ADR-018, wire-format
7180/// identifiers are explicitly carved out of the `HostBounds` rule because
7181/// cross-implementation interop requires a single shared format identifier.
7182/// Increment when the layout changes (event ordering, trailing fields,
7183/// primitive-op discriminant table, certificate-kind discriminant table).
7184/// Pinned by the `rust/trace_byte_layout_pinned` conformance validator.
7185pub const TRACE_REPLAY_FORMAT_VERSION: u16 = 10;
7186
7187/// v0.2.2 T5: pluggable content hasher with parametric output width.
7188/// The foundation does not ship an implementation. Downstream substrate
7189/// consumers (PRISM, application crates) supply their own `Hasher` impl
7190/// — BLAKE3, SHA-256, SHA-512, BLAKE2b, SipHash 2-4, FNV-1a, or any
7191/// other byte-stream hash whose output width satisfies the foundation's
7192/// derived collision-bound minimum.
7193/// # Foundation recommendation
7194/// The foundation **recommends BLAKE3** as the default substrate hash for
7195/// production deployments. BLAKE3 is fast, well-audited, has no known
7196/// cryptographic weaknesses, supports parallel and SIMD-accelerated
7197/// implementations, and has a flexible output length. PRISM ships a BLAKE3
7198/// `Hasher` impl as its production substrate; application crates should
7199/// use it unless they have a specific reason to deviate.
7200/// The recommendation is non-binding: any conforming `Hasher` impl works
7201/// with the foundation's pipeline and verify path. The foundation never
7202/// invokes a hash function itself, so the choice is fully a downstream
7203/// decision.
7204/// # Architecture
7205/// The architectural shape mirrors `Calibration`: the foundation defines
7206/// the abstract quantity (`ContentFingerprint`) and the substitution point
7207/// (`Hasher`); downstream provides the concrete substrate AND chooses the
7208/// output width within the foundation's correctness budget.
7209/// # Required laws
7210/// 1. **Width-in-budget**: `OUTPUT_BYTES` must be in
7211///    `[<B as HostBounds>::FINGERPRINT_MIN_BYTES, FP_MAX]` where `FP_MAX`
7212///    is the const-generic carrying `<B as HostBounds>::FINGERPRINT_MAX_BYTES`.
7213///    Enforced at codegen time via a `const _: () = assert!(...)` block
7214///    emitted inside every `pipeline::run::<T, _, H>` body.
7215/// 2. **Determinism**: identical byte sequences produce bit-identical outputs
7216///    across program runs, builds, target architectures, and rustc versions.
7217/// 3. **Sensitivity**: hashing two byte sequences that differ in any byte
7218///    produces two distinct outputs with probability bounded by the hasher's
7219///    documented collision rate.
7220/// 4. **No interior mutability**: `fold_byte` consumes `self` and returns a
7221///    new state. Impls that depend on hidden mutable state violate the contract.
7222/// # Example
7223/// ```
7224/// use uor_foundation::enforcement::Hasher;
7225/// /// Minimal 128-bit (16-byte) FNV-1a substrate — two 64-bit lanes.
7226/// #[derive(Clone, Copy)]
7227/// pub struct Fnv1a16 { a: u64, b: u64 }
7228/// impl Hasher for Fnv1a16 {
7229///     const OUTPUT_BYTES: usize = 16;
7230///     fn initial() -> Self {
7231///         Self { a: 0xcbf29ce484222325, b: 0x84222325cbf29ce4 }
7232///     }
7233///     fn fold_byte(mut self, x: u8) -> Self {
7234///         self.a ^= x as u64;
7235///         self.a = self.a.wrapping_mul(0x100000001b3);
7236///         self.b ^= (x as u64).rotate_left(8);
7237///         self.b = self.b.wrapping_mul(0x100000001b3);
7238///         self
7239///     }
7240///     fn finalize(self) -> [u8; 32] {
7241///         let mut buf = [0u8; 32];
7242///         buf[..8].copy_from_slice(&self.a.to_be_bytes());
7243///         buf[8..16].copy_from_slice(&self.b.to_be_bytes());
7244///         buf
7245///     }
7246/// }
7247/// ```
7248/// Above, `Hasher` is reached through its default const-generic
7249/// `<FP_MAX = 32>` (the conventional 32-byte fingerprint width).
7250/// Applications that select a different `HostBounds` impl write
7251/// `impl Hasher<{<MyBounds as HostBounds>::FINGERPRINT_MAX_BYTES}> for MyHasher`.
7252pub trait Hasher<const FP_MAX: usize = 32> {
7253    /// Active output width in bytes. Must lie within the bounds
7254    /// the application's selected `HostBounds` declares —
7255    /// `[<B as HostBounds>::FINGERPRINT_MIN_BYTES, FP_MAX]`.
7256    const OUTPUT_BYTES: usize;
7257
7258    /// Initial hasher state.
7259    fn initial() -> Self;
7260
7261    /// Fold a single byte into the running state.
7262    #[must_use]
7263    fn fold_byte(self, b: u8) -> Self;
7264
7265    /// Fold a slice of bytes (default impl: byte-by-byte).
7266    #[inline]
7267    #[must_use]
7268    fn fold_bytes(mut self, bytes: &[u8]) -> Self
7269    where
7270        Self: Sized,
7271    {
7272        let mut i = 0;
7273        while i < bytes.len() {
7274            self = self.fold_byte(bytes[i]);
7275            i += 1;
7276        }
7277        self
7278    }
7279
7280    /// Finalize into the canonical max-width buffer of `FP_MAX` bytes.
7281    /// Bytes `0..OUTPUT_BYTES` carry the hash result; bytes
7282    /// `OUTPUT_BYTES..FP_MAX` MUST be zero.
7283    fn finalize(self) -> [u8; FP_MAX];
7284}
7285
7286/// ADR-030 adapter: wrap any [`Hasher`] impl as an
7287/// [`crate::pipeline::AxisExtension`]. The lone supported kernel id
7288/// is [`HashAxis::KERNEL_HASH`] = 0, which folds the input bytes
7289/// through the wrapped Hasher and writes the first `OUTPUT_BYTES`
7290/// digest bytes to the caller-provided buffer.
7291#[derive(Debug, Clone, Copy)]
7292pub struct HashAxis<H: Hasher>(core::marker::PhantomData<H>);
7293
7294impl<H: Hasher> HashAxis<H> {
7295    /// Canonical kernel id for the hash operation. The closure-body
7296    /// grammar G19 form `hash(input)` lowers to
7297    /// `Term::AxisInvocation { axis_index: 0, kernel_id: HashAxis::KERNEL_HASH, input_index }`.
7298    pub const KERNEL_HASH: u32 = 0;
7299}
7300
7301impl<H: Hasher> crate::pipeline::__sdk_seal::Sealed for HashAxis<H> {}
7302impl<const INLINE_BYTES: usize, H: Hasher> crate::pipeline::SubstrateTermBody<INLINE_BYTES>
7303    for HashAxis<H>
7304{
7305    fn body_arena() -> &'static [Term<'static, INLINE_BYTES>] {
7306        &[]
7307    }
7308}
7309impl<const INLINE_BYTES: usize, H: Hasher> crate::pipeline::AxisExtension<INLINE_BYTES>
7310    for HashAxis<H>
7311{
7312    const AXIS_ADDRESS: &'static str = "https://uor.foundation/axis/HashAxis";
7313    const MAX_OUTPUT_BYTES: usize = <H as Hasher>::OUTPUT_BYTES;
7314    fn dispatch_kernel(
7315        kernel_id: u32,
7316        input: &[u8],
7317        out: &mut [u8],
7318    ) -> Result<usize, ShapeViolation> {
7319        if kernel_id != Self::KERNEL_HASH {
7320            return Err(ShapeViolation {
7321                shape_iri: "https://uor.foundation/axis/HashAxis",
7322                constraint_iri: "https://uor.foundation/axis/HashAxis/kernelId",
7323                property_iri: "https://uor.foundation/axis/kernelId",
7324                expected_range: "https://uor.foundation/axis/HashAxis/KERNEL_HASH",
7325                min_count: 0,
7326                max_count: 1,
7327                kind: crate::ViolationKind::ValueCheck,
7328            });
7329        }
7330        let mut hasher = <H as Hasher>::initial();
7331        hasher = hasher.fold_bytes(input);
7332        let digest = hasher.finalize();
7333        let n = <H as Hasher>::OUTPUT_BYTES.min(out.len()).min(digest.len());
7334        let mut i = 0;
7335        while i < n {
7336            out[i] = digest[i];
7337            i += 1;
7338        }
7339        Ok(n)
7340    }
7341}
7342
7343/// Sealed parametric content fingerprint.
7344/// Wraps a fixed-capacity byte buffer of `FP_MAX` bytes plus the
7345/// active width in bytes. `FP_MAX` is the const-generic that carries
7346/// the application's selected `HostBounds::FINGERPRINT_MAX_BYTES`
7347/// (default = 32, the conventional fingerprint width). The active width
7348/// is set by the producing `Hasher::OUTPUT_BYTES` and recorded so
7349/// downstream can distinguish "this is a 128-bit fingerprint" from
7350/// "this is a 256-bit fingerprint" without inspecting trailing zeros.
7351/// Equality is bit-equality on the full buffer + width tag, so two
7352/// fingerprints from different hashers (different widths) are never
7353/// equal even if their leading bytes happen to coincide. This prevents
7354/// silent collisions when downstream consumers mix substrate hashers.
7355#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7356pub struct ContentFingerprint<const FP_MAX: usize = 32> {
7357    bytes: [u8; FP_MAX],
7358    width_bytes: u8,
7359    _sealed: (),
7360}
7361
7362impl<const FP_MAX: usize> ContentFingerprint<FP_MAX> {
7363    /// Crate-internal zero placeholder. Used internally as the
7364    /// `Trace::empty()` field initializer and the `Default` impl. Not
7365    /// publicly constructible; downstream that needs a `ContentFingerprint`
7366    /// constructs one via `Hasher::finalize()` followed by `from_buffer()`.
7367    #[inline]
7368    #[must_use]
7369    #[allow(dead_code)]
7370    pub(crate) const fn zero() -> Self {
7371        Self {
7372            bytes: [0u8; FP_MAX],
7373            width_bytes: 0,
7374            _sealed: (),
7375        }
7376    }
7377
7378    /// Whether this fingerprint is the all-zero placeholder.
7379    #[inline]
7380    #[must_use]
7381    pub const fn is_zero(&self) -> bool {
7382        self.width_bytes == 0
7383    }
7384
7385    /// Active width in bytes (set by the producing hasher).
7386    #[inline]
7387    #[must_use]
7388    pub const fn width_bytes(&self) -> u8 {
7389        self.width_bytes
7390    }
7391
7392    /// Active width in bits (`width_bytes * 8`).
7393    #[inline]
7394    #[must_use]
7395    pub const fn width_bits(&self) -> u16 {
7396        (self.width_bytes as u16) * 8
7397    }
7398
7399    /// The full buffer. Bytes `0..width_bytes` are the hash; bytes
7400    /// `width_bytes..FP_MAX` are zero.
7401    #[inline]
7402    #[must_use]
7403    pub const fn as_bytes(&self) -> &[u8; FP_MAX] {
7404        &self.bytes
7405    }
7406
7407    /// Construct a fingerprint from a hasher's finalize buffer + width tag.
7408    /// Production paths reach this via `pipeline::run::<T, _, H>`; test
7409    /// paths via the `__test_helpers` back-door.
7410    #[inline]
7411    #[must_use]
7412    pub const fn from_buffer(bytes: [u8; FP_MAX], width_bytes: u8) -> Self {
7413        Self {
7414            bytes,
7415            width_bytes,
7416            _sealed: (),
7417        }
7418    }
7419}
7420
7421impl<const FP_MAX: usize> Default for ContentFingerprint<FP_MAX> {
7422    #[inline]
7423    fn default() -> Self {
7424        Self::zero()
7425    }
7426}
7427
7428/// v0.2.2 T5: stable u8 discriminant for `PrimitiveOp`. Locked to the
7429/// codegen output order; do not reorder `PrimitiveOp` variants without
7430/// bumping `TRACE_REPLAY_FORMAT_VERSION`. Folded into the canonical byte
7431/// layout of every `TraceEvent` so substrate hashers produce stable
7432/// fingerprints across builds.
7433#[inline]
7434#[must_use]
7435pub const fn primitive_op_discriminant(op: crate::PrimitiveOp) -> u8 {
7436    match op {
7437        crate::PrimitiveOp::Neg => 0,
7438        crate::PrimitiveOp::Bnot => 1,
7439        crate::PrimitiveOp::Succ => 2,
7440        crate::PrimitiveOp::Pred => 3,
7441        crate::PrimitiveOp::Add => 4,
7442        crate::PrimitiveOp::Sub => 5,
7443        crate::PrimitiveOp::Mul => 6,
7444        crate::PrimitiveOp::Xor => 7,
7445        crate::PrimitiveOp::And => 8,
7446        crate::PrimitiveOp::Or => 9,
7447        // ADR-013/TR-08 substrate amendment: byte-level ops 10..15.
7448        crate::PrimitiveOp::Le => 10,
7449        crate::PrimitiveOp::Lt => 11,
7450        crate::PrimitiveOp::Ge => 12,
7451        crate::PrimitiveOp::Gt => 13,
7452        crate::PrimitiveOp::Concat => 14,
7453        // ADR-053 substrate amendment: ring-axis arithmetic completion.
7454        crate::PrimitiveOp::Div => 15,
7455        crate::PrimitiveOp::Mod => 16,
7456        crate::PrimitiveOp::Pow => 17,
7457    }
7458}
7459
7460/// v0.2.2 T5: stable u8 discriminant tag distinguishing the certificate
7461/// kinds the foundation pipeline mints. Folded into the trailing byte of
7462/// every canonical digest so two certificates over the same source unit
7463/// but of different kinds produce distinct fingerprints. Locked at v0.2.2;
7464/// reordering or inserting variants requires bumping
7465/// `TRACE_REPLAY_FORMAT_VERSION`.
7466#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7467#[non_exhaustive]
7468pub enum CertificateKind {
7469    /// Cert minted by `pipeline::run` and `run_const` (retained for
7470    /// `run_grounding_aware`).
7471    Grounding,
7472    /// Cert minted by `certify_tower_completeness_const`.
7473    TowerCompleteness,
7474    /// Cert minted by `certify_incremental_completeness_const`.
7475    IncrementalCompleteness,
7476    /// Cert minted by `certify_inhabitance_const` / `run_inhabitance`.
7477    Inhabitance,
7478    /// Cert minted by `certify_multiplication_const`.
7479    Multiplication,
7480    /// Cert minted by `resolver::two_sat_decider::certify`.
7481    TwoSat,
7482    /// Cert minted by `resolver::horn_sat_decider::certify`.
7483    HornSat,
7484    /// Cert minted by `resolver::residual_verdict::certify`.
7485    ResidualVerdict,
7486    /// Cert minted by `resolver::canonical_form::certify`.
7487    CanonicalForm,
7488    /// Cert minted by `resolver::type_synthesis::certify`.
7489    TypeSynthesis,
7490    /// Cert minted by `resolver::homotopy::certify`.
7491    Homotopy,
7492    /// Cert minted by `resolver::monodromy::certify`.
7493    Monodromy,
7494    /// Cert minted by `resolver::moduli::certify`.
7495    Moduli,
7496    /// Cert minted by `resolver::jacobian_guided::certify`.
7497    JacobianGuided,
7498    /// Cert minted by `resolver::evaluation::certify`.
7499    Evaluation,
7500    /// Cert minted by `resolver::session::certify`.
7501    Session,
7502    /// Cert minted by `resolver::superposition::certify`.
7503    Superposition,
7504    /// Cert minted by `resolver::measurement::certify`.
7505    Measurement,
7506    /// Cert minted by `resolver::witt_level_resolver::certify`.
7507    WittLevel,
7508    /// Cert minted by `resolver::dihedral_factorization::certify`.
7509    DihedralFactorization,
7510    /// Cert minted by `resolver::completeness::certify`.
7511    Completeness,
7512    /// Cert minted by `resolver::geodesic_validator::certify`.
7513    GeodesicValidator,
7514}
7515
7516/// v0.2.2 T5: stable u8 discriminant for `CertificateKind`. Folded into
7517/// the trailing byte of canonical digests via the `*Digest` types so two
7518/// distinct certificate kinds over the same source unit produce distinct
7519/// fingerprints. Locked at v0.2.2.
7520#[inline]
7521#[must_use]
7522pub const fn certificate_kind_discriminant(kind: CertificateKind) -> u8 {
7523    match kind {
7524        CertificateKind::Grounding => 1,
7525        CertificateKind::TowerCompleteness => 2,
7526        CertificateKind::IncrementalCompleteness => 3,
7527        CertificateKind::Inhabitance => 4,
7528        CertificateKind::Multiplication => 5,
7529        CertificateKind::TwoSat => 6,
7530        CertificateKind::HornSat => 7,
7531        CertificateKind::ResidualVerdict => 8,
7532        CertificateKind::CanonicalForm => 9,
7533        CertificateKind::TypeSynthesis => 10,
7534        CertificateKind::Homotopy => 11,
7535        CertificateKind::Monodromy => 12,
7536        CertificateKind::Moduli => 13,
7537        CertificateKind::JacobianGuided => 14,
7538        CertificateKind::Evaluation => 15,
7539        CertificateKind::Session => 16,
7540        CertificateKind::Superposition => 17,
7541        CertificateKind::Measurement => 18,
7542        CertificateKind::WittLevel => 19,
7543        CertificateKind::DihedralFactorization => 20,
7544        CertificateKind::Completeness => 21,
7545        CertificateKind::GeodesicValidator => 22,
7546    }
7547}
7548
7549/// v0.2.2 T5: fold a `ConstraintRef` into a `Hasher` via the canonical
7550/// byte layout. Each variant emits a discriminant byte (1..=9) followed by
7551/// its payload bytes in big-endian order. Locked at v0.2.2; reordering
7552/// variants requires bumping `TRACE_REPLAY_FORMAT_VERSION`.
7553/// Used by `pipeline::run`, `run_const`, and the four `certify_*` entry
7554/// points to fold a unit's constraint set into the substrate fingerprint.
7555pub fn fold_constraint_ref<H: Hasher>(mut hasher: H, c: &crate::pipeline::ConstraintRef) -> H {
7556    use crate::pipeline::ConstraintRef as C;
7557    match c {
7558        C::Residue { modulus, residue } => {
7559            hasher = hasher.fold_byte(1);
7560            hasher = hasher.fold_bytes(&modulus.to_be_bytes());
7561            hasher = hasher.fold_bytes(&residue.to_be_bytes());
7562        }
7563        C::Hamming { bound } => {
7564            hasher = hasher.fold_byte(2);
7565            hasher = hasher.fold_bytes(&bound.to_be_bytes());
7566        }
7567        C::Depth { min, max } => {
7568            hasher = hasher.fold_byte(3);
7569            hasher = hasher.fold_bytes(&min.to_be_bytes());
7570            hasher = hasher.fold_bytes(&max.to_be_bytes());
7571        }
7572        C::Carry { site } => {
7573            hasher = hasher.fold_byte(4);
7574            hasher = hasher.fold_bytes(&site.to_be_bytes());
7575        }
7576        C::Site { position } => {
7577            hasher = hasher.fold_byte(5);
7578            hasher = hasher.fold_bytes(&position.to_be_bytes());
7579        }
7580        C::Affine {
7581            coefficients,
7582            coefficient_count,
7583            bias,
7584        } => {
7585            hasher = hasher.fold_byte(6);
7586            hasher = hasher.fold_bytes(&coefficient_count.to_be_bytes());
7587            let count = *coefficient_count as usize;
7588            let mut i = 0;
7589            while i < count && i < crate::pipeline::AFFINE_MAX_COEFFS {
7590                hasher = hasher.fold_bytes(&coefficients[i].to_be_bytes());
7591                i += 1;
7592            }
7593            hasher = hasher.fold_bytes(&bias.to_be_bytes());
7594        }
7595        C::SatClauses { clauses, num_vars } => {
7596            hasher = hasher.fold_byte(7);
7597            hasher = hasher.fold_bytes(&num_vars.to_be_bytes());
7598            hasher = hasher.fold_bytes(&(clauses.len() as u32).to_be_bytes());
7599            let mut i = 0;
7600            while i < clauses.len() {
7601                let clause = clauses[i];
7602                hasher = hasher.fold_bytes(&(clause.len() as u32).to_be_bytes());
7603                let mut j = 0;
7604                while j < clause.len() {
7605                    let (var, neg) = clause[j];
7606                    hasher = hasher.fold_bytes(&var.to_be_bytes());
7607                    hasher = hasher.fold_byte(if neg { 1 } else { 0 });
7608                    j += 1;
7609                }
7610                i += 1;
7611            }
7612        }
7613        C::Bound {
7614            observable_iri,
7615            bound_shape_iri,
7616            args_repr,
7617        } => {
7618            hasher = hasher.fold_byte(8);
7619            hasher = hasher.fold_bytes(observable_iri.as_bytes());
7620            hasher = hasher.fold_byte(0);
7621            hasher = hasher.fold_bytes(bound_shape_iri.as_bytes());
7622            hasher = hasher.fold_byte(0);
7623            hasher = hasher.fold_bytes(args_repr.as_bytes());
7624            hasher = hasher.fold_byte(0);
7625        }
7626        C::Conjunction {
7627            conjuncts,
7628            conjunct_count,
7629        } => {
7630            hasher = hasher.fold_byte(9);
7631            hasher = hasher.fold_bytes(&conjunct_count.to_be_bytes());
7632            let count = *conjunct_count as usize;
7633            let mut i = 0;
7634            while i < count && i < crate::pipeline::CONJUNCTION_MAX_TERMS {
7635                let lifted = conjuncts[i].into_constraint();
7636                hasher = fold_constraint_ref(hasher, &lifted);
7637                i += 1;
7638            }
7639        }
7640        // ADR-057 wire-format: discriminant byte 10 + content-addressed
7641        // shape_iri + descent_bound. The discriminant table extension
7642        // requires TRACE_REPLAY_FORMAT_VERSION bump per ADR-013/TR-08.
7643        C::Recurse {
7644            shape_iri,
7645            descent_bound,
7646        } => {
7647            hasher = hasher.fold_byte(10);
7648            hasher = hasher.fold_bytes(shape_iri.as_bytes());
7649            hasher = hasher.fold_byte(0);
7650            hasher = hasher.fold_bytes(&descent_bound.to_be_bytes());
7651        }
7652    }
7653    hasher
7654}
7655
7656/// v0.2.2 T5: fold the canonical CompileUnit byte layout into a `Hasher`.
7657/// Layout: `level_bits (2 BE) || budget (8 BE) || iri bytes || 0x00 ||
7658/// site_count (8 BE) || for each constraint: fold_constraint_ref ||
7659/// certificate_kind_discriminant (1 byte trailing)`.
7660/// Locked at v0.2.2 by the `rust/trace_byte_layout_pinned` conformance
7661/// validator. Used by `pipeline::run`, `run_const`, and the four
7662/// `certify_*` entry points.
7663pub fn fold_unit_digest<H: Hasher>(
7664    mut hasher: H,
7665    level_bits: u16,
7666    budget: u64,
7667    iri: &str,
7668    site_count: usize,
7669    constraints: &[crate::pipeline::ConstraintRef],
7670    kind: CertificateKind,
7671) -> H {
7672    hasher = hasher.fold_bytes(&level_bits.to_be_bytes());
7673    hasher = hasher.fold_bytes(&budget.to_be_bytes());
7674    hasher = hasher.fold_bytes(iri.as_bytes());
7675    hasher = hasher.fold_byte(0);
7676    hasher = hasher.fold_bytes(&(site_count as u64).to_be_bytes());
7677    let mut i = 0;
7678    while i < constraints.len() {
7679        hasher = fold_constraint_ref(hasher, &constraints[i]);
7680        i += 1;
7681    }
7682    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
7683    hasher
7684}
7685
7686/// v0.2.2 T5: fold the canonical ParallelDeclaration byte layout into a `Hasher`.
7687/// Layout: `site_count (8 BE) || iri bytes || 0x00 || decl_site_count (8 BE) ||
7688/// for each constraint: fold_constraint_ref || certificate_kind_discriminant`.
7689pub fn fold_parallel_digest<H: Hasher>(
7690    mut hasher: H,
7691    decl_site_count: u64,
7692    iri: &str,
7693    type_site_count: usize,
7694    constraints: &[crate::pipeline::ConstraintRef],
7695    kind: CertificateKind,
7696) -> H {
7697    hasher = hasher.fold_bytes(&decl_site_count.to_be_bytes());
7698    hasher = hasher.fold_bytes(iri.as_bytes());
7699    hasher = hasher.fold_byte(0);
7700    hasher = hasher.fold_bytes(&(type_site_count as u64).to_be_bytes());
7701    let mut i = 0;
7702    while i < constraints.len() {
7703        hasher = fold_constraint_ref(hasher, &constraints[i]);
7704        i += 1;
7705    }
7706    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
7707    hasher
7708}
7709
7710/// v0.2.2 T5: fold the canonical StreamDeclaration byte layout into a `Hasher`.
7711pub fn fold_stream_digest<H: Hasher>(
7712    mut hasher: H,
7713    productivity_bound: u64,
7714    iri: &str,
7715    constraints: &[crate::pipeline::ConstraintRef],
7716    kind: CertificateKind,
7717) -> H {
7718    hasher = hasher.fold_bytes(&productivity_bound.to_be_bytes());
7719    hasher = hasher.fold_bytes(iri.as_bytes());
7720    hasher = hasher.fold_byte(0);
7721    let mut i = 0;
7722    while i < constraints.len() {
7723        hasher = fold_constraint_ref(hasher, &constraints[i]);
7724        i += 1;
7725    }
7726    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
7727    hasher
7728}
7729
7730/// v0.2.2 T5: fold the canonical InteractionDeclaration byte layout into a `Hasher`.
7731pub fn fold_interaction_digest<H: Hasher>(
7732    mut hasher: H,
7733    convergence_seed: u64,
7734    iri: &str,
7735    constraints: &[crate::pipeline::ConstraintRef],
7736    kind: CertificateKind,
7737) -> H {
7738    hasher = hasher.fold_bytes(&convergence_seed.to_be_bytes());
7739    hasher = hasher.fold_bytes(iri.as_bytes());
7740    hasher = hasher.fold_byte(0);
7741    let mut i = 0;
7742    while i < constraints.len() {
7743        hasher = fold_constraint_ref(hasher, &constraints[i]);
7744        i += 1;
7745    }
7746    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
7747    hasher
7748}
7749
7750/// v0.2.2 Phase J primitive: `reduction:ReductionStep` / `recursion:BoundedRecursion`.
7751/// Content-deterministic reduction signature: `(witt_bits, constraint_count, satisfiable_bit)`.
7752pub(crate) fn primitive_terminal_reduction<T: crate::pipeline::ConstrainedTypeShape + ?Sized>(
7753    witt_bits: u16,
7754) -> Result<(u16, u32, u8), PipelineFailure> {
7755    let outcome = crate::pipeline::run_reduction_stages::<T>(witt_bits)?;
7756    let satisfiable_bit: u8 = if outcome.satisfiable { 1 } else { 0 };
7757    Ok((
7758        outcome.witt_bits,
7759        T::CONSTRAINTS.len() as u32,
7760        satisfiable_bit,
7761    ))
7762}
7763
7764/// v0.2.2 Phase J: fold the TerminalReduction triple into the hasher.
7765pub(crate) fn fold_terminal_reduction<H: Hasher>(
7766    mut hasher: H,
7767    witt_bits: u16,
7768    constraint_count: u32,
7769    satisfiable_bit: u8,
7770) -> H {
7771    hasher = hasher.fold_bytes(&witt_bits.to_be_bytes());
7772    hasher = hasher.fold_bytes(&constraint_count.to_be_bytes());
7773    hasher = hasher.fold_byte(satisfiable_bit);
7774    hasher
7775}
7776
7777/// Phase X.4: `resolver:CechNerve` / `homology:ChainComplex`.
7778/// Computes the content-deterministic Betti tuple `[b_0, b_1, b_2, 0, .., 0]`
7779/// from the 2-complex constraint-nerve over `T::CONSTRAINTS`:
7780/// vertices = constraints, 1-simplices = pairs of constraints with intersecting
7781/// site support, 2-simplices = triples of constraints with a common site.
7782/// `b_k = dim ker(∂_k) - dim im(∂_{k+1})` for k ∈ {0,1,2}; `b_3..b_7 = 0`.
7783/// Ranks of the boundary operators ∂_1, ∂_2 are computed over ℤ/p (p prime,
7784/// `NERVE_RANK_MOD_P = 1_000_000_007`) by `integer_matrix_rank`. Nerve boundary
7785/// matrices have ±1/0 entries and are totally unimodular, so rank over ℤ/p
7786/// equals rank over ℚ equals rank over ℤ for any prime p not dividing a minor.
7787/// Phase 1a (orphan-closure): inputs larger than `NERVE_CONSTRAINTS_CAP = 8`
7788/// constraints or `NERVE_SITES_CAP = 8` sites return
7789/// `Err(GenericImpossibilityWitness::for_identity("NERVE_CAPACITY_EXCEEDED"))`
7790/// rather than silently truncating — truncation produced Betti numbers for a
7791/// differently-shaped complex than the caller asked about. Callers propagate
7792/// the witness via `?` (pattern mirrored on `primitive_terminal_reduction`).
7793/// ADR-057: `T::CONSTRAINTS` may contain `ConstraintRef::Recurse` entries
7794/// referencing shapes by IRI. This primitive expands Recurse references
7795/// through the **foundation built-in shape-IRI registry** (`lookup_shape`),
7796/// decrementing the descent budget on each Recurse encountered and
7797/// terminating when the budget reaches zero. Applications that register
7798/// their own shapes (via the SDK `register_shape!` macro) use
7799/// [`primitive_simplicial_nerve_betti_in`] which is generic over the
7800/// application's `ShapeRegistryProvider`. The structural reading at ψ_1
7801/// reflects the expanded constraint geometry — Recurse entries are not
7802/// opaque anonymous Sites but their structurally-substituted body per the
7803/// registered shape's `CONSTRAINTS` array.
7804/// # Errors
7805/// Returns `NERVE_CAPACITY_EXCEEDED` when either cap is exceeded after
7806/// expansion. Returns `RECURSE_SHAPE_UNREGISTERED` when a `Recurse`
7807/// entry references an IRI not present in the consulted registry
7808/// (non-zero descent budget).
7809pub fn primitive_simplicial_nerve_betti<T: crate::pipeline::ConstrainedTypeShape + ?Sized>(
7810) -> Result<[u32; MAX_BETTI_DIMENSION], GenericImpossibilityWitness> {
7811    // ADR-057: foundation-default registry path. EmptyShapeRegistry's
7812    // REGISTRY is the empty slice, so lookup_shape_in falls through to
7813    // foundation's built-in FOUNDATION_REGISTRY (the canonical stdlib path).
7814    primitive_simplicial_nerve_betti_in::<T, crate::pipeline::shape_iri_registry::EmptyShapeRegistry>(
7815    )
7816}
7817
7818/// ADR-057: registry-parameterized variant of
7819/// [`primitive_simplicial_nerve_betti`]. Walks `T::CONSTRAINTS` and expands
7820/// every `ConstraintRef::Recurse { shape_iri, descent_bound }` entry by
7821/// looking up `shape_iri` through `R`'s registry plus foundation's
7822/// built-in registry, decrementing the descent budget on each recursive
7823/// walk, and terminating when the budget reaches zero. The expanded
7824/// constraint sequence is the input to the nerve computation — the
7825/// structural reading at ψ_1 reflects the recursive grammar.
7826/// This is the entry point ψ_1 `NerveResolver` impls call from the
7827/// application's resolver-tuple — `R` is the ResolverTuple's
7828/// `ShapeRegistry` associated type per ADR-036+ADR-057.
7829/// # Errors
7830/// Returns `NERVE_CAPACITY_EXCEEDED` when the expanded constraint set
7831/// exceeds `NERVE_CONSTRAINTS_CAP` or `NERVE_SITES_CAP`. Returns
7832/// `RECURSE_SHAPE_UNREGISTERED` when a `Recurse` entry references an
7833/// IRI not present in either `R::REGISTRY` or foundation's built-in.
7834pub fn primitive_simplicial_nerve_betti_in<
7835    T: crate::pipeline::ConstrainedTypeShape + ?Sized,
7836    R: crate::pipeline::shape_iri_registry::ShapeRegistryProvider,
7837>() -> Result<[u32; MAX_BETTI_DIMENSION], GenericImpossibilityWitness> {
7838    // ADR-057 step 3: expand T::CONSTRAINTS, walking ConstraintRef::Recurse
7839    // through R's registry with bounded descent.
7840    let mut expanded: [crate::pipeline::ConstraintRef; NERVE_CONSTRAINTS_CAP] =
7841        [crate::pipeline::ConstraintRef::Site { position: 0 }; NERVE_CONSTRAINTS_CAP];
7842    let mut n_expanded: usize = 0;
7843    expand_constraints_in::<R>(T::CONSTRAINTS, u32::MAX, &mut expanded, &mut n_expanded)?;
7844    let n_constraints = n_expanded;
7845    if n_constraints > NERVE_CONSTRAINTS_CAP {
7846        return Err(GenericImpossibilityWitness::for_identity(
7847            "NERVE_CAPACITY_EXCEEDED",
7848        ));
7849    }
7850    let s_all = T::SITE_COUNT;
7851    if s_all > NERVE_SITES_CAP {
7852        return Err(GenericImpossibilityWitness::for_identity(
7853            "NERVE_CAPACITY_EXCEEDED",
7854        ));
7855    }
7856    let n_sites = s_all;
7857    let mut out = [0u32; MAX_BETTI_DIMENSION];
7858    if n_constraints == 0 {
7859        out[0] = 1;
7860        return Ok(out);
7861    }
7862    // Compute site-support bitmask per constraint (bit `s` set iff constraint touches site `s`).
7863    let mut support = [0u16; NERVE_CONSTRAINTS_CAP];
7864    let mut c = 0;
7865    while c < n_constraints {
7866        support[c] = constraint_site_support_mask_of(&expanded[c], n_sites);
7867        c += 1;
7868    }
7869    // Enumerate 1-simplices: pairs (i,j) with i<j and support[i] & support[j] != 0.
7870    // Index in c1_pairs_lo/hi corresponds to the column in ∂_1 / row in ∂_2.
7871    let mut c1_pairs_lo = [0u8; NERVE_C1_MAX];
7872    let mut c1_pairs_hi = [0u8; NERVE_C1_MAX];
7873    let mut n_c1: usize = 0;
7874    let mut i = 0;
7875    while i < n_constraints {
7876        let mut j = i + 1;
7877        while j < n_constraints {
7878            if (support[i] & support[j]) != 0 && n_c1 < NERVE_C1_MAX {
7879                c1_pairs_lo[n_c1] = i as u8;
7880                c1_pairs_hi[n_c1] = j as u8;
7881                n_c1 += 1;
7882            }
7883            j += 1;
7884        }
7885        i += 1;
7886    }
7887    // Enumerate 2-simplices: triples (i,j,k) with i<j<k and support[i] & support[j] & support[k] != 0.
7888    let mut c2_i = [0u8; NERVE_C2_MAX];
7889    let mut c2_j = [0u8; NERVE_C2_MAX];
7890    let mut c2_k = [0u8; NERVE_C2_MAX];
7891    let mut n_c2: usize = 0;
7892    let mut i2 = 0;
7893    while i2 < n_constraints {
7894        let mut j2 = i2 + 1;
7895        while j2 < n_constraints {
7896            let mut k2 = j2 + 1;
7897            while k2 < n_constraints {
7898                if (support[i2] & support[j2] & support[k2]) != 0 && n_c2 < NERVE_C2_MAX {
7899                    c2_i[n_c2] = i2 as u8;
7900                    c2_j[n_c2] = j2 as u8;
7901                    c2_k[n_c2] = k2 as u8;
7902                    n_c2 += 1;
7903                }
7904                k2 += 1;
7905            }
7906            j2 += 1;
7907        }
7908        i2 += 1;
7909    }
7910    // Build ∂_1: rows = n_constraints (vertices of the nerve), cols = n_c1.
7911    // Convention: ∂(c_i, c_j) = c_j - c_i for i < j.
7912    let mut partial_1 = [[0i64; NERVE_C1_MAX]; NERVE_CONSTRAINTS_CAP];
7913    let mut e = 0;
7914    while e < n_c1 {
7915        let lo = c1_pairs_lo[e] as usize;
7916        let hi = c1_pairs_hi[e] as usize;
7917        partial_1[lo][e] = NERVE_RANK_MOD_P - 1; // -1 mod p
7918        partial_1[hi][e] = 1;
7919        e += 1;
7920    }
7921    let rank_1 = integer_matrix_rank::<NERVE_CONSTRAINTS_CAP, NERVE_C1_MAX>(
7922        &mut partial_1,
7923        n_constraints,
7924        n_c1,
7925    );
7926    // Build ∂_2: rows = n_c1, cols = n_c2.
7927    // Convention: ∂(c_i, c_j, c_k) = (c_j, c_k) - (c_i, c_k) + (c_i, c_j).
7928    let mut partial_2 = [[0i64; NERVE_C2_MAX]; NERVE_C1_MAX];
7929    let mut t = 0;
7930    while t < n_c2 {
7931        let ti = c2_i[t];
7932        let tj = c2_j[t];
7933        let tk = c2_k[t];
7934        let idx_jk = find_pair_index(&c1_pairs_lo, &c1_pairs_hi, n_c1, tj, tk);
7935        let idx_ik = find_pair_index(&c1_pairs_lo, &c1_pairs_hi, n_c1, ti, tk);
7936        let idx_ij = find_pair_index(&c1_pairs_lo, &c1_pairs_hi, n_c1, ti, tj);
7937        if idx_jk < NERVE_C1_MAX {
7938            partial_2[idx_jk][t] = 1;
7939        }
7940        if idx_ik < NERVE_C1_MAX {
7941            partial_2[idx_ik][t] = NERVE_RANK_MOD_P - 1;
7942        }
7943        if idx_ij < NERVE_C1_MAX {
7944            partial_2[idx_ij][t] = 1;
7945        }
7946        t += 1;
7947    }
7948    let rank_2 = integer_matrix_rank::<NERVE_C1_MAX, NERVE_C2_MAX>(&mut partial_2, n_c1, n_c2);
7949    // b_0 = |C_0| - rank(∂_1). Always ≥ 1 because partial_1 has at least one all-zero row.
7950    let b0 = (n_constraints - rank_1) as u32;
7951    // b_1 = (|C_1| - rank(∂_1)) - rank(∂_2).
7952    let cycles_1 = n_c1.saturating_sub(rank_1);
7953    let b1 = cycles_1.saturating_sub(rank_2) as u32;
7954    // b_2 = |C_2| - rank(∂_2) (the complex is 2-dimensional; no ∂_3).
7955    let b2 = n_c2.saturating_sub(rank_2) as u32;
7956    out[0] = if b0 == 0 { 1 } else { b0 };
7957    if MAX_BETTI_DIMENSION > 1 {
7958        out[1] = b1;
7959    }
7960    if MAX_BETTI_DIMENSION > 2 {
7961        out[2] = b2;
7962    }
7963    Ok(out)
7964}
7965
7966/// ADR-057 step 3: walk `in_constraints`, copying non-Recurse entries into
7967/// `out_arr` and expanding every `ConstraintRef::Recurse { shape_iri,
7968/// descent_bound }` by looking up `shape_iri` through `R`'s registry plus
7969/// foundation's built-in registry and recursing into the referenced shape's
7970/// `CONSTRAINTS`. The effective descent budget at each Recurse is the min
7971/// of the caller's `descent_remaining` and the constraint's own
7972/// `descent_bound`; on Recurse the budget decrements by 1 before recursion.
7973/// A budget of 0 terminates the descent (the Recurse contributes no
7974/// further constraints — the recursion bottoms out).
7975/// # Errors
7976/// Returns `NERVE_CAPACITY_EXCEEDED` when the expansion would exceed
7977/// `NERVE_CONSTRAINTS_CAP`. Returns `RECURSE_SHAPE_UNREGISTERED` when a
7978/// `Recurse` entry with non-zero effective budget references an IRI not
7979/// present in either `R::REGISTRY` or foundation's built-in registry.
7980pub fn expand_constraints_in<R: crate::pipeline::shape_iri_registry::ShapeRegistryProvider>(
7981    in_constraints: &[crate::pipeline::ConstraintRef],
7982    descent_remaining: u32,
7983    out_arr: &mut [crate::pipeline::ConstraintRef; NERVE_CONSTRAINTS_CAP],
7984    out_n: &mut usize,
7985) -> Result<(), GenericImpossibilityWitness> {
7986    let mut i = 0;
7987    while i < in_constraints.len() {
7988        match in_constraints[i] {
7989            crate::pipeline::ConstraintRef::Recurse {
7990                shape_iri,
7991                descent_bound,
7992            } => {
7993                // Effective budget = min(caller's remaining, this Recurse's bound).
7994                let budget = if descent_remaining < descent_bound {
7995                    descent_remaining
7996                } else {
7997                    descent_bound
7998                };
7999                if budget == 0 {
8000                    // Bottom out — contribute no further constraints.
8001                } else {
8002                    match crate::pipeline::shape_iri_registry::lookup_shape_in::<R>(shape_iri) {
8003                        Some(registered) => {
8004                            expand_constraints_in::<R>(
8005                                registered.constraints,
8006                                budget - 1,
8007                                out_arr,
8008                                out_n,
8009                            )?;
8010                        }
8011                        None => {
8012                            return Err(GenericImpossibilityWitness::for_identity(
8013                                "RECURSE_SHAPE_UNREGISTERED",
8014                            ));
8015                        }
8016                    }
8017                }
8018            }
8019            other => {
8020                if *out_n >= NERVE_CONSTRAINTS_CAP {
8021                    return Err(GenericImpossibilityWitness::for_identity(
8022                        "NERVE_CAPACITY_EXCEEDED",
8023                    ));
8024                }
8025                out_arr[*out_n] = other;
8026                *out_n += 1;
8027            }
8028        }
8029        i += 1;
8030    }
8031    Ok(())
8032}
8033
8034/// Phase X.4: cap on the number of constraints considered by the nerve
8035/// primitive. Phase 1a (orphan-closure): inputs exceeding this cap are
8036/// rejected via `NERVE_CAPACITY_EXCEEDED` (was previously silent truncation).
8037/// Wiki ADR-037: a foundation-fixed conservative default for
8038/// [`crate::HostBounds::NERVE_CONSTRAINTS_MAX`].
8039pub const NERVE_CONSTRAINTS_CAP: usize = 8;
8040
8041/// Phase X.4: cap on site-support bitmask width (matches `u16` storage).
8042/// Phase 1a (orphan-closure): inputs exceeding this cap are rejected via
8043/// `NERVE_CAPACITY_EXCEEDED` (was previously silent truncation).
8044/// Wiki ADR-037: a foundation-fixed conservative default for
8045/// [`crate::HostBounds::NERVE_SITES_MAX`].
8046pub const NERVE_SITES_CAP: usize = 8;
8047
8048/// Phase X.4: maximum number of 1-simplices = C(NERVE_CONSTRAINTS_CAP, 2) = 28.
8049pub const NERVE_C1_MAX: usize = 28;
8050
8051/// Phase X.4: maximum number of 2-simplices = C(NERVE_CONSTRAINTS_CAP, 3) = 56.
8052pub const NERVE_C2_MAX: usize = 56;
8053
8054/// Phase X.4: prime modulus for nerve boundary-matrix rank computation.
8055/// Chosen so `(i64 * i64) mod p` never overflows (`p² < 2⁶³`). Nerve boundary
8056/// matrices have entries in {-1, 0, 1}; rank over ℤ/p equals rank over ℚ.
8057pub(crate) const NERVE_RANK_MOD_P: i64 = 1_000_000_007;
8058
8059/// Phase X.4: per-constraint site-support bitmask. Returns bit `s` set iff
8060/// constraint `c` touches site index `s` (`s < n_sites`).
8061/// `Affine { coefficients, .. }` returns the bitmask of sites whose
8062/// coefficient is non-zero — the natural "site support" of the affine
8063/// relation. Remaining non-site-local variants (Residue, Hamming, Depth,
8064/// Bound, Conjunction, SatClauses) return an all-ones mask over `n_sites`.
8065/// ADR-057: slice-based — operates directly on a `&ConstraintRef` rather
8066/// than indexing a `ConstrainedTypeShape::CONSTRAINTS` slot. ψ_1 calls this
8067/// from [`primitive_simplicial_nerve_betti_in`] after `T::CONSTRAINTS` has
8068/// been expanded into a fixed-size array via [`expand_constraints_in`].
8069pub(crate) const fn constraint_site_support_mask_of(
8070    c: &crate::pipeline::ConstraintRef,
8071    n_sites: usize,
8072) -> u16 {
8073    let all_mask: u16 = if n_sites == 0 {
8074        0
8075    } else {
8076        (1u16 << n_sites) - 1
8077    };
8078    match c {
8079        crate::pipeline::ConstraintRef::Site { position } => {
8080            if n_sites == 0 {
8081                0
8082            } else {
8083                1u16 << (*position as usize % n_sites)
8084            }
8085        }
8086        crate::pipeline::ConstraintRef::Carry { site } => {
8087            if n_sites == 0 {
8088                0
8089            } else {
8090                1u16 << (*site as usize % n_sites)
8091            }
8092        }
8093        crate::pipeline::ConstraintRef::Affine {
8094            coefficients,
8095            coefficient_count,
8096            ..
8097        } => {
8098            if n_sites == 0 {
8099                0
8100            } else {
8101                let mut mask: u16 = 0;
8102                let count = *coefficient_count as usize;
8103                let mut i = 0;
8104                while i < count && i < crate::pipeline::AFFINE_MAX_COEFFS && i < n_sites {
8105                    if coefficients[i] != 0 {
8106                        mask |= 1u16 << i;
8107                    }
8108                    i += 1;
8109                }
8110                if mask == 0 {
8111                    all_mask
8112                } else {
8113                    mask
8114                }
8115            }
8116        }
8117        // ADR-057: any Recurse entry left in the array means
8118        // expand_constraints_in already bottomed out (descent_bound = 0).
8119        // Treat it as a structural placeholder with no specific site support.
8120        _ => all_mask,
8121    }
8122}
8123
8124/// Phase X.4: find the column index of the 1-simplex (lo, hi) in the enumerated
8125/// pair list. Returns `NERVE_C1_MAX` (sentinel = not found) when absent.
8126pub(crate) const fn find_pair_index(
8127    lo_arr: &[u8; NERVE_C1_MAX],
8128    hi_arr: &[u8; NERVE_C1_MAX],
8129    n_c1: usize,
8130    lo: u8,
8131    hi: u8,
8132) -> usize {
8133    let mut i = 0;
8134    while i < n_c1 {
8135        if lo_arr[i] == lo && hi_arr[i] == hi {
8136            return i;
8137        }
8138        i += 1;
8139    }
8140    NERVE_C1_MAX
8141}
8142
8143/// Phase X.4: rank of an integer matrix over ℤ/`NERVE_RANK_MOD_P` via modular
8144/// Gaussian elimination. Entries are reduced mod p and elimination uses
8145/// Fermat-inverse pivot normalization. For ±1/0 boundary matrices this
8146/// coincides with rank over ℤ.
8147pub(crate) const fn integer_matrix_rank<const R: usize, const C: usize>(
8148    matrix: &mut [[i64; C]; R],
8149    rows: usize,
8150    cols: usize,
8151) -> usize {
8152    let p = NERVE_RANK_MOD_P;
8153    // Reduce all entries into [0, p).
8154    let mut r = 0;
8155    while r < rows {
8156        let mut c = 0;
8157        while c < cols {
8158            let v = matrix[r][c] % p;
8159            matrix[r][c] = if v < 0 { v + p } else { v };
8160            c += 1;
8161        }
8162        r += 1;
8163    }
8164    let mut rank: usize = 0;
8165    let mut col: usize = 0;
8166    while col < cols && rank < rows {
8167        // Find a pivot row in column `col`, starting at `rank`.
8168        let mut pivot_row = rank;
8169        while pivot_row < rows && matrix[pivot_row][col] == 0 {
8170            pivot_row += 1;
8171        }
8172        if pivot_row == rows {
8173            col += 1;
8174            continue;
8175        }
8176        // Swap into position.
8177        if pivot_row != rank {
8178            let mut k = 0;
8179            while k < cols {
8180                let tmp = matrix[rank][k];
8181                matrix[rank][k] = matrix[pivot_row][k];
8182                matrix[pivot_row][k] = tmp;
8183                k += 1;
8184            }
8185        }
8186        // Normalize pivot row to have leading 1.
8187        let pivot = matrix[rank][col];
8188        let pivot_inv = mod_pow(pivot, p - 2, p);
8189        let mut k = 0;
8190        while k < cols {
8191            matrix[rank][k] = (matrix[rank][k] * pivot_inv) % p;
8192            k += 1;
8193        }
8194        // Eliminate the column entry from every other row.
8195        let mut r2 = 0;
8196        while r2 < rows {
8197            if r2 != rank {
8198                let factor = matrix[r2][col];
8199                if factor != 0 {
8200                    let mut kk = 0;
8201                    while kk < cols {
8202                        let sub = (matrix[rank][kk] * factor) % p;
8203                        let mut v = matrix[r2][kk] - sub;
8204                        v %= p;
8205                        if v < 0 {
8206                            v += p;
8207                        }
8208                        matrix[r2][kk] = v;
8209                        kk += 1;
8210                    }
8211                }
8212            }
8213            r2 += 1;
8214        }
8215        rank += 1;
8216        col += 1;
8217    }
8218    rank
8219}
8220
8221/// Phase X.4: modular exponentiation `base^exp mod p`, const-fn. Used by
8222/// `integer_matrix_rank` via Fermat's little theorem for modular inverses.
8223pub(crate) const fn mod_pow(base: i64, exp: i64, p: i64) -> i64 {
8224    let mut result: i64 = 1;
8225    let mut b = ((base % p) + p) % p;
8226    let mut e = exp;
8227    while e > 0 {
8228        if e & 1 == 1 {
8229            result = (result * b) % p;
8230        }
8231        b = (b * b) % p;
8232        e >>= 1;
8233    }
8234    result
8235}
8236
8237/// v0.2.2 Phase J: fold the Betti tuple into the hasher.
8238pub(crate) fn fold_betti_tuple<H: Hasher>(mut hasher: H, betti: &[u32; MAX_BETTI_DIMENSION]) -> H {
8239    let mut i = 0;
8240    while i < MAX_BETTI_DIMENSION {
8241        hasher = hasher.fold_bytes(&betti[i].to_be_bytes());
8242        i += 1;
8243    }
8244    hasher
8245}
8246
8247/// v0.2.2 Phase J: Euler characteristic `χ = Σ(-1)^k b_k` from the Betti tuple.
8248#[must_use]
8249pub(crate) fn primitive_euler_characteristic(betti: &[u32; MAX_BETTI_DIMENSION]) -> i64 {
8250    let mut chi: i64 = 0;
8251    let mut k = 0;
8252    while k < MAX_BETTI_DIMENSION {
8253        let term = betti[k] as i64;
8254        if k % 2 == 0 {
8255            chi += term;
8256        } else {
8257            chi -= term;
8258        }
8259        k += 1;
8260    }
8261    chi
8262}
8263
8264/// v0.2.2 Phase J primitive: `op:DihedralGroup` / `op:D_7`.
8265/// Returns `(orbit_size, representative)` under D_{2^n} acting on `T::SITE_COUNT`.
8266/// `orbit_size = 2n` when n ≥ 2, 2 when n == 1, 1 when n == 0 (group identity only).
8267/// `representative` is the lexicographically-minimal element of the orbit of
8268/// site 0 under D_{2n}: rotations `r^k → k mod n` and reflections `s·r^k → (n - k) mod n`.
8269/// For the orbit of site 0, both maps produce 0 as a group element, so the
8270/// representative is always 0; for a non-canonical starting index `i`, the
8271/// representative would be `min(i, (n - i) mod n)`. This helper uses site 0 as the
8272/// canonical starting point (the foundation's convention), so the representative
8273/// reflects the orbit's algebraic content, not a sentinel.
8274pub(crate) fn primitive_dihedral_signature<T: crate::pipeline::ConstrainedTypeShape + ?Sized>(
8275) -> (u32, u32) {
8276    let n = T::SITE_COUNT as u32;
8277    let orbit_size = if n < 2 {
8278        if n == 0 {
8279            1
8280        } else {
8281            2
8282        }
8283    } else {
8284        2 * n
8285    };
8286    // v0.2.2 Phase S.2: compute the lexicographically-minimal orbit element.
8287    // Orbit of site 0 under D_{2n} contains: rotation images {0, 1, ..., n-1}
8288    // (since r^k maps 0 → k mod n) and reflection images {0, n-1, n-2, ..., 1}
8289    // (since s·r^k maps 0 → (n - k) mod n). The union is {0, 1, ..., n-1}.
8290    // The lex-min is 0 by construction; formalize it by min-walking the orbit.
8291    let mut rep: u32 = 0;
8292    let mut k = 1u32;
8293    while k < n {
8294        let rot = k % n;
8295        let refl = (n - k) % n;
8296        if rot < rep {
8297            rep = rot;
8298        }
8299        if refl < rep {
8300            rep = refl;
8301        }
8302        k += 1;
8303    }
8304    (orbit_size, rep)
8305}
8306
8307/// v0.2.2 Phase J: fold the dihedral `(orbit_size, representative)` pair.
8308pub(crate) fn fold_dihedral_signature<H: Hasher>(
8309    mut hasher: H,
8310    orbit_size: u32,
8311    representative: u32,
8312) -> H {
8313    hasher = hasher.fold_bytes(&orbit_size.to_be_bytes());
8314    hasher = hasher.fold_bytes(&representative.to_be_bytes());
8315    hasher
8316}
8317
8318/// v0.2.2 Phase J primitive: `observable:Jacobian` / `op:DC_10`.
8319/// Content-deterministic per-site Jacobian profile: for each site `i`, the number
8320/// of constraints that mention site index `i` (derived from the constraint encoding).
8321/// Truncated / zero-padded to `JACOBIAN_MAX_SITES` entries to keep the fold fixed-size.
8322pub(crate) fn primitive_curvature_jacobian<T: crate::pipeline::ConstrainedTypeShape + ?Sized>(
8323) -> [i32; JACOBIAN_MAX_SITES] {
8324    let mut out = [0i32; JACOBIAN_MAX_SITES];
8325    let mut ci = 0;
8326    while ci < T::CONSTRAINTS.len() {
8327        if let crate::pipeline::ConstraintRef::Site { position } = T::CONSTRAINTS[ci] {
8328            let idx = (position as usize) % JACOBIAN_MAX_SITES;
8329            out[idx] = out[idx].saturating_add(1);
8330        }
8331        ci += 1;
8332    }
8333    // Also account for residue and hamming constraints as contributing uniformly
8334    // across all sites (they are not site-local). Represented as +1 to site 0.
8335    let total = T::CONSTRAINTS.len() as i32;
8336    out[0] = out[0].saturating_add(total);
8337    out
8338}
8339
8340/// v0.2.2 Phase J: DC_10 selects the site with the maximum absolute Jacobian value.
8341#[must_use]
8342pub(crate) fn primitive_dc10_select(jac: &[i32; JACOBIAN_MAX_SITES]) -> usize {
8343    let mut best_idx: usize = 0;
8344    let mut best_abs: i32 = jac[0].unsigned_abs() as i32;
8345    let mut i = 1;
8346    while i < JACOBIAN_MAX_SITES {
8347        let a = jac[i].unsigned_abs() as i32;
8348        if a > best_abs {
8349            best_abs = a;
8350            best_idx = i;
8351        }
8352        i += 1;
8353    }
8354    best_idx
8355}
8356
8357/// v0.2.2 Phase J: fold the Jacobian profile into the hasher.
8358pub(crate) fn fold_jacobian_profile<H: Hasher>(
8359    mut hasher: H,
8360    jac: &[i32; JACOBIAN_MAX_SITES],
8361) -> H {
8362    let mut i = 0;
8363    while i < JACOBIAN_MAX_SITES {
8364        hasher = hasher.fold_bytes(&jac[i].to_be_bytes());
8365        i += 1;
8366    }
8367    hasher
8368}
8369
8370/// v0.2.2 Phase J primitive: `state:BindingAccumulator` / `state:ContextLease`.
8371/// Returns `(binding_count, fold_address)` — a content-deterministic session signature.
8372/// v0.2.2 Phase S.4: uses an FNV-1a-style order-preserving incremental hash
8373/// (rotate-and-multiply) over each binding's `(name_index, type_index,
8374/// content_address)` tuple, rather than XOR-accumulation (which is commutative
8375/// and collides on reordered-but-otherwise-identical binding sets). Order-dependence
8376/// is intentional: `state:BindingAccumulator` semantics treat the insertion
8377/// sequence as part of the session signature.
8378pub(crate) fn primitive_session_binding_signature(bindings: &[Binding]) -> (u32, u64) {
8379    // FNV-1a-style incremental mix: start from the FNV offset basis,
8380    // multiply-then-XOR each limb. Order-dependent by construction.
8381    let mut fold: u64 = 0xcbf2_9ce4_8422_2325;
8382    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
8383    let mut i = 0;
8384    while i < bindings.len() {
8385        let b = &bindings[i];
8386        // Mix in (name_index, type_index, content_address) per binding.
8387        fold = fold.wrapping_mul(FNV_PRIME);
8388        fold ^= b.name_index as u64;
8389        fold = fold.wrapping_mul(FNV_PRIME);
8390        fold ^= b.type_index as u64;
8391        fold = fold.wrapping_mul(FNV_PRIME);
8392        fold ^= b.content_address;
8393        i += 1;
8394    }
8395    (bindings.len() as u32, fold)
8396}
8397
8398/// v0.2.2 Phase J: fold the session-binding signature into the hasher.
8399pub(crate) fn fold_session_signature<H: Hasher>(
8400    mut hasher: H,
8401    binding_count: u32,
8402    fold_address: u64,
8403) -> H {
8404    hasher = hasher.fold_bytes(&binding_count.to_be_bytes());
8405    hasher = hasher.fold_bytes(&fold_address.to_be_bytes());
8406    hasher
8407}
8408
8409/// v0.2.2 Phase J primitive: `op:QM_1` / `op:QM_5` / `resolver:collapseAmplitude`.
8410/// Seeds a two-state amplitude vector from the CompileUnit's thermodynamic budget,
8411/// computes Born-rule probabilities `P(0) = |α_0|²` and `P(1) = |α_1|²`,
8412/// verifies QM_5 normalization `Σ P = 1`, and returns `(outcome_index, probability)`
8413/// where `outcome_index` is the index of the larger amplitude and `probability` is its value.
8414/// QM_1 Landauer equality: `pre_entropy == post_cost` at β* = ln 2; since both
8415/// sides derive from the same budget the equality holds by construction.
8416/// v0.2.2 Phase S.3: amplitudes are sourced from two decorrelated projections
8417/// of the thermodynamic budget — the high 32 bits become the alpha-0
8418/// magnitude and the low 32 bits become the alpha-1 magnitude. This replaces
8419/// the earlier XOR-with-fixed-constants sourcing, preserving determinism while
8420/// ensuring both amplitudes derive from independent halves of the budget's
8421/// thermodynamic-entropy state. Born normalization and QM_1 Landauer equality
8422/// remain invariant under this sourcing change.
8423pub(crate) fn primitive_measurement_projection(budget: u64) -> (u64, u64) {
8424    // Decorrelated amplitude sourcing: high-32-bits drives alpha_0,
8425    // low-32-bits drives alpha_1. Distinct bit halves yield independent
8426    // magnitudes under any non-degenerate budget.
8427    let alpha0_bits: u32 = (budget >> 32) as u32;
8428    let alpha1_bits: u32 = (budget & 0xFFFF_FFFF) as u32;
8429    type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
8430    let a0 = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(alpha0_bits)
8431        / <DefaultDecimal as crate::DecimalTranscendental>::from_u32(u32::MAX);
8432    let a1 = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(alpha1_bits)
8433        / <DefaultDecimal as crate::DecimalTranscendental>::from_u32(u32::MAX);
8434    let norm = a0 * a0 + a1 * a1;
8435    let zero = <DefaultDecimal as Default>::default();
8436    let half =
8437        <DefaultDecimal as crate::DecimalTranscendental>::from_bits(0x3FE0_0000_0000_0000_u64);
8438    // QM_5 normalization: P(k) = |alpha_k|^2 / norm. Degenerate budget = 0
8439    // yields norm = 0; fall through to the uniform distribution (P(0) = 0.5,
8440    // P(1) = 0.5), which is the maximum-entropy projection under QM_1.
8441    let p0 = if norm > zero { (a0 * a0) / norm } else { half };
8442    let p1 = if norm > zero { (a1 * a1) / norm } else { half };
8443    if p0 >= p1 {
8444        (
8445            0,
8446            <DefaultDecimal as crate::DecimalTranscendental>::to_bits(p0),
8447        )
8448    } else {
8449        (
8450            1,
8451            <DefaultDecimal as crate::DecimalTranscendental>::to_bits(p1),
8452        )
8453    }
8454}
8455
8456/// v0.2.2 Phase J / Phase 9: fold the Born-rule outcome into the hasher.
8457/// `probability_bits` is the IEEE-754 bit pattern (call sites convert via
8458/// `<H::Decimal as DecimalTranscendental>::to_bits` if working in `H::Decimal`).
8459pub(crate) fn fold_born_outcome<H: Hasher>(
8460    mut hasher: H,
8461    outcome_index: u64,
8462    probability_bits: u64,
8463) -> H {
8464    hasher = hasher.fold_bytes(&outcome_index.to_be_bytes());
8465    hasher = hasher.fold_bytes(&probability_bits.to_be_bytes());
8466    hasher
8467}
8468
8469/// v0.2.2 Phase J primitive: `recursion:DescentMeasure` / `observable:ResidualEntropy`.
8470/// Computes `(residual_count, entropy_bits)` from `T::SITE_COUNT` and the Euler char.
8471/// `residual_count = max(0, site_count - euler_char)` — free sites after constraint contraction.
8472/// `entropy = (residual_count) × ln 2` — Landauer-temperature entropy in nats.
8473/// Phase 9: returns `(residual_count, entropy_bits)` where `entropy_bits` is the
8474/// IEEE-754 bit pattern of `residual × ln 2`. Consumers project to `H::Decimal`
8475/// via `<H::Decimal as DecimalTranscendental>::from_bits`.
8476pub(crate) fn primitive_descent_metrics<T: crate::pipeline::ConstrainedTypeShape + ?Sized>(
8477    betti: &[u32; MAX_BETTI_DIMENSION],
8478) -> (u32, u64) {
8479    let chi = primitive_euler_characteristic(betti);
8480    let n = T::SITE_COUNT as i64;
8481    let residual = if n > chi { (n - chi) as u32 } else { 0u32 };
8482    type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
8483    let residual_d = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(residual);
8484    let ln_2 = <DefaultDecimal as crate::DecimalTranscendental>::from_bits(crate::LN_2_BITS);
8485    let entropy = residual_d * ln_2;
8486    (
8487        residual,
8488        <DefaultDecimal as crate::DecimalTranscendental>::to_bits(entropy),
8489    )
8490}
8491
8492/// v0.2.2 Phase J / Phase 9: fold the descent metrics into the hasher.
8493/// `entropy_bits` is the IEEE-754 bit pattern of the descent entropy.
8494pub(crate) fn fold_descent_metrics<H: Hasher>(
8495    mut hasher: H,
8496    residual_count: u32,
8497    entropy_bits: u64,
8498) -> H {
8499    hasher = hasher.fold_bytes(&residual_count.to_be_bytes());
8500    hasher = hasher.fold_bytes(&entropy_bits.to_be_bytes());
8501    hasher
8502}
8503
8504/// Phase X.2: upper bound on cohomology class dimension. Cup products
8505/// whose summed dimension exceeds this cap are rejected as
8506/// `CohomologyError::DimensionOverflow`.
8507pub const MAX_COHOMOLOGY_DIMENSION: u32 = 32;
8508
8509/// Phase X.2: a cohomology class `H^n(·)` at dimension `n` with a content
8510/// fingerprint of the underlying cochain representative. Parametric over
8511/// dimension via a runtime field because generic-const-expression arithmetic
8512/// over `N + M` is unstable at the crate's MSRV (Rust 1.81).
8513#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8514pub struct CohomologyClass {
8515    dimension: u32,
8516    fingerprint: ContentFingerprint,
8517    _sealed: (),
8518}
8519
8520impl CohomologyClass {
8521    /// Phase X.2: crate-sealed constructor. Public callers go through
8522    /// `mint_cohomology_class` so that construction always routes through a
8523    /// validating hash of the cochain representative.
8524    #[inline]
8525    pub(crate) const fn with_dimension_and_fingerprint(
8526        dimension: u32,
8527        fingerprint: ContentFingerprint,
8528    ) -> Self {
8529        Self {
8530            dimension,
8531            fingerprint,
8532            _sealed: (),
8533        }
8534    }
8535
8536    /// The dimension `n` of this cohomology class `H^n(·)`.
8537    #[inline]
8538    #[must_use]
8539    pub const fn dimension(&self) -> u32 {
8540        self.dimension
8541    }
8542
8543    /// The content fingerprint of the underlying cochain representative.
8544    #[inline]
8545    #[must_use]
8546    pub const fn fingerprint(&self) -> ContentFingerprint {
8547        self.fingerprint
8548    }
8549
8550    /// Phase X.2: cup product `H^n × H^m → H^{n+m}`. The resulting class
8551    /// carries dimension `n + m` and a fingerprint folded from both
8552    /// operand dimensions and fingerprints via `fold_cup_product`. The
8553    /// fold is ordered (lhs-then-rhs) — graded-commutativity of the cup
8554    /// product at the algebraic level is not a fingerprint-level property.
8555    /// # Errors
8556    /// Returns `CohomologyError::DimensionOverflow` when `n + m >
8557    /// MAX_COHOMOLOGY_DIMENSION`.
8558    pub fn cup<H: Hasher>(
8559        self,
8560        other: CohomologyClass,
8561    ) -> Result<CohomologyClass, CohomologyError> {
8562        let sum = self.dimension.saturating_add(other.dimension);
8563        if sum > MAX_COHOMOLOGY_DIMENSION {
8564            return Err(CohomologyError::DimensionOverflow {
8565                lhs: self.dimension,
8566                rhs: other.dimension,
8567            });
8568        }
8569        let hasher = H::initial();
8570        let hasher = fold_cup_product(
8571            hasher,
8572            self.dimension,
8573            &self.fingerprint,
8574            other.dimension,
8575            &other.fingerprint,
8576        );
8577        let buf = hasher.finalize();
8578        let fp = ContentFingerprint::from_buffer(buf, H::OUTPUT_BYTES as u8);
8579        Ok(Self::with_dimension_and_fingerprint(sum, fp))
8580    }
8581}
8582
8583/// Phase X.2: error returned by `CohomologyClass::cup` when the summed
8584/// dimension exceeds `MAX_COHOMOLOGY_DIMENSION`.
8585#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8586pub enum CohomologyError {
8587    /// Cup product would exceed `MAX_COHOMOLOGY_DIMENSION`.
8588    DimensionOverflow { lhs: u32, rhs: u32 },
8589}
8590
8591impl core::fmt::Display for CohomologyError {
8592    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8593        match self {
8594            Self::DimensionOverflow { lhs, rhs } => write!(
8595                f,
8596                "cup product dimension overflow: {lhs} + {rhs} > MAX_COHOMOLOGY_DIMENSION ({})",
8597                MAX_COHOMOLOGY_DIMENSION
8598            ),
8599        }
8600    }
8601}
8602impl core::error::Error for CohomologyError {}
8603
8604/// Phase X.2: homology class dual to `CohomologyClass`. A homology class
8605/// `H_n(·)` at dimension `n` with a content fingerprint of its chain
8606/// representative. Shares the dimension-as-runtime-field discipline.
8607#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8608pub struct HomologyClass {
8609    dimension: u32,
8610    fingerprint: ContentFingerprint,
8611    _sealed: (),
8612}
8613
8614impl HomologyClass {
8615    /// Phase X.2: crate-sealed constructor. Public callers go through
8616    /// `mint_homology_class`.
8617    #[inline]
8618    pub(crate) const fn with_dimension_and_fingerprint(
8619        dimension: u32,
8620        fingerprint: ContentFingerprint,
8621    ) -> Self {
8622        Self {
8623            dimension,
8624            fingerprint,
8625            _sealed: (),
8626        }
8627    }
8628
8629    /// The dimension `n` of this homology class `H_n(·)`.
8630    #[inline]
8631    #[must_use]
8632    pub const fn dimension(&self) -> u32 {
8633        self.dimension
8634    }
8635
8636    /// The content fingerprint of the underlying chain representative.
8637    #[inline]
8638    #[must_use]
8639    pub const fn fingerprint(&self) -> ContentFingerprint {
8640        self.fingerprint
8641    }
8642}
8643
8644/// Phase X.2: fold the cup-product operand pair into the hasher. Ordered
8645/// (lhs dimension + fingerprint, then rhs dimension + fingerprint).
8646pub fn fold_cup_product<H: Hasher>(
8647    mut hasher: H,
8648    lhs_dim: u32,
8649    lhs_fp: &ContentFingerprint,
8650    rhs_dim: u32,
8651    rhs_fp: &ContentFingerprint,
8652) -> H {
8653    hasher = hasher.fold_bytes(&lhs_dim.to_be_bytes());
8654    hasher = hasher.fold_bytes(lhs_fp.as_bytes());
8655    hasher = hasher.fold_bytes(&rhs_dim.to_be_bytes());
8656    hasher = hasher.fold_bytes(rhs_fp.as_bytes());
8657    hasher
8658}
8659
8660/// Phase X.2: mint a `CohomologyClass` from a cochain representative `seed`.
8661/// Hashes `seed` through `H` to produce the class fingerprint. The caller's
8662/// choice of `H` determines the fingerprint width.
8663/// # Errors
8664/// Returns `CohomologyError::DimensionOverflow` when `dimension >
8665/// MAX_COHOMOLOGY_DIMENSION`.
8666pub fn mint_cohomology_class<H: Hasher>(
8667    dimension: u32,
8668    seed: &[u8],
8669) -> Result<CohomologyClass, CohomologyError> {
8670    if dimension > MAX_COHOMOLOGY_DIMENSION {
8671        return Err(CohomologyError::DimensionOverflow {
8672            lhs: dimension,
8673            rhs: 0,
8674        });
8675    }
8676    let mut hasher = H::initial();
8677    hasher = hasher.fold_bytes(&dimension.to_be_bytes());
8678    hasher = hasher.fold_bytes(seed);
8679    let buf = hasher.finalize();
8680    let fp = ContentFingerprint::from_buffer(buf, H::OUTPUT_BYTES as u8);
8681    Ok(CohomologyClass::with_dimension_and_fingerprint(
8682        dimension, fp,
8683    ))
8684}
8685
8686/// Phase X.2: mint a `HomologyClass` from a chain representative `seed`.
8687/// Hashes `seed` through `H` to produce the class fingerprint.
8688/// # Errors
8689/// Returns `CohomologyError::DimensionOverflow` when `dimension >
8690/// MAX_COHOMOLOGY_DIMENSION`.
8691pub fn mint_homology_class<H: Hasher>(
8692    dimension: u32,
8693    seed: &[u8],
8694) -> Result<HomologyClass, CohomologyError> {
8695    if dimension > MAX_COHOMOLOGY_DIMENSION {
8696        return Err(CohomologyError::DimensionOverflow {
8697            lhs: dimension,
8698            rhs: 0,
8699        });
8700    }
8701    let mut hasher = H::initial();
8702    hasher = hasher.fold_bytes(&dimension.to_be_bytes());
8703    hasher = hasher.fold_bytes(seed);
8704    let buf = hasher.finalize();
8705    let fp = ContentFingerprint::from_buffer(buf, H::OUTPUT_BYTES as u8);
8706    Ok(HomologyClass::with_dimension_and_fingerprint(dimension, fp))
8707}
8708
8709/// v0.2.2 T6.1: per-step canonical byte layout for `StreamDriver::next()`.
8710/// Layout: `productivity_remaining (8 BE) || rewrite_steps (8 BE) || seed (8 BE) ||
8711/// iri bytes || 0x00 || certificate_kind_discriminant (1 byte trailing)`.
8712pub fn fold_stream_step_digest<H: Hasher>(
8713    mut hasher: H,
8714    productivity_remaining: u64,
8715    rewrite_steps: u64,
8716    seed: u64,
8717    iri: &str,
8718    kind: CertificateKind,
8719) -> H {
8720    hasher = hasher.fold_bytes(&productivity_remaining.to_be_bytes());
8721    hasher = hasher.fold_bytes(&rewrite_steps.to_be_bytes());
8722    hasher = hasher.fold_bytes(&seed.to_be_bytes());
8723    hasher = hasher.fold_bytes(iri.as_bytes());
8724    hasher = hasher.fold_byte(0);
8725    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
8726    hasher
8727}
8728
8729/// v0.2.2 T6.1: per-step canonical byte layout for `InteractionDriver::step()`
8730/// and `InteractionDriver::finalize()`.
8731/// Layout: `commutator_acc[0..4] (4 × 8 BE bytes) || peer_step_count (8 BE) ||
8732/// seed (8 BE) || iri bytes || 0x00 || certificate_kind_discriminant (1 byte trailing)`.
8733pub fn fold_interaction_step_digest<H: Hasher>(
8734    mut hasher: H,
8735    commutator_acc: &[u64; 4],
8736    peer_step_count: u64,
8737    seed: u64,
8738    iri: &str,
8739    kind: CertificateKind,
8740) -> H {
8741    let mut i = 0;
8742    while i < 4 {
8743        hasher = hasher.fold_bytes(&commutator_acc[i].to_be_bytes());
8744        i += 1;
8745    }
8746    hasher = hasher.fold_bytes(&peer_step_count.to_be_bytes());
8747    hasher = hasher.fold_bytes(&seed.to_be_bytes());
8748    hasher = hasher.fold_bytes(iri.as_bytes());
8749    hasher = hasher.fold_byte(0);
8750    hasher = hasher.fold_byte(certificate_kind_discriminant(kind));
8751    hasher
8752}
8753
8754/// Utility — extract the leading 16 bytes of a `Hasher::finalize` buffer
8755/// as a `ContentAddress`. Used by pipeline entry points to derive the
8756/// 16-byte unit_address handle from a freshly-computed substrate
8757/// fingerprint, so two units with distinct fingerprints have distinct
8758/// unit_address handles too.
8759/// Per the wiki's ADR-018 the `FP_MAX` const-generic carries the
8760/// application's selected `<B as HostBounds>::FINGERPRINT_MAX_BYTES`.
8761/// `FP_MAX` MUST be at least 16; smaller buffers cannot supply the
8762/// 16-byte address prefix.
8763#[inline]
8764#[must_use]
8765pub const fn unit_address_from_buffer<const FP_MAX: usize>(
8766    buffer: &[u8; FP_MAX],
8767) -> ContentAddress {
8768    let mut bytes = [0u8; 16];
8769    let mut i = 0;
8770    while i < 16 {
8771        bytes[i] = buffer[i];
8772        i += 1;
8773    }
8774    ContentAddress::from_u128(u128::from_be_bytes(bytes))
8775}
8776
8777/// v0.2.2 T6.11: const-fn equality on `&str` slices. `str::eq` is not
8778/// stable in const eval under MSRV 1.81; this helper provides a
8779/// byte-by-byte equality check for use in `pipeline::run`'s ShapeMismatch
8780/// detection without runtime allocation.
8781#[inline]
8782#[must_use]
8783pub const fn str_eq(a: &str, b: &str) -> bool {
8784    let a = a.as_bytes();
8785    let b = b.as_bytes();
8786    if a.len() != b.len() {
8787        return false;
8788    }
8789    let mut i = 0;
8790    while i < a.len() {
8791        if a[i] != b[i] {
8792            return false;
8793        }
8794        i += 1;
8795    }
8796    true
8797}
8798
8799/// A binding entry in a `BindingsTable`. Pairs a `ContentAddress`
8800/// (hash of the query coordinate) with the bound bytes.
8801#[derive(Debug, Clone, Copy)]
8802pub struct BindingEntry {
8803    /// Content-hashed query address.
8804    pub address: ContentAddress,
8805    /// Bound payload bytes (length determined by the WittLevel of the table).
8806    pub bytes: &'static [u8],
8807}
8808
8809/// A static, sorted-by-address binding table laid out for `op:GS_5` zero-step
8810/// access. Looked up via binary search; the foundation guarantees the table
8811/// is materialized at compile time from the attested `state:GroundedContext`.
8812#[derive(Debug, Clone, Copy)]
8813pub struct BindingsTable {
8814    /// Entries, sorted ascending by `address`.
8815    pub entries: &'static [BindingEntry],
8816}
8817
8818impl BindingsTable {
8819    /// v0.2.2 T5 C4: validating constructor. Checks that `entries` are
8820    /// strictly ascending by `address`, which is the invariant
8821    /// `Grounded::get_binding` relies on for its binary-search lookup.
8822    /// # Errors
8823    /// Returns `BindingsTableError::Unsorted { at }` where `at` is the first
8824    /// index where the order is violated (i.e., `entries[at].address <=
8825    /// entries[at - 1].address`).
8826    pub const fn try_new(entries: &'static [BindingEntry]) -> Result<Self, BindingsTableError> {
8827        let mut i = 1;
8828        while i < entries.len() {
8829            if entries[i].address.as_u128() <= entries[i - 1].address.as_u128() {
8830                return Err(BindingsTableError::Unsorted { at: i });
8831            }
8832            i += 1;
8833        }
8834        Ok(Self { entries })
8835    }
8836}
8837
8838/// v0.2.2 T5 C4: errors returned by `BindingsTable::try_new`.
8839#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8840#[non_exhaustive]
8841pub enum BindingsTableError {
8842    /// Entries at index `at` and `at - 1` are out of order (the slice is
8843    /// not strictly ascending by `address`).
8844    Unsorted {
8845        /// The first index where the order is violated.
8846        at: usize,
8847    },
8848}
8849
8850impl core::fmt::Display for BindingsTableError {
8851    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8852        match self {
8853            Self::Unsorted { at } => write!(
8854                f,
8855                "BindingsTable entries not sorted: address at index {at} <= address at index {}",
8856                at - 1,
8857            ),
8858        }
8859    }
8860}
8861
8862impl core::error::Error for BindingsTableError {}
8863
8864/// The compile-time witness that `op:GS_4` holds for the value it carries:
8865/// σ = 1, freeRank = 0, S = 0, T_ctx = 0. `Grounded<T, Tag>` is constructed
8866/// only by the reduction pipeline and provides `op:GS_5` zero-step binding access.
8867/// v0.2.2 Phase B (Q3): the `Tag` phantom parameter (default `Tag = T`)
8868/// lets downstream code attach a domain marker to a grounded witness without
8869/// any new sealing — e.g., `Grounded<ConstrainedTypeInput, BlockHashTag>` is
8870/// a distinct Rust type from `Grounded<ConstrainedTypeInput, PixelTag>`. The
8871/// inner witness is unchanged; the tag is pure decoration. The foundation
8872/// guarantees ring soundness on the inner witness; the tag is the developer's
8873/// domain claim. Coerce via `Grounded::tag::<NewTag>()` (zero-cost).
8874///
8875/// # Wiki ADR-039 — Inhabitance verdict realization mapping
8876///
8877/// For typed feature hierarchies whose admission relations are
8878/// inhabitance questions, a successful `Grounded<Output>` IS a
8879/// `cert:InhabitanceCertificate` envelope:
8880///
8881/// - The κ-label (homotopy-classification structural witness at ψ_9
8882///   per ADR-035) is the `Term::KInvariants` emission's bytes, exposed
8883///   via [`Grounded::output_bytes`].
8884/// - The concrete `cert:witness` ValueTuple is derivable from
8885///   `Term::Nerve`'s 0-simplices at ψ_1 (the per-value bytes the model's
8886///   NerveResolver consumed).
8887/// - The `cert:searchTrace` is realized as
8888///   [`Grounded::derivation`]`().replay()`.
8889///
8890/// The κ-label and `cert:witness` are different witness granularities
8891/// (homotopy classification vs. concrete ValueTuple); the canonical
8892/// k-invariants branch ψ_1 → ψ_7 → ψ_8 → ψ_9 produces both, at the
8893/// ψ_9 and ψ_1 stages respectively. Ontology references:
8894/// `<https://uor.foundation/cert/InhabitanceCertificate>`,
8895/// `<https://uor.foundation/cert/witness>`,
8896/// `<https://uor.foundation/cert/searchTrace>`.
8897#[derive(Debug, Clone)]
8898pub struct Grounded<'a, T: GroundedShape, const INLINE_BYTES: usize, Tag = T> {
8899    /// The validated grounding certificate this wrapper carries.
8900    validated: Validated<GroundingCertificate>,
8901    /// The compile-time-materialized bindings table.
8902    bindings: BindingsTable,
8903    /// The Witt level the grounded value was minted at.
8904    witt_level_bits: u16,
8905    /// Content-address of the originating CompileUnit.
8906    unit_address: ContentAddress,
8907    /// Phase A.1: the foundation-internal two-clock value read at witness mint time.
8908    /// Computed deterministically from (witt_level_bits, unit_address, bindings).
8909    uor_time: UorTime,
8910    /// v0.2.2 T2.6 (cleanup): BaseMetric storage — populated by the
8911    /// pipeline at mint time as a deterministic function of witt level,
8912    /// unit address, and bindings. All six fields are read-only from
8913    /// the accessors; downstream cannot mutate them.
8914    /// Grounding completion ratio σ × 10⁶ (parts per million).
8915    sigma_ppm: u32,
8916    /// Metric incompatibility d_Δ.
8917    d_delta: i64,
8918    /// Euler characteristic of the constraint nerve.
8919    euler_characteristic: i64,
8920    /// Free-site count at grounding time.
8921    residual_count: u32,
8922    /// Per-site Jacobian row (fixed capacity, zero-padded).
8923    jacobian_entries: [i64; JACOBIAN_MAX_SITES],
8924    /// Active length of jacobian_entries.
8925    jacobian_len: u16,
8926    /// Betti numbers β_0..β_{MAX_BETTI_DIMENSION-1}.
8927    betti_numbers: [u32; MAX_BETTI_DIMENSION],
8928    /// v0.2.2 T5: parametric content fingerprint of the source unit's
8929    /// full state, computed at grounding time by the consumer-supplied
8930    /// `Hasher`. Width is `ContentFingerprint::width_bytes()`, set by
8931    /// `H::OUTPUT_BYTES` at the call site. Read by `Grounded::derivation()`
8932    /// so the verify path can re-derive the source certificate.
8933    content_fingerprint: ContentFingerprint,
8934    /// Wiki ADR-028 (amended by ADR-060): output-value payload — the
8935    /// catamorphism's evaluation result populated by `pipeline::run_route`
8936    /// per ADR-029's per-variant fold rules, carried as a source-polymorphic
8937    /// [`crate::pipeline::TermValue`] (Inline κ-label for content-addressing
8938    /// routes; Borrowed/Stream for structural/unbounded outputs). There is no
8939    /// fixed output buffer and no output byte-width ceiling. The lifetime
8940    /// `'a` is the borrowed-input-data lifetime a Borrowed/Stream output
8941    /// propagates from the route input. Read via [`Grounded::output_bytes`]
8942    /// (contiguous) or [`Grounded::output_value`] (the carrier).
8943    output: crate::pipeline::TermValue<'a, INLINE_BYTES>,
8944    /// Phantom type tying this `Grounded` to a specific `ConstrainedType`.
8945    _phantom: PhantomData<T>,
8946    /// Phantom domain tag (Q3). Defaults to `T` for backwards-compatible
8947    /// call sites; downstream attaches a custom tag via `tag::<NewTag>()`.
8948    _tag: PhantomData<Tag>,
8949}
8950
8951impl<'a, T: GroundedShape, const INLINE_BYTES: usize, Tag> Grounded<'a, T, INLINE_BYTES, Tag> {
8952    /// Returns the binding for the given query address, or `None` if not in
8953    /// the table. Resolves in O(log n) via binary search; for true `op:GS_5`
8954    /// zero-step access, downstream code uses statically-known indices.
8955    #[inline]
8956    #[must_use]
8957    pub fn get_binding(&self, address: ContentAddress) -> Option<&'static [u8]> {
8958        self.bindings
8959            .entries
8960            .binary_search_by_key(&address.as_u128(), |e| e.address.as_u128())
8961            .ok()
8962            .map(|i| self.bindings.entries[i].bytes)
8963    }
8964
8965    /// Iterate over all bindings in this grounded context.
8966    #[inline]
8967    pub fn iter_bindings(&self) -> impl Iterator<Item = &BindingEntry> + '_ {
8968        self.bindings.entries.iter()
8969    }
8970
8971    /// Returns the Witt level the grounded value was minted at.
8972    #[inline]
8973    #[must_use]
8974    pub const fn witt_level_bits(&self) -> u16 {
8975        self.witt_level_bits
8976    }
8977
8978    /// Returns the content-address of the originating CompileUnit.
8979    #[inline]
8980    #[must_use]
8981    pub const fn unit_address(&self) -> ContentAddress {
8982        self.unit_address
8983    }
8984
8985    /// Returns the validated grounding certificate this wrapper carries.
8986    #[inline]
8987    #[must_use]
8988    pub const fn certificate(&self) -> &Validated<GroundingCertificate> {
8989        &self.validated
8990    }
8991
8992    /// Phase A.4: `observable:d_delta_metric` — sealed metric incompatibility between
8993    /// ring distance and Hamming distance for this datum's neighborhood.
8994    #[inline]
8995    #[must_use]
8996    pub const fn d_delta(&self) -> DDeltaMetric {
8997        DDeltaMetric::new(self.d_delta)
8998    }
8999
9000    /// Phase A.4: `observable:sigma_metric` — sealed grounding completion ratio.
9001    #[inline]
9002    #[must_use]
9003    pub fn sigma(&self) -> SigmaValue<crate::DefaultHostTypes> {
9004        // Default-host (f64) projection; polymorphic consumers
9005        // can re-encode via DecimalTranscendental::from_u32 + Div.
9006        let value = <f64 as crate::DecimalTranscendental>::from_u32(self.sigma_ppm)
9007            / <f64 as crate::DecimalTranscendental>::from_u32(1_000_000);
9008        SigmaValue::<crate::DefaultHostTypes>::new_unchecked(value)
9009    }
9010
9011    /// Phase A.4: `observable:jacobian_metric` — sealed per-site Jacobian row.
9012    #[inline]
9013    #[must_use]
9014    pub fn jacobian(&self) -> JacobianMetric<T> {
9015        JacobianMetric::from_entries(self.jacobian_entries, self.jacobian_len)
9016    }
9017
9018    /// Phase A.4: `observable:betti_metric` — sealed Betti-number vector.
9019    #[inline]
9020    #[must_use]
9021    pub const fn betti(&self) -> BettiMetric {
9022        BettiMetric::new(self.betti_numbers)
9023    }
9024
9025    /// Phase A.4: `observable:euler_metric` — sealed Euler characteristic χ of
9026    /// the constraint nerve.
9027    #[inline]
9028    #[must_use]
9029    pub const fn euler(&self) -> EulerMetric {
9030        EulerMetric::new(self.euler_characteristic)
9031    }
9032
9033    /// Phase A.4: `observable:residual_metric` — sealed free-site count r at grounding.
9034    #[inline]
9035    #[must_use]
9036    pub const fn residual(&self) -> ResidualMetric {
9037        ResidualMetric::new(self.residual_count)
9038    }
9039
9040    /// v0.2.2 T5: returns the parametric content fingerprint of the source
9041    /// unit, computed at grounding time by the consumer-supplied `Hasher`.
9042    /// Width is set by `H::OUTPUT_BYTES` at the call site. Used by
9043    /// `derivation()` to seed the replayed Trace's fingerprint, which
9044    /// `verify_trace` then passes through to the re-derived certificate.
9045    #[inline]
9046    #[must_use]
9047    pub const fn content_fingerprint(&self) -> ContentFingerprint {
9048        self.content_fingerprint
9049    }
9050
9051    /// v0.2.2 T5 (C2): returns the `Derivation` that produced this grounded
9052    /// value. Use the returned `Derivation` with `Derivation::replay()` and
9053    /// then `uor_foundation_verify::verify_trace` to re-derive the source
9054    /// certificate without re-running the deciders.
9055    /// The round-trip property:
9056    /// ```text
9057    /// verify_trace(&grounded.derivation().replay()).certificate()
9058    ///     == grounded.certificate()
9059    /// ```
9060    /// holds for every conforming substrate `Hasher`.
9061    #[inline]
9062    #[must_use]
9063    pub const fn derivation(&self) -> Derivation {
9064        Derivation::new(
9065            (self.jacobian_len as u32) + 1,
9066            self.witt_level_bits,
9067            self.content_fingerprint,
9068        )
9069    }
9070
9071    /// v0.2.2 Phase B (Q3): coerce this `Grounded<T, Tag>` to a different
9072    /// phantom tag. Zero-cost — the inner witness is unchanged; only the
9073    /// type-system view differs. Downstream uses this to attach a domain
9074    /// marker for use in function signatures (e.g., `Grounded<_, BlockHashTag>`
9075    /// vs `Grounded<_, PixelTag>` are distinct Rust types).
9076    /// **The foundation does not validate the tag.** The tag records what
9077    /// the developer is claiming about the witness's domain semantics; the
9078    /// foundation's contract is about ring soundness, not domain semantics.
9079    #[inline]
9080    #[must_use]
9081    pub fn tag<NewTag>(self) -> Grounded<'a, T, INLINE_BYTES, NewTag> {
9082        Grounded {
9083            validated: self.validated,
9084            bindings: self.bindings,
9085            witt_level_bits: self.witt_level_bits,
9086            unit_address: self.unit_address,
9087            uor_time: self.uor_time,
9088            sigma_ppm: self.sigma_ppm,
9089            d_delta: self.d_delta,
9090            euler_characteristic: self.euler_characteristic,
9091            residual_count: self.residual_count,
9092            jacobian_entries: self.jacobian_entries,
9093            jacobian_len: self.jacobian_len,
9094            betti_numbers: self.betti_numbers,
9095            content_fingerprint: self.content_fingerprint,
9096            output: self.output,
9097            _phantom: PhantomData,
9098            _tag: PhantomData,
9099        }
9100    }
9101
9102    /// Wiki ADR-028: returns the catamorphism's evaluation output bytes — the
9103    /// active prefix of the on-stack output payload `pipeline::run_route`
9104    /// populated per ADR-029's per-variant fold rules.
9105    /// For the foundation-sanctioned identity output (`ConstrainedTypeInput`)
9106    /// the slice is empty (no transformation, identity route). For shapes
9107    /// declared via the `output_shape!` SDK macro the slice carries the
9108    /// route's evaluation result.
9109    #[inline]
9110    #[must_use]
9111    pub fn output_bytes(&self) -> &[u8] {
9112        // Inline/Borrowed carriers expose their contiguous bytes; a Stream
9113        // carrier has no contiguous slice (read it via `output_value()` +
9114        // `TermValue::for_each_chunk`).
9115        self.output.bytes()
9116    }
9117
9118    /// Wiki ADR-028 (amended by ADR-060): returns the output as the
9119    /// source-polymorphic [`crate::pipeline::TermValue`] carrier. Use this
9120    /// (rather than [`Grounded::output_bytes`]) when the route's output may
9121    /// be a `Stream` (unbounded) or `Borrowed` carrier — fold it via
9122    /// [`crate::pipeline::TermValue::for_each_chunk`] for arbitrary sizes.
9123    #[inline]
9124    #[must_use]
9125    pub fn output_value(&self) -> crate::pipeline::TermValue<'a, INLINE_BYTES> {
9126        self.output
9127    }
9128
9129    /// Phase A.1: the foundation-internal two-clock value read at witness mint time.
9130    /// Maps `rewrite_steps` to `derivation:stepCount` and `landauer_nats` to
9131    /// `observable:LandauerCost`. The value is content-deterministic: two `Grounded`
9132    /// witnesses minted from the same inputs share the same `UorTime`.
9133    /// Compose with a `Calibration` via [`UorTime::min_wall_clock`] to
9134    /// bound the provable minimum wall-clock duration the computation required.
9135    #[inline]
9136    #[must_use]
9137    pub const fn uor_time(&self) -> UorTime {
9138        self.uor_time
9139    }
9140
9141    /// Phase A.2: the sealed triadic coordinate `(stratum, spectrum, address)` at the
9142    /// witness's Witt level, projected from the content-addressed unit.
9143    /// `stratum` is the v₂ valuation of the lower unit-address half; `spectrum`
9144    /// is the lower 64 bits of the unit address; `address` is the upper 64 bits.
9145    /// The projection is deterministic and content-addressed, so replay reproduces the
9146    /// same `Triad` bit-for-bit.
9147    #[inline]
9148    #[must_use]
9149    pub const fn triad(&self) -> Triad<T> {
9150        let addr = self.unit_address.as_u128();
9151        let addr_lo = addr as u64;
9152        let addr_hi = (addr >> 64) as u64;
9153        let stratum = if addr_lo == 0 {
9154            0u64
9155        } else {
9156            addr_lo.trailing_zeros() as u64
9157        };
9158        Triad::new(stratum, addr_lo, addr_hi)
9159    }
9160
9161    /// Crate-internal constructor used by the pipeline at mint time.
9162    /// Not callable from outside `uor-foundation`. The tag defaults to `T`
9163    /// (the unparameterized form); downstream attaches a custom tag via `tag()`.
9164    /// v0.2.2 T2.6 (cleanup): BaseMetric fields are computed here from
9165    /// the input witt level, bindings, and unit address. Two `Grounded`
9166    /// values built from the same inputs return identical metrics; two
9167    /// built from different inputs differ in at least three fields.
9168    #[inline]
9169    #[allow(dead_code)]
9170    pub(crate) const fn new_internal(
9171        validated: Validated<GroundingCertificate>,
9172        bindings: BindingsTable,
9173        witt_level_bits: u16,
9174        unit_address: ContentAddress,
9175        content_fingerprint: ContentFingerprint,
9176    ) -> Self {
9177        let bound_count = bindings.entries.len() as u32;
9178        let declared_sites = if witt_level_bits == 0 {
9179            1u32
9180        } else {
9181            witt_level_bits as u32
9182        };
9183        // sigma = bound / declared, in parts per million.
9184        let sigma_ppm = if bound_count >= declared_sites {
9185            1_000_000u32
9186        } else {
9187            // Integer division, rounded down, cannot exceed 1_000_000.
9188            let num = (bound_count as u64) * 1_000_000u64;
9189            (num / (declared_sites as u64)) as u32
9190        };
9191        // residual_count = declared - bound (saturating).
9192        let residual_count = declared_sites.saturating_sub(bound_count);
9193        // d_delta = witt_bits - bound_count (signed).
9194        let d_delta = (witt_level_bits as i64) - (bound_count as i64);
9195        // Betti numbers: β_0 = 1 (connected); β_k = bit k of witt_level_bits.
9196        let mut betti = [0u32; MAX_BETTI_DIMENSION];
9197        betti[0] = 1;
9198        let mut k = 1usize;
9199        while k < MAX_BETTI_DIMENSION {
9200            betti[k] = ((witt_level_bits as u32) >> (k - 1)) & 1;
9201            k += 1;
9202        }
9203        // Euler characteristic: alternating sum of Betti numbers.
9204        let mut euler: i64 = 0;
9205        let mut k = 0usize;
9206        while k < MAX_BETTI_DIMENSION {
9207            if k & 1 == 0 {
9208                euler += betti[k] as i64;
9209            } else {
9210                euler -= betti[k] as i64;
9211            }
9212            k += 1;
9213        }
9214        // Jacobian row: entry i = (unit_address.as_u128() as i64 XOR (i as i64)) mod witt+1.
9215        let mut jac = [0i64; JACOBIAN_MAX_SITES];
9216        let modulus = (witt_level_bits as i64) + 1;
9217        let ua_lo = unit_address.as_u128() as i64;
9218        let mut i = 0usize;
9219        let jac_len = if (witt_level_bits as usize) < JACOBIAN_MAX_SITES {
9220            witt_level_bits as usize
9221        } else {
9222            JACOBIAN_MAX_SITES
9223        };
9224        while i < jac_len {
9225            let raw = ua_lo ^ (i as i64);
9226            // Rust's % is remainder; ensure non-negative.
9227            let m = if modulus == 0 { 1 } else { modulus };
9228            jac[i] = ((raw % m) + m) % m;
9229            i += 1;
9230        }
9231        // Phase A.1: uor_time is content-deterministic. rewrite_steps counts
9232        // the reduction work proxied by (witt bits + bound count + active jac len);
9233        // Landauer nats = rewrite_steps × ln 2 (Landauer-temperature cost of
9234        // traversing that many orthogonal states). Two Grounded values minted from
9235        // the same inputs share the same UorTime.
9236        let steps = (witt_level_bits as u64) + (bound_count as u64) + (jac_len as u64);
9237        let landauer = LandauerBudget::new((steps as f64) * core::f64::consts::LN_2);
9238        let uor_time = UorTime::new(landauer, steps);
9239        Self {
9240            validated,
9241            bindings,
9242            witt_level_bits,
9243            unit_address,
9244            uor_time,
9245            sigma_ppm,
9246            d_delta,
9247            euler_characteristic: euler,
9248            residual_count,
9249            jacobian_entries: jac,
9250            jacobian_len: jac_len as u16,
9251            betti_numbers: betti,
9252            content_fingerprint,
9253            output: crate::pipeline::TermValue::empty(),
9254            _phantom: PhantomData,
9255            _tag: PhantomData,
9256        }
9257    }
9258
9259    /// Wiki ADR-028 (amended by ADR-060): crate-internal setter for the
9260    /// source-polymorphic output-value carrier.
9261    /// Called by `pipeline::run_route` after the catamorphism evaluates the
9262    /// Term tree per ADR-029. The carrier is stored by move — no copy, no
9263    /// byte-width ceiling: an `Inline` κ-label, a `Borrowed` slice into the
9264    /// route's `'a`-lived input, or a `Stream` of arbitrary size. Returns
9265    /// self for chaining.
9266    #[inline]
9267    #[must_use]
9268    pub(crate) fn with_output(
9269        mut self,
9270        output: crate::pipeline::TermValue<'a, INLINE_BYTES>,
9271    ) -> Self {
9272        self.output = output;
9273        self
9274    }
9275
9276    /// v0.2.2 T6.17: attach a downstream-validated `BindingsTable` to this
9277    /// grounded value. The original `Grounded` was minted by the foundation
9278    /// pipeline with a substrate-computed certificate; this builder lets
9279    /// downstream attach its own binding table without re-grounding.
9280    /// The `bindings` parameter must satisfy the sortedness invariant. Use
9281    /// [`BindingsTable::try_new`] to construct a validated table from a
9282    /// pre-sorted slice.
9283    /// **Trust boundary:** the certificate witnesses the unit's grounding,
9284    /// not the bindings' contents. A downstream consumer that uses the
9285    /// certificate as a trust root for the bindings is wrong.
9286    #[inline]
9287    #[must_use]
9288    pub fn with_bindings(self, bindings: BindingsTable) -> Self {
9289        Self { bindings, ..self }
9290    }
9291
9292    /// Wiki ADR-042: borrow `self` as an
9293    /// [`crate::pipeline::InhabitanceCertificateView`] over the canonical
9294    /// k-invariants branch's verdict envelope.
9295    /// Universal — available for any `Grounded<T, Tag>`; applications whose
9296    /// admission relations are not inhabitance questions simply don't
9297    /// call the typed accessors. The view is zero-cost
9298    /// (`#[repr(transparent)]` over `&'a Grounded<T, Tag>`).
9299    #[inline]
9300    #[must_use]
9301    pub fn as_inhabitance_certificate(
9302        &self,
9303    ) -> crate::pipeline::InhabitanceCertificateView<'_, T, INLINE_BYTES, Tag> {
9304        crate::pipeline::InhabitanceCertificateView(self)
9305    }
9306}
9307
9308/// v0.2.2 W8: triadic coordinate of a Datum at level `L`. Bundles the
9309/// (stratum, spectrum, address) projection in one structurally-enforced
9310/// type. No public constructor — `Triad<L>` is built only by foundation code
9311/// at grounding time. Field access goes through the named accessors.
9312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9313pub struct Triad<L> {
9314    /// The stratum coordinate (two-adic valuation).
9315    stratum: u64,
9316    /// The spectrum coordinate (Walsh-Hadamard image).
9317    spectrum: u64,
9318    /// The address coordinate (Braille-glyph address).
9319    address: u64,
9320    /// Phantom marker for the Witt level.
9321    _level: PhantomData<L>,
9322}
9323
9324impl<L> Triad<L> {
9325    /// Returns the stratum component (`query:TwoAdicValuation` coordinate).
9326    #[inline]
9327    #[must_use]
9328    pub const fn stratum(&self) -> u64 {
9329        self.stratum
9330    }
9331
9332    /// Returns the spectrum component (`query:WalshHadamardImage` coordinate).
9333    #[inline]
9334    #[must_use]
9335    pub const fn spectrum(&self) -> u64 {
9336        self.spectrum
9337    }
9338
9339    /// Returns the address component (`query:Address` coordinate).
9340    #[inline]
9341    #[must_use]
9342    pub const fn address(&self) -> u64 {
9343        self.address
9344    }
9345
9346    /// Crate-internal constructor. Reachable only from grounding-time minting.
9347    #[inline]
9348    #[must_use]
9349    #[allow(dead_code)]
9350    pub(crate) const fn new(stratum: u64, spectrum: u64, address: u64) -> Self {
9351        Self {
9352            stratum,
9353            spectrum,
9354            address,
9355            _level: PhantomData,
9356        }
9357    }
9358}
9359
9360/// The Rust-surface rendering of `reduction:PipelineFailureReason` and the
9361/// v0.2.1 cross-namespace failure variants. Variant set and field shapes are
9362/// generated parametrically by walking `reduction:FailureField` individuals;
9363/// adding a new field requires only an ontology edit.
9364///
9365/// # Wiki ADR-039 — Inhabitance verdict realization mapping
9366///
9367/// An `Err(PipelineFailure)` whose structural cause is "the constraint
9368/// nerve has empty Kan completion" realizes a `cert:InhabitanceImpossibilityCertificate`
9369/// envelope, carrying `proof:InhabitanceImpossibilityWitness` as the
9370/// proof payload with `proof:contradictionProof` as the canonical-form
9371/// encoding of the failure trace. The verdict mapping is the dual of
9372/// the `Grounded<Output>` → `cert:InhabitanceCertificate` mapping; the
9373/// two together realize the ontology's three-primitive inhabitance
9374/// verdict structure (success / impossibility-witnessed / unknown).
9375/// Ontology references:
9376/// `<https://uor.foundation/cert/InhabitanceImpossibilityCertificate>`,
9377/// `<https://uor.foundation/proof/InhabitanceImpossibilityWitness>`,
9378/// `<https://uor.foundation/proof/contradictionProof>`.
9379#[derive(Debug, Clone, PartialEq)]
9380#[non_exhaustive]
9381pub enum PipelineFailure {
9382    /// `DispatchMiss` failure variant.
9383    DispatchMiss {
9384        /// query_iri field.
9385        query_iri: &'static str,
9386        /// table_iri field.
9387        table_iri: &'static str,
9388    },
9389    /// `GroundingFailure` failure variant.
9390    GroundingFailure {
9391        /// reason_iri field.
9392        reason_iri: &'static str,
9393    },
9394    /// `ConvergenceStall` failure variant.
9395    ConvergenceStall {
9396        /// stage_iri field.
9397        stage_iri: &'static str,
9398        /// angle_milliradians field.
9399        angle_milliradians: i64,
9400    },
9401    /// `ContradictionDetected` failure variant.
9402    ContradictionDetected {
9403        /// at_step field.
9404        at_step: usize,
9405        /// trace_iri field.
9406        trace_iri: &'static str,
9407    },
9408    /// `CoherenceViolation` failure variant.
9409    CoherenceViolation {
9410        /// site_position field.
9411        site_position: usize,
9412        /// constraint_iri field.
9413        constraint_iri: &'static str,
9414    },
9415    /// `ShapeMismatch` failure variant.
9416    ShapeMismatch {
9417        /// expected field.
9418        expected: &'static str,
9419        /// got field.
9420        got: &'static str,
9421    },
9422    /// `LiftObstructionFailure` failure variant.
9423    LiftObstructionFailure {
9424        /// site_position field.
9425        site_position: usize,
9426        /// obstruction_class_iri field.
9427        obstruction_class_iri: &'static str,
9428    },
9429    /// `ShapeViolation` failure variant.
9430    ShapeViolation {
9431        /// report field.
9432        report: ShapeViolation,
9433    },
9434}
9435
9436impl core::fmt::Display for PipelineFailure {
9437    fn fmt(&self, ff: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
9438        match self {
9439            Self::DispatchMiss {
9440                query_iri,
9441                table_iri,
9442            } => write!(
9443                ff,
9444                "DispatchMiss(query_iri={:?}, table_iri={:?})",
9445                query_iri, table_iri
9446            ),
9447            Self::GroundingFailure { reason_iri } => {
9448                write!(ff, "GroundingFailure(reason_iri={:?})", reason_iri)
9449            }
9450            Self::ConvergenceStall {
9451                stage_iri,
9452                angle_milliradians,
9453            } => write!(
9454                ff,
9455                "ConvergenceStall(stage_iri={:?}, angle_milliradians={:?})",
9456                stage_iri, angle_milliradians
9457            ),
9458            Self::ContradictionDetected { at_step, trace_iri } => write!(
9459                ff,
9460                "ContradictionDetected(at_step={:?}, trace_iri={:?})",
9461                at_step, trace_iri
9462            ),
9463            Self::CoherenceViolation {
9464                site_position,
9465                constraint_iri,
9466            } => write!(
9467                ff,
9468                "CoherenceViolation(site_position={:?}, constraint_iri={:?})",
9469                site_position, constraint_iri
9470            ),
9471            Self::ShapeMismatch { expected, got } => {
9472                write!(ff, "ShapeMismatch(expected={:?}, got={:?})", expected, got)
9473            }
9474            Self::LiftObstructionFailure {
9475                site_position,
9476                obstruction_class_iri,
9477            } => write!(
9478                ff,
9479                "LiftObstructionFailure(site_position={:?}, obstruction_class_iri={:?})",
9480                site_position, obstruction_class_iri
9481            ),
9482            Self::ShapeViolation { report } => write!(ff, "ShapeViolation({:?})", report),
9483        }
9484    }
9485}
9486
9487impl core::error::Error for PipelineFailure {}
9488
9489/// Sealed marker for impossibility witnesses returned by the resolver
9490/// free-function path. Every failure return value of every
9491/// `resolver::<name>::certify(...)` call is a member of this set.
9492pub trait ImpossibilityWitnessKind: impossibility_witness_kind_sealed::Sealed {}
9493
9494mod impossibility_witness_kind_sealed {
9495    /// Private supertrait.
9496    pub trait Sealed {}
9497    impl Sealed for super::GenericImpossibilityWitness {}
9498    impl Sealed for super::InhabitanceImpossibilityWitness {}
9499}
9500
9501impl ImpossibilityWitnessKind for GenericImpossibilityWitness {}
9502impl ImpossibilityWitnessKind for InhabitanceImpossibilityWitness {}
9503
9504/// v0.2.2 W12: resolver free functions. Replaces the v0.2.1 unit-struct
9505/// façades with module-per-resolver free functions returning the W11
9506/// `Certified<C>` parametric carrier.
9507pub mod resolver {
9508    use super::{
9509        BornRuleVerification,
9510        Certified,
9511        CompileUnit,
9512        CompletenessCertificate,
9513        GenericImpossibilityWitness,
9514        GeodesicCertificate,
9515        GroundingCertificate,
9516        InhabitanceCertificate,
9517        InhabitanceImpossibilityWitness,
9518        InvolutionCertificate,
9519        IsometryCertificate,
9520        LiftChainCertificate,
9521        MeasurementCertificate,
9522        // Phase X.1: per-resolver cert discrimination.
9523        TransformCertificate,
9524        Validated,
9525        WittLevel,
9526    };
9527
9528    /// v0.2.2 W12: certify tower-completeness for a constrained type.
9529    ///
9530    /// Replaces `TowerCompletenessResolver::new().certify(input)` from v0.2.1.
9531    /// Delegates to `crate::pipeline::run_tower_completeness` and wraps the
9532    /// returned `LiftChainCertificate` in the W11 `Certified<_>` carrier.
9533    ///
9534    /// # Errors
9535    ///
9536    /// Returns `GenericImpossibilityWitness` when no certificate can be issued.
9537    pub mod tower_completeness {
9538        use super::*;
9539        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9540        ///
9541        /// # Errors
9542        ///
9543        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9544        pub fn certify<T, P, H>(
9545            input: &Validated<T, P>,
9546        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9547        where
9548            T: crate::pipeline::ConstrainedTypeShape,
9549            P: crate::enforcement::ValidationPhase,
9550            H: crate::enforcement::Hasher,
9551        {
9552            certify_at::<T, P, H>(input, WittLevel::W32)
9553        }
9554
9555        /// Certify at an explicit Witt level.
9556        ///
9557        /// # Errors
9558        ///
9559        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9560        pub fn certify_at<T, P, H>(
9561            input: &Validated<T, P>,
9562            level: WittLevel,
9563        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9564        where
9565            T: crate::pipeline::ConstrainedTypeShape,
9566            P: crate::enforcement::ValidationPhase,
9567            H: crate::enforcement::Hasher,
9568        {
9569            crate::pipeline::run_tower_completeness::<T, H>(input.inner(), level)
9570                .map(|v| Certified::new(*v.inner()))
9571                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9572        }
9573    }
9574
9575    /// v0.2.2 closure: certify incremental completeness for a constrained type.
9576    pub mod incremental_completeness {
9577        use super::*;
9578        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9579        ///
9580        /// # Errors
9581        ///
9582        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9583        pub fn certify<T, P, H>(
9584            input: &Validated<T, P>,
9585        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9586        where
9587            T: crate::pipeline::ConstrainedTypeShape,
9588            P: crate::enforcement::ValidationPhase,
9589            H: crate::enforcement::Hasher,
9590        {
9591            certify_at::<T, P, H>(input, WittLevel::W32)
9592        }
9593
9594        /// Certify at an explicit Witt level.
9595        ///
9596        /// # Errors
9597        ///
9598        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9599        pub fn certify_at<T, P, H>(
9600            input: &Validated<T, P>,
9601            level: WittLevel,
9602        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9603        where
9604            T: crate::pipeline::ConstrainedTypeShape,
9605            P: crate::enforcement::ValidationPhase,
9606            H: crate::enforcement::Hasher,
9607        {
9608            crate::pipeline::run_incremental_completeness::<T, H>(input.inner(), level)
9609                .map(|v| Certified::new(*v.inner()))
9610                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9611        }
9612    }
9613
9614    /// v0.2.2 closure: certify grounding-aware reduction for a CompileUnit.
9615    pub mod grounding_aware {
9616        use super::*;
9617        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9618        ///
9619        /// # Errors
9620        ///
9621        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9622        pub fn certify<P, H, const INLINE_BYTES: usize>(
9623            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
9624        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9625        where
9626            P: crate::enforcement::ValidationPhase,
9627            H: crate::enforcement::Hasher,
9628        {
9629            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
9630        }
9631
9632        /// Certify at an explicit Witt level.
9633        ///
9634        /// # Errors
9635        ///
9636        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9637        pub fn certify_at<P, H, const INLINE_BYTES: usize>(
9638            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
9639            level: WittLevel,
9640        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9641        where
9642            P: crate::enforcement::ValidationPhase,
9643            H: crate::enforcement::Hasher,
9644        {
9645            crate::pipeline::run_grounding_aware::<INLINE_BYTES, H>(input.inner(), level)
9646                .map(|v| Certified::new(*v.inner()))
9647                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9648        }
9649    }
9650
9651    /// v0.2.2 closure: certify inhabitance for a constrained type.
9652    pub mod inhabitance {
9653        use super::*;
9654        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9655        ///
9656        /// # Errors
9657        ///
9658        /// Returns `Certified<InhabitanceImpossibilityWitness>` on failure.
9659        pub fn certify<T, P, H>(
9660            input: &Validated<T, P>,
9661        ) -> Result<Certified<InhabitanceCertificate>, Certified<InhabitanceImpossibilityWitness>>
9662        where
9663            T: crate::pipeline::ConstrainedTypeShape,
9664            P: crate::enforcement::ValidationPhase,
9665            H: crate::enforcement::Hasher,
9666        {
9667            certify_at::<T, P, H>(input, WittLevel::W32)
9668        }
9669
9670        /// Certify at an explicit Witt level.
9671        ///
9672        /// # Errors
9673        ///
9674        /// Returns `Certified<InhabitanceImpossibilityWitness>` on failure.
9675        pub fn certify_at<T, P, H>(
9676            input: &Validated<T, P>,
9677            level: WittLevel,
9678        ) -> Result<Certified<InhabitanceCertificate>, Certified<InhabitanceImpossibilityWitness>>
9679        where
9680            T: crate::pipeline::ConstrainedTypeShape,
9681            P: crate::enforcement::ValidationPhase,
9682            H: crate::enforcement::Hasher,
9683        {
9684            crate::pipeline::run_inhabitance::<T, H>(input.inner(), level)
9685                .map(|v: Validated<InhabitanceCertificate>| Certified::new(*v.inner()))
9686                .map_err(|_| Certified::new(InhabitanceImpossibilityWitness::default()))
9687        }
9688    }
9689
9690    /// v0.2.2 Phase C.4: multiplication resolver — picks the cost-optimal
9691    /// Toom-Cook splitting factor R for a `Datum<L>` × `Datum<L>`
9692    /// multiplication at a given call-site context. The cost function is
9693    /// closed-form and grounded in `op:OA_5`:
9694    ///
9695    /// ```text
9696    /// sub_mul_count(N, R) = (2R - 1)  for R > 1
9697    ///                     = 1         for R = 1 (schoolbook)
9698    /// landauer_cost(N, R) = sub_mul_count(N, R) · (N/R)² · 64 · ln 2  nats
9699    /// ```
9700    pub mod multiplication {
9701        use super::super::{MulContext, MultiplicationCertificate};
9702        use super::*;
9703
9704        /// v0.2.2 T6.7: parameterized over `H: Hasher`. Pick the cost-optimal
9705        /// splitting factor R for a multiplication at the given call-site
9706        /// context and return a `Certified<MultiplicationCertificate>`
9707        /// recording the choice. The certificate carries a substrate-computed
9708        /// content fingerprint.
9709        ///
9710        /// # Errors
9711        ///
9712        /// Returns `GenericImpossibilityWitness` if the call-site context is
9713        /// inadmissible (`stack_budget_bytes == 0`). The resolver is otherwise
9714        /// total over admissible inputs.
9715        pub fn certify<H: crate::enforcement::Hasher>(
9716            context: &MulContext,
9717        ) -> Result<Certified<MultiplicationCertificate>, GenericImpossibilityWitness> {
9718            if context.stack_budget_bytes == 0 {
9719                return Err(GenericImpossibilityWitness::default());
9720            }
9721            // Closed-form cost search: R = 1 (schoolbook) vs R = 2 (Karatsuba).
9722            let limb_count = context.limb_count.max(1);
9723            let karatsuba_stack_need = limb_count * 8 * 6;
9724            let choose_karatsuba = !context.const_eval
9725                && (context.stack_budget_bytes as usize) >= karatsuba_stack_need;
9726            // v0.2.2 T6.7: compute substrate fingerprint over the MulContext.
9727            let mut hasher = H::initial();
9728            hasher = hasher.fold_bytes(&context.stack_budget_bytes.to_be_bytes());
9729            hasher = hasher.fold_byte(if context.const_eval { 1 } else { 0 });
9730            hasher = hasher.fold_bytes(&(limb_count as u64).to_be_bytes());
9731            hasher = hasher.fold_byte(crate::enforcement::certificate_kind_discriminant(
9732                crate::enforcement::CertificateKind::Multiplication,
9733            ));
9734            let buffer = hasher.finalize();
9735            let fp =
9736                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9737            let cert = if choose_karatsuba {
9738                MultiplicationCertificate::with_evidence(
9739                    2,
9740                    3,
9741                    karatsuba_landauer_cost(limb_count),
9742                    fp,
9743                )
9744            } else {
9745                MultiplicationCertificate::with_evidence(
9746                    1,
9747                    1,
9748                    schoolbook_landauer_cost(limb_count),
9749                    fp,
9750                )
9751            };
9752            Ok(Certified::new(cert))
9753        }
9754
9755        // Local default-host alias for the Landauer cost helpers below.
9756        type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
9757
9758        /// Schoolbook Landauer cost in nats for an N-limb multiplication:
9759        /// `N² · 64 · ln 2`. Returns the IEEE-754 bit pattern;
9760        /// see `MultiplicationEvidence::landauer_cost_nats_bits`.
9761        fn schoolbook_landauer_cost(limb_count: usize) -> u64 {
9762            let n = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(limb_count as u32);
9763            let sixty_four = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(64);
9764            let ln_2 =
9765                <DefaultDecimal as crate::DecimalTranscendental>::from_bits(crate::LN_2_BITS);
9766            (n * n * sixty_four * ln_2).to_bits()
9767        }
9768
9769        /// Karatsuba Landauer cost: `3 · (N/2)² · 64 · ln 2`.
9770        /// Returns the IEEE-754 bit pattern.
9771        fn karatsuba_landauer_cost(limb_count: usize) -> u64 {
9772            let n = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(limb_count as u32);
9773            let two = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(2);
9774            let three = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(3);
9775            let sixty_four = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(64);
9776            let ln_2 =
9777                <DefaultDecimal as crate::DecimalTranscendental>::from_bits(crate::LN_2_BITS);
9778            let n_half = n / two;
9779            (three * n_half * n_half * sixty_four * ln_2).to_bits()
9780        }
9781    }
9782
9783    /// v0.2.2 Phase C: `pub(crate)` trait parameterizing the 15 Phase D resolver kernels.
9784    /// Each kernel marker supplies a `CertificateKind` discriminant and its
9785    /// ontology-declared certificate type via `type Cert`. The shared
9786    /// `certify_at` bodies (see `emit_phase_d_ct_body` / `emit_phase_d_cu_body`)
9787    /// mint `Certified<Kernel::Cert>` directly — so each resolver's cert class
9788    /// matches its `resolver:CertifyMapping` in the ontology.
9789    pub(crate) trait ResolverKernel {
9790        const KIND: crate::enforcement::CertificateKind;
9791        /// Phase X.1: the ontology-declared certificate class produced by
9792        /// this resolver (per `resolver:CertifyMapping`).
9793        type Cert: crate::enforcement::Certificate;
9794    }
9795
9796    /// Phase D (target §4.2): `resolver:TwoSatDecider` — certify that `predicate:Is2SatShape` inputs are 2-SAT-decidable via the Aspvall-Plass-Tarjan strongly-connected-components decider.
9797    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9798    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9799    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9800    /// failure — the witness itself is certified so downstream can persist it
9801    /// alongside success certs in a uniform `Certified<_>` channel.
9802    /// Phase X.1: the produced cert class is the ontology-declared class for
9803    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9804    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9805    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9806    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9807    /// kernels so each resolver's class discrimination is load-bearing.
9808    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9809    /// kernel's composition spec) whose output is folded into the canonical
9810    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9811    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9812    /// content-addressed per its ontology class.
9813    pub mod two_sat_decider {
9814        use super::*;
9815
9816        #[doc(hidden)]
9817        pub struct Kernel;
9818        impl super::ResolverKernel for Kernel {
9819            type Cert = crate::enforcement::GroundingCertificate;
9820            const KIND: crate::enforcement::CertificateKind =
9821                crate::enforcement::CertificateKind::TwoSat;
9822        }
9823
9824        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
9825        ///
9826        /// # Errors
9827        ///
9828        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9829        pub fn certify<
9830            T: crate::pipeline::ConstrainedTypeShape,
9831            P: crate::enforcement::ValidationPhase,
9832            H: crate::enforcement::Hasher,
9833        >(
9834            input: &Validated<T, P>,
9835        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9836        {
9837            certify_at::<T, P, H>(input, WittLevel::W32)
9838        }
9839
9840        /// Phase D (target §4.2): certify at an explicit Witt level.
9841        ///
9842        /// # Errors
9843        ///
9844        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9845        pub fn certify_at<
9846            T: crate::pipeline::ConstrainedTypeShape,
9847            P: crate::enforcement::ValidationPhase,
9848            H: crate::enforcement::Hasher,
9849        >(
9850            input: &Validated<T, P>,
9851            level: WittLevel,
9852        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9853        {
9854            let _ = input.inner();
9855            let witt_bits = level.witt_length() as u16;
9856            let (tr_bits, tr_constraints, tr_sat) =
9857                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
9858                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
9859            if tr_sat == 0 {
9860                return Err(Certified::new(GenericImpossibilityWitness::default()));
9861            }
9862            let mut hasher = H::initial();
9863            hasher = crate::enforcement::fold_terminal_reduction(
9864                hasher,
9865                tr_bits,
9866                tr_constraints,
9867                tr_sat,
9868            );
9869            hasher = crate::enforcement::fold_unit_digest(
9870                hasher,
9871                witt_bits,
9872                witt_bits as u64,
9873                T::IRI,
9874                T::SITE_COUNT,
9875                T::CONSTRAINTS,
9876                <Kernel as super::ResolverKernel>::KIND,
9877            );
9878            let buffer = hasher.finalize();
9879            let fp =
9880                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9881            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
9882            Ok(Certified::new(cert))
9883        }
9884    }
9885
9886    /// Phase D (target §4.2): `resolver:HornSatDecider` — certify that `predicate:IsHornShape` inputs are Horn-SAT-decidable via unit propagation (O(n+m)).
9887    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9888    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9889    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9890    /// failure — the witness itself is certified so downstream can persist it
9891    /// alongside success certs in a uniform `Certified<_>` channel.
9892    /// Phase X.1: the produced cert class is the ontology-declared class for
9893    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9894    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9895    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9896    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9897    /// kernels so each resolver's class discrimination is load-bearing.
9898    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9899    /// kernel's composition spec) whose output is folded into the canonical
9900    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9901    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9902    /// content-addressed per its ontology class.
9903    pub mod horn_sat_decider {
9904        use super::*;
9905
9906        #[doc(hidden)]
9907        pub struct Kernel;
9908        impl super::ResolverKernel for Kernel {
9909            type Cert = crate::enforcement::GroundingCertificate;
9910            const KIND: crate::enforcement::CertificateKind =
9911                crate::enforcement::CertificateKind::HornSat;
9912        }
9913
9914        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
9915        ///
9916        /// # Errors
9917        ///
9918        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9919        pub fn certify<
9920            T: crate::pipeline::ConstrainedTypeShape,
9921            P: crate::enforcement::ValidationPhase,
9922            H: crate::enforcement::Hasher,
9923        >(
9924            input: &Validated<T, P>,
9925        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9926        {
9927            certify_at::<T, P, H>(input, WittLevel::W32)
9928        }
9929
9930        /// Phase D (target §4.2): certify at an explicit Witt level.
9931        ///
9932        /// # Errors
9933        ///
9934        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9935        pub fn certify_at<
9936            T: crate::pipeline::ConstrainedTypeShape,
9937            P: crate::enforcement::ValidationPhase,
9938            H: crate::enforcement::Hasher,
9939        >(
9940            input: &Validated<T, P>,
9941            level: WittLevel,
9942        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9943        {
9944            let _ = input.inner();
9945            let witt_bits = level.witt_length() as u16;
9946            let (tr_bits, tr_constraints, tr_sat) =
9947                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
9948                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
9949            if tr_sat == 0 {
9950                return Err(Certified::new(GenericImpossibilityWitness::default()));
9951            }
9952            let mut hasher = H::initial();
9953            hasher = crate::enforcement::fold_terminal_reduction(
9954                hasher,
9955                tr_bits,
9956                tr_constraints,
9957                tr_sat,
9958            );
9959            hasher = crate::enforcement::fold_unit_digest(
9960                hasher,
9961                witt_bits,
9962                witt_bits as u64,
9963                T::IRI,
9964                T::SITE_COUNT,
9965                T::CONSTRAINTS,
9966                <Kernel as super::ResolverKernel>::KIND,
9967            );
9968            let buffer = hasher.finalize();
9969            let fp =
9970                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9971            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
9972            Ok(Certified::new(cert))
9973        }
9974    }
9975
9976    /// Phase D (target §4.2): `resolver:ResidualVerdictResolver` — certify `predicate:IsResidualFragment` inputs; returns `GenericImpossibilityWitness` when the residual fragment has no polynomial decider available (the canonical impossibility path).
9977    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9978    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9979    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9980    /// failure — the witness itself is certified so downstream can persist it
9981    /// alongside success certs in a uniform `Certified<_>` channel.
9982    /// Phase X.1: the produced cert class is the ontology-declared class for
9983    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9984    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9985    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9986    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9987    /// kernels so each resolver's class discrimination is load-bearing.
9988    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9989    /// kernel's composition spec) whose output is folded into the canonical
9990    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9991    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9992    /// content-addressed per its ontology class.
9993    pub mod residual_verdict {
9994        use super::*;
9995
9996        #[doc(hidden)]
9997        pub struct Kernel;
9998        impl super::ResolverKernel for Kernel {
9999            type Cert = crate::enforcement::GroundingCertificate;
10000            const KIND: crate::enforcement::CertificateKind =
10001                crate::enforcement::CertificateKind::ResidualVerdict;
10002        }
10003
10004        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10005        ///
10006        /// # Errors
10007        ///
10008        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10009        pub fn certify<
10010            T: crate::pipeline::ConstrainedTypeShape,
10011            P: crate::enforcement::ValidationPhase,
10012            H: crate::enforcement::Hasher,
10013        >(
10014            input: &Validated<T, P>,
10015        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10016        {
10017            certify_at::<T, P, H>(input, WittLevel::W32)
10018        }
10019
10020        /// Phase D (target §4.2): certify at an explicit Witt level.
10021        ///
10022        /// # Errors
10023        ///
10024        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10025        pub fn certify_at<
10026            T: crate::pipeline::ConstrainedTypeShape,
10027            P: crate::enforcement::ValidationPhase,
10028            H: crate::enforcement::Hasher,
10029        >(
10030            input: &Validated<T, P>,
10031            level: WittLevel,
10032        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10033        {
10034            let _ = input.inner();
10035            let witt_bits = level.witt_length() as u16;
10036            let (tr_bits, tr_constraints, tr_sat) =
10037                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10038                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10039            if tr_sat == 0 {
10040                return Err(Certified::new(GenericImpossibilityWitness::default()));
10041            }
10042            let mut hasher = H::initial();
10043            hasher = crate::enforcement::fold_terminal_reduction(
10044                hasher,
10045                tr_bits,
10046                tr_constraints,
10047                tr_sat,
10048            );
10049            hasher = crate::enforcement::fold_unit_digest(
10050                hasher,
10051                witt_bits,
10052                witt_bits as u64,
10053                T::IRI,
10054                T::SITE_COUNT,
10055                T::CONSTRAINTS,
10056                <Kernel as super::ResolverKernel>::KIND,
10057            );
10058            let buffer = hasher.finalize();
10059            let fp =
10060                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10061            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10062            Ok(Certified::new(cert))
10063        }
10064    }
10065
10066    /// Phase D (target §4.2): `resolver:CanonicalFormResolver` — compute the canonical form of a `ConstrainedType` by running the reduction stages and emitting a `Certified<TransformCertificate>` whose fingerprint uniquely identifies the canonicalized input.
10067    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10068    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10069    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10070    /// failure — the witness itself is certified so downstream can persist it
10071    /// alongside success certs in a uniform `Certified<_>` channel.
10072    /// Phase X.1: the produced cert class is the ontology-declared class for
10073    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10074    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10075    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10076    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10077    /// kernels so each resolver's class discrimination is load-bearing.
10078    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10079    /// kernel's composition spec) whose output is folded into the canonical
10080    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10081    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10082    /// content-addressed per its ontology class.
10083    pub mod canonical_form {
10084        use super::*;
10085
10086        #[doc(hidden)]
10087        pub struct Kernel;
10088        impl super::ResolverKernel for Kernel {
10089            type Cert = crate::enforcement::TransformCertificate;
10090            const KIND: crate::enforcement::CertificateKind =
10091                crate::enforcement::CertificateKind::CanonicalForm;
10092        }
10093
10094        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10095        ///
10096        /// # Errors
10097        ///
10098        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10099        pub fn certify<
10100            T: crate::pipeline::ConstrainedTypeShape,
10101            P: crate::enforcement::ValidationPhase,
10102            H: crate::enforcement::Hasher,
10103        >(
10104            input: &Validated<T, P>,
10105        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10106        {
10107            certify_at::<T, P, H>(input, WittLevel::W32)
10108        }
10109
10110        /// Phase D (target §4.2): certify at an explicit Witt level.
10111        ///
10112        /// # Errors
10113        ///
10114        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10115        pub fn certify_at<
10116            T: crate::pipeline::ConstrainedTypeShape,
10117            P: crate::enforcement::ValidationPhase,
10118            H: crate::enforcement::Hasher,
10119        >(
10120            input: &Validated<T, P>,
10121            level: WittLevel,
10122        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10123        {
10124            let _ = input.inner();
10125            let witt_bits = level.witt_length() as u16;
10126            let (tr_bits, tr_constraints, tr_sat) =
10127                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10128                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10129            if tr_sat == 0 {
10130                return Err(Certified::new(GenericImpossibilityWitness::default()));
10131            }
10132            let mut hasher = H::initial();
10133            hasher = crate::enforcement::fold_terminal_reduction(
10134                hasher,
10135                tr_bits,
10136                tr_constraints,
10137                tr_sat,
10138            );
10139            let (tr2_bits, tr2_constraints, tr2_sat) =
10140                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10141                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10142            // Church-Rosser: second reduction must agree with the first.
10143            if tr2_bits != tr_bits || tr2_constraints != tr_constraints || tr2_sat != tr_sat {
10144                return Err(Certified::new(GenericImpossibilityWitness::default()));
10145            }
10146            hasher = crate::enforcement::fold_terminal_reduction(
10147                hasher,
10148                tr2_bits,
10149                tr2_constraints,
10150                tr2_sat,
10151            );
10152            hasher = crate::enforcement::fold_unit_digest(
10153                hasher,
10154                witt_bits,
10155                witt_bits as u64,
10156                T::IRI,
10157                T::SITE_COUNT,
10158                T::CONSTRAINTS,
10159                <Kernel as super::ResolverKernel>::KIND,
10160            );
10161            let buffer = hasher.finalize();
10162            let fp =
10163                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10164            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10165            Ok(Certified::new(cert))
10166        }
10167    }
10168
10169    /// Phase D (target §4.2): `resolver:TypeSynthesisResolver` — run the ψ-pipeline in inverse mode: given a `TypeSynthesisGoal` expressed through `ConstrainedTypeShape`, synthesize the type's carrier or signal impossibility.
10170    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10171    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10172    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10173    /// failure — the witness itself is certified so downstream can persist it
10174    /// alongside success certs in a uniform `Certified<_>` channel.
10175    /// Phase X.1: the produced cert class is the ontology-declared class for
10176    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10177    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10178    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10179    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10180    /// kernels so each resolver's class discrimination is load-bearing.
10181    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10182    /// kernel's composition spec) whose output is folded into the canonical
10183    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10184    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10185    /// content-addressed per its ontology class.
10186    pub mod type_synthesis {
10187        use super::*;
10188
10189        #[doc(hidden)]
10190        pub struct Kernel;
10191        impl super::ResolverKernel for Kernel {
10192            type Cert = crate::enforcement::TransformCertificate;
10193            const KIND: crate::enforcement::CertificateKind =
10194                crate::enforcement::CertificateKind::TypeSynthesis;
10195        }
10196
10197        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10198        ///
10199        /// # Errors
10200        ///
10201        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10202        pub fn certify<
10203            T: crate::pipeline::ConstrainedTypeShape,
10204            P: crate::enforcement::ValidationPhase,
10205            H: crate::enforcement::Hasher,
10206        >(
10207            input: &Validated<T, P>,
10208        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10209        {
10210            certify_at::<T, P, H>(input, WittLevel::W32)
10211        }
10212
10213        /// Phase D (target §4.2): certify at an explicit Witt level.
10214        ///
10215        /// # Errors
10216        ///
10217        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10218        pub fn certify_at<
10219            T: crate::pipeline::ConstrainedTypeShape,
10220            P: crate::enforcement::ValidationPhase,
10221            H: crate::enforcement::Hasher,
10222        >(
10223            input: &Validated<T, P>,
10224            level: WittLevel,
10225        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10226        {
10227            let _ = input.inner();
10228            let witt_bits = level.witt_length() as u16;
10229            let (tr_bits, tr_constraints, tr_sat) =
10230                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10231                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10232            if tr_sat == 0 {
10233                return Err(Certified::new(GenericImpossibilityWitness::default()));
10234            }
10235            let mut hasher = H::initial();
10236            hasher = crate::enforcement::fold_terminal_reduction(
10237                hasher,
10238                tr_bits,
10239                tr_constraints,
10240                tr_sat,
10241            );
10242            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10243                .map_err(crate::enforcement::Certified::new)?;
10244            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10245            let (residual, entropy) = crate::enforcement::primitive_descent_metrics::<T>(&betti);
10246            hasher = crate::enforcement::fold_descent_metrics(hasher, residual, entropy);
10247            hasher = crate::enforcement::fold_unit_digest(
10248                hasher,
10249                witt_bits,
10250                witt_bits as u64,
10251                T::IRI,
10252                T::SITE_COUNT,
10253                T::CONSTRAINTS,
10254                <Kernel as super::ResolverKernel>::KIND,
10255            );
10256            let buffer = hasher.finalize();
10257            let fp =
10258                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10259            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10260            Ok(Certified::new(cert))
10261        }
10262    }
10263
10264    /// Phase D (target §4.2): `resolver:HomotopyResolver` — compute homotopy-type observables (fundamental group rank, Postnikov-truncation records) by walking the constraint-nerve chain and extracting Betti-number evidence.
10265    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10266    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10267    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10268    /// failure — the witness itself is certified so downstream can persist it
10269    /// alongside success certs in a uniform `Certified<_>` channel.
10270    /// Phase X.1: the produced cert class is the ontology-declared class for
10271    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10272    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10273    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10274    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10275    /// kernels so each resolver's class discrimination is load-bearing.
10276    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10277    /// kernel's composition spec) whose output is folded into the canonical
10278    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10279    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10280    /// content-addressed per its ontology class.
10281    pub mod homotopy {
10282        use super::*;
10283
10284        #[doc(hidden)]
10285        pub struct Kernel;
10286        impl super::ResolverKernel for Kernel {
10287            type Cert = crate::enforcement::TransformCertificate;
10288            const KIND: crate::enforcement::CertificateKind =
10289                crate::enforcement::CertificateKind::Homotopy;
10290        }
10291
10292        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10293        ///
10294        /// # Errors
10295        ///
10296        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10297        pub fn certify<
10298            T: crate::pipeline::ConstrainedTypeShape,
10299            P: crate::enforcement::ValidationPhase,
10300            H: crate::enforcement::Hasher,
10301        >(
10302            input: &Validated<T, P>,
10303        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10304        {
10305            certify_at::<T, P, H>(input, WittLevel::W32)
10306        }
10307
10308        /// Phase D (target §4.2): certify at an explicit Witt level.
10309        ///
10310        /// # Errors
10311        ///
10312        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10313        pub fn certify_at<
10314            T: crate::pipeline::ConstrainedTypeShape,
10315            P: crate::enforcement::ValidationPhase,
10316            H: crate::enforcement::Hasher,
10317        >(
10318            input: &Validated<T, P>,
10319            level: WittLevel,
10320        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10321        {
10322            let _ = input.inner();
10323            let witt_bits = level.witt_length() as u16;
10324            let (tr_bits, tr_constraints, tr_sat) =
10325                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10326                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10327            if tr_sat == 0 {
10328                return Err(Certified::new(GenericImpossibilityWitness::default()));
10329            }
10330            let mut hasher = H::initial();
10331            hasher = crate::enforcement::fold_terminal_reduction(
10332                hasher,
10333                tr_bits,
10334                tr_constraints,
10335                tr_sat,
10336            );
10337            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10338                .map_err(crate::enforcement::Certified::new)?;
10339            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10340            hasher = crate::enforcement::fold_unit_digest(
10341                hasher,
10342                witt_bits,
10343                witt_bits as u64,
10344                T::IRI,
10345                T::SITE_COUNT,
10346                T::CONSTRAINTS,
10347                <Kernel as super::ResolverKernel>::KIND,
10348            );
10349            let buffer = hasher.finalize();
10350            let fp =
10351                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10352            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10353            Ok(Certified::new(cert))
10354        }
10355    }
10356
10357    /// Phase D (target §4.2): `resolver:MonodromyResolver` — compute monodromy-group observables by tracing the constraint-nerve boundary cycles at the input's Witt level.
10358    /// Returns `Certified<IsometryCertificate>` on success carrying the Witt
10359    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10360    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10361    /// failure — the witness itself is certified so downstream can persist it
10362    /// alongside success certs in a uniform `Certified<_>` channel.
10363    /// Phase X.1: the produced cert class is the ontology-declared class for
10364    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10365    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10366    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10367    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10368    /// kernels so each resolver's class discrimination is load-bearing.
10369    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10370    /// kernel's composition spec) whose output is folded into the canonical
10371    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10372    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10373    /// content-addressed per its ontology class.
10374    pub mod monodromy {
10375        use super::*;
10376
10377        #[doc(hidden)]
10378        pub struct Kernel;
10379        impl super::ResolverKernel for Kernel {
10380            type Cert = crate::enforcement::IsometryCertificate;
10381            const KIND: crate::enforcement::CertificateKind =
10382                crate::enforcement::CertificateKind::Monodromy;
10383        }
10384
10385        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10386        ///
10387        /// # Errors
10388        ///
10389        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10390        pub fn certify<
10391            T: crate::pipeline::ConstrainedTypeShape,
10392            P: crate::enforcement::ValidationPhase,
10393            H: crate::enforcement::Hasher,
10394        >(
10395            input: &Validated<T, P>,
10396        ) -> Result<Certified<IsometryCertificate>, Certified<GenericImpossibilityWitness>>
10397        {
10398            certify_at::<T, P, H>(input, WittLevel::W32)
10399        }
10400
10401        /// Phase D (target §4.2): certify at an explicit Witt level.
10402        ///
10403        /// # Errors
10404        ///
10405        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10406        pub fn certify_at<
10407            T: crate::pipeline::ConstrainedTypeShape,
10408            P: crate::enforcement::ValidationPhase,
10409            H: crate::enforcement::Hasher,
10410        >(
10411            input: &Validated<T, P>,
10412            level: WittLevel,
10413        ) -> Result<Certified<IsometryCertificate>, Certified<GenericImpossibilityWitness>>
10414        {
10415            let _ = input.inner();
10416            let witt_bits = level.witt_length() as u16;
10417            let (tr_bits, tr_constraints, tr_sat) =
10418                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10419                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10420            if tr_sat == 0 {
10421                return Err(Certified::new(GenericImpossibilityWitness::default()));
10422            }
10423            let mut hasher = H::initial();
10424            hasher = crate::enforcement::fold_terminal_reduction(
10425                hasher,
10426                tr_bits,
10427                tr_constraints,
10428                tr_sat,
10429            );
10430            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10431                .map_err(crate::enforcement::Certified::new)?;
10432            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10433            let (orbit_size, representative) =
10434                crate::enforcement::primitive_dihedral_signature::<T>();
10435            hasher =
10436                crate::enforcement::fold_dihedral_signature(hasher, orbit_size, representative);
10437            hasher = crate::enforcement::fold_unit_digest(
10438                hasher,
10439                witt_bits,
10440                witt_bits as u64,
10441                T::IRI,
10442                T::SITE_COUNT,
10443                T::CONSTRAINTS,
10444                <Kernel as super::ResolverKernel>::KIND,
10445            );
10446            let buffer = hasher.finalize();
10447            let fp =
10448                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10449            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10450            Ok(Certified::new(cert))
10451        }
10452    }
10453
10454    /// Phase D (target §4.2): `resolver:ModuliResolver` — compute the local moduli-space structure at a `CompleteType`: DeformationComplex, HolonomyStratum, tangent/obstruction dimensions.
10455    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10456    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10457    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10458    /// failure — the witness itself is certified so downstream can persist it
10459    /// alongside success certs in a uniform `Certified<_>` channel.
10460    /// Phase X.1: the produced cert class is the ontology-declared class for
10461    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10462    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10463    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10464    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10465    /// kernels so each resolver's class discrimination is load-bearing.
10466    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10467    /// kernel's composition spec) whose output is folded into the canonical
10468    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10469    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10470    /// content-addressed per its ontology class.
10471    pub mod moduli {
10472        use super::*;
10473
10474        #[doc(hidden)]
10475        pub struct Kernel;
10476        impl super::ResolverKernel for Kernel {
10477            type Cert = crate::enforcement::TransformCertificate;
10478            const KIND: crate::enforcement::CertificateKind =
10479                crate::enforcement::CertificateKind::Moduli;
10480        }
10481
10482        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10483        ///
10484        /// # Errors
10485        ///
10486        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10487        pub fn certify<
10488            T: crate::pipeline::ConstrainedTypeShape,
10489            P: crate::enforcement::ValidationPhase,
10490            H: crate::enforcement::Hasher,
10491        >(
10492            input: &Validated<T, P>,
10493        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10494        {
10495            certify_at::<T, P, H>(input, WittLevel::W32)
10496        }
10497
10498        /// Phase D (target §4.2): certify at an explicit Witt level.
10499        ///
10500        /// # Errors
10501        ///
10502        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10503        pub fn certify_at<
10504            T: crate::pipeline::ConstrainedTypeShape,
10505            P: crate::enforcement::ValidationPhase,
10506            H: crate::enforcement::Hasher,
10507        >(
10508            input: &Validated<T, P>,
10509            level: WittLevel,
10510        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10511        {
10512            let _ = input.inner();
10513            let witt_bits = level.witt_length() as u16;
10514            let (tr_bits, tr_constraints, tr_sat) =
10515                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10516                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10517            if tr_sat == 0 {
10518                return Err(Certified::new(GenericImpossibilityWitness::default()));
10519            }
10520            let mut hasher = H::initial();
10521            hasher = crate::enforcement::fold_terminal_reduction(
10522                hasher,
10523                tr_bits,
10524                tr_constraints,
10525                tr_sat,
10526            );
10527            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10528                .map_err(crate::enforcement::Certified::new)?;
10529            let automorphisms: u32 = betti[0];
10530            let deformations: u32 = if crate::enforcement::MAX_BETTI_DIMENSION > 1 {
10531                betti[1]
10532            } else {
10533                0
10534            };
10535            let obstructions: u32 = if crate::enforcement::MAX_BETTI_DIMENSION > 2 {
10536                betti[2]
10537            } else {
10538                0
10539            };
10540            hasher = hasher.fold_bytes(&automorphisms.to_be_bytes());
10541            hasher = hasher.fold_bytes(&deformations.to_be_bytes());
10542            hasher = hasher.fold_bytes(&obstructions.to_be_bytes());
10543            hasher = crate::enforcement::fold_unit_digest(
10544                hasher,
10545                witt_bits,
10546                witt_bits as u64,
10547                T::IRI,
10548                T::SITE_COUNT,
10549                T::CONSTRAINTS,
10550                <Kernel as super::ResolverKernel>::KIND,
10551            );
10552            let buffer = hasher.finalize();
10553            let fp =
10554                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10555            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10556            Ok(Certified::new(cert))
10557        }
10558    }
10559
10560    /// Phase D (target §4.2): `resolver:JacobianGuidedResolver` — drive reduction using the per-site Jacobian profile; short-circuits when the Jacobian stabilizes, producing a cert attesting the stabilized observable.
10561    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10562    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10563    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10564    /// failure — the witness itself is certified so downstream can persist it
10565    /// alongside success certs in a uniform `Certified<_>` channel.
10566    /// Phase X.1: the produced cert class is the ontology-declared class for
10567    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10568    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10569    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10570    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10571    /// kernels so each resolver's class discrimination is load-bearing.
10572    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10573    /// kernel's composition spec) whose output is folded into the canonical
10574    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10575    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10576    /// content-addressed per its ontology class.
10577    pub mod jacobian_guided {
10578        use super::*;
10579
10580        #[doc(hidden)]
10581        pub struct Kernel;
10582        impl super::ResolverKernel for Kernel {
10583            type Cert = crate::enforcement::GroundingCertificate;
10584            const KIND: crate::enforcement::CertificateKind =
10585                crate::enforcement::CertificateKind::JacobianGuided;
10586        }
10587
10588        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10589        ///
10590        /// # Errors
10591        ///
10592        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10593        pub fn certify<
10594            T: crate::pipeline::ConstrainedTypeShape,
10595            P: crate::enforcement::ValidationPhase,
10596            H: crate::enforcement::Hasher,
10597        >(
10598            input: &Validated<T, P>,
10599        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10600        {
10601            certify_at::<T, P, H>(input, WittLevel::W32)
10602        }
10603
10604        /// Phase D (target §4.2): certify at an explicit Witt level.
10605        ///
10606        /// # Errors
10607        ///
10608        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10609        pub fn certify_at<
10610            T: crate::pipeline::ConstrainedTypeShape,
10611            P: crate::enforcement::ValidationPhase,
10612            H: crate::enforcement::Hasher,
10613        >(
10614            input: &Validated<T, P>,
10615            level: WittLevel,
10616        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10617        {
10618            let _ = input.inner();
10619            let witt_bits = level.witt_length() as u16;
10620            let (tr_bits, tr_constraints, tr_sat) =
10621                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10622                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10623            if tr_sat == 0 {
10624                return Err(Certified::new(GenericImpossibilityWitness::default()));
10625            }
10626            let mut hasher = H::initial();
10627            hasher = crate::enforcement::fold_terminal_reduction(
10628                hasher,
10629                tr_bits,
10630                tr_constraints,
10631                tr_sat,
10632            );
10633            let jac = crate::enforcement::primitive_curvature_jacobian::<T>();
10634            hasher = crate::enforcement::fold_jacobian_profile(hasher, &jac);
10635            let selected_site = crate::enforcement::primitive_dc10_select(&jac);
10636            hasher = hasher.fold_bytes(&(selected_site as u32).to_be_bytes());
10637            hasher = crate::enforcement::fold_unit_digest(
10638                hasher,
10639                witt_bits,
10640                witt_bits as u64,
10641                T::IRI,
10642                T::SITE_COUNT,
10643                T::CONSTRAINTS,
10644                <Kernel as super::ResolverKernel>::KIND,
10645            );
10646            let buffer = hasher.finalize();
10647            let fp =
10648                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10649            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10650            Ok(Certified::new(cert))
10651        }
10652    }
10653
10654    /// Phase D (target §4.2): `resolver:EvaluationResolver` — evaluate a grounded term at a given Witt level; the returned cert attests that the evaluation completed within the declared budget.
10655    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10656    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10657    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10658    /// failure — the witness itself is certified so downstream can persist it
10659    /// alongside success certs in a uniform `Certified<_>` channel.
10660    /// Phase X.1: the produced cert class is the ontology-declared class for
10661    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10662    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10663    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10664    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10665    /// kernels so each resolver's class discrimination is load-bearing.
10666    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10667    /// kernel's composition spec) whose output is folded into the canonical
10668    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10669    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10670    /// content-addressed per its ontology class.
10671    pub mod evaluation {
10672        use super::*;
10673
10674        #[doc(hidden)]
10675        pub struct Kernel;
10676        impl super::ResolverKernel for Kernel {
10677            type Cert = crate::enforcement::GroundingCertificate;
10678            const KIND: crate::enforcement::CertificateKind =
10679                crate::enforcement::CertificateKind::Evaluation;
10680        }
10681
10682        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10683        ///
10684        /// # Errors
10685        ///
10686        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10687        pub fn certify<
10688            T: crate::pipeline::ConstrainedTypeShape,
10689            P: crate::enforcement::ValidationPhase,
10690            H: crate::enforcement::Hasher,
10691        >(
10692            input: &Validated<T, P>,
10693        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10694        {
10695            certify_at::<T, P, H>(input, WittLevel::W32)
10696        }
10697
10698        /// Phase D (target §4.2): certify at an explicit Witt level.
10699        ///
10700        /// # Errors
10701        ///
10702        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10703        pub fn certify_at<
10704            T: crate::pipeline::ConstrainedTypeShape,
10705            P: crate::enforcement::ValidationPhase,
10706            H: crate::enforcement::Hasher,
10707        >(
10708            input: &Validated<T, P>,
10709            level: WittLevel,
10710        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10711        {
10712            let _ = input.inner();
10713            let witt_bits = level.witt_length() as u16;
10714            let (tr_bits, tr_constraints, tr_sat) =
10715                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10716                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10717            if tr_sat == 0 {
10718                return Err(Certified::new(GenericImpossibilityWitness::default()));
10719            }
10720            let mut hasher = H::initial();
10721            hasher = crate::enforcement::fold_terminal_reduction(
10722                hasher,
10723                tr_bits,
10724                tr_constraints,
10725                tr_sat,
10726            );
10727            hasher = crate::enforcement::fold_unit_digest(
10728                hasher,
10729                witt_bits,
10730                witt_bits as u64,
10731                T::IRI,
10732                T::SITE_COUNT,
10733                T::CONSTRAINTS,
10734                <Kernel as super::ResolverKernel>::KIND,
10735            );
10736            let buffer = hasher.finalize();
10737            let fp =
10738                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10739            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10740            Ok(Certified::new(cert))
10741        }
10742    }
10743
10744    /// Phase D (target §4.2): `resolver:SessionResolver` — advance a lease-scoped `state:ContextLease` by one reduction step and emit a cert over the lease's resulting BindingsTable.
10745    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10746    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10747    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10748    /// failure — the witness itself is certified so downstream can persist it
10749    /// alongside success certs in a uniform `Certified<_>` channel.
10750    /// Phase X.1: the produced cert class is the ontology-declared class for
10751    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10752    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10753    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10754    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10755    /// kernels so each resolver's class discrimination is load-bearing.
10756    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10757    /// kernel's composition spec) whose output is folded into the canonical
10758    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10759    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10760    /// content-addressed per its ontology class.
10761    pub mod session {
10762        use super::*;
10763
10764        #[doc(hidden)]
10765        pub struct Kernel;
10766        impl super::ResolverKernel for Kernel {
10767            type Cert = crate::enforcement::GroundingCertificate;
10768            const KIND: crate::enforcement::CertificateKind =
10769                crate::enforcement::CertificateKind::Session;
10770        }
10771
10772        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10773        ///
10774        /// # Errors
10775        ///
10776        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10777        pub fn certify<
10778            P: crate::enforcement::ValidationPhase,
10779            H: crate::enforcement::Hasher,
10780            const INLINE_BYTES: usize,
10781        >(
10782            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10783        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10784        {
10785            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10786        }
10787
10788        /// Phase D (target §4.2): certify at an explicit Witt level.
10789        ///
10790        /// # Errors
10791        ///
10792        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10793        pub fn certify_at<
10794            P: crate::enforcement::ValidationPhase,
10795            H: crate::enforcement::Hasher,
10796            const INLINE_BYTES: usize,
10797        >(
10798            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10799            level: WittLevel,
10800        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10801        {
10802            let unit = input.inner();
10803            let witt_bits = level.witt_length() as u16;
10804            let budget = unit.thermodynamic_budget();
10805            let result_type_iri = unit.result_type_iri();
10806            let mut hasher = H::initial();
10807            let (binding_count, fold_addr) =
10808                crate::enforcement::primitive_session_binding_signature(unit.bindings());
10809            hasher = crate::enforcement::fold_session_signature(hasher, binding_count, fold_addr);
10810            hasher = crate::enforcement::fold_unit_digest(
10811                hasher,
10812                witt_bits,
10813                budget,
10814                result_type_iri,
10815                0usize,
10816                &[],
10817                <Kernel as super::ResolverKernel>::KIND,
10818            );
10819            let buffer = hasher.finalize();
10820            let fp =
10821                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10822            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10823            Ok(Certified::new(cert))
10824        }
10825    }
10826
10827    /// Phase D (target §4.2): `resolver:SuperpositionResolver` — advance a SuperpositionResolver across a ψ-pipeline branch tree, maintaining an amplitude vector that satisfies the Born-rule normalization constraint (Σ|αᵢ|² = 1).
10828    /// Returns `Certified<BornRuleVerification>` on success carrying the Witt
10829    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10830    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10831    /// failure — the witness itself is certified so downstream can persist it
10832    /// alongside success certs in a uniform `Certified<_>` channel.
10833    /// Phase X.1: the produced cert class is the ontology-declared class for
10834    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10835    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10836    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10837    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10838    /// kernels so each resolver's class discrimination is load-bearing.
10839    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10840    /// kernel's composition spec) whose output is folded into the canonical
10841    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10842    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10843    /// content-addressed per its ontology class.
10844    pub mod superposition {
10845        use super::*;
10846
10847        #[doc(hidden)]
10848        pub struct Kernel;
10849        impl super::ResolverKernel for Kernel {
10850            type Cert = crate::enforcement::BornRuleVerification;
10851            const KIND: crate::enforcement::CertificateKind =
10852                crate::enforcement::CertificateKind::Superposition;
10853        }
10854
10855        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10856        ///
10857        /// # Errors
10858        ///
10859        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10860        pub fn certify<
10861            P: crate::enforcement::ValidationPhase,
10862            H: crate::enforcement::Hasher,
10863            const INLINE_BYTES: usize,
10864        >(
10865            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10866        ) -> Result<Certified<BornRuleVerification>, Certified<GenericImpossibilityWitness>>
10867        {
10868            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10869        }
10870
10871        /// Phase D (target §4.2): certify at an explicit Witt level.
10872        ///
10873        /// # Errors
10874        ///
10875        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10876        pub fn certify_at<
10877            P: crate::enforcement::ValidationPhase,
10878            H: crate::enforcement::Hasher,
10879            const INLINE_BYTES: usize,
10880        >(
10881            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10882            level: WittLevel,
10883        ) -> Result<Certified<BornRuleVerification>, Certified<GenericImpossibilityWitness>>
10884        {
10885            let unit = input.inner();
10886            let witt_bits = level.witt_length() as u16;
10887            let budget = unit.thermodynamic_budget();
10888            let result_type_iri = unit.result_type_iri();
10889            let mut hasher = H::initial();
10890            let (binding_count, fold_addr) =
10891                crate::enforcement::primitive_session_binding_signature(unit.bindings());
10892            hasher = crate::enforcement::fold_session_signature(hasher, binding_count, fold_addr);
10893            let (outcome_index, probability) =
10894                crate::enforcement::primitive_measurement_projection(budget);
10895            hasher = crate::enforcement::fold_born_outcome(hasher, outcome_index, probability);
10896            hasher = crate::enforcement::fold_unit_digest(
10897                hasher,
10898                witt_bits,
10899                budget,
10900                result_type_iri,
10901                0usize,
10902                &[],
10903                <Kernel as super::ResolverKernel>::KIND,
10904            );
10905            let buffer = hasher.finalize();
10906            let fp =
10907                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10908            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10909            Ok(Certified::new(cert))
10910        }
10911    }
10912
10913    /// Phase D (target §4.2): `resolver:MeasurementResolver` — resolve a `trace:MeasurementEvent` against the von Neumann-Landauer bridge (QM_1): `preCollapseEntropy = postCollapseLandauerCost` at β* = ln 2.
10914    /// Returns `Certified<MeasurementCertificate>` on success carrying the Witt
10915    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10916    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10917    /// failure — the witness itself is certified so downstream can persist it
10918    /// alongside success certs in a uniform `Certified<_>` channel.
10919    /// Phase X.1: the produced cert class is the ontology-declared class for
10920    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10921    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10922    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10923    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10924    /// kernels so each resolver's class discrimination is load-bearing.
10925    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10926    /// kernel's composition spec) whose output is folded into the canonical
10927    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10928    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10929    /// content-addressed per its ontology class.
10930    pub mod measurement {
10931        use super::*;
10932
10933        #[doc(hidden)]
10934        pub struct Kernel;
10935        impl super::ResolverKernel for Kernel {
10936            type Cert = crate::enforcement::MeasurementCertificate;
10937            const KIND: crate::enforcement::CertificateKind =
10938                crate::enforcement::CertificateKind::Measurement;
10939        }
10940
10941        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10942        ///
10943        /// # Errors
10944        ///
10945        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10946        pub fn certify<
10947            P: crate::enforcement::ValidationPhase,
10948            H: crate::enforcement::Hasher,
10949            const INLINE_BYTES: usize,
10950        >(
10951            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10952        ) -> Result<Certified<MeasurementCertificate>, Certified<GenericImpossibilityWitness>>
10953        {
10954            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10955        }
10956
10957        /// Phase D (target §4.2): certify at an explicit Witt level.
10958        ///
10959        /// # Errors
10960        ///
10961        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10962        pub fn certify_at<
10963            P: crate::enforcement::ValidationPhase,
10964            H: crate::enforcement::Hasher,
10965            const INLINE_BYTES: usize,
10966        >(
10967            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10968            level: WittLevel,
10969        ) -> Result<Certified<MeasurementCertificate>, Certified<GenericImpossibilityWitness>>
10970        {
10971            let unit = input.inner();
10972            let witt_bits = level.witt_length() as u16;
10973            let budget = unit.thermodynamic_budget();
10974            let result_type_iri = unit.result_type_iri();
10975            let mut hasher = H::initial();
10976            let (outcome_index, probability) =
10977                crate::enforcement::primitive_measurement_projection(budget);
10978            hasher = crate::enforcement::fold_born_outcome(hasher, outcome_index, probability);
10979            hasher = crate::enforcement::fold_unit_digest(
10980                hasher,
10981                witt_bits,
10982                budget,
10983                result_type_iri,
10984                0usize,
10985                &[],
10986                <Kernel as super::ResolverKernel>::KIND,
10987            );
10988            let buffer = hasher.finalize();
10989            let fp =
10990                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10991            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10992            Ok(Certified::new(cert))
10993        }
10994    }
10995
10996    /// Phase D (target §4.2): `resolver:WittLevelResolver` — given a WittLevel declaration, validate the (bit_width, cycle_size) pair satisfies `conformance:WittLevelShape` and emit a cert over the normalized level.
10997    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10998    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10999    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11000    /// failure — the witness itself is certified so downstream can persist it
11001    /// alongside success certs in a uniform `Certified<_>` channel.
11002    /// Phase X.1: the produced cert class is the ontology-declared class for
11003    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11004    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11005    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11006    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11007    /// kernels so each resolver's class discrimination is load-bearing.
11008    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11009    /// kernel's composition spec) whose output is folded into the canonical
11010    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11011    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11012    /// content-addressed per its ontology class.
11013    pub mod witt_level_resolver {
11014        use super::*;
11015
11016        #[doc(hidden)]
11017        pub struct Kernel;
11018        impl super::ResolverKernel for Kernel {
11019            type Cert = crate::enforcement::GroundingCertificate;
11020            const KIND: crate::enforcement::CertificateKind =
11021                crate::enforcement::CertificateKind::WittLevel;
11022        }
11023
11024        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11025        ///
11026        /// # Errors
11027        ///
11028        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11029        pub fn certify<
11030            P: crate::enforcement::ValidationPhase,
11031            H: crate::enforcement::Hasher,
11032            const INLINE_BYTES: usize,
11033        >(
11034            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
11035        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
11036        {
11037            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
11038        }
11039
11040        /// Phase D (target §4.2): certify at an explicit Witt level.
11041        ///
11042        /// # Errors
11043        ///
11044        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11045        pub fn certify_at<
11046            P: crate::enforcement::ValidationPhase,
11047            H: crate::enforcement::Hasher,
11048            const INLINE_BYTES: usize,
11049        >(
11050            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
11051            level: WittLevel,
11052        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
11053        {
11054            let unit = input.inner();
11055            let witt_bits = level.witt_length() as u16;
11056            let budget = unit.thermodynamic_budget();
11057            let result_type_iri = unit.result_type_iri();
11058            let mut hasher = H::initial();
11059            hasher = hasher.fold_bytes(&witt_bits.to_be_bytes());
11060            let declared_level_bits = unit.witt_level().witt_length() as u16;
11061            hasher = hasher.fold_bytes(&declared_level_bits.to_be_bytes());
11062            hasher = crate::enforcement::fold_unit_digest(
11063                hasher,
11064                witt_bits,
11065                budget,
11066                result_type_iri,
11067                0usize,
11068                &[],
11069                <Kernel as super::ResolverKernel>::KIND,
11070            );
11071            let buffer = hasher.finalize();
11072            let fp =
11073                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11074            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11075            Ok(Certified::new(cert))
11076        }
11077    }
11078
11079    /// Phase D (target §4.2): `resolver:DihedralFactorizationResolver` — run the dihedral factorization decider on a `ConstrainedType`'s carrier, producing a cert over the factor structure.
11080    /// Returns `Certified<InvolutionCertificate>` on success carrying the Witt
11081    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11082    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11083    /// failure — the witness itself is certified so downstream can persist it
11084    /// alongside success certs in a uniform `Certified<_>` channel.
11085    /// Phase X.1: the produced cert class is the ontology-declared class for
11086    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11087    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11088    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11089    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11090    /// kernels so each resolver's class discrimination is load-bearing.
11091    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11092    /// kernel's composition spec) whose output is folded into the canonical
11093    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11094    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11095    /// content-addressed per its ontology class.
11096    pub mod dihedral_factorization {
11097        use super::*;
11098
11099        #[doc(hidden)]
11100        pub struct Kernel;
11101        impl super::ResolverKernel for Kernel {
11102            type Cert = crate::enforcement::InvolutionCertificate;
11103            const KIND: crate::enforcement::CertificateKind =
11104                crate::enforcement::CertificateKind::DihedralFactorization;
11105        }
11106
11107        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11108        ///
11109        /// # Errors
11110        ///
11111        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11112        pub fn certify<
11113            T: crate::pipeline::ConstrainedTypeShape,
11114            P: crate::enforcement::ValidationPhase,
11115            H: crate::enforcement::Hasher,
11116        >(
11117            input: &Validated<T, P>,
11118        ) -> Result<Certified<InvolutionCertificate>, Certified<GenericImpossibilityWitness>>
11119        {
11120            certify_at::<T, P, H>(input, WittLevel::W32)
11121        }
11122
11123        /// Phase D (target §4.2): certify at an explicit Witt level.
11124        ///
11125        /// # Errors
11126        ///
11127        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11128        pub fn certify_at<
11129            T: crate::pipeline::ConstrainedTypeShape,
11130            P: crate::enforcement::ValidationPhase,
11131            H: crate::enforcement::Hasher,
11132        >(
11133            input: &Validated<T, P>,
11134            level: WittLevel,
11135        ) -> Result<Certified<InvolutionCertificate>, Certified<GenericImpossibilityWitness>>
11136        {
11137            let _ = input.inner();
11138            let witt_bits = level.witt_length() as u16;
11139            let (tr_bits, tr_constraints, tr_sat) =
11140                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11141                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11142            if tr_sat == 0 {
11143                return Err(Certified::new(GenericImpossibilityWitness::default()));
11144            }
11145            let mut hasher = H::initial();
11146            hasher = crate::enforcement::fold_terminal_reduction(
11147                hasher,
11148                tr_bits,
11149                tr_constraints,
11150                tr_sat,
11151            );
11152            let (orbit_size, representative) =
11153                crate::enforcement::primitive_dihedral_signature::<T>();
11154            hasher =
11155                crate::enforcement::fold_dihedral_signature(hasher, orbit_size, representative);
11156            hasher = crate::enforcement::fold_unit_digest(
11157                hasher,
11158                witt_bits,
11159                witt_bits as u64,
11160                T::IRI,
11161                T::SITE_COUNT,
11162                T::CONSTRAINTS,
11163                <Kernel as super::ResolverKernel>::KIND,
11164            );
11165            let buffer = hasher.finalize();
11166            let fp =
11167                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11168            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11169            Ok(Certified::new(cert))
11170        }
11171    }
11172
11173    /// Phase D (target §4.2): `resolver:CompletenessResolver` — generic completeness-loop resolver: runs the ψ-pipeline without the tower-specific lift chain and emits a cert if the input's constraint nerve has Euler characteristic n at quantum level n.
11174    /// Returns `Certified<CompletenessCertificate>` on success carrying the Witt
11175    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11176    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11177    /// failure — the witness itself is certified so downstream can persist it
11178    /// alongside success certs in a uniform `Certified<_>` channel.
11179    /// Phase X.1: the produced cert class is the ontology-declared class for
11180    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11181    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11182    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11183    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11184    /// kernels so each resolver's class discrimination is load-bearing.
11185    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11186    /// kernel's composition spec) whose output is folded into the canonical
11187    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11188    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11189    /// content-addressed per its ontology class.
11190    pub mod completeness {
11191        use super::*;
11192
11193        #[doc(hidden)]
11194        pub struct Kernel;
11195        impl super::ResolverKernel for Kernel {
11196            type Cert = crate::enforcement::CompletenessCertificate;
11197            const KIND: crate::enforcement::CertificateKind =
11198                crate::enforcement::CertificateKind::Completeness;
11199        }
11200
11201        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11202        ///
11203        /// # Errors
11204        ///
11205        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11206        pub fn certify<
11207            T: crate::pipeline::ConstrainedTypeShape,
11208            P: crate::enforcement::ValidationPhase,
11209            H: crate::enforcement::Hasher,
11210        >(
11211            input: &Validated<T, P>,
11212        ) -> Result<Certified<CompletenessCertificate>, Certified<GenericImpossibilityWitness>>
11213        {
11214            certify_at::<T, P, H>(input, WittLevel::W32)
11215        }
11216
11217        /// Phase D (target §4.2): certify at an explicit Witt level.
11218        ///
11219        /// # Errors
11220        ///
11221        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11222        pub fn certify_at<
11223            T: crate::pipeline::ConstrainedTypeShape,
11224            P: crate::enforcement::ValidationPhase,
11225            H: crate::enforcement::Hasher,
11226        >(
11227            input: &Validated<T, P>,
11228            level: WittLevel,
11229        ) -> Result<Certified<CompletenessCertificate>, Certified<GenericImpossibilityWitness>>
11230        {
11231            let _ = input.inner();
11232            let witt_bits = level.witt_length() as u16;
11233            let (tr_bits, tr_constraints, tr_sat) =
11234                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11235                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11236            if tr_sat == 0 {
11237                return Err(Certified::new(GenericImpossibilityWitness::default()));
11238            }
11239            let mut hasher = H::initial();
11240            hasher = crate::enforcement::fold_terminal_reduction(
11241                hasher,
11242                tr_bits,
11243                tr_constraints,
11244                tr_sat,
11245            );
11246            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
11247                .map_err(crate::enforcement::Certified::new)?;
11248            let chi = crate::enforcement::primitive_euler_characteristic(&betti);
11249            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
11250            hasher = hasher.fold_bytes(&chi.to_be_bytes());
11251            hasher = crate::enforcement::fold_unit_digest(
11252                hasher,
11253                witt_bits,
11254                witt_bits as u64,
11255                T::IRI,
11256                T::SITE_COUNT,
11257                T::CONSTRAINTS,
11258                <Kernel as super::ResolverKernel>::KIND,
11259            );
11260            let buffer = hasher.finalize();
11261            let fp =
11262                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11263            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11264            Ok(Certified::new(cert))
11265        }
11266    }
11267
11268    /// Phase D (target §4.2): `resolver:GeodesicValidator` — validate whether a `trace:ComputationTrace` satisfies the dual geodesic condition (AR_1-ordered and DC_10-selected); produces a `GeodesicCertificate` on success, `GenericImpossibilityWitness` otherwise.
11269    /// Returns `Certified<GeodesicCertificate>` on success carrying the Witt
11270    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11271    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11272    /// failure — the witness itself is certified so downstream can persist it
11273    /// alongside success certs in a uniform `Certified<_>` channel.
11274    /// Phase X.1: the produced cert class is the ontology-declared class for
11275    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11276    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11277    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11278    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11279    /// kernels so each resolver's class discrimination is load-bearing.
11280    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11281    /// kernel's composition spec) whose output is folded into the canonical
11282    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11283    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11284    /// content-addressed per its ontology class.
11285    pub mod geodesic_validator {
11286        use super::*;
11287
11288        #[doc(hidden)]
11289        pub struct Kernel;
11290        impl super::ResolverKernel for Kernel {
11291            type Cert = crate::enforcement::GeodesicCertificate;
11292            const KIND: crate::enforcement::CertificateKind =
11293                crate::enforcement::CertificateKind::GeodesicValidator;
11294        }
11295
11296        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11297        ///
11298        /// # Errors
11299        ///
11300        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11301        pub fn certify<
11302            T: crate::pipeline::ConstrainedTypeShape,
11303            P: crate::enforcement::ValidationPhase,
11304            H: crate::enforcement::Hasher,
11305        >(
11306            input: &Validated<T, P>,
11307        ) -> Result<Certified<GeodesicCertificate>, Certified<GenericImpossibilityWitness>>
11308        {
11309            certify_at::<T, P, H>(input, WittLevel::W32)
11310        }
11311
11312        /// Phase D (target §4.2): certify at an explicit Witt level.
11313        ///
11314        /// # Errors
11315        ///
11316        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11317        pub fn certify_at<
11318            T: crate::pipeline::ConstrainedTypeShape,
11319            P: crate::enforcement::ValidationPhase,
11320            H: crate::enforcement::Hasher,
11321        >(
11322            input: &Validated<T, P>,
11323            level: WittLevel,
11324        ) -> Result<Certified<GeodesicCertificate>, Certified<GenericImpossibilityWitness>>
11325        {
11326            let _ = input.inner();
11327            let witt_bits = level.witt_length() as u16;
11328            let (tr_bits, tr_constraints, tr_sat) =
11329                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11330                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11331            if tr_sat == 0 {
11332                return Err(Certified::new(GenericImpossibilityWitness::default()));
11333            }
11334            let mut hasher = H::initial();
11335            hasher = crate::enforcement::fold_terminal_reduction(
11336                hasher,
11337                tr_bits,
11338                tr_constraints,
11339                tr_sat,
11340            );
11341            let jac = crate::enforcement::primitive_curvature_jacobian::<T>();
11342            hasher = crate::enforcement::fold_jacobian_profile(hasher, &jac);
11343            let selected_site = crate::enforcement::primitive_dc10_select(&jac);
11344            hasher = hasher.fold_bytes(&(selected_site as u32).to_be_bytes());
11345            hasher = crate::enforcement::fold_unit_digest(
11346                hasher,
11347                witt_bits,
11348                witt_bits as u64,
11349                T::IRI,
11350                T::SITE_COUNT,
11351                T::CONSTRAINTS,
11352                <Kernel as super::ResolverKernel>::KIND,
11353            );
11354            let buffer = hasher.finalize();
11355            let fp =
11356                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11357            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11358            Ok(Certified::new(cert))
11359        }
11360    }
11361}
11362
11363/// v0.2.2 phantom-typed ring operation surface. Each phantom struct binds a
11364/// `WittLevel` at the type level so consumers can write
11365/// `Mul::<W8>::apply(a, b)` for compile-time level-checked arithmetic.
11366pub trait RingOp<L> {
11367    /// Operand type at this level.
11368    type Operand;
11369    /// Apply this binary ring op.
11370    fn apply(a: Self::Operand, b: Self::Operand) -> Self::Operand;
11371}
11372
11373/// v0.2.2 W3: unary phantom-typed ring operation surface. Mirrors `RingOp`
11374/// for arity-1 operations (`Neg`, `BNot`, `Succ`) so consumers can write
11375/// `Neg::<W8>::apply(a)` for compile-time level-checked unary arithmetic.
11376pub trait UnaryRingOp<L> {
11377    /// Operand type at this level.
11378    type Operand;
11379    /// Apply this unary ring op.
11380    fn apply(a: Self::Operand) -> Self::Operand;
11381}
11382
11383/// Multiplicative ring op. phantom-typed at level `L`.
11384#[derive(Debug, Default, Clone, Copy)]
11385pub struct Mul<L>(PhantomData<L>);
11386
11387/// Additive ring op. phantom-typed at level `L`.
11388#[derive(Debug, Default, Clone, Copy)]
11389pub struct Add<L>(PhantomData<L>);
11390
11391/// Subtractive ring op. phantom-typed at level `L`.
11392#[derive(Debug, Default, Clone, Copy)]
11393pub struct Sub<L>(PhantomData<L>);
11394
11395/// Bitwise XOR ring op. phantom-typed at level `L`.
11396#[derive(Debug, Default, Clone, Copy)]
11397pub struct Xor<L>(PhantomData<L>);
11398
11399/// Bitwise AND ring op. phantom-typed at level `L`.
11400#[derive(Debug, Default, Clone, Copy)]
11401pub struct And<L>(PhantomData<L>);
11402
11403/// Bitwise OR ring op. phantom-typed at level `L`.
11404#[derive(Debug, Default, Clone, Copy)]
11405pub struct Or<L>(PhantomData<L>);
11406
11407/// Ring negation (the canonical involution: x → -x). Phantom-typed at level `L` (v0.2.2 W3).
11408#[derive(Debug, Default, Clone, Copy)]
11409pub struct Neg<L>(PhantomData<L>);
11410
11411/// Bitwise NOT (the Hamming involution: x → (2^n - 1) XOR x). Phantom-typed at level `L` (v0.2.2 W3).
11412#[derive(Debug, Default, Clone, Copy)]
11413pub struct BNot<L>(PhantomData<L>);
11414
11415/// Successor (= Neg ∘ BNot per the critical composition law). Phantom-typed at level `L` (v0.2.2 W3).
11416#[derive(Debug, Default, Clone, Copy)]
11417pub struct Succ<L>(PhantomData<L>);
11418
11419/// W8 marker — 8-bit Witt level reified at the type level.
11420#[derive(Debug, Default, Clone, Copy)]
11421pub struct W8;
11422
11423/// W16 marker — 16-bit Witt level reified at the type level.
11424#[derive(Debug, Default, Clone, Copy)]
11425pub struct W16;
11426
11427/// W24 marker — 24-bit Witt level reified at the type level.
11428#[derive(Debug, Default, Clone, Copy)]
11429pub struct W24;
11430
11431/// W32 marker — 32-bit Witt level reified at the type level.
11432#[derive(Debug, Default, Clone, Copy)]
11433pub struct W32;
11434
11435/// W40 marker — 40-bit Witt level reified at the type level.
11436#[derive(Debug, Default, Clone, Copy)]
11437pub struct W40;
11438
11439/// W48 marker — 48-bit Witt level reified at the type level.
11440#[derive(Debug, Default, Clone, Copy)]
11441pub struct W48;
11442
11443/// W56 marker — 56-bit Witt level reified at the type level.
11444#[derive(Debug, Default, Clone, Copy)]
11445pub struct W56;
11446
11447/// W64 marker — 64-bit Witt level reified at the type level.
11448#[derive(Debug, Default, Clone, Copy)]
11449pub struct W64;
11450
11451/// W72 marker — 72-bit Witt level reified at the type level.
11452#[derive(Debug, Default, Clone, Copy)]
11453pub struct W72;
11454
11455/// W80 marker — 80-bit Witt level reified at the type level.
11456#[derive(Debug, Default, Clone, Copy)]
11457pub struct W80;
11458
11459/// W88 marker — 88-bit Witt level reified at the type level.
11460#[derive(Debug, Default, Clone, Copy)]
11461pub struct W88;
11462
11463/// W96 marker — 96-bit Witt level reified at the type level.
11464#[derive(Debug, Default, Clone, Copy)]
11465pub struct W96;
11466
11467/// W104 marker — 104-bit Witt level reified at the type level.
11468#[derive(Debug, Default, Clone, Copy)]
11469pub struct W104;
11470
11471/// W112 marker — 112-bit Witt level reified at the type level.
11472#[derive(Debug, Default, Clone, Copy)]
11473pub struct W112;
11474
11475/// W120 marker — 120-bit Witt level reified at the type level.
11476#[derive(Debug, Default, Clone, Copy)]
11477pub struct W120;
11478
11479/// W128 marker — 128-bit Witt level reified at the type level.
11480#[derive(Debug, Default, Clone, Copy)]
11481pub struct W128;
11482
11483impl RingOp<W8> for Mul<W8> {
11484    type Operand = u8;
11485    #[inline]
11486    fn apply(a: u8, b: u8) -> u8 {
11487        const_ring_eval_w8(PrimitiveOp::Mul, a, b)
11488    }
11489}
11490
11491impl RingOp<W8> for Add<W8> {
11492    type Operand = u8;
11493    #[inline]
11494    fn apply(a: u8, b: u8) -> u8 {
11495        const_ring_eval_w8(PrimitiveOp::Add, a, b)
11496    }
11497}
11498
11499impl RingOp<W8> for Sub<W8> {
11500    type Operand = u8;
11501    #[inline]
11502    fn apply(a: u8, b: u8) -> u8 {
11503        const_ring_eval_w8(PrimitiveOp::Sub, a, b)
11504    }
11505}
11506
11507impl RingOp<W8> for Xor<W8> {
11508    type Operand = u8;
11509    #[inline]
11510    fn apply(a: u8, b: u8) -> u8 {
11511        const_ring_eval_w8(PrimitiveOp::Xor, a, b)
11512    }
11513}
11514
11515impl RingOp<W8> for And<W8> {
11516    type Operand = u8;
11517    #[inline]
11518    fn apply(a: u8, b: u8) -> u8 {
11519        const_ring_eval_w8(PrimitiveOp::And, a, b)
11520    }
11521}
11522
11523impl RingOp<W8> for Or<W8> {
11524    type Operand = u8;
11525    #[inline]
11526    fn apply(a: u8, b: u8) -> u8 {
11527        const_ring_eval_w8(PrimitiveOp::Or, a, b)
11528    }
11529}
11530
11531impl RingOp<W16> for Mul<W16> {
11532    type Operand = u16;
11533    #[inline]
11534    fn apply(a: u16, b: u16) -> u16 {
11535        const_ring_eval_w16(PrimitiveOp::Mul, a, b)
11536    }
11537}
11538
11539impl RingOp<W16> for Add<W16> {
11540    type Operand = u16;
11541    #[inline]
11542    fn apply(a: u16, b: u16) -> u16 {
11543        const_ring_eval_w16(PrimitiveOp::Add, a, b)
11544    }
11545}
11546
11547impl RingOp<W16> for Sub<W16> {
11548    type Operand = u16;
11549    #[inline]
11550    fn apply(a: u16, b: u16) -> u16 {
11551        const_ring_eval_w16(PrimitiveOp::Sub, a, b)
11552    }
11553}
11554
11555impl RingOp<W16> for Xor<W16> {
11556    type Operand = u16;
11557    #[inline]
11558    fn apply(a: u16, b: u16) -> u16 {
11559        const_ring_eval_w16(PrimitiveOp::Xor, a, b)
11560    }
11561}
11562
11563impl RingOp<W16> for And<W16> {
11564    type Operand = u16;
11565    #[inline]
11566    fn apply(a: u16, b: u16) -> u16 {
11567        const_ring_eval_w16(PrimitiveOp::And, a, b)
11568    }
11569}
11570
11571impl RingOp<W16> for Or<W16> {
11572    type Operand = u16;
11573    #[inline]
11574    fn apply(a: u16, b: u16) -> u16 {
11575        const_ring_eval_w16(PrimitiveOp::Or, a, b)
11576    }
11577}
11578
11579impl RingOp<W24> for Mul<W24> {
11580    type Operand = u32;
11581    #[inline]
11582    fn apply(a: u32, b: u32) -> u32 {
11583        const_ring_eval_w24(PrimitiveOp::Mul, a, b)
11584    }
11585}
11586
11587impl RingOp<W24> for Add<W24> {
11588    type Operand = u32;
11589    #[inline]
11590    fn apply(a: u32, b: u32) -> u32 {
11591        const_ring_eval_w24(PrimitiveOp::Add, a, b)
11592    }
11593}
11594
11595impl RingOp<W24> for Sub<W24> {
11596    type Operand = u32;
11597    #[inline]
11598    fn apply(a: u32, b: u32) -> u32 {
11599        const_ring_eval_w24(PrimitiveOp::Sub, a, b)
11600    }
11601}
11602
11603impl RingOp<W24> for Xor<W24> {
11604    type Operand = u32;
11605    #[inline]
11606    fn apply(a: u32, b: u32) -> u32 {
11607        const_ring_eval_w24(PrimitiveOp::Xor, a, b)
11608    }
11609}
11610
11611impl RingOp<W24> for And<W24> {
11612    type Operand = u32;
11613    #[inline]
11614    fn apply(a: u32, b: u32) -> u32 {
11615        const_ring_eval_w24(PrimitiveOp::And, a, b)
11616    }
11617}
11618
11619impl RingOp<W24> for Or<W24> {
11620    type Operand = u32;
11621    #[inline]
11622    fn apply(a: u32, b: u32) -> u32 {
11623        const_ring_eval_w24(PrimitiveOp::Or, a, b)
11624    }
11625}
11626
11627impl RingOp<W32> for Mul<W32> {
11628    type Operand = u32;
11629    #[inline]
11630    fn apply(a: u32, b: u32) -> u32 {
11631        const_ring_eval_w32(PrimitiveOp::Mul, a, b)
11632    }
11633}
11634
11635impl RingOp<W32> for Add<W32> {
11636    type Operand = u32;
11637    #[inline]
11638    fn apply(a: u32, b: u32) -> u32 {
11639        const_ring_eval_w32(PrimitiveOp::Add, a, b)
11640    }
11641}
11642
11643impl RingOp<W32> for Sub<W32> {
11644    type Operand = u32;
11645    #[inline]
11646    fn apply(a: u32, b: u32) -> u32 {
11647        const_ring_eval_w32(PrimitiveOp::Sub, a, b)
11648    }
11649}
11650
11651impl RingOp<W32> for Xor<W32> {
11652    type Operand = u32;
11653    #[inline]
11654    fn apply(a: u32, b: u32) -> u32 {
11655        const_ring_eval_w32(PrimitiveOp::Xor, a, b)
11656    }
11657}
11658
11659impl RingOp<W32> for And<W32> {
11660    type Operand = u32;
11661    #[inline]
11662    fn apply(a: u32, b: u32) -> u32 {
11663        const_ring_eval_w32(PrimitiveOp::And, a, b)
11664    }
11665}
11666
11667impl RingOp<W32> for Or<W32> {
11668    type Operand = u32;
11669    #[inline]
11670    fn apply(a: u32, b: u32) -> u32 {
11671        const_ring_eval_w32(PrimitiveOp::Or, a, b)
11672    }
11673}
11674
11675impl RingOp<W40> for Mul<W40> {
11676    type Operand = u64;
11677    #[inline]
11678    fn apply(a: u64, b: u64) -> u64 {
11679        const_ring_eval_w40(PrimitiveOp::Mul, a, b)
11680    }
11681}
11682
11683impl RingOp<W40> for Add<W40> {
11684    type Operand = u64;
11685    #[inline]
11686    fn apply(a: u64, b: u64) -> u64 {
11687        const_ring_eval_w40(PrimitiveOp::Add, a, b)
11688    }
11689}
11690
11691impl RingOp<W40> for Sub<W40> {
11692    type Operand = u64;
11693    #[inline]
11694    fn apply(a: u64, b: u64) -> u64 {
11695        const_ring_eval_w40(PrimitiveOp::Sub, a, b)
11696    }
11697}
11698
11699impl RingOp<W40> for Xor<W40> {
11700    type Operand = u64;
11701    #[inline]
11702    fn apply(a: u64, b: u64) -> u64 {
11703        const_ring_eval_w40(PrimitiveOp::Xor, a, b)
11704    }
11705}
11706
11707impl RingOp<W40> for And<W40> {
11708    type Operand = u64;
11709    #[inline]
11710    fn apply(a: u64, b: u64) -> u64 {
11711        const_ring_eval_w40(PrimitiveOp::And, a, b)
11712    }
11713}
11714
11715impl RingOp<W40> for Or<W40> {
11716    type Operand = u64;
11717    #[inline]
11718    fn apply(a: u64, b: u64) -> u64 {
11719        const_ring_eval_w40(PrimitiveOp::Or, a, b)
11720    }
11721}
11722
11723impl RingOp<W48> for Mul<W48> {
11724    type Operand = u64;
11725    #[inline]
11726    fn apply(a: u64, b: u64) -> u64 {
11727        const_ring_eval_w48(PrimitiveOp::Mul, a, b)
11728    }
11729}
11730
11731impl RingOp<W48> for Add<W48> {
11732    type Operand = u64;
11733    #[inline]
11734    fn apply(a: u64, b: u64) -> u64 {
11735        const_ring_eval_w48(PrimitiveOp::Add, a, b)
11736    }
11737}
11738
11739impl RingOp<W48> for Sub<W48> {
11740    type Operand = u64;
11741    #[inline]
11742    fn apply(a: u64, b: u64) -> u64 {
11743        const_ring_eval_w48(PrimitiveOp::Sub, a, b)
11744    }
11745}
11746
11747impl RingOp<W48> for Xor<W48> {
11748    type Operand = u64;
11749    #[inline]
11750    fn apply(a: u64, b: u64) -> u64 {
11751        const_ring_eval_w48(PrimitiveOp::Xor, a, b)
11752    }
11753}
11754
11755impl RingOp<W48> for And<W48> {
11756    type Operand = u64;
11757    #[inline]
11758    fn apply(a: u64, b: u64) -> u64 {
11759        const_ring_eval_w48(PrimitiveOp::And, a, b)
11760    }
11761}
11762
11763impl RingOp<W48> for Or<W48> {
11764    type Operand = u64;
11765    #[inline]
11766    fn apply(a: u64, b: u64) -> u64 {
11767        const_ring_eval_w48(PrimitiveOp::Or, a, b)
11768    }
11769}
11770
11771impl RingOp<W56> for Mul<W56> {
11772    type Operand = u64;
11773    #[inline]
11774    fn apply(a: u64, b: u64) -> u64 {
11775        const_ring_eval_w56(PrimitiveOp::Mul, a, b)
11776    }
11777}
11778
11779impl RingOp<W56> for Add<W56> {
11780    type Operand = u64;
11781    #[inline]
11782    fn apply(a: u64, b: u64) -> u64 {
11783        const_ring_eval_w56(PrimitiveOp::Add, a, b)
11784    }
11785}
11786
11787impl RingOp<W56> for Sub<W56> {
11788    type Operand = u64;
11789    #[inline]
11790    fn apply(a: u64, b: u64) -> u64 {
11791        const_ring_eval_w56(PrimitiveOp::Sub, a, b)
11792    }
11793}
11794
11795impl RingOp<W56> for Xor<W56> {
11796    type Operand = u64;
11797    #[inline]
11798    fn apply(a: u64, b: u64) -> u64 {
11799        const_ring_eval_w56(PrimitiveOp::Xor, a, b)
11800    }
11801}
11802
11803impl RingOp<W56> for And<W56> {
11804    type Operand = u64;
11805    #[inline]
11806    fn apply(a: u64, b: u64) -> u64 {
11807        const_ring_eval_w56(PrimitiveOp::And, a, b)
11808    }
11809}
11810
11811impl RingOp<W56> for Or<W56> {
11812    type Operand = u64;
11813    #[inline]
11814    fn apply(a: u64, b: u64) -> u64 {
11815        const_ring_eval_w56(PrimitiveOp::Or, a, b)
11816    }
11817}
11818
11819impl RingOp<W64> for Mul<W64> {
11820    type Operand = u64;
11821    #[inline]
11822    fn apply(a: u64, b: u64) -> u64 {
11823        const_ring_eval_w64(PrimitiveOp::Mul, a, b)
11824    }
11825}
11826
11827impl RingOp<W64> for Add<W64> {
11828    type Operand = u64;
11829    #[inline]
11830    fn apply(a: u64, b: u64) -> u64 {
11831        const_ring_eval_w64(PrimitiveOp::Add, a, b)
11832    }
11833}
11834
11835impl RingOp<W64> for Sub<W64> {
11836    type Operand = u64;
11837    #[inline]
11838    fn apply(a: u64, b: u64) -> u64 {
11839        const_ring_eval_w64(PrimitiveOp::Sub, a, b)
11840    }
11841}
11842
11843impl RingOp<W64> for Xor<W64> {
11844    type Operand = u64;
11845    #[inline]
11846    fn apply(a: u64, b: u64) -> u64 {
11847        const_ring_eval_w64(PrimitiveOp::Xor, a, b)
11848    }
11849}
11850
11851impl RingOp<W64> for And<W64> {
11852    type Operand = u64;
11853    #[inline]
11854    fn apply(a: u64, b: u64) -> u64 {
11855        const_ring_eval_w64(PrimitiveOp::And, a, b)
11856    }
11857}
11858
11859impl RingOp<W64> for Or<W64> {
11860    type Operand = u64;
11861    #[inline]
11862    fn apply(a: u64, b: u64) -> u64 {
11863        const_ring_eval_w64(PrimitiveOp::Or, a, b)
11864    }
11865}
11866
11867impl RingOp<W72> for Mul<W72> {
11868    type Operand = u128;
11869    #[inline]
11870    fn apply(a: u128, b: u128) -> u128 {
11871        const_ring_eval_w72(PrimitiveOp::Mul, a, b)
11872    }
11873}
11874
11875impl RingOp<W72> for Add<W72> {
11876    type Operand = u128;
11877    #[inline]
11878    fn apply(a: u128, b: u128) -> u128 {
11879        const_ring_eval_w72(PrimitiveOp::Add, a, b)
11880    }
11881}
11882
11883impl RingOp<W72> for Sub<W72> {
11884    type Operand = u128;
11885    #[inline]
11886    fn apply(a: u128, b: u128) -> u128 {
11887        const_ring_eval_w72(PrimitiveOp::Sub, a, b)
11888    }
11889}
11890
11891impl RingOp<W72> for Xor<W72> {
11892    type Operand = u128;
11893    #[inline]
11894    fn apply(a: u128, b: u128) -> u128 {
11895        const_ring_eval_w72(PrimitiveOp::Xor, a, b)
11896    }
11897}
11898
11899impl RingOp<W72> for And<W72> {
11900    type Operand = u128;
11901    #[inline]
11902    fn apply(a: u128, b: u128) -> u128 {
11903        const_ring_eval_w72(PrimitiveOp::And, a, b)
11904    }
11905}
11906
11907impl RingOp<W72> for Or<W72> {
11908    type Operand = u128;
11909    #[inline]
11910    fn apply(a: u128, b: u128) -> u128 {
11911        const_ring_eval_w72(PrimitiveOp::Or, a, b)
11912    }
11913}
11914
11915impl RingOp<W80> for Mul<W80> {
11916    type Operand = u128;
11917    #[inline]
11918    fn apply(a: u128, b: u128) -> u128 {
11919        const_ring_eval_w80(PrimitiveOp::Mul, a, b)
11920    }
11921}
11922
11923impl RingOp<W80> for Add<W80> {
11924    type Operand = u128;
11925    #[inline]
11926    fn apply(a: u128, b: u128) -> u128 {
11927        const_ring_eval_w80(PrimitiveOp::Add, a, b)
11928    }
11929}
11930
11931impl RingOp<W80> for Sub<W80> {
11932    type Operand = u128;
11933    #[inline]
11934    fn apply(a: u128, b: u128) -> u128 {
11935        const_ring_eval_w80(PrimitiveOp::Sub, a, b)
11936    }
11937}
11938
11939impl RingOp<W80> for Xor<W80> {
11940    type Operand = u128;
11941    #[inline]
11942    fn apply(a: u128, b: u128) -> u128 {
11943        const_ring_eval_w80(PrimitiveOp::Xor, a, b)
11944    }
11945}
11946
11947impl RingOp<W80> for And<W80> {
11948    type Operand = u128;
11949    #[inline]
11950    fn apply(a: u128, b: u128) -> u128 {
11951        const_ring_eval_w80(PrimitiveOp::And, a, b)
11952    }
11953}
11954
11955impl RingOp<W80> for Or<W80> {
11956    type Operand = u128;
11957    #[inline]
11958    fn apply(a: u128, b: u128) -> u128 {
11959        const_ring_eval_w80(PrimitiveOp::Or, a, b)
11960    }
11961}
11962
11963impl RingOp<W88> for Mul<W88> {
11964    type Operand = u128;
11965    #[inline]
11966    fn apply(a: u128, b: u128) -> u128 {
11967        const_ring_eval_w88(PrimitiveOp::Mul, a, b)
11968    }
11969}
11970
11971impl RingOp<W88> for Add<W88> {
11972    type Operand = u128;
11973    #[inline]
11974    fn apply(a: u128, b: u128) -> u128 {
11975        const_ring_eval_w88(PrimitiveOp::Add, a, b)
11976    }
11977}
11978
11979impl RingOp<W88> for Sub<W88> {
11980    type Operand = u128;
11981    #[inline]
11982    fn apply(a: u128, b: u128) -> u128 {
11983        const_ring_eval_w88(PrimitiveOp::Sub, a, b)
11984    }
11985}
11986
11987impl RingOp<W88> for Xor<W88> {
11988    type Operand = u128;
11989    #[inline]
11990    fn apply(a: u128, b: u128) -> u128 {
11991        const_ring_eval_w88(PrimitiveOp::Xor, a, b)
11992    }
11993}
11994
11995impl RingOp<W88> for And<W88> {
11996    type Operand = u128;
11997    #[inline]
11998    fn apply(a: u128, b: u128) -> u128 {
11999        const_ring_eval_w88(PrimitiveOp::And, a, b)
12000    }
12001}
12002
12003impl RingOp<W88> for Or<W88> {
12004    type Operand = u128;
12005    #[inline]
12006    fn apply(a: u128, b: u128) -> u128 {
12007        const_ring_eval_w88(PrimitiveOp::Or, a, b)
12008    }
12009}
12010
12011impl RingOp<W96> for Mul<W96> {
12012    type Operand = u128;
12013    #[inline]
12014    fn apply(a: u128, b: u128) -> u128 {
12015        const_ring_eval_w96(PrimitiveOp::Mul, a, b)
12016    }
12017}
12018
12019impl RingOp<W96> for Add<W96> {
12020    type Operand = u128;
12021    #[inline]
12022    fn apply(a: u128, b: u128) -> u128 {
12023        const_ring_eval_w96(PrimitiveOp::Add, a, b)
12024    }
12025}
12026
12027impl RingOp<W96> for Sub<W96> {
12028    type Operand = u128;
12029    #[inline]
12030    fn apply(a: u128, b: u128) -> u128 {
12031        const_ring_eval_w96(PrimitiveOp::Sub, a, b)
12032    }
12033}
12034
12035impl RingOp<W96> for Xor<W96> {
12036    type Operand = u128;
12037    #[inline]
12038    fn apply(a: u128, b: u128) -> u128 {
12039        const_ring_eval_w96(PrimitiveOp::Xor, a, b)
12040    }
12041}
12042
12043impl RingOp<W96> for And<W96> {
12044    type Operand = u128;
12045    #[inline]
12046    fn apply(a: u128, b: u128) -> u128 {
12047        const_ring_eval_w96(PrimitiveOp::And, a, b)
12048    }
12049}
12050
12051impl RingOp<W96> for Or<W96> {
12052    type Operand = u128;
12053    #[inline]
12054    fn apply(a: u128, b: u128) -> u128 {
12055        const_ring_eval_w96(PrimitiveOp::Or, a, b)
12056    }
12057}
12058
12059impl RingOp<W104> for Mul<W104> {
12060    type Operand = u128;
12061    #[inline]
12062    fn apply(a: u128, b: u128) -> u128 {
12063        const_ring_eval_w104(PrimitiveOp::Mul, a, b)
12064    }
12065}
12066
12067impl RingOp<W104> for Add<W104> {
12068    type Operand = u128;
12069    #[inline]
12070    fn apply(a: u128, b: u128) -> u128 {
12071        const_ring_eval_w104(PrimitiveOp::Add, a, b)
12072    }
12073}
12074
12075impl RingOp<W104> for Sub<W104> {
12076    type Operand = u128;
12077    #[inline]
12078    fn apply(a: u128, b: u128) -> u128 {
12079        const_ring_eval_w104(PrimitiveOp::Sub, a, b)
12080    }
12081}
12082
12083impl RingOp<W104> for Xor<W104> {
12084    type Operand = u128;
12085    #[inline]
12086    fn apply(a: u128, b: u128) -> u128 {
12087        const_ring_eval_w104(PrimitiveOp::Xor, a, b)
12088    }
12089}
12090
12091impl RingOp<W104> for And<W104> {
12092    type Operand = u128;
12093    #[inline]
12094    fn apply(a: u128, b: u128) -> u128 {
12095        const_ring_eval_w104(PrimitiveOp::And, a, b)
12096    }
12097}
12098
12099impl RingOp<W104> for Or<W104> {
12100    type Operand = u128;
12101    #[inline]
12102    fn apply(a: u128, b: u128) -> u128 {
12103        const_ring_eval_w104(PrimitiveOp::Or, a, b)
12104    }
12105}
12106
12107impl RingOp<W112> for Mul<W112> {
12108    type Operand = u128;
12109    #[inline]
12110    fn apply(a: u128, b: u128) -> u128 {
12111        const_ring_eval_w112(PrimitiveOp::Mul, a, b)
12112    }
12113}
12114
12115impl RingOp<W112> for Add<W112> {
12116    type Operand = u128;
12117    #[inline]
12118    fn apply(a: u128, b: u128) -> u128 {
12119        const_ring_eval_w112(PrimitiveOp::Add, a, b)
12120    }
12121}
12122
12123impl RingOp<W112> for Sub<W112> {
12124    type Operand = u128;
12125    #[inline]
12126    fn apply(a: u128, b: u128) -> u128 {
12127        const_ring_eval_w112(PrimitiveOp::Sub, a, b)
12128    }
12129}
12130
12131impl RingOp<W112> for Xor<W112> {
12132    type Operand = u128;
12133    #[inline]
12134    fn apply(a: u128, b: u128) -> u128 {
12135        const_ring_eval_w112(PrimitiveOp::Xor, a, b)
12136    }
12137}
12138
12139impl RingOp<W112> for And<W112> {
12140    type Operand = u128;
12141    #[inline]
12142    fn apply(a: u128, b: u128) -> u128 {
12143        const_ring_eval_w112(PrimitiveOp::And, a, b)
12144    }
12145}
12146
12147impl RingOp<W112> for Or<W112> {
12148    type Operand = u128;
12149    #[inline]
12150    fn apply(a: u128, b: u128) -> u128 {
12151        const_ring_eval_w112(PrimitiveOp::Or, a, b)
12152    }
12153}
12154
12155impl RingOp<W120> for Mul<W120> {
12156    type Operand = u128;
12157    #[inline]
12158    fn apply(a: u128, b: u128) -> u128 {
12159        const_ring_eval_w120(PrimitiveOp::Mul, a, b)
12160    }
12161}
12162
12163impl RingOp<W120> for Add<W120> {
12164    type Operand = u128;
12165    #[inline]
12166    fn apply(a: u128, b: u128) -> u128 {
12167        const_ring_eval_w120(PrimitiveOp::Add, a, b)
12168    }
12169}
12170
12171impl RingOp<W120> for Sub<W120> {
12172    type Operand = u128;
12173    #[inline]
12174    fn apply(a: u128, b: u128) -> u128 {
12175        const_ring_eval_w120(PrimitiveOp::Sub, a, b)
12176    }
12177}
12178
12179impl RingOp<W120> for Xor<W120> {
12180    type Operand = u128;
12181    #[inline]
12182    fn apply(a: u128, b: u128) -> u128 {
12183        const_ring_eval_w120(PrimitiveOp::Xor, a, b)
12184    }
12185}
12186
12187impl RingOp<W120> for And<W120> {
12188    type Operand = u128;
12189    #[inline]
12190    fn apply(a: u128, b: u128) -> u128 {
12191        const_ring_eval_w120(PrimitiveOp::And, a, b)
12192    }
12193}
12194
12195impl RingOp<W120> for Or<W120> {
12196    type Operand = u128;
12197    #[inline]
12198    fn apply(a: u128, b: u128) -> u128 {
12199        const_ring_eval_w120(PrimitiveOp::Or, a, b)
12200    }
12201}
12202
12203impl RingOp<W128> for Mul<W128> {
12204    type Operand = u128;
12205    #[inline]
12206    fn apply(a: u128, b: u128) -> u128 {
12207        const_ring_eval_w128(PrimitiveOp::Mul, a, b)
12208    }
12209}
12210
12211impl RingOp<W128> for Add<W128> {
12212    type Operand = u128;
12213    #[inline]
12214    fn apply(a: u128, b: u128) -> u128 {
12215        const_ring_eval_w128(PrimitiveOp::Add, a, b)
12216    }
12217}
12218
12219impl RingOp<W128> for Sub<W128> {
12220    type Operand = u128;
12221    #[inline]
12222    fn apply(a: u128, b: u128) -> u128 {
12223        const_ring_eval_w128(PrimitiveOp::Sub, a, b)
12224    }
12225}
12226
12227impl RingOp<W128> for Xor<W128> {
12228    type Operand = u128;
12229    #[inline]
12230    fn apply(a: u128, b: u128) -> u128 {
12231        const_ring_eval_w128(PrimitiveOp::Xor, a, b)
12232    }
12233}
12234
12235impl RingOp<W128> for And<W128> {
12236    type Operand = u128;
12237    #[inline]
12238    fn apply(a: u128, b: u128) -> u128 {
12239        const_ring_eval_w128(PrimitiveOp::And, a, b)
12240    }
12241}
12242
12243impl RingOp<W128> for Or<W128> {
12244    type Operand = u128;
12245    #[inline]
12246    fn apply(a: u128, b: u128) -> u128 {
12247        const_ring_eval_w128(PrimitiveOp::Or, a, b)
12248    }
12249}
12250
12251impl UnaryRingOp<W8> for Neg<W8> {
12252    type Operand = u8;
12253    #[inline]
12254    fn apply(a: u8) -> u8 {
12255        const_ring_eval_w8(PrimitiveOp::Sub, 0, a)
12256    }
12257}
12258
12259impl UnaryRingOp<W8> for BNot<W8> {
12260    type Operand = u8;
12261    #[inline]
12262    fn apply(a: u8) -> u8 {
12263        const_ring_eval_w8(PrimitiveOp::Xor, a, u8::MAX)
12264    }
12265}
12266
12267impl UnaryRingOp<W8> for Succ<W8> {
12268    type Operand = u8;
12269    #[inline]
12270    fn apply(a: u8) -> u8 {
12271        <Neg<W8> as UnaryRingOp<W8>>::apply(<BNot<W8> as UnaryRingOp<W8>>::apply(a))
12272    }
12273}
12274
12275impl UnaryRingOp<W16> for Neg<W16> {
12276    type Operand = u16;
12277    #[inline]
12278    fn apply(a: u16) -> u16 {
12279        const_ring_eval_w16(PrimitiveOp::Sub, 0, a)
12280    }
12281}
12282
12283impl UnaryRingOp<W16> for BNot<W16> {
12284    type Operand = u16;
12285    #[inline]
12286    fn apply(a: u16) -> u16 {
12287        const_ring_eval_w16(PrimitiveOp::Xor, a, u16::MAX)
12288    }
12289}
12290
12291impl UnaryRingOp<W16> for Succ<W16> {
12292    type Operand = u16;
12293    #[inline]
12294    fn apply(a: u16) -> u16 {
12295        <Neg<W16> as UnaryRingOp<W16>>::apply(<BNot<W16> as UnaryRingOp<W16>>::apply(a))
12296    }
12297}
12298
12299impl UnaryRingOp<W24> for Neg<W24> {
12300    type Operand = u32;
12301    #[inline]
12302    fn apply(a: u32) -> u32 {
12303        const_ring_eval_w24(PrimitiveOp::Sub, 0, a)
12304    }
12305}
12306
12307impl UnaryRingOp<W24> for BNot<W24> {
12308    type Operand = u32;
12309    #[inline]
12310    fn apply(a: u32) -> u32 {
12311        const_ring_eval_w24(PrimitiveOp::Xor, a, 0x00FF_FFFFu32)
12312    }
12313}
12314
12315impl UnaryRingOp<W24> for Succ<W24> {
12316    type Operand = u32;
12317    #[inline]
12318    fn apply(a: u32) -> u32 {
12319        <Neg<W24> as UnaryRingOp<W24>>::apply(<BNot<W24> as UnaryRingOp<W24>>::apply(a))
12320    }
12321}
12322
12323impl UnaryRingOp<W32> for Neg<W32> {
12324    type Operand = u32;
12325    #[inline]
12326    fn apply(a: u32) -> u32 {
12327        const_ring_eval_w32(PrimitiveOp::Sub, 0, a)
12328    }
12329}
12330
12331impl UnaryRingOp<W32> for BNot<W32> {
12332    type Operand = u32;
12333    #[inline]
12334    fn apply(a: u32) -> u32 {
12335        const_ring_eval_w32(PrimitiveOp::Xor, a, u32::MAX)
12336    }
12337}
12338
12339impl UnaryRingOp<W32> for Succ<W32> {
12340    type Operand = u32;
12341    #[inline]
12342    fn apply(a: u32) -> u32 {
12343        <Neg<W32> as UnaryRingOp<W32>>::apply(<BNot<W32> as UnaryRingOp<W32>>::apply(a))
12344    }
12345}
12346
12347impl UnaryRingOp<W40> for Neg<W40> {
12348    type Operand = u64;
12349    #[inline]
12350    fn apply(a: u64) -> u64 {
12351        const_ring_eval_w40(PrimitiveOp::Sub, 0, a)
12352    }
12353}
12354
12355impl UnaryRingOp<W40> for BNot<W40> {
12356    type Operand = u64;
12357    #[inline]
12358    fn apply(a: u64) -> u64 {
12359        const_ring_eval_w40(PrimitiveOp::Xor, a, 0x0000_00FF_FFFF_FFFFu64)
12360    }
12361}
12362
12363impl UnaryRingOp<W40> for Succ<W40> {
12364    type Operand = u64;
12365    #[inline]
12366    fn apply(a: u64) -> u64 {
12367        <Neg<W40> as UnaryRingOp<W40>>::apply(<BNot<W40> as UnaryRingOp<W40>>::apply(a))
12368    }
12369}
12370
12371impl UnaryRingOp<W48> for Neg<W48> {
12372    type Operand = u64;
12373    #[inline]
12374    fn apply(a: u64) -> u64 {
12375        const_ring_eval_w48(PrimitiveOp::Sub, 0, a)
12376    }
12377}
12378
12379impl UnaryRingOp<W48> for BNot<W48> {
12380    type Operand = u64;
12381    #[inline]
12382    fn apply(a: u64) -> u64 {
12383        const_ring_eval_w48(PrimitiveOp::Xor, a, 0x0000_FFFF_FFFF_FFFFu64)
12384    }
12385}
12386
12387impl UnaryRingOp<W48> for Succ<W48> {
12388    type Operand = u64;
12389    #[inline]
12390    fn apply(a: u64) -> u64 {
12391        <Neg<W48> as UnaryRingOp<W48>>::apply(<BNot<W48> as UnaryRingOp<W48>>::apply(a))
12392    }
12393}
12394
12395impl UnaryRingOp<W56> for Neg<W56> {
12396    type Operand = u64;
12397    #[inline]
12398    fn apply(a: u64) -> u64 {
12399        const_ring_eval_w56(PrimitiveOp::Sub, 0, a)
12400    }
12401}
12402
12403impl UnaryRingOp<W56> for BNot<W56> {
12404    type Operand = u64;
12405    #[inline]
12406    fn apply(a: u64) -> u64 {
12407        const_ring_eval_w56(PrimitiveOp::Xor, a, 0x00FF_FFFF_FFFF_FFFFu64)
12408    }
12409}
12410
12411impl UnaryRingOp<W56> for Succ<W56> {
12412    type Operand = u64;
12413    #[inline]
12414    fn apply(a: u64) -> u64 {
12415        <Neg<W56> as UnaryRingOp<W56>>::apply(<BNot<W56> as UnaryRingOp<W56>>::apply(a))
12416    }
12417}
12418
12419impl UnaryRingOp<W64> for Neg<W64> {
12420    type Operand = u64;
12421    #[inline]
12422    fn apply(a: u64) -> u64 {
12423        const_ring_eval_w64(PrimitiveOp::Sub, 0, a)
12424    }
12425}
12426
12427impl UnaryRingOp<W64> for BNot<W64> {
12428    type Operand = u64;
12429    #[inline]
12430    fn apply(a: u64) -> u64 {
12431        const_ring_eval_w64(PrimitiveOp::Xor, a, u64::MAX)
12432    }
12433}
12434
12435impl UnaryRingOp<W64> for Succ<W64> {
12436    type Operand = u64;
12437    #[inline]
12438    fn apply(a: u64) -> u64 {
12439        <Neg<W64> as UnaryRingOp<W64>>::apply(<BNot<W64> as UnaryRingOp<W64>>::apply(a))
12440    }
12441}
12442
12443impl UnaryRingOp<W72> for Neg<W72> {
12444    type Operand = u128;
12445    #[inline]
12446    fn apply(a: u128) -> u128 {
12447        const_ring_eval_w72(PrimitiveOp::Sub, 0, a)
12448    }
12449}
12450
12451impl UnaryRingOp<W72> for BNot<W72> {
12452    type Operand = u128;
12453    #[inline]
12454    fn apply(a: u128) -> u128 {
12455        const_ring_eval_w72(PrimitiveOp::Xor, a, u128::MAX >> (128 - 72))
12456    }
12457}
12458
12459impl UnaryRingOp<W72> for Succ<W72> {
12460    type Operand = u128;
12461    #[inline]
12462    fn apply(a: u128) -> u128 {
12463        <Neg<W72> as UnaryRingOp<W72>>::apply(<BNot<W72> as UnaryRingOp<W72>>::apply(a))
12464    }
12465}
12466
12467impl UnaryRingOp<W80> for Neg<W80> {
12468    type Operand = u128;
12469    #[inline]
12470    fn apply(a: u128) -> u128 {
12471        const_ring_eval_w80(PrimitiveOp::Sub, 0, a)
12472    }
12473}
12474
12475impl UnaryRingOp<W80> for BNot<W80> {
12476    type Operand = u128;
12477    #[inline]
12478    fn apply(a: u128) -> u128 {
12479        const_ring_eval_w80(PrimitiveOp::Xor, a, u128::MAX >> (128 - 80))
12480    }
12481}
12482
12483impl UnaryRingOp<W80> for Succ<W80> {
12484    type Operand = u128;
12485    #[inline]
12486    fn apply(a: u128) -> u128 {
12487        <Neg<W80> as UnaryRingOp<W80>>::apply(<BNot<W80> as UnaryRingOp<W80>>::apply(a))
12488    }
12489}
12490
12491impl UnaryRingOp<W88> for Neg<W88> {
12492    type Operand = u128;
12493    #[inline]
12494    fn apply(a: u128) -> u128 {
12495        const_ring_eval_w88(PrimitiveOp::Sub, 0, a)
12496    }
12497}
12498
12499impl UnaryRingOp<W88> for BNot<W88> {
12500    type Operand = u128;
12501    #[inline]
12502    fn apply(a: u128) -> u128 {
12503        const_ring_eval_w88(PrimitiveOp::Xor, a, u128::MAX >> (128 - 88))
12504    }
12505}
12506
12507impl UnaryRingOp<W88> for Succ<W88> {
12508    type Operand = u128;
12509    #[inline]
12510    fn apply(a: u128) -> u128 {
12511        <Neg<W88> as UnaryRingOp<W88>>::apply(<BNot<W88> as UnaryRingOp<W88>>::apply(a))
12512    }
12513}
12514
12515impl UnaryRingOp<W96> for Neg<W96> {
12516    type Operand = u128;
12517    #[inline]
12518    fn apply(a: u128) -> u128 {
12519        const_ring_eval_w96(PrimitiveOp::Sub, 0, a)
12520    }
12521}
12522
12523impl UnaryRingOp<W96> for BNot<W96> {
12524    type Operand = u128;
12525    #[inline]
12526    fn apply(a: u128) -> u128 {
12527        const_ring_eval_w96(PrimitiveOp::Xor, a, u128::MAX >> (128 - 96))
12528    }
12529}
12530
12531impl UnaryRingOp<W96> for Succ<W96> {
12532    type Operand = u128;
12533    #[inline]
12534    fn apply(a: u128) -> u128 {
12535        <Neg<W96> as UnaryRingOp<W96>>::apply(<BNot<W96> as UnaryRingOp<W96>>::apply(a))
12536    }
12537}
12538
12539impl UnaryRingOp<W104> for Neg<W104> {
12540    type Operand = u128;
12541    #[inline]
12542    fn apply(a: u128) -> u128 {
12543        const_ring_eval_w104(PrimitiveOp::Sub, 0, a)
12544    }
12545}
12546
12547impl UnaryRingOp<W104> for BNot<W104> {
12548    type Operand = u128;
12549    #[inline]
12550    fn apply(a: u128) -> u128 {
12551        const_ring_eval_w104(PrimitiveOp::Xor, a, u128::MAX >> (128 - 104))
12552    }
12553}
12554
12555impl UnaryRingOp<W104> for Succ<W104> {
12556    type Operand = u128;
12557    #[inline]
12558    fn apply(a: u128) -> u128 {
12559        <Neg<W104> as UnaryRingOp<W104>>::apply(<BNot<W104> as UnaryRingOp<W104>>::apply(a))
12560    }
12561}
12562
12563impl UnaryRingOp<W112> for Neg<W112> {
12564    type Operand = u128;
12565    #[inline]
12566    fn apply(a: u128) -> u128 {
12567        const_ring_eval_w112(PrimitiveOp::Sub, 0, a)
12568    }
12569}
12570
12571impl UnaryRingOp<W112> for BNot<W112> {
12572    type Operand = u128;
12573    #[inline]
12574    fn apply(a: u128) -> u128 {
12575        const_ring_eval_w112(PrimitiveOp::Xor, a, u128::MAX >> (128 - 112))
12576    }
12577}
12578
12579impl UnaryRingOp<W112> for Succ<W112> {
12580    type Operand = u128;
12581    #[inline]
12582    fn apply(a: u128) -> u128 {
12583        <Neg<W112> as UnaryRingOp<W112>>::apply(<BNot<W112> as UnaryRingOp<W112>>::apply(a))
12584    }
12585}
12586
12587impl UnaryRingOp<W120> for Neg<W120> {
12588    type Operand = u128;
12589    #[inline]
12590    fn apply(a: u128) -> u128 {
12591        const_ring_eval_w120(PrimitiveOp::Sub, 0, a)
12592    }
12593}
12594
12595impl UnaryRingOp<W120> for BNot<W120> {
12596    type Operand = u128;
12597    #[inline]
12598    fn apply(a: u128) -> u128 {
12599        const_ring_eval_w120(PrimitiveOp::Xor, a, u128::MAX >> (128 - 120))
12600    }
12601}
12602
12603impl UnaryRingOp<W120> for Succ<W120> {
12604    type Operand = u128;
12605    #[inline]
12606    fn apply(a: u128) -> u128 {
12607        <Neg<W120> as UnaryRingOp<W120>>::apply(<BNot<W120> as UnaryRingOp<W120>>::apply(a))
12608    }
12609}
12610
12611impl UnaryRingOp<W128> for Neg<W128> {
12612    type Operand = u128;
12613    #[inline]
12614    fn apply(a: u128) -> u128 {
12615        const_ring_eval_w128(PrimitiveOp::Sub, 0, a)
12616    }
12617}
12618
12619impl UnaryRingOp<W128> for BNot<W128> {
12620    type Operand = u128;
12621    #[inline]
12622    fn apply(a: u128) -> u128 {
12623        const_ring_eval_w128(PrimitiveOp::Xor, a, u128::MAX)
12624    }
12625}
12626
12627impl UnaryRingOp<W128> for Succ<W128> {
12628    type Operand = u128;
12629    #[inline]
12630    fn apply(a: u128) -> u128 {
12631        <Neg<W128> as UnaryRingOp<W128>>::apply(<BNot<W128> as UnaryRingOp<W128>>::apply(a))
12632    }
12633}
12634
12635/// Sealed marker for well-formed level embedding pairs (`(From, To)` with
12636/// `From <= To`). v0.2.2 W3.
12637pub trait ValidLevelEmbedding: valid_level_embedding_sealed::Sealed {}
12638
12639mod valid_level_embedding_sealed {
12640    /// Private supertrait. Not implementable outside this crate.
12641    pub trait Sealed {}
12642    impl Sealed for (super::W8, super::W8) {}
12643    impl Sealed for (super::W8, super::W16) {}
12644    impl Sealed for (super::W8, super::W24) {}
12645    impl Sealed for (super::W8, super::W32) {}
12646    impl Sealed for (super::W8, super::W40) {}
12647    impl Sealed for (super::W8, super::W48) {}
12648    impl Sealed for (super::W8, super::W56) {}
12649    impl Sealed for (super::W8, super::W64) {}
12650    impl Sealed for (super::W8, super::W72) {}
12651    impl Sealed for (super::W8, super::W80) {}
12652    impl Sealed for (super::W8, super::W88) {}
12653    impl Sealed for (super::W8, super::W96) {}
12654    impl Sealed for (super::W8, super::W104) {}
12655    impl Sealed for (super::W8, super::W112) {}
12656    impl Sealed for (super::W8, super::W120) {}
12657    impl Sealed for (super::W8, super::W128) {}
12658    impl Sealed for (super::W16, super::W16) {}
12659    impl Sealed for (super::W16, super::W24) {}
12660    impl Sealed for (super::W16, super::W32) {}
12661    impl Sealed for (super::W16, super::W40) {}
12662    impl Sealed for (super::W16, super::W48) {}
12663    impl Sealed for (super::W16, super::W56) {}
12664    impl Sealed for (super::W16, super::W64) {}
12665    impl Sealed for (super::W16, super::W72) {}
12666    impl Sealed for (super::W16, super::W80) {}
12667    impl Sealed for (super::W16, super::W88) {}
12668    impl Sealed for (super::W16, super::W96) {}
12669    impl Sealed for (super::W16, super::W104) {}
12670    impl Sealed for (super::W16, super::W112) {}
12671    impl Sealed for (super::W16, super::W120) {}
12672    impl Sealed for (super::W16, super::W128) {}
12673    impl Sealed for (super::W24, super::W24) {}
12674    impl Sealed for (super::W24, super::W32) {}
12675    impl Sealed for (super::W24, super::W40) {}
12676    impl Sealed for (super::W24, super::W48) {}
12677    impl Sealed for (super::W24, super::W56) {}
12678    impl Sealed for (super::W24, super::W64) {}
12679    impl Sealed for (super::W24, super::W72) {}
12680    impl Sealed for (super::W24, super::W80) {}
12681    impl Sealed for (super::W24, super::W88) {}
12682    impl Sealed for (super::W24, super::W96) {}
12683    impl Sealed for (super::W24, super::W104) {}
12684    impl Sealed for (super::W24, super::W112) {}
12685    impl Sealed for (super::W24, super::W120) {}
12686    impl Sealed for (super::W24, super::W128) {}
12687    impl Sealed for (super::W32, super::W32) {}
12688    impl Sealed for (super::W32, super::W40) {}
12689    impl Sealed for (super::W32, super::W48) {}
12690    impl Sealed for (super::W32, super::W56) {}
12691    impl Sealed for (super::W32, super::W64) {}
12692    impl Sealed for (super::W32, super::W72) {}
12693    impl Sealed for (super::W32, super::W80) {}
12694    impl Sealed for (super::W32, super::W88) {}
12695    impl Sealed for (super::W32, super::W96) {}
12696    impl Sealed for (super::W32, super::W104) {}
12697    impl Sealed for (super::W32, super::W112) {}
12698    impl Sealed for (super::W32, super::W120) {}
12699    impl Sealed for (super::W32, super::W128) {}
12700    impl Sealed for (super::W40, super::W40) {}
12701    impl Sealed for (super::W40, super::W48) {}
12702    impl Sealed for (super::W40, super::W56) {}
12703    impl Sealed for (super::W40, super::W64) {}
12704    impl Sealed for (super::W40, super::W72) {}
12705    impl Sealed for (super::W40, super::W80) {}
12706    impl Sealed for (super::W40, super::W88) {}
12707    impl Sealed for (super::W40, super::W96) {}
12708    impl Sealed for (super::W40, super::W104) {}
12709    impl Sealed for (super::W40, super::W112) {}
12710    impl Sealed for (super::W40, super::W120) {}
12711    impl Sealed for (super::W40, super::W128) {}
12712    impl Sealed for (super::W48, super::W48) {}
12713    impl Sealed for (super::W48, super::W56) {}
12714    impl Sealed for (super::W48, super::W64) {}
12715    impl Sealed for (super::W48, super::W72) {}
12716    impl Sealed for (super::W48, super::W80) {}
12717    impl Sealed for (super::W48, super::W88) {}
12718    impl Sealed for (super::W48, super::W96) {}
12719    impl Sealed for (super::W48, super::W104) {}
12720    impl Sealed for (super::W48, super::W112) {}
12721    impl Sealed for (super::W48, super::W120) {}
12722    impl Sealed for (super::W48, super::W128) {}
12723    impl Sealed for (super::W56, super::W56) {}
12724    impl Sealed for (super::W56, super::W64) {}
12725    impl Sealed for (super::W56, super::W72) {}
12726    impl Sealed for (super::W56, super::W80) {}
12727    impl Sealed for (super::W56, super::W88) {}
12728    impl Sealed for (super::W56, super::W96) {}
12729    impl Sealed for (super::W56, super::W104) {}
12730    impl Sealed for (super::W56, super::W112) {}
12731    impl Sealed for (super::W56, super::W120) {}
12732    impl Sealed for (super::W56, super::W128) {}
12733    impl Sealed for (super::W64, super::W64) {}
12734    impl Sealed for (super::W64, super::W72) {}
12735    impl Sealed for (super::W64, super::W80) {}
12736    impl Sealed for (super::W64, super::W88) {}
12737    impl Sealed for (super::W64, super::W96) {}
12738    impl Sealed for (super::W64, super::W104) {}
12739    impl Sealed for (super::W64, super::W112) {}
12740    impl Sealed for (super::W64, super::W120) {}
12741    impl Sealed for (super::W64, super::W128) {}
12742    impl Sealed for (super::W72, super::W72) {}
12743    impl Sealed for (super::W72, super::W80) {}
12744    impl Sealed for (super::W72, super::W88) {}
12745    impl Sealed for (super::W72, super::W96) {}
12746    impl Sealed for (super::W72, super::W104) {}
12747    impl Sealed for (super::W72, super::W112) {}
12748    impl Sealed for (super::W72, super::W120) {}
12749    impl Sealed for (super::W72, super::W128) {}
12750    impl Sealed for (super::W80, super::W80) {}
12751    impl Sealed for (super::W80, super::W88) {}
12752    impl Sealed for (super::W80, super::W96) {}
12753    impl Sealed for (super::W80, super::W104) {}
12754    impl Sealed for (super::W80, super::W112) {}
12755    impl Sealed for (super::W80, super::W120) {}
12756    impl Sealed for (super::W80, super::W128) {}
12757    impl Sealed for (super::W88, super::W88) {}
12758    impl Sealed for (super::W88, super::W96) {}
12759    impl Sealed for (super::W88, super::W104) {}
12760    impl Sealed for (super::W88, super::W112) {}
12761    impl Sealed for (super::W88, super::W120) {}
12762    impl Sealed for (super::W88, super::W128) {}
12763    impl Sealed for (super::W96, super::W96) {}
12764    impl Sealed for (super::W96, super::W104) {}
12765    impl Sealed for (super::W96, super::W112) {}
12766    impl Sealed for (super::W96, super::W120) {}
12767    impl Sealed for (super::W96, super::W128) {}
12768    impl Sealed for (super::W104, super::W104) {}
12769    impl Sealed for (super::W104, super::W112) {}
12770    impl Sealed for (super::W104, super::W120) {}
12771    impl Sealed for (super::W104, super::W128) {}
12772    impl Sealed for (super::W112, super::W112) {}
12773    impl Sealed for (super::W112, super::W120) {}
12774    impl Sealed for (super::W112, super::W128) {}
12775    impl Sealed for (super::W120, super::W120) {}
12776    impl Sealed for (super::W120, super::W128) {}
12777    impl Sealed for (super::W128, super::W128) {}
12778}
12779
12780impl ValidLevelEmbedding for (W8, W8) {}
12781impl ValidLevelEmbedding for (W8, W16) {}
12782impl ValidLevelEmbedding for (W8, W24) {}
12783impl ValidLevelEmbedding for (W8, W32) {}
12784impl ValidLevelEmbedding for (W8, W40) {}
12785impl ValidLevelEmbedding for (W8, W48) {}
12786impl ValidLevelEmbedding for (W8, W56) {}
12787impl ValidLevelEmbedding for (W8, W64) {}
12788impl ValidLevelEmbedding for (W8, W72) {}
12789impl ValidLevelEmbedding for (W8, W80) {}
12790impl ValidLevelEmbedding for (W8, W88) {}
12791impl ValidLevelEmbedding for (W8, W96) {}
12792impl ValidLevelEmbedding for (W8, W104) {}
12793impl ValidLevelEmbedding for (W8, W112) {}
12794impl ValidLevelEmbedding for (W8, W120) {}
12795impl ValidLevelEmbedding for (W8, W128) {}
12796impl ValidLevelEmbedding for (W16, W16) {}
12797impl ValidLevelEmbedding for (W16, W24) {}
12798impl ValidLevelEmbedding for (W16, W32) {}
12799impl ValidLevelEmbedding for (W16, W40) {}
12800impl ValidLevelEmbedding for (W16, W48) {}
12801impl ValidLevelEmbedding for (W16, W56) {}
12802impl ValidLevelEmbedding for (W16, W64) {}
12803impl ValidLevelEmbedding for (W16, W72) {}
12804impl ValidLevelEmbedding for (W16, W80) {}
12805impl ValidLevelEmbedding for (W16, W88) {}
12806impl ValidLevelEmbedding for (W16, W96) {}
12807impl ValidLevelEmbedding for (W16, W104) {}
12808impl ValidLevelEmbedding for (W16, W112) {}
12809impl ValidLevelEmbedding for (W16, W120) {}
12810impl ValidLevelEmbedding for (W16, W128) {}
12811impl ValidLevelEmbedding for (W24, W24) {}
12812impl ValidLevelEmbedding for (W24, W32) {}
12813impl ValidLevelEmbedding for (W24, W40) {}
12814impl ValidLevelEmbedding for (W24, W48) {}
12815impl ValidLevelEmbedding for (W24, W56) {}
12816impl ValidLevelEmbedding for (W24, W64) {}
12817impl ValidLevelEmbedding for (W24, W72) {}
12818impl ValidLevelEmbedding for (W24, W80) {}
12819impl ValidLevelEmbedding for (W24, W88) {}
12820impl ValidLevelEmbedding for (W24, W96) {}
12821impl ValidLevelEmbedding for (W24, W104) {}
12822impl ValidLevelEmbedding for (W24, W112) {}
12823impl ValidLevelEmbedding for (W24, W120) {}
12824impl ValidLevelEmbedding for (W24, W128) {}
12825impl ValidLevelEmbedding for (W32, W32) {}
12826impl ValidLevelEmbedding for (W32, W40) {}
12827impl ValidLevelEmbedding for (W32, W48) {}
12828impl ValidLevelEmbedding for (W32, W56) {}
12829impl ValidLevelEmbedding for (W32, W64) {}
12830impl ValidLevelEmbedding for (W32, W72) {}
12831impl ValidLevelEmbedding for (W32, W80) {}
12832impl ValidLevelEmbedding for (W32, W88) {}
12833impl ValidLevelEmbedding for (W32, W96) {}
12834impl ValidLevelEmbedding for (W32, W104) {}
12835impl ValidLevelEmbedding for (W32, W112) {}
12836impl ValidLevelEmbedding for (W32, W120) {}
12837impl ValidLevelEmbedding for (W32, W128) {}
12838impl ValidLevelEmbedding for (W40, W40) {}
12839impl ValidLevelEmbedding for (W40, W48) {}
12840impl ValidLevelEmbedding for (W40, W56) {}
12841impl ValidLevelEmbedding for (W40, W64) {}
12842impl ValidLevelEmbedding for (W40, W72) {}
12843impl ValidLevelEmbedding for (W40, W80) {}
12844impl ValidLevelEmbedding for (W40, W88) {}
12845impl ValidLevelEmbedding for (W40, W96) {}
12846impl ValidLevelEmbedding for (W40, W104) {}
12847impl ValidLevelEmbedding for (W40, W112) {}
12848impl ValidLevelEmbedding for (W40, W120) {}
12849impl ValidLevelEmbedding for (W40, W128) {}
12850impl ValidLevelEmbedding for (W48, W48) {}
12851impl ValidLevelEmbedding for (W48, W56) {}
12852impl ValidLevelEmbedding for (W48, W64) {}
12853impl ValidLevelEmbedding for (W48, W72) {}
12854impl ValidLevelEmbedding for (W48, W80) {}
12855impl ValidLevelEmbedding for (W48, W88) {}
12856impl ValidLevelEmbedding for (W48, W96) {}
12857impl ValidLevelEmbedding for (W48, W104) {}
12858impl ValidLevelEmbedding for (W48, W112) {}
12859impl ValidLevelEmbedding for (W48, W120) {}
12860impl ValidLevelEmbedding for (W48, W128) {}
12861impl ValidLevelEmbedding for (W56, W56) {}
12862impl ValidLevelEmbedding for (W56, W64) {}
12863impl ValidLevelEmbedding for (W56, W72) {}
12864impl ValidLevelEmbedding for (W56, W80) {}
12865impl ValidLevelEmbedding for (W56, W88) {}
12866impl ValidLevelEmbedding for (W56, W96) {}
12867impl ValidLevelEmbedding for (W56, W104) {}
12868impl ValidLevelEmbedding for (W56, W112) {}
12869impl ValidLevelEmbedding for (W56, W120) {}
12870impl ValidLevelEmbedding for (W56, W128) {}
12871impl ValidLevelEmbedding for (W64, W64) {}
12872impl ValidLevelEmbedding for (W64, W72) {}
12873impl ValidLevelEmbedding for (W64, W80) {}
12874impl ValidLevelEmbedding for (W64, W88) {}
12875impl ValidLevelEmbedding for (W64, W96) {}
12876impl ValidLevelEmbedding for (W64, W104) {}
12877impl ValidLevelEmbedding for (W64, W112) {}
12878impl ValidLevelEmbedding for (W64, W120) {}
12879impl ValidLevelEmbedding for (W64, W128) {}
12880impl ValidLevelEmbedding for (W72, W72) {}
12881impl ValidLevelEmbedding for (W72, W80) {}
12882impl ValidLevelEmbedding for (W72, W88) {}
12883impl ValidLevelEmbedding for (W72, W96) {}
12884impl ValidLevelEmbedding for (W72, W104) {}
12885impl ValidLevelEmbedding for (W72, W112) {}
12886impl ValidLevelEmbedding for (W72, W120) {}
12887impl ValidLevelEmbedding for (W72, W128) {}
12888impl ValidLevelEmbedding for (W80, W80) {}
12889impl ValidLevelEmbedding for (W80, W88) {}
12890impl ValidLevelEmbedding for (W80, W96) {}
12891impl ValidLevelEmbedding for (W80, W104) {}
12892impl ValidLevelEmbedding for (W80, W112) {}
12893impl ValidLevelEmbedding for (W80, W120) {}
12894impl ValidLevelEmbedding for (W80, W128) {}
12895impl ValidLevelEmbedding for (W88, W88) {}
12896impl ValidLevelEmbedding for (W88, W96) {}
12897impl ValidLevelEmbedding for (W88, W104) {}
12898impl ValidLevelEmbedding for (W88, W112) {}
12899impl ValidLevelEmbedding for (W88, W120) {}
12900impl ValidLevelEmbedding for (W88, W128) {}
12901impl ValidLevelEmbedding for (W96, W96) {}
12902impl ValidLevelEmbedding for (W96, W104) {}
12903impl ValidLevelEmbedding for (W96, W112) {}
12904impl ValidLevelEmbedding for (W96, W120) {}
12905impl ValidLevelEmbedding for (W96, W128) {}
12906impl ValidLevelEmbedding for (W104, W104) {}
12907impl ValidLevelEmbedding for (W104, W112) {}
12908impl ValidLevelEmbedding for (W104, W120) {}
12909impl ValidLevelEmbedding for (W104, W128) {}
12910impl ValidLevelEmbedding for (W112, W112) {}
12911impl ValidLevelEmbedding for (W112, W120) {}
12912impl ValidLevelEmbedding for (W112, W128) {}
12913impl ValidLevelEmbedding for (W120, W120) {}
12914impl ValidLevelEmbedding for (W120, W128) {}
12915impl ValidLevelEmbedding for (W128, W128) {}
12916
12917/// v0.2.2 W3: phantom-typed level embedding `Embed<From, To>` for the
12918/// canonical injection ι : R_From → R_To when `From <= To`.
12919/// Implementations exist only for sealed `(From, To)` pairs in the
12920/// `ValidLevelEmbedding` trait, so attempting an unsupported direction
12921/// (e.g., `Embed<W32, W8>`) fails at compile time.
12922#[derive(Debug, Default, Clone, Copy)]
12923pub struct Embed<From, To>(PhantomData<(From, To)>);
12924
12925impl Embed<W8, W8> {
12926    /// Embed a `u8` value at W8 into a `u8` value at W8.
12927    #[inline]
12928    #[must_use]
12929    pub const fn apply(value: u8) -> u8 {
12930        value
12931    }
12932}
12933
12934impl Embed<W8, W16> {
12935    /// Embed a `u8` value at W8 into a `u16` value at W16.
12936    #[inline]
12937    #[must_use]
12938    pub const fn apply(value: u8) -> u16 {
12939        value as u16
12940    }
12941}
12942
12943impl Embed<W8, W24> {
12944    /// Embed a `u8` value at W8 into a `u32` value at W24.
12945    #[inline]
12946    #[must_use]
12947    pub const fn apply(value: u8) -> u32 {
12948        value as u32
12949    }
12950}
12951
12952impl Embed<W8, W32> {
12953    /// Embed a `u8` value at W8 into a `u32` value at W32.
12954    #[inline]
12955    #[must_use]
12956    pub const fn apply(value: u8) -> u32 {
12957        value as u32
12958    }
12959}
12960
12961impl Embed<W8, W40> {
12962    /// Embed a `u8` value at W8 into a `u64` value at W40.
12963    #[inline]
12964    #[must_use]
12965    pub const fn apply(value: u8) -> u64 {
12966        value as u64
12967    }
12968}
12969
12970impl Embed<W8, W48> {
12971    /// Embed a `u8` value at W8 into a `u64` value at W48.
12972    #[inline]
12973    #[must_use]
12974    pub const fn apply(value: u8) -> u64 {
12975        value as u64
12976    }
12977}
12978
12979impl Embed<W8, W56> {
12980    /// Embed a `u8` value at W8 into a `u64` value at W56.
12981    #[inline]
12982    #[must_use]
12983    pub const fn apply(value: u8) -> u64 {
12984        value as u64
12985    }
12986}
12987
12988impl Embed<W8, W64> {
12989    /// Embed a `u8` value at W8 into a `u64` value at W64.
12990    #[inline]
12991    #[must_use]
12992    pub const fn apply(value: u8) -> u64 {
12993        value as u64
12994    }
12995}
12996
12997impl Embed<W8, W72> {
12998    /// Embed a `u8` value at W8 into a `u128` value at W72.
12999    #[inline]
13000    #[must_use]
13001    pub const fn apply(value: u8) -> u128 {
13002        value as u128
13003    }
13004}
13005
13006impl Embed<W8, W80> {
13007    /// Embed a `u8` value at W8 into a `u128` value at W80.
13008    #[inline]
13009    #[must_use]
13010    pub const fn apply(value: u8) -> u128 {
13011        value as u128
13012    }
13013}
13014
13015impl Embed<W8, W88> {
13016    /// Embed a `u8` value at W8 into a `u128` value at W88.
13017    #[inline]
13018    #[must_use]
13019    pub const fn apply(value: u8) -> u128 {
13020        value as u128
13021    }
13022}
13023
13024impl Embed<W8, W96> {
13025    /// Embed a `u8` value at W8 into a `u128` value at W96.
13026    #[inline]
13027    #[must_use]
13028    pub const fn apply(value: u8) -> u128 {
13029        value as u128
13030    }
13031}
13032
13033impl Embed<W8, W104> {
13034    /// Embed a `u8` value at W8 into a `u128` value at W104.
13035    #[inline]
13036    #[must_use]
13037    pub const fn apply(value: u8) -> u128 {
13038        value as u128
13039    }
13040}
13041
13042impl Embed<W8, W112> {
13043    /// Embed a `u8` value at W8 into a `u128` value at W112.
13044    #[inline]
13045    #[must_use]
13046    pub const fn apply(value: u8) -> u128 {
13047        value as u128
13048    }
13049}
13050
13051impl Embed<W8, W120> {
13052    /// Embed a `u8` value at W8 into a `u128` value at W120.
13053    #[inline]
13054    #[must_use]
13055    pub const fn apply(value: u8) -> u128 {
13056        value as u128
13057    }
13058}
13059
13060impl Embed<W8, W128> {
13061    /// Embed a `u8` value at W8 into a `u128` value at W128.
13062    #[inline]
13063    #[must_use]
13064    pub const fn apply(value: u8) -> u128 {
13065        value as u128
13066    }
13067}
13068
13069impl Embed<W16, W16> {
13070    /// Embed a `u16` value at W16 into a `u16` value at W16.
13071    #[inline]
13072    #[must_use]
13073    pub const fn apply(value: u16) -> u16 {
13074        value
13075    }
13076}
13077
13078impl Embed<W16, W24> {
13079    /// Embed a `u16` value at W16 into a `u32` value at W24.
13080    #[inline]
13081    #[must_use]
13082    pub const fn apply(value: u16) -> u32 {
13083        value as u32
13084    }
13085}
13086
13087impl Embed<W16, W32> {
13088    /// Embed a `u16` value at W16 into a `u32` value at W32.
13089    #[inline]
13090    #[must_use]
13091    pub const fn apply(value: u16) -> u32 {
13092        value as u32
13093    }
13094}
13095
13096impl Embed<W16, W40> {
13097    /// Embed a `u16` value at W16 into a `u64` value at W40.
13098    #[inline]
13099    #[must_use]
13100    pub const fn apply(value: u16) -> u64 {
13101        value as u64
13102    }
13103}
13104
13105impl Embed<W16, W48> {
13106    /// Embed a `u16` value at W16 into a `u64` value at W48.
13107    #[inline]
13108    #[must_use]
13109    pub const fn apply(value: u16) -> u64 {
13110        value as u64
13111    }
13112}
13113
13114impl Embed<W16, W56> {
13115    /// Embed a `u16` value at W16 into a `u64` value at W56.
13116    #[inline]
13117    #[must_use]
13118    pub const fn apply(value: u16) -> u64 {
13119        value as u64
13120    }
13121}
13122
13123impl Embed<W16, W64> {
13124    /// Embed a `u16` value at W16 into a `u64` value at W64.
13125    #[inline]
13126    #[must_use]
13127    pub const fn apply(value: u16) -> u64 {
13128        value as u64
13129    }
13130}
13131
13132impl Embed<W16, W72> {
13133    /// Embed a `u16` value at W16 into a `u128` value at W72.
13134    #[inline]
13135    #[must_use]
13136    pub const fn apply(value: u16) -> u128 {
13137        value as u128
13138    }
13139}
13140
13141impl Embed<W16, W80> {
13142    /// Embed a `u16` value at W16 into a `u128` value at W80.
13143    #[inline]
13144    #[must_use]
13145    pub const fn apply(value: u16) -> u128 {
13146        value as u128
13147    }
13148}
13149
13150impl Embed<W16, W88> {
13151    /// Embed a `u16` value at W16 into a `u128` value at W88.
13152    #[inline]
13153    #[must_use]
13154    pub const fn apply(value: u16) -> u128 {
13155        value as u128
13156    }
13157}
13158
13159impl Embed<W16, W96> {
13160    /// Embed a `u16` value at W16 into a `u128` value at W96.
13161    #[inline]
13162    #[must_use]
13163    pub const fn apply(value: u16) -> u128 {
13164        value as u128
13165    }
13166}
13167
13168impl Embed<W16, W104> {
13169    /// Embed a `u16` value at W16 into a `u128` value at W104.
13170    #[inline]
13171    #[must_use]
13172    pub const fn apply(value: u16) -> u128 {
13173        value as u128
13174    }
13175}
13176
13177impl Embed<W16, W112> {
13178    /// Embed a `u16` value at W16 into a `u128` value at W112.
13179    #[inline]
13180    #[must_use]
13181    pub const fn apply(value: u16) -> u128 {
13182        value as u128
13183    }
13184}
13185
13186impl Embed<W16, W120> {
13187    /// Embed a `u16` value at W16 into a `u128` value at W120.
13188    #[inline]
13189    #[must_use]
13190    pub const fn apply(value: u16) -> u128 {
13191        value as u128
13192    }
13193}
13194
13195impl Embed<W16, W128> {
13196    /// Embed a `u16` value at W16 into a `u128` value at W128.
13197    #[inline]
13198    #[must_use]
13199    pub const fn apply(value: u16) -> u128 {
13200        value as u128
13201    }
13202}
13203
13204impl Embed<W24, W24> {
13205    /// Embed a `u32` value at W24 into a `u32` value at W24.
13206    #[inline]
13207    #[must_use]
13208    pub const fn apply(value: u32) -> u32 {
13209        value
13210    }
13211}
13212
13213impl Embed<W24, W32> {
13214    /// Embed a `u32` value at W24 into a `u32` value at W32.
13215    #[inline]
13216    #[must_use]
13217    pub const fn apply(value: u32) -> u32 {
13218        value
13219    }
13220}
13221
13222impl Embed<W24, W40> {
13223    /// Embed a `u32` value at W24 into a `u64` value at W40.
13224    #[inline]
13225    #[must_use]
13226    pub const fn apply(value: u32) -> u64 {
13227        value as u64
13228    }
13229}
13230
13231impl Embed<W24, W48> {
13232    /// Embed a `u32` value at W24 into a `u64` value at W48.
13233    #[inline]
13234    #[must_use]
13235    pub const fn apply(value: u32) -> u64 {
13236        value as u64
13237    }
13238}
13239
13240impl Embed<W24, W56> {
13241    /// Embed a `u32` value at W24 into a `u64` value at W56.
13242    #[inline]
13243    #[must_use]
13244    pub const fn apply(value: u32) -> u64 {
13245        value as u64
13246    }
13247}
13248
13249impl Embed<W24, W64> {
13250    /// Embed a `u32` value at W24 into a `u64` value at W64.
13251    #[inline]
13252    #[must_use]
13253    pub const fn apply(value: u32) -> u64 {
13254        value as u64
13255    }
13256}
13257
13258impl Embed<W24, W72> {
13259    /// Embed a `u32` value at W24 into a `u128` value at W72.
13260    #[inline]
13261    #[must_use]
13262    pub const fn apply(value: u32) -> u128 {
13263        value as u128
13264    }
13265}
13266
13267impl Embed<W24, W80> {
13268    /// Embed a `u32` value at W24 into a `u128` value at W80.
13269    #[inline]
13270    #[must_use]
13271    pub const fn apply(value: u32) -> u128 {
13272        value as u128
13273    }
13274}
13275
13276impl Embed<W24, W88> {
13277    /// Embed a `u32` value at W24 into a `u128` value at W88.
13278    #[inline]
13279    #[must_use]
13280    pub const fn apply(value: u32) -> u128 {
13281        value as u128
13282    }
13283}
13284
13285impl Embed<W24, W96> {
13286    /// Embed a `u32` value at W24 into a `u128` value at W96.
13287    #[inline]
13288    #[must_use]
13289    pub const fn apply(value: u32) -> u128 {
13290        value as u128
13291    }
13292}
13293
13294impl Embed<W24, W104> {
13295    /// Embed a `u32` value at W24 into a `u128` value at W104.
13296    #[inline]
13297    #[must_use]
13298    pub const fn apply(value: u32) -> u128 {
13299        value as u128
13300    }
13301}
13302
13303impl Embed<W24, W112> {
13304    /// Embed a `u32` value at W24 into a `u128` value at W112.
13305    #[inline]
13306    #[must_use]
13307    pub const fn apply(value: u32) -> u128 {
13308        value as u128
13309    }
13310}
13311
13312impl Embed<W24, W120> {
13313    /// Embed a `u32` value at W24 into a `u128` value at W120.
13314    #[inline]
13315    #[must_use]
13316    pub const fn apply(value: u32) -> u128 {
13317        value as u128
13318    }
13319}
13320
13321impl Embed<W24, W128> {
13322    /// Embed a `u32` value at W24 into a `u128` value at W128.
13323    #[inline]
13324    #[must_use]
13325    pub const fn apply(value: u32) -> u128 {
13326        value as u128
13327    }
13328}
13329
13330impl Embed<W32, W32> {
13331    /// Embed a `u32` value at W32 into a `u32` value at W32.
13332    #[inline]
13333    #[must_use]
13334    pub const fn apply(value: u32) -> u32 {
13335        value
13336    }
13337}
13338
13339impl Embed<W32, W40> {
13340    /// Embed a `u32` value at W32 into a `u64` value at W40.
13341    #[inline]
13342    #[must_use]
13343    pub const fn apply(value: u32) -> u64 {
13344        value as u64
13345    }
13346}
13347
13348impl Embed<W32, W48> {
13349    /// Embed a `u32` value at W32 into a `u64` value at W48.
13350    #[inline]
13351    #[must_use]
13352    pub const fn apply(value: u32) -> u64 {
13353        value as u64
13354    }
13355}
13356
13357impl Embed<W32, W56> {
13358    /// Embed a `u32` value at W32 into a `u64` value at W56.
13359    #[inline]
13360    #[must_use]
13361    pub const fn apply(value: u32) -> u64 {
13362        value as u64
13363    }
13364}
13365
13366impl Embed<W32, W64> {
13367    /// Embed a `u32` value at W32 into a `u64` value at W64.
13368    #[inline]
13369    #[must_use]
13370    pub const fn apply(value: u32) -> u64 {
13371        value as u64
13372    }
13373}
13374
13375impl Embed<W32, W72> {
13376    /// Embed a `u32` value at W32 into a `u128` value at W72.
13377    #[inline]
13378    #[must_use]
13379    pub const fn apply(value: u32) -> u128 {
13380        value as u128
13381    }
13382}
13383
13384impl Embed<W32, W80> {
13385    /// Embed a `u32` value at W32 into a `u128` value at W80.
13386    #[inline]
13387    #[must_use]
13388    pub const fn apply(value: u32) -> u128 {
13389        value as u128
13390    }
13391}
13392
13393impl Embed<W32, W88> {
13394    /// Embed a `u32` value at W32 into a `u128` value at W88.
13395    #[inline]
13396    #[must_use]
13397    pub const fn apply(value: u32) -> u128 {
13398        value as u128
13399    }
13400}
13401
13402impl Embed<W32, W96> {
13403    /// Embed a `u32` value at W32 into a `u128` value at W96.
13404    #[inline]
13405    #[must_use]
13406    pub const fn apply(value: u32) -> u128 {
13407        value as u128
13408    }
13409}
13410
13411impl Embed<W32, W104> {
13412    /// Embed a `u32` value at W32 into a `u128` value at W104.
13413    #[inline]
13414    #[must_use]
13415    pub const fn apply(value: u32) -> u128 {
13416        value as u128
13417    }
13418}
13419
13420impl Embed<W32, W112> {
13421    /// Embed a `u32` value at W32 into a `u128` value at W112.
13422    #[inline]
13423    #[must_use]
13424    pub const fn apply(value: u32) -> u128 {
13425        value as u128
13426    }
13427}
13428
13429impl Embed<W32, W120> {
13430    /// Embed a `u32` value at W32 into a `u128` value at W120.
13431    #[inline]
13432    #[must_use]
13433    pub const fn apply(value: u32) -> u128 {
13434        value as u128
13435    }
13436}
13437
13438impl Embed<W32, W128> {
13439    /// Embed a `u32` value at W32 into a `u128` value at W128.
13440    #[inline]
13441    #[must_use]
13442    pub const fn apply(value: u32) -> u128 {
13443        value as u128
13444    }
13445}
13446
13447impl Embed<W40, W40> {
13448    /// Embed a `u64` value at W40 into a `u64` value at W40.
13449    #[inline]
13450    #[must_use]
13451    pub const fn apply(value: u64) -> u64 {
13452        value
13453    }
13454}
13455
13456impl Embed<W40, W48> {
13457    /// Embed a `u64` value at W40 into a `u64` value at W48.
13458    #[inline]
13459    #[must_use]
13460    pub const fn apply(value: u64) -> u64 {
13461        value
13462    }
13463}
13464
13465impl Embed<W40, W56> {
13466    /// Embed a `u64` value at W40 into a `u64` value at W56.
13467    #[inline]
13468    #[must_use]
13469    pub const fn apply(value: u64) -> u64 {
13470        value
13471    }
13472}
13473
13474impl Embed<W40, W64> {
13475    /// Embed a `u64` value at W40 into a `u64` value at W64.
13476    #[inline]
13477    #[must_use]
13478    pub const fn apply(value: u64) -> u64 {
13479        value
13480    }
13481}
13482
13483impl Embed<W40, W72> {
13484    /// Embed a `u64` value at W40 into a `u128` value at W72.
13485    #[inline]
13486    #[must_use]
13487    pub const fn apply(value: u64) -> u128 {
13488        value as u128
13489    }
13490}
13491
13492impl Embed<W40, W80> {
13493    /// Embed a `u64` value at W40 into a `u128` value at W80.
13494    #[inline]
13495    #[must_use]
13496    pub const fn apply(value: u64) -> u128 {
13497        value as u128
13498    }
13499}
13500
13501impl Embed<W40, W88> {
13502    /// Embed a `u64` value at W40 into a `u128` value at W88.
13503    #[inline]
13504    #[must_use]
13505    pub const fn apply(value: u64) -> u128 {
13506        value as u128
13507    }
13508}
13509
13510impl Embed<W40, W96> {
13511    /// Embed a `u64` value at W40 into a `u128` value at W96.
13512    #[inline]
13513    #[must_use]
13514    pub const fn apply(value: u64) -> u128 {
13515        value as u128
13516    }
13517}
13518
13519impl Embed<W40, W104> {
13520    /// Embed a `u64` value at W40 into a `u128` value at W104.
13521    #[inline]
13522    #[must_use]
13523    pub const fn apply(value: u64) -> u128 {
13524        value as u128
13525    }
13526}
13527
13528impl Embed<W40, W112> {
13529    /// Embed a `u64` value at W40 into a `u128` value at W112.
13530    #[inline]
13531    #[must_use]
13532    pub const fn apply(value: u64) -> u128 {
13533        value as u128
13534    }
13535}
13536
13537impl Embed<W40, W120> {
13538    /// Embed a `u64` value at W40 into a `u128` value at W120.
13539    #[inline]
13540    #[must_use]
13541    pub const fn apply(value: u64) -> u128 {
13542        value as u128
13543    }
13544}
13545
13546impl Embed<W40, W128> {
13547    /// Embed a `u64` value at W40 into a `u128` value at W128.
13548    #[inline]
13549    #[must_use]
13550    pub const fn apply(value: u64) -> u128 {
13551        value as u128
13552    }
13553}
13554
13555impl Embed<W48, W48> {
13556    /// Embed a `u64` value at W48 into a `u64` value at W48.
13557    #[inline]
13558    #[must_use]
13559    pub const fn apply(value: u64) -> u64 {
13560        value
13561    }
13562}
13563
13564impl Embed<W48, W56> {
13565    /// Embed a `u64` value at W48 into a `u64` value at W56.
13566    #[inline]
13567    #[must_use]
13568    pub const fn apply(value: u64) -> u64 {
13569        value
13570    }
13571}
13572
13573impl Embed<W48, W64> {
13574    /// Embed a `u64` value at W48 into a `u64` value at W64.
13575    #[inline]
13576    #[must_use]
13577    pub const fn apply(value: u64) -> u64 {
13578        value
13579    }
13580}
13581
13582impl Embed<W48, W72> {
13583    /// Embed a `u64` value at W48 into a `u128` value at W72.
13584    #[inline]
13585    #[must_use]
13586    pub const fn apply(value: u64) -> u128 {
13587        value as u128
13588    }
13589}
13590
13591impl Embed<W48, W80> {
13592    /// Embed a `u64` value at W48 into a `u128` value at W80.
13593    #[inline]
13594    #[must_use]
13595    pub const fn apply(value: u64) -> u128 {
13596        value as u128
13597    }
13598}
13599
13600impl Embed<W48, W88> {
13601    /// Embed a `u64` value at W48 into a `u128` value at W88.
13602    #[inline]
13603    #[must_use]
13604    pub const fn apply(value: u64) -> u128 {
13605        value as u128
13606    }
13607}
13608
13609impl Embed<W48, W96> {
13610    /// Embed a `u64` value at W48 into a `u128` value at W96.
13611    #[inline]
13612    #[must_use]
13613    pub const fn apply(value: u64) -> u128 {
13614        value as u128
13615    }
13616}
13617
13618impl Embed<W48, W104> {
13619    /// Embed a `u64` value at W48 into a `u128` value at W104.
13620    #[inline]
13621    #[must_use]
13622    pub const fn apply(value: u64) -> u128 {
13623        value as u128
13624    }
13625}
13626
13627impl Embed<W48, W112> {
13628    /// Embed a `u64` value at W48 into a `u128` value at W112.
13629    #[inline]
13630    #[must_use]
13631    pub const fn apply(value: u64) -> u128 {
13632        value as u128
13633    }
13634}
13635
13636impl Embed<W48, W120> {
13637    /// Embed a `u64` value at W48 into a `u128` value at W120.
13638    #[inline]
13639    #[must_use]
13640    pub const fn apply(value: u64) -> u128 {
13641        value as u128
13642    }
13643}
13644
13645impl Embed<W48, W128> {
13646    /// Embed a `u64` value at W48 into a `u128` value at W128.
13647    #[inline]
13648    #[must_use]
13649    pub const fn apply(value: u64) -> u128 {
13650        value as u128
13651    }
13652}
13653
13654impl Embed<W56, W56> {
13655    /// Embed a `u64` value at W56 into a `u64` value at W56.
13656    #[inline]
13657    #[must_use]
13658    pub const fn apply(value: u64) -> u64 {
13659        value
13660    }
13661}
13662
13663impl Embed<W56, W64> {
13664    /// Embed a `u64` value at W56 into a `u64` value at W64.
13665    #[inline]
13666    #[must_use]
13667    pub const fn apply(value: u64) -> u64 {
13668        value
13669    }
13670}
13671
13672impl Embed<W56, W72> {
13673    /// Embed a `u64` value at W56 into a `u128` value at W72.
13674    #[inline]
13675    #[must_use]
13676    pub const fn apply(value: u64) -> u128 {
13677        value as u128
13678    }
13679}
13680
13681impl Embed<W56, W80> {
13682    /// Embed a `u64` value at W56 into a `u128` value at W80.
13683    #[inline]
13684    #[must_use]
13685    pub const fn apply(value: u64) -> u128 {
13686        value as u128
13687    }
13688}
13689
13690impl Embed<W56, W88> {
13691    /// Embed a `u64` value at W56 into a `u128` value at W88.
13692    #[inline]
13693    #[must_use]
13694    pub const fn apply(value: u64) -> u128 {
13695        value as u128
13696    }
13697}
13698
13699impl Embed<W56, W96> {
13700    /// Embed a `u64` value at W56 into a `u128` value at W96.
13701    #[inline]
13702    #[must_use]
13703    pub const fn apply(value: u64) -> u128 {
13704        value as u128
13705    }
13706}
13707
13708impl Embed<W56, W104> {
13709    /// Embed a `u64` value at W56 into a `u128` value at W104.
13710    #[inline]
13711    #[must_use]
13712    pub const fn apply(value: u64) -> u128 {
13713        value as u128
13714    }
13715}
13716
13717impl Embed<W56, W112> {
13718    /// Embed a `u64` value at W56 into a `u128` value at W112.
13719    #[inline]
13720    #[must_use]
13721    pub const fn apply(value: u64) -> u128 {
13722        value as u128
13723    }
13724}
13725
13726impl Embed<W56, W120> {
13727    /// Embed a `u64` value at W56 into a `u128` value at W120.
13728    #[inline]
13729    #[must_use]
13730    pub const fn apply(value: u64) -> u128 {
13731        value as u128
13732    }
13733}
13734
13735impl Embed<W56, W128> {
13736    /// Embed a `u64` value at W56 into a `u128` value at W128.
13737    #[inline]
13738    #[must_use]
13739    pub const fn apply(value: u64) -> u128 {
13740        value as u128
13741    }
13742}
13743
13744impl Embed<W64, W64> {
13745    /// Embed a `u64` value at W64 into a `u64` value at W64.
13746    #[inline]
13747    #[must_use]
13748    pub const fn apply(value: u64) -> u64 {
13749        value
13750    }
13751}
13752
13753impl Embed<W64, W72> {
13754    /// Embed a `u64` value at W64 into a `u128` value at W72.
13755    #[inline]
13756    #[must_use]
13757    pub const fn apply(value: u64) -> u128 {
13758        value as u128
13759    }
13760}
13761
13762impl Embed<W64, W80> {
13763    /// Embed a `u64` value at W64 into a `u128` value at W80.
13764    #[inline]
13765    #[must_use]
13766    pub const fn apply(value: u64) -> u128 {
13767        value as u128
13768    }
13769}
13770
13771impl Embed<W64, W88> {
13772    /// Embed a `u64` value at W64 into a `u128` value at W88.
13773    #[inline]
13774    #[must_use]
13775    pub const fn apply(value: u64) -> u128 {
13776        value as u128
13777    }
13778}
13779
13780impl Embed<W64, W96> {
13781    /// Embed a `u64` value at W64 into a `u128` value at W96.
13782    #[inline]
13783    #[must_use]
13784    pub const fn apply(value: u64) -> u128 {
13785        value as u128
13786    }
13787}
13788
13789impl Embed<W64, W104> {
13790    /// Embed a `u64` value at W64 into a `u128` value at W104.
13791    #[inline]
13792    #[must_use]
13793    pub const fn apply(value: u64) -> u128 {
13794        value as u128
13795    }
13796}
13797
13798impl Embed<W64, W112> {
13799    /// Embed a `u64` value at W64 into a `u128` value at W112.
13800    #[inline]
13801    #[must_use]
13802    pub const fn apply(value: u64) -> u128 {
13803        value as u128
13804    }
13805}
13806
13807impl Embed<W64, W120> {
13808    /// Embed a `u64` value at W64 into a `u128` value at W120.
13809    #[inline]
13810    #[must_use]
13811    pub const fn apply(value: u64) -> u128 {
13812        value as u128
13813    }
13814}
13815
13816impl Embed<W64, W128> {
13817    /// Embed a `u64` value at W64 into a `u128` value at W128.
13818    #[inline]
13819    #[must_use]
13820    pub const fn apply(value: u64) -> u128 {
13821        value as u128
13822    }
13823}
13824
13825impl Embed<W72, W72> {
13826    /// Embed a `u128` value at W72 into a `u128` value at W72.
13827    #[inline]
13828    #[must_use]
13829    pub const fn apply(value: u128) -> u128 {
13830        value
13831    }
13832}
13833
13834impl Embed<W72, W80> {
13835    /// Embed a `u128` value at W72 into a `u128` value at W80.
13836    #[inline]
13837    #[must_use]
13838    pub const fn apply(value: u128) -> u128 {
13839        value
13840    }
13841}
13842
13843impl Embed<W72, W88> {
13844    /// Embed a `u128` value at W72 into a `u128` value at W88.
13845    #[inline]
13846    #[must_use]
13847    pub const fn apply(value: u128) -> u128 {
13848        value
13849    }
13850}
13851
13852impl Embed<W72, W96> {
13853    /// Embed a `u128` value at W72 into a `u128` value at W96.
13854    #[inline]
13855    #[must_use]
13856    pub const fn apply(value: u128) -> u128 {
13857        value
13858    }
13859}
13860
13861impl Embed<W72, W104> {
13862    /// Embed a `u128` value at W72 into a `u128` value at W104.
13863    #[inline]
13864    #[must_use]
13865    pub const fn apply(value: u128) -> u128 {
13866        value
13867    }
13868}
13869
13870impl Embed<W72, W112> {
13871    /// Embed a `u128` value at W72 into a `u128` value at W112.
13872    #[inline]
13873    #[must_use]
13874    pub const fn apply(value: u128) -> u128 {
13875        value
13876    }
13877}
13878
13879impl Embed<W72, W120> {
13880    /// Embed a `u128` value at W72 into a `u128` value at W120.
13881    #[inline]
13882    #[must_use]
13883    pub const fn apply(value: u128) -> u128 {
13884        value
13885    }
13886}
13887
13888impl Embed<W72, W128> {
13889    /// Embed a `u128` value at W72 into a `u128` value at W128.
13890    #[inline]
13891    #[must_use]
13892    pub const fn apply(value: u128) -> u128 {
13893        value
13894    }
13895}
13896
13897impl Embed<W80, W80> {
13898    /// Embed a `u128` value at W80 into a `u128` value at W80.
13899    #[inline]
13900    #[must_use]
13901    pub const fn apply(value: u128) -> u128 {
13902        value
13903    }
13904}
13905
13906impl Embed<W80, W88> {
13907    /// Embed a `u128` value at W80 into a `u128` value at W88.
13908    #[inline]
13909    #[must_use]
13910    pub const fn apply(value: u128) -> u128 {
13911        value
13912    }
13913}
13914
13915impl Embed<W80, W96> {
13916    /// Embed a `u128` value at W80 into a `u128` value at W96.
13917    #[inline]
13918    #[must_use]
13919    pub const fn apply(value: u128) -> u128 {
13920        value
13921    }
13922}
13923
13924impl Embed<W80, W104> {
13925    /// Embed a `u128` value at W80 into a `u128` value at W104.
13926    #[inline]
13927    #[must_use]
13928    pub const fn apply(value: u128) -> u128 {
13929        value
13930    }
13931}
13932
13933impl Embed<W80, W112> {
13934    /// Embed a `u128` value at W80 into a `u128` value at W112.
13935    #[inline]
13936    #[must_use]
13937    pub const fn apply(value: u128) -> u128 {
13938        value
13939    }
13940}
13941
13942impl Embed<W80, W120> {
13943    /// Embed a `u128` value at W80 into a `u128` value at W120.
13944    #[inline]
13945    #[must_use]
13946    pub const fn apply(value: u128) -> u128 {
13947        value
13948    }
13949}
13950
13951impl Embed<W80, W128> {
13952    /// Embed a `u128` value at W80 into a `u128` value at W128.
13953    #[inline]
13954    #[must_use]
13955    pub const fn apply(value: u128) -> u128 {
13956        value
13957    }
13958}
13959
13960impl Embed<W88, W88> {
13961    /// Embed a `u128` value at W88 into a `u128` value at W88.
13962    #[inline]
13963    #[must_use]
13964    pub const fn apply(value: u128) -> u128 {
13965        value
13966    }
13967}
13968
13969impl Embed<W88, W96> {
13970    /// Embed a `u128` value at W88 into a `u128` value at W96.
13971    #[inline]
13972    #[must_use]
13973    pub const fn apply(value: u128) -> u128 {
13974        value
13975    }
13976}
13977
13978impl Embed<W88, W104> {
13979    /// Embed a `u128` value at W88 into a `u128` value at W104.
13980    #[inline]
13981    #[must_use]
13982    pub const fn apply(value: u128) -> u128 {
13983        value
13984    }
13985}
13986
13987impl Embed<W88, W112> {
13988    /// Embed a `u128` value at W88 into a `u128` value at W112.
13989    #[inline]
13990    #[must_use]
13991    pub const fn apply(value: u128) -> u128 {
13992        value
13993    }
13994}
13995
13996impl Embed<W88, W120> {
13997    /// Embed a `u128` value at W88 into a `u128` value at W120.
13998    #[inline]
13999    #[must_use]
14000    pub const fn apply(value: u128) -> u128 {
14001        value
14002    }
14003}
14004
14005impl Embed<W88, W128> {
14006    /// Embed a `u128` value at W88 into a `u128` value at W128.
14007    #[inline]
14008    #[must_use]
14009    pub const fn apply(value: u128) -> u128 {
14010        value
14011    }
14012}
14013
14014impl Embed<W96, W96> {
14015    /// Embed a `u128` value at W96 into a `u128` value at W96.
14016    #[inline]
14017    #[must_use]
14018    pub const fn apply(value: u128) -> u128 {
14019        value
14020    }
14021}
14022
14023impl Embed<W96, W104> {
14024    /// Embed a `u128` value at W96 into a `u128` value at W104.
14025    #[inline]
14026    #[must_use]
14027    pub const fn apply(value: u128) -> u128 {
14028        value
14029    }
14030}
14031
14032impl Embed<W96, W112> {
14033    /// Embed a `u128` value at W96 into a `u128` value at W112.
14034    #[inline]
14035    #[must_use]
14036    pub const fn apply(value: u128) -> u128 {
14037        value
14038    }
14039}
14040
14041impl Embed<W96, W120> {
14042    /// Embed a `u128` value at W96 into a `u128` value at W120.
14043    #[inline]
14044    #[must_use]
14045    pub const fn apply(value: u128) -> u128 {
14046        value
14047    }
14048}
14049
14050impl Embed<W96, W128> {
14051    /// Embed a `u128` value at W96 into a `u128` value at W128.
14052    #[inline]
14053    #[must_use]
14054    pub const fn apply(value: u128) -> u128 {
14055        value
14056    }
14057}
14058
14059impl Embed<W104, W104> {
14060    /// Embed a `u128` value at W104 into a `u128` value at W104.
14061    #[inline]
14062    #[must_use]
14063    pub const fn apply(value: u128) -> u128 {
14064        value
14065    }
14066}
14067
14068impl Embed<W104, W112> {
14069    /// Embed a `u128` value at W104 into a `u128` value at W112.
14070    #[inline]
14071    #[must_use]
14072    pub const fn apply(value: u128) -> u128 {
14073        value
14074    }
14075}
14076
14077impl Embed<W104, W120> {
14078    /// Embed a `u128` value at W104 into a `u128` value at W120.
14079    #[inline]
14080    #[must_use]
14081    pub const fn apply(value: u128) -> u128 {
14082        value
14083    }
14084}
14085
14086impl Embed<W104, W128> {
14087    /// Embed a `u128` value at W104 into a `u128` value at W128.
14088    #[inline]
14089    #[must_use]
14090    pub const fn apply(value: u128) -> u128 {
14091        value
14092    }
14093}
14094
14095impl Embed<W112, W112> {
14096    /// Embed a `u128` value at W112 into a `u128` value at W112.
14097    #[inline]
14098    #[must_use]
14099    pub const fn apply(value: u128) -> u128 {
14100        value
14101    }
14102}
14103
14104impl Embed<W112, W120> {
14105    /// Embed a `u128` value at W112 into a `u128` value at W120.
14106    #[inline]
14107    #[must_use]
14108    pub const fn apply(value: u128) -> u128 {
14109        value
14110    }
14111}
14112
14113impl Embed<W112, W128> {
14114    /// Embed a `u128` value at W112 into a `u128` value at W128.
14115    #[inline]
14116    #[must_use]
14117    pub const fn apply(value: u128) -> u128 {
14118        value
14119    }
14120}
14121
14122impl Embed<W120, W120> {
14123    /// Embed a `u128` value at W120 into a `u128` value at W120.
14124    #[inline]
14125    #[must_use]
14126    pub const fn apply(value: u128) -> u128 {
14127        value
14128    }
14129}
14130
14131impl Embed<W120, W128> {
14132    /// Embed a `u128` value at W120 into a `u128` value at W128.
14133    #[inline]
14134    #[must_use]
14135    pub const fn apply(value: u128) -> u128 {
14136        value
14137    }
14138}
14139
14140impl Embed<W128, W128> {
14141    /// Embed a `u128` value at W128 into a `u128` value at W128.
14142    #[inline]
14143    #[must_use]
14144    pub const fn apply(value: u128) -> u128 {
14145        value
14146    }
14147}
14148
14149/// v0.2.2 Phase C.3: marker structs for Limbs-backed Witt levels.
14150/// Each level binds a const-generic `Limbs<N>` width at the type level.
14151/// W160 marker — 160-bit Witt level, Limbs-backed.
14152#[derive(Debug, Default, Clone, Copy)]
14153pub struct W160;
14154
14155/// W192 marker — 192-bit Witt level, Limbs-backed.
14156#[derive(Debug, Default, Clone, Copy)]
14157pub struct W192;
14158
14159/// W224 marker — 224-bit Witt level, Limbs-backed.
14160#[derive(Debug, Default, Clone, Copy)]
14161pub struct W224;
14162
14163/// W256 marker — 256-bit Witt level, Limbs-backed.
14164#[derive(Debug, Default, Clone, Copy)]
14165pub struct W256;
14166
14167/// W384 marker — 384-bit Witt level, Limbs-backed.
14168#[derive(Debug, Default, Clone, Copy)]
14169pub struct W384;
14170
14171/// W448 marker — 448-bit Witt level, Limbs-backed.
14172#[derive(Debug, Default, Clone, Copy)]
14173pub struct W448;
14174
14175/// W512 marker — 512-bit Witt level, Limbs-backed.
14176#[derive(Debug, Default, Clone, Copy)]
14177pub struct W512;
14178
14179/// W520 marker — 520-bit Witt level, Limbs-backed.
14180#[derive(Debug, Default, Clone, Copy)]
14181pub struct W520;
14182
14183/// W528 marker — 528-bit Witt level, Limbs-backed.
14184#[derive(Debug, Default, Clone, Copy)]
14185pub struct W528;
14186
14187/// W1024 marker — 1024-bit Witt level, Limbs-backed.
14188#[derive(Debug, Default, Clone, Copy)]
14189pub struct W1024;
14190
14191/// W2048 marker — 2048-bit Witt level, Limbs-backed.
14192#[derive(Debug, Default, Clone, Copy)]
14193pub struct W2048;
14194
14195/// W4096 marker — 4096-bit Witt level, Limbs-backed.
14196#[derive(Debug, Default, Clone, Copy)]
14197pub struct W4096;
14198
14199/// W8192 marker — 8192-bit Witt level, Limbs-backed.
14200#[derive(Debug, Default, Clone, Copy)]
14201pub struct W8192;
14202
14203/// W12288 marker — 12288-bit Witt level, Limbs-backed.
14204#[derive(Debug, Default, Clone, Copy)]
14205pub struct W12288;
14206
14207/// W16384 marker — 16384-bit Witt level, Limbs-backed.
14208#[derive(Debug, Default, Clone, Copy)]
14209pub struct W16384;
14210
14211/// W32768 marker — 32768-bit Witt level, Limbs-backed.
14212#[derive(Debug, Default, Clone, Copy)]
14213pub struct W32768;
14214
14215impl RingOp<W160> for Mul<W160> {
14216    type Operand = Limbs<3>;
14217    #[inline]
14218    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14219        a.wrapping_mul(b).mask_high_bits(160)
14220    }
14221}
14222
14223impl RingOp<W160> for Add<W160> {
14224    type Operand = Limbs<3>;
14225    #[inline]
14226    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14227        a.wrapping_add(b).mask_high_bits(160)
14228    }
14229}
14230
14231impl RingOp<W160> for Sub<W160> {
14232    type Operand = Limbs<3>;
14233    #[inline]
14234    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14235        a.wrapping_sub(b).mask_high_bits(160)
14236    }
14237}
14238
14239impl RingOp<W160> for Xor<W160> {
14240    type Operand = Limbs<3>;
14241    #[inline]
14242    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14243        a.xor(b).mask_high_bits(160)
14244    }
14245}
14246
14247impl RingOp<W160> for And<W160> {
14248    type Operand = Limbs<3>;
14249    #[inline]
14250    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14251        a.and(b).mask_high_bits(160)
14252    }
14253}
14254
14255impl RingOp<W160> for Or<W160> {
14256    type Operand = Limbs<3>;
14257    #[inline]
14258    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14259        a.or(b).mask_high_bits(160)
14260    }
14261}
14262
14263impl UnaryRingOp<W160> for Neg<W160> {
14264    type Operand = Limbs<3>;
14265    #[inline]
14266    fn apply(a: Limbs<3>) -> Limbs<3> {
14267        (Limbs::<3>::zero().wrapping_sub(a)).mask_high_bits(160)
14268    }
14269}
14270
14271impl UnaryRingOp<W160> for BNot<W160> {
14272    type Operand = Limbs<3>;
14273    #[inline]
14274    fn apply(a: Limbs<3>) -> Limbs<3> {
14275        (a.not()).mask_high_bits(160)
14276    }
14277}
14278
14279impl UnaryRingOp<W160> for Succ<W160> {
14280    type Operand = Limbs<3>;
14281    #[inline]
14282    fn apply(a: Limbs<3>) -> Limbs<3> {
14283        (a.wrapping_add(Limbs::<3>::from_words([1u64, 0u64, 0u64]))).mask_high_bits(160)
14284    }
14285}
14286
14287impl RingOp<W192> for Mul<W192> {
14288    type Operand = Limbs<3>;
14289    #[inline]
14290    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14291        a.wrapping_mul(b)
14292    }
14293}
14294
14295impl RingOp<W192> for Add<W192> {
14296    type Operand = Limbs<3>;
14297    #[inline]
14298    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14299        a.wrapping_add(b)
14300    }
14301}
14302
14303impl RingOp<W192> for Sub<W192> {
14304    type Operand = Limbs<3>;
14305    #[inline]
14306    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14307        a.wrapping_sub(b)
14308    }
14309}
14310
14311impl RingOp<W192> for Xor<W192> {
14312    type Operand = Limbs<3>;
14313    #[inline]
14314    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14315        a.xor(b)
14316    }
14317}
14318
14319impl RingOp<W192> for And<W192> {
14320    type Operand = Limbs<3>;
14321    #[inline]
14322    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14323        a.and(b)
14324    }
14325}
14326
14327impl RingOp<W192> for Or<W192> {
14328    type Operand = Limbs<3>;
14329    #[inline]
14330    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14331        a.or(b)
14332    }
14333}
14334
14335impl UnaryRingOp<W192> for Neg<W192> {
14336    type Operand = Limbs<3>;
14337    #[inline]
14338    fn apply(a: Limbs<3>) -> Limbs<3> {
14339        Limbs::<3>::zero().wrapping_sub(a)
14340    }
14341}
14342
14343impl UnaryRingOp<W192> for BNot<W192> {
14344    type Operand = Limbs<3>;
14345    #[inline]
14346    fn apply(a: Limbs<3>) -> Limbs<3> {
14347        a.not()
14348    }
14349}
14350
14351impl UnaryRingOp<W192> for Succ<W192> {
14352    type Operand = Limbs<3>;
14353    #[inline]
14354    fn apply(a: Limbs<3>) -> Limbs<3> {
14355        a.wrapping_add(Limbs::<3>::from_words([1u64, 0u64, 0u64]))
14356    }
14357}
14358
14359impl RingOp<W224> for Mul<W224> {
14360    type Operand = Limbs<4>;
14361    #[inline]
14362    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14363        a.wrapping_mul(b).mask_high_bits(224)
14364    }
14365}
14366
14367impl RingOp<W224> for Add<W224> {
14368    type Operand = Limbs<4>;
14369    #[inline]
14370    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14371        a.wrapping_add(b).mask_high_bits(224)
14372    }
14373}
14374
14375impl RingOp<W224> for Sub<W224> {
14376    type Operand = Limbs<4>;
14377    #[inline]
14378    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14379        a.wrapping_sub(b).mask_high_bits(224)
14380    }
14381}
14382
14383impl RingOp<W224> for Xor<W224> {
14384    type Operand = Limbs<4>;
14385    #[inline]
14386    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14387        a.xor(b).mask_high_bits(224)
14388    }
14389}
14390
14391impl RingOp<W224> for And<W224> {
14392    type Operand = Limbs<4>;
14393    #[inline]
14394    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14395        a.and(b).mask_high_bits(224)
14396    }
14397}
14398
14399impl RingOp<W224> for Or<W224> {
14400    type Operand = Limbs<4>;
14401    #[inline]
14402    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14403        a.or(b).mask_high_bits(224)
14404    }
14405}
14406
14407impl UnaryRingOp<W224> for Neg<W224> {
14408    type Operand = Limbs<4>;
14409    #[inline]
14410    fn apply(a: Limbs<4>) -> Limbs<4> {
14411        (Limbs::<4>::zero().wrapping_sub(a)).mask_high_bits(224)
14412    }
14413}
14414
14415impl UnaryRingOp<W224> for BNot<W224> {
14416    type Operand = Limbs<4>;
14417    #[inline]
14418    fn apply(a: Limbs<4>) -> Limbs<4> {
14419        (a.not()).mask_high_bits(224)
14420    }
14421}
14422
14423impl UnaryRingOp<W224> for Succ<W224> {
14424    type Operand = Limbs<4>;
14425    #[inline]
14426    fn apply(a: Limbs<4>) -> Limbs<4> {
14427        (a.wrapping_add(Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64]))).mask_high_bits(224)
14428    }
14429}
14430
14431impl RingOp<W256> for Mul<W256> {
14432    type Operand = Limbs<4>;
14433    #[inline]
14434    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14435        a.wrapping_mul(b)
14436    }
14437}
14438
14439impl RingOp<W256> for Add<W256> {
14440    type Operand = Limbs<4>;
14441    #[inline]
14442    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14443        a.wrapping_add(b)
14444    }
14445}
14446
14447impl RingOp<W256> for Sub<W256> {
14448    type Operand = Limbs<4>;
14449    #[inline]
14450    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14451        a.wrapping_sub(b)
14452    }
14453}
14454
14455impl RingOp<W256> for Xor<W256> {
14456    type Operand = Limbs<4>;
14457    #[inline]
14458    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14459        a.xor(b)
14460    }
14461}
14462
14463impl RingOp<W256> for And<W256> {
14464    type Operand = Limbs<4>;
14465    #[inline]
14466    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14467        a.and(b)
14468    }
14469}
14470
14471impl RingOp<W256> for Or<W256> {
14472    type Operand = Limbs<4>;
14473    #[inline]
14474    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14475        a.or(b)
14476    }
14477}
14478
14479impl UnaryRingOp<W256> for Neg<W256> {
14480    type Operand = Limbs<4>;
14481    #[inline]
14482    fn apply(a: Limbs<4>) -> Limbs<4> {
14483        Limbs::<4>::zero().wrapping_sub(a)
14484    }
14485}
14486
14487impl UnaryRingOp<W256> for BNot<W256> {
14488    type Operand = Limbs<4>;
14489    #[inline]
14490    fn apply(a: Limbs<4>) -> Limbs<4> {
14491        a.not()
14492    }
14493}
14494
14495impl UnaryRingOp<W256> for Succ<W256> {
14496    type Operand = Limbs<4>;
14497    #[inline]
14498    fn apply(a: Limbs<4>) -> Limbs<4> {
14499        a.wrapping_add(Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64]))
14500    }
14501}
14502
14503impl RingOp<W384> for Mul<W384> {
14504    type Operand = Limbs<6>;
14505    #[inline]
14506    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14507        a.wrapping_mul(b)
14508    }
14509}
14510
14511impl RingOp<W384> for Add<W384> {
14512    type Operand = Limbs<6>;
14513    #[inline]
14514    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14515        a.wrapping_add(b)
14516    }
14517}
14518
14519impl RingOp<W384> for Sub<W384> {
14520    type Operand = Limbs<6>;
14521    #[inline]
14522    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14523        a.wrapping_sub(b)
14524    }
14525}
14526
14527impl RingOp<W384> for Xor<W384> {
14528    type Operand = Limbs<6>;
14529    #[inline]
14530    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14531        a.xor(b)
14532    }
14533}
14534
14535impl RingOp<W384> for And<W384> {
14536    type Operand = Limbs<6>;
14537    #[inline]
14538    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14539        a.and(b)
14540    }
14541}
14542
14543impl RingOp<W384> for Or<W384> {
14544    type Operand = Limbs<6>;
14545    #[inline]
14546    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14547        a.or(b)
14548    }
14549}
14550
14551impl UnaryRingOp<W384> for Neg<W384> {
14552    type Operand = Limbs<6>;
14553    #[inline]
14554    fn apply(a: Limbs<6>) -> Limbs<6> {
14555        Limbs::<6>::zero().wrapping_sub(a)
14556    }
14557}
14558
14559impl UnaryRingOp<W384> for BNot<W384> {
14560    type Operand = Limbs<6>;
14561    #[inline]
14562    fn apply(a: Limbs<6>) -> Limbs<6> {
14563        a.not()
14564    }
14565}
14566
14567impl UnaryRingOp<W384> for Succ<W384> {
14568    type Operand = Limbs<6>;
14569    #[inline]
14570    fn apply(a: Limbs<6>) -> Limbs<6> {
14571        a.wrapping_add(Limbs::<6>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64]))
14572    }
14573}
14574
14575impl RingOp<W448> for Mul<W448> {
14576    type Operand = Limbs<7>;
14577    #[inline]
14578    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14579        a.wrapping_mul(b)
14580    }
14581}
14582
14583impl RingOp<W448> for Add<W448> {
14584    type Operand = Limbs<7>;
14585    #[inline]
14586    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14587        a.wrapping_add(b)
14588    }
14589}
14590
14591impl RingOp<W448> for Sub<W448> {
14592    type Operand = Limbs<7>;
14593    #[inline]
14594    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14595        a.wrapping_sub(b)
14596    }
14597}
14598
14599impl RingOp<W448> for Xor<W448> {
14600    type Operand = Limbs<7>;
14601    #[inline]
14602    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14603        a.xor(b)
14604    }
14605}
14606
14607impl RingOp<W448> for And<W448> {
14608    type Operand = Limbs<7>;
14609    #[inline]
14610    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14611        a.and(b)
14612    }
14613}
14614
14615impl RingOp<W448> for Or<W448> {
14616    type Operand = Limbs<7>;
14617    #[inline]
14618    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14619        a.or(b)
14620    }
14621}
14622
14623impl UnaryRingOp<W448> for Neg<W448> {
14624    type Operand = Limbs<7>;
14625    #[inline]
14626    fn apply(a: Limbs<7>) -> Limbs<7> {
14627        Limbs::<7>::zero().wrapping_sub(a)
14628    }
14629}
14630
14631impl UnaryRingOp<W448> for BNot<W448> {
14632    type Operand = Limbs<7>;
14633    #[inline]
14634    fn apply(a: Limbs<7>) -> Limbs<7> {
14635        a.not()
14636    }
14637}
14638
14639impl UnaryRingOp<W448> for Succ<W448> {
14640    type Operand = Limbs<7>;
14641    #[inline]
14642    fn apply(a: Limbs<7>) -> Limbs<7> {
14643        a.wrapping_add(Limbs::<7>::from_words([
14644            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14645        ]))
14646    }
14647}
14648
14649impl RingOp<W512> for Mul<W512> {
14650    type Operand = Limbs<8>;
14651    #[inline]
14652    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14653        a.wrapping_mul(b)
14654    }
14655}
14656
14657impl RingOp<W512> for Add<W512> {
14658    type Operand = Limbs<8>;
14659    #[inline]
14660    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14661        a.wrapping_add(b)
14662    }
14663}
14664
14665impl RingOp<W512> for Sub<W512> {
14666    type Operand = Limbs<8>;
14667    #[inline]
14668    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14669        a.wrapping_sub(b)
14670    }
14671}
14672
14673impl RingOp<W512> for Xor<W512> {
14674    type Operand = Limbs<8>;
14675    #[inline]
14676    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14677        a.xor(b)
14678    }
14679}
14680
14681impl RingOp<W512> for And<W512> {
14682    type Operand = Limbs<8>;
14683    #[inline]
14684    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14685        a.and(b)
14686    }
14687}
14688
14689impl RingOp<W512> for Or<W512> {
14690    type Operand = Limbs<8>;
14691    #[inline]
14692    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14693        a.or(b)
14694    }
14695}
14696
14697impl UnaryRingOp<W512> for Neg<W512> {
14698    type Operand = Limbs<8>;
14699    #[inline]
14700    fn apply(a: Limbs<8>) -> Limbs<8> {
14701        Limbs::<8>::zero().wrapping_sub(a)
14702    }
14703}
14704
14705impl UnaryRingOp<W512> for BNot<W512> {
14706    type Operand = Limbs<8>;
14707    #[inline]
14708    fn apply(a: Limbs<8>) -> Limbs<8> {
14709        a.not()
14710    }
14711}
14712
14713impl UnaryRingOp<W512> for Succ<W512> {
14714    type Operand = Limbs<8>;
14715    #[inline]
14716    fn apply(a: Limbs<8>) -> Limbs<8> {
14717        a.wrapping_add(Limbs::<8>::from_words([
14718            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14719        ]))
14720    }
14721}
14722
14723impl RingOp<W520> for Mul<W520> {
14724    type Operand = Limbs<9>;
14725    #[inline]
14726    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14727        a.wrapping_mul(b).mask_high_bits(520)
14728    }
14729}
14730
14731impl RingOp<W520> for Add<W520> {
14732    type Operand = Limbs<9>;
14733    #[inline]
14734    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14735        a.wrapping_add(b).mask_high_bits(520)
14736    }
14737}
14738
14739impl RingOp<W520> for Sub<W520> {
14740    type Operand = Limbs<9>;
14741    #[inline]
14742    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14743        a.wrapping_sub(b).mask_high_bits(520)
14744    }
14745}
14746
14747impl RingOp<W520> for Xor<W520> {
14748    type Operand = Limbs<9>;
14749    #[inline]
14750    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14751        a.xor(b).mask_high_bits(520)
14752    }
14753}
14754
14755impl RingOp<W520> for And<W520> {
14756    type Operand = Limbs<9>;
14757    #[inline]
14758    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14759        a.and(b).mask_high_bits(520)
14760    }
14761}
14762
14763impl RingOp<W520> for Or<W520> {
14764    type Operand = Limbs<9>;
14765    #[inline]
14766    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14767        a.or(b).mask_high_bits(520)
14768    }
14769}
14770
14771impl UnaryRingOp<W520> for Neg<W520> {
14772    type Operand = Limbs<9>;
14773    #[inline]
14774    fn apply(a: Limbs<9>) -> Limbs<9> {
14775        (Limbs::<9>::zero().wrapping_sub(a)).mask_high_bits(520)
14776    }
14777}
14778
14779impl UnaryRingOp<W520> for BNot<W520> {
14780    type Operand = Limbs<9>;
14781    #[inline]
14782    fn apply(a: Limbs<9>) -> Limbs<9> {
14783        (a.not()).mask_high_bits(520)
14784    }
14785}
14786
14787impl UnaryRingOp<W520> for Succ<W520> {
14788    type Operand = Limbs<9>;
14789    #[inline]
14790    fn apply(a: Limbs<9>) -> Limbs<9> {
14791        (a.wrapping_add(Limbs::<9>::from_words([
14792            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14793        ])))
14794        .mask_high_bits(520)
14795    }
14796}
14797
14798impl RingOp<W528> for Mul<W528> {
14799    type Operand = Limbs<9>;
14800    #[inline]
14801    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14802        a.wrapping_mul(b).mask_high_bits(528)
14803    }
14804}
14805
14806impl RingOp<W528> for Add<W528> {
14807    type Operand = Limbs<9>;
14808    #[inline]
14809    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14810        a.wrapping_add(b).mask_high_bits(528)
14811    }
14812}
14813
14814impl RingOp<W528> for Sub<W528> {
14815    type Operand = Limbs<9>;
14816    #[inline]
14817    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14818        a.wrapping_sub(b).mask_high_bits(528)
14819    }
14820}
14821
14822impl RingOp<W528> for Xor<W528> {
14823    type Operand = Limbs<9>;
14824    #[inline]
14825    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14826        a.xor(b).mask_high_bits(528)
14827    }
14828}
14829
14830impl RingOp<W528> for And<W528> {
14831    type Operand = Limbs<9>;
14832    #[inline]
14833    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14834        a.and(b).mask_high_bits(528)
14835    }
14836}
14837
14838impl RingOp<W528> for Or<W528> {
14839    type Operand = Limbs<9>;
14840    #[inline]
14841    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14842        a.or(b).mask_high_bits(528)
14843    }
14844}
14845
14846impl UnaryRingOp<W528> for Neg<W528> {
14847    type Operand = Limbs<9>;
14848    #[inline]
14849    fn apply(a: Limbs<9>) -> Limbs<9> {
14850        (Limbs::<9>::zero().wrapping_sub(a)).mask_high_bits(528)
14851    }
14852}
14853
14854impl UnaryRingOp<W528> for BNot<W528> {
14855    type Operand = Limbs<9>;
14856    #[inline]
14857    fn apply(a: Limbs<9>) -> Limbs<9> {
14858        (a.not()).mask_high_bits(528)
14859    }
14860}
14861
14862impl UnaryRingOp<W528> for Succ<W528> {
14863    type Operand = Limbs<9>;
14864    #[inline]
14865    fn apply(a: Limbs<9>) -> Limbs<9> {
14866        (a.wrapping_add(Limbs::<9>::from_words([
14867            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14868        ])))
14869        .mask_high_bits(528)
14870    }
14871}
14872
14873impl RingOp<W1024> for Mul<W1024> {
14874    type Operand = Limbs<16>;
14875    #[inline]
14876    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14877        a.wrapping_mul(b)
14878    }
14879}
14880
14881impl RingOp<W1024> for Add<W1024> {
14882    type Operand = Limbs<16>;
14883    #[inline]
14884    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14885        a.wrapping_add(b)
14886    }
14887}
14888
14889impl RingOp<W1024> for Sub<W1024> {
14890    type Operand = Limbs<16>;
14891    #[inline]
14892    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14893        a.wrapping_sub(b)
14894    }
14895}
14896
14897impl RingOp<W1024> for Xor<W1024> {
14898    type Operand = Limbs<16>;
14899    #[inline]
14900    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14901        a.xor(b)
14902    }
14903}
14904
14905impl RingOp<W1024> for And<W1024> {
14906    type Operand = Limbs<16>;
14907    #[inline]
14908    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14909        a.and(b)
14910    }
14911}
14912
14913impl RingOp<W1024> for Or<W1024> {
14914    type Operand = Limbs<16>;
14915    #[inline]
14916    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14917        a.or(b)
14918    }
14919}
14920
14921impl UnaryRingOp<W1024> for Neg<W1024> {
14922    type Operand = Limbs<16>;
14923    #[inline]
14924    fn apply(a: Limbs<16>) -> Limbs<16> {
14925        Limbs::<16>::zero().wrapping_sub(a)
14926    }
14927}
14928
14929impl UnaryRingOp<W1024> for BNot<W1024> {
14930    type Operand = Limbs<16>;
14931    #[inline]
14932    fn apply(a: Limbs<16>) -> Limbs<16> {
14933        a.not()
14934    }
14935}
14936
14937impl UnaryRingOp<W1024> for Succ<W1024> {
14938    type Operand = Limbs<16>;
14939    #[inline]
14940    fn apply(a: Limbs<16>) -> Limbs<16> {
14941        a.wrapping_add(Limbs::<16>::from_words([
14942            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14943            0u64, 0u64,
14944        ]))
14945    }
14946}
14947
14948impl RingOp<W2048> for Mul<W2048> {
14949    type Operand = Limbs<32>;
14950    #[inline]
14951    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14952        a.wrapping_mul(b)
14953    }
14954}
14955
14956impl RingOp<W2048> for Add<W2048> {
14957    type Operand = Limbs<32>;
14958    #[inline]
14959    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14960        a.wrapping_add(b)
14961    }
14962}
14963
14964impl RingOp<W2048> for Sub<W2048> {
14965    type Operand = Limbs<32>;
14966    #[inline]
14967    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14968        a.wrapping_sub(b)
14969    }
14970}
14971
14972impl RingOp<W2048> for Xor<W2048> {
14973    type Operand = Limbs<32>;
14974    #[inline]
14975    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14976        a.xor(b)
14977    }
14978}
14979
14980impl RingOp<W2048> for And<W2048> {
14981    type Operand = Limbs<32>;
14982    #[inline]
14983    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14984        a.and(b)
14985    }
14986}
14987
14988impl RingOp<W2048> for Or<W2048> {
14989    type Operand = Limbs<32>;
14990    #[inline]
14991    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14992        a.or(b)
14993    }
14994}
14995
14996impl UnaryRingOp<W2048> for Neg<W2048> {
14997    type Operand = Limbs<32>;
14998    #[inline]
14999    fn apply(a: Limbs<32>) -> Limbs<32> {
15000        Limbs::<32>::zero().wrapping_sub(a)
15001    }
15002}
15003
15004impl UnaryRingOp<W2048> for BNot<W2048> {
15005    type Operand = Limbs<32>;
15006    #[inline]
15007    fn apply(a: Limbs<32>) -> Limbs<32> {
15008        a.not()
15009    }
15010}
15011
15012impl UnaryRingOp<W2048> for Succ<W2048> {
15013    type Operand = Limbs<32>;
15014    #[inline]
15015    fn apply(a: Limbs<32>) -> Limbs<32> {
15016        a.wrapping_add(Limbs::<32>::from_words([
15017            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15018            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15019            0u64, 0u64, 0u64, 0u64,
15020        ]))
15021    }
15022}
15023
15024impl RingOp<W4096> for Mul<W4096> {
15025    type Operand = Limbs<64>;
15026    #[inline]
15027    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15028        a.wrapping_mul(b)
15029    }
15030}
15031
15032impl RingOp<W4096> for Add<W4096> {
15033    type Operand = Limbs<64>;
15034    #[inline]
15035    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15036        a.wrapping_add(b)
15037    }
15038}
15039
15040impl RingOp<W4096> for Sub<W4096> {
15041    type Operand = Limbs<64>;
15042    #[inline]
15043    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15044        a.wrapping_sub(b)
15045    }
15046}
15047
15048impl RingOp<W4096> for Xor<W4096> {
15049    type Operand = Limbs<64>;
15050    #[inline]
15051    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15052        a.xor(b)
15053    }
15054}
15055
15056impl RingOp<W4096> for And<W4096> {
15057    type Operand = Limbs<64>;
15058    #[inline]
15059    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15060        a.and(b)
15061    }
15062}
15063
15064impl RingOp<W4096> for Or<W4096> {
15065    type Operand = Limbs<64>;
15066    #[inline]
15067    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15068        a.or(b)
15069    }
15070}
15071
15072impl UnaryRingOp<W4096> for Neg<W4096> {
15073    type Operand = Limbs<64>;
15074    #[inline]
15075    fn apply(a: Limbs<64>) -> Limbs<64> {
15076        Limbs::<64>::zero().wrapping_sub(a)
15077    }
15078}
15079
15080impl UnaryRingOp<W4096> for BNot<W4096> {
15081    type Operand = Limbs<64>;
15082    #[inline]
15083    fn apply(a: Limbs<64>) -> Limbs<64> {
15084        a.not()
15085    }
15086}
15087
15088impl UnaryRingOp<W4096> for Succ<W4096> {
15089    type Operand = Limbs<64>;
15090    #[inline]
15091    fn apply(a: Limbs<64>) -> Limbs<64> {
15092        a.wrapping_add(Limbs::<64>::from_words([
15093            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15094            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15095            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15096            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15097            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15098        ]))
15099    }
15100}
15101
15102impl RingOp<W8192> for Mul<W8192> {
15103    type Operand = Limbs<128>;
15104    #[inline]
15105    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15106        a.wrapping_mul(b)
15107    }
15108}
15109
15110impl RingOp<W8192> for Add<W8192> {
15111    type Operand = Limbs<128>;
15112    #[inline]
15113    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15114        a.wrapping_add(b)
15115    }
15116}
15117
15118impl RingOp<W8192> for Sub<W8192> {
15119    type Operand = Limbs<128>;
15120    #[inline]
15121    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15122        a.wrapping_sub(b)
15123    }
15124}
15125
15126impl RingOp<W8192> for Xor<W8192> {
15127    type Operand = Limbs<128>;
15128    #[inline]
15129    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15130        a.xor(b)
15131    }
15132}
15133
15134impl RingOp<W8192> for And<W8192> {
15135    type Operand = Limbs<128>;
15136    #[inline]
15137    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15138        a.and(b)
15139    }
15140}
15141
15142impl RingOp<W8192> for Or<W8192> {
15143    type Operand = Limbs<128>;
15144    #[inline]
15145    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15146        a.or(b)
15147    }
15148}
15149
15150impl UnaryRingOp<W8192> for Neg<W8192> {
15151    type Operand = Limbs<128>;
15152    #[inline]
15153    fn apply(a: Limbs<128>) -> Limbs<128> {
15154        Limbs::<128>::zero().wrapping_sub(a)
15155    }
15156}
15157
15158impl UnaryRingOp<W8192> for BNot<W8192> {
15159    type Operand = Limbs<128>;
15160    #[inline]
15161    fn apply(a: Limbs<128>) -> Limbs<128> {
15162        a.not()
15163    }
15164}
15165
15166impl UnaryRingOp<W8192> for Succ<W8192> {
15167    type Operand = Limbs<128>;
15168    #[inline]
15169    fn apply(a: Limbs<128>) -> Limbs<128> {
15170        a.wrapping_add(Limbs::<128>::from_words([
15171            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15172            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15173            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15174            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15175            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15176            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15177            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15178            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15179            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15180            0u64, 0u64,
15181        ]))
15182    }
15183}
15184
15185impl RingOp<W12288> for Mul<W12288> {
15186    type Operand = Limbs<192>;
15187    #[inline]
15188    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15189        a.wrapping_mul(b)
15190    }
15191}
15192
15193impl RingOp<W12288> for Add<W12288> {
15194    type Operand = Limbs<192>;
15195    #[inline]
15196    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15197        a.wrapping_add(b)
15198    }
15199}
15200
15201impl RingOp<W12288> for Sub<W12288> {
15202    type Operand = Limbs<192>;
15203    #[inline]
15204    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15205        a.wrapping_sub(b)
15206    }
15207}
15208
15209impl RingOp<W12288> for Xor<W12288> {
15210    type Operand = Limbs<192>;
15211    #[inline]
15212    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15213        a.xor(b)
15214    }
15215}
15216
15217impl RingOp<W12288> for And<W12288> {
15218    type Operand = Limbs<192>;
15219    #[inline]
15220    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15221        a.and(b)
15222    }
15223}
15224
15225impl RingOp<W12288> for Or<W12288> {
15226    type Operand = Limbs<192>;
15227    #[inline]
15228    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15229        a.or(b)
15230    }
15231}
15232
15233impl UnaryRingOp<W12288> for Neg<W12288> {
15234    type Operand = Limbs<192>;
15235    #[inline]
15236    fn apply(a: Limbs<192>) -> Limbs<192> {
15237        Limbs::<192>::zero().wrapping_sub(a)
15238    }
15239}
15240
15241impl UnaryRingOp<W12288> for BNot<W12288> {
15242    type Operand = Limbs<192>;
15243    #[inline]
15244    fn apply(a: Limbs<192>) -> Limbs<192> {
15245        a.not()
15246    }
15247}
15248
15249impl UnaryRingOp<W12288> for Succ<W12288> {
15250    type Operand = Limbs<192>;
15251    #[inline]
15252    fn apply(a: Limbs<192>) -> Limbs<192> {
15253        a.wrapping_add(Limbs::<192>::from_words([
15254            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15255            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15256            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15257            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15258            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15259            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15260            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15261            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15262            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15263            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15264            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15265            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15266            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15267            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15268        ]))
15269    }
15270}
15271
15272impl RingOp<W16384> for Mul<W16384> {
15273    type Operand = Limbs<256>;
15274    #[inline]
15275    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15276        a.wrapping_mul(b)
15277    }
15278}
15279
15280impl RingOp<W16384> for Add<W16384> {
15281    type Operand = Limbs<256>;
15282    #[inline]
15283    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15284        a.wrapping_add(b)
15285    }
15286}
15287
15288impl RingOp<W16384> for Sub<W16384> {
15289    type Operand = Limbs<256>;
15290    #[inline]
15291    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15292        a.wrapping_sub(b)
15293    }
15294}
15295
15296impl RingOp<W16384> for Xor<W16384> {
15297    type Operand = Limbs<256>;
15298    #[inline]
15299    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15300        a.xor(b)
15301    }
15302}
15303
15304impl RingOp<W16384> for And<W16384> {
15305    type Operand = Limbs<256>;
15306    #[inline]
15307    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15308        a.and(b)
15309    }
15310}
15311
15312impl RingOp<W16384> for Or<W16384> {
15313    type Operand = Limbs<256>;
15314    #[inline]
15315    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15316        a.or(b)
15317    }
15318}
15319
15320impl UnaryRingOp<W16384> for Neg<W16384> {
15321    type Operand = Limbs<256>;
15322    #[inline]
15323    fn apply(a: Limbs<256>) -> Limbs<256> {
15324        Limbs::<256>::zero().wrapping_sub(a)
15325    }
15326}
15327
15328impl UnaryRingOp<W16384> for BNot<W16384> {
15329    type Operand = Limbs<256>;
15330    #[inline]
15331    fn apply(a: Limbs<256>) -> Limbs<256> {
15332        a.not()
15333    }
15334}
15335
15336impl UnaryRingOp<W16384> for Succ<W16384> {
15337    type Operand = Limbs<256>;
15338    #[inline]
15339    fn apply(a: Limbs<256>) -> Limbs<256> {
15340        a.wrapping_add(Limbs::<256>::from_words([
15341            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15342            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15343            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15344            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15345            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15346            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15347            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15348            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15349            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15350            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15351            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15352            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15353            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15354            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15355            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15356            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15357            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15358            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15359            0u64, 0u64, 0u64, 0u64,
15360        ]))
15361    }
15362}
15363
15364impl RingOp<W32768> for Mul<W32768> {
15365    type Operand = Limbs<512>;
15366    #[inline]
15367    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15368        a.wrapping_mul(b)
15369    }
15370}
15371
15372impl RingOp<W32768> for Add<W32768> {
15373    type Operand = Limbs<512>;
15374    #[inline]
15375    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15376        a.wrapping_add(b)
15377    }
15378}
15379
15380impl RingOp<W32768> for Sub<W32768> {
15381    type Operand = Limbs<512>;
15382    #[inline]
15383    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15384        a.wrapping_sub(b)
15385    }
15386}
15387
15388impl RingOp<W32768> for Xor<W32768> {
15389    type Operand = Limbs<512>;
15390    #[inline]
15391    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15392        a.xor(b)
15393    }
15394}
15395
15396impl RingOp<W32768> for And<W32768> {
15397    type Operand = Limbs<512>;
15398    #[inline]
15399    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15400        a.and(b)
15401    }
15402}
15403
15404impl RingOp<W32768> for Or<W32768> {
15405    type Operand = Limbs<512>;
15406    #[inline]
15407    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15408        a.or(b)
15409    }
15410}
15411
15412impl UnaryRingOp<W32768> for Neg<W32768> {
15413    type Operand = Limbs<512>;
15414    #[inline]
15415    fn apply(a: Limbs<512>) -> Limbs<512> {
15416        Limbs::<512>::zero().wrapping_sub(a)
15417    }
15418}
15419
15420impl UnaryRingOp<W32768> for BNot<W32768> {
15421    type Operand = Limbs<512>;
15422    #[inline]
15423    fn apply(a: Limbs<512>) -> Limbs<512> {
15424        a.not()
15425    }
15426}
15427
15428impl UnaryRingOp<W32768> for Succ<W32768> {
15429    type Operand = Limbs<512>;
15430    #[inline]
15431    fn apply(a: Limbs<512>) -> Limbs<512> {
15432        a.wrapping_add(Limbs::<512>::from_words([
15433            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15434            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15435            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15436            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15437            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15438            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15439            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15440            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15441            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15442            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15443            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15444            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15445            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15446            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15447            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15448            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15449            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15450            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15451            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15452            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15453            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15454            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15455            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15456            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15457            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15458            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15459            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15460            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15461            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15462            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15463            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15464            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15465            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15466            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15467            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15468            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15469            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15470        ]))
15471    }
15472}
15473
15474/// Phase L.2 (target §4.5): `const_ring_eval_w{n}` helpers for Limbs-backed
15475/// Witt levels. Each helper runs a `PrimitiveOp` over two `Limbs<N>` operands
15476/// and applies the level's bit-width mask to the result.
15477/// These helpers are always const-fn; whether `rustc` can complete a specific
15478/// compile-time evaluation within the developer's budget is a function of the
15479/// invocation (see target §4.5 Q2 practicality table).
15480#[inline]
15481#[must_use]
15482pub const fn const_ring_eval_w160(op: PrimitiveOp, a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
15483    let raw = match op {
15484        PrimitiveOp::Add => a.wrapping_add(b),
15485        PrimitiveOp::Sub => a.wrapping_sub(b),
15486        PrimitiveOp::Mul => a.wrapping_mul(b),
15487        PrimitiveOp::And => a.and(b),
15488        PrimitiveOp::Or => a.or(b),
15489        PrimitiveOp::Xor => a.xor(b),
15490        PrimitiveOp::Neg => Limbs::<3>::zero().wrapping_sub(a),
15491        PrimitiveOp::Bnot => a.not(),
15492        PrimitiveOp::Succ => a.wrapping_add(limbs_one_3()),
15493        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_3()),
15494        PrimitiveOp::Le => {
15495            if limbs_le_3(a, b) {
15496                limbs_one_3()
15497            } else {
15498                Limbs::<3>::zero()
15499            }
15500        }
15501        PrimitiveOp::Lt => {
15502            if limbs_lt_3(a, b) {
15503                limbs_one_3()
15504            } else {
15505                Limbs::<3>::zero()
15506            }
15507        }
15508        PrimitiveOp::Ge => {
15509            if limbs_le_3(b, a) {
15510                limbs_one_3()
15511            } else {
15512                Limbs::<3>::zero()
15513            }
15514        }
15515        PrimitiveOp::Gt => {
15516            if limbs_lt_3(b, a) {
15517                limbs_one_3()
15518            } else {
15519                Limbs::<3>::zero()
15520            }
15521        }
15522        PrimitiveOp::Concat => Limbs::<3>::zero(),
15523        PrimitiveOp::Div => {
15524            if limbs_is_zero_3(b) {
15525                Limbs::<3>::zero()
15526            } else {
15527                limbs_div_3(a, b)
15528            }
15529        }
15530        PrimitiveOp::Mod => {
15531            if limbs_is_zero_3(b) {
15532                Limbs::<3>::zero()
15533            } else {
15534                limbs_mod_3(a, b)
15535            }
15536        }
15537        PrimitiveOp::Pow => limbs_pow_3(a, b),
15538    };
15539    raw.mask_high_bits(160)
15540}
15541
15542#[inline]
15543#[must_use]
15544pub const fn const_ring_eval_w192(op: PrimitiveOp, a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
15545    match op {
15546        PrimitiveOp::Add => a.wrapping_add(b),
15547        PrimitiveOp::Sub => a.wrapping_sub(b),
15548        PrimitiveOp::Mul => a.wrapping_mul(b),
15549        PrimitiveOp::And => a.and(b),
15550        PrimitiveOp::Or => a.or(b),
15551        PrimitiveOp::Xor => a.xor(b),
15552        PrimitiveOp::Neg => Limbs::<3>::zero().wrapping_sub(a),
15553        PrimitiveOp::Bnot => a.not(),
15554        PrimitiveOp::Succ => a.wrapping_add(limbs_one_3()),
15555        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_3()),
15556        PrimitiveOp::Le => {
15557            if limbs_le_3(a, b) {
15558                limbs_one_3()
15559            } else {
15560                Limbs::<3>::zero()
15561            }
15562        }
15563        PrimitiveOp::Lt => {
15564            if limbs_lt_3(a, b) {
15565                limbs_one_3()
15566            } else {
15567                Limbs::<3>::zero()
15568            }
15569        }
15570        PrimitiveOp::Ge => {
15571            if limbs_le_3(b, a) {
15572                limbs_one_3()
15573            } else {
15574                Limbs::<3>::zero()
15575            }
15576        }
15577        PrimitiveOp::Gt => {
15578            if limbs_lt_3(b, a) {
15579                limbs_one_3()
15580            } else {
15581                Limbs::<3>::zero()
15582            }
15583        }
15584        PrimitiveOp::Concat => Limbs::<3>::zero(),
15585        PrimitiveOp::Div => {
15586            if limbs_is_zero_3(b) {
15587                Limbs::<3>::zero()
15588            } else {
15589                limbs_div_3(a, b)
15590            }
15591        }
15592        PrimitiveOp::Mod => {
15593            if limbs_is_zero_3(b) {
15594                Limbs::<3>::zero()
15595            } else {
15596                limbs_mod_3(a, b)
15597            }
15598        }
15599        PrimitiveOp::Pow => limbs_pow_3(a, b),
15600    }
15601}
15602
15603#[inline]
15604#[must_use]
15605pub const fn const_ring_eval_w224(op: PrimitiveOp, a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
15606    let raw = match op {
15607        PrimitiveOp::Add => a.wrapping_add(b),
15608        PrimitiveOp::Sub => a.wrapping_sub(b),
15609        PrimitiveOp::Mul => a.wrapping_mul(b),
15610        PrimitiveOp::And => a.and(b),
15611        PrimitiveOp::Or => a.or(b),
15612        PrimitiveOp::Xor => a.xor(b),
15613        PrimitiveOp::Neg => Limbs::<4>::zero().wrapping_sub(a),
15614        PrimitiveOp::Bnot => a.not(),
15615        PrimitiveOp::Succ => a.wrapping_add(limbs_one_4()),
15616        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_4()),
15617        PrimitiveOp::Le => {
15618            if limbs_le_4(a, b) {
15619                limbs_one_4()
15620            } else {
15621                Limbs::<4>::zero()
15622            }
15623        }
15624        PrimitiveOp::Lt => {
15625            if limbs_lt_4(a, b) {
15626                limbs_one_4()
15627            } else {
15628                Limbs::<4>::zero()
15629            }
15630        }
15631        PrimitiveOp::Ge => {
15632            if limbs_le_4(b, a) {
15633                limbs_one_4()
15634            } else {
15635                Limbs::<4>::zero()
15636            }
15637        }
15638        PrimitiveOp::Gt => {
15639            if limbs_lt_4(b, a) {
15640                limbs_one_4()
15641            } else {
15642                Limbs::<4>::zero()
15643            }
15644        }
15645        PrimitiveOp::Concat => Limbs::<4>::zero(),
15646        PrimitiveOp::Div => {
15647            if limbs_is_zero_4(b) {
15648                Limbs::<4>::zero()
15649            } else {
15650                limbs_div_4(a, b)
15651            }
15652        }
15653        PrimitiveOp::Mod => {
15654            if limbs_is_zero_4(b) {
15655                Limbs::<4>::zero()
15656            } else {
15657                limbs_mod_4(a, b)
15658            }
15659        }
15660        PrimitiveOp::Pow => limbs_pow_4(a, b),
15661    };
15662    raw.mask_high_bits(224)
15663}
15664
15665#[inline]
15666#[must_use]
15667pub const fn const_ring_eval_w256(op: PrimitiveOp, a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
15668    match op {
15669        PrimitiveOp::Add => a.wrapping_add(b),
15670        PrimitiveOp::Sub => a.wrapping_sub(b),
15671        PrimitiveOp::Mul => a.wrapping_mul(b),
15672        PrimitiveOp::And => a.and(b),
15673        PrimitiveOp::Or => a.or(b),
15674        PrimitiveOp::Xor => a.xor(b),
15675        PrimitiveOp::Neg => Limbs::<4>::zero().wrapping_sub(a),
15676        PrimitiveOp::Bnot => a.not(),
15677        PrimitiveOp::Succ => a.wrapping_add(limbs_one_4()),
15678        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_4()),
15679        PrimitiveOp::Le => {
15680            if limbs_le_4(a, b) {
15681                limbs_one_4()
15682            } else {
15683                Limbs::<4>::zero()
15684            }
15685        }
15686        PrimitiveOp::Lt => {
15687            if limbs_lt_4(a, b) {
15688                limbs_one_4()
15689            } else {
15690                Limbs::<4>::zero()
15691            }
15692        }
15693        PrimitiveOp::Ge => {
15694            if limbs_le_4(b, a) {
15695                limbs_one_4()
15696            } else {
15697                Limbs::<4>::zero()
15698            }
15699        }
15700        PrimitiveOp::Gt => {
15701            if limbs_lt_4(b, a) {
15702                limbs_one_4()
15703            } else {
15704                Limbs::<4>::zero()
15705            }
15706        }
15707        PrimitiveOp::Concat => Limbs::<4>::zero(),
15708        PrimitiveOp::Div => {
15709            if limbs_is_zero_4(b) {
15710                Limbs::<4>::zero()
15711            } else {
15712                limbs_div_4(a, b)
15713            }
15714        }
15715        PrimitiveOp::Mod => {
15716            if limbs_is_zero_4(b) {
15717                Limbs::<4>::zero()
15718            } else {
15719                limbs_mod_4(a, b)
15720            }
15721        }
15722        PrimitiveOp::Pow => limbs_pow_4(a, b),
15723    }
15724}
15725
15726#[inline]
15727#[must_use]
15728pub const fn const_ring_eval_w384(op: PrimitiveOp, a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
15729    match op {
15730        PrimitiveOp::Add => a.wrapping_add(b),
15731        PrimitiveOp::Sub => a.wrapping_sub(b),
15732        PrimitiveOp::Mul => a.wrapping_mul(b),
15733        PrimitiveOp::And => a.and(b),
15734        PrimitiveOp::Or => a.or(b),
15735        PrimitiveOp::Xor => a.xor(b),
15736        PrimitiveOp::Neg => Limbs::<6>::zero().wrapping_sub(a),
15737        PrimitiveOp::Bnot => a.not(),
15738        PrimitiveOp::Succ => a.wrapping_add(limbs_one_6()),
15739        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_6()),
15740        PrimitiveOp::Le => {
15741            if limbs_le_6(a, b) {
15742                limbs_one_6()
15743            } else {
15744                Limbs::<6>::zero()
15745            }
15746        }
15747        PrimitiveOp::Lt => {
15748            if limbs_lt_6(a, b) {
15749                limbs_one_6()
15750            } else {
15751                Limbs::<6>::zero()
15752            }
15753        }
15754        PrimitiveOp::Ge => {
15755            if limbs_le_6(b, a) {
15756                limbs_one_6()
15757            } else {
15758                Limbs::<6>::zero()
15759            }
15760        }
15761        PrimitiveOp::Gt => {
15762            if limbs_lt_6(b, a) {
15763                limbs_one_6()
15764            } else {
15765                Limbs::<6>::zero()
15766            }
15767        }
15768        PrimitiveOp::Concat => Limbs::<6>::zero(),
15769        PrimitiveOp::Div => {
15770            if limbs_is_zero_6(b) {
15771                Limbs::<6>::zero()
15772            } else {
15773                limbs_div_6(a, b)
15774            }
15775        }
15776        PrimitiveOp::Mod => {
15777            if limbs_is_zero_6(b) {
15778                Limbs::<6>::zero()
15779            } else {
15780                limbs_mod_6(a, b)
15781            }
15782        }
15783        PrimitiveOp::Pow => limbs_pow_6(a, b),
15784    }
15785}
15786
15787#[inline]
15788#[must_use]
15789pub const fn const_ring_eval_w448(op: PrimitiveOp, a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
15790    match op {
15791        PrimitiveOp::Add => a.wrapping_add(b),
15792        PrimitiveOp::Sub => a.wrapping_sub(b),
15793        PrimitiveOp::Mul => a.wrapping_mul(b),
15794        PrimitiveOp::And => a.and(b),
15795        PrimitiveOp::Or => a.or(b),
15796        PrimitiveOp::Xor => a.xor(b),
15797        PrimitiveOp::Neg => Limbs::<7>::zero().wrapping_sub(a),
15798        PrimitiveOp::Bnot => a.not(),
15799        PrimitiveOp::Succ => a.wrapping_add(limbs_one_7()),
15800        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_7()),
15801        PrimitiveOp::Le => {
15802            if limbs_le_7(a, b) {
15803                limbs_one_7()
15804            } else {
15805                Limbs::<7>::zero()
15806            }
15807        }
15808        PrimitiveOp::Lt => {
15809            if limbs_lt_7(a, b) {
15810                limbs_one_7()
15811            } else {
15812                Limbs::<7>::zero()
15813            }
15814        }
15815        PrimitiveOp::Ge => {
15816            if limbs_le_7(b, a) {
15817                limbs_one_7()
15818            } else {
15819                Limbs::<7>::zero()
15820            }
15821        }
15822        PrimitiveOp::Gt => {
15823            if limbs_lt_7(b, a) {
15824                limbs_one_7()
15825            } else {
15826                Limbs::<7>::zero()
15827            }
15828        }
15829        PrimitiveOp::Concat => Limbs::<7>::zero(),
15830        PrimitiveOp::Div => {
15831            if limbs_is_zero_7(b) {
15832                Limbs::<7>::zero()
15833            } else {
15834                limbs_div_7(a, b)
15835            }
15836        }
15837        PrimitiveOp::Mod => {
15838            if limbs_is_zero_7(b) {
15839                Limbs::<7>::zero()
15840            } else {
15841                limbs_mod_7(a, b)
15842            }
15843        }
15844        PrimitiveOp::Pow => limbs_pow_7(a, b),
15845    }
15846}
15847
15848#[inline]
15849#[must_use]
15850pub const fn const_ring_eval_w512(op: PrimitiveOp, a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
15851    match op {
15852        PrimitiveOp::Add => a.wrapping_add(b),
15853        PrimitiveOp::Sub => a.wrapping_sub(b),
15854        PrimitiveOp::Mul => a.wrapping_mul(b),
15855        PrimitiveOp::And => a.and(b),
15856        PrimitiveOp::Or => a.or(b),
15857        PrimitiveOp::Xor => a.xor(b),
15858        PrimitiveOp::Neg => Limbs::<8>::zero().wrapping_sub(a),
15859        PrimitiveOp::Bnot => a.not(),
15860        PrimitiveOp::Succ => a.wrapping_add(limbs_one_8()),
15861        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_8()),
15862        PrimitiveOp::Le => {
15863            if limbs_le_8(a, b) {
15864                limbs_one_8()
15865            } else {
15866                Limbs::<8>::zero()
15867            }
15868        }
15869        PrimitiveOp::Lt => {
15870            if limbs_lt_8(a, b) {
15871                limbs_one_8()
15872            } else {
15873                Limbs::<8>::zero()
15874            }
15875        }
15876        PrimitiveOp::Ge => {
15877            if limbs_le_8(b, a) {
15878                limbs_one_8()
15879            } else {
15880                Limbs::<8>::zero()
15881            }
15882        }
15883        PrimitiveOp::Gt => {
15884            if limbs_lt_8(b, a) {
15885                limbs_one_8()
15886            } else {
15887                Limbs::<8>::zero()
15888            }
15889        }
15890        PrimitiveOp::Concat => Limbs::<8>::zero(),
15891        PrimitiveOp::Div => {
15892            if limbs_is_zero_8(b) {
15893                Limbs::<8>::zero()
15894            } else {
15895                limbs_div_8(a, b)
15896            }
15897        }
15898        PrimitiveOp::Mod => {
15899            if limbs_is_zero_8(b) {
15900                Limbs::<8>::zero()
15901            } else {
15902                limbs_mod_8(a, b)
15903            }
15904        }
15905        PrimitiveOp::Pow => limbs_pow_8(a, b),
15906    }
15907}
15908
15909#[inline]
15910#[must_use]
15911pub const fn const_ring_eval_w520(op: PrimitiveOp, a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
15912    let raw = match op {
15913        PrimitiveOp::Add => a.wrapping_add(b),
15914        PrimitiveOp::Sub => a.wrapping_sub(b),
15915        PrimitiveOp::Mul => a.wrapping_mul(b),
15916        PrimitiveOp::And => a.and(b),
15917        PrimitiveOp::Or => a.or(b),
15918        PrimitiveOp::Xor => a.xor(b),
15919        PrimitiveOp::Neg => Limbs::<9>::zero().wrapping_sub(a),
15920        PrimitiveOp::Bnot => a.not(),
15921        PrimitiveOp::Succ => a.wrapping_add(limbs_one_9()),
15922        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_9()),
15923        PrimitiveOp::Le => {
15924            if limbs_le_9(a, b) {
15925                limbs_one_9()
15926            } else {
15927                Limbs::<9>::zero()
15928            }
15929        }
15930        PrimitiveOp::Lt => {
15931            if limbs_lt_9(a, b) {
15932                limbs_one_9()
15933            } else {
15934                Limbs::<9>::zero()
15935            }
15936        }
15937        PrimitiveOp::Ge => {
15938            if limbs_le_9(b, a) {
15939                limbs_one_9()
15940            } else {
15941                Limbs::<9>::zero()
15942            }
15943        }
15944        PrimitiveOp::Gt => {
15945            if limbs_lt_9(b, a) {
15946                limbs_one_9()
15947            } else {
15948                Limbs::<9>::zero()
15949            }
15950        }
15951        PrimitiveOp::Concat => Limbs::<9>::zero(),
15952        PrimitiveOp::Div => {
15953            if limbs_is_zero_9(b) {
15954                Limbs::<9>::zero()
15955            } else {
15956                limbs_div_9(a, b)
15957            }
15958        }
15959        PrimitiveOp::Mod => {
15960            if limbs_is_zero_9(b) {
15961                Limbs::<9>::zero()
15962            } else {
15963                limbs_mod_9(a, b)
15964            }
15965        }
15966        PrimitiveOp::Pow => limbs_pow_9(a, b),
15967    };
15968    raw.mask_high_bits(520)
15969}
15970
15971#[inline]
15972#[must_use]
15973pub const fn const_ring_eval_w528(op: PrimitiveOp, a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
15974    let raw = match op {
15975        PrimitiveOp::Add => a.wrapping_add(b),
15976        PrimitiveOp::Sub => a.wrapping_sub(b),
15977        PrimitiveOp::Mul => a.wrapping_mul(b),
15978        PrimitiveOp::And => a.and(b),
15979        PrimitiveOp::Or => a.or(b),
15980        PrimitiveOp::Xor => a.xor(b),
15981        PrimitiveOp::Neg => Limbs::<9>::zero().wrapping_sub(a),
15982        PrimitiveOp::Bnot => a.not(),
15983        PrimitiveOp::Succ => a.wrapping_add(limbs_one_9()),
15984        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_9()),
15985        PrimitiveOp::Le => {
15986            if limbs_le_9(a, b) {
15987                limbs_one_9()
15988            } else {
15989                Limbs::<9>::zero()
15990            }
15991        }
15992        PrimitiveOp::Lt => {
15993            if limbs_lt_9(a, b) {
15994                limbs_one_9()
15995            } else {
15996                Limbs::<9>::zero()
15997            }
15998        }
15999        PrimitiveOp::Ge => {
16000            if limbs_le_9(b, a) {
16001                limbs_one_9()
16002            } else {
16003                Limbs::<9>::zero()
16004            }
16005        }
16006        PrimitiveOp::Gt => {
16007            if limbs_lt_9(b, a) {
16008                limbs_one_9()
16009            } else {
16010                Limbs::<9>::zero()
16011            }
16012        }
16013        PrimitiveOp::Concat => Limbs::<9>::zero(),
16014        PrimitiveOp::Div => {
16015            if limbs_is_zero_9(b) {
16016                Limbs::<9>::zero()
16017            } else {
16018                limbs_div_9(a, b)
16019            }
16020        }
16021        PrimitiveOp::Mod => {
16022            if limbs_is_zero_9(b) {
16023                Limbs::<9>::zero()
16024            } else {
16025                limbs_mod_9(a, b)
16026            }
16027        }
16028        PrimitiveOp::Pow => limbs_pow_9(a, b),
16029    };
16030    raw.mask_high_bits(528)
16031}
16032
16033#[inline]
16034#[must_use]
16035pub const fn const_ring_eval_w1024(op: PrimitiveOp, a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
16036    match op {
16037        PrimitiveOp::Add => a.wrapping_add(b),
16038        PrimitiveOp::Sub => a.wrapping_sub(b),
16039        PrimitiveOp::Mul => a.wrapping_mul(b),
16040        PrimitiveOp::And => a.and(b),
16041        PrimitiveOp::Or => a.or(b),
16042        PrimitiveOp::Xor => a.xor(b),
16043        PrimitiveOp::Neg => Limbs::<16>::zero().wrapping_sub(a),
16044        PrimitiveOp::Bnot => a.not(),
16045        PrimitiveOp::Succ => a.wrapping_add(limbs_one_16()),
16046        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_16()),
16047        PrimitiveOp::Le => {
16048            if limbs_le_16(a, b) {
16049                limbs_one_16()
16050            } else {
16051                Limbs::<16>::zero()
16052            }
16053        }
16054        PrimitiveOp::Lt => {
16055            if limbs_lt_16(a, b) {
16056                limbs_one_16()
16057            } else {
16058                Limbs::<16>::zero()
16059            }
16060        }
16061        PrimitiveOp::Ge => {
16062            if limbs_le_16(b, a) {
16063                limbs_one_16()
16064            } else {
16065                Limbs::<16>::zero()
16066            }
16067        }
16068        PrimitiveOp::Gt => {
16069            if limbs_lt_16(b, a) {
16070                limbs_one_16()
16071            } else {
16072                Limbs::<16>::zero()
16073            }
16074        }
16075        PrimitiveOp::Concat => Limbs::<16>::zero(),
16076        PrimitiveOp::Div => {
16077            if limbs_is_zero_16(b) {
16078                Limbs::<16>::zero()
16079            } else {
16080                limbs_div_16(a, b)
16081            }
16082        }
16083        PrimitiveOp::Mod => {
16084            if limbs_is_zero_16(b) {
16085                Limbs::<16>::zero()
16086            } else {
16087                limbs_mod_16(a, b)
16088            }
16089        }
16090        PrimitiveOp::Pow => limbs_pow_16(a, b),
16091    }
16092}
16093
16094#[inline]
16095#[must_use]
16096pub const fn const_ring_eval_w2048(op: PrimitiveOp, a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
16097    match op {
16098        PrimitiveOp::Add => a.wrapping_add(b),
16099        PrimitiveOp::Sub => a.wrapping_sub(b),
16100        PrimitiveOp::Mul => a.wrapping_mul(b),
16101        PrimitiveOp::And => a.and(b),
16102        PrimitiveOp::Or => a.or(b),
16103        PrimitiveOp::Xor => a.xor(b),
16104        PrimitiveOp::Neg => Limbs::<32>::zero().wrapping_sub(a),
16105        PrimitiveOp::Bnot => a.not(),
16106        PrimitiveOp::Succ => a.wrapping_add(limbs_one_32()),
16107        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_32()),
16108        PrimitiveOp::Le => {
16109            if limbs_le_32(a, b) {
16110                limbs_one_32()
16111            } else {
16112                Limbs::<32>::zero()
16113            }
16114        }
16115        PrimitiveOp::Lt => {
16116            if limbs_lt_32(a, b) {
16117                limbs_one_32()
16118            } else {
16119                Limbs::<32>::zero()
16120            }
16121        }
16122        PrimitiveOp::Ge => {
16123            if limbs_le_32(b, a) {
16124                limbs_one_32()
16125            } else {
16126                Limbs::<32>::zero()
16127            }
16128        }
16129        PrimitiveOp::Gt => {
16130            if limbs_lt_32(b, a) {
16131                limbs_one_32()
16132            } else {
16133                Limbs::<32>::zero()
16134            }
16135        }
16136        PrimitiveOp::Concat => Limbs::<32>::zero(),
16137        PrimitiveOp::Div => {
16138            if limbs_is_zero_32(b) {
16139                Limbs::<32>::zero()
16140            } else {
16141                limbs_div_32(a, b)
16142            }
16143        }
16144        PrimitiveOp::Mod => {
16145            if limbs_is_zero_32(b) {
16146                Limbs::<32>::zero()
16147            } else {
16148                limbs_mod_32(a, b)
16149            }
16150        }
16151        PrimitiveOp::Pow => limbs_pow_32(a, b),
16152    }
16153}
16154
16155#[inline]
16156#[must_use]
16157pub const fn const_ring_eval_w4096(op: PrimitiveOp, a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
16158    match op {
16159        PrimitiveOp::Add => a.wrapping_add(b),
16160        PrimitiveOp::Sub => a.wrapping_sub(b),
16161        PrimitiveOp::Mul => a.wrapping_mul(b),
16162        PrimitiveOp::And => a.and(b),
16163        PrimitiveOp::Or => a.or(b),
16164        PrimitiveOp::Xor => a.xor(b),
16165        PrimitiveOp::Neg => Limbs::<64>::zero().wrapping_sub(a),
16166        PrimitiveOp::Bnot => a.not(),
16167        PrimitiveOp::Succ => a.wrapping_add(limbs_one_64()),
16168        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_64()),
16169        PrimitiveOp::Le => {
16170            if limbs_le_64(a, b) {
16171                limbs_one_64()
16172            } else {
16173                Limbs::<64>::zero()
16174            }
16175        }
16176        PrimitiveOp::Lt => {
16177            if limbs_lt_64(a, b) {
16178                limbs_one_64()
16179            } else {
16180                Limbs::<64>::zero()
16181            }
16182        }
16183        PrimitiveOp::Ge => {
16184            if limbs_le_64(b, a) {
16185                limbs_one_64()
16186            } else {
16187                Limbs::<64>::zero()
16188            }
16189        }
16190        PrimitiveOp::Gt => {
16191            if limbs_lt_64(b, a) {
16192                limbs_one_64()
16193            } else {
16194                Limbs::<64>::zero()
16195            }
16196        }
16197        PrimitiveOp::Concat => Limbs::<64>::zero(),
16198        PrimitiveOp::Div => {
16199            if limbs_is_zero_64(b) {
16200                Limbs::<64>::zero()
16201            } else {
16202                limbs_div_64(a, b)
16203            }
16204        }
16205        PrimitiveOp::Mod => {
16206            if limbs_is_zero_64(b) {
16207                Limbs::<64>::zero()
16208            } else {
16209                limbs_mod_64(a, b)
16210            }
16211        }
16212        PrimitiveOp::Pow => limbs_pow_64(a, b),
16213    }
16214}
16215
16216#[inline]
16217#[must_use]
16218pub const fn const_ring_eval_w8192(op: PrimitiveOp, a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
16219    match op {
16220        PrimitiveOp::Add => a.wrapping_add(b),
16221        PrimitiveOp::Sub => a.wrapping_sub(b),
16222        PrimitiveOp::Mul => a.wrapping_mul(b),
16223        PrimitiveOp::And => a.and(b),
16224        PrimitiveOp::Or => a.or(b),
16225        PrimitiveOp::Xor => a.xor(b),
16226        PrimitiveOp::Neg => Limbs::<128>::zero().wrapping_sub(a),
16227        PrimitiveOp::Bnot => a.not(),
16228        PrimitiveOp::Succ => a.wrapping_add(limbs_one_128()),
16229        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_128()),
16230        PrimitiveOp::Le => {
16231            if limbs_le_128(a, b) {
16232                limbs_one_128()
16233            } else {
16234                Limbs::<128>::zero()
16235            }
16236        }
16237        PrimitiveOp::Lt => {
16238            if limbs_lt_128(a, b) {
16239                limbs_one_128()
16240            } else {
16241                Limbs::<128>::zero()
16242            }
16243        }
16244        PrimitiveOp::Ge => {
16245            if limbs_le_128(b, a) {
16246                limbs_one_128()
16247            } else {
16248                Limbs::<128>::zero()
16249            }
16250        }
16251        PrimitiveOp::Gt => {
16252            if limbs_lt_128(b, a) {
16253                limbs_one_128()
16254            } else {
16255                Limbs::<128>::zero()
16256            }
16257        }
16258        PrimitiveOp::Concat => Limbs::<128>::zero(),
16259        PrimitiveOp::Div => {
16260            if limbs_is_zero_128(b) {
16261                Limbs::<128>::zero()
16262            } else {
16263                limbs_div_128(a, b)
16264            }
16265        }
16266        PrimitiveOp::Mod => {
16267            if limbs_is_zero_128(b) {
16268                Limbs::<128>::zero()
16269            } else {
16270                limbs_mod_128(a, b)
16271            }
16272        }
16273        PrimitiveOp::Pow => limbs_pow_128(a, b),
16274    }
16275}
16276
16277#[inline]
16278#[must_use]
16279pub const fn const_ring_eval_w12288(op: PrimitiveOp, a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
16280    match op {
16281        PrimitiveOp::Add => a.wrapping_add(b),
16282        PrimitiveOp::Sub => a.wrapping_sub(b),
16283        PrimitiveOp::Mul => a.wrapping_mul(b),
16284        PrimitiveOp::And => a.and(b),
16285        PrimitiveOp::Or => a.or(b),
16286        PrimitiveOp::Xor => a.xor(b),
16287        PrimitiveOp::Neg => Limbs::<192>::zero().wrapping_sub(a),
16288        PrimitiveOp::Bnot => a.not(),
16289        PrimitiveOp::Succ => a.wrapping_add(limbs_one_192()),
16290        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_192()),
16291        PrimitiveOp::Le => {
16292            if limbs_le_192(a, b) {
16293                limbs_one_192()
16294            } else {
16295                Limbs::<192>::zero()
16296            }
16297        }
16298        PrimitiveOp::Lt => {
16299            if limbs_lt_192(a, b) {
16300                limbs_one_192()
16301            } else {
16302                Limbs::<192>::zero()
16303            }
16304        }
16305        PrimitiveOp::Ge => {
16306            if limbs_le_192(b, a) {
16307                limbs_one_192()
16308            } else {
16309                Limbs::<192>::zero()
16310            }
16311        }
16312        PrimitiveOp::Gt => {
16313            if limbs_lt_192(b, a) {
16314                limbs_one_192()
16315            } else {
16316                Limbs::<192>::zero()
16317            }
16318        }
16319        PrimitiveOp::Concat => Limbs::<192>::zero(),
16320        PrimitiveOp::Div => {
16321            if limbs_is_zero_192(b) {
16322                Limbs::<192>::zero()
16323            } else {
16324                limbs_div_192(a, b)
16325            }
16326        }
16327        PrimitiveOp::Mod => {
16328            if limbs_is_zero_192(b) {
16329                Limbs::<192>::zero()
16330            } else {
16331                limbs_mod_192(a, b)
16332            }
16333        }
16334        PrimitiveOp::Pow => limbs_pow_192(a, b),
16335    }
16336}
16337
16338#[inline]
16339#[must_use]
16340pub const fn const_ring_eval_w16384(op: PrimitiveOp, a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
16341    match op {
16342        PrimitiveOp::Add => a.wrapping_add(b),
16343        PrimitiveOp::Sub => a.wrapping_sub(b),
16344        PrimitiveOp::Mul => a.wrapping_mul(b),
16345        PrimitiveOp::And => a.and(b),
16346        PrimitiveOp::Or => a.or(b),
16347        PrimitiveOp::Xor => a.xor(b),
16348        PrimitiveOp::Neg => Limbs::<256>::zero().wrapping_sub(a),
16349        PrimitiveOp::Bnot => a.not(),
16350        PrimitiveOp::Succ => a.wrapping_add(limbs_one_256()),
16351        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_256()),
16352        PrimitiveOp::Le => {
16353            if limbs_le_256(a, b) {
16354                limbs_one_256()
16355            } else {
16356                Limbs::<256>::zero()
16357            }
16358        }
16359        PrimitiveOp::Lt => {
16360            if limbs_lt_256(a, b) {
16361                limbs_one_256()
16362            } else {
16363                Limbs::<256>::zero()
16364            }
16365        }
16366        PrimitiveOp::Ge => {
16367            if limbs_le_256(b, a) {
16368                limbs_one_256()
16369            } else {
16370                Limbs::<256>::zero()
16371            }
16372        }
16373        PrimitiveOp::Gt => {
16374            if limbs_lt_256(b, a) {
16375                limbs_one_256()
16376            } else {
16377                Limbs::<256>::zero()
16378            }
16379        }
16380        PrimitiveOp::Concat => Limbs::<256>::zero(),
16381        PrimitiveOp::Div => {
16382            if limbs_is_zero_256(b) {
16383                Limbs::<256>::zero()
16384            } else {
16385                limbs_div_256(a, b)
16386            }
16387        }
16388        PrimitiveOp::Mod => {
16389            if limbs_is_zero_256(b) {
16390                Limbs::<256>::zero()
16391            } else {
16392                limbs_mod_256(a, b)
16393            }
16394        }
16395        PrimitiveOp::Pow => limbs_pow_256(a, b),
16396    }
16397}
16398
16399#[inline]
16400#[must_use]
16401pub const fn const_ring_eval_w32768(op: PrimitiveOp, a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
16402    match op {
16403        PrimitiveOp::Add => a.wrapping_add(b),
16404        PrimitiveOp::Sub => a.wrapping_sub(b),
16405        PrimitiveOp::Mul => a.wrapping_mul(b),
16406        PrimitiveOp::And => a.and(b),
16407        PrimitiveOp::Or => a.or(b),
16408        PrimitiveOp::Xor => a.xor(b),
16409        PrimitiveOp::Neg => Limbs::<512>::zero().wrapping_sub(a),
16410        PrimitiveOp::Bnot => a.not(),
16411        PrimitiveOp::Succ => a.wrapping_add(limbs_one_512()),
16412        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_512()),
16413        PrimitiveOp::Le => {
16414            if limbs_le_512(a, b) {
16415                limbs_one_512()
16416            } else {
16417                Limbs::<512>::zero()
16418            }
16419        }
16420        PrimitiveOp::Lt => {
16421            if limbs_lt_512(a, b) {
16422                limbs_one_512()
16423            } else {
16424                Limbs::<512>::zero()
16425            }
16426        }
16427        PrimitiveOp::Ge => {
16428            if limbs_le_512(b, a) {
16429                limbs_one_512()
16430            } else {
16431                Limbs::<512>::zero()
16432            }
16433        }
16434        PrimitiveOp::Gt => {
16435            if limbs_lt_512(b, a) {
16436                limbs_one_512()
16437            } else {
16438                Limbs::<512>::zero()
16439            }
16440        }
16441        PrimitiveOp::Concat => Limbs::<512>::zero(),
16442        PrimitiveOp::Div => {
16443            if limbs_is_zero_512(b) {
16444                Limbs::<512>::zero()
16445            } else {
16446                limbs_div_512(a, b)
16447            }
16448        }
16449        PrimitiveOp::Mod => {
16450            if limbs_is_zero_512(b) {
16451                Limbs::<512>::zero()
16452            } else {
16453                limbs_mod_512(a, b)
16454            }
16455        }
16456        PrimitiveOp::Pow => limbs_pow_512(a, b),
16457    }
16458}
16459
16460/// Phase L.2: one-constant helpers for `Limbs<N>::from_words([1, 0, ...])`.
16461#[inline]
16462#[must_use]
16463const fn limbs_one_3() -> Limbs<3> {
16464    Limbs::<3>::from_words([1u64, 0u64, 0u64])
16465}
16466
16467#[inline]
16468#[must_use]
16469const fn limbs_one_4() -> Limbs<4> {
16470    Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64])
16471}
16472
16473#[inline]
16474#[must_use]
16475const fn limbs_one_6() -> Limbs<6> {
16476    Limbs::<6>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16477}
16478
16479#[inline]
16480#[must_use]
16481const fn limbs_one_7() -> Limbs<7> {
16482    Limbs::<7>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16483}
16484
16485#[inline]
16486#[must_use]
16487const fn limbs_one_8() -> Limbs<8> {
16488    Limbs::<8>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16489}
16490
16491#[inline]
16492#[must_use]
16493const fn limbs_one_9() -> Limbs<9> {
16494    Limbs::<9>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16495}
16496
16497#[inline]
16498#[must_use]
16499const fn limbs_one_16() -> Limbs<16> {
16500    Limbs::<16>::from_words([
16501        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16502        0u64,
16503    ])
16504}
16505
16506#[inline]
16507#[must_use]
16508const fn limbs_one_32() -> Limbs<32> {
16509    Limbs::<32>::from_words([
16510        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16511        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16512        0u64, 0u64,
16513    ])
16514}
16515
16516#[inline]
16517#[must_use]
16518const fn limbs_one_64() -> Limbs<64> {
16519    Limbs::<64>::from_words([
16520        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16521        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16522        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16523        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16524        0u64, 0u64, 0u64, 0u64,
16525    ])
16526}
16527
16528#[inline]
16529#[must_use]
16530const fn limbs_one_128() -> Limbs<128> {
16531    Limbs::<128>::from_words([
16532        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16533        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16534        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16535        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16536        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16537        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16538        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16539        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16540        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16541    ])
16542}
16543
16544#[inline]
16545#[must_use]
16546const fn limbs_one_192() -> Limbs<192> {
16547    Limbs::<192>::from_words([
16548        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16549        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16550        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16551        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16552        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16553        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16554        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16555        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16556        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16557        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16558        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16559        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16560        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16561    ])
16562}
16563
16564#[inline]
16565#[must_use]
16566const fn limbs_one_256() -> Limbs<256> {
16567    Limbs::<256>::from_words([
16568        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16569        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16570        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16571        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16572        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16573        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16574        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16575        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16576        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16577        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16578        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16579        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16580        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16581        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16582        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16583        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16584        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16585        0u64,
16586    ])
16587}
16588
16589#[inline]
16590#[must_use]
16591const fn limbs_one_512() -> Limbs<512> {
16592    Limbs::<512>::from_words([
16593        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16594        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16595        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16596        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16597        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16598        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16599        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16600        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16601        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16602        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16603        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16604        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16605        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16606        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16607        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16608        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16609        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16610        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16611        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16612        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16613        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16614        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16615        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16616        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16617        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16618        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16619        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16620        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16621        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16622        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16623        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16624        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16625        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16626        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16627        0u64, 0u64,
16628    ])
16629}
16630
16631/// ADR-013/TR-08: const-fn limb comparisons used by `const_ring_eval_w{n}`
16632/// to lift the comparison primitives to 0/1-valued ring indicators.
16633#[inline]
16634#[must_use]
16635const fn limbs_lt_3(a: Limbs<3>, b: Limbs<3>) -> bool {
16636    let aw = a.words();
16637    let bw = b.words();
16638    let mut i = 3;
16639    while i > 0 {
16640        i -= 1;
16641        if aw[i] < bw[i] {
16642            return true;
16643        }
16644        if aw[i] > bw[i] {
16645            return false;
16646        }
16647    }
16648    false
16649}
16650
16651#[inline]
16652#[must_use]
16653const fn limbs_le_3(a: Limbs<3>, b: Limbs<3>) -> bool {
16654    let aw = a.words();
16655    let bw = b.words();
16656    let mut i = 3;
16657    while i > 0 {
16658        i -= 1;
16659        if aw[i] < bw[i] {
16660            return true;
16661        }
16662        if aw[i] > bw[i] {
16663            return false;
16664        }
16665    }
16666    true
16667}
16668
16669#[inline]
16670#[must_use]
16671const fn limbs_lt_4(a: Limbs<4>, b: Limbs<4>) -> bool {
16672    let aw = a.words();
16673    let bw = b.words();
16674    let mut i = 4;
16675    while i > 0 {
16676        i -= 1;
16677        if aw[i] < bw[i] {
16678            return true;
16679        }
16680        if aw[i] > bw[i] {
16681            return false;
16682        }
16683    }
16684    false
16685}
16686
16687#[inline]
16688#[must_use]
16689const fn limbs_le_4(a: Limbs<4>, b: Limbs<4>) -> bool {
16690    let aw = a.words();
16691    let bw = b.words();
16692    let mut i = 4;
16693    while i > 0 {
16694        i -= 1;
16695        if aw[i] < bw[i] {
16696            return true;
16697        }
16698        if aw[i] > bw[i] {
16699            return false;
16700        }
16701    }
16702    true
16703}
16704
16705#[inline]
16706#[must_use]
16707const fn limbs_lt_6(a: Limbs<6>, b: Limbs<6>) -> bool {
16708    let aw = a.words();
16709    let bw = b.words();
16710    let mut i = 6;
16711    while i > 0 {
16712        i -= 1;
16713        if aw[i] < bw[i] {
16714            return true;
16715        }
16716        if aw[i] > bw[i] {
16717            return false;
16718        }
16719    }
16720    false
16721}
16722
16723#[inline]
16724#[must_use]
16725const fn limbs_le_6(a: Limbs<6>, b: Limbs<6>) -> bool {
16726    let aw = a.words();
16727    let bw = b.words();
16728    let mut i = 6;
16729    while i > 0 {
16730        i -= 1;
16731        if aw[i] < bw[i] {
16732            return true;
16733        }
16734        if aw[i] > bw[i] {
16735            return false;
16736        }
16737    }
16738    true
16739}
16740
16741#[inline]
16742#[must_use]
16743const fn limbs_lt_7(a: Limbs<7>, b: Limbs<7>) -> bool {
16744    let aw = a.words();
16745    let bw = b.words();
16746    let mut i = 7;
16747    while i > 0 {
16748        i -= 1;
16749        if aw[i] < bw[i] {
16750            return true;
16751        }
16752        if aw[i] > bw[i] {
16753            return false;
16754        }
16755    }
16756    false
16757}
16758
16759#[inline]
16760#[must_use]
16761const fn limbs_le_7(a: Limbs<7>, b: Limbs<7>) -> bool {
16762    let aw = a.words();
16763    let bw = b.words();
16764    let mut i = 7;
16765    while i > 0 {
16766        i -= 1;
16767        if aw[i] < bw[i] {
16768            return true;
16769        }
16770        if aw[i] > bw[i] {
16771            return false;
16772        }
16773    }
16774    true
16775}
16776
16777#[inline]
16778#[must_use]
16779const fn limbs_lt_8(a: Limbs<8>, b: Limbs<8>) -> bool {
16780    let aw = a.words();
16781    let bw = b.words();
16782    let mut i = 8;
16783    while i > 0 {
16784        i -= 1;
16785        if aw[i] < bw[i] {
16786            return true;
16787        }
16788        if aw[i] > bw[i] {
16789            return false;
16790        }
16791    }
16792    false
16793}
16794
16795#[inline]
16796#[must_use]
16797const fn limbs_le_8(a: Limbs<8>, b: Limbs<8>) -> bool {
16798    let aw = a.words();
16799    let bw = b.words();
16800    let mut i = 8;
16801    while i > 0 {
16802        i -= 1;
16803        if aw[i] < bw[i] {
16804            return true;
16805        }
16806        if aw[i] > bw[i] {
16807            return false;
16808        }
16809    }
16810    true
16811}
16812
16813#[inline]
16814#[must_use]
16815const fn limbs_lt_9(a: Limbs<9>, b: Limbs<9>) -> bool {
16816    let aw = a.words();
16817    let bw = b.words();
16818    let mut i = 9;
16819    while i > 0 {
16820        i -= 1;
16821        if aw[i] < bw[i] {
16822            return true;
16823        }
16824        if aw[i] > bw[i] {
16825            return false;
16826        }
16827    }
16828    false
16829}
16830
16831#[inline]
16832#[must_use]
16833const fn limbs_le_9(a: Limbs<9>, b: Limbs<9>) -> bool {
16834    let aw = a.words();
16835    let bw = b.words();
16836    let mut i = 9;
16837    while i > 0 {
16838        i -= 1;
16839        if aw[i] < bw[i] {
16840            return true;
16841        }
16842        if aw[i] > bw[i] {
16843            return false;
16844        }
16845    }
16846    true
16847}
16848
16849#[inline]
16850#[must_use]
16851const fn limbs_lt_16(a: Limbs<16>, b: Limbs<16>) -> bool {
16852    let aw = a.words();
16853    let bw = b.words();
16854    let mut i = 16;
16855    while i > 0 {
16856        i -= 1;
16857        if aw[i] < bw[i] {
16858            return true;
16859        }
16860        if aw[i] > bw[i] {
16861            return false;
16862        }
16863    }
16864    false
16865}
16866
16867#[inline]
16868#[must_use]
16869const fn limbs_le_16(a: Limbs<16>, b: Limbs<16>) -> bool {
16870    let aw = a.words();
16871    let bw = b.words();
16872    let mut i = 16;
16873    while i > 0 {
16874        i -= 1;
16875        if aw[i] < bw[i] {
16876            return true;
16877        }
16878        if aw[i] > bw[i] {
16879            return false;
16880        }
16881    }
16882    true
16883}
16884
16885#[inline]
16886#[must_use]
16887const fn limbs_lt_32(a: Limbs<32>, b: Limbs<32>) -> bool {
16888    let aw = a.words();
16889    let bw = b.words();
16890    let mut i = 32;
16891    while i > 0 {
16892        i -= 1;
16893        if aw[i] < bw[i] {
16894            return true;
16895        }
16896        if aw[i] > bw[i] {
16897            return false;
16898        }
16899    }
16900    false
16901}
16902
16903#[inline]
16904#[must_use]
16905const fn limbs_le_32(a: Limbs<32>, b: Limbs<32>) -> bool {
16906    let aw = a.words();
16907    let bw = b.words();
16908    let mut i = 32;
16909    while i > 0 {
16910        i -= 1;
16911        if aw[i] < bw[i] {
16912            return true;
16913        }
16914        if aw[i] > bw[i] {
16915            return false;
16916        }
16917    }
16918    true
16919}
16920
16921#[inline]
16922#[must_use]
16923const fn limbs_lt_64(a: Limbs<64>, b: Limbs<64>) -> bool {
16924    let aw = a.words();
16925    let bw = b.words();
16926    let mut i = 64;
16927    while i > 0 {
16928        i -= 1;
16929        if aw[i] < bw[i] {
16930            return true;
16931        }
16932        if aw[i] > bw[i] {
16933            return false;
16934        }
16935    }
16936    false
16937}
16938
16939#[inline]
16940#[must_use]
16941const fn limbs_le_64(a: Limbs<64>, b: Limbs<64>) -> bool {
16942    let aw = a.words();
16943    let bw = b.words();
16944    let mut i = 64;
16945    while i > 0 {
16946        i -= 1;
16947        if aw[i] < bw[i] {
16948            return true;
16949        }
16950        if aw[i] > bw[i] {
16951            return false;
16952        }
16953    }
16954    true
16955}
16956
16957#[inline]
16958#[must_use]
16959const fn limbs_lt_128(a: Limbs<128>, b: Limbs<128>) -> bool {
16960    let aw = a.words();
16961    let bw = b.words();
16962    let mut i = 128;
16963    while i > 0 {
16964        i -= 1;
16965        if aw[i] < bw[i] {
16966            return true;
16967        }
16968        if aw[i] > bw[i] {
16969            return false;
16970        }
16971    }
16972    false
16973}
16974
16975#[inline]
16976#[must_use]
16977const fn limbs_le_128(a: Limbs<128>, b: Limbs<128>) -> bool {
16978    let aw = a.words();
16979    let bw = b.words();
16980    let mut i = 128;
16981    while i > 0 {
16982        i -= 1;
16983        if aw[i] < bw[i] {
16984            return true;
16985        }
16986        if aw[i] > bw[i] {
16987            return false;
16988        }
16989    }
16990    true
16991}
16992
16993#[inline]
16994#[must_use]
16995const fn limbs_lt_192(a: Limbs<192>, b: Limbs<192>) -> bool {
16996    let aw = a.words();
16997    let bw = b.words();
16998    let mut i = 192;
16999    while i > 0 {
17000        i -= 1;
17001        if aw[i] < bw[i] {
17002            return true;
17003        }
17004        if aw[i] > bw[i] {
17005            return false;
17006        }
17007    }
17008    false
17009}
17010
17011#[inline]
17012#[must_use]
17013const fn limbs_le_192(a: Limbs<192>, b: Limbs<192>) -> bool {
17014    let aw = a.words();
17015    let bw = b.words();
17016    let mut i = 192;
17017    while i > 0 {
17018        i -= 1;
17019        if aw[i] < bw[i] {
17020            return true;
17021        }
17022        if aw[i] > bw[i] {
17023            return false;
17024        }
17025    }
17026    true
17027}
17028
17029#[inline]
17030#[must_use]
17031const fn limbs_lt_256(a: Limbs<256>, b: Limbs<256>) -> bool {
17032    let aw = a.words();
17033    let bw = b.words();
17034    let mut i = 256;
17035    while i > 0 {
17036        i -= 1;
17037        if aw[i] < bw[i] {
17038            return true;
17039        }
17040        if aw[i] > bw[i] {
17041            return false;
17042        }
17043    }
17044    false
17045}
17046
17047#[inline]
17048#[must_use]
17049const fn limbs_le_256(a: Limbs<256>, b: Limbs<256>) -> bool {
17050    let aw = a.words();
17051    let bw = b.words();
17052    let mut i = 256;
17053    while i > 0 {
17054        i -= 1;
17055        if aw[i] < bw[i] {
17056            return true;
17057        }
17058        if aw[i] > bw[i] {
17059            return false;
17060        }
17061    }
17062    true
17063}
17064
17065#[inline]
17066#[must_use]
17067const fn limbs_lt_512(a: Limbs<512>, b: Limbs<512>) -> bool {
17068    let aw = a.words();
17069    let bw = b.words();
17070    let mut i = 512;
17071    while i > 0 {
17072        i -= 1;
17073        if aw[i] < bw[i] {
17074            return true;
17075        }
17076        if aw[i] > bw[i] {
17077            return false;
17078        }
17079    }
17080    false
17081}
17082
17083#[inline]
17084#[must_use]
17085const fn limbs_le_512(a: Limbs<512>, b: Limbs<512>) -> bool {
17086    let aw = a.words();
17087    let bw = b.words();
17088    let mut i = 512;
17089    while i > 0 {
17090        i -= 1;
17091        if aw[i] < bw[i] {
17092            return true;
17093        }
17094        if aw[i] > bw[i] {
17095            return false;
17096        }
17097    }
17098    true
17099}
17100
17101/// ADR-053: zero-check, binary-long-division, and square-and-multiply
17102/// helpers used by the const-fn `Div`/`Mod`/`Pow` arms of `const_ring_eval_w{n}`.
17103#[inline]
17104#[must_use]
17105const fn limbs_is_zero_3(a: Limbs<3>) -> bool {
17106    let aw = a.words();
17107    let mut i = 0usize;
17108    while i < 3 {
17109        if aw[i] != 0 {
17110            return false;
17111        }
17112        i += 1;
17113    }
17114    true
17115}
17116
17117#[inline]
17118#[must_use]
17119const fn limbs_shl1_3(a: Limbs<3>) -> Limbs<3> {
17120    let aw = a.words();
17121    let mut out = [0u64; 3];
17122    let mut carry: u64 = 0;
17123    let mut i = 0usize;
17124    while i < 3 {
17125        let v = aw[i];
17126        out[i] = (v << 1) | carry;
17127        carry = v >> 63;
17128        i += 1;
17129    }
17130    Limbs::<3>::from_words(out)
17131}
17132
17133#[inline]
17134#[must_use]
17135const fn limbs_set_bit0_3(a: Limbs<3>) -> Limbs<3> {
17136    let aw = a.words();
17137    let mut out = [0u64; 3];
17138    let mut i = 0usize;
17139    while i < 3 {
17140        out[i] = aw[i];
17141        i += 1;
17142    }
17143    out[0] |= 1u64;
17144    Limbs::<3>::from_words(out)
17145}
17146
17147#[inline]
17148#[must_use]
17149const fn limbs_bit_msb_3(a: Limbs<3>, msb_index: usize) -> u64 {
17150    let aw = a.words();
17151    let total_bits = 3 * 64;
17152    let lsb_index = total_bits - 1 - msb_index;
17153    let word = lsb_index / 64;
17154    let bit = lsb_index % 64;
17155    (aw[word] >> bit) & 1u64
17156}
17157
17158#[inline]
17159#[must_use]
17160const fn limbs_divmod_3(a: Limbs<3>, b: Limbs<3>) -> (Limbs<3>, Limbs<3>) {
17161    let mut q = Limbs::<3>::zero();
17162    let mut r = Limbs::<3>::zero();
17163    let total_bits = 3 * 64;
17164    let mut i = 0usize;
17165    while i < total_bits {
17166        r = limbs_shl1_3(r);
17167        if limbs_bit_msb_3(a, i) == 1 {
17168            r = limbs_set_bit0_3(r);
17169        }
17170        if limbs_le_3(b, r) {
17171            r = r.wrapping_sub(b);
17172            q = limbs_shl1_3(q);
17173            q = limbs_set_bit0_3(q);
17174        } else {
17175            q = limbs_shl1_3(q);
17176        }
17177        i += 1;
17178    }
17179    (q, r)
17180}
17181
17182#[inline]
17183#[must_use]
17184const fn limbs_div_3(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
17185    let (q, _) = limbs_divmod_3(a, b);
17186    q
17187}
17188
17189#[inline]
17190#[must_use]
17191const fn limbs_mod_3(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
17192    let (_, r) = limbs_divmod_3(a, b);
17193    r
17194}
17195
17196#[inline]
17197#[must_use]
17198const fn limbs_pow_3(base: Limbs<3>, exp: Limbs<3>) -> Limbs<3> {
17199    let mut result = limbs_one_3();
17200    let mut b = base;
17201    let ew = exp.words();
17202    let mut word = 0usize;
17203    while word < 3 {
17204        let mut bit = 0u32;
17205        while bit < 64 {
17206            if ((ew[word] >> bit) & 1u64) == 1u64 {
17207                result = result.wrapping_mul(b);
17208            }
17209            b = b.wrapping_mul(b);
17210            bit += 1;
17211        }
17212        word += 1;
17213    }
17214    result
17215}
17216
17217#[inline]
17218#[must_use]
17219const fn limbs_is_zero_4(a: Limbs<4>) -> bool {
17220    let aw = a.words();
17221    let mut i = 0usize;
17222    while i < 4 {
17223        if aw[i] != 0 {
17224            return false;
17225        }
17226        i += 1;
17227    }
17228    true
17229}
17230
17231#[inline]
17232#[must_use]
17233const fn limbs_shl1_4(a: Limbs<4>) -> Limbs<4> {
17234    let aw = a.words();
17235    let mut out = [0u64; 4];
17236    let mut carry: u64 = 0;
17237    let mut i = 0usize;
17238    while i < 4 {
17239        let v = aw[i];
17240        out[i] = (v << 1) | carry;
17241        carry = v >> 63;
17242        i += 1;
17243    }
17244    Limbs::<4>::from_words(out)
17245}
17246
17247#[inline]
17248#[must_use]
17249const fn limbs_set_bit0_4(a: Limbs<4>) -> Limbs<4> {
17250    let aw = a.words();
17251    let mut out = [0u64; 4];
17252    let mut i = 0usize;
17253    while i < 4 {
17254        out[i] = aw[i];
17255        i += 1;
17256    }
17257    out[0] |= 1u64;
17258    Limbs::<4>::from_words(out)
17259}
17260
17261#[inline]
17262#[must_use]
17263const fn limbs_bit_msb_4(a: Limbs<4>, msb_index: usize) -> u64 {
17264    let aw = a.words();
17265    let total_bits = 4 * 64;
17266    let lsb_index = total_bits - 1 - msb_index;
17267    let word = lsb_index / 64;
17268    let bit = lsb_index % 64;
17269    (aw[word] >> bit) & 1u64
17270}
17271
17272#[inline]
17273#[must_use]
17274const fn limbs_divmod_4(a: Limbs<4>, b: Limbs<4>) -> (Limbs<4>, Limbs<4>) {
17275    let mut q = Limbs::<4>::zero();
17276    let mut r = Limbs::<4>::zero();
17277    let total_bits = 4 * 64;
17278    let mut i = 0usize;
17279    while i < total_bits {
17280        r = limbs_shl1_4(r);
17281        if limbs_bit_msb_4(a, i) == 1 {
17282            r = limbs_set_bit0_4(r);
17283        }
17284        if limbs_le_4(b, r) {
17285            r = r.wrapping_sub(b);
17286            q = limbs_shl1_4(q);
17287            q = limbs_set_bit0_4(q);
17288        } else {
17289            q = limbs_shl1_4(q);
17290        }
17291        i += 1;
17292    }
17293    (q, r)
17294}
17295
17296#[inline]
17297#[must_use]
17298const fn limbs_div_4(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
17299    let (q, _) = limbs_divmod_4(a, b);
17300    q
17301}
17302
17303#[inline]
17304#[must_use]
17305const fn limbs_mod_4(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
17306    let (_, r) = limbs_divmod_4(a, b);
17307    r
17308}
17309
17310#[inline]
17311#[must_use]
17312const fn limbs_pow_4(base: Limbs<4>, exp: Limbs<4>) -> Limbs<4> {
17313    let mut result = limbs_one_4();
17314    let mut b = base;
17315    let ew = exp.words();
17316    let mut word = 0usize;
17317    while word < 4 {
17318        let mut bit = 0u32;
17319        while bit < 64 {
17320            if ((ew[word] >> bit) & 1u64) == 1u64 {
17321                result = result.wrapping_mul(b);
17322            }
17323            b = b.wrapping_mul(b);
17324            bit += 1;
17325        }
17326        word += 1;
17327    }
17328    result
17329}
17330
17331#[inline]
17332#[must_use]
17333const fn limbs_is_zero_6(a: Limbs<6>) -> bool {
17334    let aw = a.words();
17335    let mut i = 0usize;
17336    while i < 6 {
17337        if aw[i] != 0 {
17338            return false;
17339        }
17340        i += 1;
17341    }
17342    true
17343}
17344
17345#[inline]
17346#[must_use]
17347const fn limbs_shl1_6(a: Limbs<6>) -> Limbs<6> {
17348    let aw = a.words();
17349    let mut out = [0u64; 6];
17350    let mut carry: u64 = 0;
17351    let mut i = 0usize;
17352    while i < 6 {
17353        let v = aw[i];
17354        out[i] = (v << 1) | carry;
17355        carry = v >> 63;
17356        i += 1;
17357    }
17358    Limbs::<6>::from_words(out)
17359}
17360
17361#[inline]
17362#[must_use]
17363const fn limbs_set_bit0_6(a: Limbs<6>) -> Limbs<6> {
17364    let aw = a.words();
17365    let mut out = [0u64; 6];
17366    let mut i = 0usize;
17367    while i < 6 {
17368        out[i] = aw[i];
17369        i += 1;
17370    }
17371    out[0] |= 1u64;
17372    Limbs::<6>::from_words(out)
17373}
17374
17375#[inline]
17376#[must_use]
17377const fn limbs_bit_msb_6(a: Limbs<6>, msb_index: usize) -> u64 {
17378    let aw = a.words();
17379    let total_bits = 6 * 64;
17380    let lsb_index = total_bits - 1 - msb_index;
17381    let word = lsb_index / 64;
17382    let bit = lsb_index % 64;
17383    (aw[word] >> bit) & 1u64
17384}
17385
17386#[inline]
17387#[must_use]
17388const fn limbs_divmod_6(a: Limbs<6>, b: Limbs<6>) -> (Limbs<6>, Limbs<6>) {
17389    let mut q = Limbs::<6>::zero();
17390    let mut r = Limbs::<6>::zero();
17391    let total_bits = 6 * 64;
17392    let mut i = 0usize;
17393    while i < total_bits {
17394        r = limbs_shl1_6(r);
17395        if limbs_bit_msb_6(a, i) == 1 {
17396            r = limbs_set_bit0_6(r);
17397        }
17398        if limbs_le_6(b, r) {
17399            r = r.wrapping_sub(b);
17400            q = limbs_shl1_6(q);
17401            q = limbs_set_bit0_6(q);
17402        } else {
17403            q = limbs_shl1_6(q);
17404        }
17405        i += 1;
17406    }
17407    (q, r)
17408}
17409
17410#[inline]
17411#[must_use]
17412const fn limbs_div_6(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
17413    let (q, _) = limbs_divmod_6(a, b);
17414    q
17415}
17416
17417#[inline]
17418#[must_use]
17419const fn limbs_mod_6(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
17420    let (_, r) = limbs_divmod_6(a, b);
17421    r
17422}
17423
17424#[inline]
17425#[must_use]
17426const fn limbs_pow_6(base: Limbs<6>, exp: Limbs<6>) -> Limbs<6> {
17427    let mut result = limbs_one_6();
17428    let mut b = base;
17429    let ew = exp.words();
17430    let mut word = 0usize;
17431    while word < 6 {
17432        let mut bit = 0u32;
17433        while bit < 64 {
17434            if ((ew[word] >> bit) & 1u64) == 1u64 {
17435                result = result.wrapping_mul(b);
17436            }
17437            b = b.wrapping_mul(b);
17438            bit += 1;
17439        }
17440        word += 1;
17441    }
17442    result
17443}
17444
17445#[inline]
17446#[must_use]
17447const fn limbs_is_zero_7(a: Limbs<7>) -> bool {
17448    let aw = a.words();
17449    let mut i = 0usize;
17450    while i < 7 {
17451        if aw[i] != 0 {
17452            return false;
17453        }
17454        i += 1;
17455    }
17456    true
17457}
17458
17459#[inline]
17460#[must_use]
17461const fn limbs_shl1_7(a: Limbs<7>) -> Limbs<7> {
17462    let aw = a.words();
17463    let mut out = [0u64; 7];
17464    let mut carry: u64 = 0;
17465    let mut i = 0usize;
17466    while i < 7 {
17467        let v = aw[i];
17468        out[i] = (v << 1) | carry;
17469        carry = v >> 63;
17470        i += 1;
17471    }
17472    Limbs::<7>::from_words(out)
17473}
17474
17475#[inline]
17476#[must_use]
17477const fn limbs_set_bit0_7(a: Limbs<7>) -> Limbs<7> {
17478    let aw = a.words();
17479    let mut out = [0u64; 7];
17480    let mut i = 0usize;
17481    while i < 7 {
17482        out[i] = aw[i];
17483        i += 1;
17484    }
17485    out[0] |= 1u64;
17486    Limbs::<7>::from_words(out)
17487}
17488
17489#[inline]
17490#[must_use]
17491const fn limbs_bit_msb_7(a: Limbs<7>, msb_index: usize) -> u64 {
17492    let aw = a.words();
17493    let total_bits = 7 * 64;
17494    let lsb_index = total_bits - 1 - msb_index;
17495    let word = lsb_index / 64;
17496    let bit = lsb_index % 64;
17497    (aw[word] >> bit) & 1u64
17498}
17499
17500#[inline]
17501#[must_use]
17502const fn limbs_divmod_7(a: Limbs<7>, b: Limbs<7>) -> (Limbs<7>, Limbs<7>) {
17503    let mut q = Limbs::<7>::zero();
17504    let mut r = Limbs::<7>::zero();
17505    let total_bits = 7 * 64;
17506    let mut i = 0usize;
17507    while i < total_bits {
17508        r = limbs_shl1_7(r);
17509        if limbs_bit_msb_7(a, i) == 1 {
17510            r = limbs_set_bit0_7(r);
17511        }
17512        if limbs_le_7(b, r) {
17513            r = r.wrapping_sub(b);
17514            q = limbs_shl1_7(q);
17515            q = limbs_set_bit0_7(q);
17516        } else {
17517            q = limbs_shl1_7(q);
17518        }
17519        i += 1;
17520    }
17521    (q, r)
17522}
17523
17524#[inline]
17525#[must_use]
17526const fn limbs_div_7(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
17527    let (q, _) = limbs_divmod_7(a, b);
17528    q
17529}
17530
17531#[inline]
17532#[must_use]
17533const fn limbs_mod_7(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
17534    let (_, r) = limbs_divmod_7(a, b);
17535    r
17536}
17537
17538#[inline]
17539#[must_use]
17540const fn limbs_pow_7(base: Limbs<7>, exp: Limbs<7>) -> Limbs<7> {
17541    let mut result = limbs_one_7();
17542    let mut b = base;
17543    let ew = exp.words();
17544    let mut word = 0usize;
17545    while word < 7 {
17546        let mut bit = 0u32;
17547        while bit < 64 {
17548            if ((ew[word] >> bit) & 1u64) == 1u64 {
17549                result = result.wrapping_mul(b);
17550            }
17551            b = b.wrapping_mul(b);
17552            bit += 1;
17553        }
17554        word += 1;
17555    }
17556    result
17557}
17558
17559#[inline]
17560#[must_use]
17561const fn limbs_is_zero_8(a: Limbs<8>) -> bool {
17562    let aw = a.words();
17563    let mut i = 0usize;
17564    while i < 8 {
17565        if aw[i] != 0 {
17566            return false;
17567        }
17568        i += 1;
17569    }
17570    true
17571}
17572
17573#[inline]
17574#[must_use]
17575const fn limbs_shl1_8(a: Limbs<8>) -> Limbs<8> {
17576    let aw = a.words();
17577    let mut out = [0u64; 8];
17578    let mut carry: u64 = 0;
17579    let mut i = 0usize;
17580    while i < 8 {
17581        let v = aw[i];
17582        out[i] = (v << 1) | carry;
17583        carry = v >> 63;
17584        i += 1;
17585    }
17586    Limbs::<8>::from_words(out)
17587}
17588
17589#[inline]
17590#[must_use]
17591const fn limbs_set_bit0_8(a: Limbs<8>) -> Limbs<8> {
17592    let aw = a.words();
17593    let mut out = [0u64; 8];
17594    let mut i = 0usize;
17595    while i < 8 {
17596        out[i] = aw[i];
17597        i += 1;
17598    }
17599    out[0] |= 1u64;
17600    Limbs::<8>::from_words(out)
17601}
17602
17603#[inline]
17604#[must_use]
17605const fn limbs_bit_msb_8(a: Limbs<8>, msb_index: usize) -> u64 {
17606    let aw = a.words();
17607    let total_bits = 8 * 64;
17608    let lsb_index = total_bits - 1 - msb_index;
17609    let word = lsb_index / 64;
17610    let bit = lsb_index % 64;
17611    (aw[word] >> bit) & 1u64
17612}
17613
17614#[inline]
17615#[must_use]
17616const fn limbs_divmod_8(a: Limbs<8>, b: Limbs<8>) -> (Limbs<8>, Limbs<8>) {
17617    let mut q = Limbs::<8>::zero();
17618    let mut r = Limbs::<8>::zero();
17619    let total_bits = 8 * 64;
17620    let mut i = 0usize;
17621    while i < total_bits {
17622        r = limbs_shl1_8(r);
17623        if limbs_bit_msb_8(a, i) == 1 {
17624            r = limbs_set_bit0_8(r);
17625        }
17626        if limbs_le_8(b, r) {
17627            r = r.wrapping_sub(b);
17628            q = limbs_shl1_8(q);
17629            q = limbs_set_bit0_8(q);
17630        } else {
17631            q = limbs_shl1_8(q);
17632        }
17633        i += 1;
17634    }
17635    (q, r)
17636}
17637
17638#[inline]
17639#[must_use]
17640const fn limbs_div_8(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
17641    let (q, _) = limbs_divmod_8(a, b);
17642    q
17643}
17644
17645#[inline]
17646#[must_use]
17647const fn limbs_mod_8(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
17648    let (_, r) = limbs_divmod_8(a, b);
17649    r
17650}
17651
17652#[inline]
17653#[must_use]
17654const fn limbs_pow_8(base: Limbs<8>, exp: Limbs<8>) -> Limbs<8> {
17655    let mut result = limbs_one_8();
17656    let mut b = base;
17657    let ew = exp.words();
17658    let mut word = 0usize;
17659    while word < 8 {
17660        let mut bit = 0u32;
17661        while bit < 64 {
17662            if ((ew[word] >> bit) & 1u64) == 1u64 {
17663                result = result.wrapping_mul(b);
17664            }
17665            b = b.wrapping_mul(b);
17666            bit += 1;
17667        }
17668        word += 1;
17669    }
17670    result
17671}
17672
17673#[inline]
17674#[must_use]
17675const fn limbs_is_zero_9(a: Limbs<9>) -> bool {
17676    let aw = a.words();
17677    let mut i = 0usize;
17678    while i < 9 {
17679        if aw[i] != 0 {
17680            return false;
17681        }
17682        i += 1;
17683    }
17684    true
17685}
17686
17687#[inline]
17688#[must_use]
17689const fn limbs_shl1_9(a: Limbs<9>) -> Limbs<9> {
17690    let aw = a.words();
17691    let mut out = [0u64; 9];
17692    let mut carry: u64 = 0;
17693    let mut i = 0usize;
17694    while i < 9 {
17695        let v = aw[i];
17696        out[i] = (v << 1) | carry;
17697        carry = v >> 63;
17698        i += 1;
17699    }
17700    Limbs::<9>::from_words(out)
17701}
17702
17703#[inline]
17704#[must_use]
17705const fn limbs_set_bit0_9(a: Limbs<9>) -> Limbs<9> {
17706    let aw = a.words();
17707    let mut out = [0u64; 9];
17708    let mut i = 0usize;
17709    while i < 9 {
17710        out[i] = aw[i];
17711        i += 1;
17712    }
17713    out[0] |= 1u64;
17714    Limbs::<9>::from_words(out)
17715}
17716
17717#[inline]
17718#[must_use]
17719const fn limbs_bit_msb_9(a: Limbs<9>, msb_index: usize) -> u64 {
17720    let aw = a.words();
17721    let total_bits = 9 * 64;
17722    let lsb_index = total_bits - 1 - msb_index;
17723    let word = lsb_index / 64;
17724    let bit = lsb_index % 64;
17725    (aw[word] >> bit) & 1u64
17726}
17727
17728#[inline]
17729#[must_use]
17730const fn limbs_divmod_9(a: Limbs<9>, b: Limbs<9>) -> (Limbs<9>, Limbs<9>) {
17731    let mut q = Limbs::<9>::zero();
17732    let mut r = Limbs::<9>::zero();
17733    let total_bits = 9 * 64;
17734    let mut i = 0usize;
17735    while i < total_bits {
17736        r = limbs_shl1_9(r);
17737        if limbs_bit_msb_9(a, i) == 1 {
17738            r = limbs_set_bit0_9(r);
17739        }
17740        if limbs_le_9(b, r) {
17741            r = r.wrapping_sub(b);
17742            q = limbs_shl1_9(q);
17743            q = limbs_set_bit0_9(q);
17744        } else {
17745            q = limbs_shl1_9(q);
17746        }
17747        i += 1;
17748    }
17749    (q, r)
17750}
17751
17752#[inline]
17753#[must_use]
17754const fn limbs_div_9(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
17755    let (q, _) = limbs_divmod_9(a, b);
17756    q
17757}
17758
17759#[inline]
17760#[must_use]
17761const fn limbs_mod_9(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
17762    let (_, r) = limbs_divmod_9(a, b);
17763    r
17764}
17765
17766#[inline]
17767#[must_use]
17768const fn limbs_pow_9(base: Limbs<9>, exp: Limbs<9>) -> Limbs<9> {
17769    let mut result = limbs_one_9();
17770    let mut b = base;
17771    let ew = exp.words();
17772    let mut word = 0usize;
17773    while word < 9 {
17774        let mut bit = 0u32;
17775        while bit < 64 {
17776            if ((ew[word] >> bit) & 1u64) == 1u64 {
17777                result = result.wrapping_mul(b);
17778            }
17779            b = b.wrapping_mul(b);
17780            bit += 1;
17781        }
17782        word += 1;
17783    }
17784    result
17785}
17786
17787#[inline]
17788#[must_use]
17789const fn limbs_is_zero_16(a: Limbs<16>) -> bool {
17790    let aw = a.words();
17791    let mut i = 0usize;
17792    while i < 16 {
17793        if aw[i] != 0 {
17794            return false;
17795        }
17796        i += 1;
17797    }
17798    true
17799}
17800
17801#[inline]
17802#[must_use]
17803const fn limbs_shl1_16(a: Limbs<16>) -> Limbs<16> {
17804    let aw = a.words();
17805    let mut out = [0u64; 16];
17806    let mut carry: u64 = 0;
17807    let mut i = 0usize;
17808    while i < 16 {
17809        let v = aw[i];
17810        out[i] = (v << 1) | carry;
17811        carry = v >> 63;
17812        i += 1;
17813    }
17814    Limbs::<16>::from_words(out)
17815}
17816
17817#[inline]
17818#[must_use]
17819const fn limbs_set_bit0_16(a: Limbs<16>) -> Limbs<16> {
17820    let aw = a.words();
17821    let mut out = [0u64; 16];
17822    let mut i = 0usize;
17823    while i < 16 {
17824        out[i] = aw[i];
17825        i += 1;
17826    }
17827    out[0] |= 1u64;
17828    Limbs::<16>::from_words(out)
17829}
17830
17831#[inline]
17832#[must_use]
17833const fn limbs_bit_msb_16(a: Limbs<16>, msb_index: usize) -> u64 {
17834    let aw = a.words();
17835    let total_bits = 16 * 64;
17836    let lsb_index = total_bits - 1 - msb_index;
17837    let word = lsb_index / 64;
17838    let bit = lsb_index % 64;
17839    (aw[word] >> bit) & 1u64
17840}
17841
17842#[inline]
17843#[must_use]
17844const fn limbs_divmod_16(a: Limbs<16>, b: Limbs<16>) -> (Limbs<16>, Limbs<16>) {
17845    let mut q = Limbs::<16>::zero();
17846    let mut r = Limbs::<16>::zero();
17847    let total_bits = 16 * 64;
17848    let mut i = 0usize;
17849    while i < total_bits {
17850        r = limbs_shl1_16(r);
17851        if limbs_bit_msb_16(a, i) == 1 {
17852            r = limbs_set_bit0_16(r);
17853        }
17854        if limbs_le_16(b, r) {
17855            r = r.wrapping_sub(b);
17856            q = limbs_shl1_16(q);
17857            q = limbs_set_bit0_16(q);
17858        } else {
17859            q = limbs_shl1_16(q);
17860        }
17861        i += 1;
17862    }
17863    (q, r)
17864}
17865
17866#[inline]
17867#[must_use]
17868const fn limbs_div_16(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
17869    let (q, _) = limbs_divmod_16(a, b);
17870    q
17871}
17872
17873#[inline]
17874#[must_use]
17875const fn limbs_mod_16(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
17876    let (_, r) = limbs_divmod_16(a, b);
17877    r
17878}
17879
17880#[inline]
17881#[must_use]
17882const fn limbs_pow_16(base: Limbs<16>, exp: Limbs<16>) -> Limbs<16> {
17883    let mut result = limbs_one_16();
17884    let mut b = base;
17885    let ew = exp.words();
17886    let mut word = 0usize;
17887    while word < 16 {
17888        let mut bit = 0u32;
17889        while bit < 64 {
17890            if ((ew[word] >> bit) & 1u64) == 1u64 {
17891                result = result.wrapping_mul(b);
17892            }
17893            b = b.wrapping_mul(b);
17894            bit += 1;
17895        }
17896        word += 1;
17897    }
17898    result
17899}
17900
17901#[inline]
17902#[must_use]
17903const fn limbs_is_zero_32(a: Limbs<32>) -> bool {
17904    let aw = a.words();
17905    let mut i = 0usize;
17906    while i < 32 {
17907        if aw[i] != 0 {
17908            return false;
17909        }
17910        i += 1;
17911    }
17912    true
17913}
17914
17915#[inline]
17916#[must_use]
17917const fn limbs_shl1_32(a: Limbs<32>) -> Limbs<32> {
17918    let aw = a.words();
17919    let mut out = [0u64; 32];
17920    let mut carry: u64 = 0;
17921    let mut i = 0usize;
17922    while i < 32 {
17923        let v = aw[i];
17924        out[i] = (v << 1) | carry;
17925        carry = v >> 63;
17926        i += 1;
17927    }
17928    Limbs::<32>::from_words(out)
17929}
17930
17931#[inline]
17932#[must_use]
17933const fn limbs_set_bit0_32(a: Limbs<32>) -> Limbs<32> {
17934    let aw = a.words();
17935    let mut out = [0u64; 32];
17936    let mut i = 0usize;
17937    while i < 32 {
17938        out[i] = aw[i];
17939        i += 1;
17940    }
17941    out[0] |= 1u64;
17942    Limbs::<32>::from_words(out)
17943}
17944
17945#[inline]
17946#[must_use]
17947const fn limbs_bit_msb_32(a: Limbs<32>, msb_index: usize) -> u64 {
17948    let aw = a.words();
17949    let total_bits = 32 * 64;
17950    let lsb_index = total_bits - 1 - msb_index;
17951    let word = lsb_index / 64;
17952    let bit = lsb_index % 64;
17953    (aw[word] >> bit) & 1u64
17954}
17955
17956#[inline]
17957#[must_use]
17958const fn limbs_divmod_32(a: Limbs<32>, b: Limbs<32>) -> (Limbs<32>, Limbs<32>) {
17959    let mut q = Limbs::<32>::zero();
17960    let mut r = Limbs::<32>::zero();
17961    let total_bits = 32 * 64;
17962    let mut i = 0usize;
17963    while i < total_bits {
17964        r = limbs_shl1_32(r);
17965        if limbs_bit_msb_32(a, i) == 1 {
17966            r = limbs_set_bit0_32(r);
17967        }
17968        if limbs_le_32(b, r) {
17969            r = r.wrapping_sub(b);
17970            q = limbs_shl1_32(q);
17971            q = limbs_set_bit0_32(q);
17972        } else {
17973            q = limbs_shl1_32(q);
17974        }
17975        i += 1;
17976    }
17977    (q, r)
17978}
17979
17980#[inline]
17981#[must_use]
17982const fn limbs_div_32(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
17983    let (q, _) = limbs_divmod_32(a, b);
17984    q
17985}
17986
17987#[inline]
17988#[must_use]
17989const fn limbs_mod_32(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
17990    let (_, r) = limbs_divmod_32(a, b);
17991    r
17992}
17993
17994#[inline]
17995#[must_use]
17996const fn limbs_pow_32(base: Limbs<32>, exp: Limbs<32>) -> Limbs<32> {
17997    let mut result = limbs_one_32();
17998    let mut b = base;
17999    let ew = exp.words();
18000    let mut word = 0usize;
18001    while word < 32 {
18002        let mut bit = 0u32;
18003        while bit < 64 {
18004            if ((ew[word] >> bit) & 1u64) == 1u64 {
18005                result = result.wrapping_mul(b);
18006            }
18007            b = b.wrapping_mul(b);
18008            bit += 1;
18009        }
18010        word += 1;
18011    }
18012    result
18013}
18014
18015#[inline]
18016#[must_use]
18017const fn limbs_is_zero_64(a: Limbs<64>) -> bool {
18018    let aw = a.words();
18019    let mut i = 0usize;
18020    while i < 64 {
18021        if aw[i] != 0 {
18022            return false;
18023        }
18024        i += 1;
18025    }
18026    true
18027}
18028
18029#[inline]
18030#[must_use]
18031const fn limbs_shl1_64(a: Limbs<64>) -> Limbs<64> {
18032    let aw = a.words();
18033    let mut out = [0u64; 64];
18034    let mut carry: u64 = 0;
18035    let mut i = 0usize;
18036    while i < 64 {
18037        let v = aw[i];
18038        out[i] = (v << 1) | carry;
18039        carry = v >> 63;
18040        i += 1;
18041    }
18042    Limbs::<64>::from_words(out)
18043}
18044
18045#[inline]
18046#[must_use]
18047const fn limbs_set_bit0_64(a: Limbs<64>) -> Limbs<64> {
18048    let aw = a.words();
18049    let mut out = [0u64; 64];
18050    let mut i = 0usize;
18051    while i < 64 {
18052        out[i] = aw[i];
18053        i += 1;
18054    }
18055    out[0] |= 1u64;
18056    Limbs::<64>::from_words(out)
18057}
18058
18059#[inline]
18060#[must_use]
18061const fn limbs_bit_msb_64(a: Limbs<64>, msb_index: usize) -> u64 {
18062    let aw = a.words();
18063    let total_bits = 64 * 64;
18064    let lsb_index = total_bits - 1 - msb_index;
18065    let word = lsb_index / 64;
18066    let bit = lsb_index % 64;
18067    (aw[word] >> bit) & 1u64
18068}
18069
18070#[inline]
18071#[must_use]
18072const fn limbs_divmod_64(a: Limbs<64>, b: Limbs<64>) -> (Limbs<64>, Limbs<64>) {
18073    let mut q = Limbs::<64>::zero();
18074    let mut r = Limbs::<64>::zero();
18075    let total_bits = 64 * 64;
18076    let mut i = 0usize;
18077    while i < total_bits {
18078        r = limbs_shl1_64(r);
18079        if limbs_bit_msb_64(a, i) == 1 {
18080            r = limbs_set_bit0_64(r);
18081        }
18082        if limbs_le_64(b, r) {
18083            r = r.wrapping_sub(b);
18084            q = limbs_shl1_64(q);
18085            q = limbs_set_bit0_64(q);
18086        } else {
18087            q = limbs_shl1_64(q);
18088        }
18089        i += 1;
18090    }
18091    (q, r)
18092}
18093
18094#[inline]
18095#[must_use]
18096const fn limbs_div_64(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
18097    let (q, _) = limbs_divmod_64(a, b);
18098    q
18099}
18100
18101#[inline]
18102#[must_use]
18103const fn limbs_mod_64(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
18104    let (_, r) = limbs_divmod_64(a, b);
18105    r
18106}
18107
18108#[inline]
18109#[must_use]
18110const fn limbs_pow_64(base: Limbs<64>, exp: Limbs<64>) -> Limbs<64> {
18111    let mut result = limbs_one_64();
18112    let mut b = base;
18113    let ew = exp.words();
18114    let mut word = 0usize;
18115    while word < 64 {
18116        let mut bit = 0u32;
18117        while bit < 64 {
18118            if ((ew[word] >> bit) & 1u64) == 1u64 {
18119                result = result.wrapping_mul(b);
18120            }
18121            b = b.wrapping_mul(b);
18122            bit += 1;
18123        }
18124        word += 1;
18125    }
18126    result
18127}
18128
18129#[inline]
18130#[must_use]
18131const fn limbs_is_zero_128(a: Limbs<128>) -> bool {
18132    let aw = a.words();
18133    let mut i = 0usize;
18134    while i < 128 {
18135        if aw[i] != 0 {
18136            return false;
18137        }
18138        i += 1;
18139    }
18140    true
18141}
18142
18143#[inline]
18144#[must_use]
18145const fn limbs_shl1_128(a: Limbs<128>) -> Limbs<128> {
18146    let aw = a.words();
18147    let mut out = [0u64; 128];
18148    let mut carry: u64 = 0;
18149    let mut i = 0usize;
18150    while i < 128 {
18151        let v = aw[i];
18152        out[i] = (v << 1) | carry;
18153        carry = v >> 63;
18154        i += 1;
18155    }
18156    Limbs::<128>::from_words(out)
18157}
18158
18159#[inline]
18160#[must_use]
18161const fn limbs_set_bit0_128(a: Limbs<128>) -> Limbs<128> {
18162    let aw = a.words();
18163    let mut out = [0u64; 128];
18164    let mut i = 0usize;
18165    while i < 128 {
18166        out[i] = aw[i];
18167        i += 1;
18168    }
18169    out[0] |= 1u64;
18170    Limbs::<128>::from_words(out)
18171}
18172
18173#[inline]
18174#[must_use]
18175const fn limbs_bit_msb_128(a: Limbs<128>, msb_index: usize) -> u64 {
18176    let aw = a.words();
18177    let total_bits = 128 * 64;
18178    let lsb_index = total_bits - 1 - msb_index;
18179    let word = lsb_index / 64;
18180    let bit = lsb_index % 64;
18181    (aw[word] >> bit) & 1u64
18182}
18183
18184#[inline]
18185#[must_use]
18186const fn limbs_divmod_128(a: Limbs<128>, b: Limbs<128>) -> (Limbs<128>, Limbs<128>) {
18187    let mut q = Limbs::<128>::zero();
18188    let mut r = Limbs::<128>::zero();
18189    let total_bits = 128 * 64;
18190    let mut i = 0usize;
18191    while i < total_bits {
18192        r = limbs_shl1_128(r);
18193        if limbs_bit_msb_128(a, i) == 1 {
18194            r = limbs_set_bit0_128(r);
18195        }
18196        if limbs_le_128(b, r) {
18197            r = r.wrapping_sub(b);
18198            q = limbs_shl1_128(q);
18199            q = limbs_set_bit0_128(q);
18200        } else {
18201            q = limbs_shl1_128(q);
18202        }
18203        i += 1;
18204    }
18205    (q, r)
18206}
18207
18208#[inline]
18209#[must_use]
18210const fn limbs_div_128(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
18211    let (q, _) = limbs_divmod_128(a, b);
18212    q
18213}
18214
18215#[inline]
18216#[must_use]
18217const fn limbs_mod_128(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
18218    let (_, r) = limbs_divmod_128(a, b);
18219    r
18220}
18221
18222#[inline]
18223#[must_use]
18224const fn limbs_pow_128(base: Limbs<128>, exp: Limbs<128>) -> Limbs<128> {
18225    let mut result = limbs_one_128();
18226    let mut b = base;
18227    let ew = exp.words();
18228    let mut word = 0usize;
18229    while word < 128 {
18230        let mut bit = 0u32;
18231        while bit < 64 {
18232            if ((ew[word] >> bit) & 1u64) == 1u64 {
18233                result = result.wrapping_mul(b);
18234            }
18235            b = b.wrapping_mul(b);
18236            bit += 1;
18237        }
18238        word += 1;
18239    }
18240    result
18241}
18242
18243#[inline]
18244#[must_use]
18245const fn limbs_is_zero_192(a: Limbs<192>) -> bool {
18246    let aw = a.words();
18247    let mut i = 0usize;
18248    while i < 192 {
18249        if aw[i] != 0 {
18250            return false;
18251        }
18252        i += 1;
18253    }
18254    true
18255}
18256
18257#[inline]
18258#[must_use]
18259const fn limbs_shl1_192(a: Limbs<192>) -> Limbs<192> {
18260    let aw = a.words();
18261    let mut out = [0u64; 192];
18262    let mut carry: u64 = 0;
18263    let mut i = 0usize;
18264    while i < 192 {
18265        let v = aw[i];
18266        out[i] = (v << 1) | carry;
18267        carry = v >> 63;
18268        i += 1;
18269    }
18270    Limbs::<192>::from_words(out)
18271}
18272
18273#[inline]
18274#[must_use]
18275const fn limbs_set_bit0_192(a: Limbs<192>) -> Limbs<192> {
18276    let aw = a.words();
18277    let mut out = [0u64; 192];
18278    let mut i = 0usize;
18279    while i < 192 {
18280        out[i] = aw[i];
18281        i += 1;
18282    }
18283    out[0] |= 1u64;
18284    Limbs::<192>::from_words(out)
18285}
18286
18287#[inline]
18288#[must_use]
18289const fn limbs_bit_msb_192(a: Limbs<192>, msb_index: usize) -> u64 {
18290    let aw = a.words();
18291    let total_bits = 192 * 64;
18292    let lsb_index = total_bits - 1 - msb_index;
18293    let word = lsb_index / 64;
18294    let bit = lsb_index % 64;
18295    (aw[word] >> bit) & 1u64
18296}
18297
18298#[inline]
18299#[must_use]
18300const fn limbs_divmod_192(a: Limbs<192>, b: Limbs<192>) -> (Limbs<192>, Limbs<192>) {
18301    let mut q = Limbs::<192>::zero();
18302    let mut r = Limbs::<192>::zero();
18303    let total_bits = 192 * 64;
18304    let mut i = 0usize;
18305    while i < total_bits {
18306        r = limbs_shl1_192(r);
18307        if limbs_bit_msb_192(a, i) == 1 {
18308            r = limbs_set_bit0_192(r);
18309        }
18310        if limbs_le_192(b, r) {
18311            r = r.wrapping_sub(b);
18312            q = limbs_shl1_192(q);
18313            q = limbs_set_bit0_192(q);
18314        } else {
18315            q = limbs_shl1_192(q);
18316        }
18317        i += 1;
18318    }
18319    (q, r)
18320}
18321
18322#[inline]
18323#[must_use]
18324const fn limbs_div_192(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
18325    let (q, _) = limbs_divmod_192(a, b);
18326    q
18327}
18328
18329#[inline]
18330#[must_use]
18331const fn limbs_mod_192(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
18332    let (_, r) = limbs_divmod_192(a, b);
18333    r
18334}
18335
18336#[inline]
18337#[must_use]
18338const fn limbs_pow_192(base: Limbs<192>, exp: Limbs<192>) -> Limbs<192> {
18339    let mut result = limbs_one_192();
18340    let mut b = base;
18341    let ew = exp.words();
18342    let mut word = 0usize;
18343    while word < 192 {
18344        let mut bit = 0u32;
18345        while bit < 64 {
18346            if ((ew[word] >> bit) & 1u64) == 1u64 {
18347                result = result.wrapping_mul(b);
18348            }
18349            b = b.wrapping_mul(b);
18350            bit += 1;
18351        }
18352        word += 1;
18353    }
18354    result
18355}
18356
18357#[inline]
18358#[must_use]
18359const fn limbs_is_zero_256(a: Limbs<256>) -> bool {
18360    let aw = a.words();
18361    let mut i = 0usize;
18362    while i < 256 {
18363        if aw[i] != 0 {
18364            return false;
18365        }
18366        i += 1;
18367    }
18368    true
18369}
18370
18371#[inline]
18372#[must_use]
18373const fn limbs_shl1_256(a: Limbs<256>) -> Limbs<256> {
18374    let aw = a.words();
18375    let mut out = [0u64; 256];
18376    let mut carry: u64 = 0;
18377    let mut i = 0usize;
18378    while i < 256 {
18379        let v = aw[i];
18380        out[i] = (v << 1) | carry;
18381        carry = v >> 63;
18382        i += 1;
18383    }
18384    Limbs::<256>::from_words(out)
18385}
18386
18387#[inline]
18388#[must_use]
18389const fn limbs_set_bit0_256(a: Limbs<256>) -> Limbs<256> {
18390    let aw = a.words();
18391    let mut out = [0u64; 256];
18392    let mut i = 0usize;
18393    while i < 256 {
18394        out[i] = aw[i];
18395        i += 1;
18396    }
18397    out[0] |= 1u64;
18398    Limbs::<256>::from_words(out)
18399}
18400
18401#[inline]
18402#[must_use]
18403const fn limbs_bit_msb_256(a: Limbs<256>, msb_index: usize) -> u64 {
18404    let aw = a.words();
18405    let total_bits = 256 * 64;
18406    let lsb_index = total_bits - 1 - msb_index;
18407    let word = lsb_index / 64;
18408    let bit = lsb_index % 64;
18409    (aw[word] >> bit) & 1u64
18410}
18411
18412#[inline]
18413#[must_use]
18414const fn limbs_divmod_256(a: Limbs<256>, b: Limbs<256>) -> (Limbs<256>, Limbs<256>) {
18415    let mut q = Limbs::<256>::zero();
18416    let mut r = Limbs::<256>::zero();
18417    let total_bits = 256 * 64;
18418    let mut i = 0usize;
18419    while i < total_bits {
18420        r = limbs_shl1_256(r);
18421        if limbs_bit_msb_256(a, i) == 1 {
18422            r = limbs_set_bit0_256(r);
18423        }
18424        if limbs_le_256(b, r) {
18425            r = r.wrapping_sub(b);
18426            q = limbs_shl1_256(q);
18427            q = limbs_set_bit0_256(q);
18428        } else {
18429            q = limbs_shl1_256(q);
18430        }
18431        i += 1;
18432    }
18433    (q, r)
18434}
18435
18436#[inline]
18437#[must_use]
18438const fn limbs_div_256(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
18439    let (q, _) = limbs_divmod_256(a, b);
18440    q
18441}
18442
18443#[inline]
18444#[must_use]
18445const fn limbs_mod_256(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
18446    let (_, r) = limbs_divmod_256(a, b);
18447    r
18448}
18449
18450#[inline]
18451#[must_use]
18452const fn limbs_pow_256(base: Limbs<256>, exp: Limbs<256>) -> Limbs<256> {
18453    let mut result = limbs_one_256();
18454    let mut b = base;
18455    let ew = exp.words();
18456    let mut word = 0usize;
18457    while word < 256 {
18458        let mut bit = 0u32;
18459        while bit < 64 {
18460            if ((ew[word] >> bit) & 1u64) == 1u64 {
18461                result = result.wrapping_mul(b);
18462            }
18463            b = b.wrapping_mul(b);
18464            bit += 1;
18465        }
18466        word += 1;
18467    }
18468    result
18469}
18470
18471#[inline]
18472#[must_use]
18473const fn limbs_is_zero_512(a: Limbs<512>) -> bool {
18474    let aw = a.words();
18475    let mut i = 0usize;
18476    while i < 512 {
18477        if aw[i] != 0 {
18478            return false;
18479        }
18480        i += 1;
18481    }
18482    true
18483}
18484
18485#[inline]
18486#[must_use]
18487const fn limbs_shl1_512(a: Limbs<512>) -> Limbs<512> {
18488    let aw = a.words();
18489    let mut out = [0u64; 512];
18490    let mut carry: u64 = 0;
18491    let mut i = 0usize;
18492    while i < 512 {
18493        let v = aw[i];
18494        out[i] = (v << 1) | carry;
18495        carry = v >> 63;
18496        i += 1;
18497    }
18498    Limbs::<512>::from_words(out)
18499}
18500
18501#[inline]
18502#[must_use]
18503const fn limbs_set_bit0_512(a: Limbs<512>) -> Limbs<512> {
18504    let aw = a.words();
18505    let mut out = [0u64; 512];
18506    let mut i = 0usize;
18507    while i < 512 {
18508        out[i] = aw[i];
18509        i += 1;
18510    }
18511    out[0] |= 1u64;
18512    Limbs::<512>::from_words(out)
18513}
18514
18515#[inline]
18516#[must_use]
18517const fn limbs_bit_msb_512(a: Limbs<512>, msb_index: usize) -> u64 {
18518    let aw = a.words();
18519    let total_bits = 512 * 64;
18520    let lsb_index = total_bits - 1 - msb_index;
18521    let word = lsb_index / 64;
18522    let bit = lsb_index % 64;
18523    (aw[word] >> bit) & 1u64
18524}
18525
18526#[inline]
18527#[must_use]
18528const fn limbs_divmod_512(a: Limbs<512>, b: Limbs<512>) -> (Limbs<512>, Limbs<512>) {
18529    let mut q = Limbs::<512>::zero();
18530    let mut r = Limbs::<512>::zero();
18531    let total_bits = 512 * 64;
18532    let mut i = 0usize;
18533    while i < total_bits {
18534        r = limbs_shl1_512(r);
18535        if limbs_bit_msb_512(a, i) == 1 {
18536            r = limbs_set_bit0_512(r);
18537        }
18538        if limbs_le_512(b, r) {
18539            r = r.wrapping_sub(b);
18540            q = limbs_shl1_512(q);
18541            q = limbs_set_bit0_512(q);
18542        } else {
18543            q = limbs_shl1_512(q);
18544        }
18545        i += 1;
18546    }
18547    (q, r)
18548}
18549
18550#[inline]
18551#[must_use]
18552const fn limbs_div_512(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
18553    let (q, _) = limbs_divmod_512(a, b);
18554    q
18555}
18556
18557#[inline]
18558#[must_use]
18559const fn limbs_mod_512(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
18560    let (_, r) = limbs_divmod_512(a, b);
18561    r
18562}
18563
18564#[inline]
18565#[must_use]
18566const fn limbs_pow_512(base: Limbs<512>, exp: Limbs<512>) -> Limbs<512> {
18567    let mut result = limbs_one_512();
18568    let mut b = base;
18569    let ew = exp.words();
18570    let mut word = 0usize;
18571    while word < 512 {
18572        let mut bit = 0u32;
18573        while bit < 64 {
18574            if ((ew[word] >> bit) & 1u64) == 1u64 {
18575                result = result.wrapping_mul(b);
18576            }
18577            b = b.wrapping_mul(b);
18578            bit += 1;
18579        }
18580        word += 1;
18581    }
18582    result
18583}
18584
18585/// Sealed marker trait for fragment classifiers (Is2SatShape, IsHornShape,
18586/// IsResidualFragment) emitted parametrically from the predicate individuals
18587/// referenced by `predicate:InhabitanceDispatchTable`.
18588pub trait FragmentMarker: fragment_sealed::Sealed {}
18589
18590mod fragment_sealed {
18591    /// Private supertrait.
18592    pub trait Sealed {}
18593    impl Sealed for super::Is2SatShape {}
18594    impl Sealed for super::IsHornShape {}
18595    impl Sealed for super::IsResidualFragment {}
18596}
18597
18598/// Fragment marker for `predicate:Is2SatShape`. Zero-sized.
18599#[derive(Debug, Default, Clone, Copy)]
18600pub struct Is2SatShape;
18601impl FragmentMarker for Is2SatShape {}
18602
18603/// Fragment marker for `predicate:IsHornShape`. Zero-sized.
18604#[derive(Debug, Default, Clone, Copy)]
18605pub struct IsHornShape;
18606impl FragmentMarker for IsHornShape {}
18607
18608/// Fragment marker for `predicate:IsResidualFragment`. Zero-sized.
18609#[derive(Debug, Default, Clone, Copy)]
18610pub struct IsResidualFragment;
18611impl FragmentMarker for IsResidualFragment {}
18612
18613/// A single dispatch rule entry pairing a predicate IRI, a target resolver
18614/// name, and an evaluation priority.
18615#[derive(Debug, Clone, Copy)]
18616pub struct DispatchRule {
18617    /// IRI of the predicate that selects this rule.
18618    pub predicate_iri: &'static str,
18619    /// IRI of the target resolver class invoked when the predicate holds.
18620    pub target_resolver_iri: &'static str,
18621    /// Evaluation order; lower values evaluate first.
18622    pub priority: u32,
18623}
18624
18625/// A static dispatch table — an ordered slice of `DispatchRule` entries.
18626pub type DispatchTable = &'static [DispatchRule];
18627
18628/// v0.2.1 dispatch table generated from `predicate:InhabitanceDispatchTable`.
18629pub const INHABITANCE_DISPATCH_TABLE: DispatchTable = &[
18630    DispatchRule {
18631        predicate_iri: "https://uor.foundation/predicate/Is2SatShape",
18632        target_resolver_iri: "https://uor.foundation/resolver/TwoSatDecider",
18633        priority: 0,
18634    },
18635    DispatchRule {
18636        predicate_iri: "https://uor.foundation/predicate/IsHornShape",
18637        target_resolver_iri: "https://uor.foundation/resolver/HornSatDecider",
18638        priority: 1,
18639    },
18640    DispatchRule {
18641        predicate_iri: "https://uor.foundation/predicate/IsResidualFragment",
18642        target_resolver_iri: "https://uor.foundation/resolver/ResidualVerdictResolver",
18643        priority: 2,
18644    },
18645];
18646
18647/// v0.2.1 `Deref` impl for `Validated<T: OntologyTarget>` so consumers can call
18648/// certificate methods directly: `cert.target_level()` rather than
18649/// `cert.inner().target_level()`. The bound `T: OntologyTarget` keeps the
18650/// auto-deref scoped to foundation-produced types.
18651impl<T: OntologyTarget> core::ops::Deref for Validated<T> {
18652    type Target = T;
18653    #[inline]
18654    fn deref(&self) -> &T {
18655        &self.inner
18656    }
18657}
18658
18659mod bound_constraint_sealed {
18660    /// Sealed supertrait for the closed Observable catalogue.
18661    pub trait ObservableSealed {}
18662    /// Sealed supertrait for the closed BoundShape catalogue.
18663    pub trait BoundShapeSealed {}
18664}
18665
18666/// Sealed marker trait identifying the closed catalogue of observables
18667/// admissible in BoundConstraint. Implemented by unit structs emitted
18668/// below per `observable:Observable` subclass referenced by a
18669/// BoundConstraint kind individual.
18670pub trait Observable: bound_constraint_sealed::ObservableSealed {
18671    /// Ontology IRI of this observable class.
18672    const IRI: &'static str;
18673}
18674
18675/// Sealed marker trait identifying the closed catalogue of bound shapes.
18676/// Exactly six individuals: EqualBound, LessEqBound, GreaterEqBound,
18677/// RangeContainBound, ResidueClassBound, AffineEqualBound.
18678pub trait BoundShape: bound_constraint_sealed::BoundShapeSealed {
18679    /// Ontology IRI of this bound shape individual.
18680    const IRI: &'static str;
18681}
18682
18683/// Observes a Datum's value modulo a configurable modulus.
18684#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18685pub struct ValueModObservable;
18686impl bound_constraint_sealed::ObservableSealed for ValueModObservable {}
18687impl Observable for ValueModObservable {
18688    const IRI: &'static str = "https://uor.foundation/observable/ValueModObservable";
18689}
18690
18691/// Distance between two ring elements under the Hamming metric.
18692#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18693pub struct HammingMetric;
18694impl bound_constraint_sealed::ObservableSealed for HammingMetric {}
18695impl Observable for HammingMetric {
18696    const IRI: &'static str = "https://uor.foundation/observable/HammingMetric";
18697}
18698
18699/// Observes the derivation depth of a Datum.
18700#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18701pub struct DerivationDepthObservable;
18702impl bound_constraint_sealed::ObservableSealed for DerivationDepthObservable {}
18703impl Observable for DerivationDepthObservable {
18704    const IRI: &'static str = "https://uor.foundation/derivation/DerivationDepthObservable";
18705}
18706
18707/// Observes the carry depth of a Datum in the W₂ tower.
18708#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18709pub struct CarryDepthObservable;
18710impl bound_constraint_sealed::ObservableSealed for CarryDepthObservable {}
18711impl Observable for CarryDepthObservable {
18712    const IRI: &'static str = "https://uor.foundation/carry/CarryDepthObservable";
18713}
18714
18715/// Observes the free-rank of the partition associated with a Datum.
18716#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18717pub struct FreeRankObservable;
18718impl bound_constraint_sealed::ObservableSealed for FreeRankObservable {}
18719impl Observable for FreeRankObservable {
18720    const IRI: &'static str = "https://uor.foundation/partition/FreeRankObservable";
18721}
18722
18723/// Predicate form: `observable(datum) == target`.
18724#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18725pub struct EqualBound;
18726impl bound_constraint_sealed::BoundShapeSealed for EqualBound {}
18727impl BoundShape for EqualBound {
18728    const IRI: &'static str = "https://uor.foundation/type/EqualBound";
18729}
18730
18731/// Predicate form: `observable(datum) <= bound`.
18732#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18733pub struct LessEqBound;
18734impl bound_constraint_sealed::BoundShapeSealed for LessEqBound {}
18735impl BoundShape for LessEqBound {
18736    const IRI: &'static str = "https://uor.foundation/type/LessEqBound";
18737}
18738
18739/// Predicate form: `observable(datum) >= bound`.
18740#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18741pub struct GreaterEqBound;
18742impl bound_constraint_sealed::BoundShapeSealed for GreaterEqBound {}
18743impl BoundShape for GreaterEqBound {
18744    const IRI: &'static str = "https://uor.foundation/type/GreaterEqBound";
18745}
18746
18747/// Predicate form: `lo <= observable(datum) <= hi`.
18748#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18749pub struct RangeContainBound;
18750impl bound_constraint_sealed::BoundShapeSealed for RangeContainBound {}
18751impl BoundShape for RangeContainBound {
18752    const IRI: &'static str = "https://uor.foundation/type/RangeContainBound";
18753}
18754
18755/// Predicate form: `observable(datum) ≡ residue (mod modulus)`.
18756#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18757pub struct ResidueClassBound;
18758impl bound_constraint_sealed::BoundShapeSealed for ResidueClassBound {}
18759impl BoundShape for ResidueClassBound {
18760    const IRI: &'static str = "https://uor.foundation/type/ResidueClassBound";
18761}
18762
18763/// Predicate form: `observable(datum) == offset + affine combination`.
18764#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18765pub struct AffineEqualBound;
18766impl bound_constraint_sealed::BoundShapeSealed for AffineEqualBound {}
18767impl BoundShape for AffineEqualBound {
18768    const IRI: &'static str = "https://uor.foundation/type/AffineEqualBound";
18769}
18770
18771/// Parameter value type for `BoundConstraint` arguments.
18772/// Sealed enum over the closed set of primitive kinds the bound-shape
18773/// catalogue requires. No heap, no `String`.
18774#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18775pub enum BoundArgValue {
18776    /// Unsigned 64-bit integer.
18777    U64(u64),
18778    /// Signed 64-bit integer.
18779    I64(i64),
18780    /// Fixed 32-byte content-addressed value.
18781    Bytes32([u8; 32]),
18782}
18783
18784/// Fixed-size arguments carrier for a `BoundConstraint`.
18785/// Holds up to eight `(name, value)` pairs inline. The closed
18786/// bound-shape catalogue requires at most three parameters per kind;
18787/// the extra slots are reserved for future kind additions without
18788/// changing the carrier layout.
18789#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18790pub struct BoundArguments {
18791    entries: [Option<BoundArgEntry>; 8],
18792}
18793
18794/// A single named parameter in a `BoundArguments` table.
18795#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18796pub struct BoundArgEntry {
18797    /// Parameter name (a `&'static str` intentional over heap-owned).
18798    pub name: &'static str,
18799    /// Parameter value.
18800    pub value: BoundArgValue,
18801}
18802
18803impl BoundArguments {
18804    /// Construct an empty argument table.
18805    #[inline]
18806    #[must_use]
18807    pub const fn empty() -> Self {
18808        Self { entries: [None; 8] }
18809    }
18810
18811    /// Construct a table with a single `(name, value)` pair.
18812    #[inline]
18813    #[must_use]
18814    pub const fn single(name: &'static str, value: BoundArgValue) -> Self {
18815        let mut entries = [None; 8];
18816        entries[0] = Some(BoundArgEntry { name, value });
18817        Self { entries }
18818    }
18819
18820    /// Construct a table with two `(name, value)` pairs.
18821    #[inline]
18822    #[must_use]
18823    pub const fn pair(
18824        first: (&'static str, BoundArgValue),
18825        second: (&'static str, BoundArgValue),
18826    ) -> Self {
18827        let mut entries = [None; 8];
18828        entries[0] = Some(BoundArgEntry {
18829            name: first.0,
18830            value: first.1,
18831        });
18832        entries[1] = Some(BoundArgEntry {
18833            name: second.0,
18834            value: second.1,
18835        });
18836        Self { entries }
18837    }
18838
18839    /// Access the stored entries.
18840    #[inline]
18841    #[must_use]
18842    pub const fn entries(&self) -> &[Option<BoundArgEntry>; 8] {
18843        &self.entries
18844    }
18845}
18846
18847/// Parametric constraint carrier (v0.2.2 Phase D).
18848/// Generic over `O: Observable` and `B: BoundShape`. The seven
18849/// legacy constraint kinds are preserved as type aliases over this
18850/// carrier; see `ResidueConstraint`, `HammingConstraint`, etc. below.
18851#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18852pub struct BoundConstraint<O: Observable, B: BoundShape> {
18853    observable: O,
18854    bound: B,
18855    args: BoundArguments,
18856    _sealed: (),
18857}
18858
18859impl<O: Observable, B: BoundShape> BoundConstraint<O, B> {
18860    /// Crate-internal constructor. Downstream obtains values through
18861    /// the per-type-alias `pub const fn new` constructors.
18862    #[inline]
18863    #[must_use]
18864    pub(crate) const fn from_parts(observable: O, bound: B, args: BoundArguments) -> Self {
18865        Self {
18866            observable,
18867            bound,
18868            args,
18869            _sealed: (),
18870        }
18871    }
18872
18873    /// Access the bound observable.
18874    #[inline]
18875    #[must_use]
18876    pub const fn observable(&self) -> &O {
18877        &self.observable
18878    }
18879
18880    /// Access the bound shape.
18881    #[inline]
18882    #[must_use]
18883    pub const fn bound(&self) -> &B {
18884        &self.bound
18885    }
18886
18887    /// Access the bound arguments.
18888    #[inline]
18889    #[must_use]
18890    pub const fn args(&self) -> &BoundArguments {
18891        &self.args
18892    }
18893}
18894
18895/// Parametric conjunction of `BoundConstraint` kinds (v0.2.2 Phase D).
18896/// Replaces the v0.2.1 `CompositeConstraint` enumeration; the legacy
18897/// name survives as the type alias `CompositeConstraint<N>` below.
18898#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18899pub struct Conjunction<const N: usize> {
18900    len: usize,
18901    _sealed: (),
18902}
18903
18904impl<const N: usize> Conjunction<N> {
18905    /// Construct a new Conjunction with `len` conjuncts.
18906    #[inline]
18907    #[must_use]
18908    pub const fn new(len: usize) -> Self {
18909        Self { len, _sealed: () }
18910    }
18911
18912    /// The number of conjuncts in this Conjunction.
18913    #[inline]
18914    #[must_use]
18915    pub const fn len(&self) -> usize {
18916        self.len
18917    }
18918
18919    /// Whether the Conjunction is empty.
18920    #[inline]
18921    #[must_use]
18922    pub const fn is_empty(&self) -> bool {
18923        self.len == 0
18924    }
18925}
18926
18927/// v0.2.1 legacy type alias: a `BoundConstraint` kind asserting
18928/// residue-class membership (`value mod m == r`).
18929pub type ResidueConstraint = BoundConstraint<ValueModObservable, ResidueClassBound>;
18930
18931impl ResidueConstraint {
18932    /// Construct a residue constraint with the given modulus and residue.
18933    #[inline]
18934    #[must_use]
18935    pub const fn new(modulus: u64, residue: u64) -> Self {
18936        let args = BoundArguments::pair(
18937            ("modulus", BoundArgValue::U64(modulus)),
18938            ("residue", BoundArgValue::U64(residue)),
18939        );
18940        BoundConstraint::from_parts(ValueModObservable, ResidueClassBound, args)
18941    }
18942}
18943
18944/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18945/// Hamming weight of the Datum (`weight <= bound`).
18946pub type HammingConstraint = BoundConstraint<HammingMetric, LessEqBound>;
18947
18948impl HammingConstraint {
18949    /// Construct a Hamming constraint with the given upper bound.
18950    #[inline]
18951    #[must_use]
18952    pub const fn new(bound: u64) -> Self {
18953        let args = BoundArguments::single("bound", BoundArgValue::U64(bound));
18954        BoundConstraint::from_parts(HammingMetric, LessEqBound, args)
18955    }
18956}
18957
18958/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18959/// derivation depth of the Datum.
18960pub type DepthConstraint = BoundConstraint<DerivationDepthObservable, LessEqBound>;
18961
18962impl DepthConstraint {
18963    /// Construct a depth constraint with min and max depths.
18964    #[inline]
18965    #[must_use]
18966    pub const fn new(min_depth: u64, max_depth: u64) -> Self {
18967        let args = BoundArguments::pair(
18968            ("min_depth", BoundArgValue::U64(min_depth)),
18969            ("max_depth", BoundArgValue::U64(max_depth)),
18970        );
18971        BoundConstraint::from_parts(DerivationDepthObservable, LessEqBound, args)
18972    }
18973}
18974
18975/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18976/// carry depth of the Datum in the W₂ tower.
18977pub type CarryConstraint = BoundConstraint<CarryDepthObservable, LessEqBound>;
18978
18979impl CarryConstraint {
18980    /// Construct a carry constraint with the given upper bound.
18981    #[inline]
18982    #[must_use]
18983    pub const fn new(bound: u64) -> Self {
18984        let args = BoundArguments::single("bound", BoundArgValue::U64(bound));
18985        BoundConstraint::from_parts(CarryDepthObservable, LessEqBound, args)
18986    }
18987}
18988
18989/// v0.2.1 legacy type alias: a `BoundConstraint` kind pinning a
18990/// single site coordinate.
18991pub type SiteConstraint = BoundConstraint<FreeRankObservable, LessEqBound>;
18992
18993impl SiteConstraint {
18994    /// Construct a site constraint with the given site index.
18995    #[inline]
18996    #[must_use]
18997    pub const fn new(site_index: u64) -> Self {
18998        let args = BoundArguments::single("site_index", BoundArgValue::U64(site_index));
18999        BoundConstraint::from_parts(FreeRankObservable, LessEqBound, args)
19000    }
19001}
19002
19003/// v0.2.1 legacy type alias: a `BoundConstraint` kind pinning an
19004/// affine relationship on the Datum's value projection.
19005pub type AffineConstraint = BoundConstraint<ValueModObservable, AffineEqualBound>;
19006
19007impl AffineConstraint {
19008    /// Construct an affine constraint with the given offset.
19009    #[inline]
19010    #[must_use]
19011    pub const fn new(offset: u64) -> Self {
19012        let args = BoundArguments::single("offset", BoundArgValue::U64(offset));
19013        BoundConstraint::from_parts(ValueModObservable, AffineEqualBound, args)
19014    }
19015}
19016
19017/// v0.2.1 legacy type alias: a `Conjunction` over `N` BoundConstraint
19018/// kinds (`CompositeConstraint<3>` = 3-way conjunction).
19019pub type CompositeConstraint<const N: usize> = Conjunction<N>;
19020
19021/// v0.2.2 Phase E: sealed query handle.
19022#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19023pub struct Query {
19024    address: ContentAddress,
19025    _sealed: (),
19026}
19027
19028impl Query {
19029    /// Returns the content-hashed query address.
19030    #[inline]
19031    #[must_use]
19032    pub const fn address(&self) -> ContentAddress {
19033        self.address
19034    }
19035
19036    /// Crate-internal constructor.
19037    #[inline]
19038    #[must_use]
19039    #[allow(dead_code)]
19040    pub(crate) const fn new(address: ContentAddress) -> Self {
19041        Self {
19042            address,
19043            _sealed: (),
19044        }
19045    }
19046}
19047
19048/// v0.2.2 Phase E: typed query coordinate parametric over WittLevel.
19049#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19050pub struct Coordinate<L> {
19051    stratum: u64,
19052    spectrum: u64,
19053    address: u64,
19054    _level: PhantomData<L>,
19055    _sealed: (),
19056}
19057
19058impl<L> Coordinate<L> {
19059    /// Returns the stratum coordinate.
19060    #[inline]
19061    #[must_use]
19062    pub const fn stratum(&self) -> u64 {
19063        self.stratum
19064    }
19065
19066    /// Returns the spectrum coordinate.
19067    #[inline]
19068    #[must_use]
19069    pub const fn spectrum(&self) -> u64 {
19070        self.spectrum
19071    }
19072
19073    /// Returns the address coordinate.
19074    #[inline]
19075    #[must_use]
19076    pub const fn address(&self) -> u64 {
19077        self.address
19078    }
19079
19080    /// Crate-internal constructor.
19081    #[inline]
19082    #[must_use]
19083    #[allow(dead_code)]
19084    pub(crate) const fn new(stratum: u64, spectrum: u64, address: u64) -> Self {
19085        Self {
19086            stratum,
19087            spectrum,
19088            address,
19089            _level: PhantomData,
19090            _sealed: (),
19091        }
19092    }
19093}
19094
19095/// v0.2.2 Phase E: sealed binding query handle.
19096#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19097pub struct BindingQuery {
19098    address: ContentAddress,
19099    _sealed: (),
19100}
19101
19102impl BindingQuery {
19103    /// Returns the content-hashed binding query address.
19104    #[inline]
19105    #[must_use]
19106    pub const fn address(&self) -> ContentAddress {
19107        self.address
19108    }
19109
19110    /// Crate-internal constructor.
19111    #[inline]
19112    #[must_use]
19113    #[allow(dead_code)]
19114    pub(crate) const fn new(address: ContentAddress) -> Self {
19115        Self {
19116            address,
19117            _sealed: (),
19118        }
19119    }
19120}
19121
19122/// v0.2.2 Phase E: sealed Partition handle over the bridge:partition
19123/// component classification produced during grounding.
19124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19125pub struct Partition {
19126    component: PartitionComponent,
19127    _sealed: (),
19128}
19129
19130impl Partition {
19131    /// Returns the component classification.
19132    #[inline]
19133    #[must_use]
19134    pub const fn component(&self) -> PartitionComponent {
19135        self.component
19136    }
19137
19138    /// Crate-internal constructor.
19139    #[inline]
19140    #[must_use]
19141    #[allow(dead_code)]
19142    pub(crate) const fn new(component: PartitionComponent) -> Self {
19143        Self {
19144            component,
19145            _sealed: (),
19146        }
19147    }
19148}
19149
19150/// v0.2.2 Phase E: a single event in a derivation Trace.
19151/// Fixed-size event; content-addressed so Trace replays are stable
19152/// across builds. The verifier in `uor-foundation-verify` (Phase H)
19153/// reconstructs the witness chain by walking a `Trace` iterator.
19154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19155pub struct TraceEvent {
19156    /// Step index in the derivation.
19157    step_index: u32,
19158    /// Primitive op applied at this step.
19159    op: PrimitiveOp,
19160    /// Content-hashed target address the op produced.
19161    target: ContentAddress,
19162    /// Sealing marker.
19163    _sealed: (),
19164}
19165
19166impl TraceEvent {
19167    /// Returns the step index.
19168    #[inline]
19169    #[must_use]
19170    pub const fn step_index(&self) -> u32 {
19171        self.step_index
19172    }
19173
19174    /// Returns the primitive op applied at this step.
19175    #[inline]
19176    #[must_use]
19177    pub const fn op(&self) -> PrimitiveOp {
19178        self.op
19179    }
19180
19181    /// Returns the content-hashed target address.
19182    #[inline]
19183    #[must_use]
19184    pub const fn target(&self) -> ContentAddress {
19185        self.target
19186    }
19187
19188    /// Crate-internal constructor.
19189    #[inline]
19190    #[must_use]
19191    #[allow(dead_code)]
19192    pub(crate) const fn new(step_index: u32, op: PrimitiveOp, target: ContentAddress) -> Self {
19193        Self {
19194            step_index,
19195            op,
19196            target,
19197            _sealed: (),
19198        }
19199    }
19200}
19201
19202/// Fixed-capacity derivation trace. Holds up to `TR_MAX` events inline;
19203/// no heap. Produced by `Derivation::replay()` and consumed by
19204/// `uor-foundation-verify`. `TR_MAX` is the const-generic that carries
19205/// the application's selected `<MyBounds as HostBounds>::TRACE_MAX_EVENTS`;
19206/// the default const-generic resolves to the conventional 256.
19207/// Carries `witt_level_bits` and `content_fingerprint` so `verify_trace`
19208/// can reconstruct the source `GroundingCertificate` via structural-
19209/// validation + fingerprint passthrough (no hash recomputation).
19210#[derive(Debug, Clone, Copy)]
19211pub struct Trace<const TR_MAX: usize = 256> {
19212    events: [Option<TraceEvent>; TR_MAX],
19213    len: u16,
19214    /// Witt level the source grounding was minted at, packed
19215    /// by `Derivation::replay` from the parent `Grounded::witt_level_bits`.
19216    /// `verify_trace` reads this back to populate the certificate.
19217    witt_level_bits: u16,
19218    /// Parametric content fingerprint of the source unit's full state,
19219    /// computed at grounding time by the consumer-supplied `Hasher` and
19220    /// packed in by `Derivation::replay`. `verify_trace` passes it through
19221    /// unchanged. The fingerprint's `FP_MAX` follows the application's
19222    /// selected `<MyBounds as HostBounds>::FINGERPRINT_MAX_BYTES`; this
19223    /// field uses the default-bound `ContentFingerprint`.
19224    content_fingerprint: ContentFingerprint,
19225    _sealed: (),
19226}
19227
19228impl<const TR_MAX: usize> Trace<TR_MAX> {
19229    /// An empty Trace.
19230    #[inline]
19231    #[must_use]
19232    pub const fn empty() -> Self {
19233        Self {
19234            events: [None; TR_MAX],
19235            len: 0,
19236            witt_level_bits: 0,
19237            content_fingerprint: ContentFingerprint::zero(),
19238            _sealed: (),
19239        }
19240    }
19241
19242    /// Crate-internal ctor for `Derivation::replay()` only.
19243    /// Bypasses validation because `replay()` constructs events from
19244    /// foundation-guaranteed-valid state (monotonic, contiguous, non-zero
19245    /// seed). No public path reaches this constructor; downstream uses the
19246    /// validating `try_from_events` instead.
19247    #[inline]
19248    #[must_use]
19249    #[allow(dead_code)]
19250    pub(crate) const fn from_replay_events_const(
19251        events: [Option<TraceEvent>; TR_MAX],
19252        len: u16,
19253        witt_level_bits: u16,
19254        content_fingerprint: ContentFingerprint,
19255    ) -> Self {
19256        Self {
19257            events,
19258            len,
19259            witt_level_bits,
19260            content_fingerprint,
19261            _sealed: (),
19262        }
19263    }
19264
19265    /// Number of events recorded.
19266    #[inline]
19267    #[must_use]
19268    pub const fn len(&self) -> u16 {
19269        self.len
19270    }
19271
19272    /// Whether the Trace is empty.
19273    #[inline]
19274    #[must_use]
19275    pub const fn is_empty(&self) -> bool {
19276        self.len == 0
19277    }
19278
19279    /// Access the event at the given index, or `None` if out of range.
19280    #[inline]
19281    #[must_use]
19282    pub fn event(&self, index: usize) -> Option<&TraceEvent> {
19283        self.events.get(index).and_then(|e| e.as_ref())
19284    }
19285
19286    /// v0.2.2 T5: returns the Witt level the source grounding was minted at.
19287    /// Carried through replay so `verify_trace` can populate the certificate.
19288    #[inline]
19289    #[must_use]
19290    pub const fn witt_level_bits(&self) -> u16 {
19291        self.witt_level_bits
19292    }
19293
19294    /// v0.2.2 T5: returns the parametric content fingerprint of the source
19295    /// unit, computed at grounding time by the consumer-supplied `Hasher`.
19296    /// `verify_trace` passes this through unchanged into the re-derived
19297    /// certificate, upholding the round-trip property.
19298    #[inline]
19299    #[must_use]
19300    pub const fn content_fingerprint(&self) -> ContentFingerprint {
19301        self.content_fingerprint
19302    }
19303
19304    /// Validating constructor. Checks every invariant the verify path
19305    /// relies on: events are contiguous from index 0, no event has a zero
19306    /// target, and the slice fits within `TR_MAX` events.
19307    /// # Errors
19308    /// - `ReplayError::EmptyTrace` if `events.is_empty()`.
19309    /// - `ReplayError::CapacityExceeded { declared, provided }` if the
19310    ///   slice exceeds `TR_MAX`.
19311    /// - `ReplayError::OutOfOrderEvent { index }` if the event at `index`
19312    ///   has a `step_index` not equal to `index` (strict contiguity).
19313    /// - `ReplayError::ZeroTarget { index }` if any event carries a zero
19314    ///   `ContentAddress` target.
19315    pub fn try_from_events(
19316        events: &[TraceEvent],
19317        witt_level_bits: u16,
19318        content_fingerprint: ContentFingerprint,
19319    ) -> Result<Self, ReplayError> {
19320        if events.is_empty() {
19321            return Err(ReplayError::EmptyTrace);
19322        }
19323        if events.len() > TR_MAX {
19324            return Err(ReplayError::CapacityExceeded {
19325                declared: TR_MAX as u16,
19326                provided: events.len() as u32,
19327            });
19328        }
19329        let mut i = 0usize;
19330        while i < events.len() {
19331            let e = &events[i];
19332            if e.step_index() as usize != i {
19333                return Err(ReplayError::OutOfOrderEvent { index: i });
19334            }
19335            if e.target().is_zero() {
19336                return Err(ReplayError::ZeroTarget { index: i });
19337            }
19338            i += 1;
19339        }
19340        let mut arr = [None; TR_MAX];
19341        let mut j = 0usize;
19342        while j < events.len() {
19343            arr[j] = Some(events[j]);
19344            j += 1;
19345        }
19346        Ok(Self {
19347            events: arr,
19348            len: events.len() as u16,
19349            witt_level_bits,
19350            content_fingerprint,
19351            _sealed: (),
19352        })
19353    }
19354}
19355
19356impl<const TR_MAX: usize> Default for Trace<TR_MAX> {
19357    #[inline]
19358    fn default() -> Self {
19359        Self::empty()
19360    }
19361}
19362
19363/// v0.2.2 Phase E / T2.6: `Derivation::replay()` produces a content-addressed
19364/// Trace the verifier can re-walk without invoking the deciders. The trace
19365/// length matches the derivation's `step_count()`, and each event's
19366/// `step_index` reflects its position in the derivation.
19367impl Derivation {
19368    /// Replay this derivation as a fixed-size `Trace<TR_MAX>` whose length matches
19369    /// `self.step_count()` (capped at the application's `<HostBounds>::TRACE_MAX_EVENTS`).
19370    /// Callers either annotate the binding (`let trace: Trace = ...;` picks
19371    /// `Trace`'s default `TR_MAX` of 256) or use turbofish (`derivation.replay::<1024>()`).
19372    /// # Example
19373    /// ```no_run
19374    /// use uor_foundation::enforcement::{
19375    ///     replay, CompileUnitBuilder, ConstrainedTypeInput, Grounded, Term, Trace,
19376    /// };
19377    /// use uor_foundation::pipeline::run;
19378    /// use uor_foundation::{VerificationDomain, WittLevel};
19379    /// # use uor_foundation::enforcement::Hasher;
19380    /// # struct H; impl Hasher for H {
19381    /// #     const OUTPUT_BYTES: usize = 16;
19382    /// #     fn initial() -> Self { Self }
19383    /// #     fn fold_byte(self, _: u8) -> Self { self }
19384    /// #     fn finalize(self) -> [u8; 32] { [0; 32] } }
19385    /// // ADR-060: `Term`/`Grounded` carry an `INLINE_BYTES` const-generic the
19386    /// // application derives from its `HostBounds`; fix a concrete width and
19387    /// // thread it through `run`'s 4th const argument.
19388    /// const N: usize = 32;
19389    /// let terms: [Term<'static, N>; 1] = [uor_foundation::pipeline::literal_u64(7, WittLevel::W8)];
19390    /// let doms: [VerificationDomain; 1] = [VerificationDomain::Enumerative];
19391    /// let unit = CompileUnitBuilder::<N>::new()
19392    ///     .root_term(&terms).witt_level_ceiling(WittLevel::W32)
19393    ///     .thermodynamic_budget(1024).target_domains(&doms)
19394    ///     .result_type::<ConstrainedTypeInput>()
19395    ///     .validate().expect("unit well-formed");
19396    /// let grounded: Grounded<ConstrainedTypeInput, N> =
19397    ///     run::<ConstrainedTypeInput, _, H, N>(unit).expect("grounds");
19398    /// // Replay → round-trip verification. The trace's event-count
19399    /// // capacity comes from the application's `HostBounds`; here the
19400    /// // type-annotated binding defaults `Trace`'s `TR_MAX` to 256.
19401    /// let trace: Trace = grounded.derivation().replay();
19402    /// let recert = replay::certify_from_trace(&trace).expect("valid trace");
19403    /// assert_eq!(recert.certificate().content_fingerprint(),
19404    ///            grounded.content_fingerprint());
19405    /// ```
19406    #[inline]
19407    #[must_use]
19408    pub fn replay<const TR_MAX: usize>(&self) -> Trace<TR_MAX> {
19409        let steps = self.step_count() as usize;
19410        let len = if steps > TR_MAX { TR_MAX } else { steps };
19411        let mut events = [None; TR_MAX];
19412        // Seed targets from the leading 8 bytes of the source
19413        // `content_fingerprint` (substrate-computed). Combined with `| 1` so
19414        // the first event's target is guaranteed nonzero even when the
19415        // leading bytes are all zero, and XOR with `(i + 1)` keeps the
19416        // sequence non-degenerate.
19417        let fp = self.content_fingerprint.as_bytes();
19418        let seed =
19419            u64::from_be_bytes([fp[0], fp[1], fp[2], fp[3], fp[4], fp[5], fp[6], fp[7]]) as u128;
19420        let nonzero_seed = seed | 1u128;
19421        let mut i = 0usize;
19422        while i < len {
19423            let target_raw = nonzero_seed ^ ((i as u128) + 1u128);
19424            events[i] = Some(TraceEvent::new(
19425                i as u32,
19426                crate::PrimitiveOp::Add,
19427                ContentAddress::from_u128(target_raw),
19428            ));
19429            i += 1;
19430        }
19431        // Pack the source `witt_level_bits` and `content_fingerprint`
19432        // into the Trace so `verify_trace` can reproduce the source certificate
19433        // via passthrough. The fingerprint was computed at grounding time by the
19434        // consumer-supplied Hasher and stored on the parent Grounded; the
19435        // Derivation accessor read it through.
19436        Trace::from_replay_events_const(
19437            events,
19438            len as u16,
19439            self.witt_level_bits,
19440            self.content_fingerprint,
19441        )
19442    }
19443}
19444
19445/// v0.2.2 T5: errors emitted by the trace-replay re-derivation path.
19446#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19447#[non_exhaustive]
19448pub enum ReplayError {
19449    /// The trace was empty; nothing to replay.
19450    EmptyTrace,
19451    /// Event at `index` has a non-monotonic step_index.
19452    OutOfOrderEvent {
19453        /// The event index that was out of order.
19454        index: usize,
19455    },
19456    /// Event at `index` carries a zero ContentAddress (forbidden in well-formed traces).
19457    ZeroTarget {
19458        /// The event index that carried a zero target.
19459        index: usize,
19460    },
19461    /// v0.2.2 T5.8: event step indices do not form a contiguous sequence
19462    /// `[0, 1, ..., len-1]`. Replaces the misleadingly-named v0.2.1
19463    /// `LengthMismatch` variant. The trace has the right number of
19464    /// events, but their step indices skip values (e.g., `[0, 2, 5]`
19465    /// with `len = 3`).
19466    NonContiguousSteps {
19467        /// The trace's declared length (number of events).
19468        declared: u16,
19469        /// The largest step_index observed in the event sequence.
19470        /// Always strictly greater than `declared - 1` when this
19471        /// variant fires.
19472        last_step: u32,
19473    },
19474    /// A caller attempted to construct a `Trace<TR_MAX>` whose event count
19475    /// exceeds `TR_MAX` (the application's `<HostBounds>::TRACE_MAX_EVENTS`).
19476    /// Distinct from `NonContiguousSteps` because the recovery is different
19477    /// (truncate vs. close gaps). Returned by `Trace::try_from_events`,
19478    /// never by `verify_trace` (the verifier reads from an existing `Trace`
19479    /// whose capacity is already enforced by the type's storage).
19480    CapacityExceeded {
19481        /// The trace's hard capacity (`TR_MAX`).
19482        declared: u16,
19483        /// The actual event count the caller attempted to pack in.
19484        provided: u32,
19485    },
19486}
19487
19488impl core::fmt::Display for ReplayError {
19489    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
19490        match self {
19491            Self::EmptyTrace => f.write_str("trace was empty; nothing to replay"),
19492            Self::OutOfOrderEvent { index } => write!(
19493                f,
19494                "event at index {index} has out-of-order step index",
19495            ),
19496            Self::ZeroTarget { index } => write!(
19497                f,
19498                "event at index {index} has a zero ContentAddress target",
19499            ),
19500            Self::NonContiguousSteps { declared, last_step } => write!(
19501                f,
19502                "trace declares {declared} events but step indices skip values \
19503                 (last step {last_step})",
19504            ),
19505            Self::CapacityExceeded { declared, provided } => write!(
19506                f,
19507                "trace capacity exceeded: tried to pack {provided} events into a buffer of {declared}",
19508            ),
19509        }
19510    }
19511}
19512
19513impl core::error::Error for ReplayError {}
19514
19515/// v0.2.2 T5: trace-replay re-derivation module.
19516/// The foundation owns the certificate-construction boundary; the
19517/// `uor-foundation-verify` crate is a thin facade that delegates to
19518/// `replay::certify_from_trace`. This preserves sealing discipline:
19519/// `Certified::new` stays `pub(crate)` and no external crate can mint a
19520/// certificate.
19521pub mod replay {
19522    use super::{Certified, GroundingCertificate, ReplayError, Trace};
19523
19524    /// Re-derive the `Certified<GroundingCertificate>` that the foundation
19525    /// grounding path produced for the source unit.
19526    /// Validates the trace's structural invariants (monotonic, contiguous
19527    /// step indices; no zero targets; no None slots in the populated
19528    /// prefix) and re-packages the trace's stored `ContentFingerprint` and
19529    /// `witt_level_bits` into a fresh certificate. The verifier does NOT
19530    /// invoke a hash function: the fingerprint is *data carried by the
19531    /// Trace*, computed at mint time by the consumer-supplied `Hasher` and
19532    /// passed through unchanged.
19533    /// # Round-trip property
19534    /// For every `Grounded<T>` produced by `pipeline::run::<T, _, H>` with
19535    /// a conforming substrate `H: Hasher`:
19536    /// ```text
19537    /// verify_trace(&grounded.derivation().replay()).certificate()
19538    ///     == grounded.certificate()
19539    /// ```
19540    /// holds bit-identically. The contract is orthogonal to the substrate
19541    /// hasher choice and to the chosen `OUTPUT_BYTES` width.
19542    /// # Errors
19543    /// Returns:
19544    /// - `ReplayError::EmptyTrace` if `trace.is_empty()`.
19545    /// - `ReplayError::OutOfOrderEvent { index }` if step indices are not
19546    ///   strictly monotonic at position `index`.
19547    /// - `ReplayError::ZeroTarget { index }` if any event carries
19548    ///   `ContentAddress::zero()`.
19549    /// - `ReplayError::NonContiguousSteps { declared, last_step }` if
19550    ///   the event step indices skip values.
19551    pub fn certify_from_trace<const TR_MAX: usize>(
19552        trace: &Trace<TR_MAX>,
19553    ) -> Result<Certified<GroundingCertificate>, ReplayError> {
19554        let len = trace.len() as usize;
19555        if len == 0 {
19556            return Err(ReplayError::EmptyTrace);
19557        }
19558        // Structural validation: monotonic step indices, contiguous from 0,
19559        // no zero targets, no None slots in the populated prefix.
19560        let mut last_step: i64 = -1;
19561        let mut max_step_index: u32 = 0;
19562        let mut i = 0usize;
19563        while i < len {
19564            let event = match trace.event(i) {
19565                Some(e) => e,
19566                None => return Err(ReplayError::OutOfOrderEvent { index: i }),
19567            };
19568            let step_index = event.step_index();
19569            if (step_index as i64) <= last_step {
19570                return Err(ReplayError::OutOfOrderEvent { index: i });
19571            }
19572            if event.target().is_zero() {
19573                return Err(ReplayError::ZeroTarget { index: i });
19574            }
19575            if step_index > max_step_index {
19576                max_step_index = step_index;
19577            }
19578            last_step = step_index as i64;
19579            i += 1;
19580        }
19581        if (max_step_index as u16).saturating_add(1) != trace.len() {
19582            return Err(ReplayError::NonContiguousSteps {
19583                declared: trace.len(),
19584                last_step: max_step_index,
19585            });
19586        }
19587        // v0.2.2 T5: fingerprint passthrough. The trace was minted by the
19588        // foundation pipeline with a `ContentFingerprint` already computed by
19589        // the consumer-supplied `Hasher`. The verifier does not invoke any
19590        // hash function; it copies the fingerprint through unchanged. The
19591        // round-trip property holds by construction. v0.2.2 T6.5: the
19592        // FingerprintMissing variant is removed because under T6.3 / T6.10,
19593        // no public path can produce a Trace with a zero fingerprint.
19594        Ok(Certified::new(
19595            GroundingCertificate::with_level_and_fingerprint_const(
19596                trace.witt_level_bits(),
19597                trace.content_fingerprint(),
19598            ),
19599        ))
19600    }
19601}
19602
19603/// v0.2.2 Phase E: sealed builder for an InteractionDeclaration.
19604/// Validates the peer protocol, convergence predicate, and
19605/// commutator state class required by `conformance:InteractionShape`.
19606/// Phase F wires the full `InteractionDriver` on top of this builder.
19607#[derive(Debug, Clone, Copy, Default)]
19608pub struct InteractionDeclarationBuilder {
19609    peer_protocol: Option<u128>,
19610    convergence_predicate: Option<u128>,
19611    commutator_state_class: Option<u128>,
19612}
19613
19614impl InteractionDeclarationBuilder {
19615    /// Construct a new builder.
19616    #[inline]
19617    #[must_use]
19618    pub const fn new() -> Self {
19619        Self {
19620            peer_protocol: None,
19621            convergence_predicate: None,
19622            commutator_state_class: None,
19623        }
19624    }
19625
19626    /// Set the peer protocol content address.
19627    #[inline]
19628    #[must_use]
19629    pub const fn peer_protocol(mut self, address: u128) -> Self {
19630        self.peer_protocol = Some(address);
19631        self
19632    }
19633
19634    /// Set the convergence predicate content address.
19635    #[inline]
19636    #[must_use]
19637    pub const fn convergence_predicate(mut self, address: u128) -> Self {
19638        self.convergence_predicate = Some(address);
19639        self
19640    }
19641
19642    /// Set the commutator state class content address.
19643    #[inline]
19644    #[must_use]
19645    pub const fn commutator_state_class(mut self, address: u128) -> Self {
19646        self.commutator_state_class = Some(address);
19647        self
19648    }
19649
19650    /// Phase E.6: validate against `conformance:InteractionShape`.
19651    /// # Errors
19652    /// Returns `ShapeViolation` if any of the three required fields is missing.
19653    pub fn validate(&self) -> Result<Validated<InteractionShape>, ShapeViolation> {
19654        self.validate_common().map(|_| {
19655            Validated::new(InteractionShape {
19656                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19657            })
19658        })
19659    }
19660
19661    /// Phase E.6 + C.1: const-fn companion.
19662    /// # Errors
19663    /// Returns `ShapeViolation` if any required field is missing.
19664    pub const fn validate_const(
19665        &self,
19666    ) -> Result<Validated<InteractionShape, CompileTime>, ShapeViolation> {
19667        if self.peer_protocol.is_none() {
19668            return Err(ShapeViolation {
19669                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19670                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19671                property_iri: "https://uor.foundation/interaction/peerProtocol",
19672                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19673                min_count: 1,
19674                max_count: 1,
19675                kind: ViolationKind::Missing,
19676            });
19677        }
19678        if self.convergence_predicate.is_none() {
19679            return Err(ShapeViolation {
19680                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19681                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19682                property_iri: "https://uor.foundation/interaction/convergencePredicate",
19683                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19684                min_count: 1,
19685                max_count: 1,
19686                kind: ViolationKind::Missing,
19687            });
19688        }
19689        if self.commutator_state_class.is_none() {
19690            return Err(ShapeViolation {
19691                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19692                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19693                property_iri: "https://uor.foundation/interaction/commutatorStateClass",
19694                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19695                min_count: 1,
19696                max_count: 1,
19697                kind: ViolationKind::Missing,
19698            });
19699        }
19700        Ok(Validated::new(InteractionShape {
19701            shape_iri: "https://uor.foundation/conformance/InteractionShape",
19702        }))
19703    }
19704
19705    fn validate_common(&self) -> Result<(), ShapeViolation> {
19706        self.validate_const().map(|_| ())
19707    }
19708}
19709
19710/// Phase E.6: validated InteractionDeclaration per `conformance:InteractionShape`.
19711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19712pub struct InteractionShape {
19713    /// Shape IRI this declaration was validated against.
19714    pub shape_iri: &'static str,
19715}
19716
19717/// Phase E.5 (target §7.4): observability subscribe API.
19718/// When the `observability` feature is enabled, downstream may call
19719/// `subscribe_trace_events` with a handler closure that receives each
19720/// `TraceEvent` as the pipeline emits it. When the feature is off, this
19721/// function is entirely absent from the public API.
19722#[cfg(feature = "observability")]
19723pub fn subscribe_trace_events<F>(handler: F) -> ObservabilitySubscription<F>
19724where
19725    F: FnMut(&TraceEvent),
19726{
19727    ObservabilitySubscription {
19728        handler,
19729        _sealed: (),
19730    }
19731}
19732
19733#[cfg(feature = "observability")]
19734/// Phase E.5: sealed subscription handle returned by `subscribe_trace_events`.
19735#[cfg(feature = "observability")]
19736pub struct ObservabilitySubscription<F: FnMut(&TraceEvent)> {
19737    handler: F,
19738    _sealed: (),
19739}
19740
19741#[cfg(feature = "observability")]
19742impl<F: FnMut(&TraceEvent)> ObservabilitySubscription<F> {
19743    /// Dispatch a TraceEvent through the subscribed handler.
19744    pub fn emit(&mut self, event: &TraceEvent) {
19745        (self.handler)(event);
19746    }
19747}
19748
19749/// Phase F.2 (target §4.7): closed enumeration of the six constraint kinds.
19750/// `type-decl` bodies enumerate exactly these six kinds per `uor_term.ebnf`'s
19751/// `constraint-decl` production. `CompositeConstraint` — the implicit shape of
19752/// a multi-decl body — has no syntactic constructor and is therefore not a
19753/// variant of this enum.
19754#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19755#[non_exhaustive]
19756pub enum ConstraintKind {
19757    /// `type:ResidueConstraint` — value is congruent to `r (mod m)`.
19758    Residue,
19759    /// `type:CarryConstraint` — bounded carry depth.
19760    Carry,
19761    /// `type:DepthConstraint` — bounded derivation depth.
19762    Depth,
19763    /// `type:HammingConstraint` — bounded Hamming distance from a reference.
19764    Hamming,
19765    /// `type:SiteConstraint` — per-site cardinality or containment.
19766    Site,
19767    /// `type:AffineConstraint` — linear inequality over site values.
19768    Affine,
19769}
19770
19771/// Phase F.3 (target §4.7 carry): sealed per-ring-op carry profile.
19772#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19773pub struct CarryProfile {
19774    chain_length: u32,
19775    max_depth: u32,
19776    _sealed: (),
19777}
19778
19779impl CarryProfile {
19780    /// Length of the longest carry chain observed.
19781    #[inline]
19782    #[must_use]
19783    pub const fn chain_length(&self) -> u32 {
19784        self.chain_length
19785    }
19786
19787    /// Maximum carry depth across the op.
19788    #[inline]
19789    #[must_use]
19790    pub const fn max_depth(&self) -> u32 {
19791        self.max_depth
19792    }
19793
19794    /// Crate-internal constructor.
19795    #[inline]
19796    #[must_use]
19797    #[allow(dead_code)]
19798    pub(crate) const fn new(chain_length: u32, max_depth: u32) -> Self {
19799        Self {
19800            chain_length,
19801            max_depth,
19802            _sealed: (),
19803        }
19804    }
19805}
19806
19807/// Phase F.3 (target §4.7 carry): sealed carry-event witness — records the ring op
19808/// and two `Datum<L>` witt widths involved.
19809#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19810pub struct CarryEvent {
19811    left_bits: u16,
19812    right_bits: u16,
19813    _sealed: (),
19814}
19815
19816impl CarryEvent {
19817    /// Witt bit-width of the left operand.
19818    #[inline]
19819    #[must_use]
19820    pub const fn left_bits(&self) -> u16 {
19821        self.left_bits
19822    }
19823
19824    /// Witt bit-width of the right operand.
19825    #[inline]
19826    #[must_use]
19827    pub const fn right_bits(&self) -> u16 {
19828        self.right_bits
19829    }
19830
19831    /// Crate-internal constructor.
19832    #[inline]
19833    #[must_use]
19834    #[allow(dead_code)]
19835    pub(crate) const fn new(left_bits: u16, right_bits: u16) -> Self {
19836        Self {
19837            left_bits,
19838            right_bits,
19839            _sealed: (),
19840        }
19841    }
19842}
19843
19844/// Phase F.3 (target §4.7 convergence): sealed convergence-level witness at `L`.
19845#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19846pub struct ConvergenceLevel<L> {
19847    valuation: u32,
19848    _level: PhantomData<L>,
19849    _sealed: (),
19850}
19851
19852impl<L> ConvergenceLevel<L> {
19853    /// The v₂ valuation of the datum at this convergence level.
19854    #[inline]
19855    #[must_use]
19856    pub const fn valuation(&self) -> u32 {
19857        self.valuation
19858    }
19859
19860    /// Crate-internal constructor.
19861    #[inline]
19862    #[must_use]
19863    #[allow(dead_code)]
19864    pub(crate) const fn new(valuation: u32) -> Self {
19865        Self {
19866            valuation,
19867            _level: PhantomData,
19868            _sealed: (),
19869        }
19870    }
19871}
19872
19873/// Phase F.3 (target §4.7 division): sealed enum over the four normed division
19874/// algebras from Cayley-Dickson. No other admissible algebra exists (Hurwitz's theorem).
19875#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19876#[non_exhaustive]
19877pub enum DivisionAlgebraWitness {
19878    /// Real numbers ℝ (dimension 1).
19879    Real,
19880    /// Complex numbers ℂ (dimension 2).
19881    Complex,
19882    /// Quaternions ℍ (dimension 4, non-commutative).
19883    Quaternion,
19884    /// Octonions 𝕆 (dimension 8, non-commutative, non-associative).
19885    Octonion,
19886}
19887
19888/// Phase F.3 (target §4.7 monoidal): sealed monoidal-product witness.
19889#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19890pub struct MonoidalProduct<L, R> {
19891    _left: PhantomData<L>,
19892    _right: PhantomData<R>,
19893    _sealed: (),
19894}
19895
19896impl<L, R> MonoidalProduct<L, R> {
19897    /// Crate-internal constructor.
19898    #[inline]
19899    #[must_use]
19900    #[allow(dead_code)]
19901    pub(crate) const fn new() -> Self {
19902        Self {
19903            _left: PhantomData,
19904            _right: PhantomData,
19905            _sealed: (),
19906        }
19907    }
19908}
19909
19910/// Phase F.3 (target §4.7 monoidal): sealed monoidal-unit witness at `L`.
19911#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19912pub struct MonoidalUnit<L> {
19913    _level: PhantomData<L>,
19914    _sealed: (),
19915}
19916
19917impl<L> MonoidalUnit<L> {
19918    /// Crate-internal constructor.
19919    #[inline]
19920    #[must_use]
19921    #[allow(dead_code)]
19922    pub(crate) const fn new() -> Self {
19923        Self {
19924            _level: PhantomData,
19925            _sealed: (),
19926        }
19927    }
19928}
19929
19930/// Phase F.1 (target §4.7 operad): sealed operad-composition witness.
19931/// Every `type-app` form in the term grammar materializes a fresh `OperadComposition`
19932/// carrying the outer/inner type IRIs and composed site count, per `operad:` ontology.
19933#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19934pub struct OperadComposition {
19935    outer_type_iri: &'static str,
19936    inner_type_iri: &'static str,
19937    composed_site_count: u32,
19938    _sealed: (),
19939}
19940
19941impl OperadComposition {
19942    /// IRI of the outer `type:TypeDefinition`.
19943    #[inline]
19944    #[must_use]
19945    pub const fn outer_type_iri(&self) -> &'static str {
19946        self.outer_type_iri
19947    }
19948
19949    /// IRI of the inner `type:TypeDefinition`.
19950    #[inline]
19951    #[must_use]
19952    pub const fn inner_type_iri(&self) -> &'static str {
19953        self.inner_type_iri
19954    }
19955
19956    /// Site count of the composed type.
19957    #[inline]
19958    #[must_use]
19959    pub const fn composed_site_count(&self) -> u32 {
19960        self.composed_site_count
19961    }
19962
19963    /// Crate-internal constructor.
19964    #[inline]
19965    #[must_use]
19966    #[allow(dead_code)]
19967    pub(crate) const fn new(
19968        outer_type_iri: &'static str,
19969        inner_type_iri: &'static str,
19970        composed_site_count: u32,
19971    ) -> Self {
19972        Self {
19973            outer_type_iri,
19974            inner_type_iri,
19975            composed_site_count,
19976            _sealed: (),
19977        }
19978    }
19979}
19980
19981/// Phase F.3 (target §4.7 recursion): maximum depth of the recursion trace
19982/// witness. Bounded by the declared descent budget at builder-validate time;
19983/// the constant is a size-budget cap matching other foundation arenas.
19984/// Wiki ADR-037: a foundation-fixed conservative default for
19985/// [`crate::HostBounds::RECURSION_TRACE_DEPTH_MAX`].
19986pub const RECURSION_TRACE_MAX_DEPTH: usize = 16;
19987
19988/// Phase F.3 (target §4.7 recursion): sealed recursion trace with fixed-capacity
19989/// descent-measure sequence.
19990#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19991pub struct RecursionTrace {
19992    depth: u32,
19993    measure: [u32; RECURSION_TRACE_MAX_DEPTH],
19994    _sealed: (),
19995}
19996
19997impl RecursionTrace {
19998    /// Number of recursive descents in this trace.
19999    #[inline]
20000    #[must_use]
20001    pub const fn depth(&self) -> u32 {
20002        self.depth
20003    }
20004
20005    /// Descent-measure sequence.
20006    #[inline]
20007    #[must_use]
20008    pub const fn measure(&self) -> &[u32; RECURSION_TRACE_MAX_DEPTH] {
20009        &self.measure
20010    }
20011
20012    /// Crate-internal constructor.
20013    #[inline]
20014    #[must_use]
20015    #[allow(dead_code)]
20016    pub(crate) const fn new(depth: u32, measure: [u32; RECURSION_TRACE_MAX_DEPTH]) -> Self {
20017        Self {
20018            depth,
20019            measure,
20020            _sealed: (),
20021        }
20022    }
20023}
20024
20025/// Phase F.3 (target §4.7 region): sealed address-region witness.
20026#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20027pub struct AddressRegion {
20028    base: u128,
20029    extent: u64,
20030    _sealed: (),
20031}
20032
20033impl AddressRegion {
20034    /// Base address of the region.
20035    #[inline]
20036    #[must_use]
20037    pub const fn base(&self) -> u128 {
20038        self.base
20039    }
20040
20041    /// Extent (number of addressable cells).
20042    #[inline]
20043    #[must_use]
20044    pub const fn extent(&self) -> u64 {
20045        self.extent
20046    }
20047
20048    /// Crate-internal constructor.
20049    #[inline]
20050    #[must_use]
20051    #[allow(dead_code)]
20052    pub(crate) const fn new(base: u128, extent: u64) -> Self {
20053        Self {
20054            base,
20055            extent,
20056            _sealed: (),
20057        }
20058    }
20059}
20060
20061/// Phase F.3 (target §4.7 linear): sealed linear-resource budget.
20062#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20063pub struct LinearBudget {
20064    sites_remaining: u64,
20065    _sealed: (),
20066}
20067
20068impl LinearBudget {
20069    /// Number of linear sites still available for allocation.
20070    #[inline]
20071    #[must_use]
20072    pub const fn sites_remaining(&self) -> u64 {
20073        self.sites_remaining
20074    }
20075
20076    /// Crate-internal constructor.
20077    #[inline]
20078    #[must_use]
20079    #[allow(dead_code)]
20080    pub(crate) const fn new(sites_remaining: u64) -> Self {
20081        Self {
20082            sites_remaining,
20083            _sealed: (),
20084        }
20085    }
20086}
20087
20088/// Phase F.3 (target §4.7 linear): sealed lease-allocation witness.
20089#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20090pub struct LeaseAllocation {
20091    site_count: u32,
20092    scope_hash: u128,
20093    _sealed: (),
20094}
20095
20096impl LeaseAllocation {
20097    /// Number of linear sites taken by this allocation.
20098    #[inline]
20099    #[must_use]
20100    pub const fn site_count(&self) -> u32 {
20101        self.site_count
20102    }
20103
20104    /// Content-hash of the lease scope identifier.
20105    #[inline]
20106    #[must_use]
20107    pub const fn scope_hash(&self) -> u128 {
20108        self.scope_hash
20109    }
20110
20111    /// Crate-internal constructor.
20112    #[inline]
20113    #[must_use]
20114    #[allow(dead_code)]
20115    pub(crate) const fn new(site_count: u32, scope_hash: u128) -> Self {
20116        Self {
20117            site_count,
20118            scope_hash,
20119            _sealed: (),
20120        }
20121    }
20122}
20123
20124/// v0.2.2 Phase J: zero-sized token identifying the `Total` marker.
20125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20126pub struct TotalMarker;
20127
20128/// v0.2.2 Phase J: zero-sized token identifying the `Invertible` marker.
20129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20130pub struct InvertibleMarker;
20131
20132/// v0.2.2 Phase J: zero-sized token identifying the `PreservesStructure` marker.
20133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20134pub struct PreservesStructureMarker;
20135
20136mod marker_tuple_sealed {
20137    /// Private supertrait. Not implementable outside this crate.
20138    pub trait Sealed {}
20139}
20140
20141/// v0.2.2 Phase J: sealed marker-tuple trait. Implemented exhaustively by
20142/// the closed catalogue of six admissible marker tuples in canonical order
20143/// (Total, Invertible, PreservesStructure). Downstream cannot add new
20144/// marker tuples; the seal anchors Phase J's compile-time correctness claim.
20145pub trait MarkerTuple: marker_tuple_sealed::Sealed {}
20146
20147impl marker_tuple_sealed::Sealed for () {}
20148impl MarkerTuple for () {}
20149impl marker_tuple_sealed::Sealed for (TotalMarker,) {}
20150impl MarkerTuple for (TotalMarker,) {}
20151impl marker_tuple_sealed::Sealed for (TotalMarker, InvertibleMarker) {}
20152impl MarkerTuple for (TotalMarker, InvertibleMarker) {}
20153impl marker_tuple_sealed::Sealed for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {}
20154impl MarkerTuple for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {}
20155impl marker_tuple_sealed::Sealed for (InvertibleMarker,) {}
20156impl MarkerTuple for (InvertibleMarker,) {}
20157impl marker_tuple_sealed::Sealed for (InvertibleMarker, PreservesStructureMarker) {}
20158impl MarkerTuple for (InvertibleMarker, PreservesStructureMarker) {}
20159
20160/// v0.2.2 Phase J: type-level set intersection of two marker tuples.
20161/// Implemented exhaustively for every ordered pair in the closed catalogue.
20162/// Composition combinators (`then`, `and_then`) use this trait to compute
20163/// the output marker tuple of a composed primitive as the intersection of
20164/// its two inputs' tuples. Because the catalogue is closed, the result is
20165/// always another tuple in the catalogue — no open-world hazards.
20166pub trait MarkerIntersection<Other: MarkerTuple>: MarkerTuple {
20167    /// The intersection of `Self` and `Other` in the closed catalogue.
20168    type Output: MarkerTuple;
20169}
20170
20171impl MarkerIntersection<()> for () {
20172    type Output = ();
20173}
20174impl MarkerIntersection<(TotalMarker,)> for () {
20175    type Output = ();
20176}
20177impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for () {
20178    type Output = ();
20179}
20180impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)> for () {
20181    type Output = ();
20182}
20183impl MarkerIntersection<(InvertibleMarker,)> for () {
20184    type Output = ();
20185}
20186impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for () {
20187    type Output = ();
20188}
20189impl MarkerIntersection<()> for (TotalMarker,) {
20190    type Output = ();
20191}
20192impl MarkerIntersection<(TotalMarker,)> for (TotalMarker,) {
20193    type Output = (TotalMarker,);
20194}
20195impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (TotalMarker,) {
20196    type Output = (TotalMarker,);
20197}
20198impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20199    for (TotalMarker,)
20200{
20201    type Output = (TotalMarker,);
20202}
20203impl MarkerIntersection<(InvertibleMarker,)> for (TotalMarker,) {
20204    type Output = ();
20205}
20206impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for (TotalMarker,) {
20207    type Output = ();
20208}
20209impl MarkerIntersection<()> for (TotalMarker, InvertibleMarker) {
20210    type Output = ();
20211}
20212impl MarkerIntersection<(TotalMarker,)> for (TotalMarker, InvertibleMarker) {
20213    type Output = (TotalMarker,);
20214}
20215impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (TotalMarker, InvertibleMarker) {
20216    type Output = (TotalMarker, InvertibleMarker);
20217}
20218impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20219    for (TotalMarker, InvertibleMarker)
20220{
20221    type Output = (TotalMarker, InvertibleMarker);
20222}
20223impl MarkerIntersection<(InvertibleMarker,)> for (TotalMarker, InvertibleMarker) {
20224    type Output = (InvertibleMarker,);
20225}
20226impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20227    for (TotalMarker, InvertibleMarker)
20228{
20229    type Output = (InvertibleMarker,);
20230}
20231impl MarkerIntersection<()> for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {
20232    type Output = ();
20233}
20234impl MarkerIntersection<(TotalMarker,)>
20235    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20236{
20237    type Output = (TotalMarker,);
20238}
20239impl MarkerIntersection<(TotalMarker, InvertibleMarker)>
20240    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20241{
20242    type Output = (TotalMarker, InvertibleMarker);
20243}
20244impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20245    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20246{
20247    type Output = (TotalMarker, InvertibleMarker, PreservesStructureMarker);
20248}
20249impl MarkerIntersection<(InvertibleMarker,)>
20250    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20251{
20252    type Output = (InvertibleMarker,);
20253}
20254impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20255    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20256{
20257    type Output = (InvertibleMarker, PreservesStructureMarker);
20258}
20259impl MarkerIntersection<()> for (InvertibleMarker,) {
20260    type Output = ();
20261}
20262impl MarkerIntersection<(TotalMarker,)> for (InvertibleMarker,) {
20263    type Output = ();
20264}
20265impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (InvertibleMarker,) {
20266    type Output = (InvertibleMarker,);
20267}
20268impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20269    for (InvertibleMarker,)
20270{
20271    type Output = (InvertibleMarker,);
20272}
20273impl MarkerIntersection<(InvertibleMarker,)> for (InvertibleMarker,) {
20274    type Output = (InvertibleMarker,);
20275}
20276impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for (InvertibleMarker,) {
20277    type Output = (InvertibleMarker,);
20278}
20279impl MarkerIntersection<()> for (InvertibleMarker, PreservesStructureMarker) {
20280    type Output = ();
20281}
20282impl MarkerIntersection<(TotalMarker,)> for (InvertibleMarker, PreservesStructureMarker) {
20283    type Output = ();
20284}
20285impl MarkerIntersection<(TotalMarker, InvertibleMarker)>
20286    for (InvertibleMarker, PreservesStructureMarker)
20287{
20288    type Output = (InvertibleMarker,);
20289}
20290impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20291    for (InvertibleMarker, PreservesStructureMarker)
20292{
20293    type Output = (InvertibleMarker, PreservesStructureMarker);
20294}
20295impl MarkerIntersection<(InvertibleMarker,)> for (InvertibleMarker, PreservesStructureMarker) {
20296    type Output = (InvertibleMarker,);
20297}
20298impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20299    for (InvertibleMarker, PreservesStructureMarker)
20300{
20301    type Output = (InvertibleMarker, PreservesStructureMarker);
20302}
20303
20304/// v0.2.2 Phase J: compile-time check that a combinator's marker tuple
20305/// carries every property declared by the `GroundingMapKind` a program
20306/// claims. Implemented exhaustively by codegen for every valid `(tuple,
20307/// map)` pair; absent impls reject the mismatched declaration at the
20308/// `GroundingProgram::from_primitive` call site.
20309pub trait MarkersImpliedBy<Map: GroundingMapKind>: MarkerTuple {}
20310
20311/// v0.2.2 Phase J: bitmask encoding of a combinator's marker set.
20312/// Bit 0 = Total, bit 1 = Invertible, bit 2 = PreservesStructure.
20313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20314pub struct MarkerBits(u8);
20315
20316impl MarkerBits {
20317    /// The `Total` marker bit.
20318    pub const TOTAL: Self = Self(1);
20319    /// The `Invertible` marker bit.
20320    pub const INVERTIBLE: Self = Self(2);
20321    /// The `PreservesStructure` marker bit.
20322    pub const PRESERVES_STRUCTURE: Self = Self(4);
20323    /// An empty marker set.
20324    pub const NONE: Self = Self(0);
20325
20326    /// Construct a marker bitmask from raw u8.
20327    #[inline]
20328    #[must_use]
20329    pub const fn from_u8(bits: u8) -> Self {
20330        Self(bits)
20331    }
20332
20333    /// Access the raw bitmask.
20334    #[inline]
20335    #[must_use]
20336    pub const fn as_u8(&self) -> u8 {
20337        self.0
20338    }
20339
20340    /// Bitwise OR of two marker bitmasks.
20341    #[inline]
20342    #[must_use]
20343    pub const fn union(self, other: Self) -> Self {
20344        Self(self.0 | other.0)
20345    }
20346
20347    /// Bitwise AND of two marker bitmasks (marker intersection).
20348    #[inline]
20349    #[must_use]
20350    pub const fn intersection(self, other: Self) -> Self {
20351        Self(self.0 & other.0)
20352    }
20353
20354    /// Whether this set contains all marker bits of `other`.
20355    #[inline]
20356    #[must_use]
20357    pub const fn contains(&self, other: Self) -> bool {
20358        (self.0 & other.0) == other.0
20359    }
20360}
20361
20362/// v0.2.2 Phase J: closed catalogue of grounding primitives.
20363/// Exactly 12 operations — read_bytes, interpret_le_integer,
20364/// interpret_be_integer, digest, decode_utf8, decode_json, select_field,
20365/// select_index, const_value, then, map_err, and_then. Adding a new
20366/// primitive is an ontology+grammar+codegen edit, not a Rust patch.
20367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20368#[non_exhaustive]
20369pub enum GroundingPrimitiveOp {
20370    /// Read a fixed-size byte slice from the input.
20371    ReadBytes,
20372    /// Interpret bytes as a little-endian integer at the target WittLevel.
20373    InterpretLeInteger,
20374    /// Interpret bytes as a big-endian integer.
20375    InterpretBeInteger,
20376    /// Hash bytes via blake3 → 32-byte digest → `Datum<W256>`.
20377    /// # Scope
20378    /// `interpret_leaf_op` returns the first byte of the blake3 32-byte digest.
20379    /// The full digest is produced by `Datum<W256>` composition of 32 `Digest` leaves —
20380    /// the leaf-level output is the single-byte projection.
20381    Digest,
20382    /// Decode UTF-8 bytes; rejects malformed input.
20383    /// # Scope
20384    /// Only single-byte ASCII (`b < 0x80`) is decoded by `interpret_leaf_op`.
20385    /// Multi-byte UTF-8 is not decoded by this leaf; multi-byte sequences traverse the
20386    /// foundation via `GroundedTuple<N>` composition of single-byte leaves.
20387    DecodeUtf8,
20388    /// Decode JSON bytes; rejects malformed input.
20389    /// # Scope
20390    /// Only the leading byte of a JSON number scalar (`-` or ASCII digit) is parsed
20391    /// by `interpret_leaf_op`. Structured JSON values (objects, arrays, strings,
20392    /// multi-byte numbers) are not parsed by this leaf.
20393    DecodeJson,
20394    /// Select a field from a structured value.
20395    SelectField,
20396    /// Select an indexed element.
20397    SelectIndex,
20398    /// Inject a foundation-known constant.
20399    /// # Scope
20400    /// `interpret_leaf_op` returns `GroundedCoord::w8(0)` — the foundation-canonical
20401    /// zero constant. Non-zero constants are materialized through the const-fn frontier
20402    /// (`validate_const` paths) rather than through this leaf.
20403    ConstValue,
20404    /// Compose two combinators sequentially.
20405    Then,
20406    /// Map the error variant of a fallible combinator.
20407    MapErr,
20408    /// Conditional composition (and_then).
20409    AndThen,
20410}
20411
20412/// Max depth of a composed op chain retained inline inside
20413/// `GroundingPrimitive`. Depth-2 composites (`Then(leaf, leaf)`,
20414/// `AndThen(leaf, leaf)`) are the exercised shape today; 8 gives headroom
20415/// for nested composition while keeping `Copy` and `no_std` without alloc.
20416/// Wiki ADR-037: a foundation-fixed conservative default for
20417/// [`crate::HostBounds::OP_CHAIN_DEPTH_MAX`].
20418pub const MAX_OP_CHAIN_DEPTH: usize = 8;
20419
20420/// v0.2.2 Phase J: a single grounding primitive parametric over its output
20421/// type `Out` and its type-level marker tuple `Markers`.
20422/// Constructed only by the 12 enumerated combinator functions below;
20423/// downstream cannot construct one directly. The `Markers` parameter
20424/// defaults to `()` for backwards-compatible call sites, but each
20425/// combinator returns a specific tuple — see `combinators::digest` etc.
20426/// For leaf primitives `chain_len == 0`. For `Then`/`AndThen`/`MapErr`
20427/// composites, `chain[..chain_len as usize]` is the linearized post-order
20428/// sequence of leaf primitive ops the interpreter walks.
20429#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20430pub struct GroundingPrimitive<Out, Markers: MarkerTuple = ()> {
20431    op: GroundingPrimitiveOp,
20432    markers: MarkerBits,
20433    chain: [GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH],
20434    chain_len: u8,
20435    _out: PhantomData<Out>,
20436    _markers: PhantomData<Markers>,
20437    _sealed: (),
20438}
20439
20440impl<Out, Markers: MarkerTuple> GroundingPrimitive<Out, Markers> {
20441    /// Access the primitive op.
20442    #[inline]
20443    #[must_use]
20444    pub const fn op(&self) -> GroundingPrimitiveOp {
20445        self.op
20446    }
20447
20448    /// Access the runtime marker bitmask (mirrors the type-level tuple).
20449    #[inline]
20450    #[must_use]
20451    pub const fn markers(&self) -> MarkerBits {
20452        self.markers
20453    }
20454
20455    /// Access the recorded composition chain. Empty for leaf primitives;
20456    /// the post-order leaf-op sequence for `Then`/`AndThen`/`MapErr`.
20457    #[inline]
20458    #[must_use]
20459    pub fn chain(&self) -> &[GroundingPrimitiveOp] {
20460        &self.chain[..self.chain_len as usize]
20461    }
20462
20463    /// Crate-internal constructor for a leaf primitive (no recorded chain).
20464    /// The type-level `Markers` tuple is selected via turbofish at call
20465    /// sites inside the combinator functions.
20466    #[inline]
20467    #[must_use]
20468    #[allow(dead_code)]
20469    pub(crate) const fn from_parts(op: GroundingPrimitiveOp, markers: MarkerBits) -> Self {
20470        Self {
20471            op,
20472            markers,
20473            chain: [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH],
20474            chain_len: 0,
20475            _out: PhantomData,
20476            _markers: PhantomData,
20477            _sealed: (),
20478        }
20479    }
20480
20481    /// Crate-internal constructor for a composite primitive. Stores
20482    /// `chain[..chain_len]` inline; accessors expose only the prefix.
20483    #[inline]
20484    #[must_use]
20485    #[allow(dead_code)]
20486    pub(crate) const fn from_parts_with_chain(
20487        op: GroundingPrimitiveOp,
20488        markers: MarkerBits,
20489        chain: [GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH],
20490        chain_len: u8,
20491    ) -> Self {
20492        Self {
20493            op,
20494            markers,
20495            chain,
20496            chain_len,
20497            _out: PhantomData,
20498            _markers: PhantomData,
20499            _sealed: (),
20500        }
20501    }
20502}
20503
20504/// v0.2.2 Phase J: closed 12-combinator surface for building grounding
20505/// programs. See `GroundingProgram` for composition. Each leaf combinator
20506/// returns a `GroundingPrimitive<Out, M>` carrying a specific marker tuple;
20507/// the type parameter is what `GroundingProgram::from_primitive`'s
20508/// `MarkersImpliedBy<Map>` bound checks at compile time.
20509pub mod combinators {
20510    use super::{
20511        GroundingPrimitive, GroundingPrimitiveOp, InvertibleMarker, MarkerBits, MarkerIntersection,
20512        MarkerTuple, PreservesStructureMarker, TotalMarker, MAX_OP_CHAIN_DEPTH,
20513    };
20514
20515    /// Build the post-order leaf-op chain for a sequential composite:
20516    /// `first.chain ++ [first.op] ++ second.chain ++ [second.op]`.
20517    /// Saturated to `MAX_OP_CHAIN_DEPTH`.
20518    fn compose_chain<A, B, MA: MarkerTuple, MB: MarkerTuple>(
20519        first: &GroundingPrimitive<A, MA>,
20520        second: &GroundingPrimitive<B, MB>,
20521    ) -> ([GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH], u8) {
20522        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20523        let mut len: usize = 0;
20524        for &op in first.chain() {
20525            if len >= MAX_OP_CHAIN_DEPTH {
20526                return (chain, len as u8);
20527            }
20528            chain[len] = op;
20529            len += 1;
20530        }
20531        if len < MAX_OP_CHAIN_DEPTH {
20532            chain[len] = first.op();
20533            len += 1;
20534        }
20535        for &op in second.chain() {
20536            if len >= MAX_OP_CHAIN_DEPTH {
20537                return (chain, len as u8);
20538            }
20539            chain[len] = op;
20540            len += 1;
20541        }
20542        if len < MAX_OP_CHAIN_DEPTH {
20543            chain[len] = second.op();
20544            len += 1;
20545        }
20546        (chain, len as u8)
20547    }
20548
20549    /// Build the chain for `map_err(first)`: `first.chain ++ [first.op]`.
20550    fn map_err_chain<A, M: MarkerTuple>(
20551        first: &GroundingPrimitive<A, M>,
20552    ) -> ([GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH], u8) {
20553        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20554        let mut len: usize = 0;
20555        for &op in first.chain() {
20556            if len >= MAX_OP_CHAIN_DEPTH {
20557                return (chain, len as u8);
20558            }
20559            chain[len] = op;
20560            len += 1;
20561        }
20562        if len < MAX_OP_CHAIN_DEPTH {
20563            chain[len] = first.op();
20564            len += 1;
20565        }
20566        (chain, len as u8)
20567    }
20568
20569    /// Read a fixed-size byte slice from the input. `(Total, Invertible)`.
20570    #[inline]
20571    #[must_use]
20572    pub const fn read_bytes<Out>() -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker)> {
20573        GroundingPrimitive::from_parts(
20574            GroundingPrimitiveOp::ReadBytes,
20575            MarkerBits::TOTAL.union(MarkerBits::INVERTIBLE),
20576        )
20577    }
20578
20579    /// Interpret bytes as a little-endian integer at the target WittLevel.
20580    #[inline]
20581    #[must_use]
20582    pub const fn interpret_le_integer<Out>(
20583    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20584        GroundingPrimitive::from_parts(
20585            GroundingPrimitiveOp::InterpretLeInteger,
20586            MarkerBits::TOTAL
20587                .union(MarkerBits::INVERTIBLE)
20588                .union(MarkerBits::PRESERVES_STRUCTURE),
20589        )
20590    }
20591
20592    /// Interpret bytes as a big-endian integer.
20593    #[inline]
20594    #[must_use]
20595    pub const fn interpret_be_integer<Out>(
20596    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20597        GroundingPrimitive::from_parts(
20598            GroundingPrimitiveOp::InterpretBeInteger,
20599            MarkerBits::TOTAL
20600                .union(MarkerBits::INVERTIBLE)
20601                .union(MarkerBits::PRESERVES_STRUCTURE),
20602        )
20603    }
20604
20605    /// Hash bytes via blake3 → 32-byte digest → `Datum<W256>`. `(Total,)` only.
20606    #[inline]
20607    #[must_use]
20608    pub const fn digest<Out>() -> GroundingPrimitive<Out, (TotalMarker,)> {
20609        GroundingPrimitive::from_parts(GroundingPrimitiveOp::Digest, MarkerBits::TOTAL)
20610    }
20611
20612    /// Decode UTF-8 bytes. `(Invertible, PreservesStructure)` — not Total.
20613    #[inline]
20614    #[must_use]
20615    pub const fn decode_utf8<Out>(
20616    ) -> GroundingPrimitive<Out, (InvertibleMarker, PreservesStructureMarker)> {
20617        GroundingPrimitive::from_parts(
20618            GroundingPrimitiveOp::DecodeUtf8,
20619            MarkerBits::INVERTIBLE.union(MarkerBits::PRESERVES_STRUCTURE),
20620        )
20621    }
20622
20623    /// Decode JSON bytes. `(Invertible, PreservesStructure)` — not Total.
20624    #[inline]
20625    #[must_use]
20626    pub const fn decode_json<Out>(
20627    ) -> GroundingPrimitive<Out, (InvertibleMarker, PreservesStructureMarker)> {
20628        GroundingPrimitive::from_parts(
20629            GroundingPrimitiveOp::DecodeJson,
20630            MarkerBits::INVERTIBLE.union(MarkerBits::PRESERVES_STRUCTURE),
20631        )
20632    }
20633
20634    /// Select a field from a structured value. `(Invertible,)` — not Total.
20635    #[inline]
20636    #[must_use]
20637    pub const fn select_field<Out>() -> GroundingPrimitive<Out, (InvertibleMarker,)> {
20638        GroundingPrimitive::from_parts(GroundingPrimitiveOp::SelectField, MarkerBits::INVERTIBLE)
20639    }
20640
20641    /// Select an indexed element. `(Invertible,)` — not Total.
20642    #[inline]
20643    #[must_use]
20644    pub const fn select_index<Out>() -> GroundingPrimitive<Out, (InvertibleMarker,)> {
20645        GroundingPrimitive::from_parts(GroundingPrimitiveOp::SelectIndex, MarkerBits::INVERTIBLE)
20646    }
20647
20648    /// Inject a foundation-known constant. `(Total, Invertible, PreservesStructure)`.
20649    #[inline]
20650    #[must_use]
20651    pub const fn const_value<Out>(
20652    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20653        GroundingPrimitive::from_parts(
20654            GroundingPrimitiveOp::ConstValue,
20655            MarkerBits::TOTAL
20656                .union(MarkerBits::INVERTIBLE)
20657                .union(MarkerBits::PRESERVES_STRUCTURE),
20658        )
20659    }
20660
20661    /// Compose two combinators sequentially. Markers are intersected at
20662    /// the type level via the `MarkerIntersection` trait. The recorded
20663    /// leaf-op chain lets the foundation's interpreter walk the operands
20664    /// at runtime.
20665    #[inline]
20666    #[must_use]
20667    pub fn then<A, B, MA, MB>(
20668        first: GroundingPrimitive<A, MA>,
20669        second: GroundingPrimitive<B, MB>,
20670    ) -> GroundingPrimitive<B, <MA as MarkerIntersection<MB>>::Output>
20671    where
20672        MA: MarkerTuple + MarkerIntersection<MB>,
20673        MB: MarkerTuple,
20674    {
20675        let (chain, chain_len) = compose_chain(&first, &second);
20676        GroundingPrimitive::from_parts_with_chain(
20677            GroundingPrimitiveOp::Then,
20678            first.markers().intersection(second.markers()),
20679            chain,
20680            chain_len,
20681        )
20682    }
20683
20684    /// Map an error variant of a fallible combinator. Marker tuple
20685    /// is preserved. The operand's op is recorded so the interpreter's
20686    /// `MapErr` arm can forward the success value.
20687    #[inline]
20688    #[must_use]
20689    pub fn map_err<A, M: MarkerTuple>(first: GroundingPrimitive<A, M>) -> GroundingPrimitive<A, M> {
20690        let (chain, chain_len) = map_err_chain(&first);
20691        GroundingPrimitive::from_parts_with_chain(
20692            GroundingPrimitiveOp::MapErr,
20693            first.markers(),
20694            chain,
20695            chain_len,
20696        )
20697    }
20698
20699    /// Conditional composition (and_then). Markers are intersected; the
20700    /// recorded chain mirrors `then` so the interpreter walks operands.
20701    #[inline]
20702    #[must_use]
20703    pub fn and_then<A, B, MA, MB>(
20704        first: GroundingPrimitive<A, MA>,
20705        second: GroundingPrimitive<B, MB>,
20706    ) -> GroundingPrimitive<B, <MA as MarkerIntersection<MB>>::Output>
20707    where
20708        MA: MarkerTuple + MarkerIntersection<MB>,
20709        MB: MarkerTuple,
20710    {
20711        let (chain, chain_len) = compose_chain(&first, &second);
20712        GroundingPrimitive::from_parts_with_chain(
20713            GroundingPrimitiveOp::AndThen,
20714            first.markers().intersection(second.markers()),
20715            chain,
20716            chain_len,
20717        )
20718    }
20719}
20720
20721/// v0.2.2 Phase J: sealed grounding program.
20722/// A composition of combinators with a statically tracked marker tuple.
20723/// Constructed only via `GroundingProgram::from_primitive`, which requires
20724/// via the `MarkersImpliedBy<Map>` trait bound that the primitive's marker
20725/// tuple carries every property declared by `Map: GroundingMapKind`.
20726#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20727pub struct GroundingProgram<Out, Map: GroundingMapKind> {
20728    primitive: GroundingPrimitive<Out>,
20729    _map: PhantomData<Map>,
20730    _sealed: (),
20731}
20732
20733impl<Out, Map: GroundingMapKind> GroundingProgram<Out, Map> {
20734    /// Foundation-verified constructor. Accepts a primitive whose marker
20735    /// tuple satisfies `MarkersImpliedBy<Map>`. Programs built from
20736    /// combinators whose marker tuple lacks a property `Map` requires are
20737    /// rejected at compile time — this is Phase J's marquee correctness
20738    /// claim: misdeclarations fail to compile.
20739    /// # Example: valid program
20740    /// ```
20741    /// use uor_foundation::enforcement::{GroundingProgram, IntegerGroundingMap, combinators};
20742    /// let prog: GroundingProgram<u64, IntegerGroundingMap> =
20743    ///     GroundingProgram::from_primitive(combinators::interpret_le_integer::<u64>());
20744    /// let _ = prog;
20745    /// ```
20746    /// # Example: rejected misdeclaration
20747    /// ```compile_fail
20748    /// use uor_foundation::enforcement::{GroundingProgram, IntegerGroundingMap, combinators};
20749    /// // digest returns (TotalMarker,) which does NOT satisfy
20750    /// // MarkersImpliedBy<IntegerGroundingMap> — the line below fails to compile.
20751    /// let prog: GroundingProgram<[u8; 32], IntegerGroundingMap> =
20752    ///     GroundingProgram::from_primitive(combinators::digest::<[u8; 32]>());
20753    /// let _ = prog;
20754    /// ```
20755    #[inline]
20756    #[must_use]
20757    pub fn from_primitive<Markers>(primitive: GroundingPrimitive<Out, Markers>) -> Self
20758    where
20759        Markers: MarkerTuple + MarkersImpliedBy<Map>,
20760    {
20761        // Preserve the composition chain so the interpreter can walk
20762        // operands of Then/AndThen/MapErr composites.
20763        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20764        let src = primitive.chain();
20765        let mut i = 0;
20766        while i < src.len() && i < MAX_OP_CHAIN_DEPTH {
20767            chain[i] = src[i];
20768            i += 1;
20769        }
20770        let erased = GroundingPrimitive::<Out, ()>::from_parts_with_chain(
20771            primitive.op(),
20772            primitive.markers(),
20773            chain,
20774            i as u8,
20775        );
20776        Self {
20777            primitive: erased,
20778            _map: PhantomData,
20779            _sealed: (),
20780        }
20781    }
20782
20783    /// Access the underlying primitive (erased marker tuple).
20784    #[inline]
20785    #[must_use]
20786    pub const fn primitive(&self) -> &GroundingPrimitive<Out> {
20787        &self.primitive
20788    }
20789}
20790
20791/// Phase K (target §4.3 / §9 criterion 1): foundation-supplied interpreter for
20792/// grounding programs whose `Out` is `GroundedCoord`. Handles every op in
20793/// the closed 12-combinator catalogue: leaf ops (`ReadBytes`,
20794/// `InterpretLeInteger`, `InterpretBeInteger`, `Digest`, `DecodeUtf8`,
20795/// `DecodeJson`, `ConstValue`, `SelectField`, `SelectIndex`) call
20796/// `interpret_leaf_op` directly; composition ops (`Then`, `AndThen`,
20797/// `MapErr`) walk the chain recorded in the primitive and thread
20798/// `external` through each leaf step. The interpreter surfaces
20799/// `GroundedCoord::w8(byte)` values; richer outputs compose through
20800/// combinator chains producing `GroundedTuple<N>`. No `ground()`
20801/// override exists after W4 closure — downstream provides only
20802/// `program()`, and `GroundingExt::ground` is foundation-authored.
20803impl<Map: GroundingMapKind> GroundingProgram<GroundedCoord, Map> {
20804    /// Run this program on external bytes, producing a `GroundedCoord`.
20805    /// Returns `None` if the input is malformed/undersized for the
20806    /// program's op chain.
20807    #[inline]
20808    #[must_use]
20809    pub fn run(&self, external: &[u8]) -> Option<GroundedCoord> {
20810        match self.primitive.op() {
20811            GroundingPrimitiveOp::Then | GroundingPrimitiveOp::AndThen => {
20812                let chain = self.primitive.chain();
20813                if chain.is_empty() {
20814                    return None;
20815                }
20816                let mut last: Option<GroundedCoord> = None;
20817                for &op in chain {
20818                    match interpret_leaf_op(op, external) {
20819                        Some(c) => last = Some(c),
20820                        None => return None,
20821                    }
20822                }
20823                last
20824            }
20825            GroundingPrimitiveOp::MapErr => self
20826                .primitive
20827                .chain()
20828                .first()
20829                .and_then(|&op| interpret_leaf_op(op, external)),
20830            leaf => interpret_leaf_op(leaf, external),
20831        }
20832    }
20833}
20834
20835/// W4 closure (target §4.3 + §9 criterion 1): foundation-supplied
20836/// interpreter for programs producing `GroundedTuple<N>`. Splits
20837/// `external` into `N` equal windows and runs the same dispatch
20838/// that `GroundingProgram<GroundedCoord, Map>::run` performs on
20839/// each window. Returns `None` if `N == 0`, the input is empty,
20840/// the input length isn't divisible by `N`, or any window fails.
20841impl<const N: usize, Map: GroundingMapKind> GroundingProgram<GroundedTuple<N>, Map> {
20842    /// Run this program on external bytes, producing a `GroundedTuple<N>`.
20843    #[inline]
20844    #[must_use]
20845    pub fn run(&self, external: &[u8]) -> Option<GroundedTuple<N>> {
20846        if N == 0 || external.is_empty() || external.len() % N != 0 {
20847            return None;
20848        }
20849        let window = external.len() / N;
20850        let mut coords: [GroundedCoord; N] = [const { GroundedCoord::w8(0) }; N];
20851        let mut i = 0usize;
20852        while i < N {
20853            let start = i * window;
20854            let end = start + window;
20855            let sub = &external[start..end];
20856            // Walk this window through the same leaf/composition
20857            // dispatch as the GroundedCoord interpreter above. A
20858            // helper that runs the chain is reused via the same
20859            // primitive accessors.
20860            let outcome = match self.primitive.op() {
20861                GroundingPrimitiveOp::Then | GroundingPrimitiveOp::AndThen => {
20862                    let chain = self.primitive.chain();
20863                    if chain.is_empty() {
20864                        return None;
20865                    }
20866                    let mut last: Option<GroundedCoord> = None;
20867                    for &op in chain {
20868                        match interpret_leaf_op(op, sub) {
20869                            Some(c) => last = Some(c),
20870                            None => return None,
20871                        }
20872                    }
20873                    last
20874                }
20875                GroundingPrimitiveOp::MapErr => self
20876                    .primitive
20877                    .chain()
20878                    .first()
20879                    .and_then(|&op| interpret_leaf_op(op, sub)),
20880                leaf => interpret_leaf_op(leaf, sub),
20881            };
20882            match outcome {
20883                Some(c) => {
20884                    coords[i] = c;
20885                }
20886                None => {
20887                    return None;
20888                }
20889            }
20890            i += 1;
20891        }
20892        Some(GroundedTuple::new(coords))
20893    }
20894}
20895
20896/// Foundation-canonical leaf-op interpreter. Called directly by
20897/// `GroundingProgram::run` for leaf primitives and step-by-step for
20898/// composition ops.
20899#[inline]
20900fn interpret_leaf_op(op: GroundingPrimitiveOp, external: &[u8]) -> Option<GroundedCoord> {
20901    match op {
20902        GroundingPrimitiveOp::ReadBytes | GroundingPrimitiveOp::InterpretLeInteger => {
20903            external.first().map(|&b| GroundedCoord::w8(b))
20904        }
20905        GroundingPrimitiveOp::InterpretBeInteger => external.last().map(|&b| GroundedCoord::w8(b)),
20906        GroundingPrimitiveOp::Digest => {
20907            // Foundation-canonical digest: first byte as `GroundedCoord` —
20908            // the full 32-byte digest requires a Datum<W256> sink that does
20909            // not fit in `GroundedCoord`. Downstream that needs the full
20910            // digest composes a richer program via Then/AndThen chains over
20911            // the 12 closed combinators — no `ground()` override exists after
20912            // W4 closure.
20913            external.first().map(|&b| GroundedCoord::w8(b))
20914        }
20915        GroundingPrimitiveOp::DecodeUtf8 => {
20916            // ASCII single-byte path — the canonical v0.2.2 semantics for
20917            // `Grounding::ground` over `GroundedCoord` outputs. Multi-byte
20918            // UTF-8 sequences are out of scope for w8-sized leaves; a richer
20919            // structured output composes via combinator chains into
20920            // `GroundedTuple<N>`.
20921            match external.first() {
20922                Some(&b) if b < 0x80 => Some(GroundedCoord::w8(b)),
20923                _ => None,
20924            }
20925        }
20926        GroundingPrimitiveOp::DecodeJson => {
20927            // Accept JSON number scalars (leading `-` or ASCII digit).
20928            match external.first() {
20929                Some(&b) if b == b'-' || b.is_ascii_digit() => Some(GroundedCoord::w8(b)),
20930                _ => None,
20931            }
20932        }
20933        GroundingPrimitiveOp::ConstValue => Some(GroundedCoord::w8(0)),
20934        GroundingPrimitiveOp::SelectField | GroundingPrimitiveOp::SelectIndex => {
20935            // Selector ops are composition-only in normal use; if invoked
20936            // directly, forward the first byte as a GroundedCoord.
20937            external.first().map(|&b| GroundedCoord::w8(b))
20938        }
20939        GroundingPrimitiveOp::Then
20940        | GroundingPrimitiveOp::AndThen
20941        | GroundingPrimitiveOp::MapErr => {
20942            // Composite ops are dispatched by `run()` through the chain;
20943            // they never reach the leaf interpreter.
20944            None
20945        }
20946    }
20947}
20948
20949/// v0.2.2 Phase J: MarkersImpliedBy impls for the closed catalogue of valid
20950/// (marker tuple, GroundingMapKind) pairs. These are the compile-time
20951/// witnesses the foundation accepts; every absent pair is a rejection.
20952impl MarkersImpliedBy<DigestGroundingMap> for (TotalMarker,) {}
20953impl MarkersImpliedBy<BinaryGroundingMap> for (TotalMarker, InvertibleMarker) {}
20954impl MarkersImpliedBy<DigestGroundingMap> for (TotalMarker, InvertibleMarker) {}
20955impl MarkersImpliedBy<BinaryGroundingMap>
20956    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20957{
20958}
20959impl MarkersImpliedBy<DigestGroundingMap>
20960    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20961{
20962}
20963impl MarkersImpliedBy<IntegerGroundingMap>
20964    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20965{
20966}
20967impl MarkersImpliedBy<JsonGroundingMap>
20968    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20969{
20970}
20971impl MarkersImpliedBy<Utf8GroundingMap>
20972    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20973{
20974}
20975impl MarkersImpliedBy<JsonGroundingMap> for (InvertibleMarker, PreservesStructureMarker) {}
20976impl MarkersImpliedBy<Utf8GroundingMap> for (InvertibleMarker, PreservesStructureMarker) {}
20977
20978/// v0.2.2 T2.5: foundation-private test-only back-door module.
20979/// Exposes crate-internal constructors for `Trace`, `TraceEvent`, and
20980/// `MulContext` to the `uor-foundation-test-helpers` workspace member, which
20981/// re-exports them under stable test-only names. Not part of the public API.
20982#[doc(hidden)]
20983pub mod __test_helpers {
20984    use super::{ContentAddress, ContentFingerprint, MulContext, Trace, TraceEvent, Validated};
20985
20986    /// Test-only ctor: build a Trace from a slice of events with a
20987    /// `ContentFingerprint::zero()` placeholder. Tests that need a non-zero
20988    /// fingerprint use `trace_with_fingerprint` instead. Parametric in
20989    /// `TR_MAX` per the wiki's ADR-018; callers pick the trace event-count
20990    /// ceiling from their selected `HostBounds`.
20991    #[must_use]
20992    pub fn trace_from_events<const TR_MAX: usize>(events: &[TraceEvent]) -> Trace<TR_MAX> {
20993        trace_with_fingerprint(events, 0, ContentFingerprint::zero())
20994    }
20995
20996    /// Test-only ctor that takes an explicit `witt_level_bits` and
20997    /// `ContentFingerprint`. Used by round-trip tests that need to verify
20998    /// the verify-trace fingerprint passthrough invariant.
20999    #[must_use]
21000    pub fn trace_with_fingerprint<const TR_MAX: usize>(
21001        events: &[TraceEvent],
21002        witt_level_bits: u16,
21003        content_fingerprint: ContentFingerprint,
21004    ) -> Trace<TR_MAX> {
21005        let mut arr = [None; TR_MAX];
21006        let n = events.len().min(TR_MAX);
21007        let mut i = 0;
21008        while i < n {
21009            arr[i] = Some(events[i]);
21010            i += 1;
21011        }
21012        // The test-helpers back-door uses the foundation-private
21013        // `from_replay_events_const` to build malformed fixtures for error-path
21014        // tests. Downstream code uses `Trace::try_from_events` (validating).
21015        Trace::from_replay_events_const(arr, n as u16, witt_level_bits, content_fingerprint)
21016    }
21017
21018    /// Test-only ctor: build a TraceEvent.
21019    #[must_use]
21020    pub fn trace_event(step_index: u32, target: u128) -> TraceEvent {
21021        TraceEvent::new(
21022            step_index,
21023            crate::PrimitiveOp::Add,
21024            ContentAddress::from_u128(target),
21025        )
21026    }
21027
21028    /// Test-only ctor: build a MulContext.
21029    #[must_use]
21030    pub fn mul_context(stack_budget_bytes: u64, const_eval: bool, limb_count: usize) -> MulContext {
21031        MulContext::new(stack_budget_bytes, const_eval, limb_count)
21032    }
21033
21034    /// Test-only ctor: wrap any T in a Runtime-phase Validated. Used by
21035    /// integration tests to construct `Validated<Decl, P>` values that
21036    /// the public API otherwise can't construct directly.
21037    #[must_use]
21038    pub fn validated_runtime<T>(inner: T) -> Validated<T> {
21039        Validated::new(inner)
21040    }
21041}
21042
21043/// Tolerance for entropy equality checks in the Product/Coproduct
21044/// Completion Amendment mint primitives. Returns an absolute-error bound
21045/// scaled to the magnitude of `expected`, so PT_4 / ST_2 / CPT_5
21046/// verifications are robust to floating-point rounding accumulated through
21047/// Künneth products and componentwise sums. The default-host (f64) backing
21048/// is hidden behind the `DefaultDecimal` alias so the function signature
21049/// reads as host-typed; downstream that swaps `H::Decimal` reaches the
21050/// same surface via the alias rebind.
21051type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
21052
21053#[inline]
21054const fn pc_entropy_tolerance(expected: DefaultDecimal) -> DefaultDecimal {
21055    let magnitude = if expected < 0.0 { -expected } else { expected };
21056    let scale = if magnitude > 1.0 { magnitude } else { 1.0 };
21057    1024.0 * <DefaultDecimal>::EPSILON * scale
21058}
21059
21060/// Validate an entropy value before participating in additivity checks.
21061/// Rejects NaN, ±∞, and negative values — the foundation's
21062/// `primitive_descent_metrics` produces `residual × LN_2` with
21063/// `residual: u32`, so valid entropies are non-negative finite Decimals.
21064#[inline]
21065fn pc_entropy_input_is_valid(value: DefaultDecimal) -> bool {
21066    value.is_finite() && value >= 0.0
21067}
21068
21069/// Check that `actual` matches `expected` within tolerance and that both
21070/// inputs are valid entropy values. Returns `false` if either input is
21071/// non-finite, negative, or differs from `expected` by more than
21072/// `pc_entropy_tolerance(expected)`.
21073#[inline]
21074fn pc_entropy_additivity_holds(actual: DefaultDecimal, expected: DefaultDecimal) -> bool {
21075    if !pc_entropy_input_is_valid(actual) || !pc_entropy_input_is_valid(expected) {
21076        return false;
21077    }
21078    let diff = actual - expected;
21079    let diff_abs = if diff < 0.0 { -diff } else { diff };
21080    diff_abs <= pc_entropy_tolerance(expected)
21081}
21082
21083/// Evidence bundle for `PartitionProductWitness`. Carries the PT_1 / PT_3 /
21084/// PT_4 input values used at mint time. Derives `PartialEq` only because
21085/// `f64` entropy fields exclude `Eq` / `Hash`; this is the auditing surface,
21086/// not a hash-map key.
21087#[derive(Debug, Clone, Copy, PartialEq)]
21088pub struct PartitionProductEvidence {
21089    /// Left operand `siteBudget` (data sites only, PT_1 input).
21090    pub left_site_budget: u16,
21091    /// Right operand `siteBudget`.
21092    pub right_site_budget: u16,
21093    /// Left operand `SITE_COUNT` (layout width, layout-invariant input).
21094    pub left_total_site_count: u16,
21095    /// Right operand `SITE_COUNT`.
21096    pub right_total_site_count: u16,
21097    /// Left operand Euler characteristic (PT_3 input).
21098    pub left_euler: i32,
21099    /// Right operand Euler characteristic.
21100    pub right_euler: i32,
21101    /// Left operand entropy in nats (PT_4 input).
21102    pub left_entropy_nats_bits: u64,
21103    /// Right operand entropy in nats.
21104    pub right_entropy_nats_bits: u64,
21105    /// Fingerprint of the source witness the evidence belongs to.
21106    pub source_witness_fingerprint: ContentFingerprint,
21107}
21108
21109/// Evidence bundle for `PartitionCoproductWitness`. Carries the
21110/// ST_1 / ST_2 / ST_9 / ST_10 input values used at mint time.
21111#[derive(Debug, Clone, Copy, PartialEq)]
21112pub struct PartitionCoproductEvidence {
21113    pub left_site_budget: u16,
21114    pub right_site_budget: u16,
21115    pub left_total_site_count: u16,
21116    pub right_total_site_count: u16,
21117    pub left_euler: i32,
21118    pub right_euler: i32,
21119    pub left_entropy_nats_bits: u64,
21120    pub right_entropy_nats_bits: u64,
21121    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21122    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21123    pub source_witness_fingerprint: ContentFingerprint,
21124}
21125
21126/// Evidence bundle for `CartesianProductWitness`. Carries the
21127/// CPT_1 / CPT_3 / CPT_4 / CPT_5 input values used at mint time, plus
21128/// `combined_entropy_nats` — the CartesianProductWitness itself does not
21129/// store entropy (see §1a), so the evidence sidecar preserves the
21130/// verification target value for re-audit.
21131#[derive(Debug, Clone, Copy, PartialEq)]
21132pub struct CartesianProductEvidence {
21133    pub left_site_budget: u16,
21134    pub right_site_budget: u16,
21135    pub left_total_site_count: u16,
21136    pub right_total_site_count: u16,
21137    pub left_euler: i32,
21138    pub right_euler: i32,
21139    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21140    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21141    pub left_entropy_nats_bits: u64,
21142    pub right_entropy_nats_bits: u64,
21143    pub combined_entropy_nats_bits: u64,
21144    pub source_witness_fingerprint: ContentFingerprint,
21145}
21146
21147/// Inputs to `PartitionProductWitness::mint_verified`. Mirrors the
21148/// underlying primitive's parameter list; each field is supplied by the
21149/// caller (typically a `product_shape!` macro expansion or a manual
21150/// construction following the amendment's Gap 2 pattern). Derives
21151/// `PartialEq` only because of the `f64` entropy fields.
21152#[derive(Debug, Clone, Copy, PartialEq)]
21153pub struct PartitionProductMintInputs {
21154    pub witt_bits: u16,
21155    pub left_fingerprint: ContentFingerprint,
21156    pub right_fingerprint: ContentFingerprint,
21157    pub left_site_budget: u16,
21158    pub right_site_budget: u16,
21159    pub left_total_site_count: u16,
21160    pub right_total_site_count: u16,
21161    pub left_euler: i32,
21162    pub right_euler: i32,
21163    pub left_entropy_nats_bits: u64,
21164    pub right_entropy_nats_bits: u64,
21165    pub combined_site_budget: u16,
21166    pub combined_site_count: u16,
21167    pub combined_euler: i32,
21168    pub combined_entropy_nats_bits: u64,
21169    pub combined_fingerprint: ContentFingerprint,
21170}
21171
21172/// Inputs to `PartitionCoproductWitness::mint_verified`. Adds three
21173/// structural fields beyond the other two MintInputs: the combined
21174/// constraint array, the boundary index between L and R regions, and the
21175/// tag site layout index. These feed `validate_coproduct_structure` at
21176/// mint time so ST_6 / ST_7 / ST_8 are verified numerically rather than
21177/// trusted from the caller.
21178/// Derives `Debug`, `Clone`, `Copy` only — no `PartialEq`. `ConstraintRef`
21179/// does not implement `PartialEq`, so deriving equality on a struct with a
21180/// `&[ConstraintRef]` field would not compile. MintInputs is not used as
21181/// an equality target in practice; downstream consumers compare the minted
21182/// witness (which derives `Eq` + `Hash`) instead.
21183#[derive(Debug, Clone, Copy)]
21184pub struct PartitionCoproductMintInputs {
21185    pub witt_bits: u16,
21186    pub left_fingerprint: ContentFingerprint,
21187    pub right_fingerprint: ContentFingerprint,
21188    pub left_site_budget: u16,
21189    pub right_site_budget: u16,
21190    pub left_total_site_count: u16,
21191    pub right_total_site_count: u16,
21192    pub left_euler: i32,
21193    pub right_euler: i32,
21194    pub left_entropy_nats_bits: u64,
21195    pub right_entropy_nats_bits: u64,
21196    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21197    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21198    pub combined_site_budget: u16,
21199    pub combined_site_count: u16,
21200    pub combined_euler: i32,
21201    pub combined_entropy_nats_bits: u64,
21202    pub combined_betti: [u32; MAX_BETTI_DIMENSION],
21203    pub combined_fingerprint: ContentFingerprint,
21204    pub combined_constraints: &'static [crate::pipeline::ConstraintRef],
21205    pub left_constraint_count: usize,
21206    pub tag_site: u16,
21207}
21208
21209/// Inputs to `CartesianProductWitness::mint_verified`. Matches the
21210/// CartesianProduct mint primitive's parameter list.
21211#[derive(Debug, Clone, Copy, PartialEq)]
21212pub struct CartesianProductMintInputs {
21213    pub witt_bits: u16,
21214    pub left_fingerprint: ContentFingerprint,
21215    pub right_fingerprint: ContentFingerprint,
21216    pub left_site_budget: u16,
21217    pub right_site_budget: u16,
21218    pub left_total_site_count: u16,
21219    pub right_total_site_count: u16,
21220    pub left_euler: i32,
21221    pub right_euler: i32,
21222    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21223    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21224    pub left_entropy_nats_bits: u64,
21225    pub right_entropy_nats_bits: u64,
21226    pub combined_site_budget: u16,
21227    pub combined_site_count: u16,
21228    pub combined_euler: i32,
21229    pub combined_betti: [u32; MAX_BETTI_DIMENSION],
21230    pub combined_entropy_nats_bits: u64,
21231    pub combined_fingerprint: ContentFingerprint,
21232}
21233
21234/// Sealed PartitionProduct witness — content-addressed assertion that a
21235/// partition decomposes as `PartitionProduct(left, right)` per PT_2a.
21236/// Minting is gated on PT_1, PT_3, PT_4, and the foundation
21237/// `ProductLayoutWidth` invariant being verified against component
21238/// shapes. Existence of an instance is the attestation — there is no
21239/// partial or unverified form.
21240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21241pub struct PartitionProductWitness {
21242    witt_bits: u16,
21243    content_fingerprint: ContentFingerprint,
21244    left_fingerprint: ContentFingerprint,
21245    right_fingerprint: ContentFingerprint,
21246    combined_site_budget: u16,
21247    combined_site_count: u16,
21248}
21249
21250impl PartitionProductWitness {
21251    /// Witt level at which the witness was minted.
21252    #[inline]
21253    #[must_use]
21254    pub const fn witt_bits(&self) -> u16 {
21255        self.witt_bits
21256    }
21257    /// Content fingerprint of the combined (A × B) shape.
21258    #[inline]
21259    #[must_use]
21260    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21261        self.content_fingerprint
21262    }
21263    /// Content fingerprint of the left factor A.
21264    #[inline]
21265    #[must_use]
21266    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21267        self.left_fingerprint
21268    }
21269    /// Content fingerprint of the right factor B.
21270    #[inline]
21271    #[must_use]
21272    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21273        self.right_fingerprint
21274    }
21275    /// `siteBudget(A × B)` per PT_1.
21276    #[inline]
21277    #[must_use]
21278    pub const fn combined_site_budget(&self) -> u16 {
21279        self.combined_site_budget
21280    }
21281    /// `SITE_COUNT(A × B)` — the foundation layout width.
21282    #[inline]
21283    #[must_use]
21284    pub const fn combined_site_count(&self) -> u16 {
21285        self.combined_site_count
21286    }
21287    /// Crate-internal mint entry. Only the verified mint primitive may call this.
21288    #[inline]
21289    #[must_use]
21290    #[allow(clippy::too_many_arguments)]
21291    pub(crate) const fn with_level_fingerprints_and_sites(
21292        witt_bits: u16,
21293        content_fingerprint: ContentFingerprint,
21294        left_fingerprint: ContentFingerprint,
21295        right_fingerprint: ContentFingerprint,
21296        combined_site_budget: u16,
21297        combined_site_count: u16,
21298    ) -> Self {
21299        Self {
21300            witt_bits,
21301            content_fingerprint,
21302            left_fingerprint,
21303            right_fingerprint,
21304            combined_site_budget,
21305            combined_site_count,
21306        }
21307    }
21308}
21309
21310/// Sealed PartitionCoproduct witness — content-addressed assertion that a
21311/// partition decomposes as `PartitionCoproduct(left, right)` per PT_2b.
21312/// Minting verifies ST_1, ST_2, ST_6, ST_7, ST_8, ST_9, ST_10, the
21313/// foundation `CoproductLayoutWidth` invariant, and — for ST_6/ST_7/ST_8 —
21314/// walks the supplied constraint array through `validate_coproduct_structure`.
21315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21316pub struct PartitionCoproductWitness {
21317    witt_bits: u16,
21318    content_fingerprint: ContentFingerprint,
21319    left_fingerprint: ContentFingerprint,
21320    right_fingerprint: ContentFingerprint,
21321    combined_site_budget: u16,
21322    combined_site_count: u16,
21323    tag_site_index: u16,
21324}
21325
21326impl PartitionCoproductWitness {
21327    #[inline]
21328    #[must_use]
21329    pub const fn witt_bits(&self) -> u16 {
21330        self.witt_bits
21331    }
21332    #[inline]
21333    #[must_use]
21334    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21335        self.content_fingerprint
21336    }
21337    #[inline]
21338    #[must_use]
21339    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21340        self.left_fingerprint
21341    }
21342    #[inline]
21343    #[must_use]
21344    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21345        self.right_fingerprint
21346    }
21347    /// `siteBudget(A + B)` per ST_1 = max(siteBudget(A), siteBudget(B)).
21348    #[inline]
21349    #[must_use]
21350    pub const fn combined_site_budget(&self) -> u16 {
21351        self.combined_site_budget
21352    }
21353    /// `SITE_COUNT(A + B)` — the foundation layout width including the new tag site.
21354    #[inline]
21355    #[must_use]
21356    pub const fn combined_site_count(&self) -> u16 {
21357        self.combined_site_count
21358    }
21359    /// Index of the tag site in the layout convention of §4b'.
21360    /// Equals `max(SITE_COUNT(A), SITE_COUNT(B))`.
21361    #[inline]
21362    #[must_use]
21363    pub const fn tag_site_index(&self) -> u16 {
21364        self.tag_site_index
21365    }
21366    #[inline]
21367    #[must_use]
21368    #[allow(clippy::too_many_arguments)]
21369    pub(crate) const fn with_level_fingerprints_sites_and_tag(
21370        witt_bits: u16,
21371        content_fingerprint: ContentFingerprint,
21372        left_fingerprint: ContentFingerprint,
21373        right_fingerprint: ContentFingerprint,
21374        combined_site_budget: u16,
21375        combined_site_count: u16,
21376        tag_site_index: u16,
21377    ) -> Self {
21378        Self {
21379            witt_bits,
21380            content_fingerprint,
21381            left_fingerprint,
21382            right_fingerprint,
21383            combined_site_budget,
21384            combined_site_count,
21385            tag_site_index,
21386        }
21387    }
21388}
21389
21390/// Sealed CartesianPartitionProduct witness — content-addressed
21391/// assertion that a shape is `CartesianPartitionProduct(left, right)`
21392/// per CPT_2a. Minting verifies CPT_1, CPT_3, CPT_4, CPT_5, and the
21393/// foundation `CartesianLayoutWidth` invariant. The witness stores
21394/// a snapshot of the combined topological invariants (χ, Betti profile)
21395/// because the construction is axiomatic at the invariant level per §3c.
21396/// Entropy is not stored here (f64 has no Eq/Hash); use the paired
21397/// `CartesianProductEvidence` for entropy re-audit.
21398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21399pub struct CartesianProductWitness {
21400    witt_bits: u16,
21401    content_fingerprint: ContentFingerprint,
21402    left_fingerprint: ContentFingerprint,
21403    right_fingerprint: ContentFingerprint,
21404    combined_site_budget: u16,
21405    combined_site_count: u16,
21406    combined_euler: i32,
21407    combined_betti: [u32; MAX_BETTI_DIMENSION],
21408}
21409
21410impl CartesianProductWitness {
21411    #[inline]
21412    #[must_use]
21413    pub const fn witt_bits(&self) -> u16 {
21414        self.witt_bits
21415    }
21416    #[inline]
21417    #[must_use]
21418    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21419        self.content_fingerprint
21420    }
21421    #[inline]
21422    #[must_use]
21423    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21424        self.left_fingerprint
21425    }
21426    #[inline]
21427    #[must_use]
21428    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21429        self.right_fingerprint
21430    }
21431    #[inline]
21432    #[must_use]
21433    pub const fn combined_site_budget(&self) -> u16 {
21434        self.combined_site_budget
21435    }
21436    #[inline]
21437    #[must_use]
21438    pub const fn combined_site_count(&self) -> u16 {
21439        self.combined_site_count
21440    }
21441    #[inline]
21442    #[must_use]
21443    pub const fn combined_euler(&self) -> i32 {
21444        self.combined_euler
21445    }
21446    #[inline]
21447    #[must_use]
21448    pub const fn combined_betti(&self) -> [u32; MAX_BETTI_DIMENSION] {
21449        self.combined_betti
21450    }
21451    #[inline]
21452    #[must_use]
21453    #[allow(clippy::too_many_arguments)]
21454    pub(crate) const fn with_level_fingerprints_and_invariants(
21455        witt_bits: u16,
21456        content_fingerprint: ContentFingerprint,
21457        left_fingerprint: ContentFingerprint,
21458        right_fingerprint: ContentFingerprint,
21459        combined_site_budget: u16,
21460        combined_site_count: u16,
21461        combined_euler: i32,
21462        combined_betti: [u32; MAX_BETTI_DIMENSION],
21463    ) -> Self {
21464        Self {
21465            witt_bits,
21466            content_fingerprint,
21467            left_fingerprint,
21468            right_fingerprint,
21469            combined_site_budget,
21470            combined_site_count,
21471            combined_euler,
21472            combined_betti,
21473        }
21474    }
21475}
21476
21477impl Certificate for PartitionProductWitness {
21478    const IRI: &'static str = "https://uor.foundation/partition/PartitionProduct";
21479    type Evidence = PartitionProductEvidence;
21480}
21481
21482impl Certificate for PartitionCoproductWitness {
21483    const IRI: &'static str = "https://uor.foundation/partition/PartitionCoproduct";
21484    type Evidence = PartitionCoproductEvidence;
21485}
21486
21487impl Certificate for CartesianProductWitness {
21488    const IRI: &'static str = "https://uor.foundation/partition/CartesianPartitionProduct";
21489    type Evidence = CartesianProductEvidence;
21490}
21491
21492impl core::fmt::Display for PartitionProductWitness {
21493    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21494        f.write_str("PartitionProductWitness")
21495    }
21496}
21497impl core::error::Error for PartitionProductWitness {}
21498
21499impl core::fmt::Display for PartitionCoproductWitness {
21500    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21501        f.write_str("PartitionCoproductWitness")
21502    }
21503}
21504impl core::error::Error for PartitionCoproductWitness {}
21505
21506impl core::fmt::Display for CartesianProductWitness {
21507    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21508        f.write_str("CartesianProductWitness")
21509    }
21510}
21511impl core::error::Error for CartesianProductWitness {}
21512
21513/// Sealed mint path for certificates that require multi-theorem verification
21514/// before minting. Introduced by the Product/Coproduct Completion Amendment
21515/// §1c; distinct from `MintWithLevelFingerprint` (which is the generic
21516/// partial-mint path for sealed shims). `VerifiedMint` implementors are
21517/// the three partition-algebra witnesses, each routing through a
21518/// foundation-internal mint primitive that verifies the relevant theorems.
21519/// The trait is public so external callers can invoke `mint_verified`
21520/// directly, but the `Certificate` supertrait's `certificate_sealed::Sealed`
21521/// bound keeps the implementor set closed to this crate.
21522pub trait VerifiedMint: Certificate {
21523    /// Caller-supplied input bundle — one `*MintInputs` struct per witness.
21524    type Inputs;
21525    /// Failure kind — always `GenericImpossibilityWitness` citing the
21526    /// specific op-namespace theorem or foundation-namespace layout
21527    /// invariant that was violated.
21528    type Error;
21529    /// Verify the theorems and invariants against `inputs`, then mint a
21530    /// witness or return a typed impossibility witness.
21531    /// # Errors
21532    /// Returns a `GenericImpossibilityWitness::for_identity(iri)` when any
21533    /// of the gated theorems or foundation invariants fails. The IRI
21534    /// identifies exactly which identity failed — `op/PT_*`, `op/ST_*`,
21535    /// `op/CPT_*`, or `foundation/*LayoutWidth` / `foundation/CoproductTagEncoding`.
21536    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error>
21537    where
21538        Self: Sized;
21539}
21540
21541/// Recursive classifier used by `validate_coproduct_structure`. Inspects
21542/// one `ConstraintRef`, tallies tag-pinner sightings via mutable references,
21543/// and recurses into `Conjunction` conjuncts up to `max_depth` levels. See
21544/// plan §A4 for the depth bound rationale.
21545#[allow(clippy::too_many_arguments)]
21546fn pc_classify_constraint(
21547    c: &crate::pipeline::ConstraintRef,
21548    in_left_region: bool,
21549    tag_site: u16,
21550    max_depth: u32,
21551    left_pins: &mut u32,
21552    right_pins: &mut u32,
21553    left_bias_ok: &mut bool,
21554    right_bias_ok: &mut bool,
21555) -> Result<(), GenericImpossibilityWitness> {
21556    match c {
21557        crate::pipeline::ConstraintRef::Site { position } => {
21558            if (*position as u16) >= tag_site {
21559                return Err(GenericImpossibilityWitness::for_identity(
21560                    "https://uor.foundation/op/ST_6",
21561                ));
21562            }
21563        }
21564        crate::pipeline::ConstraintRef::Carry { site } => {
21565            if (*site as u16) >= tag_site {
21566                return Err(GenericImpossibilityWitness::for_identity(
21567                    "https://uor.foundation/op/ST_6",
21568                ));
21569            }
21570        }
21571        crate::pipeline::ConstraintRef::Affine { coefficients, coefficient_count, bias } => {
21572            let count = *coefficient_count as usize;
21573            let mut nonzero_count: u32 = 0;
21574            let mut nonzero_index: usize = 0;
21575            let mut max_nonzero_index: usize = 0;
21576            let mut i: usize = 0;
21577            while i < count && i < crate::pipeline::AFFINE_MAX_COEFFS {
21578                if coefficients[i] != 0 {
21579                    nonzero_count = nonzero_count.saturating_add(1);
21580                    nonzero_index = i;
21581                    if i > max_nonzero_index { max_nonzero_index = i; }
21582                }
21583                i += 1;
21584            }
21585            let touches_tag_site = nonzero_count > 0
21586                && (max_nonzero_index as u16) >= tag_site;
21587            let is_canonical_tag_pinner = nonzero_count == 1
21588                && (nonzero_index as u16) == tag_site
21589                && coefficients[nonzero_index] == 1;
21590            if is_canonical_tag_pinner {
21591                if *bias != 0 && *bias != -1 {
21592                    return Err(GenericImpossibilityWitness::for_identity(
21593                        "https://uor.foundation/foundation/CoproductTagEncoding",
21594                    ));
21595                }
21596                if in_left_region {
21597                    *left_pins = left_pins.saturating_add(1);
21598                    if *bias != 0 { *left_bias_ok = false; }
21599                } else {
21600                    *right_pins = right_pins.saturating_add(1);
21601                    if *bias != -1 { *right_bias_ok = false; }
21602                }
21603            } else if touches_tag_site {
21604                let nonzero_only_at_tag_site = nonzero_count == 1
21605                    && (nonzero_index as u16) == tag_site;
21606                if nonzero_only_at_tag_site {
21607                    return Err(GenericImpossibilityWitness::for_identity(
21608                        "https://uor.foundation/foundation/CoproductTagEncoding",
21609                    ));
21610                } else {
21611                    return Err(GenericImpossibilityWitness::for_identity(
21612                        "https://uor.foundation/op/ST_6",
21613                    ));
21614                }
21615            }
21616        }
21617        crate::pipeline::ConstraintRef::Conjunction { conjuncts, conjunct_count } => {
21618            if max_depth == 0 {
21619                return Err(GenericImpossibilityWitness::for_identity(
21620                    "https://uor.foundation/op/ST_6",
21621                ));
21622            }
21623            let count = *conjunct_count as usize;
21624            let mut idx: usize = 0;
21625            while idx < count && idx < crate::pipeline::CONJUNCTION_MAX_TERMS {
21626                let lifted = conjuncts[idx].into_constraint();
21627                pc_classify_constraint(
21628                    &lifted,
21629                    in_left_region,
21630                    tag_site,
21631                    max_depth - 1,
21632                    left_pins,
21633                    right_pins,
21634                    left_bias_ok,
21635                    right_bias_ok,
21636                )?;
21637                idx += 1;
21638            }
21639        }
21640        crate::pipeline::ConstraintRef::Residue { .. }
21641        | crate::pipeline::ConstraintRef::Hamming { .. }
21642        | crate::pipeline::ConstraintRef::Depth { .. }
21643        | crate::pipeline::ConstraintRef::SatClauses { .. }
21644        | crate::pipeline::ConstraintRef::Bound { .. }
21645        // ADR-057: Recurse references a shape by content-addressed IRI;
21646        // no site references at this level to check.
21647        | crate::pipeline::ConstraintRef::Recurse { .. } => {
21648            // No site references at this level; nothing to check.
21649        }
21650    }
21651    Ok(())
21652}
21653
21654/// Validates ST_6 / ST_7 / ST_8 for a PartitionCoproduct construction by
21655/// walking the emitted constraint array. Recurses into
21656/// `ConstraintRef::Conjunction` conjuncts up to depth 8 (bounded by
21657/// `NERVE_CONSTRAINTS_CAP`) so nested constructions are audited without
21658/// unbounded recursion.
21659/// # Errors
21660/// Returns `GenericImpossibilityWitness::for_identity(...)` citing the
21661/// specific failed identity: `op/ST_6`, `op/ST_7`, or
21662/// `foundation/CoproductTagEncoding`. ST_8 is implied by ST_6 ∧ ST_7 and
21663/// is not cited separately on failure.
21664pub(crate) fn validate_coproduct_structure(
21665    combined_constraints: &[crate::pipeline::ConstraintRef],
21666    left_constraint_count: usize,
21667    tag_site: u16,
21668) -> Result<(), GenericImpossibilityWitness> {
21669    let mut left_pins: u32 = 0;
21670    let mut right_pins: u32 = 0;
21671    let mut left_bias_ok: bool = true;
21672    let mut right_bias_ok: bool = true;
21673    let mut idx: usize = 0;
21674    while idx < combined_constraints.len() {
21675        let in_left_region = idx < left_constraint_count;
21676        pc_classify_constraint(
21677            &combined_constraints[idx],
21678            in_left_region,
21679            tag_site,
21680            NERVE_CONSTRAINTS_CAP as u32,
21681            &mut left_pins,
21682            &mut right_pins,
21683            &mut left_bias_ok,
21684            &mut right_bias_ok,
21685        )?;
21686        idx += 1;
21687    }
21688    if left_pins != 1 || right_pins != 1 {
21689        return Err(GenericImpossibilityWitness::for_identity(
21690            "https://uor.foundation/op/ST_6",
21691        ));
21692    }
21693    if !left_bias_ok || !right_bias_ok {
21694        return Err(GenericImpossibilityWitness::for_identity(
21695            "https://uor.foundation/op/ST_7",
21696        ));
21697    }
21698    Ok(())
21699}
21700
21701/// Mint a `PartitionProductWitness` after verifying PT_1, PT_3, PT_4, and
21702/// the `ProductLayoutWidth` layout invariant. PT_2a is structural (the
21703/// witness existing is the claim); no separate check is needed once the
21704/// invariants match.
21705#[allow(clippy::too_many_arguments)]
21706pub(crate) fn pc_primitive_partition_product(
21707    witt_bits: u16,
21708    left_fingerprint: ContentFingerprint,
21709    right_fingerprint: ContentFingerprint,
21710    left_site_budget: u16,
21711    right_site_budget: u16,
21712    left_total_site_count: u16,
21713    right_total_site_count: u16,
21714    left_euler: i32,
21715    right_euler: i32,
21716    left_entropy_nats_bits: u64,
21717    right_entropy_nats_bits: u64,
21718    combined_site_budget: u16,
21719    combined_site_count: u16,
21720    combined_euler: i32,
21721    combined_entropy_nats_bits: u64,
21722    combined_fingerprint: ContentFingerprint,
21723) -> Result<PartitionProductWitness, GenericImpossibilityWitness> {
21724    let left_entropy_nats =
21725        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21726    let right_entropy_nats =
21727        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21728    let combined_entropy_nats =
21729        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21730    if combined_site_budget != left_site_budget.saturating_add(right_site_budget) {
21731        return Err(GenericImpossibilityWitness::for_identity(
21732            "https://uor.foundation/op/PT_1",
21733        ));
21734    }
21735    if combined_site_count != left_total_site_count.saturating_add(right_total_site_count) {
21736        return Err(GenericImpossibilityWitness::for_identity(
21737            "https://uor.foundation/foundation/ProductLayoutWidth",
21738        ));
21739    }
21740    if combined_euler != left_euler.saturating_add(right_euler) {
21741        return Err(GenericImpossibilityWitness::for_identity(
21742            "https://uor.foundation/op/PT_3",
21743        ));
21744    }
21745    if !pc_entropy_input_is_valid(left_entropy_nats)
21746        || !pc_entropy_input_is_valid(right_entropy_nats)
21747        || !pc_entropy_input_is_valid(combined_entropy_nats)
21748    {
21749        return Err(GenericImpossibilityWitness::for_identity(
21750            "https://uor.foundation/op/PT_4",
21751        ));
21752    }
21753    let expected_entropy = left_entropy_nats + right_entropy_nats;
21754    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21755        return Err(GenericImpossibilityWitness::for_identity(
21756            "https://uor.foundation/op/PT_4",
21757        ));
21758    }
21759    Ok(PartitionProductWitness::with_level_fingerprints_and_sites(
21760        witt_bits,
21761        combined_fingerprint,
21762        left_fingerprint,
21763        right_fingerprint,
21764        combined_site_budget,
21765        combined_site_count,
21766    ))
21767}
21768
21769/// Mint a `PartitionCoproductWitness` after verifying ST_1, ST_2, ST_6,
21770/// ST_7, ST_8, ST_9, ST_10, the `CoproductLayoutWidth` layout invariant,
21771/// the tag-site alignment against §4b', and running
21772/// `validate_coproduct_structure` over the supplied constraint array.
21773#[allow(clippy::too_many_arguments)]
21774pub(crate) fn pc_primitive_partition_coproduct(
21775    witt_bits: u16,
21776    left_fingerprint: ContentFingerprint,
21777    right_fingerprint: ContentFingerprint,
21778    left_site_budget: u16,
21779    right_site_budget: u16,
21780    left_total_site_count: u16,
21781    right_total_site_count: u16,
21782    left_euler: i32,
21783    right_euler: i32,
21784    left_entropy_nats_bits: u64,
21785    right_entropy_nats_bits: u64,
21786    left_betti: [u32; MAX_BETTI_DIMENSION],
21787    right_betti: [u32; MAX_BETTI_DIMENSION],
21788    combined_site_budget: u16,
21789    combined_site_count: u16,
21790    combined_euler: i32,
21791    combined_entropy_nats_bits: u64,
21792    combined_betti: [u32; MAX_BETTI_DIMENSION],
21793    combined_fingerprint: ContentFingerprint,
21794    combined_constraints: &[crate::pipeline::ConstraintRef],
21795    left_constraint_count: usize,
21796    tag_site: u16,
21797) -> Result<PartitionCoproductWitness, GenericImpossibilityWitness> {
21798    let left_entropy_nats =
21799        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21800    let right_entropy_nats =
21801        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21802    let combined_entropy_nats =
21803        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21804    let expected_budget = if left_site_budget > right_site_budget {
21805        left_site_budget
21806    } else {
21807        right_site_budget
21808    };
21809    if combined_site_budget != expected_budget {
21810        return Err(GenericImpossibilityWitness::for_identity(
21811            "https://uor.foundation/op/ST_1",
21812        ));
21813    }
21814    let max_total = if left_total_site_count > right_total_site_count {
21815        left_total_site_count
21816    } else {
21817        right_total_site_count
21818    };
21819    let expected_total = max_total.saturating_add(1);
21820    if combined_site_count != expected_total {
21821        return Err(GenericImpossibilityWitness::for_identity(
21822            "https://uor.foundation/foundation/CoproductLayoutWidth",
21823        ));
21824    }
21825    if !pc_entropy_input_is_valid(left_entropy_nats)
21826        || !pc_entropy_input_is_valid(right_entropy_nats)
21827        || !pc_entropy_input_is_valid(combined_entropy_nats)
21828    {
21829        return Err(GenericImpossibilityWitness::for_identity(
21830            "https://uor.foundation/op/ST_2",
21831        ));
21832    }
21833    let max_operand_entropy = if left_entropy_nats > right_entropy_nats {
21834        left_entropy_nats
21835    } else {
21836        right_entropy_nats
21837    };
21838    let expected_entropy = core::f64::consts::LN_2 + max_operand_entropy;
21839    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21840        return Err(GenericImpossibilityWitness::for_identity(
21841            "https://uor.foundation/op/ST_2",
21842        ));
21843    }
21844    if tag_site != max_total {
21845        return Err(GenericImpossibilityWitness::for_identity(
21846            "https://uor.foundation/foundation/CoproductLayoutWidth",
21847        ));
21848    }
21849    validate_coproduct_structure(combined_constraints, left_constraint_count, tag_site)?;
21850    if combined_euler != left_euler.saturating_add(right_euler) {
21851        return Err(GenericImpossibilityWitness::for_identity(
21852            "https://uor.foundation/op/ST_9",
21853        ));
21854    }
21855    let mut k: usize = 0;
21856    while k < MAX_BETTI_DIMENSION {
21857        if combined_betti[k] != left_betti[k].saturating_add(right_betti[k]) {
21858            return Err(GenericImpossibilityWitness::for_identity(
21859                "https://uor.foundation/op/ST_10",
21860            ));
21861        }
21862        k += 1;
21863    }
21864    Ok(
21865        PartitionCoproductWitness::with_level_fingerprints_sites_and_tag(
21866            witt_bits,
21867            combined_fingerprint,
21868            left_fingerprint,
21869            right_fingerprint,
21870            combined_site_budget,
21871            combined_site_count,
21872            max_total,
21873        ),
21874    )
21875}
21876
21877/// Mint a `CartesianProductWitness` after verifying CPT_1, CPT_3, CPT_4,
21878/// CPT_5, and the `CartesianLayoutWidth` layout invariant. Checks
21879/// caller-supplied Künneth-composed invariants against the component
21880/// values (the witness defines these axiomatically per §3c).
21881#[allow(clippy::too_many_arguments)]
21882pub(crate) fn pc_primitive_cartesian_product(
21883    witt_bits: u16,
21884    left_fingerprint: ContentFingerprint,
21885    right_fingerprint: ContentFingerprint,
21886    left_site_budget: u16,
21887    right_site_budget: u16,
21888    left_total_site_count: u16,
21889    right_total_site_count: u16,
21890    left_euler: i32,
21891    right_euler: i32,
21892    left_betti: [u32; MAX_BETTI_DIMENSION],
21893    right_betti: [u32; MAX_BETTI_DIMENSION],
21894    left_entropy_nats_bits: u64,
21895    right_entropy_nats_bits: u64,
21896    combined_site_budget: u16,
21897    combined_site_count: u16,
21898    combined_euler: i32,
21899    combined_betti: [u32; MAX_BETTI_DIMENSION],
21900    combined_entropy_nats_bits: u64,
21901    combined_fingerprint: ContentFingerprint,
21902) -> Result<CartesianProductWitness, GenericImpossibilityWitness> {
21903    let left_entropy_nats =
21904        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21905    let right_entropy_nats =
21906        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21907    let combined_entropy_nats =
21908        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21909    if combined_site_budget != left_site_budget.saturating_add(right_site_budget) {
21910        return Err(GenericImpossibilityWitness::for_identity(
21911            "https://uor.foundation/op/CPT_1",
21912        ));
21913    }
21914    if combined_site_count != left_total_site_count.saturating_add(right_total_site_count) {
21915        return Err(GenericImpossibilityWitness::for_identity(
21916            "https://uor.foundation/foundation/CartesianLayoutWidth",
21917        ));
21918    }
21919    if combined_euler != left_euler.saturating_mul(right_euler) {
21920        return Err(GenericImpossibilityWitness::for_identity(
21921            "https://uor.foundation/op/CPT_3",
21922        ));
21923    }
21924    let kunneth = crate::pipeline::kunneth_compose(&left_betti, &right_betti);
21925    let mut k: usize = 0;
21926    while k < MAX_BETTI_DIMENSION {
21927        if combined_betti[k] != kunneth[k] {
21928            return Err(GenericImpossibilityWitness::for_identity(
21929                "https://uor.foundation/op/CPT_4",
21930            ));
21931        }
21932        k += 1;
21933    }
21934    if !pc_entropy_input_is_valid(left_entropy_nats)
21935        || !pc_entropy_input_is_valid(right_entropy_nats)
21936        || !pc_entropy_input_is_valid(combined_entropy_nats)
21937    {
21938        return Err(GenericImpossibilityWitness::for_identity(
21939            "https://uor.foundation/op/CPT_5",
21940        ));
21941    }
21942    let expected_entropy = left_entropy_nats + right_entropy_nats;
21943    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21944        return Err(GenericImpossibilityWitness::for_identity(
21945            "https://uor.foundation/op/CPT_5",
21946        ));
21947    }
21948    Ok(
21949        CartesianProductWitness::with_level_fingerprints_and_invariants(
21950            witt_bits,
21951            combined_fingerprint,
21952            left_fingerprint,
21953            right_fingerprint,
21954            combined_site_budget,
21955            combined_site_count,
21956            combined_euler,
21957            combined_betti,
21958        ),
21959    )
21960}
21961
21962impl VerifiedMint for PartitionProductWitness {
21963    type Inputs = PartitionProductMintInputs;
21964    type Error = GenericImpossibilityWitness;
21965    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
21966        pc_primitive_partition_product(
21967            inputs.witt_bits,
21968            inputs.left_fingerprint,
21969            inputs.right_fingerprint,
21970            inputs.left_site_budget,
21971            inputs.right_site_budget,
21972            inputs.left_total_site_count,
21973            inputs.right_total_site_count,
21974            inputs.left_euler,
21975            inputs.right_euler,
21976            inputs.left_entropy_nats_bits,
21977            inputs.right_entropy_nats_bits,
21978            inputs.combined_site_budget,
21979            inputs.combined_site_count,
21980            inputs.combined_euler,
21981            inputs.combined_entropy_nats_bits,
21982            inputs.combined_fingerprint,
21983        )
21984    }
21985}
21986
21987impl VerifiedMint for PartitionCoproductWitness {
21988    type Inputs = PartitionCoproductMintInputs;
21989    type Error = GenericImpossibilityWitness;
21990    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
21991        pc_primitive_partition_coproduct(
21992            inputs.witt_bits,
21993            inputs.left_fingerprint,
21994            inputs.right_fingerprint,
21995            inputs.left_site_budget,
21996            inputs.right_site_budget,
21997            inputs.left_total_site_count,
21998            inputs.right_total_site_count,
21999            inputs.left_euler,
22000            inputs.right_euler,
22001            inputs.left_entropy_nats_bits,
22002            inputs.right_entropy_nats_bits,
22003            inputs.left_betti,
22004            inputs.right_betti,
22005            inputs.combined_site_budget,
22006            inputs.combined_site_count,
22007            inputs.combined_euler,
22008            inputs.combined_entropy_nats_bits,
22009            inputs.combined_betti,
22010            inputs.combined_fingerprint,
22011            inputs.combined_constraints,
22012            inputs.left_constraint_count,
22013            inputs.tag_site,
22014        )
22015    }
22016}
22017
22018impl VerifiedMint for CartesianProductWitness {
22019    type Inputs = CartesianProductMintInputs;
22020    type Error = GenericImpossibilityWitness;
22021    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
22022        pc_primitive_cartesian_product(
22023            inputs.witt_bits,
22024            inputs.left_fingerprint,
22025            inputs.right_fingerprint,
22026            inputs.left_site_budget,
22027            inputs.right_site_budget,
22028            inputs.left_total_site_count,
22029            inputs.right_total_site_count,
22030            inputs.left_euler,
22031            inputs.right_euler,
22032            inputs.left_betti,
22033            inputs.right_betti,
22034            inputs.left_entropy_nats_bits,
22035            inputs.right_entropy_nats_bits,
22036            inputs.combined_site_budget,
22037            inputs.combined_site_count,
22038            inputs.combined_euler,
22039            inputs.combined_betti,
22040            inputs.combined_entropy_nats_bits,
22041            inputs.combined_fingerprint,
22042        )
22043    }
22044}
22045
22046/// Data record of a partition's runtime-queried properties. Produced at
22047/// witness-mint time and consulted by consumer code that holds a
22048/// `PartitionHandle` and a `PartitionResolver`. Phase 9 stores entropy
22049/// as the IEEE-754 `u64` bit-pattern (`entropy_nats_bits`) so the record
22050/// derives `Eq + Hash` cleanly; consumers project to `H::Decimal` via
22051/// `<H::Decimal as DecimalTranscendental>::from_bits`.
22052#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22053pub struct PartitionRecord<H: crate::HostTypes> {
22054    /// Data sites only — the partition's `siteBudget`, not its layout width.
22055    pub site_budget: u16,
22056    /// Euler characteristic of the partition's nerve.
22057    pub euler: i32,
22058    /// Betti profile of the partition's nerve, padded to `MAX_BETTI_DIMENSION`.
22059    pub betti: [u32; MAX_BETTI_DIMENSION],
22060    /// Shannon entropy in nats (matches `LandauerBudget::nats()` convention).
22061    pub entropy_nats_bits: u64,
22062    _phantom: core::marker::PhantomData<H>,
22063}
22064
22065impl<H: crate::HostTypes> PartitionRecord<H> {
22066    /// Construct a new record. The phantom marker ensures records are
22067    /// parameterized by the host types they originate from.
22068    #[inline]
22069    #[must_use]
22070    pub const fn new(
22071        site_budget: u16,
22072        euler: i32,
22073        betti: [u32; MAX_BETTI_DIMENSION],
22074        entropy_nats_bits: u64,
22075    ) -> Self {
22076        Self {
22077            site_budget,
22078            euler,
22079            betti,
22080            entropy_nats_bits,
22081            _phantom: core::marker::PhantomData,
22082        }
22083    }
22084}
22085
22086/// Resolver mapping content fingerprints to `PartitionRecord`s. Provided
22087/// by the host application — typically a persistent store, an in-memory
22088/// registry populated from witness mint-time data, or a chain-of-witnesses
22089/// trail that can reconstruct properties.
22090pub trait PartitionResolver<H: crate::HostTypes> {
22091    /// Look up partition data by fingerprint. Returns `None` if the
22092    /// resolver has no record for the handle. Handles remain valid as
22093    /// identity tokens regardless of resolver presence.
22094    fn resolve(&self, fp: ContentFingerprint) -> Option<PartitionRecord<H>>;
22095}
22096
22097/// Content-addressed identity token for a partition. Carries only a
22098/// fingerprint; partition data is recovered by pairing the handle with a
22099/// `PartitionResolver` via `resolve_with`. Handles compare and hash by
22100/// fingerprint, so they can serve as keys in content-addressed indices
22101/// without resolver access.
22102#[derive(Debug)]
22103pub struct PartitionHandle<H: crate::HostTypes> {
22104    fingerprint: ContentFingerprint,
22105    _phantom: core::marker::PhantomData<H>,
22106}
22107impl<H: crate::HostTypes> Copy for PartitionHandle<H> {}
22108impl<H: crate::HostTypes> Clone for PartitionHandle<H> {
22109    #[inline]
22110    fn clone(&self) -> Self {
22111        *self
22112    }
22113}
22114impl<H: crate::HostTypes> PartialEq for PartitionHandle<H> {
22115    #[inline]
22116    fn eq(&self, other: &Self) -> bool {
22117        self.fingerprint == other.fingerprint
22118    }
22119}
22120impl<H: crate::HostTypes> Eq for PartitionHandle<H> {}
22121impl<H: crate::HostTypes> core::hash::Hash for PartitionHandle<H> {
22122    #[inline]
22123    fn hash<S: core::hash::Hasher>(&self, state: &mut S) {
22124        self.fingerprint.hash(state);
22125    }
22126}
22127
22128impl<H: crate::HostTypes> PartitionHandle<H> {
22129    /// Construct a handle from a content fingerprint.
22130    #[inline]
22131    #[must_use]
22132    pub const fn from_fingerprint(fingerprint: ContentFingerprint) -> Self {
22133        Self {
22134            fingerprint,
22135            _phantom: core::marker::PhantomData,
22136        }
22137    }
22138    /// Return the content fingerprint this handle references.
22139    #[inline]
22140    #[must_use]
22141    pub const fn fingerprint(&self) -> ContentFingerprint {
22142        self.fingerprint
22143    }
22144    /// Resolve this handle against a consumer-supplied resolver.
22145    /// Returns `None` if the resolver has no record for this fingerprint.
22146    #[inline]
22147    pub fn resolve_with<R: PartitionResolver<H>>(
22148        &self,
22149        resolver: &R,
22150    ) -> Option<PartitionRecord<H>> {
22151        resolver.resolve(self.fingerprint)
22152    }
22153}
22154
22155/// Resolver-absent default `Element<H>`. Returns empty defaults via the
22156/// `HostTypes::EMPTY_*` constants — used by `NullDatum<H>` and
22157/// `NullTypeDefinition<H>` to satisfy their `Element` associated types.
22158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22159pub struct NullElement<H: HostTypes> {
22160    _phantom: core::marker::PhantomData<H>,
22161}
22162impl<H: HostTypes> Default for NullElement<H> {
22163    fn default() -> Self {
22164        Self {
22165            _phantom: core::marker::PhantomData,
22166        }
22167    }
22168}
22169impl<H: HostTypes> crate::kernel::address::Element<H> for NullElement<H> {
22170    fn length(&self) -> u64 {
22171        0
22172    }
22173    fn addresses(&self) -> &H::HostString {
22174        H::EMPTY_HOST_STRING
22175    }
22176    fn digest(&self) -> &H::HostString {
22177        H::EMPTY_HOST_STRING
22178    }
22179    fn digest_algorithm(&self) -> &H::HostString {
22180        H::EMPTY_HOST_STRING
22181    }
22182    fn canonical_bytes(&self) -> &H::WitnessBytes {
22183        H::EMPTY_WITNESS_BYTES
22184    }
22185    fn witt_length(&self) -> u64 {
22186        0
22187    }
22188}
22189
22190/// Resolver-absent default `Datum<H>`. All numeric methods return 0.
22191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22192pub struct NullDatum<H: HostTypes> {
22193    element: NullElement<H>,
22194    _phantom: core::marker::PhantomData<H>,
22195}
22196impl<H: HostTypes> Default for NullDatum<H> {
22197    fn default() -> Self {
22198        Self {
22199            element: NullElement::default(),
22200            _phantom: core::marker::PhantomData,
22201        }
22202    }
22203}
22204impl<H: HostTypes> crate::kernel::schema::Datum<H> for NullDatum<H> {
22205    fn value(&self) -> u64 {
22206        0
22207    }
22208    fn witt_length(&self) -> u64 {
22209        0
22210    }
22211    fn stratum(&self) -> u64 {
22212        0
22213    }
22214    fn spectrum(&self) -> u64 {
22215        0
22216    }
22217    type Element = NullElement<H>;
22218    fn element(&self) -> &Self::Element {
22219        &self.element
22220    }
22221}
22222
22223/// Resolver-absent default `TermExpression<H>`. Empty marker trait, no methods.
22224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22225pub struct NullTermExpression<H: HostTypes> {
22226    _phantom: core::marker::PhantomData<H>,
22227}
22228impl<H: HostTypes> Default for NullTermExpression<H> {
22229    fn default() -> Self {
22230        Self {
22231            _phantom: core::marker::PhantomData,
22232        }
22233    }
22234}
22235impl<H: HostTypes> crate::kernel::schema::TermExpression<H> for NullTermExpression<H> {}
22236
22237/// Resolver-absent default `SiteIndex<H>`. Self-recursive: `ancilla_site()`
22238/// returns `&self` (no ancilla pairing in the default).
22239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22240pub struct NullSiteIndex<H: HostTypes> {
22241    _phantom: core::marker::PhantomData<H>,
22242}
22243impl<H: HostTypes> Default for NullSiteIndex<H> {
22244    fn default() -> Self {
22245        Self {
22246            _phantom: core::marker::PhantomData,
22247        }
22248    }
22249}
22250impl<H: HostTypes> crate::bridge::partition::SiteIndex<H> for NullSiteIndex<H> {
22251    fn site_position(&self) -> u64 {
22252        0
22253    }
22254    fn site_state(&self) -> u64 {
22255        0
22256    }
22257    type SiteIndexTarget = NullSiteIndex<H>;
22258    fn ancilla_site(&self) -> &Self::SiteIndexTarget {
22259        self
22260    }
22261}
22262
22263/// Resolver-absent default `TagSite<H>`. Embeds an inline `NullSiteIndex`
22264/// field so the inherited `ancilla_site()` accessor returns a valid
22265/// reference; `tag_value()` returns false.
22266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22267pub struct NullTagSite<H: HostTypes> {
22268    ancilla: NullSiteIndex<H>,
22269}
22270impl<H: HostTypes> Default for NullTagSite<H> {
22271    fn default() -> Self {
22272        Self {
22273            ancilla: NullSiteIndex::default(),
22274        }
22275    }
22276}
22277impl<H: HostTypes> crate::bridge::partition::SiteIndex<H> for NullTagSite<H> {
22278    fn site_position(&self) -> u64 {
22279        0
22280    }
22281    fn site_state(&self) -> u64 {
22282        0
22283    }
22284    type SiteIndexTarget = NullSiteIndex<H>;
22285    fn ancilla_site(&self) -> &Self::SiteIndexTarget {
22286        &self.ancilla
22287    }
22288}
22289impl<H: HostTypes> crate::bridge::partition::TagSite<H> for NullTagSite<H> {
22290    fn tag_value(&self) -> bool {
22291        false
22292    }
22293}
22294
22295/// Resolver-absent default `SiteBinding<H>`. Embeds inline `NullConstraint`
22296/// and `NullSiteIndex` so the trait's reference accessors work via &self.field.
22297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22298pub struct NullSiteBinding<H: HostTypes> {
22299    constraint: NullConstraint<H>,
22300    site_index: NullSiteIndex<H>,
22301}
22302impl<H: HostTypes> Default for NullSiteBinding<H> {
22303    fn default() -> Self {
22304        Self {
22305            constraint: NullConstraint::default(),
22306            site_index: NullSiteIndex::default(),
22307        }
22308    }
22309}
22310impl<H: HostTypes> crate::bridge::partition::SiteBinding<H> for NullSiteBinding<H> {
22311    type Constraint = NullConstraint<H>;
22312    fn pinned_by(&self) -> &Self::Constraint {
22313        &self.constraint
22314    }
22315    type SiteIndex = NullSiteIndex<H>;
22316    fn pins_coordinate(&self) -> &Self::SiteIndex {
22317        &self.site_index
22318    }
22319}
22320
22321/// Resolver-absent default `Constraint<H>`. Returns Vertical metric axis,
22322/// empty pinned-sites slice, and zero crossing cost.
22323#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22324pub struct NullConstraint<H: HostTypes> {
22325    _phantom: core::marker::PhantomData<H>,
22326}
22327impl<H: HostTypes> Default for NullConstraint<H> {
22328    fn default() -> Self {
22329        Self {
22330            _phantom: core::marker::PhantomData,
22331        }
22332    }
22333}
22334impl<H: HostTypes> crate::user::type_::Constraint<H> for NullConstraint<H> {
22335    fn metric_axis(&self) -> MetricAxis {
22336        MetricAxis::Vertical
22337    }
22338    type SiteIndex = NullSiteIndex<H>;
22339    fn pins_sites(&self) -> &[Self::SiteIndex] {
22340        &[]
22341    }
22342    fn crossing_cost(&self) -> u64 {
22343        0
22344    }
22345}
22346
22347/// Resolver-absent default `FreeRank<H>`. Empty budget — `is_closed()` true,
22348/// zero counts. Empty `has_site` / `has_binding` slices.
22349#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22350pub struct NullFreeRank<H: HostTypes> {
22351    _phantom: core::marker::PhantomData<H>,
22352}
22353impl<H: HostTypes> Default for NullFreeRank<H> {
22354    fn default() -> Self {
22355        Self {
22356            _phantom: core::marker::PhantomData,
22357        }
22358    }
22359}
22360impl<H: HostTypes> crate::bridge::partition::FreeRank<H> for NullFreeRank<H> {
22361    fn total_sites(&self) -> u64 {
22362        0
22363    }
22364    fn pinned_count(&self) -> u64 {
22365        0
22366    }
22367    fn free_rank(&self) -> u64 {
22368        0
22369    }
22370    fn is_closed(&self) -> bool {
22371        true
22372    }
22373    type SiteIndex = NullSiteIndex<H>;
22374    fn has_site(&self) -> &[Self::SiteIndex] {
22375        &[]
22376    }
22377    type SiteBinding = NullSiteBinding<H>;
22378    fn has_binding(&self) -> &[Self::SiteBinding] {
22379        &[]
22380    }
22381    fn reversible_strategy(&self) -> bool {
22382        false
22383    }
22384}
22385
22386/// Resolver-absent default `IrreducibleSet<H>`. Implements `Component<H>` with empty
22387/// `member` slice and zero `cardinality`.
22388#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22389pub struct NullIrreducibleSet<H: HostTypes> {
22390    _phantom: core::marker::PhantomData<H>,
22391}
22392impl<H: HostTypes> Default for NullIrreducibleSet<H> {
22393    fn default() -> Self {
22394        Self {
22395            _phantom: core::marker::PhantomData,
22396        }
22397    }
22398}
22399impl<H: HostTypes> crate::bridge::partition::Component<H> for NullIrreducibleSet<H> {
22400    type Datum = NullDatum<H>;
22401    fn member(&self) -> &[Self::Datum] {
22402        &[]
22403    }
22404    fn cardinality(&self) -> u64 {
22405        0
22406    }
22407}
22408impl<H: HostTypes> crate::bridge::partition::IrreducibleSet<H> for NullIrreducibleSet<H> {}
22409
22410/// Resolver-absent default `ReducibleSet<H>`. Implements `Component<H>` with empty
22411/// `member` slice and zero `cardinality`.
22412#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22413pub struct NullReducibleSet<H: HostTypes> {
22414    _phantom: core::marker::PhantomData<H>,
22415}
22416impl<H: HostTypes> Default for NullReducibleSet<H> {
22417    fn default() -> Self {
22418        Self {
22419            _phantom: core::marker::PhantomData,
22420        }
22421    }
22422}
22423impl<H: HostTypes> crate::bridge::partition::Component<H> for NullReducibleSet<H> {
22424    type Datum = NullDatum<H>;
22425    fn member(&self) -> &[Self::Datum] {
22426        &[]
22427    }
22428    fn cardinality(&self) -> u64 {
22429        0
22430    }
22431}
22432impl<H: HostTypes> crate::bridge::partition::ReducibleSet<H> for NullReducibleSet<H> {}
22433
22434/// Resolver-absent default `UnitGroup<H>`. Implements `Component<H>` with empty
22435/// `member` slice and zero `cardinality`.
22436#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22437pub struct NullUnitGroup<H: HostTypes> {
22438    _phantom: core::marker::PhantomData<H>,
22439}
22440impl<H: HostTypes> Default for NullUnitGroup<H> {
22441    fn default() -> Self {
22442        Self {
22443            _phantom: core::marker::PhantomData,
22444        }
22445    }
22446}
22447impl<H: HostTypes> crate::bridge::partition::Component<H> for NullUnitGroup<H> {
22448    type Datum = NullDatum<H>;
22449    fn member(&self) -> &[Self::Datum] {
22450        &[]
22451    }
22452    fn cardinality(&self) -> u64 {
22453        0
22454    }
22455}
22456impl<H: HostTypes> crate::bridge::partition::UnitGroup<H> for NullUnitGroup<H> {}
22457
22458/// Resolver-absent default `Complement<H>`. Implements `Component<H>` plus
22459/// the `exterior_criteria()` accessor returning a reference to an embedded
22460/// `NullTermExpression`.
22461#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22462pub struct NullComplement<H: HostTypes> {
22463    term: NullTermExpression<H>,
22464}
22465impl<H: HostTypes> Default for NullComplement<H> {
22466    fn default() -> Self {
22467        Self {
22468            term: NullTermExpression::default(),
22469        }
22470    }
22471}
22472impl<H: HostTypes> crate::bridge::partition::Component<H> for NullComplement<H> {
22473    type Datum = NullDatum<H>;
22474    fn member(&self) -> &[Self::Datum] {
22475        &[]
22476    }
22477    fn cardinality(&self) -> u64 {
22478        0
22479    }
22480}
22481impl<H: HostTypes> crate::bridge::partition::Complement<H> for NullComplement<H> {
22482    type TermExpression = NullTermExpression<H>;
22483    fn exterior_criteria(&self) -> &Self::TermExpression {
22484        &self.term
22485    }
22486}
22487
22488/// Resolver-absent default `TypeDefinition<H>`. Embeds inline `NullElement`
22489/// for the content_address accessor.
22490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22491pub struct NullTypeDefinition<H: HostTypes> {
22492    element: NullElement<H>,
22493}
22494impl<H: HostTypes> Default for NullTypeDefinition<H> {
22495    fn default() -> Self {
22496        Self {
22497            element: NullElement::default(),
22498        }
22499    }
22500}
22501impl<H: HostTypes> crate::user::type_::TypeDefinition<H> for NullTypeDefinition<H> {
22502    type Element = NullElement<H>;
22503    fn content_address(&self) -> &Self::Element {
22504        &self.element
22505    }
22506}
22507
22508/// Resolver-absent default `Partition<H>`. Embeds inline stubs for every
22509/// sub-trait associated type so `Partition<H>` accessors return references
22510/// to fields rather than to statics. The only meaningful state is the
22511/// `fingerprint`; everything else uses `HostTypes::EMPTY_*` defaults.
22512/// Returned by the three witness trait impls' `left_factor` / `right_factor`
22513/// / `left_summand` / etc. accessors as the resolver-absent value pathway.
22514/// Consumers needing real partition data pair the sibling `PartitionHandle`
22515/// with a `PartitionResolver` instead.
22516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22517pub struct NullPartition<H: HostTypes> {
22518    irreducibles: NullIrreducibleSet<H>,
22519    reducibles: NullReducibleSet<H>,
22520    units: NullUnitGroup<H>,
22521    exterior: NullComplement<H>,
22522    free_rank: NullFreeRank<H>,
22523    tag_site: NullTagSite<H>,
22524    source_type: NullTypeDefinition<H>,
22525    fingerprint: ContentFingerprint,
22526}
22527
22528impl<H: HostTypes> NullPartition<H> {
22529    /// Construct a NullPartition with the given content fingerprint.
22530    /// All other fields are resolver-absent defaults.
22531    #[inline]
22532    #[must_use]
22533    pub fn from_fingerprint(fingerprint: ContentFingerprint) -> Self {
22534        Self {
22535            irreducibles: NullIrreducibleSet::default(),
22536            reducibles: NullReducibleSet::default(),
22537            units: NullUnitGroup::default(),
22538            exterior: NullComplement::default(),
22539            free_rank: NullFreeRank::default(),
22540            tag_site: NullTagSite::default(),
22541            source_type: NullTypeDefinition::default(),
22542            fingerprint,
22543        }
22544    }
22545    /// Returns the content fingerprint identifying which Partition this stub stands in for.
22546    #[inline]
22547    #[must_use]
22548    pub const fn fingerprint(&self) -> ContentFingerprint {
22549        self.fingerprint
22550    }
22551    /// Phase 2 (orphan-closure): absent-value sentinel used by Null stubs
22552    /// in other namespaces to satisfy `&Self::Partition` return borrows.
22553    pub const ABSENT: NullPartition<H> = NullPartition {
22554        irreducibles: NullIrreducibleSet {
22555            _phantom: core::marker::PhantomData,
22556        },
22557        reducibles: NullReducibleSet {
22558            _phantom: core::marker::PhantomData,
22559        },
22560        units: NullUnitGroup {
22561            _phantom: core::marker::PhantomData,
22562        },
22563        exterior: NullComplement {
22564            term: NullTermExpression {
22565                _phantom: core::marker::PhantomData,
22566            },
22567        },
22568        free_rank: NullFreeRank {
22569            _phantom: core::marker::PhantomData,
22570        },
22571        tag_site: NullTagSite {
22572            ancilla: NullSiteIndex {
22573                _phantom: core::marker::PhantomData,
22574            },
22575        },
22576        source_type: NullTypeDefinition {
22577            element: NullElement {
22578                _phantom: core::marker::PhantomData,
22579            },
22580        },
22581        fingerprint: ContentFingerprint::zero(),
22582    };
22583}
22584
22585impl<H: HostTypes> crate::bridge::partition::Partition<H> for NullPartition<H> {
22586    type IrreducibleSet = NullIrreducibleSet<H>;
22587    fn irreducibles(&self) -> &Self::IrreducibleSet {
22588        &self.irreducibles
22589    }
22590    type ReducibleSet = NullReducibleSet<H>;
22591    fn reducibles(&self) -> &Self::ReducibleSet {
22592        &self.reducibles
22593    }
22594    type UnitGroup = NullUnitGroup<H>;
22595    fn units(&self) -> &Self::UnitGroup {
22596        &self.units
22597    }
22598    type Complement = NullComplement<H>;
22599    fn exterior(&self) -> &Self::Complement {
22600        &self.exterior
22601    }
22602    fn density(&self) -> H::Decimal {
22603        H::EMPTY_DECIMAL
22604    }
22605    type TypeDefinition = NullTypeDefinition<H>;
22606    fn source_type(&self) -> &Self::TypeDefinition {
22607        &self.source_type
22608    }
22609    fn witt_length(&self) -> u64 {
22610        0
22611    }
22612    type FreeRank = NullFreeRank<H>;
22613    fn site_budget(&self) -> &Self::FreeRank {
22614        &self.free_rank
22615    }
22616    fn is_exhaustive(&self) -> bool {
22617        true
22618    }
22619    type TagSite = NullTagSite<H>;
22620    fn tag_site_of(&self) -> &Self::TagSite {
22621        &self.tag_site
22622    }
22623    fn product_category_level(&self) -> &H::HostString {
22624        H::EMPTY_HOST_STRING
22625    }
22626}
22627
22628impl<H: HostTypes> crate::bridge::partition::PartitionProduct<H> for PartitionProductWitness {
22629    type Partition = NullPartition<H>;
22630    fn left_factor(&self) -> Self::Partition {
22631        NullPartition::from_fingerprint(self.left_fingerprint)
22632    }
22633    fn right_factor(&self) -> Self::Partition {
22634        NullPartition::from_fingerprint(self.right_fingerprint)
22635    }
22636}
22637
22638impl<H: HostTypes> crate::bridge::partition::PartitionCoproduct<H> for PartitionCoproductWitness {
22639    type Partition = NullPartition<H>;
22640    fn left_summand(&self) -> Self::Partition {
22641        NullPartition::from_fingerprint(self.left_fingerprint)
22642    }
22643    fn right_summand(&self) -> Self::Partition {
22644        NullPartition::from_fingerprint(self.right_fingerprint)
22645    }
22646}
22647
22648impl<H: HostTypes> crate::bridge::partition::CartesianPartitionProduct<H>
22649    for CartesianProductWitness
22650{
22651    type Partition = NullPartition<H>;
22652    fn left_cartesian_factor(&self) -> Self::Partition {
22653        NullPartition::from_fingerprint(self.left_fingerprint)
22654    }
22655    fn right_cartesian_factor(&self) -> Self::Partition {
22656        NullPartition::from_fingerprint(self.right_fingerprint)
22657    }
22658}
22659
22660/// v0.2.1 ergonomics prelude. Re-exports the core symbols downstream crates
22661/// need for the consumer-facing one-liners.
22662/// Ontology-driven: the set of certificate / type / builder symbols is
22663/// sourced from `conformance:PreludeExport` individuals. Adding a new
22664/// symbol to the prelude is an ontology edit, verified against the
22665/// codegen's known-name mapping at build time.
22666pub mod prelude {
22667    pub use super::calibrations;
22668    pub use super::Add;
22669    pub use super::And;
22670    pub use super::BNot;
22671    pub use super::BinaryGroundingMap;
22672    pub use super::BindingEntry;
22673    pub use super::BindingsTable;
22674    pub use super::BornRuleVerification;
22675    pub use super::Calibration;
22676    pub use super::CalibrationError;
22677    pub use super::CanonicalTimingPolicy;
22678    pub use super::Certificate;
22679    pub use super::Certified;
22680    pub use super::ChainAuditTrail;
22681    pub use super::CompileTime;
22682    pub use super::CompileUnit;
22683    pub use super::CompileUnitBuilder;
22684    pub use super::CompletenessAuditTrail;
22685    pub use super::CompletenessCertificate;
22686    pub use super::ConstrainedTypeInput;
22687    pub use super::ContentAddress;
22688    pub use super::ContentFingerprint;
22689    pub use super::Datum;
22690    pub use super::DigestGroundingMap;
22691    pub use super::Embed;
22692    pub use super::FragmentMarker;
22693    pub use super::GenericImpossibilityWitness;
22694    pub use super::GeodesicCertificate;
22695    pub use super::GeodesicEvidenceBundle;
22696    pub use super::Grounded;
22697    pub use super::GroundedCoord;
22698    pub use super::GroundedShape;
22699    pub use super::GroundedTuple;
22700    pub use super::GroundedValue;
22701    pub use super::Grounding;
22702    pub use super::GroundingCertificate;
22703    pub use super::GroundingExt;
22704    pub use super::GroundingMapKind;
22705    pub use super::GroundingProgram;
22706    pub use super::Hasher;
22707    pub use super::ImpossibilityWitnessKind;
22708    pub use super::InhabitanceCertificate;
22709    pub use super::InhabitanceImpossibilityWitness;
22710    pub use super::IntegerGroundingMap;
22711    pub use super::Invertible;
22712    pub use super::InvolutionCertificate;
22713    pub use super::IsometryCertificate;
22714    pub use super::JsonGroundingMap;
22715    pub use super::LandauerBudget;
22716    pub use super::LiftChainCertificate;
22717    pub use super::MeasurementCertificate;
22718    pub use super::Mul;
22719    pub use super::Nanos;
22720    pub use super::Neg;
22721    pub use super::OntologyTarget;
22722    pub use super::Or;
22723    pub use super::PipelineFailure;
22724    pub use super::PreservesMetric;
22725    pub use super::PreservesStructure;
22726    pub use super::RingOp;
22727    pub use super::Runtime;
22728    pub use super::ShapeViolation;
22729    pub use super::Sub;
22730    pub use super::Succ;
22731    pub use super::Term;
22732    pub use super::TermArena;
22733    pub use super::TimingPolicy;
22734    pub use super::Total;
22735    pub use super::TransformCertificate;
22736    pub use super::Triad;
22737    pub use super::UnaryRingOp;
22738    pub use super::UorTime;
22739    pub use super::Utf8GroundingMap;
22740    pub use super::ValidLevelEmbedding;
22741    pub use super::Validated;
22742    pub use super::ValidationPhase;
22743    pub use super::Xor;
22744    pub use super::W16;
22745    pub use super::W8;
22746    pub use crate::pipeline::empty_bindings_table;
22747    pub use crate::pipeline::{
22748        validate_constrained_type, validate_constrained_type_const, ConstrainedTypeShape,
22749        ConstraintRef, FragmentKind,
22750    };
22751    pub use crate::{DecimalTranscendental, DefaultHostTypes, HostTypes, WittLevel};
22752}