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 factor MAX_BYTES).
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<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: output-value payload — the catamorphism's evaluation
8935    /// result populated by `pipeline::run_route` per ADR-029's per-variant
8936    /// fold rules. Fixed-capacity stack buffer; the active prefix runs to
8937    /// `output_len` bytes. Read via [`Grounded::output_bytes`].
8938    output_payload: [u8; INLINE_BYTES],
8939    /// Active length of `output_payload` (the route's evaluation output length).
8940    output_len: u16,
8941    /// Phantom type tying this `Grounded` to a specific `ConstrainedType`.
8942    _phantom: PhantomData<T>,
8943    /// Phantom domain tag (Q3). Defaults to `T` for backwards-compatible
8944    /// call sites; downstream attaches a custom tag via `tag::<NewTag>()`.
8945    _tag: PhantomData<Tag>,
8946}
8947
8948impl<T: GroundedShape, const INLINE_BYTES: usize, Tag> Grounded<T, INLINE_BYTES, Tag> {
8949    /// Returns the binding for the given query address, or `None` if not in
8950    /// the table. Resolves in O(log n) via binary search; for true `op:GS_5`
8951    /// zero-step access, downstream code uses statically-known indices.
8952    #[inline]
8953    #[must_use]
8954    pub fn get_binding(&self, address: ContentAddress) -> Option<&'static [u8]> {
8955        self.bindings
8956            .entries
8957            .binary_search_by_key(&address.as_u128(), |e| e.address.as_u128())
8958            .ok()
8959            .map(|i| self.bindings.entries[i].bytes)
8960    }
8961
8962    /// Iterate over all bindings in this grounded context.
8963    #[inline]
8964    pub fn iter_bindings(&self) -> impl Iterator<Item = &BindingEntry> + '_ {
8965        self.bindings.entries.iter()
8966    }
8967
8968    /// Returns the Witt level the grounded value was minted at.
8969    #[inline]
8970    #[must_use]
8971    pub const fn witt_level_bits(&self) -> u16 {
8972        self.witt_level_bits
8973    }
8974
8975    /// Returns the content-address of the originating CompileUnit.
8976    #[inline]
8977    #[must_use]
8978    pub const fn unit_address(&self) -> ContentAddress {
8979        self.unit_address
8980    }
8981
8982    /// Returns the validated grounding certificate this wrapper carries.
8983    #[inline]
8984    #[must_use]
8985    pub const fn certificate(&self) -> &Validated<GroundingCertificate> {
8986        &self.validated
8987    }
8988
8989    /// Phase A.4: `observable:d_delta_metric` — sealed metric incompatibility between
8990    /// ring distance and Hamming distance for this datum's neighborhood.
8991    #[inline]
8992    #[must_use]
8993    pub const fn d_delta(&self) -> DDeltaMetric {
8994        DDeltaMetric::new(self.d_delta)
8995    }
8996
8997    /// Phase A.4: `observable:sigma_metric` — sealed grounding completion ratio.
8998    #[inline]
8999    #[must_use]
9000    pub fn sigma(&self) -> SigmaValue<crate::DefaultHostTypes> {
9001        // Default-host (f64) projection; polymorphic consumers
9002        // can re-encode via DecimalTranscendental::from_u32 + Div.
9003        let value = <f64 as crate::DecimalTranscendental>::from_u32(self.sigma_ppm)
9004            / <f64 as crate::DecimalTranscendental>::from_u32(1_000_000);
9005        SigmaValue::<crate::DefaultHostTypes>::new_unchecked(value)
9006    }
9007
9008    /// Phase A.4: `observable:jacobian_metric` — sealed per-site Jacobian row.
9009    #[inline]
9010    #[must_use]
9011    pub fn jacobian(&self) -> JacobianMetric<T> {
9012        JacobianMetric::from_entries(self.jacobian_entries, self.jacobian_len)
9013    }
9014
9015    /// Phase A.4: `observable:betti_metric` — sealed Betti-number vector.
9016    #[inline]
9017    #[must_use]
9018    pub const fn betti(&self) -> BettiMetric {
9019        BettiMetric::new(self.betti_numbers)
9020    }
9021
9022    /// Phase A.4: `observable:euler_metric` — sealed Euler characteristic χ of
9023    /// the constraint nerve.
9024    #[inline]
9025    #[must_use]
9026    pub const fn euler(&self) -> EulerMetric {
9027        EulerMetric::new(self.euler_characteristic)
9028    }
9029
9030    /// Phase A.4: `observable:residual_metric` — sealed free-site count r at grounding.
9031    #[inline]
9032    #[must_use]
9033    pub const fn residual(&self) -> ResidualMetric {
9034        ResidualMetric::new(self.residual_count)
9035    }
9036
9037    /// v0.2.2 T5: returns the parametric content fingerprint of the source
9038    /// unit, computed at grounding time by the consumer-supplied `Hasher`.
9039    /// Width is set by `H::OUTPUT_BYTES` at the call site. Used by
9040    /// `derivation()` to seed the replayed Trace's fingerprint, which
9041    /// `verify_trace` then passes through to the re-derived certificate.
9042    #[inline]
9043    #[must_use]
9044    pub const fn content_fingerprint(&self) -> ContentFingerprint {
9045        self.content_fingerprint
9046    }
9047
9048    /// v0.2.2 T5 (C2): returns the `Derivation` that produced this grounded
9049    /// value. Use the returned `Derivation` with `Derivation::replay()` and
9050    /// then `uor_foundation_verify::verify_trace` to re-derive the source
9051    /// certificate without re-running the deciders.
9052    /// The round-trip property:
9053    /// ```text
9054    /// verify_trace(&grounded.derivation().replay()).certificate()
9055    ///     == grounded.certificate()
9056    /// ```
9057    /// holds for every conforming substrate `Hasher`.
9058    #[inline]
9059    #[must_use]
9060    pub const fn derivation(&self) -> Derivation {
9061        Derivation::new(
9062            (self.jacobian_len as u32) + 1,
9063            self.witt_level_bits,
9064            self.content_fingerprint,
9065        )
9066    }
9067
9068    /// v0.2.2 Phase B (Q3): coerce this `Grounded<T, Tag>` to a different
9069    /// phantom tag. Zero-cost — the inner witness is unchanged; only the
9070    /// type-system view differs. Downstream uses this to attach a domain
9071    /// marker for use in function signatures (e.g., `Grounded<_, BlockHashTag>`
9072    /// vs `Grounded<_, PixelTag>` are distinct Rust types).
9073    /// **The foundation does not validate the tag.** The tag records what
9074    /// the developer is claiming about the witness's domain semantics; the
9075    /// foundation's contract is about ring soundness, not domain semantics.
9076    #[inline]
9077    #[must_use]
9078    pub fn tag<NewTag>(self) -> Grounded<T, INLINE_BYTES, NewTag> {
9079        Grounded {
9080            validated: self.validated,
9081            bindings: self.bindings,
9082            witt_level_bits: self.witt_level_bits,
9083            unit_address: self.unit_address,
9084            uor_time: self.uor_time,
9085            sigma_ppm: self.sigma_ppm,
9086            d_delta: self.d_delta,
9087            euler_characteristic: self.euler_characteristic,
9088            residual_count: self.residual_count,
9089            jacobian_entries: self.jacobian_entries,
9090            jacobian_len: self.jacobian_len,
9091            betti_numbers: self.betti_numbers,
9092            content_fingerprint: self.content_fingerprint,
9093            output_payload: self.output_payload,
9094            output_len: self.output_len,
9095            _phantom: PhantomData,
9096            _tag: PhantomData,
9097        }
9098    }
9099
9100    /// Wiki ADR-028: returns the catamorphism's evaluation output bytes — the
9101    /// active prefix of the on-stack output payload `pipeline::run_route`
9102    /// populated per ADR-029's per-variant fold rules.
9103    /// For the foundation-sanctioned identity output (`ConstrainedTypeInput`)
9104    /// the slice is empty (no transformation, identity route). For shapes
9105    /// declared via the `output_shape!` SDK macro the slice carries the
9106    /// route's evaluation result.
9107    #[inline]
9108    #[must_use]
9109    pub fn output_bytes(&self) -> &[u8] {
9110        let len = self.output_len as usize;
9111        &self.output_payload[..len]
9112    }
9113
9114    /// Phase A.1: the foundation-internal two-clock value read at witness mint time.
9115    /// Maps `rewrite_steps` to `derivation:stepCount` and `landauer_nats` to
9116    /// `observable:LandauerCost`. The value is content-deterministic: two `Grounded`
9117    /// witnesses minted from the same inputs share the same `UorTime`.
9118    /// Compose with a `Calibration` via [`UorTime::min_wall_clock`] to
9119    /// bound the provable minimum wall-clock duration the computation required.
9120    #[inline]
9121    #[must_use]
9122    pub const fn uor_time(&self) -> UorTime {
9123        self.uor_time
9124    }
9125
9126    /// Phase A.2: the sealed triadic coordinate `(stratum, spectrum, address)` at the
9127    /// witness's Witt level, projected from the content-addressed unit.
9128    /// `stratum` is the v₂ valuation of the lower unit-address half; `spectrum`
9129    /// is the lower 64 bits of the unit address; `address` is the upper 64 bits.
9130    /// The projection is deterministic and content-addressed, so replay reproduces the
9131    /// same `Triad` bit-for-bit.
9132    #[inline]
9133    #[must_use]
9134    pub const fn triad(&self) -> Triad<T> {
9135        let addr = self.unit_address.as_u128();
9136        let addr_lo = addr as u64;
9137        let addr_hi = (addr >> 64) as u64;
9138        let stratum = if addr_lo == 0 {
9139            0u64
9140        } else {
9141            addr_lo.trailing_zeros() as u64
9142        };
9143        Triad::new(stratum, addr_lo, addr_hi)
9144    }
9145
9146    /// Crate-internal constructor used by the pipeline at mint time.
9147    /// Not callable from outside `uor-foundation`. The tag defaults to `T`
9148    /// (the unparameterized form); downstream attaches a custom tag via `tag()`.
9149    /// v0.2.2 T2.6 (cleanup): BaseMetric fields are computed here from
9150    /// the input witt level, bindings, and unit address. Two `Grounded`
9151    /// values built from the same inputs return identical metrics; two
9152    /// built from different inputs differ in at least three fields.
9153    #[inline]
9154    #[allow(dead_code)]
9155    pub(crate) const fn new_internal(
9156        validated: Validated<GroundingCertificate>,
9157        bindings: BindingsTable,
9158        witt_level_bits: u16,
9159        unit_address: ContentAddress,
9160        content_fingerprint: ContentFingerprint,
9161    ) -> Self {
9162        let bound_count = bindings.entries.len() as u32;
9163        let declared_sites = if witt_level_bits == 0 {
9164            1u32
9165        } else {
9166            witt_level_bits as u32
9167        };
9168        // sigma = bound / declared, in parts per million.
9169        let sigma_ppm = if bound_count >= declared_sites {
9170            1_000_000u32
9171        } else {
9172            // Integer division, rounded down, cannot exceed 1_000_000.
9173            let num = (bound_count as u64) * 1_000_000u64;
9174            (num / (declared_sites as u64)) as u32
9175        };
9176        // residual_count = declared - bound (saturating).
9177        let residual_count = declared_sites.saturating_sub(bound_count);
9178        // d_delta = witt_bits - bound_count (signed).
9179        let d_delta = (witt_level_bits as i64) - (bound_count as i64);
9180        // Betti numbers: β_0 = 1 (connected); β_k = bit k of witt_level_bits.
9181        let mut betti = [0u32; MAX_BETTI_DIMENSION];
9182        betti[0] = 1;
9183        let mut k = 1usize;
9184        while k < MAX_BETTI_DIMENSION {
9185            betti[k] = ((witt_level_bits as u32) >> (k - 1)) & 1;
9186            k += 1;
9187        }
9188        // Euler characteristic: alternating sum of Betti numbers.
9189        let mut euler: i64 = 0;
9190        let mut k = 0usize;
9191        while k < MAX_BETTI_DIMENSION {
9192            if k & 1 == 0 {
9193                euler += betti[k] as i64;
9194            } else {
9195                euler -= betti[k] as i64;
9196            }
9197            k += 1;
9198        }
9199        // Jacobian row: entry i = (unit_address.as_u128() as i64 XOR (i as i64)) mod witt+1.
9200        let mut jac = [0i64; JACOBIAN_MAX_SITES];
9201        let modulus = (witt_level_bits as i64) + 1;
9202        let ua_lo = unit_address.as_u128() as i64;
9203        let mut i = 0usize;
9204        let jac_len = if (witt_level_bits as usize) < JACOBIAN_MAX_SITES {
9205            witt_level_bits as usize
9206        } else {
9207            JACOBIAN_MAX_SITES
9208        };
9209        while i < jac_len {
9210            let raw = ua_lo ^ (i as i64);
9211            // Rust's % is remainder; ensure non-negative.
9212            let m = if modulus == 0 { 1 } else { modulus };
9213            jac[i] = ((raw % m) + m) % m;
9214            i += 1;
9215        }
9216        // Phase A.1: uor_time is content-deterministic. rewrite_steps counts
9217        // the reduction work proxied by (witt bits + bound count + active jac len);
9218        // Landauer nats = rewrite_steps × ln 2 (Landauer-temperature cost of
9219        // traversing that many orthogonal states). Two Grounded values minted from
9220        // the same inputs share the same UorTime.
9221        let steps = (witt_level_bits as u64) + (bound_count as u64) + (jac_len as u64);
9222        let landauer = LandauerBudget::new((steps as f64) * core::f64::consts::LN_2);
9223        let uor_time = UorTime::new(landauer, steps);
9224        Self {
9225            validated,
9226            bindings,
9227            witt_level_bits,
9228            unit_address,
9229            uor_time,
9230            sigma_ppm,
9231            d_delta,
9232            euler_characteristic: euler,
9233            residual_count,
9234            jacobian_entries: jac,
9235            jacobian_len: jac_len as u16,
9236            betti_numbers: betti,
9237            content_fingerprint,
9238            output_payload: [0u8; INLINE_BYTES],
9239            output_len: 0,
9240            _phantom: PhantomData,
9241            _tag: PhantomData,
9242        }
9243    }
9244
9245    /// Wiki ADR-028: crate-internal setter for the output-value payload.
9246    /// Called by `pipeline::run_route` after the catamorphism evaluates the
9247    /// Term tree per ADR-029. The bytes are copied into the on-stack
9248    /// buffer; bytes beyond `len` are zero-padded. Returns self for chaining.
9249    /// Panics if `bytes.len() > INLINE_BYTES`.
9250    #[inline]
9251    #[must_use]
9252    pub(crate) fn with_output_bytes(mut self, bytes: &[u8]) -> Self {
9253        let len = bytes.len();
9254        debug_assert!(len <= INLINE_BYTES);
9255        let copy_len = if len > INLINE_BYTES {
9256            INLINE_BYTES
9257        } else {
9258            len
9259        };
9260        let mut i = 0;
9261        while i < copy_len {
9262            self.output_payload[i] = bytes[i];
9263            i += 1;
9264        }
9265        self.output_len = copy_len as u16;
9266        self
9267    }
9268
9269    /// v0.2.2 T6.17: attach a downstream-validated `BindingsTable` to this
9270    /// grounded value. The original `Grounded` was minted by the foundation
9271    /// pipeline with a substrate-computed certificate; this builder lets
9272    /// downstream attach its own binding table without re-grounding.
9273    /// The `bindings` parameter must satisfy the sortedness invariant. Use
9274    /// [`BindingsTable::try_new`] to construct a validated table from a
9275    /// pre-sorted slice.
9276    /// **Trust boundary:** the certificate witnesses the unit's grounding,
9277    /// not the bindings' contents. A downstream consumer that uses the
9278    /// certificate as a trust root for the bindings is wrong.
9279    #[inline]
9280    #[must_use]
9281    pub fn with_bindings(self, bindings: BindingsTable) -> Self {
9282        Self { bindings, ..self }
9283    }
9284
9285    /// Wiki ADR-042: borrow `self` as an
9286    /// [`crate::pipeline::InhabitanceCertificateView`] over the canonical
9287    /// k-invariants branch's verdict envelope.
9288    /// Universal — available for any `Grounded<T, Tag>`; applications whose
9289    /// admission relations are not inhabitance questions simply don't
9290    /// call the typed accessors. The view is zero-cost
9291    /// (`#[repr(transparent)]` over `&'a Grounded<T, Tag>`).
9292    #[inline]
9293    #[must_use]
9294    pub fn as_inhabitance_certificate(
9295        &self,
9296    ) -> crate::pipeline::InhabitanceCertificateView<'_, T, INLINE_BYTES, Tag> {
9297        crate::pipeline::InhabitanceCertificateView(self)
9298    }
9299}
9300
9301/// v0.2.2 W8: triadic coordinate of a Datum at level `L`. Bundles the
9302/// (stratum, spectrum, address) projection in one structurally-enforced
9303/// type. No public constructor — `Triad<L>` is built only by foundation code
9304/// at grounding time. Field access goes through the named accessors.
9305#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9306pub struct Triad<L> {
9307    /// The stratum coordinate (two-adic valuation).
9308    stratum: u64,
9309    /// The spectrum coordinate (Walsh-Hadamard image).
9310    spectrum: u64,
9311    /// The address coordinate (Braille-glyph address).
9312    address: u64,
9313    /// Phantom marker for the Witt level.
9314    _level: PhantomData<L>,
9315}
9316
9317impl<L> Triad<L> {
9318    /// Returns the stratum component (`query:TwoAdicValuation` coordinate).
9319    #[inline]
9320    #[must_use]
9321    pub const fn stratum(&self) -> u64 {
9322        self.stratum
9323    }
9324
9325    /// Returns the spectrum component (`query:WalshHadamardImage` coordinate).
9326    #[inline]
9327    #[must_use]
9328    pub const fn spectrum(&self) -> u64 {
9329        self.spectrum
9330    }
9331
9332    /// Returns the address component (`query:Address` coordinate).
9333    #[inline]
9334    #[must_use]
9335    pub const fn address(&self) -> u64 {
9336        self.address
9337    }
9338
9339    /// Crate-internal constructor. Reachable only from grounding-time minting.
9340    #[inline]
9341    #[must_use]
9342    #[allow(dead_code)]
9343    pub(crate) const fn new(stratum: u64, spectrum: u64, address: u64) -> Self {
9344        Self {
9345            stratum,
9346            spectrum,
9347            address,
9348            _level: PhantomData,
9349        }
9350    }
9351}
9352
9353/// The Rust-surface rendering of `reduction:PipelineFailureReason` and the
9354/// v0.2.1 cross-namespace failure variants. Variant set and field shapes are
9355/// generated parametrically by walking `reduction:FailureField` individuals;
9356/// adding a new field requires only an ontology edit.
9357///
9358/// # Wiki ADR-039 — Inhabitance verdict realization mapping
9359///
9360/// An `Err(PipelineFailure)` whose structural cause is "the constraint
9361/// nerve has empty Kan completion" realizes a `cert:InhabitanceImpossibilityCertificate`
9362/// envelope, carrying `proof:InhabitanceImpossibilityWitness` as the
9363/// proof payload with `proof:contradictionProof` as the canonical-form
9364/// encoding of the failure trace. The verdict mapping is the dual of
9365/// the `Grounded<Output>` → `cert:InhabitanceCertificate` mapping; the
9366/// two together realize the ontology's three-primitive inhabitance
9367/// verdict structure (success / impossibility-witnessed / unknown).
9368/// Ontology references:
9369/// `<https://uor.foundation/cert/InhabitanceImpossibilityCertificate>`,
9370/// `<https://uor.foundation/proof/InhabitanceImpossibilityWitness>`,
9371/// `<https://uor.foundation/proof/contradictionProof>`.
9372#[derive(Debug, Clone, PartialEq)]
9373#[non_exhaustive]
9374pub enum PipelineFailure {
9375    /// `DispatchMiss` failure variant.
9376    DispatchMiss {
9377        /// query_iri field.
9378        query_iri: &'static str,
9379        /// table_iri field.
9380        table_iri: &'static str,
9381    },
9382    /// `GroundingFailure` failure variant.
9383    GroundingFailure {
9384        /// reason_iri field.
9385        reason_iri: &'static str,
9386    },
9387    /// `ConvergenceStall` failure variant.
9388    ConvergenceStall {
9389        /// stage_iri field.
9390        stage_iri: &'static str,
9391        /// angle_milliradians field.
9392        angle_milliradians: i64,
9393    },
9394    /// `ContradictionDetected` failure variant.
9395    ContradictionDetected {
9396        /// at_step field.
9397        at_step: usize,
9398        /// trace_iri field.
9399        trace_iri: &'static str,
9400    },
9401    /// `CoherenceViolation` failure variant.
9402    CoherenceViolation {
9403        /// site_position field.
9404        site_position: usize,
9405        /// constraint_iri field.
9406        constraint_iri: &'static str,
9407    },
9408    /// `ShapeMismatch` failure variant.
9409    ShapeMismatch {
9410        /// expected field.
9411        expected: &'static str,
9412        /// got field.
9413        got: &'static str,
9414    },
9415    /// `LiftObstructionFailure` failure variant.
9416    LiftObstructionFailure {
9417        /// site_position field.
9418        site_position: usize,
9419        /// obstruction_class_iri field.
9420        obstruction_class_iri: &'static str,
9421    },
9422    /// `ShapeViolation` failure variant.
9423    ShapeViolation {
9424        /// report field.
9425        report: ShapeViolation,
9426    },
9427}
9428
9429impl core::fmt::Display for PipelineFailure {
9430    fn fmt(&self, ff: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
9431        match self {
9432            Self::DispatchMiss {
9433                query_iri,
9434                table_iri,
9435            } => write!(
9436                ff,
9437                "DispatchMiss(query_iri={:?}, table_iri={:?})",
9438                query_iri, table_iri
9439            ),
9440            Self::GroundingFailure { reason_iri } => {
9441                write!(ff, "GroundingFailure(reason_iri={:?})", reason_iri)
9442            }
9443            Self::ConvergenceStall {
9444                stage_iri,
9445                angle_milliradians,
9446            } => write!(
9447                ff,
9448                "ConvergenceStall(stage_iri={:?}, angle_milliradians={:?})",
9449                stage_iri, angle_milliradians
9450            ),
9451            Self::ContradictionDetected { at_step, trace_iri } => write!(
9452                ff,
9453                "ContradictionDetected(at_step={:?}, trace_iri={:?})",
9454                at_step, trace_iri
9455            ),
9456            Self::CoherenceViolation {
9457                site_position,
9458                constraint_iri,
9459            } => write!(
9460                ff,
9461                "CoherenceViolation(site_position={:?}, constraint_iri={:?})",
9462                site_position, constraint_iri
9463            ),
9464            Self::ShapeMismatch { expected, got } => {
9465                write!(ff, "ShapeMismatch(expected={:?}, got={:?})", expected, got)
9466            }
9467            Self::LiftObstructionFailure {
9468                site_position,
9469                obstruction_class_iri,
9470            } => write!(
9471                ff,
9472                "LiftObstructionFailure(site_position={:?}, obstruction_class_iri={:?})",
9473                site_position, obstruction_class_iri
9474            ),
9475            Self::ShapeViolation { report } => write!(ff, "ShapeViolation({:?})", report),
9476        }
9477    }
9478}
9479
9480impl core::error::Error for PipelineFailure {}
9481
9482/// Sealed marker for impossibility witnesses returned by the resolver
9483/// free-function path. Every failure return value of every
9484/// `resolver::<name>::certify(...)` call is a member of this set.
9485pub trait ImpossibilityWitnessKind: impossibility_witness_kind_sealed::Sealed {}
9486
9487mod impossibility_witness_kind_sealed {
9488    /// Private supertrait.
9489    pub trait Sealed {}
9490    impl Sealed for super::GenericImpossibilityWitness {}
9491    impl Sealed for super::InhabitanceImpossibilityWitness {}
9492}
9493
9494impl ImpossibilityWitnessKind for GenericImpossibilityWitness {}
9495impl ImpossibilityWitnessKind for InhabitanceImpossibilityWitness {}
9496
9497/// v0.2.2 W12: resolver free functions. Replaces the v0.2.1 unit-struct
9498/// façades with module-per-resolver free functions returning the W11
9499/// `Certified<C>` parametric carrier.
9500pub mod resolver {
9501    use super::{
9502        BornRuleVerification,
9503        Certified,
9504        CompileUnit,
9505        CompletenessCertificate,
9506        GenericImpossibilityWitness,
9507        GeodesicCertificate,
9508        GroundingCertificate,
9509        InhabitanceCertificate,
9510        InhabitanceImpossibilityWitness,
9511        InvolutionCertificate,
9512        IsometryCertificate,
9513        LiftChainCertificate,
9514        MeasurementCertificate,
9515        // Phase X.1: per-resolver cert discrimination.
9516        TransformCertificate,
9517        Validated,
9518        WittLevel,
9519    };
9520
9521    /// v0.2.2 W12: certify tower-completeness for a constrained type.
9522    ///
9523    /// Replaces `TowerCompletenessResolver::new().certify(input)` from v0.2.1.
9524    /// Delegates to `crate::pipeline::run_tower_completeness` and wraps the
9525    /// returned `LiftChainCertificate` in the W11 `Certified<_>` carrier.
9526    ///
9527    /// # Errors
9528    ///
9529    /// Returns `GenericImpossibilityWitness` when no certificate can be issued.
9530    pub mod tower_completeness {
9531        use super::*;
9532        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9533        ///
9534        /// # Errors
9535        ///
9536        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9537        pub fn certify<T, P, H>(
9538            input: &Validated<T, P>,
9539        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9540        where
9541            T: crate::pipeline::ConstrainedTypeShape,
9542            P: crate::enforcement::ValidationPhase,
9543            H: crate::enforcement::Hasher,
9544        {
9545            certify_at::<T, P, H>(input, WittLevel::W32)
9546        }
9547
9548        /// Certify at an explicit Witt level.
9549        ///
9550        /// # Errors
9551        ///
9552        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9553        pub fn certify_at<T, P, H>(
9554            input: &Validated<T, P>,
9555            level: WittLevel,
9556        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9557        where
9558            T: crate::pipeline::ConstrainedTypeShape,
9559            P: crate::enforcement::ValidationPhase,
9560            H: crate::enforcement::Hasher,
9561        {
9562            crate::pipeline::run_tower_completeness::<T, H>(input.inner(), level)
9563                .map(|v| Certified::new(*v.inner()))
9564                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9565        }
9566    }
9567
9568    /// v0.2.2 closure: certify incremental completeness for a constrained type.
9569    pub mod incremental_completeness {
9570        use super::*;
9571        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9572        ///
9573        /// # Errors
9574        ///
9575        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9576        pub fn certify<T, P, H>(
9577            input: &Validated<T, P>,
9578        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9579        where
9580            T: crate::pipeline::ConstrainedTypeShape,
9581            P: crate::enforcement::ValidationPhase,
9582            H: crate::enforcement::Hasher,
9583        {
9584            certify_at::<T, P, H>(input, WittLevel::W32)
9585        }
9586
9587        /// Certify at an explicit Witt level.
9588        ///
9589        /// # Errors
9590        ///
9591        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9592        pub fn certify_at<T, P, H>(
9593            input: &Validated<T, P>,
9594            level: WittLevel,
9595        ) -> Result<Certified<LiftChainCertificate>, Certified<GenericImpossibilityWitness>>
9596        where
9597            T: crate::pipeline::ConstrainedTypeShape,
9598            P: crate::enforcement::ValidationPhase,
9599            H: crate::enforcement::Hasher,
9600        {
9601            crate::pipeline::run_incremental_completeness::<T, H>(input.inner(), level)
9602                .map(|v| Certified::new(*v.inner()))
9603                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9604        }
9605    }
9606
9607    /// v0.2.2 closure: certify grounding-aware reduction for a CompileUnit.
9608    pub mod grounding_aware {
9609        use super::*;
9610        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9611        ///
9612        /// # Errors
9613        ///
9614        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9615        pub fn certify<P, H, const INLINE_BYTES: usize>(
9616            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
9617        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9618        where
9619            P: crate::enforcement::ValidationPhase,
9620            H: crate::enforcement::Hasher,
9621        {
9622            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
9623        }
9624
9625        /// Certify at an explicit Witt level.
9626        ///
9627        /// # Errors
9628        ///
9629        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9630        pub fn certify_at<P, H, const INLINE_BYTES: usize>(
9631            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
9632            level: WittLevel,
9633        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9634        where
9635            P: crate::enforcement::ValidationPhase,
9636            H: crate::enforcement::Hasher,
9637        {
9638            crate::pipeline::run_grounding_aware::<INLINE_BYTES, H>(input.inner(), level)
9639                .map(|v| Certified::new(*v.inner()))
9640                .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))
9641        }
9642    }
9643
9644    /// v0.2.2 closure: certify inhabitance for a constrained type.
9645    pub mod inhabitance {
9646        use super::*;
9647        /// v0.2.2 closure (target §4.2): parameterized over phase + hasher.
9648        ///
9649        /// # Errors
9650        ///
9651        /// Returns `Certified<InhabitanceImpossibilityWitness>` on failure.
9652        pub fn certify<T, P, H>(
9653            input: &Validated<T, P>,
9654        ) -> Result<Certified<InhabitanceCertificate>, Certified<InhabitanceImpossibilityWitness>>
9655        where
9656            T: crate::pipeline::ConstrainedTypeShape,
9657            P: crate::enforcement::ValidationPhase,
9658            H: crate::enforcement::Hasher,
9659        {
9660            certify_at::<T, P, H>(input, WittLevel::W32)
9661        }
9662
9663        /// Certify at an explicit Witt level.
9664        ///
9665        /// # Errors
9666        ///
9667        /// Returns `Certified<InhabitanceImpossibilityWitness>` on failure.
9668        pub fn certify_at<T, P, H>(
9669            input: &Validated<T, P>,
9670            level: WittLevel,
9671        ) -> Result<Certified<InhabitanceCertificate>, Certified<InhabitanceImpossibilityWitness>>
9672        where
9673            T: crate::pipeline::ConstrainedTypeShape,
9674            P: crate::enforcement::ValidationPhase,
9675            H: crate::enforcement::Hasher,
9676        {
9677            crate::pipeline::run_inhabitance::<T, H>(input.inner(), level)
9678                .map(|v: Validated<InhabitanceCertificate>| Certified::new(*v.inner()))
9679                .map_err(|_| Certified::new(InhabitanceImpossibilityWitness::default()))
9680        }
9681    }
9682
9683    /// v0.2.2 Phase C.4: multiplication resolver — picks the cost-optimal
9684    /// Toom-Cook splitting factor R for a `Datum<L>` × `Datum<L>`
9685    /// multiplication at a given call-site context. The cost function is
9686    /// closed-form and grounded in `op:OA_5`:
9687    ///
9688    /// ```text
9689    /// sub_mul_count(N, R) = (2R - 1)  for R > 1
9690    ///                     = 1         for R = 1 (schoolbook)
9691    /// landauer_cost(N, R) = sub_mul_count(N, R) · (N/R)² · 64 · ln 2  nats
9692    /// ```
9693    pub mod multiplication {
9694        use super::super::{MulContext, MultiplicationCertificate};
9695        use super::*;
9696
9697        /// v0.2.2 T6.7: parameterized over `H: Hasher`. Pick the cost-optimal
9698        /// splitting factor R for a multiplication at the given call-site
9699        /// context and return a `Certified<MultiplicationCertificate>`
9700        /// recording the choice. The certificate carries a substrate-computed
9701        /// content fingerprint.
9702        ///
9703        /// # Errors
9704        ///
9705        /// Returns `GenericImpossibilityWitness` if the call-site context is
9706        /// inadmissible (`stack_budget_bytes == 0`). The resolver is otherwise
9707        /// total over admissible inputs.
9708        pub fn certify<H: crate::enforcement::Hasher>(
9709            context: &MulContext,
9710        ) -> Result<Certified<MultiplicationCertificate>, GenericImpossibilityWitness> {
9711            if context.stack_budget_bytes == 0 {
9712                return Err(GenericImpossibilityWitness::default());
9713            }
9714            // Closed-form cost search: R = 1 (schoolbook) vs R = 2 (Karatsuba).
9715            let limb_count = context.limb_count.max(1);
9716            let karatsuba_stack_need = limb_count * 8 * 6;
9717            let choose_karatsuba = !context.const_eval
9718                && (context.stack_budget_bytes as usize) >= karatsuba_stack_need;
9719            // v0.2.2 T6.7: compute substrate fingerprint over the MulContext.
9720            let mut hasher = H::initial();
9721            hasher = hasher.fold_bytes(&context.stack_budget_bytes.to_be_bytes());
9722            hasher = hasher.fold_byte(if context.const_eval { 1 } else { 0 });
9723            hasher = hasher.fold_bytes(&(limb_count as u64).to_be_bytes());
9724            hasher = hasher.fold_byte(crate::enforcement::certificate_kind_discriminant(
9725                crate::enforcement::CertificateKind::Multiplication,
9726            ));
9727            let buffer = hasher.finalize();
9728            let fp =
9729                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9730            let cert = if choose_karatsuba {
9731                MultiplicationCertificate::with_evidence(
9732                    2,
9733                    3,
9734                    karatsuba_landauer_cost(limb_count),
9735                    fp,
9736                )
9737            } else {
9738                MultiplicationCertificate::with_evidence(
9739                    1,
9740                    1,
9741                    schoolbook_landauer_cost(limb_count),
9742                    fp,
9743                )
9744            };
9745            Ok(Certified::new(cert))
9746        }
9747
9748        // Local default-host alias for the Landauer cost helpers below.
9749        type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
9750
9751        /// Schoolbook Landauer cost in nats for an N-limb multiplication:
9752        /// `N² · 64 · ln 2`. Returns the IEEE-754 bit pattern;
9753        /// see `MultiplicationEvidence::landauer_cost_nats_bits`.
9754        fn schoolbook_landauer_cost(limb_count: usize) -> u64 {
9755            let n = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(limb_count as u32);
9756            let sixty_four = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(64);
9757            let ln_2 =
9758                <DefaultDecimal as crate::DecimalTranscendental>::from_bits(crate::LN_2_BITS);
9759            (n * n * sixty_four * ln_2).to_bits()
9760        }
9761
9762        /// Karatsuba Landauer cost: `3 · (N/2)² · 64 · ln 2`.
9763        /// Returns the IEEE-754 bit pattern.
9764        fn karatsuba_landauer_cost(limb_count: usize) -> u64 {
9765            let n = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(limb_count as u32);
9766            let two = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(2);
9767            let three = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(3);
9768            let sixty_four = <DefaultDecimal as crate::DecimalTranscendental>::from_u32(64);
9769            let ln_2 =
9770                <DefaultDecimal as crate::DecimalTranscendental>::from_bits(crate::LN_2_BITS);
9771            let n_half = n / two;
9772            (three * n_half * n_half * sixty_four * ln_2).to_bits()
9773        }
9774    }
9775
9776    /// v0.2.2 Phase C: `pub(crate)` trait parameterizing the 15 Phase D resolver kernels.
9777    /// Each kernel marker supplies a `CertificateKind` discriminant and its
9778    /// ontology-declared certificate type via `type Cert`. The shared
9779    /// `certify_at` bodies (see `emit_phase_d_ct_body` / `emit_phase_d_cu_body`)
9780    /// mint `Certified<Kernel::Cert>` directly — so each resolver's cert class
9781    /// matches its `resolver:CertifyMapping` in the ontology.
9782    pub(crate) trait ResolverKernel {
9783        const KIND: crate::enforcement::CertificateKind;
9784        /// Phase X.1: the ontology-declared certificate class produced by
9785        /// this resolver (per `resolver:CertifyMapping`).
9786        type Cert: crate::enforcement::Certificate;
9787    }
9788
9789    /// 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.
9790    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9791    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9792    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9793    /// failure — the witness itself is certified so downstream can persist it
9794    /// alongside success certs in a uniform `Certified<_>` channel.
9795    /// Phase X.1: the produced cert class is the ontology-declared class for
9796    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9797    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9798    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9799    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9800    /// kernels so each resolver's class discrimination is load-bearing.
9801    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9802    /// kernel's composition spec) whose output is folded into the canonical
9803    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9804    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9805    /// content-addressed per its ontology class.
9806    pub mod two_sat_decider {
9807        use super::*;
9808
9809        #[doc(hidden)]
9810        pub struct Kernel;
9811        impl super::ResolverKernel for Kernel {
9812            type Cert = crate::enforcement::GroundingCertificate;
9813            const KIND: crate::enforcement::CertificateKind =
9814                crate::enforcement::CertificateKind::TwoSat;
9815        }
9816
9817        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
9818        ///
9819        /// # Errors
9820        ///
9821        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9822        pub fn certify<
9823            T: crate::pipeline::ConstrainedTypeShape,
9824            P: crate::enforcement::ValidationPhase,
9825            H: crate::enforcement::Hasher,
9826        >(
9827            input: &Validated<T, P>,
9828        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9829        {
9830            certify_at::<T, P, H>(input, WittLevel::W32)
9831        }
9832
9833        /// Phase D (target §4.2): certify at an explicit Witt level.
9834        ///
9835        /// # Errors
9836        ///
9837        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9838        pub fn certify_at<
9839            T: crate::pipeline::ConstrainedTypeShape,
9840            P: crate::enforcement::ValidationPhase,
9841            H: crate::enforcement::Hasher,
9842        >(
9843            input: &Validated<T, P>,
9844            level: WittLevel,
9845        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9846        {
9847            let _ = input.inner();
9848            let witt_bits = level.witt_length() as u16;
9849            let (tr_bits, tr_constraints, tr_sat) =
9850                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
9851                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
9852            if tr_sat == 0 {
9853                return Err(Certified::new(GenericImpossibilityWitness::default()));
9854            }
9855            let mut hasher = H::initial();
9856            hasher = crate::enforcement::fold_terminal_reduction(
9857                hasher,
9858                tr_bits,
9859                tr_constraints,
9860                tr_sat,
9861            );
9862            hasher = crate::enforcement::fold_unit_digest(
9863                hasher,
9864                witt_bits,
9865                witt_bits as u64,
9866                T::IRI,
9867                T::SITE_COUNT,
9868                T::CONSTRAINTS,
9869                <Kernel as super::ResolverKernel>::KIND,
9870            );
9871            let buffer = hasher.finalize();
9872            let fp =
9873                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9874            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
9875            Ok(Certified::new(cert))
9876        }
9877    }
9878
9879    /// Phase D (target §4.2): `resolver:HornSatDecider` — certify that `predicate:IsHornShape` inputs are Horn-SAT-decidable via unit propagation (O(n+m)).
9880    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9881    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9882    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9883    /// failure — the witness itself is certified so downstream can persist it
9884    /// alongside success certs in a uniform `Certified<_>` channel.
9885    /// Phase X.1: the produced cert class is the ontology-declared class for
9886    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9887    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9888    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9889    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9890    /// kernels so each resolver's class discrimination is load-bearing.
9891    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9892    /// kernel's composition spec) whose output is folded into the canonical
9893    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9894    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9895    /// content-addressed per its ontology class.
9896    pub mod horn_sat_decider {
9897        use super::*;
9898
9899        #[doc(hidden)]
9900        pub struct Kernel;
9901        impl super::ResolverKernel for Kernel {
9902            type Cert = crate::enforcement::GroundingCertificate;
9903            const KIND: crate::enforcement::CertificateKind =
9904                crate::enforcement::CertificateKind::HornSat;
9905        }
9906
9907        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
9908        ///
9909        /// # Errors
9910        ///
9911        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9912        pub fn certify<
9913            T: crate::pipeline::ConstrainedTypeShape,
9914            P: crate::enforcement::ValidationPhase,
9915            H: crate::enforcement::Hasher,
9916        >(
9917            input: &Validated<T, P>,
9918        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9919        {
9920            certify_at::<T, P, H>(input, WittLevel::W32)
9921        }
9922
9923        /// Phase D (target §4.2): certify at an explicit Witt level.
9924        ///
9925        /// # Errors
9926        ///
9927        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
9928        pub fn certify_at<
9929            T: crate::pipeline::ConstrainedTypeShape,
9930            P: crate::enforcement::ValidationPhase,
9931            H: crate::enforcement::Hasher,
9932        >(
9933            input: &Validated<T, P>,
9934            level: WittLevel,
9935        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
9936        {
9937            let _ = input.inner();
9938            let witt_bits = level.witt_length() as u16;
9939            let (tr_bits, tr_constraints, tr_sat) =
9940                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
9941                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
9942            if tr_sat == 0 {
9943                return Err(Certified::new(GenericImpossibilityWitness::default()));
9944            }
9945            let mut hasher = H::initial();
9946            hasher = crate::enforcement::fold_terminal_reduction(
9947                hasher,
9948                tr_bits,
9949                tr_constraints,
9950                tr_sat,
9951            );
9952            hasher = crate::enforcement::fold_unit_digest(
9953                hasher,
9954                witt_bits,
9955                witt_bits as u64,
9956                T::IRI,
9957                T::SITE_COUNT,
9958                T::CONSTRAINTS,
9959                <Kernel as super::ResolverKernel>::KIND,
9960            );
9961            let buffer = hasher.finalize();
9962            let fp =
9963                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
9964            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
9965            Ok(Certified::new(cert))
9966        }
9967    }
9968
9969    /// 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).
9970    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
9971    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
9972    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
9973    /// failure — the witness itself is certified so downstream can persist it
9974    /// alongside success certs in a uniform `Certified<_>` channel.
9975    /// Phase X.1: the produced cert class is the ontology-declared class for
9976    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
9977    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
9978    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
9979    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
9980    /// kernels so each resolver's class discrimination is load-bearing.
9981    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
9982    /// kernel's composition spec) whose output is folded into the canonical
9983    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
9984    /// yield distinct fingerprints — i.e., each kernel's decision is real and
9985    /// content-addressed per its ontology class.
9986    pub mod residual_verdict {
9987        use super::*;
9988
9989        #[doc(hidden)]
9990        pub struct Kernel;
9991        impl super::ResolverKernel for Kernel {
9992            type Cert = crate::enforcement::GroundingCertificate;
9993            const KIND: crate::enforcement::CertificateKind =
9994                crate::enforcement::CertificateKind::ResidualVerdict;
9995        }
9996
9997        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
9998        ///
9999        /// # Errors
10000        ///
10001        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10002        pub fn certify<
10003            T: crate::pipeline::ConstrainedTypeShape,
10004            P: crate::enforcement::ValidationPhase,
10005            H: crate::enforcement::Hasher,
10006        >(
10007            input: &Validated<T, P>,
10008        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10009        {
10010            certify_at::<T, P, H>(input, WittLevel::W32)
10011        }
10012
10013        /// Phase D (target §4.2): certify at an explicit Witt level.
10014        ///
10015        /// # Errors
10016        ///
10017        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10018        pub fn certify_at<
10019            T: crate::pipeline::ConstrainedTypeShape,
10020            P: crate::enforcement::ValidationPhase,
10021            H: crate::enforcement::Hasher,
10022        >(
10023            input: &Validated<T, P>,
10024            level: WittLevel,
10025        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10026        {
10027            let _ = input.inner();
10028            let witt_bits = level.witt_length() as u16;
10029            let (tr_bits, tr_constraints, tr_sat) =
10030                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10031                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10032            if tr_sat == 0 {
10033                return Err(Certified::new(GenericImpossibilityWitness::default()));
10034            }
10035            let mut hasher = H::initial();
10036            hasher = crate::enforcement::fold_terminal_reduction(
10037                hasher,
10038                tr_bits,
10039                tr_constraints,
10040                tr_sat,
10041            );
10042            hasher = crate::enforcement::fold_unit_digest(
10043                hasher,
10044                witt_bits,
10045                witt_bits as u64,
10046                T::IRI,
10047                T::SITE_COUNT,
10048                T::CONSTRAINTS,
10049                <Kernel as super::ResolverKernel>::KIND,
10050            );
10051            let buffer = hasher.finalize();
10052            let fp =
10053                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10054            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10055            Ok(Certified::new(cert))
10056        }
10057    }
10058
10059    /// 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.
10060    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10061    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10062    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10063    /// failure — the witness itself is certified so downstream can persist it
10064    /// alongside success certs in a uniform `Certified<_>` channel.
10065    /// Phase X.1: the produced cert class is the ontology-declared class for
10066    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10067    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10068    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10069    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10070    /// kernels so each resolver's class discrimination is load-bearing.
10071    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10072    /// kernel's composition spec) whose output is folded into the canonical
10073    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10074    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10075    /// content-addressed per its ontology class.
10076    pub mod canonical_form {
10077        use super::*;
10078
10079        #[doc(hidden)]
10080        pub struct Kernel;
10081        impl super::ResolverKernel for Kernel {
10082            type Cert = crate::enforcement::TransformCertificate;
10083            const KIND: crate::enforcement::CertificateKind =
10084                crate::enforcement::CertificateKind::CanonicalForm;
10085        }
10086
10087        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10088        ///
10089        /// # Errors
10090        ///
10091        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10092        pub fn certify<
10093            T: crate::pipeline::ConstrainedTypeShape,
10094            P: crate::enforcement::ValidationPhase,
10095            H: crate::enforcement::Hasher,
10096        >(
10097            input: &Validated<T, P>,
10098        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10099        {
10100            certify_at::<T, P, H>(input, WittLevel::W32)
10101        }
10102
10103        /// Phase D (target §4.2): certify at an explicit Witt level.
10104        ///
10105        /// # Errors
10106        ///
10107        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10108        pub fn certify_at<
10109            T: crate::pipeline::ConstrainedTypeShape,
10110            P: crate::enforcement::ValidationPhase,
10111            H: crate::enforcement::Hasher,
10112        >(
10113            input: &Validated<T, P>,
10114            level: WittLevel,
10115        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10116        {
10117            let _ = input.inner();
10118            let witt_bits = level.witt_length() as u16;
10119            let (tr_bits, tr_constraints, tr_sat) =
10120                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10121                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10122            if tr_sat == 0 {
10123                return Err(Certified::new(GenericImpossibilityWitness::default()));
10124            }
10125            let mut hasher = H::initial();
10126            hasher = crate::enforcement::fold_terminal_reduction(
10127                hasher,
10128                tr_bits,
10129                tr_constraints,
10130                tr_sat,
10131            );
10132            let (tr2_bits, tr2_constraints, tr2_sat) =
10133                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10134                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10135            // Church-Rosser: second reduction must agree with the first.
10136            if tr2_bits != tr_bits || tr2_constraints != tr_constraints || tr2_sat != tr_sat {
10137                return Err(Certified::new(GenericImpossibilityWitness::default()));
10138            }
10139            hasher = crate::enforcement::fold_terminal_reduction(
10140                hasher,
10141                tr2_bits,
10142                tr2_constraints,
10143                tr2_sat,
10144            );
10145            hasher = crate::enforcement::fold_unit_digest(
10146                hasher,
10147                witt_bits,
10148                witt_bits as u64,
10149                T::IRI,
10150                T::SITE_COUNT,
10151                T::CONSTRAINTS,
10152                <Kernel as super::ResolverKernel>::KIND,
10153            );
10154            let buffer = hasher.finalize();
10155            let fp =
10156                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10157            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10158            Ok(Certified::new(cert))
10159        }
10160    }
10161
10162    /// 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.
10163    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10164    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10165    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10166    /// failure — the witness itself is certified so downstream can persist it
10167    /// alongside success certs in a uniform `Certified<_>` channel.
10168    /// Phase X.1: the produced cert class is the ontology-declared class for
10169    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10170    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10171    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10172    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10173    /// kernels so each resolver's class discrimination is load-bearing.
10174    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10175    /// kernel's composition spec) whose output is folded into the canonical
10176    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10177    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10178    /// content-addressed per its ontology class.
10179    pub mod type_synthesis {
10180        use super::*;
10181
10182        #[doc(hidden)]
10183        pub struct Kernel;
10184        impl super::ResolverKernel for Kernel {
10185            type Cert = crate::enforcement::TransformCertificate;
10186            const KIND: crate::enforcement::CertificateKind =
10187                crate::enforcement::CertificateKind::TypeSynthesis;
10188        }
10189
10190        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10191        ///
10192        /// # Errors
10193        ///
10194        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10195        pub fn certify<
10196            T: crate::pipeline::ConstrainedTypeShape,
10197            P: crate::enforcement::ValidationPhase,
10198            H: crate::enforcement::Hasher,
10199        >(
10200            input: &Validated<T, P>,
10201        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10202        {
10203            certify_at::<T, P, H>(input, WittLevel::W32)
10204        }
10205
10206        /// Phase D (target §4.2): certify at an explicit Witt level.
10207        ///
10208        /// # Errors
10209        ///
10210        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10211        pub fn certify_at<
10212            T: crate::pipeline::ConstrainedTypeShape,
10213            P: crate::enforcement::ValidationPhase,
10214            H: crate::enforcement::Hasher,
10215        >(
10216            input: &Validated<T, P>,
10217            level: WittLevel,
10218        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10219        {
10220            let _ = input.inner();
10221            let witt_bits = level.witt_length() as u16;
10222            let (tr_bits, tr_constraints, tr_sat) =
10223                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10224                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10225            if tr_sat == 0 {
10226                return Err(Certified::new(GenericImpossibilityWitness::default()));
10227            }
10228            let mut hasher = H::initial();
10229            hasher = crate::enforcement::fold_terminal_reduction(
10230                hasher,
10231                tr_bits,
10232                tr_constraints,
10233                tr_sat,
10234            );
10235            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10236                .map_err(crate::enforcement::Certified::new)?;
10237            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10238            let (residual, entropy) = crate::enforcement::primitive_descent_metrics::<T>(&betti);
10239            hasher = crate::enforcement::fold_descent_metrics(hasher, residual, entropy);
10240            hasher = crate::enforcement::fold_unit_digest(
10241                hasher,
10242                witt_bits,
10243                witt_bits as u64,
10244                T::IRI,
10245                T::SITE_COUNT,
10246                T::CONSTRAINTS,
10247                <Kernel as super::ResolverKernel>::KIND,
10248            );
10249            let buffer = hasher.finalize();
10250            let fp =
10251                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10252            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10253            Ok(Certified::new(cert))
10254        }
10255    }
10256
10257    /// 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.
10258    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10259    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10260    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10261    /// failure — the witness itself is certified so downstream can persist it
10262    /// alongside success certs in a uniform `Certified<_>` channel.
10263    /// Phase X.1: the produced cert class is the ontology-declared class for
10264    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10265    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10266    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10267    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10268    /// kernels so each resolver's class discrimination is load-bearing.
10269    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10270    /// kernel's composition spec) whose output is folded into the canonical
10271    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10272    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10273    /// content-addressed per its ontology class.
10274    pub mod homotopy {
10275        use super::*;
10276
10277        #[doc(hidden)]
10278        pub struct Kernel;
10279        impl super::ResolverKernel for Kernel {
10280            type Cert = crate::enforcement::TransformCertificate;
10281            const KIND: crate::enforcement::CertificateKind =
10282                crate::enforcement::CertificateKind::Homotopy;
10283        }
10284
10285        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10286        ///
10287        /// # Errors
10288        ///
10289        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10290        pub fn certify<
10291            T: crate::pipeline::ConstrainedTypeShape,
10292            P: crate::enforcement::ValidationPhase,
10293            H: crate::enforcement::Hasher,
10294        >(
10295            input: &Validated<T, P>,
10296        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10297        {
10298            certify_at::<T, P, H>(input, WittLevel::W32)
10299        }
10300
10301        /// Phase D (target §4.2): certify at an explicit Witt level.
10302        ///
10303        /// # Errors
10304        ///
10305        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10306        pub fn certify_at<
10307            T: crate::pipeline::ConstrainedTypeShape,
10308            P: crate::enforcement::ValidationPhase,
10309            H: crate::enforcement::Hasher,
10310        >(
10311            input: &Validated<T, P>,
10312            level: WittLevel,
10313        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10314        {
10315            let _ = input.inner();
10316            let witt_bits = level.witt_length() as u16;
10317            let (tr_bits, tr_constraints, tr_sat) =
10318                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10319                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10320            if tr_sat == 0 {
10321                return Err(Certified::new(GenericImpossibilityWitness::default()));
10322            }
10323            let mut hasher = H::initial();
10324            hasher = crate::enforcement::fold_terminal_reduction(
10325                hasher,
10326                tr_bits,
10327                tr_constraints,
10328                tr_sat,
10329            );
10330            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10331                .map_err(crate::enforcement::Certified::new)?;
10332            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10333            hasher = crate::enforcement::fold_unit_digest(
10334                hasher,
10335                witt_bits,
10336                witt_bits as u64,
10337                T::IRI,
10338                T::SITE_COUNT,
10339                T::CONSTRAINTS,
10340                <Kernel as super::ResolverKernel>::KIND,
10341            );
10342            let buffer = hasher.finalize();
10343            let fp =
10344                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10345            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10346            Ok(Certified::new(cert))
10347        }
10348    }
10349
10350    /// Phase D (target §4.2): `resolver:MonodromyResolver` — compute monodromy-group observables by tracing the constraint-nerve boundary cycles at the input's Witt level.
10351    /// Returns `Certified<IsometryCertificate>` on success carrying the Witt
10352    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10353    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10354    /// failure — the witness itself is certified so downstream can persist it
10355    /// alongside success certs in a uniform `Certified<_>` channel.
10356    /// Phase X.1: the produced cert class is the ontology-declared class for
10357    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10358    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10359    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10360    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10361    /// kernels so each resolver's class discrimination is load-bearing.
10362    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10363    /// kernel's composition spec) whose output is folded into the canonical
10364    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10365    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10366    /// content-addressed per its ontology class.
10367    pub mod monodromy {
10368        use super::*;
10369
10370        #[doc(hidden)]
10371        pub struct Kernel;
10372        impl super::ResolverKernel for Kernel {
10373            type Cert = crate::enforcement::IsometryCertificate;
10374            const KIND: crate::enforcement::CertificateKind =
10375                crate::enforcement::CertificateKind::Monodromy;
10376        }
10377
10378        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10379        ///
10380        /// # Errors
10381        ///
10382        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10383        pub fn certify<
10384            T: crate::pipeline::ConstrainedTypeShape,
10385            P: crate::enforcement::ValidationPhase,
10386            H: crate::enforcement::Hasher,
10387        >(
10388            input: &Validated<T, P>,
10389        ) -> Result<Certified<IsometryCertificate>, Certified<GenericImpossibilityWitness>>
10390        {
10391            certify_at::<T, P, H>(input, WittLevel::W32)
10392        }
10393
10394        /// Phase D (target §4.2): certify at an explicit Witt level.
10395        ///
10396        /// # Errors
10397        ///
10398        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10399        pub fn certify_at<
10400            T: crate::pipeline::ConstrainedTypeShape,
10401            P: crate::enforcement::ValidationPhase,
10402            H: crate::enforcement::Hasher,
10403        >(
10404            input: &Validated<T, P>,
10405            level: WittLevel,
10406        ) -> Result<Certified<IsometryCertificate>, Certified<GenericImpossibilityWitness>>
10407        {
10408            let _ = input.inner();
10409            let witt_bits = level.witt_length() as u16;
10410            let (tr_bits, tr_constraints, tr_sat) =
10411                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10412                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10413            if tr_sat == 0 {
10414                return Err(Certified::new(GenericImpossibilityWitness::default()));
10415            }
10416            let mut hasher = H::initial();
10417            hasher = crate::enforcement::fold_terminal_reduction(
10418                hasher,
10419                tr_bits,
10420                tr_constraints,
10421                tr_sat,
10422            );
10423            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10424                .map_err(crate::enforcement::Certified::new)?;
10425            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
10426            let (orbit_size, representative) =
10427                crate::enforcement::primitive_dihedral_signature::<T>();
10428            hasher =
10429                crate::enforcement::fold_dihedral_signature(hasher, orbit_size, representative);
10430            hasher = crate::enforcement::fold_unit_digest(
10431                hasher,
10432                witt_bits,
10433                witt_bits as u64,
10434                T::IRI,
10435                T::SITE_COUNT,
10436                T::CONSTRAINTS,
10437                <Kernel as super::ResolverKernel>::KIND,
10438            );
10439            let buffer = hasher.finalize();
10440            let fp =
10441                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10442            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10443            Ok(Certified::new(cert))
10444        }
10445    }
10446
10447    /// Phase D (target §4.2): `resolver:ModuliResolver` — compute the local moduli-space structure at a `CompleteType`: DeformationComplex, HolonomyStratum, tangent/obstruction dimensions.
10448    /// Returns `Certified<TransformCertificate>` on success carrying the Witt
10449    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10450    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10451    /// failure — the witness itself is certified so downstream can persist it
10452    /// alongside success certs in a uniform `Certified<_>` channel.
10453    /// Phase X.1: the produced cert class is the ontology-declared class for
10454    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10455    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10456    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10457    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10458    /// kernels so each resolver's class discrimination is load-bearing.
10459    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10460    /// kernel's composition spec) whose output is folded into the canonical
10461    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10462    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10463    /// content-addressed per its ontology class.
10464    pub mod moduli {
10465        use super::*;
10466
10467        #[doc(hidden)]
10468        pub struct Kernel;
10469        impl super::ResolverKernel for Kernel {
10470            type Cert = crate::enforcement::TransformCertificate;
10471            const KIND: crate::enforcement::CertificateKind =
10472                crate::enforcement::CertificateKind::Moduli;
10473        }
10474
10475        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10476        ///
10477        /// # Errors
10478        ///
10479        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10480        pub fn certify<
10481            T: crate::pipeline::ConstrainedTypeShape,
10482            P: crate::enforcement::ValidationPhase,
10483            H: crate::enforcement::Hasher,
10484        >(
10485            input: &Validated<T, P>,
10486        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10487        {
10488            certify_at::<T, P, H>(input, WittLevel::W32)
10489        }
10490
10491        /// Phase D (target §4.2): certify at an explicit Witt level.
10492        ///
10493        /// # Errors
10494        ///
10495        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10496        pub fn certify_at<
10497            T: crate::pipeline::ConstrainedTypeShape,
10498            P: crate::enforcement::ValidationPhase,
10499            H: crate::enforcement::Hasher,
10500        >(
10501            input: &Validated<T, P>,
10502            level: WittLevel,
10503        ) -> Result<Certified<TransformCertificate>, Certified<GenericImpossibilityWitness>>
10504        {
10505            let _ = input.inner();
10506            let witt_bits = level.witt_length() as u16;
10507            let (tr_bits, tr_constraints, tr_sat) =
10508                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10509                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10510            if tr_sat == 0 {
10511                return Err(Certified::new(GenericImpossibilityWitness::default()));
10512            }
10513            let mut hasher = H::initial();
10514            hasher = crate::enforcement::fold_terminal_reduction(
10515                hasher,
10516                tr_bits,
10517                tr_constraints,
10518                tr_sat,
10519            );
10520            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
10521                .map_err(crate::enforcement::Certified::new)?;
10522            let automorphisms: u32 = betti[0];
10523            let deformations: u32 = if crate::enforcement::MAX_BETTI_DIMENSION > 1 {
10524                betti[1]
10525            } else {
10526                0
10527            };
10528            let obstructions: u32 = if crate::enforcement::MAX_BETTI_DIMENSION > 2 {
10529                betti[2]
10530            } else {
10531                0
10532            };
10533            hasher = hasher.fold_bytes(&automorphisms.to_be_bytes());
10534            hasher = hasher.fold_bytes(&deformations.to_be_bytes());
10535            hasher = hasher.fold_bytes(&obstructions.to_be_bytes());
10536            hasher = crate::enforcement::fold_unit_digest(
10537                hasher,
10538                witt_bits,
10539                witt_bits as u64,
10540                T::IRI,
10541                T::SITE_COUNT,
10542                T::CONSTRAINTS,
10543                <Kernel as super::ResolverKernel>::KIND,
10544            );
10545            let buffer = hasher.finalize();
10546            let fp =
10547                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10548            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10549            Ok(Certified::new(cert))
10550        }
10551    }
10552
10553    /// 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.
10554    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10555    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10556    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10557    /// failure — the witness itself is certified so downstream can persist it
10558    /// alongside success certs in a uniform `Certified<_>` channel.
10559    /// Phase X.1: the produced cert class is the ontology-declared class for
10560    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10561    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10562    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10563    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10564    /// kernels so each resolver's class discrimination is load-bearing.
10565    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10566    /// kernel's composition spec) whose output is folded into the canonical
10567    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10568    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10569    /// content-addressed per its ontology class.
10570    pub mod jacobian_guided {
10571        use super::*;
10572
10573        #[doc(hidden)]
10574        pub struct Kernel;
10575        impl super::ResolverKernel for Kernel {
10576            type Cert = crate::enforcement::GroundingCertificate;
10577            const KIND: crate::enforcement::CertificateKind =
10578                crate::enforcement::CertificateKind::JacobianGuided;
10579        }
10580
10581        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10582        ///
10583        /// # Errors
10584        ///
10585        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10586        pub fn certify<
10587            T: crate::pipeline::ConstrainedTypeShape,
10588            P: crate::enforcement::ValidationPhase,
10589            H: crate::enforcement::Hasher,
10590        >(
10591            input: &Validated<T, P>,
10592        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10593        {
10594            certify_at::<T, P, H>(input, WittLevel::W32)
10595        }
10596
10597        /// Phase D (target §4.2): certify at an explicit Witt level.
10598        ///
10599        /// # Errors
10600        ///
10601        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10602        pub fn certify_at<
10603            T: crate::pipeline::ConstrainedTypeShape,
10604            P: crate::enforcement::ValidationPhase,
10605            H: crate::enforcement::Hasher,
10606        >(
10607            input: &Validated<T, P>,
10608            level: WittLevel,
10609        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10610        {
10611            let _ = input.inner();
10612            let witt_bits = level.witt_length() as u16;
10613            let (tr_bits, tr_constraints, tr_sat) =
10614                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10615                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10616            if tr_sat == 0 {
10617                return Err(Certified::new(GenericImpossibilityWitness::default()));
10618            }
10619            let mut hasher = H::initial();
10620            hasher = crate::enforcement::fold_terminal_reduction(
10621                hasher,
10622                tr_bits,
10623                tr_constraints,
10624                tr_sat,
10625            );
10626            let jac = crate::enforcement::primitive_curvature_jacobian::<T>();
10627            hasher = crate::enforcement::fold_jacobian_profile(hasher, &jac);
10628            let selected_site = crate::enforcement::primitive_dc10_select(&jac);
10629            hasher = hasher.fold_bytes(&(selected_site as u32).to_be_bytes());
10630            hasher = crate::enforcement::fold_unit_digest(
10631                hasher,
10632                witt_bits,
10633                witt_bits as u64,
10634                T::IRI,
10635                T::SITE_COUNT,
10636                T::CONSTRAINTS,
10637                <Kernel as super::ResolverKernel>::KIND,
10638            );
10639            let buffer = hasher.finalize();
10640            let fp =
10641                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10642            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10643            Ok(Certified::new(cert))
10644        }
10645    }
10646
10647    /// 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.
10648    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10649    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10650    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10651    /// failure — the witness itself is certified so downstream can persist it
10652    /// alongside success certs in a uniform `Certified<_>` channel.
10653    /// Phase X.1: the produced cert class is the ontology-declared class for
10654    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10655    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10656    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10657    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10658    /// kernels so each resolver's class discrimination is load-bearing.
10659    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10660    /// kernel's composition spec) whose output is folded into the canonical
10661    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10662    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10663    /// content-addressed per its ontology class.
10664    pub mod evaluation {
10665        use super::*;
10666
10667        #[doc(hidden)]
10668        pub struct Kernel;
10669        impl super::ResolverKernel for Kernel {
10670            type Cert = crate::enforcement::GroundingCertificate;
10671            const KIND: crate::enforcement::CertificateKind =
10672                crate::enforcement::CertificateKind::Evaluation;
10673        }
10674
10675        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10676        ///
10677        /// # Errors
10678        ///
10679        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10680        pub fn certify<
10681            T: crate::pipeline::ConstrainedTypeShape,
10682            P: crate::enforcement::ValidationPhase,
10683            H: crate::enforcement::Hasher,
10684        >(
10685            input: &Validated<T, P>,
10686        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10687        {
10688            certify_at::<T, P, H>(input, WittLevel::W32)
10689        }
10690
10691        /// Phase D (target §4.2): certify at an explicit Witt level.
10692        ///
10693        /// # Errors
10694        ///
10695        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10696        pub fn certify_at<
10697            T: crate::pipeline::ConstrainedTypeShape,
10698            P: crate::enforcement::ValidationPhase,
10699            H: crate::enforcement::Hasher,
10700        >(
10701            input: &Validated<T, P>,
10702            level: WittLevel,
10703        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10704        {
10705            let _ = input.inner();
10706            let witt_bits = level.witt_length() as u16;
10707            let (tr_bits, tr_constraints, tr_sat) =
10708                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
10709                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
10710            if tr_sat == 0 {
10711                return Err(Certified::new(GenericImpossibilityWitness::default()));
10712            }
10713            let mut hasher = H::initial();
10714            hasher = crate::enforcement::fold_terminal_reduction(
10715                hasher,
10716                tr_bits,
10717                tr_constraints,
10718                tr_sat,
10719            );
10720            hasher = crate::enforcement::fold_unit_digest(
10721                hasher,
10722                witt_bits,
10723                witt_bits as u64,
10724                T::IRI,
10725                T::SITE_COUNT,
10726                T::CONSTRAINTS,
10727                <Kernel as super::ResolverKernel>::KIND,
10728            );
10729            let buffer = hasher.finalize();
10730            let fp =
10731                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10732            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10733            Ok(Certified::new(cert))
10734        }
10735    }
10736
10737    /// 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.
10738    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10739    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10740    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10741    /// failure — the witness itself is certified so downstream can persist it
10742    /// alongside success certs in a uniform `Certified<_>` channel.
10743    /// Phase X.1: the produced cert class is the ontology-declared class for
10744    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10745    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10746    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10747    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10748    /// kernels so each resolver's class discrimination is load-bearing.
10749    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10750    /// kernel's composition spec) whose output is folded into the canonical
10751    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10752    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10753    /// content-addressed per its ontology class.
10754    pub mod session {
10755        use super::*;
10756
10757        #[doc(hidden)]
10758        pub struct Kernel;
10759        impl super::ResolverKernel for Kernel {
10760            type Cert = crate::enforcement::GroundingCertificate;
10761            const KIND: crate::enforcement::CertificateKind =
10762                crate::enforcement::CertificateKind::Session;
10763        }
10764
10765        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10766        ///
10767        /// # Errors
10768        ///
10769        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10770        pub fn certify<
10771            P: crate::enforcement::ValidationPhase,
10772            H: crate::enforcement::Hasher,
10773            const INLINE_BYTES: usize,
10774        >(
10775            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10776        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10777        {
10778            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10779        }
10780
10781        /// Phase D (target §4.2): certify at an explicit Witt level.
10782        ///
10783        /// # Errors
10784        ///
10785        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10786        pub fn certify_at<
10787            P: crate::enforcement::ValidationPhase,
10788            H: crate::enforcement::Hasher,
10789            const INLINE_BYTES: usize,
10790        >(
10791            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10792            level: WittLevel,
10793        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
10794        {
10795            let unit = input.inner();
10796            let witt_bits = level.witt_length() as u16;
10797            let budget = unit.thermodynamic_budget();
10798            let result_type_iri = unit.result_type_iri();
10799            let mut hasher = H::initial();
10800            let (binding_count, fold_addr) =
10801                crate::enforcement::primitive_session_binding_signature(unit.bindings());
10802            hasher = crate::enforcement::fold_session_signature(hasher, binding_count, fold_addr);
10803            hasher = crate::enforcement::fold_unit_digest(
10804                hasher,
10805                witt_bits,
10806                budget,
10807                result_type_iri,
10808                0usize,
10809                &[],
10810                <Kernel as super::ResolverKernel>::KIND,
10811            );
10812            let buffer = hasher.finalize();
10813            let fp =
10814                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10815            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10816            Ok(Certified::new(cert))
10817        }
10818    }
10819
10820    /// 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).
10821    /// Returns `Certified<BornRuleVerification>` on success carrying the Witt
10822    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10823    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10824    /// failure — the witness itself is certified so downstream can persist it
10825    /// alongside success certs in a uniform `Certified<_>` channel.
10826    /// Phase X.1: the produced cert class is the ontology-declared class for
10827    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10828    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10829    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10830    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10831    /// kernels so each resolver's class discrimination is load-bearing.
10832    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10833    /// kernel's composition spec) whose output is folded into the canonical
10834    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10835    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10836    /// content-addressed per its ontology class.
10837    pub mod superposition {
10838        use super::*;
10839
10840        #[doc(hidden)]
10841        pub struct Kernel;
10842        impl super::ResolverKernel for Kernel {
10843            type Cert = crate::enforcement::BornRuleVerification;
10844            const KIND: crate::enforcement::CertificateKind =
10845                crate::enforcement::CertificateKind::Superposition;
10846        }
10847
10848        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10849        ///
10850        /// # Errors
10851        ///
10852        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10853        pub fn certify<
10854            P: crate::enforcement::ValidationPhase,
10855            H: crate::enforcement::Hasher,
10856            const INLINE_BYTES: usize,
10857        >(
10858            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10859        ) -> Result<Certified<BornRuleVerification>, Certified<GenericImpossibilityWitness>>
10860        {
10861            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10862        }
10863
10864        /// Phase D (target §4.2): certify at an explicit Witt level.
10865        ///
10866        /// # Errors
10867        ///
10868        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10869        pub fn certify_at<
10870            P: crate::enforcement::ValidationPhase,
10871            H: crate::enforcement::Hasher,
10872            const INLINE_BYTES: usize,
10873        >(
10874            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10875            level: WittLevel,
10876        ) -> Result<Certified<BornRuleVerification>, Certified<GenericImpossibilityWitness>>
10877        {
10878            let unit = input.inner();
10879            let witt_bits = level.witt_length() as u16;
10880            let budget = unit.thermodynamic_budget();
10881            let result_type_iri = unit.result_type_iri();
10882            let mut hasher = H::initial();
10883            let (binding_count, fold_addr) =
10884                crate::enforcement::primitive_session_binding_signature(unit.bindings());
10885            hasher = crate::enforcement::fold_session_signature(hasher, binding_count, fold_addr);
10886            let (outcome_index, probability) =
10887                crate::enforcement::primitive_measurement_projection(budget);
10888            hasher = crate::enforcement::fold_born_outcome(hasher, outcome_index, probability);
10889            hasher = crate::enforcement::fold_unit_digest(
10890                hasher,
10891                witt_bits,
10892                budget,
10893                result_type_iri,
10894                0usize,
10895                &[],
10896                <Kernel as super::ResolverKernel>::KIND,
10897            );
10898            let buffer = hasher.finalize();
10899            let fp =
10900                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10901            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10902            Ok(Certified::new(cert))
10903        }
10904    }
10905
10906    /// Phase D (target §4.2): `resolver:MeasurementResolver` — resolve a `trace:MeasurementEvent` against the von Neumann-Landauer bridge (QM_1): `preCollapseEntropy = postCollapseLandauerCost` at β* = ln 2.
10907    /// Returns `Certified<MeasurementCertificate>` on success carrying the Witt
10908    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10909    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10910    /// failure — the witness itself is certified so downstream can persist it
10911    /// alongside success certs in a uniform `Certified<_>` channel.
10912    /// Phase X.1: the produced cert class is the ontology-declared class for
10913    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10914    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10915    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10916    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
10917    /// kernels so each resolver's class discrimination is load-bearing.
10918    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
10919    /// kernel's composition spec) whose output is folded into the canonical
10920    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
10921    /// yield distinct fingerprints — i.e., each kernel's decision is real and
10922    /// content-addressed per its ontology class.
10923    pub mod measurement {
10924        use super::*;
10925
10926        #[doc(hidden)]
10927        pub struct Kernel;
10928        impl super::ResolverKernel for Kernel {
10929            type Cert = crate::enforcement::MeasurementCertificate;
10930            const KIND: crate::enforcement::CertificateKind =
10931                crate::enforcement::CertificateKind::Measurement;
10932        }
10933
10934        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
10935        ///
10936        /// # Errors
10937        ///
10938        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10939        pub fn certify<
10940            P: crate::enforcement::ValidationPhase,
10941            H: crate::enforcement::Hasher,
10942            const INLINE_BYTES: usize,
10943        >(
10944            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10945        ) -> Result<Certified<MeasurementCertificate>, Certified<GenericImpossibilityWitness>>
10946        {
10947            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
10948        }
10949
10950        /// Phase D (target §4.2): certify at an explicit Witt level.
10951        ///
10952        /// # Errors
10953        ///
10954        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
10955        pub fn certify_at<
10956            P: crate::enforcement::ValidationPhase,
10957            H: crate::enforcement::Hasher,
10958            const INLINE_BYTES: usize,
10959        >(
10960            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
10961            level: WittLevel,
10962        ) -> Result<Certified<MeasurementCertificate>, Certified<GenericImpossibilityWitness>>
10963        {
10964            let unit = input.inner();
10965            let witt_bits = level.witt_length() as u16;
10966            let budget = unit.thermodynamic_budget();
10967            let result_type_iri = unit.result_type_iri();
10968            let mut hasher = H::initial();
10969            let (outcome_index, probability) =
10970                crate::enforcement::primitive_measurement_projection(budget);
10971            hasher = crate::enforcement::fold_born_outcome(hasher, outcome_index, probability);
10972            hasher = crate::enforcement::fold_unit_digest(
10973                hasher,
10974                witt_bits,
10975                budget,
10976                result_type_iri,
10977                0usize,
10978                &[],
10979                <Kernel as super::ResolverKernel>::KIND,
10980            );
10981            let buffer = hasher.finalize();
10982            let fp =
10983                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
10984            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
10985            Ok(Certified::new(cert))
10986        }
10987    }
10988
10989    /// 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.
10990    /// Returns `Certified<GroundingCertificate>` on success carrying the Witt
10991    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
10992    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
10993    /// failure — the witness itself is certified so downstream can persist it
10994    /// alongside success certs in a uniform `Certified<_>` channel.
10995    /// Phase X.1: the produced cert class is the ontology-declared class for
10996    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
10997    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
10998    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
10999    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11000    /// kernels so each resolver's class discrimination is load-bearing.
11001    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11002    /// kernel's composition spec) whose output is folded into the canonical
11003    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11004    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11005    /// content-addressed per its ontology class.
11006    pub mod witt_level_resolver {
11007        use super::*;
11008
11009        #[doc(hidden)]
11010        pub struct Kernel;
11011        impl super::ResolverKernel for Kernel {
11012            type Cert = crate::enforcement::GroundingCertificate;
11013            const KIND: crate::enforcement::CertificateKind =
11014                crate::enforcement::CertificateKind::WittLevel;
11015        }
11016
11017        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11018        ///
11019        /// # Errors
11020        ///
11021        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11022        pub fn certify<
11023            P: crate::enforcement::ValidationPhase,
11024            H: crate::enforcement::Hasher,
11025            const INLINE_BYTES: usize,
11026        >(
11027            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
11028        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
11029        {
11030            certify_at::<P, H, INLINE_BYTES>(input, WittLevel::W32)
11031        }
11032
11033        /// Phase D (target §4.2): certify at an explicit Witt level.
11034        ///
11035        /// # Errors
11036        ///
11037        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11038        pub fn certify_at<
11039            P: crate::enforcement::ValidationPhase,
11040            H: crate::enforcement::Hasher,
11041            const INLINE_BYTES: usize,
11042        >(
11043            input: &Validated<CompileUnit<'_, INLINE_BYTES>, P>,
11044            level: WittLevel,
11045        ) -> Result<Certified<GroundingCertificate>, Certified<GenericImpossibilityWitness>>
11046        {
11047            let unit = input.inner();
11048            let witt_bits = level.witt_length() as u16;
11049            let budget = unit.thermodynamic_budget();
11050            let result_type_iri = unit.result_type_iri();
11051            let mut hasher = H::initial();
11052            hasher = hasher.fold_bytes(&witt_bits.to_be_bytes());
11053            let declared_level_bits = unit.witt_level().witt_length() as u16;
11054            hasher = hasher.fold_bytes(&declared_level_bits.to_be_bytes());
11055            hasher = crate::enforcement::fold_unit_digest(
11056                hasher,
11057                witt_bits,
11058                budget,
11059                result_type_iri,
11060                0usize,
11061                &[],
11062                <Kernel as super::ResolverKernel>::KIND,
11063            );
11064            let buffer = hasher.finalize();
11065            let fp =
11066                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11067            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11068            Ok(Certified::new(cert))
11069        }
11070    }
11071
11072    /// Phase D (target §4.2): `resolver:DihedralFactorizationResolver` — run the dihedral factorization decider on a `ConstrainedType`'s carrier, producing a cert over the factor structure.
11073    /// Returns `Certified<InvolutionCertificate>` on success carrying the Witt
11074    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11075    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11076    /// failure — the witness itself is certified so downstream can persist it
11077    /// alongside success certs in a uniform `Certified<_>` channel.
11078    /// Phase X.1: the produced cert class is the ontology-declared class for
11079    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11080    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11081    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11082    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11083    /// kernels so each resolver's class discrimination is load-bearing.
11084    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11085    /// kernel's composition spec) whose output is folded into the canonical
11086    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11087    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11088    /// content-addressed per its ontology class.
11089    pub mod dihedral_factorization {
11090        use super::*;
11091
11092        #[doc(hidden)]
11093        pub struct Kernel;
11094        impl super::ResolverKernel for Kernel {
11095            type Cert = crate::enforcement::InvolutionCertificate;
11096            const KIND: crate::enforcement::CertificateKind =
11097                crate::enforcement::CertificateKind::DihedralFactorization;
11098        }
11099
11100        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11101        ///
11102        /// # Errors
11103        ///
11104        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11105        pub fn certify<
11106            T: crate::pipeline::ConstrainedTypeShape,
11107            P: crate::enforcement::ValidationPhase,
11108            H: crate::enforcement::Hasher,
11109        >(
11110            input: &Validated<T, P>,
11111        ) -> Result<Certified<InvolutionCertificate>, Certified<GenericImpossibilityWitness>>
11112        {
11113            certify_at::<T, P, H>(input, WittLevel::W32)
11114        }
11115
11116        /// Phase D (target §4.2): certify at an explicit Witt level.
11117        ///
11118        /// # Errors
11119        ///
11120        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11121        pub fn certify_at<
11122            T: crate::pipeline::ConstrainedTypeShape,
11123            P: crate::enforcement::ValidationPhase,
11124            H: crate::enforcement::Hasher,
11125        >(
11126            input: &Validated<T, P>,
11127            level: WittLevel,
11128        ) -> Result<Certified<InvolutionCertificate>, Certified<GenericImpossibilityWitness>>
11129        {
11130            let _ = input.inner();
11131            let witt_bits = level.witt_length() as u16;
11132            let (tr_bits, tr_constraints, tr_sat) =
11133                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11134                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11135            if tr_sat == 0 {
11136                return Err(Certified::new(GenericImpossibilityWitness::default()));
11137            }
11138            let mut hasher = H::initial();
11139            hasher = crate::enforcement::fold_terminal_reduction(
11140                hasher,
11141                tr_bits,
11142                tr_constraints,
11143                tr_sat,
11144            );
11145            let (orbit_size, representative) =
11146                crate::enforcement::primitive_dihedral_signature::<T>();
11147            hasher =
11148                crate::enforcement::fold_dihedral_signature(hasher, orbit_size, representative);
11149            hasher = crate::enforcement::fold_unit_digest(
11150                hasher,
11151                witt_bits,
11152                witt_bits as u64,
11153                T::IRI,
11154                T::SITE_COUNT,
11155                T::CONSTRAINTS,
11156                <Kernel as super::ResolverKernel>::KIND,
11157            );
11158            let buffer = hasher.finalize();
11159            let fp =
11160                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11161            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11162            Ok(Certified::new(cert))
11163        }
11164    }
11165
11166    /// 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.
11167    /// Returns `Certified<CompletenessCertificate>` on success carrying the Witt
11168    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11169    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11170    /// failure — the witness itself is certified so downstream can persist it
11171    /// alongside success certs in a uniform `Certified<_>` channel.
11172    /// Phase X.1: the produced cert class is the ontology-declared class for
11173    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11174    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11175    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11176    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11177    /// kernels so each resolver's class discrimination is load-bearing.
11178    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11179    /// kernel's composition spec) whose output is folded into the canonical
11180    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11181    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11182    /// content-addressed per its ontology class.
11183    pub mod completeness {
11184        use super::*;
11185
11186        #[doc(hidden)]
11187        pub struct Kernel;
11188        impl super::ResolverKernel for Kernel {
11189            type Cert = crate::enforcement::CompletenessCertificate;
11190            const KIND: crate::enforcement::CertificateKind =
11191                crate::enforcement::CertificateKind::Completeness;
11192        }
11193
11194        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11195        ///
11196        /// # Errors
11197        ///
11198        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11199        pub fn certify<
11200            T: crate::pipeline::ConstrainedTypeShape,
11201            P: crate::enforcement::ValidationPhase,
11202            H: crate::enforcement::Hasher,
11203        >(
11204            input: &Validated<T, P>,
11205        ) -> Result<Certified<CompletenessCertificate>, Certified<GenericImpossibilityWitness>>
11206        {
11207            certify_at::<T, P, H>(input, WittLevel::W32)
11208        }
11209
11210        /// Phase D (target §4.2): certify at an explicit Witt level.
11211        ///
11212        /// # Errors
11213        ///
11214        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11215        pub fn certify_at<
11216            T: crate::pipeline::ConstrainedTypeShape,
11217            P: crate::enforcement::ValidationPhase,
11218            H: crate::enforcement::Hasher,
11219        >(
11220            input: &Validated<T, P>,
11221            level: WittLevel,
11222        ) -> Result<Certified<CompletenessCertificate>, Certified<GenericImpossibilityWitness>>
11223        {
11224            let _ = input.inner();
11225            let witt_bits = level.witt_length() as u16;
11226            let (tr_bits, tr_constraints, tr_sat) =
11227                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11228                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11229            if tr_sat == 0 {
11230                return Err(Certified::new(GenericImpossibilityWitness::default()));
11231            }
11232            let mut hasher = H::initial();
11233            hasher = crate::enforcement::fold_terminal_reduction(
11234                hasher,
11235                tr_bits,
11236                tr_constraints,
11237                tr_sat,
11238            );
11239            let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()
11240                .map_err(crate::enforcement::Certified::new)?;
11241            let chi = crate::enforcement::primitive_euler_characteristic(&betti);
11242            hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
11243            hasher = hasher.fold_bytes(&chi.to_be_bytes());
11244            hasher = crate::enforcement::fold_unit_digest(
11245                hasher,
11246                witt_bits,
11247                witt_bits as u64,
11248                T::IRI,
11249                T::SITE_COUNT,
11250                T::CONSTRAINTS,
11251                <Kernel as super::ResolverKernel>::KIND,
11252            );
11253            let buffer = hasher.finalize();
11254            let fp =
11255                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11256            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11257            Ok(Certified::new(cert))
11258        }
11259    }
11260
11261    /// 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.
11262    /// Returns `Certified<GeodesicCertificate>` on success carrying the Witt
11263    /// level and a consumer-hasher-computed substrate fingerprint that uniquely
11264    /// identifies the input. `Certified<GenericImpossibilityWitness>` on
11265    /// failure — the witness itself is certified so downstream can persist it
11266    /// alongside success certs in a uniform `Certified<_>` channel.
11267    /// Phase X.1: the produced cert class is the ontology-declared class for
11268    /// this resolver's `resolver:CertifyMapping`. Eight cert subclasses —
11269    /// `TransformCertificate`, `IsometryCertificate`, `InvolutionCertificate`,
11270    /// `CompletenessCertificate`, `GeodesicCertificate`, `MeasurementCertificate`,
11271    /// `BornRuleVerification`, and `GroundingCertificate` — are minted across the 17 Phase D
11272    /// kernels so each resolver's class discrimination is load-bearing.
11273    /// v0.2.2 Phase J: `certify_at` composes an ontology primitive (per the
11274    /// kernel's composition spec) whose output is folded into the canonical
11275    /// fingerprint ahead of `fold_unit_digest`, so distinct primitive outputs
11276    /// yield distinct fingerprints — i.e., each kernel's decision is real and
11277    /// content-addressed per its ontology class.
11278    pub mod geodesic_validator {
11279        use super::*;
11280
11281        #[doc(hidden)]
11282        pub struct Kernel;
11283        impl super::ResolverKernel for Kernel {
11284            type Cert = crate::enforcement::GeodesicCertificate;
11285            const KIND: crate::enforcement::CertificateKind =
11286                crate::enforcement::CertificateKind::GeodesicValidator;
11287        }
11288
11289        /// Phase D (target §4.2): certify at the canonical `WittLevel::W32`.
11290        ///
11291        /// # Errors
11292        ///
11293        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11294        pub fn certify<
11295            T: crate::pipeline::ConstrainedTypeShape,
11296            P: crate::enforcement::ValidationPhase,
11297            H: crate::enforcement::Hasher,
11298        >(
11299            input: &Validated<T, P>,
11300        ) -> Result<Certified<GeodesicCertificate>, Certified<GenericImpossibilityWitness>>
11301        {
11302            certify_at::<T, P, H>(input, WittLevel::W32)
11303        }
11304
11305        /// Phase D (target §4.2): certify at an explicit Witt level.
11306        ///
11307        /// # Errors
11308        ///
11309        /// Returns `Certified<GenericImpossibilityWitness>` on failure.
11310        pub fn certify_at<
11311            T: crate::pipeline::ConstrainedTypeShape,
11312            P: crate::enforcement::ValidationPhase,
11313            H: crate::enforcement::Hasher,
11314        >(
11315            input: &Validated<T, P>,
11316            level: WittLevel,
11317        ) -> Result<Certified<GeodesicCertificate>, Certified<GenericImpossibilityWitness>>
11318        {
11319            let _ = input.inner();
11320            let witt_bits = level.witt_length() as u16;
11321            let (tr_bits, tr_constraints, tr_sat) =
11322                crate::enforcement::primitive_terminal_reduction::<T>(witt_bits)
11323                    .map_err(|_| Certified::new(GenericImpossibilityWitness::default()))?;
11324            if tr_sat == 0 {
11325                return Err(Certified::new(GenericImpossibilityWitness::default()));
11326            }
11327            let mut hasher = H::initial();
11328            hasher = crate::enforcement::fold_terminal_reduction(
11329                hasher,
11330                tr_bits,
11331                tr_constraints,
11332                tr_sat,
11333            );
11334            let jac = crate::enforcement::primitive_curvature_jacobian::<T>();
11335            hasher = crate::enforcement::fold_jacobian_profile(hasher, &jac);
11336            let selected_site = crate::enforcement::primitive_dc10_select(&jac);
11337            hasher = hasher.fold_bytes(&(selected_site as u32).to_be_bytes());
11338            hasher = crate::enforcement::fold_unit_digest(
11339                hasher,
11340                witt_bits,
11341                witt_bits as u64,
11342                T::IRI,
11343                T::SITE_COUNT,
11344                T::CONSTRAINTS,
11345                <Kernel as super::ResolverKernel>::KIND,
11346            );
11347            let buffer = hasher.finalize();
11348            let fp =
11349                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
11350            let cert = <<Kernel as super::ResolverKernel>::Cert as crate::enforcement::certify_const_mint::MintWithLevelFingerprint>::mint_with_level_fingerprint(witt_bits, fp);
11351            Ok(Certified::new(cert))
11352        }
11353    }
11354}
11355
11356/// v0.2.2 phantom-typed ring operation surface. Each phantom struct binds a
11357/// `WittLevel` at the type level so consumers can write
11358/// `Mul::<W8>::apply(a, b)` for compile-time level-checked arithmetic.
11359pub trait RingOp<L> {
11360    /// Operand type at this level.
11361    type Operand;
11362    /// Apply this binary ring op.
11363    fn apply(a: Self::Operand, b: Self::Operand) -> Self::Operand;
11364}
11365
11366/// v0.2.2 W3: unary phantom-typed ring operation surface. Mirrors `RingOp`
11367/// for arity-1 operations (`Neg`, `BNot`, `Succ`) so consumers can write
11368/// `Neg::<W8>::apply(a)` for compile-time level-checked unary arithmetic.
11369pub trait UnaryRingOp<L> {
11370    /// Operand type at this level.
11371    type Operand;
11372    /// Apply this unary ring op.
11373    fn apply(a: Self::Operand) -> Self::Operand;
11374}
11375
11376/// Multiplicative ring op. phantom-typed at level `L`.
11377#[derive(Debug, Default, Clone, Copy)]
11378pub struct Mul<L>(PhantomData<L>);
11379
11380/// Additive ring op. phantom-typed at level `L`.
11381#[derive(Debug, Default, Clone, Copy)]
11382pub struct Add<L>(PhantomData<L>);
11383
11384/// Subtractive ring op. phantom-typed at level `L`.
11385#[derive(Debug, Default, Clone, Copy)]
11386pub struct Sub<L>(PhantomData<L>);
11387
11388/// Bitwise XOR ring op. phantom-typed at level `L`.
11389#[derive(Debug, Default, Clone, Copy)]
11390pub struct Xor<L>(PhantomData<L>);
11391
11392/// Bitwise AND ring op. phantom-typed at level `L`.
11393#[derive(Debug, Default, Clone, Copy)]
11394pub struct And<L>(PhantomData<L>);
11395
11396/// Bitwise OR ring op. phantom-typed at level `L`.
11397#[derive(Debug, Default, Clone, Copy)]
11398pub struct Or<L>(PhantomData<L>);
11399
11400/// Ring negation (the canonical involution: x → -x). Phantom-typed at level `L` (v0.2.2 W3).
11401#[derive(Debug, Default, Clone, Copy)]
11402pub struct Neg<L>(PhantomData<L>);
11403
11404/// Bitwise NOT (the Hamming involution: x → (2^n - 1) XOR x). Phantom-typed at level `L` (v0.2.2 W3).
11405#[derive(Debug, Default, Clone, Copy)]
11406pub struct BNot<L>(PhantomData<L>);
11407
11408/// Successor (= Neg ∘ BNot per the critical composition law). Phantom-typed at level `L` (v0.2.2 W3).
11409#[derive(Debug, Default, Clone, Copy)]
11410pub struct Succ<L>(PhantomData<L>);
11411
11412/// W8 marker — 8-bit Witt level reified at the type level.
11413#[derive(Debug, Default, Clone, Copy)]
11414pub struct W8;
11415
11416/// W16 marker — 16-bit Witt level reified at the type level.
11417#[derive(Debug, Default, Clone, Copy)]
11418pub struct W16;
11419
11420/// W24 marker — 24-bit Witt level reified at the type level.
11421#[derive(Debug, Default, Clone, Copy)]
11422pub struct W24;
11423
11424/// W32 marker — 32-bit Witt level reified at the type level.
11425#[derive(Debug, Default, Clone, Copy)]
11426pub struct W32;
11427
11428/// W40 marker — 40-bit Witt level reified at the type level.
11429#[derive(Debug, Default, Clone, Copy)]
11430pub struct W40;
11431
11432/// W48 marker — 48-bit Witt level reified at the type level.
11433#[derive(Debug, Default, Clone, Copy)]
11434pub struct W48;
11435
11436/// W56 marker — 56-bit Witt level reified at the type level.
11437#[derive(Debug, Default, Clone, Copy)]
11438pub struct W56;
11439
11440/// W64 marker — 64-bit Witt level reified at the type level.
11441#[derive(Debug, Default, Clone, Copy)]
11442pub struct W64;
11443
11444/// W72 marker — 72-bit Witt level reified at the type level.
11445#[derive(Debug, Default, Clone, Copy)]
11446pub struct W72;
11447
11448/// W80 marker — 80-bit Witt level reified at the type level.
11449#[derive(Debug, Default, Clone, Copy)]
11450pub struct W80;
11451
11452/// W88 marker — 88-bit Witt level reified at the type level.
11453#[derive(Debug, Default, Clone, Copy)]
11454pub struct W88;
11455
11456/// W96 marker — 96-bit Witt level reified at the type level.
11457#[derive(Debug, Default, Clone, Copy)]
11458pub struct W96;
11459
11460/// W104 marker — 104-bit Witt level reified at the type level.
11461#[derive(Debug, Default, Clone, Copy)]
11462pub struct W104;
11463
11464/// W112 marker — 112-bit Witt level reified at the type level.
11465#[derive(Debug, Default, Clone, Copy)]
11466pub struct W112;
11467
11468/// W120 marker — 120-bit Witt level reified at the type level.
11469#[derive(Debug, Default, Clone, Copy)]
11470pub struct W120;
11471
11472/// W128 marker — 128-bit Witt level reified at the type level.
11473#[derive(Debug, Default, Clone, Copy)]
11474pub struct W128;
11475
11476impl RingOp<W8> for Mul<W8> {
11477    type Operand = u8;
11478    #[inline]
11479    fn apply(a: u8, b: u8) -> u8 {
11480        const_ring_eval_w8(PrimitiveOp::Mul, a, b)
11481    }
11482}
11483
11484impl RingOp<W8> for Add<W8> {
11485    type Operand = u8;
11486    #[inline]
11487    fn apply(a: u8, b: u8) -> u8 {
11488        const_ring_eval_w8(PrimitiveOp::Add, a, b)
11489    }
11490}
11491
11492impl RingOp<W8> for Sub<W8> {
11493    type Operand = u8;
11494    #[inline]
11495    fn apply(a: u8, b: u8) -> u8 {
11496        const_ring_eval_w8(PrimitiveOp::Sub, a, b)
11497    }
11498}
11499
11500impl RingOp<W8> for Xor<W8> {
11501    type Operand = u8;
11502    #[inline]
11503    fn apply(a: u8, b: u8) -> u8 {
11504        const_ring_eval_w8(PrimitiveOp::Xor, a, b)
11505    }
11506}
11507
11508impl RingOp<W8> for And<W8> {
11509    type Operand = u8;
11510    #[inline]
11511    fn apply(a: u8, b: u8) -> u8 {
11512        const_ring_eval_w8(PrimitiveOp::And, a, b)
11513    }
11514}
11515
11516impl RingOp<W8> for Or<W8> {
11517    type Operand = u8;
11518    #[inline]
11519    fn apply(a: u8, b: u8) -> u8 {
11520        const_ring_eval_w8(PrimitiveOp::Or, a, b)
11521    }
11522}
11523
11524impl RingOp<W16> for Mul<W16> {
11525    type Operand = u16;
11526    #[inline]
11527    fn apply(a: u16, b: u16) -> u16 {
11528        const_ring_eval_w16(PrimitiveOp::Mul, a, b)
11529    }
11530}
11531
11532impl RingOp<W16> for Add<W16> {
11533    type Operand = u16;
11534    #[inline]
11535    fn apply(a: u16, b: u16) -> u16 {
11536        const_ring_eval_w16(PrimitiveOp::Add, a, b)
11537    }
11538}
11539
11540impl RingOp<W16> for Sub<W16> {
11541    type Operand = u16;
11542    #[inline]
11543    fn apply(a: u16, b: u16) -> u16 {
11544        const_ring_eval_w16(PrimitiveOp::Sub, a, b)
11545    }
11546}
11547
11548impl RingOp<W16> for Xor<W16> {
11549    type Operand = u16;
11550    #[inline]
11551    fn apply(a: u16, b: u16) -> u16 {
11552        const_ring_eval_w16(PrimitiveOp::Xor, a, b)
11553    }
11554}
11555
11556impl RingOp<W16> for And<W16> {
11557    type Operand = u16;
11558    #[inline]
11559    fn apply(a: u16, b: u16) -> u16 {
11560        const_ring_eval_w16(PrimitiveOp::And, a, b)
11561    }
11562}
11563
11564impl RingOp<W16> for Or<W16> {
11565    type Operand = u16;
11566    #[inline]
11567    fn apply(a: u16, b: u16) -> u16 {
11568        const_ring_eval_w16(PrimitiveOp::Or, a, b)
11569    }
11570}
11571
11572impl RingOp<W24> for Mul<W24> {
11573    type Operand = u32;
11574    #[inline]
11575    fn apply(a: u32, b: u32) -> u32 {
11576        const_ring_eval_w24(PrimitiveOp::Mul, a, b)
11577    }
11578}
11579
11580impl RingOp<W24> for Add<W24> {
11581    type Operand = u32;
11582    #[inline]
11583    fn apply(a: u32, b: u32) -> u32 {
11584        const_ring_eval_w24(PrimitiveOp::Add, a, b)
11585    }
11586}
11587
11588impl RingOp<W24> for Sub<W24> {
11589    type Operand = u32;
11590    #[inline]
11591    fn apply(a: u32, b: u32) -> u32 {
11592        const_ring_eval_w24(PrimitiveOp::Sub, a, b)
11593    }
11594}
11595
11596impl RingOp<W24> for Xor<W24> {
11597    type Operand = u32;
11598    #[inline]
11599    fn apply(a: u32, b: u32) -> u32 {
11600        const_ring_eval_w24(PrimitiveOp::Xor, a, b)
11601    }
11602}
11603
11604impl RingOp<W24> for And<W24> {
11605    type Operand = u32;
11606    #[inline]
11607    fn apply(a: u32, b: u32) -> u32 {
11608        const_ring_eval_w24(PrimitiveOp::And, a, b)
11609    }
11610}
11611
11612impl RingOp<W24> for Or<W24> {
11613    type Operand = u32;
11614    #[inline]
11615    fn apply(a: u32, b: u32) -> u32 {
11616        const_ring_eval_w24(PrimitiveOp::Or, a, b)
11617    }
11618}
11619
11620impl RingOp<W32> for Mul<W32> {
11621    type Operand = u32;
11622    #[inline]
11623    fn apply(a: u32, b: u32) -> u32 {
11624        const_ring_eval_w32(PrimitiveOp::Mul, a, b)
11625    }
11626}
11627
11628impl RingOp<W32> for Add<W32> {
11629    type Operand = u32;
11630    #[inline]
11631    fn apply(a: u32, b: u32) -> u32 {
11632        const_ring_eval_w32(PrimitiveOp::Add, a, b)
11633    }
11634}
11635
11636impl RingOp<W32> for Sub<W32> {
11637    type Operand = u32;
11638    #[inline]
11639    fn apply(a: u32, b: u32) -> u32 {
11640        const_ring_eval_w32(PrimitiveOp::Sub, a, b)
11641    }
11642}
11643
11644impl RingOp<W32> for Xor<W32> {
11645    type Operand = u32;
11646    #[inline]
11647    fn apply(a: u32, b: u32) -> u32 {
11648        const_ring_eval_w32(PrimitiveOp::Xor, a, b)
11649    }
11650}
11651
11652impl RingOp<W32> for And<W32> {
11653    type Operand = u32;
11654    #[inline]
11655    fn apply(a: u32, b: u32) -> u32 {
11656        const_ring_eval_w32(PrimitiveOp::And, a, b)
11657    }
11658}
11659
11660impl RingOp<W32> for Or<W32> {
11661    type Operand = u32;
11662    #[inline]
11663    fn apply(a: u32, b: u32) -> u32 {
11664        const_ring_eval_w32(PrimitiveOp::Or, a, b)
11665    }
11666}
11667
11668impl RingOp<W40> for Mul<W40> {
11669    type Operand = u64;
11670    #[inline]
11671    fn apply(a: u64, b: u64) -> u64 {
11672        const_ring_eval_w40(PrimitiveOp::Mul, a, b)
11673    }
11674}
11675
11676impl RingOp<W40> for Add<W40> {
11677    type Operand = u64;
11678    #[inline]
11679    fn apply(a: u64, b: u64) -> u64 {
11680        const_ring_eval_w40(PrimitiveOp::Add, a, b)
11681    }
11682}
11683
11684impl RingOp<W40> for Sub<W40> {
11685    type Operand = u64;
11686    #[inline]
11687    fn apply(a: u64, b: u64) -> u64 {
11688        const_ring_eval_w40(PrimitiveOp::Sub, a, b)
11689    }
11690}
11691
11692impl RingOp<W40> for Xor<W40> {
11693    type Operand = u64;
11694    #[inline]
11695    fn apply(a: u64, b: u64) -> u64 {
11696        const_ring_eval_w40(PrimitiveOp::Xor, a, b)
11697    }
11698}
11699
11700impl RingOp<W40> for And<W40> {
11701    type Operand = u64;
11702    #[inline]
11703    fn apply(a: u64, b: u64) -> u64 {
11704        const_ring_eval_w40(PrimitiveOp::And, a, b)
11705    }
11706}
11707
11708impl RingOp<W40> for Or<W40> {
11709    type Operand = u64;
11710    #[inline]
11711    fn apply(a: u64, b: u64) -> u64 {
11712        const_ring_eval_w40(PrimitiveOp::Or, a, b)
11713    }
11714}
11715
11716impl RingOp<W48> for Mul<W48> {
11717    type Operand = u64;
11718    #[inline]
11719    fn apply(a: u64, b: u64) -> u64 {
11720        const_ring_eval_w48(PrimitiveOp::Mul, a, b)
11721    }
11722}
11723
11724impl RingOp<W48> for Add<W48> {
11725    type Operand = u64;
11726    #[inline]
11727    fn apply(a: u64, b: u64) -> u64 {
11728        const_ring_eval_w48(PrimitiveOp::Add, a, b)
11729    }
11730}
11731
11732impl RingOp<W48> for Sub<W48> {
11733    type Operand = u64;
11734    #[inline]
11735    fn apply(a: u64, b: u64) -> u64 {
11736        const_ring_eval_w48(PrimitiveOp::Sub, a, b)
11737    }
11738}
11739
11740impl RingOp<W48> for Xor<W48> {
11741    type Operand = u64;
11742    #[inline]
11743    fn apply(a: u64, b: u64) -> u64 {
11744        const_ring_eval_w48(PrimitiveOp::Xor, a, b)
11745    }
11746}
11747
11748impl RingOp<W48> for And<W48> {
11749    type Operand = u64;
11750    #[inline]
11751    fn apply(a: u64, b: u64) -> u64 {
11752        const_ring_eval_w48(PrimitiveOp::And, a, b)
11753    }
11754}
11755
11756impl RingOp<W48> for Or<W48> {
11757    type Operand = u64;
11758    #[inline]
11759    fn apply(a: u64, b: u64) -> u64 {
11760        const_ring_eval_w48(PrimitiveOp::Or, a, b)
11761    }
11762}
11763
11764impl RingOp<W56> for Mul<W56> {
11765    type Operand = u64;
11766    #[inline]
11767    fn apply(a: u64, b: u64) -> u64 {
11768        const_ring_eval_w56(PrimitiveOp::Mul, a, b)
11769    }
11770}
11771
11772impl RingOp<W56> for Add<W56> {
11773    type Operand = u64;
11774    #[inline]
11775    fn apply(a: u64, b: u64) -> u64 {
11776        const_ring_eval_w56(PrimitiveOp::Add, a, b)
11777    }
11778}
11779
11780impl RingOp<W56> for Sub<W56> {
11781    type Operand = u64;
11782    #[inline]
11783    fn apply(a: u64, b: u64) -> u64 {
11784        const_ring_eval_w56(PrimitiveOp::Sub, a, b)
11785    }
11786}
11787
11788impl RingOp<W56> for Xor<W56> {
11789    type Operand = u64;
11790    #[inline]
11791    fn apply(a: u64, b: u64) -> u64 {
11792        const_ring_eval_w56(PrimitiveOp::Xor, a, b)
11793    }
11794}
11795
11796impl RingOp<W56> for And<W56> {
11797    type Operand = u64;
11798    #[inline]
11799    fn apply(a: u64, b: u64) -> u64 {
11800        const_ring_eval_w56(PrimitiveOp::And, a, b)
11801    }
11802}
11803
11804impl RingOp<W56> for Or<W56> {
11805    type Operand = u64;
11806    #[inline]
11807    fn apply(a: u64, b: u64) -> u64 {
11808        const_ring_eval_w56(PrimitiveOp::Or, a, b)
11809    }
11810}
11811
11812impl RingOp<W64> for Mul<W64> {
11813    type Operand = u64;
11814    #[inline]
11815    fn apply(a: u64, b: u64) -> u64 {
11816        const_ring_eval_w64(PrimitiveOp::Mul, a, b)
11817    }
11818}
11819
11820impl RingOp<W64> for Add<W64> {
11821    type Operand = u64;
11822    #[inline]
11823    fn apply(a: u64, b: u64) -> u64 {
11824        const_ring_eval_w64(PrimitiveOp::Add, a, b)
11825    }
11826}
11827
11828impl RingOp<W64> for Sub<W64> {
11829    type Operand = u64;
11830    #[inline]
11831    fn apply(a: u64, b: u64) -> u64 {
11832        const_ring_eval_w64(PrimitiveOp::Sub, a, b)
11833    }
11834}
11835
11836impl RingOp<W64> for Xor<W64> {
11837    type Operand = u64;
11838    #[inline]
11839    fn apply(a: u64, b: u64) -> u64 {
11840        const_ring_eval_w64(PrimitiveOp::Xor, a, b)
11841    }
11842}
11843
11844impl RingOp<W64> for And<W64> {
11845    type Operand = u64;
11846    #[inline]
11847    fn apply(a: u64, b: u64) -> u64 {
11848        const_ring_eval_w64(PrimitiveOp::And, a, b)
11849    }
11850}
11851
11852impl RingOp<W64> for Or<W64> {
11853    type Operand = u64;
11854    #[inline]
11855    fn apply(a: u64, b: u64) -> u64 {
11856        const_ring_eval_w64(PrimitiveOp::Or, a, b)
11857    }
11858}
11859
11860impl RingOp<W72> for Mul<W72> {
11861    type Operand = u128;
11862    #[inline]
11863    fn apply(a: u128, b: u128) -> u128 {
11864        const_ring_eval_w72(PrimitiveOp::Mul, a, b)
11865    }
11866}
11867
11868impl RingOp<W72> for Add<W72> {
11869    type Operand = u128;
11870    #[inline]
11871    fn apply(a: u128, b: u128) -> u128 {
11872        const_ring_eval_w72(PrimitiveOp::Add, a, b)
11873    }
11874}
11875
11876impl RingOp<W72> for Sub<W72> {
11877    type Operand = u128;
11878    #[inline]
11879    fn apply(a: u128, b: u128) -> u128 {
11880        const_ring_eval_w72(PrimitiveOp::Sub, a, b)
11881    }
11882}
11883
11884impl RingOp<W72> for Xor<W72> {
11885    type Operand = u128;
11886    #[inline]
11887    fn apply(a: u128, b: u128) -> u128 {
11888        const_ring_eval_w72(PrimitiveOp::Xor, a, b)
11889    }
11890}
11891
11892impl RingOp<W72> for And<W72> {
11893    type Operand = u128;
11894    #[inline]
11895    fn apply(a: u128, b: u128) -> u128 {
11896        const_ring_eval_w72(PrimitiveOp::And, a, b)
11897    }
11898}
11899
11900impl RingOp<W72> for Or<W72> {
11901    type Operand = u128;
11902    #[inline]
11903    fn apply(a: u128, b: u128) -> u128 {
11904        const_ring_eval_w72(PrimitiveOp::Or, a, b)
11905    }
11906}
11907
11908impl RingOp<W80> for Mul<W80> {
11909    type Operand = u128;
11910    #[inline]
11911    fn apply(a: u128, b: u128) -> u128 {
11912        const_ring_eval_w80(PrimitiveOp::Mul, a, b)
11913    }
11914}
11915
11916impl RingOp<W80> for Add<W80> {
11917    type Operand = u128;
11918    #[inline]
11919    fn apply(a: u128, b: u128) -> u128 {
11920        const_ring_eval_w80(PrimitiveOp::Add, a, b)
11921    }
11922}
11923
11924impl RingOp<W80> for Sub<W80> {
11925    type Operand = u128;
11926    #[inline]
11927    fn apply(a: u128, b: u128) -> u128 {
11928        const_ring_eval_w80(PrimitiveOp::Sub, a, b)
11929    }
11930}
11931
11932impl RingOp<W80> for Xor<W80> {
11933    type Operand = u128;
11934    #[inline]
11935    fn apply(a: u128, b: u128) -> u128 {
11936        const_ring_eval_w80(PrimitiveOp::Xor, a, b)
11937    }
11938}
11939
11940impl RingOp<W80> for And<W80> {
11941    type Operand = u128;
11942    #[inline]
11943    fn apply(a: u128, b: u128) -> u128 {
11944        const_ring_eval_w80(PrimitiveOp::And, a, b)
11945    }
11946}
11947
11948impl RingOp<W80> for Or<W80> {
11949    type Operand = u128;
11950    #[inline]
11951    fn apply(a: u128, b: u128) -> u128 {
11952        const_ring_eval_w80(PrimitiveOp::Or, a, b)
11953    }
11954}
11955
11956impl RingOp<W88> for Mul<W88> {
11957    type Operand = u128;
11958    #[inline]
11959    fn apply(a: u128, b: u128) -> u128 {
11960        const_ring_eval_w88(PrimitiveOp::Mul, a, b)
11961    }
11962}
11963
11964impl RingOp<W88> for Add<W88> {
11965    type Operand = u128;
11966    #[inline]
11967    fn apply(a: u128, b: u128) -> u128 {
11968        const_ring_eval_w88(PrimitiveOp::Add, a, b)
11969    }
11970}
11971
11972impl RingOp<W88> for Sub<W88> {
11973    type Operand = u128;
11974    #[inline]
11975    fn apply(a: u128, b: u128) -> u128 {
11976        const_ring_eval_w88(PrimitiveOp::Sub, a, b)
11977    }
11978}
11979
11980impl RingOp<W88> for Xor<W88> {
11981    type Operand = u128;
11982    #[inline]
11983    fn apply(a: u128, b: u128) -> u128 {
11984        const_ring_eval_w88(PrimitiveOp::Xor, a, b)
11985    }
11986}
11987
11988impl RingOp<W88> for And<W88> {
11989    type Operand = u128;
11990    #[inline]
11991    fn apply(a: u128, b: u128) -> u128 {
11992        const_ring_eval_w88(PrimitiveOp::And, a, b)
11993    }
11994}
11995
11996impl RingOp<W88> for Or<W88> {
11997    type Operand = u128;
11998    #[inline]
11999    fn apply(a: u128, b: u128) -> u128 {
12000        const_ring_eval_w88(PrimitiveOp::Or, a, b)
12001    }
12002}
12003
12004impl RingOp<W96> for Mul<W96> {
12005    type Operand = u128;
12006    #[inline]
12007    fn apply(a: u128, b: u128) -> u128 {
12008        const_ring_eval_w96(PrimitiveOp::Mul, a, b)
12009    }
12010}
12011
12012impl RingOp<W96> for Add<W96> {
12013    type Operand = u128;
12014    #[inline]
12015    fn apply(a: u128, b: u128) -> u128 {
12016        const_ring_eval_w96(PrimitiveOp::Add, a, b)
12017    }
12018}
12019
12020impl RingOp<W96> for Sub<W96> {
12021    type Operand = u128;
12022    #[inline]
12023    fn apply(a: u128, b: u128) -> u128 {
12024        const_ring_eval_w96(PrimitiveOp::Sub, a, b)
12025    }
12026}
12027
12028impl RingOp<W96> for Xor<W96> {
12029    type Operand = u128;
12030    #[inline]
12031    fn apply(a: u128, b: u128) -> u128 {
12032        const_ring_eval_w96(PrimitiveOp::Xor, a, b)
12033    }
12034}
12035
12036impl RingOp<W96> for And<W96> {
12037    type Operand = u128;
12038    #[inline]
12039    fn apply(a: u128, b: u128) -> u128 {
12040        const_ring_eval_w96(PrimitiveOp::And, a, b)
12041    }
12042}
12043
12044impl RingOp<W96> for Or<W96> {
12045    type Operand = u128;
12046    #[inline]
12047    fn apply(a: u128, b: u128) -> u128 {
12048        const_ring_eval_w96(PrimitiveOp::Or, a, b)
12049    }
12050}
12051
12052impl RingOp<W104> for Mul<W104> {
12053    type Operand = u128;
12054    #[inline]
12055    fn apply(a: u128, b: u128) -> u128 {
12056        const_ring_eval_w104(PrimitiveOp::Mul, a, b)
12057    }
12058}
12059
12060impl RingOp<W104> for Add<W104> {
12061    type Operand = u128;
12062    #[inline]
12063    fn apply(a: u128, b: u128) -> u128 {
12064        const_ring_eval_w104(PrimitiveOp::Add, a, b)
12065    }
12066}
12067
12068impl RingOp<W104> for Sub<W104> {
12069    type Operand = u128;
12070    #[inline]
12071    fn apply(a: u128, b: u128) -> u128 {
12072        const_ring_eval_w104(PrimitiveOp::Sub, a, b)
12073    }
12074}
12075
12076impl RingOp<W104> for Xor<W104> {
12077    type Operand = u128;
12078    #[inline]
12079    fn apply(a: u128, b: u128) -> u128 {
12080        const_ring_eval_w104(PrimitiveOp::Xor, a, b)
12081    }
12082}
12083
12084impl RingOp<W104> for And<W104> {
12085    type Operand = u128;
12086    #[inline]
12087    fn apply(a: u128, b: u128) -> u128 {
12088        const_ring_eval_w104(PrimitiveOp::And, a, b)
12089    }
12090}
12091
12092impl RingOp<W104> for Or<W104> {
12093    type Operand = u128;
12094    #[inline]
12095    fn apply(a: u128, b: u128) -> u128 {
12096        const_ring_eval_w104(PrimitiveOp::Or, a, b)
12097    }
12098}
12099
12100impl RingOp<W112> for Mul<W112> {
12101    type Operand = u128;
12102    #[inline]
12103    fn apply(a: u128, b: u128) -> u128 {
12104        const_ring_eval_w112(PrimitiveOp::Mul, a, b)
12105    }
12106}
12107
12108impl RingOp<W112> for Add<W112> {
12109    type Operand = u128;
12110    #[inline]
12111    fn apply(a: u128, b: u128) -> u128 {
12112        const_ring_eval_w112(PrimitiveOp::Add, a, b)
12113    }
12114}
12115
12116impl RingOp<W112> for Sub<W112> {
12117    type Operand = u128;
12118    #[inline]
12119    fn apply(a: u128, b: u128) -> u128 {
12120        const_ring_eval_w112(PrimitiveOp::Sub, a, b)
12121    }
12122}
12123
12124impl RingOp<W112> for Xor<W112> {
12125    type Operand = u128;
12126    #[inline]
12127    fn apply(a: u128, b: u128) -> u128 {
12128        const_ring_eval_w112(PrimitiveOp::Xor, a, b)
12129    }
12130}
12131
12132impl RingOp<W112> for And<W112> {
12133    type Operand = u128;
12134    #[inline]
12135    fn apply(a: u128, b: u128) -> u128 {
12136        const_ring_eval_w112(PrimitiveOp::And, a, b)
12137    }
12138}
12139
12140impl RingOp<W112> for Or<W112> {
12141    type Operand = u128;
12142    #[inline]
12143    fn apply(a: u128, b: u128) -> u128 {
12144        const_ring_eval_w112(PrimitiveOp::Or, a, b)
12145    }
12146}
12147
12148impl RingOp<W120> for Mul<W120> {
12149    type Operand = u128;
12150    #[inline]
12151    fn apply(a: u128, b: u128) -> u128 {
12152        const_ring_eval_w120(PrimitiveOp::Mul, a, b)
12153    }
12154}
12155
12156impl RingOp<W120> for Add<W120> {
12157    type Operand = u128;
12158    #[inline]
12159    fn apply(a: u128, b: u128) -> u128 {
12160        const_ring_eval_w120(PrimitiveOp::Add, a, b)
12161    }
12162}
12163
12164impl RingOp<W120> for Sub<W120> {
12165    type Operand = u128;
12166    #[inline]
12167    fn apply(a: u128, b: u128) -> u128 {
12168        const_ring_eval_w120(PrimitiveOp::Sub, a, b)
12169    }
12170}
12171
12172impl RingOp<W120> for Xor<W120> {
12173    type Operand = u128;
12174    #[inline]
12175    fn apply(a: u128, b: u128) -> u128 {
12176        const_ring_eval_w120(PrimitiveOp::Xor, a, b)
12177    }
12178}
12179
12180impl RingOp<W120> for And<W120> {
12181    type Operand = u128;
12182    #[inline]
12183    fn apply(a: u128, b: u128) -> u128 {
12184        const_ring_eval_w120(PrimitiveOp::And, a, b)
12185    }
12186}
12187
12188impl RingOp<W120> for Or<W120> {
12189    type Operand = u128;
12190    #[inline]
12191    fn apply(a: u128, b: u128) -> u128 {
12192        const_ring_eval_w120(PrimitiveOp::Or, a, b)
12193    }
12194}
12195
12196impl RingOp<W128> for Mul<W128> {
12197    type Operand = u128;
12198    #[inline]
12199    fn apply(a: u128, b: u128) -> u128 {
12200        const_ring_eval_w128(PrimitiveOp::Mul, a, b)
12201    }
12202}
12203
12204impl RingOp<W128> for Add<W128> {
12205    type Operand = u128;
12206    #[inline]
12207    fn apply(a: u128, b: u128) -> u128 {
12208        const_ring_eval_w128(PrimitiveOp::Add, a, b)
12209    }
12210}
12211
12212impl RingOp<W128> for Sub<W128> {
12213    type Operand = u128;
12214    #[inline]
12215    fn apply(a: u128, b: u128) -> u128 {
12216        const_ring_eval_w128(PrimitiveOp::Sub, a, b)
12217    }
12218}
12219
12220impl RingOp<W128> for Xor<W128> {
12221    type Operand = u128;
12222    #[inline]
12223    fn apply(a: u128, b: u128) -> u128 {
12224        const_ring_eval_w128(PrimitiveOp::Xor, a, b)
12225    }
12226}
12227
12228impl RingOp<W128> for And<W128> {
12229    type Operand = u128;
12230    #[inline]
12231    fn apply(a: u128, b: u128) -> u128 {
12232        const_ring_eval_w128(PrimitiveOp::And, a, b)
12233    }
12234}
12235
12236impl RingOp<W128> for Or<W128> {
12237    type Operand = u128;
12238    #[inline]
12239    fn apply(a: u128, b: u128) -> u128 {
12240        const_ring_eval_w128(PrimitiveOp::Or, a, b)
12241    }
12242}
12243
12244impl UnaryRingOp<W8> for Neg<W8> {
12245    type Operand = u8;
12246    #[inline]
12247    fn apply(a: u8) -> u8 {
12248        const_ring_eval_w8(PrimitiveOp::Sub, 0, a)
12249    }
12250}
12251
12252impl UnaryRingOp<W8> for BNot<W8> {
12253    type Operand = u8;
12254    #[inline]
12255    fn apply(a: u8) -> u8 {
12256        const_ring_eval_w8(PrimitiveOp::Xor, a, u8::MAX)
12257    }
12258}
12259
12260impl UnaryRingOp<W8> for Succ<W8> {
12261    type Operand = u8;
12262    #[inline]
12263    fn apply(a: u8) -> u8 {
12264        <Neg<W8> as UnaryRingOp<W8>>::apply(<BNot<W8> as UnaryRingOp<W8>>::apply(a))
12265    }
12266}
12267
12268impl UnaryRingOp<W16> for Neg<W16> {
12269    type Operand = u16;
12270    #[inline]
12271    fn apply(a: u16) -> u16 {
12272        const_ring_eval_w16(PrimitiveOp::Sub, 0, a)
12273    }
12274}
12275
12276impl UnaryRingOp<W16> for BNot<W16> {
12277    type Operand = u16;
12278    #[inline]
12279    fn apply(a: u16) -> u16 {
12280        const_ring_eval_w16(PrimitiveOp::Xor, a, u16::MAX)
12281    }
12282}
12283
12284impl UnaryRingOp<W16> for Succ<W16> {
12285    type Operand = u16;
12286    #[inline]
12287    fn apply(a: u16) -> u16 {
12288        <Neg<W16> as UnaryRingOp<W16>>::apply(<BNot<W16> as UnaryRingOp<W16>>::apply(a))
12289    }
12290}
12291
12292impl UnaryRingOp<W24> for Neg<W24> {
12293    type Operand = u32;
12294    #[inline]
12295    fn apply(a: u32) -> u32 {
12296        const_ring_eval_w24(PrimitiveOp::Sub, 0, a)
12297    }
12298}
12299
12300impl UnaryRingOp<W24> for BNot<W24> {
12301    type Operand = u32;
12302    #[inline]
12303    fn apply(a: u32) -> u32 {
12304        const_ring_eval_w24(PrimitiveOp::Xor, a, 0x00FF_FFFFu32)
12305    }
12306}
12307
12308impl UnaryRingOp<W24> for Succ<W24> {
12309    type Operand = u32;
12310    #[inline]
12311    fn apply(a: u32) -> u32 {
12312        <Neg<W24> as UnaryRingOp<W24>>::apply(<BNot<W24> as UnaryRingOp<W24>>::apply(a))
12313    }
12314}
12315
12316impl UnaryRingOp<W32> for Neg<W32> {
12317    type Operand = u32;
12318    #[inline]
12319    fn apply(a: u32) -> u32 {
12320        const_ring_eval_w32(PrimitiveOp::Sub, 0, a)
12321    }
12322}
12323
12324impl UnaryRingOp<W32> for BNot<W32> {
12325    type Operand = u32;
12326    #[inline]
12327    fn apply(a: u32) -> u32 {
12328        const_ring_eval_w32(PrimitiveOp::Xor, a, u32::MAX)
12329    }
12330}
12331
12332impl UnaryRingOp<W32> for Succ<W32> {
12333    type Operand = u32;
12334    #[inline]
12335    fn apply(a: u32) -> u32 {
12336        <Neg<W32> as UnaryRingOp<W32>>::apply(<BNot<W32> as UnaryRingOp<W32>>::apply(a))
12337    }
12338}
12339
12340impl UnaryRingOp<W40> for Neg<W40> {
12341    type Operand = u64;
12342    #[inline]
12343    fn apply(a: u64) -> u64 {
12344        const_ring_eval_w40(PrimitiveOp::Sub, 0, a)
12345    }
12346}
12347
12348impl UnaryRingOp<W40> for BNot<W40> {
12349    type Operand = u64;
12350    #[inline]
12351    fn apply(a: u64) -> u64 {
12352        const_ring_eval_w40(PrimitiveOp::Xor, a, 0x0000_00FF_FFFF_FFFFu64)
12353    }
12354}
12355
12356impl UnaryRingOp<W40> for Succ<W40> {
12357    type Operand = u64;
12358    #[inline]
12359    fn apply(a: u64) -> u64 {
12360        <Neg<W40> as UnaryRingOp<W40>>::apply(<BNot<W40> as UnaryRingOp<W40>>::apply(a))
12361    }
12362}
12363
12364impl UnaryRingOp<W48> for Neg<W48> {
12365    type Operand = u64;
12366    #[inline]
12367    fn apply(a: u64) -> u64 {
12368        const_ring_eval_w48(PrimitiveOp::Sub, 0, a)
12369    }
12370}
12371
12372impl UnaryRingOp<W48> for BNot<W48> {
12373    type Operand = u64;
12374    #[inline]
12375    fn apply(a: u64) -> u64 {
12376        const_ring_eval_w48(PrimitiveOp::Xor, a, 0x0000_FFFF_FFFF_FFFFu64)
12377    }
12378}
12379
12380impl UnaryRingOp<W48> for Succ<W48> {
12381    type Operand = u64;
12382    #[inline]
12383    fn apply(a: u64) -> u64 {
12384        <Neg<W48> as UnaryRingOp<W48>>::apply(<BNot<W48> as UnaryRingOp<W48>>::apply(a))
12385    }
12386}
12387
12388impl UnaryRingOp<W56> for Neg<W56> {
12389    type Operand = u64;
12390    #[inline]
12391    fn apply(a: u64) -> u64 {
12392        const_ring_eval_w56(PrimitiveOp::Sub, 0, a)
12393    }
12394}
12395
12396impl UnaryRingOp<W56> for BNot<W56> {
12397    type Operand = u64;
12398    #[inline]
12399    fn apply(a: u64) -> u64 {
12400        const_ring_eval_w56(PrimitiveOp::Xor, a, 0x00FF_FFFF_FFFF_FFFFu64)
12401    }
12402}
12403
12404impl UnaryRingOp<W56> for Succ<W56> {
12405    type Operand = u64;
12406    #[inline]
12407    fn apply(a: u64) -> u64 {
12408        <Neg<W56> as UnaryRingOp<W56>>::apply(<BNot<W56> as UnaryRingOp<W56>>::apply(a))
12409    }
12410}
12411
12412impl UnaryRingOp<W64> for Neg<W64> {
12413    type Operand = u64;
12414    #[inline]
12415    fn apply(a: u64) -> u64 {
12416        const_ring_eval_w64(PrimitiveOp::Sub, 0, a)
12417    }
12418}
12419
12420impl UnaryRingOp<W64> for BNot<W64> {
12421    type Operand = u64;
12422    #[inline]
12423    fn apply(a: u64) -> u64 {
12424        const_ring_eval_w64(PrimitiveOp::Xor, a, u64::MAX)
12425    }
12426}
12427
12428impl UnaryRingOp<W64> for Succ<W64> {
12429    type Operand = u64;
12430    #[inline]
12431    fn apply(a: u64) -> u64 {
12432        <Neg<W64> as UnaryRingOp<W64>>::apply(<BNot<W64> as UnaryRingOp<W64>>::apply(a))
12433    }
12434}
12435
12436impl UnaryRingOp<W72> for Neg<W72> {
12437    type Operand = u128;
12438    #[inline]
12439    fn apply(a: u128) -> u128 {
12440        const_ring_eval_w72(PrimitiveOp::Sub, 0, a)
12441    }
12442}
12443
12444impl UnaryRingOp<W72> for BNot<W72> {
12445    type Operand = u128;
12446    #[inline]
12447    fn apply(a: u128) -> u128 {
12448        const_ring_eval_w72(PrimitiveOp::Xor, a, u128::MAX >> (128 - 72))
12449    }
12450}
12451
12452impl UnaryRingOp<W72> for Succ<W72> {
12453    type Operand = u128;
12454    #[inline]
12455    fn apply(a: u128) -> u128 {
12456        <Neg<W72> as UnaryRingOp<W72>>::apply(<BNot<W72> as UnaryRingOp<W72>>::apply(a))
12457    }
12458}
12459
12460impl UnaryRingOp<W80> for Neg<W80> {
12461    type Operand = u128;
12462    #[inline]
12463    fn apply(a: u128) -> u128 {
12464        const_ring_eval_w80(PrimitiveOp::Sub, 0, a)
12465    }
12466}
12467
12468impl UnaryRingOp<W80> for BNot<W80> {
12469    type Operand = u128;
12470    #[inline]
12471    fn apply(a: u128) -> u128 {
12472        const_ring_eval_w80(PrimitiveOp::Xor, a, u128::MAX >> (128 - 80))
12473    }
12474}
12475
12476impl UnaryRingOp<W80> for Succ<W80> {
12477    type Operand = u128;
12478    #[inline]
12479    fn apply(a: u128) -> u128 {
12480        <Neg<W80> as UnaryRingOp<W80>>::apply(<BNot<W80> as UnaryRingOp<W80>>::apply(a))
12481    }
12482}
12483
12484impl UnaryRingOp<W88> for Neg<W88> {
12485    type Operand = u128;
12486    #[inline]
12487    fn apply(a: u128) -> u128 {
12488        const_ring_eval_w88(PrimitiveOp::Sub, 0, a)
12489    }
12490}
12491
12492impl UnaryRingOp<W88> for BNot<W88> {
12493    type Operand = u128;
12494    #[inline]
12495    fn apply(a: u128) -> u128 {
12496        const_ring_eval_w88(PrimitiveOp::Xor, a, u128::MAX >> (128 - 88))
12497    }
12498}
12499
12500impl UnaryRingOp<W88> for Succ<W88> {
12501    type Operand = u128;
12502    #[inline]
12503    fn apply(a: u128) -> u128 {
12504        <Neg<W88> as UnaryRingOp<W88>>::apply(<BNot<W88> as UnaryRingOp<W88>>::apply(a))
12505    }
12506}
12507
12508impl UnaryRingOp<W96> for Neg<W96> {
12509    type Operand = u128;
12510    #[inline]
12511    fn apply(a: u128) -> u128 {
12512        const_ring_eval_w96(PrimitiveOp::Sub, 0, a)
12513    }
12514}
12515
12516impl UnaryRingOp<W96> for BNot<W96> {
12517    type Operand = u128;
12518    #[inline]
12519    fn apply(a: u128) -> u128 {
12520        const_ring_eval_w96(PrimitiveOp::Xor, a, u128::MAX >> (128 - 96))
12521    }
12522}
12523
12524impl UnaryRingOp<W96> for Succ<W96> {
12525    type Operand = u128;
12526    #[inline]
12527    fn apply(a: u128) -> u128 {
12528        <Neg<W96> as UnaryRingOp<W96>>::apply(<BNot<W96> as UnaryRingOp<W96>>::apply(a))
12529    }
12530}
12531
12532impl UnaryRingOp<W104> for Neg<W104> {
12533    type Operand = u128;
12534    #[inline]
12535    fn apply(a: u128) -> u128 {
12536        const_ring_eval_w104(PrimitiveOp::Sub, 0, a)
12537    }
12538}
12539
12540impl UnaryRingOp<W104> for BNot<W104> {
12541    type Operand = u128;
12542    #[inline]
12543    fn apply(a: u128) -> u128 {
12544        const_ring_eval_w104(PrimitiveOp::Xor, a, u128::MAX >> (128 - 104))
12545    }
12546}
12547
12548impl UnaryRingOp<W104> for Succ<W104> {
12549    type Operand = u128;
12550    #[inline]
12551    fn apply(a: u128) -> u128 {
12552        <Neg<W104> as UnaryRingOp<W104>>::apply(<BNot<W104> as UnaryRingOp<W104>>::apply(a))
12553    }
12554}
12555
12556impl UnaryRingOp<W112> for Neg<W112> {
12557    type Operand = u128;
12558    #[inline]
12559    fn apply(a: u128) -> u128 {
12560        const_ring_eval_w112(PrimitiveOp::Sub, 0, a)
12561    }
12562}
12563
12564impl UnaryRingOp<W112> for BNot<W112> {
12565    type Operand = u128;
12566    #[inline]
12567    fn apply(a: u128) -> u128 {
12568        const_ring_eval_w112(PrimitiveOp::Xor, a, u128::MAX >> (128 - 112))
12569    }
12570}
12571
12572impl UnaryRingOp<W112> for Succ<W112> {
12573    type Operand = u128;
12574    #[inline]
12575    fn apply(a: u128) -> u128 {
12576        <Neg<W112> as UnaryRingOp<W112>>::apply(<BNot<W112> as UnaryRingOp<W112>>::apply(a))
12577    }
12578}
12579
12580impl UnaryRingOp<W120> for Neg<W120> {
12581    type Operand = u128;
12582    #[inline]
12583    fn apply(a: u128) -> u128 {
12584        const_ring_eval_w120(PrimitiveOp::Sub, 0, a)
12585    }
12586}
12587
12588impl UnaryRingOp<W120> for BNot<W120> {
12589    type Operand = u128;
12590    #[inline]
12591    fn apply(a: u128) -> u128 {
12592        const_ring_eval_w120(PrimitiveOp::Xor, a, u128::MAX >> (128 - 120))
12593    }
12594}
12595
12596impl UnaryRingOp<W120> for Succ<W120> {
12597    type Operand = u128;
12598    #[inline]
12599    fn apply(a: u128) -> u128 {
12600        <Neg<W120> as UnaryRingOp<W120>>::apply(<BNot<W120> as UnaryRingOp<W120>>::apply(a))
12601    }
12602}
12603
12604impl UnaryRingOp<W128> for Neg<W128> {
12605    type Operand = u128;
12606    #[inline]
12607    fn apply(a: u128) -> u128 {
12608        const_ring_eval_w128(PrimitiveOp::Sub, 0, a)
12609    }
12610}
12611
12612impl UnaryRingOp<W128> for BNot<W128> {
12613    type Operand = u128;
12614    #[inline]
12615    fn apply(a: u128) -> u128 {
12616        const_ring_eval_w128(PrimitiveOp::Xor, a, u128::MAX)
12617    }
12618}
12619
12620impl UnaryRingOp<W128> for Succ<W128> {
12621    type Operand = u128;
12622    #[inline]
12623    fn apply(a: u128) -> u128 {
12624        <Neg<W128> as UnaryRingOp<W128>>::apply(<BNot<W128> as UnaryRingOp<W128>>::apply(a))
12625    }
12626}
12627
12628/// Sealed marker for well-formed level embedding pairs (`(From, To)` with
12629/// `From <= To`). v0.2.2 W3.
12630pub trait ValidLevelEmbedding: valid_level_embedding_sealed::Sealed {}
12631
12632mod valid_level_embedding_sealed {
12633    /// Private supertrait. Not implementable outside this crate.
12634    pub trait Sealed {}
12635    impl Sealed for (super::W8, super::W8) {}
12636    impl Sealed for (super::W8, super::W16) {}
12637    impl Sealed for (super::W8, super::W24) {}
12638    impl Sealed for (super::W8, super::W32) {}
12639    impl Sealed for (super::W8, super::W40) {}
12640    impl Sealed for (super::W8, super::W48) {}
12641    impl Sealed for (super::W8, super::W56) {}
12642    impl Sealed for (super::W8, super::W64) {}
12643    impl Sealed for (super::W8, super::W72) {}
12644    impl Sealed for (super::W8, super::W80) {}
12645    impl Sealed for (super::W8, super::W88) {}
12646    impl Sealed for (super::W8, super::W96) {}
12647    impl Sealed for (super::W8, super::W104) {}
12648    impl Sealed for (super::W8, super::W112) {}
12649    impl Sealed for (super::W8, super::W120) {}
12650    impl Sealed for (super::W8, super::W128) {}
12651    impl Sealed for (super::W16, super::W16) {}
12652    impl Sealed for (super::W16, super::W24) {}
12653    impl Sealed for (super::W16, super::W32) {}
12654    impl Sealed for (super::W16, super::W40) {}
12655    impl Sealed for (super::W16, super::W48) {}
12656    impl Sealed for (super::W16, super::W56) {}
12657    impl Sealed for (super::W16, super::W64) {}
12658    impl Sealed for (super::W16, super::W72) {}
12659    impl Sealed for (super::W16, super::W80) {}
12660    impl Sealed for (super::W16, super::W88) {}
12661    impl Sealed for (super::W16, super::W96) {}
12662    impl Sealed for (super::W16, super::W104) {}
12663    impl Sealed for (super::W16, super::W112) {}
12664    impl Sealed for (super::W16, super::W120) {}
12665    impl Sealed for (super::W16, super::W128) {}
12666    impl Sealed for (super::W24, super::W24) {}
12667    impl Sealed for (super::W24, super::W32) {}
12668    impl Sealed for (super::W24, super::W40) {}
12669    impl Sealed for (super::W24, super::W48) {}
12670    impl Sealed for (super::W24, super::W56) {}
12671    impl Sealed for (super::W24, super::W64) {}
12672    impl Sealed for (super::W24, super::W72) {}
12673    impl Sealed for (super::W24, super::W80) {}
12674    impl Sealed for (super::W24, super::W88) {}
12675    impl Sealed for (super::W24, super::W96) {}
12676    impl Sealed for (super::W24, super::W104) {}
12677    impl Sealed for (super::W24, super::W112) {}
12678    impl Sealed for (super::W24, super::W120) {}
12679    impl Sealed for (super::W24, super::W128) {}
12680    impl Sealed for (super::W32, super::W32) {}
12681    impl Sealed for (super::W32, super::W40) {}
12682    impl Sealed for (super::W32, super::W48) {}
12683    impl Sealed for (super::W32, super::W56) {}
12684    impl Sealed for (super::W32, super::W64) {}
12685    impl Sealed for (super::W32, super::W72) {}
12686    impl Sealed for (super::W32, super::W80) {}
12687    impl Sealed for (super::W32, super::W88) {}
12688    impl Sealed for (super::W32, super::W96) {}
12689    impl Sealed for (super::W32, super::W104) {}
12690    impl Sealed for (super::W32, super::W112) {}
12691    impl Sealed for (super::W32, super::W120) {}
12692    impl Sealed for (super::W32, super::W128) {}
12693    impl Sealed for (super::W40, super::W40) {}
12694    impl Sealed for (super::W40, super::W48) {}
12695    impl Sealed for (super::W40, super::W56) {}
12696    impl Sealed for (super::W40, super::W64) {}
12697    impl Sealed for (super::W40, super::W72) {}
12698    impl Sealed for (super::W40, super::W80) {}
12699    impl Sealed for (super::W40, super::W88) {}
12700    impl Sealed for (super::W40, super::W96) {}
12701    impl Sealed for (super::W40, super::W104) {}
12702    impl Sealed for (super::W40, super::W112) {}
12703    impl Sealed for (super::W40, super::W120) {}
12704    impl Sealed for (super::W40, super::W128) {}
12705    impl Sealed for (super::W48, super::W48) {}
12706    impl Sealed for (super::W48, super::W56) {}
12707    impl Sealed for (super::W48, super::W64) {}
12708    impl Sealed for (super::W48, super::W72) {}
12709    impl Sealed for (super::W48, super::W80) {}
12710    impl Sealed for (super::W48, super::W88) {}
12711    impl Sealed for (super::W48, super::W96) {}
12712    impl Sealed for (super::W48, super::W104) {}
12713    impl Sealed for (super::W48, super::W112) {}
12714    impl Sealed for (super::W48, super::W120) {}
12715    impl Sealed for (super::W48, super::W128) {}
12716    impl Sealed for (super::W56, super::W56) {}
12717    impl Sealed for (super::W56, super::W64) {}
12718    impl Sealed for (super::W56, super::W72) {}
12719    impl Sealed for (super::W56, super::W80) {}
12720    impl Sealed for (super::W56, super::W88) {}
12721    impl Sealed for (super::W56, super::W96) {}
12722    impl Sealed for (super::W56, super::W104) {}
12723    impl Sealed for (super::W56, super::W112) {}
12724    impl Sealed for (super::W56, super::W120) {}
12725    impl Sealed for (super::W56, super::W128) {}
12726    impl Sealed for (super::W64, super::W64) {}
12727    impl Sealed for (super::W64, super::W72) {}
12728    impl Sealed for (super::W64, super::W80) {}
12729    impl Sealed for (super::W64, super::W88) {}
12730    impl Sealed for (super::W64, super::W96) {}
12731    impl Sealed for (super::W64, super::W104) {}
12732    impl Sealed for (super::W64, super::W112) {}
12733    impl Sealed for (super::W64, super::W120) {}
12734    impl Sealed for (super::W64, super::W128) {}
12735    impl Sealed for (super::W72, super::W72) {}
12736    impl Sealed for (super::W72, super::W80) {}
12737    impl Sealed for (super::W72, super::W88) {}
12738    impl Sealed for (super::W72, super::W96) {}
12739    impl Sealed for (super::W72, super::W104) {}
12740    impl Sealed for (super::W72, super::W112) {}
12741    impl Sealed for (super::W72, super::W120) {}
12742    impl Sealed for (super::W72, super::W128) {}
12743    impl Sealed for (super::W80, super::W80) {}
12744    impl Sealed for (super::W80, super::W88) {}
12745    impl Sealed for (super::W80, super::W96) {}
12746    impl Sealed for (super::W80, super::W104) {}
12747    impl Sealed for (super::W80, super::W112) {}
12748    impl Sealed for (super::W80, super::W120) {}
12749    impl Sealed for (super::W80, super::W128) {}
12750    impl Sealed for (super::W88, super::W88) {}
12751    impl Sealed for (super::W88, super::W96) {}
12752    impl Sealed for (super::W88, super::W104) {}
12753    impl Sealed for (super::W88, super::W112) {}
12754    impl Sealed for (super::W88, super::W120) {}
12755    impl Sealed for (super::W88, super::W128) {}
12756    impl Sealed for (super::W96, super::W96) {}
12757    impl Sealed for (super::W96, super::W104) {}
12758    impl Sealed for (super::W96, super::W112) {}
12759    impl Sealed for (super::W96, super::W120) {}
12760    impl Sealed for (super::W96, super::W128) {}
12761    impl Sealed for (super::W104, super::W104) {}
12762    impl Sealed for (super::W104, super::W112) {}
12763    impl Sealed for (super::W104, super::W120) {}
12764    impl Sealed for (super::W104, super::W128) {}
12765    impl Sealed for (super::W112, super::W112) {}
12766    impl Sealed for (super::W112, super::W120) {}
12767    impl Sealed for (super::W112, super::W128) {}
12768    impl Sealed for (super::W120, super::W120) {}
12769    impl Sealed for (super::W120, super::W128) {}
12770    impl Sealed for (super::W128, super::W128) {}
12771}
12772
12773impl ValidLevelEmbedding for (W8, W8) {}
12774impl ValidLevelEmbedding for (W8, W16) {}
12775impl ValidLevelEmbedding for (W8, W24) {}
12776impl ValidLevelEmbedding for (W8, W32) {}
12777impl ValidLevelEmbedding for (W8, W40) {}
12778impl ValidLevelEmbedding for (W8, W48) {}
12779impl ValidLevelEmbedding for (W8, W56) {}
12780impl ValidLevelEmbedding for (W8, W64) {}
12781impl ValidLevelEmbedding for (W8, W72) {}
12782impl ValidLevelEmbedding for (W8, W80) {}
12783impl ValidLevelEmbedding for (W8, W88) {}
12784impl ValidLevelEmbedding for (W8, W96) {}
12785impl ValidLevelEmbedding for (W8, W104) {}
12786impl ValidLevelEmbedding for (W8, W112) {}
12787impl ValidLevelEmbedding for (W8, W120) {}
12788impl ValidLevelEmbedding for (W8, W128) {}
12789impl ValidLevelEmbedding for (W16, W16) {}
12790impl ValidLevelEmbedding for (W16, W24) {}
12791impl ValidLevelEmbedding for (W16, W32) {}
12792impl ValidLevelEmbedding for (W16, W40) {}
12793impl ValidLevelEmbedding for (W16, W48) {}
12794impl ValidLevelEmbedding for (W16, W56) {}
12795impl ValidLevelEmbedding for (W16, W64) {}
12796impl ValidLevelEmbedding for (W16, W72) {}
12797impl ValidLevelEmbedding for (W16, W80) {}
12798impl ValidLevelEmbedding for (W16, W88) {}
12799impl ValidLevelEmbedding for (W16, W96) {}
12800impl ValidLevelEmbedding for (W16, W104) {}
12801impl ValidLevelEmbedding for (W16, W112) {}
12802impl ValidLevelEmbedding for (W16, W120) {}
12803impl ValidLevelEmbedding for (W16, W128) {}
12804impl ValidLevelEmbedding for (W24, W24) {}
12805impl ValidLevelEmbedding for (W24, W32) {}
12806impl ValidLevelEmbedding for (W24, W40) {}
12807impl ValidLevelEmbedding for (W24, W48) {}
12808impl ValidLevelEmbedding for (W24, W56) {}
12809impl ValidLevelEmbedding for (W24, W64) {}
12810impl ValidLevelEmbedding for (W24, W72) {}
12811impl ValidLevelEmbedding for (W24, W80) {}
12812impl ValidLevelEmbedding for (W24, W88) {}
12813impl ValidLevelEmbedding for (W24, W96) {}
12814impl ValidLevelEmbedding for (W24, W104) {}
12815impl ValidLevelEmbedding for (W24, W112) {}
12816impl ValidLevelEmbedding for (W24, W120) {}
12817impl ValidLevelEmbedding for (W24, W128) {}
12818impl ValidLevelEmbedding for (W32, W32) {}
12819impl ValidLevelEmbedding for (W32, W40) {}
12820impl ValidLevelEmbedding for (W32, W48) {}
12821impl ValidLevelEmbedding for (W32, W56) {}
12822impl ValidLevelEmbedding for (W32, W64) {}
12823impl ValidLevelEmbedding for (W32, W72) {}
12824impl ValidLevelEmbedding for (W32, W80) {}
12825impl ValidLevelEmbedding for (W32, W88) {}
12826impl ValidLevelEmbedding for (W32, W96) {}
12827impl ValidLevelEmbedding for (W32, W104) {}
12828impl ValidLevelEmbedding for (W32, W112) {}
12829impl ValidLevelEmbedding for (W32, W120) {}
12830impl ValidLevelEmbedding for (W32, W128) {}
12831impl ValidLevelEmbedding for (W40, W40) {}
12832impl ValidLevelEmbedding for (W40, W48) {}
12833impl ValidLevelEmbedding for (W40, W56) {}
12834impl ValidLevelEmbedding for (W40, W64) {}
12835impl ValidLevelEmbedding for (W40, W72) {}
12836impl ValidLevelEmbedding for (W40, W80) {}
12837impl ValidLevelEmbedding for (W40, W88) {}
12838impl ValidLevelEmbedding for (W40, W96) {}
12839impl ValidLevelEmbedding for (W40, W104) {}
12840impl ValidLevelEmbedding for (W40, W112) {}
12841impl ValidLevelEmbedding for (W40, W120) {}
12842impl ValidLevelEmbedding for (W40, W128) {}
12843impl ValidLevelEmbedding for (W48, W48) {}
12844impl ValidLevelEmbedding for (W48, W56) {}
12845impl ValidLevelEmbedding for (W48, W64) {}
12846impl ValidLevelEmbedding for (W48, W72) {}
12847impl ValidLevelEmbedding for (W48, W80) {}
12848impl ValidLevelEmbedding for (W48, W88) {}
12849impl ValidLevelEmbedding for (W48, W96) {}
12850impl ValidLevelEmbedding for (W48, W104) {}
12851impl ValidLevelEmbedding for (W48, W112) {}
12852impl ValidLevelEmbedding for (W48, W120) {}
12853impl ValidLevelEmbedding for (W48, W128) {}
12854impl ValidLevelEmbedding for (W56, W56) {}
12855impl ValidLevelEmbedding for (W56, W64) {}
12856impl ValidLevelEmbedding for (W56, W72) {}
12857impl ValidLevelEmbedding for (W56, W80) {}
12858impl ValidLevelEmbedding for (W56, W88) {}
12859impl ValidLevelEmbedding for (W56, W96) {}
12860impl ValidLevelEmbedding for (W56, W104) {}
12861impl ValidLevelEmbedding for (W56, W112) {}
12862impl ValidLevelEmbedding for (W56, W120) {}
12863impl ValidLevelEmbedding for (W56, W128) {}
12864impl ValidLevelEmbedding for (W64, W64) {}
12865impl ValidLevelEmbedding for (W64, W72) {}
12866impl ValidLevelEmbedding for (W64, W80) {}
12867impl ValidLevelEmbedding for (W64, W88) {}
12868impl ValidLevelEmbedding for (W64, W96) {}
12869impl ValidLevelEmbedding for (W64, W104) {}
12870impl ValidLevelEmbedding for (W64, W112) {}
12871impl ValidLevelEmbedding for (W64, W120) {}
12872impl ValidLevelEmbedding for (W64, W128) {}
12873impl ValidLevelEmbedding for (W72, W72) {}
12874impl ValidLevelEmbedding for (W72, W80) {}
12875impl ValidLevelEmbedding for (W72, W88) {}
12876impl ValidLevelEmbedding for (W72, W96) {}
12877impl ValidLevelEmbedding for (W72, W104) {}
12878impl ValidLevelEmbedding for (W72, W112) {}
12879impl ValidLevelEmbedding for (W72, W120) {}
12880impl ValidLevelEmbedding for (W72, W128) {}
12881impl ValidLevelEmbedding for (W80, W80) {}
12882impl ValidLevelEmbedding for (W80, W88) {}
12883impl ValidLevelEmbedding for (W80, W96) {}
12884impl ValidLevelEmbedding for (W80, W104) {}
12885impl ValidLevelEmbedding for (W80, W112) {}
12886impl ValidLevelEmbedding for (W80, W120) {}
12887impl ValidLevelEmbedding for (W80, W128) {}
12888impl ValidLevelEmbedding for (W88, W88) {}
12889impl ValidLevelEmbedding for (W88, W96) {}
12890impl ValidLevelEmbedding for (W88, W104) {}
12891impl ValidLevelEmbedding for (W88, W112) {}
12892impl ValidLevelEmbedding for (W88, W120) {}
12893impl ValidLevelEmbedding for (W88, W128) {}
12894impl ValidLevelEmbedding for (W96, W96) {}
12895impl ValidLevelEmbedding for (W96, W104) {}
12896impl ValidLevelEmbedding for (W96, W112) {}
12897impl ValidLevelEmbedding for (W96, W120) {}
12898impl ValidLevelEmbedding for (W96, W128) {}
12899impl ValidLevelEmbedding for (W104, W104) {}
12900impl ValidLevelEmbedding for (W104, W112) {}
12901impl ValidLevelEmbedding for (W104, W120) {}
12902impl ValidLevelEmbedding for (W104, W128) {}
12903impl ValidLevelEmbedding for (W112, W112) {}
12904impl ValidLevelEmbedding for (W112, W120) {}
12905impl ValidLevelEmbedding for (W112, W128) {}
12906impl ValidLevelEmbedding for (W120, W120) {}
12907impl ValidLevelEmbedding for (W120, W128) {}
12908impl ValidLevelEmbedding for (W128, W128) {}
12909
12910/// v0.2.2 W3: phantom-typed level embedding `Embed<From, To>` for the
12911/// canonical injection ι : R_From → R_To when `From <= To`.
12912/// Implementations exist only for sealed `(From, To)` pairs in the
12913/// `ValidLevelEmbedding` trait, so attempting an unsupported direction
12914/// (e.g., `Embed<W32, W8>`) fails at compile time.
12915#[derive(Debug, Default, Clone, Copy)]
12916pub struct Embed<From, To>(PhantomData<(From, To)>);
12917
12918impl Embed<W8, W8> {
12919    /// Embed a `u8` value at W8 into a `u8` value at W8.
12920    #[inline]
12921    #[must_use]
12922    pub const fn apply(value: u8) -> u8 {
12923        value
12924    }
12925}
12926
12927impl Embed<W8, W16> {
12928    /// Embed a `u8` value at W8 into a `u16` value at W16.
12929    #[inline]
12930    #[must_use]
12931    pub const fn apply(value: u8) -> u16 {
12932        value as u16
12933    }
12934}
12935
12936impl Embed<W8, W24> {
12937    /// Embed a `u8` value at W8 into a `u32` value at W24.
12938    #[inline]
12939    #[must_use]
12940    pub const fn apply(value: u8) -> u32 {
12941        value as u32
12942    }
12943}
12944
12945impl Embed<W8, W32> {
12946    /// Embed a `u8` value at W8 into a `u32` value at W32.
12947    #[inline]
12948    #[must_use]
12949    pub const fn apply(value: u8) -> u32 {
12950        value as u32
12951    }
12952}
12953
12954impl Embed<W8, W40> {
12955    /// Embed a `u8` value at W8 into a `u64` value at W40.
12956    #[inline]
12957    #[must_use]
12958    pub const fn apply(value: u8) -> u64 {
12959        value as u64
12960    }
12961}
12962
12963impl Embed<W8, W48> {
12964    /// Embed a `u8` value at W8 into a `u64` value at W48.
12965    #[inline]
12966    #[must_use]
12967    pub const fn apply(value: u8) -> u64 {
12968        value as u64
12969    }
12970}
12971
12972impl Embed<W8, W56> {
12973    /// Embed a `u8` value at W8 into a `u64` value at W56.
12974    #[inline]
12975    #[must_use]
12976    pub const fn apply(value: u8) -> u64 {
12977        value as u64
12978    }
12979}
12980
12981impl Embed<W8, W64> {
12982    /// Embed a `u8` value at W8 into a `u64` value at W64.
12983    #[inline]
12984    #[must_use]
12985    pub const fn apply(value: u8) -> u64 {
12986        value as u64
12987    }
12988}
12989
12990impl Embed<W8, W72> {
12991    /// Embed a `u8` value at W8 into a `u128` value at W72.
12992    #[inline]
12993    #[must_use]
12994    pub const fn apply(value: u8) -> u128 {
12995        value as u128
12996    }
12997}
12998
12999impl Embed<W8, W80> {
13000    /// Embed a `u8` value at W8 into a `u128` value at W80.
13001    #[inline]
13002    #[must_use]
13003    pub const fn apply(value: u8) -> u128 {
13004        value as u128
13005    }
13006}
13007
13008impl Embed<W8, W88> {
13009    /// Embed a `u8` value at W8 into a `u128` value at W88.
13010    #[inline]
13011    #[must_use]
13012    pub const fn apply(value: u8) -> u128 {
13013        value as u128
13014    }
13015}
13016
13017impl Embed<W8, W96> {
13018    /// Embed a `u8` value at W8 into a `u128` value at W96.
13019    #[inline]
13020    #[must_use]
13021    pub const fn apply(value: u8) -> u128 {
13022        value as u128
13023    }
13024}
13025
13026impl Embed<W8, W104> {
13027    /// Embed a `u8` value at W8 into a `u128` value at W104.
13028    #[inline]
13029    #[must_use]
13030    pub const fn apply(value: u8) -> u128 {
13031        value as u128
13032    }
13033}
13034
13035impl Embed<W8, W112> {
13036    /// Embed a `u8` value at W8 into a `u128` value at W112.
13037    #[inline]
13038    #[must_use]
13039    pub const fn apply(value: u8) -> u128 {
13040        value as u128
13041    }
13042}
13043
13044impl Embed<W8, W120> {
13045    /// Embed a `u8` value at W8 into a `u128` value at W120.
13046    #[inline]
13047    #[must_use]
13048    pub const fn apply(value: u8) -> u128 {
13049        value as u128
13050    }
13051}
13052
13053impl Embed<W8, W128> {
13054    /// Embed a `u8` value at W8 into a `u128` value at W128.
13055    #[inline]
13056    #[must_use]
13057    pub const fn apply(value: u8) -> u128 {
13058        value as u128
13059    }
13060}
13061
13062impl Embed<W16, W16> {
13063    /// Embed a `u16` value at W16 into a `u16` value at W16.
13064    #[inline]
13065    #[must_use]
13066    pub const fn apply(value: u16) -> u16 {
13067        value
13068    }
13069}
13070
13071impl Embed<W16, W24> {
13072    /// Embed a `u16` value at W16 into a `u32` value at W24.
13073    #[inline]
13074    #[must_use]
13075    pub const fn apply(value: u16) -> u32 {
13076        value as u32
13077    }
13078}
13079
13080impl Embed<W16, W32> {
13081    /// Embed a `u16` value at W16 into a `u32` value at W32.
13082    #[inline]
13083    #[must_use]
13084    pub const fn apply(value: u16) -> u32 {
13085        value as u32
13086    }
13087}
13088
13089impl Embed<W16, W40> {
13090    /// Embed a `u16` value at W16 into a `u64` value at W40.
13091    #[inline]
13092    #[must_use]
13093    pub const fn apply(value: u16) -> u64 {
13094        value as u64
13095    }
13096}
13097
13098impl Embed<W16, W48> {
13099    /// Embed a `u16` value at W16 into a `u64` value at W48.
13100    #[inline]
13101    #[must_use]
13102    pub const fn apply(value: u16) -> u64 {
13103        value as u64
13104    }
13105}
13106
13107impl Embed<W16, W56> {
13108    /// Embed a `u16` value at W16 into a `u64` value at W56.
13109    #[inline]
13110    #[must_use]
13111    pub const fn apply(value: u16) -> u64 {
13112        value as u64
13113    }
13114}
13115
13116impl Embed<W16, W64> {
13117    /// Embed a `u16` value at W16 into a `u64` value at W64.
13118    #[inline]
13119    #[must_use]
13120    pub const fn apply(value: u16) -> u64 {
13121        value as u64
13122    }
13123}
13124
13125impl Embed<W16, W72> {
13126    /// Embed a `u16` value at W16 into a `u128` value at W72.
13127    #[inline]
13128    #[must_use]
13129    pub const fn apply(value: u16) -> u128 {
13130        value as u128
13131    }
13132}
13133
13134impl Embed<W16, W80> {
13135    /// Embed a `u16` value at W16 into a `u128` value at W80.
13136    #[inline]
13137    #[must_use]
13138    pub const fn apply(value: u16) -> u128 {
13139        value as u128
13140    }
13141}
13142
13143impl Embed<W16, W88> {
13144    /// Embed a `u16` value at W16 into a `u128` value at W88.
13145    #[inline]
13146    #[must_use]
13147    pub const fn apply(value: u16) -> u128 {
13148        value as u128
13149    }
13150}
13151
13152impl Embed<W16, W96> {
13153    /// Embed a `u16` value at W16 into a `u128` value at W96.
13154    #[inline]
13155    #[must_use]
13156    pub const fn apply(value: u16) -> u128 {
13157        value as u128
13158    }
13159}
13160
13161impl Embed<W16, W104> {
13162    /// Embed a `u16` value at W16 into a `u128` value at W104.
13163    #[inline]
13164    #[must_use]
13165    pub const fn apply(value: u16) -> u128 {
13166        value as u128
13167    }
13168}
13169
13170impl Embed<W16, W112> {
13171    /// Embed a `u16` value at W16 into a `u128` value at W112.
13172    #[inline]
13173    #[must_use]
13174    pub const fn apply(value: u16) -> u128 {
13175        value as u128
13176    }
13177}
13178
13179impl Embed<W16, W120> {
13180    /// Embed a `u16` value at W16 into a `u128` value at W120.
13181    #[inline]
13182    #[must_use]
13183    pub const fn apply(value: u16) -> u128 {
13184        value as u128
13185    }
13186}
13187
13188impl Embed<W16, W128> {
13189    /// Embed a `u16` value at W16 into a `u128` value at W128.
13190    #[inline]
13191    #[must_use]
13192    pub const fn apply(value: u16) -> u128 {
13193        value as u128
13194    }
13195}
13196
13197impl Embed<W24, W24> {
13198    /// Embed a `u32` value at W24 into a `u32` value at W24.
13199    #[inline]
13200    #[must_use]
13201    pub const fn apply(value: u32) -> u32 {
13202        value
13203    }
13204}
13205
13206impl Embed<W24, W32> {
13207    /// Embed a `u32` value at W24 into a `u32` value at W32.
13208    #[inline]
13209    #[must_use]
13210    pub const fn apply(value: u32) -> u32 {
13211        value
13212    }
13213}
13214
13215impl Embed<W24, W40> {
13216    /// Embed a `u32` value at W24 into a `u64` value at W40.
13217    #[inline]
13218    #[must_use]
13219    pub const fn apply(value: u32) -> u64 {
13220        value as u64
13221    }
13222}
13223
13224impl Embed<W24, W48> {
13225    /// Embed a `u32` value at W24 into a `u64` value at W48.
13226    #[inline]
13227    #[must_use]
13228    pub const fn apply(value: u32) -> u64 {
13229        value as u64
13230    }
13231}
13232
13233impl Embed<W24, W56> {
13234    /// Embed a `u32` value at W24 into a `u64` value at W56.
13235    #[inline]
13236    #[must_use]
13237    pub const fn apply(value: u32) -> u64 {
13238        value as u64
13239    }
13240}
13241
13242impl Embed<W24, W64> {
13243    /// Embed a `u32` value at W24 into a `u64` value at W64.
13244    #[inline]
13245    #[must_use]
13246    pub const fn apply(value: u32) -> u64 {
13247        value as u64
13248    }
13249}
13250
13251impl Embed<W24, W72> {
13252    /// Embed a `u32` value at W24 into a `u128` value at W72.
13253    #[inline]
13254    #[must_use]
13255    pub const fn apply(value: u32) -> u128 {
13256        value as u128
13257    }
13258}
13259
13260impl Embed<W24, W80> {
13261    /// Embed a `u32` value at W24 into a `u128` value at W80.
13262    #[inline]
13263    #[must_use]
13264    pub const fn apply(value: u32) -> u128 {
13265        value as u128
13266    }
13267}
13268
13269impl Embed<W24, W88> {
13270    /// Embed a `u32` value at W24 into a `u128` value at W88.
13271    #[inline]
13272    #[must_use]
13273    pub const fn apply(value: u32) -> u128 {
13274        value as u128
13275    }
13276}
13277
13278impl Embed<W24, W96> {
13279    /// Embed a `u32` value at W24 into a `u128` value at W96.
13280    #[inline]
13281    #[must_use]
13282    pub const fn apply(value: u32) -> u128 {
13283        value as u128
13284    }
13285}
13286
13287impl Embed<W24, W104> {
13288    /// Embed a `u32` value at W24 into a `u128` value at W104.
13289    #[inline]
13290    #[must_use]
13291    pub const fn apply(value: u32) -> u128 {
13292        value as u128
13293    }
13294}
13295
13296impl Embed<W24, W112> {
13297    /// Embed a `u32` value at W24 into a `u128` value at W112.
13298    #[inline]
13299    #[must_use]
13300    pub const fn apply(value: u32) -> u128 {
13301        value as u128
13302    }
13303}
13304
13305impl Embed<W24, W120> {
13306    /// Embed a `u32` value at W24 into a `u128` value at W120.
13307    #[inline]
13308    #[must_use]
13309    pub const fn apply(value: u32) -> u128 {
13310        value as u128
13311    }
13312}
13313
13314impl Embed<W24, W128> {
13315    /// Embed a `u32` value at W24 into a `u128` value at W128.
13316    #[inline]
13317    #[must_use]
13318    pub const fn apply(value: u32) -> u128 {
13319        value as u128
13320    }
13321}
13322
13323impl Embed<W32, W32> {
13324    /// Embed a `u32` value at W32 into a `u32` value at W32.
13325    #[inline]
13326    #[must_use]
13327    pub const fn apply(value: u32) -> u32 {
13328        value
13329    }
13330}
13331
13332impl Embed<W32, W40> {
13333    /// Embed a `u32` value at W32 into a `u64` value at W40.
13334    #[inline]
13335    #[must_use]
13336    pub const fn apply(value: u32) -> u64 {
13337        value as u64
13338    }
13339}
13340
13341impl Embed<W32, W48> {
13342    /// Embed a `u32` value at W32 into a `u64` value at W48.
13343    #[inline]
13344    #[must_use]
13345    pub const fn apply(value: u32) -> u64 {
13346        value as u64
13347    }
13348}
13349
13350impl Embed<W32, W56> {
13351    /// Embed a `u32` value at W32 into a `u64` value at W56.
13352    #[inline]
13353    #[must_use]
13354    pub const fn apply(value: u32) -> u64 {
13355        value as u64
13356    }
13357}
13358
13359impl Embed<W32, W64> {
13360    /// Embed a `u32` value at W32 into a `u64` value at W64.
13361    #[inline]
13362    #[must_use]
13363    pub const fn apply(value: u32) -> u64 {
13364        value as u64
13365    }
13366}
13367
13368impl Embed<W32, W72> {
13369    /// Embed a `u32` value at W32 into a `u128` value at W72.
13370    #[inline]
13371    #[must_use]
13372    pub const fn apply(value: u32) -> u128 {
13373        value as u128
13374    }
13375}
13376
13377impl Embed<W32, W80> {
13378    /// Embed a `u32` value at W32 into a `u128` value at W80.
13379    #[inline]
13380    #[must_use]
13381    pub const fn apply(value: u32) -> u128 {
13382        value as u128
13383    }
13384}
13385
13386impl Embed<W32, W88> {
13387    /// Embed a `u32` value at W32 into a `u128` value at W88.
13388    #[inline]
13389    #[must_use]
13390    pub const fn apply(value: u32) -> u128 {
13391        value as u128
13392    }
13393}
13394
13395impl Embed<W32, W96> {
13396    /// Embed a `u32` value at W32 into a `u128` value at W96.
13397    #[inline]
13398    #[must_use]
13399    pub const fn apply(value: u32) -> u128 {
13400        value as u128
13401    }
13402}
13403
13404impl Embed<W32, W104> {
13405    /// Embed a `u32` value at W32 into a `u128` value at W104.
13406    #[inline]
13407    #[must_use]
13408    pub const fn apply(value: u32) -> u128 {
13409        value as u128
13410    }
13411}
13412
13413impl Embed<W32, W112> {
13414    /// Embed a `u32` value at W32 into a `u128` value at W112.
13415    #[inline]
13416    #[must_use]
13417    pub const fn apply(value: u32) -> u128 {
13418        value as u128
13419    }
13420}
13421
13422impl Embed<W32, W120> {
13423    /// Embed a `u32` value at W32 into a `u128` value at W120.
13424    #[inline]
13425    #[must_use]
13426    pub const fn apply(value: u32) -> u128 {
13427        value as u128
13428    }
13429}
13430
13431impl Embed<W32, W128> {
13432    /// Embed a `u32` value at W32 into a `u128` value at W128.
13433    #[inline]
13434    #[must_use]
13435    pub const fn apply(value: u32) -> u128 {
13436        value as u128
13437    }
13438}
13439
13440impl Embed<W40, W40> {
13441    /// Embed a `u64` value at W40 into a `u64` value at W40.
13442    #[inline]
13443    #[must_use]
13444    pub const fn apply(value: u64) -> u64 {
13445        value
13446    }
13447}
13448
13449impl Embed<W40, W48> {
13450    /// Embed a `u64` value at W40 into a `u64` value at W48.
13451    #[inline]
13452    #[must_use]
13453    pub const fn apply(value: u64) -> u64 {
13454        value
13455    }
13456}
13457
13458impl Embed<W40, W56> {
13459    /// Embed a `u64` value at W40 into a `u64` value at W56.
13460    #[inline]
13461    #[must_use]
13462    pub const fn apply(value: u64) -> u64 {
13463        value
13464    }
13465}
13466
13467impl Embed<W40, W64> {
13468    /// Embed a `u64` value at W40 into a `u64` value at W64.
13469    #[inline]
13470    #[must_use]
13471    pub const fn apply(value: u64) -> u64 {
13472        value
13473    }
13474}
13475
13476impl Embed<W40, W72> {
13477    /// Embed a `u64` value at W40 into a `u128` value at W72.
13478    #[inline]
13479    #[must_use]
13480    pub const fn apply(value: u64) -> u128 {
13481        value as u128
13482    }
13483}
13484
13485impl Embed<W40, W80> {
13486    /// Embed a `u64` value at W40 into a `u128` value at W80.
13487    #[inline]
13488    #[must_use]
13489    pub const fn apply(value: u64) -> u128 {
13490        value as u128
13491    }
13492}
13493
13494impl Embed<W40, W88> {
13495    /// Embed a `u64` value at W40 into a `u128` value at W88.
13496    #[inline]
13497    #[must_use]
13498    pub const fn apply(value: u64) -> u128 {
13499        value as u128
13500    }
13501}
13502
13503impl Embed<W40, W96> {
13504    /// Embed a `u64` value at W40 into a `u128` value at W96.
13505    #[inline]
13506    #[must_use]
13507    pub const fn apply(value: u64) -> u128 {
13508        value as u128
13509    }
13510}
13511
13512impl Embed<W40, W104> {
13513    /// Embed a `u64` value at W40 into a `u128` value at W104.
13514    #[inline]
13515    #[must_use]
13516    pub const fn apply(value: u64) -> u128 {
13517        value as u128
13518    }
13519}
13520
13521impl Embed<W40, W112> {
13522    /// Embed a `u64` value at W40 into a `u128` value at W112.
13523    #[inline]
13524    #[must_use]
13525    pub const fn apply(value: u64) -> u128 {
13526        value as u128
13527    }
13528}
13529
13530impl Embed<W40, W120> {
13531    /// Embed a `u64` value at W40 into a `u128` value at W120.
13532    #[inline]
13533    #[must_use]
13534    pub const fn apply(value: u64) -> u128 {
13535        value as u128
13536    }
13537}
13538
13539impl Embed<W40, W128> {
13540    /// Embed a `u64` value at W40 into a `u128` value at W128.
13541    #[inline]
13542    #[must_use]
13543    pub const fn apply(value: u64) -> u128 {
13544        value as u128
13545    }
13546}
13547
13548impl Embed<W48, W48> {
13549    /// Embed a `u64` value at W48 into a `u64` value at W48.
13550    #[inline]
13551    #[must_use]
13552    pub const fn apply(value: u64) -> u64 {
13553        value
13554    }
13555}
13556
13557impl Embed<W48, W56> {
13558    /// Embed a `u64` value at W48 into a `u64` value at W56.
13559    #[inline]
13560    #[must_use]
13561    pub const fn apply(value: u64) -> u64 {
13562        value
13563    }
13564}
13565
13566impl Embed<W48, W64> {
13567    /// Embed a `u64` value at W48 into a `u64` value at W64.
13568    #[inline]
13569    #[must_use]
13570    pub const fn apply(value: u64) -> u64 {
13571        value
13572    }
13573}
13574
13575impl Embed<W48, W72> {
13576    /// Embed a `u64` value at W48 into a `u128` value at W72.
13577    #[inline]
13578    #[must_use]
13579    pub const fn apply(value: u64) -> u128 {
13580        value as u128
13581    }
13582}
13583
13584impl Embed<W48, W80> {
13585    /// Embed a `u64` value at W48 into a `u128` value at W80.
13586    #[inline]
13587    #[must_use]
13588    pub const fn apply(value: u64) -> u128 {
13589        value as u128
13590    }
13591}
13592
13593impl Embed<W48, W88> {
13594    /// Embed a `u64` value at W48 into a `u128` value at W88.
13595    #[inline]
13596    #[must_use]
13597    pub const fn apply(value: u64) -> u128 {
13598        value as u128
13599    }
13600}
13601
13602impl Embed<W48, W96> {
13603    /// Embed a `u64` value at W48 into a `u128` value at W96.
13604    #[inline]
13605    #[must_use]
13606    pub const fn apply(value: u64) -> u128 {
13607        value as u128
13608    }
13609}
13610
13611impl Embed<W48, W104> {
13612    /// Embed a `u64` value at W48 into a `u128` value at W104.
13613    #[inline]
13614    #[must_use]
13615    pub const fn apply(value: u64) -> u128 {
13616        value as u128
13617    }
13618}
13619
13620impl Embed<W48, W112> {
13621    /// Embed a `u64` value at W48 into a `u128` value at W112.
13622    #[inline]
13623    #[must_use]
13624    pub const fn apply(value: u64) -> u128 {
13625        value as u128
13626    }
13627}
13628
13629impl Embed<W48, W120> {
13630    /// Embed a `u64` value at W48 into a `u128` value at W120.
13631    #[inline]
13632    #[must_use]
13633    pub const fn apply(value: u64) -> u128 {
13634        value as u128
13635    }
13636}
13637
13638impl Embed<W48, W128> {
13639    /// Embed a `u64` value at W48 into a `u128` value at W128.
13640    #[inline]
13641    #[must_use]
13642    pub const fn apply(value: u64) -> u128 {
13643        value as u128
13644    }
13645}
13646
13647impl Embed<W56, W56> {
13648    /// Embed a `u64` value at W56 into a `u64` value at W56.
13649    #[inline]
13650    #[must_use]
13651    pub const fn apply(value: u64) -> u64 {
13652        value
13653    }
13654}
13655
13656impl Embed<W56, W64> {
13657    /// Embed a `u64` value at W56 into a `u64` value at W64.
13658    #[inline]
13659    #[must_use]
13660    pub const fn apply(value: u64) -> u64 {
13661        value
13662    }
13663}
13664
13665impl Embed<W56, W72> {
13666    /// Embed a `u64` value at W56 into a `u128` value at W72.
13667    #[inline]
13668    #[must_use]
13669    pub const fn apply(value: u64) -> u128 {
13670        value as u128
13671    }
13672}
13673
13674impl Embed<W56, W80> {
13675    /// Embed a `u64` value at W56 into a `u128` value at W80.
13676    #[inline]
13677    #[must_use]
13678    pub const fn apply(value: u64) -> u128 {
13679        value as u128
13680    }
13681}
13682
13683impl Embed<W56, W88> {
13684    /// Embed a `u64` value at W56 into a `u128` value at W88.
13685    #[inline]
13686    #[must_use]
13687    pub const fn apply(value: u64) -> u128 {
13688        value as u128
13689    }
13690}
13691
13692impl Embed<W56, W96> {
13693    /// Embed a `u64` value at W56 into a `u128` value at W96.
13694    #[inline]
13695    #[must_use]
13696    pub const fn apply(value: u64) -> u128 {
13697        value as u128
13698    }
13699}
13700
13701impl Embed<W56, W104> {
13702    /// Embed a `u64` value at W56 into a `u128` value at W104.
13703    #[inline]
13704    #[must_use]
13705    pub const fn apply(value: u64) -> u128 {
13706        value as u128
13707    }
13708}
13709
13710impl Embed<W56, W112> {
13711    /// Embed a `u64` value at W56 into a `u128` value at W112.
13712    #[inline]
13713    #[must_use]
13714    pub const fn apply(value: u64) -> u128 {
13715        value as u128
13716    }
13717}
13718
13719impl Embed<W56, W120> {
13720    /// Embed a `u64` value at W56 into a `u128` value at W120.
13721    #[inline]
13722    #[must_use]
13723    pub const fn apply(value: u64) -> u128 {
13724        value as u128
13725    }
13726}
13727
13728impl Embed<W56, W128> {
13729    /// Embed a `u64` value at W56 into a `u128` value at W128.
13730    #[inline]
13731    #[must_use]
13732    pub const fn apply(value: u64) -> u128 {
13733        value as u128
13734    }
13735}
13736
13737impl Embed<W64, W64> {
13738    /// Embed a `u64` value at W64 into a `u64` value at W64.
13739    #[inline]
13740    #[must_use]
13741    pub const fn apply(value: u64) -> u64 {
13742        value
13743    }
13744}
13745
13746impl Embed<W64, W72> {
13747    /// Embed a `u64` value at W64 into a `u128` value at W72.
13748    #[inline]
13749    #[must_use]
13750    pub const fn apply(value: u64) -> u128 {
13751        value as u128
13752    }
13753}
13754
13755impl Embed<W64, W80> {
13756    /// Embed a `u64` value at W64 into a `u128` value at W80.
13757    #[inline]
13758    #[must_use]
13759    pub const fn apply(value: u64) -> u128 {
13760        value as u128
13761    }
13762}
13763
13764impl Embed<W64, W88> {
13765    /// Embed a `u64` value at W64 into a `u128` value at W88.
13766    #[inline]
13767    #[must_use]
13768    pub const fn apply(value: u64) -> u128 {
13769        value as u128
13770    }
13771}
13772
13773impl Embed<W64, W96> {
13774    /// Embed a `u64` value at W64 into a `u128` value at W96.
13775    #[inline]
13776    #[must_use]
13777    pub const fn apply(value: u64) -> u128 {
13778        value as u128
13779    }
13780}
13781
13782impl Embed<W64, W104> {
13783    /// Embed a `u64` value at W64 into a `u128` value at W104.
13784    #[inline]
13785    #[must_use]
13786    pub const fn apply(value: u64) -> u128 {
13787        value as u128
13788    }
13789}
13790
13791impl Embed<W64, W112> {
13792    /// Embed a `u64` value at W64 into a `u128` value at W112.
13793    #[inline]
13794    #[must_use]
13795    pub const fn apply(value: u64) -> u128 {
13796        value as u128
13797    }
13798}
13799
13800impl Embed<W64, W120> {
13801    /// Embed a `u64` value at W64 into a `u128` value at W120.
13802    #[inline]
13803    #[must_use]
13804    pub const fn apply(value: u64) -> u128 {
13805        value as u128
13806    }
13807}
13808
13809impl Embed<W64, W128> {
13810    /// Embed a `u64` value at W64 into a `u128` value at W128.
13811    #[inline]
13812    #[must_use]
13813    pub const fn apply(value: u64) -> u128 {
13814        value as u128
13815    }
13816}
13817
13818impl Embed<W72, W72> {
13819    /// Embed a `u128` value at W72 into a `u128` value at W72.
13820    #[inline]
13821    #[must_use]
13822    pub const fn apply(value: u128) -> u128 {
13823        value
13824    }
13825}
13826
13827impl Embed<W72, W80> {
13828    /// Embed a `u128` value at W72 into a `u128` value at W80.
13829    #[inline]
13830    #[must_use]
13831    pub const fn apply(value: u128) -> u128 {
13832        value
13833    }
13834}
13835
13836impl Embed<W72, W88> {
13837    /// Embed a `u128` value at W72 into a `u128` value at W88.
13838    #[inline]
13839    #[must_use]
13840    pub const fn apply(value: u128) -> u128 {
13841        value
13842    }
13843}
13844
13845impl Embed<W72, W96> {
13846    /// Embed a `u128` value at W72 into a `u128` value at W96.
13847    #[inline]
13848    #[must_use]
13849    pub const fn apply(value: u128) -> u128 {
13850        value
13851    }
13852}
13853
13854impl Embed<W72, W104> {
13855    /// Embed a `u128` value at W72 into a `u128` value at W104.
13856    #[inline]
13857    #[must_use]
13858    pub const fn apply(value: u128) -> u128 {
13859        value
13860    }
13861}
13862
13863impl Embed<W72, W112> {
13864    /// Embed a `u128` value at W72 into a `u128` value at W112.
13865    #[inline]
13866    #[must_use]
13867    pub const fn apply(value: u128) -> u128 {
13868        value
13869    }
13870}
13871
13872impl Embed<W72, W120> {
13873    /// Embed a `u128` value at W72 into a `u128` value at W120.
13874    #[inline]
13875    #[must_use]
13876    pub const fn apply(value: u128) -> u128 {
13877        value
13878    }
13879}
13880
13881impl Embed<W72, W128> {
13882    /// Embed a `u128` value at W72 into a `u128` value at W128.
13883    #[inline]
13884    #[must_use]
13885    pub const fn apply(value: u128) -> u128 {
13886        value
13887    }
13888}
13889
13890impl Embed<W80, W80> {
13891    /// Embed a `u128` value at W80 into a `u128` value at W80.
13892    #[inline]
13893    #[must_use]
13894    pub const fn apply(value: u128) -> u128 {
13895        value
13896    }
13897}
13898
13899impl Embed<W80, W88> {
13900    /// Embed a `u128` value at W80 into a `u128` value at W88.
13901    #[inline]
13902    #[must_use]
13903    pub const fn apply(value: u128) -> u128 {
13904        value
13905    }
13906}
13907
13908impl Embed<W80, W96> {
13909    /// Embed a `u128` value at W80 into a `u128` value at W96.
13910    #[inline]
13911    #[must_use]
13912    pub const fn apply(value: u128) -> u128 {
13913        value
13914    }
13915}
13916
13917impl Embed<W80, W104> {
13918    /// Embed a `u128` value at W80 into a `u128` value at W104.
13919    #[inline]
13920    #[must_use]
13921    pub const fn apply(value: u128) -> u128 {
13922        value
13923    }
13924}
13925
13926impl Embed<W80, W112> {
13927    /// Embed a `u128` value at W80 into a `u128` value at W112.
13928    #[inline]
13929    #[must_use]
13930    pub const fn apply(value: u128) -> u128 {
13931        value
13932    }
13933}
13934
13935impl Embed<W80, W120> {
13936    /// Embed a `u128` value at W80 into a `u128` value at W120.
13937    #[inline]
13938    #[must_use]
13939    pub const fn apply(value: u128) -> u128 {
13940        value
13941    }
13942}
13943
13944impl Embed<W80, W128> {
13945    /// Embed a `u128` value at W80 into a `u128` value at W128.
13946    #[inline]
13947    #[must_use]
13948    pub const fn apply(value: u128) -> u128 {
13949        value
13950    }
13951}
13952
13953impl Embed<W88, W88> {
13954    /// Embed a `u128` value at W88 into a `u128` value at W88.
13955    #[inline]
13956    #[must_use]
13957    pub const fn apply(value: u128) -> u128 {
13958        value
13959    }
13960}
13961
13962impl Embed<W88, W96> {
13963    /// Embed a `u128` value at W88 into a `u128` value at W96.
13964    #[inline]
13965    #[must_use]
13966    pub const fn apply(value: u128) -> u128 {
13967        value
13968    }
13969}
13970
13971impl Embed<W88, W104> {
13972    /// Embed a `u128` value at W88 into a `u128` value at W104.
13973    #[inline]
13974    #[must_use]
13975    pub const fn apply(value: u128) -> u128 {
13976        value
13977    }
13978}
13979
13980impl Embed<W88, W112> {
13981    /// Embed a `u128` value at W88 into a `u128` value at W112.
13982    #[inline]
13983    #[must_use]
13984    pub const fn apply(value: u128) -> u128 {
13985        value
13986    }
13987}
13988
13989impl Embed<W88, W120> {
13990    /// Embed a `u128` value at W88 into a `u128` value at W120.
13991    #[inline]
13992    #[must_use]
13993    pub const fn apply(value: u128) -> u128 {
13994        value
13995    }
13996}
13997
13998impl Embed<W88, W128> {
13999    /// Embed a `u128` value at W88 into a `u128` value at W128.
14000    #[inline]
14001    #[must_use]
14002    pub const fn apply(value: u128) -> u128 {
14003        value
14004    }
14005}
14006
14007impl Embed<W96, W96> {
14008    /// Embed a `u128` value at W96 into a `u128` value at W96.
14009    #[inline]
14010    #[must_use]
14011    pub const fn apply(value: u128) -> u128 {
14012        value
14013    }
14014}
14015
14016impl Embed<W96, W104> {
14017    /// Embed a `u128` value at W96 into a `u128` value at W104.
14018    #[inline]
14019    #[must_use]
14020    pub const fn apply(value: u128) -> u128 {
14021        value
14022    }
14023}
14024
14025impl Embed<W96, W112> {
14026    /// Embed a `u128` value at W96 into a `u128` value at W112.
14027    #[inline]
14028    #[must_use]
14029    pub const fn apply(value: u128) -> u128 {
14030        value
14031    }
14032}
14033
14034impl Embed<W96, W120> {
14035    /// Embed a `u128` value at W96 into a `u128` value at W120.
14036    #[inline]
14037    #[must_use]
14038    pub const fn apply(value: u128) -> u128 {
14039        value
14040    }
14041}
14042
14043impl Embed<W96, W128> {
14044    /// Embed a `u128` value at W96 into a `u128` value at W128.
14045    #[inline]
14046    #[must_use]
14047    pub const fn apply(value: u128) -> u128 {
14048        value
14049    }
14050}
14051
14052impl Embed<W104, W104> {
14053    /// Embed a `u128` value at W104 into a `u128` value at W104.
14054    #[inline]
14055    #[must_use]
14056    pub const fn apply(value: u128) -> u128 {
14057        value
14058    }
14059}
14060
14061impl Embed<W104, W112> {
14062    /// Embed a `u128` value at W104 into a `u128` value at W112.
14063    #[inline]
14064    #[must_use]
14065    pub const fn apply(value: u128) -> u128 {
14066        value
14067    }
14068}
14069
14070impl Embed<W104, W120> {
14071    /// Embed a `u128` value at W104 into a `u128` value at W120.
14072    #[inline]
14073    #[must_use]
14074    pub const fn apply(value: u128) -> u128 {
14075        value
14076    }
14077}
14078
14079impl Embed<W104, W128> {
14080    /// Embed a `u128` value at W104 into a `u128` value at W128.
14081    #[inline]
14082    #[must_use]
14083    pub const fn apply(value: u128) -> u128 {
14084        value
14085    }
14086}
14087
14088impl Embed<W112, W112> {
14089    /// Embed a `u128` value at W112 into a `u128` value at W112.
14090    #[inline]
14091    #[must_use]
14092    pub const fn apply(value: u128) -> u128 {
14093        value
14094    }
14095}
14096
14097impl Embed<W112, W120> {
14098    /// Embed a `u128` value at W112 into a `u128` value at W120.
14099    #[inline]
14100    #[must_use]
14101    pub const fn apply(value: u128) -> u128 {
14102        value
14103    }
14104}
14105
14106impl Embed<W112, W128> {
14107    /// Embed a `u128` value at W112 into a `u128` value at W128.
14108    #[inline]
14109    #[must_use]
14110    pub const fn apply(value: u128) -> u128 {
14111        value
14112    }
14113}
14114
14115impl Embed<W120, W120> {
14116    /// Embed a `u128` value at W120 into a `u128` value at W120.
14117    #[inline]
14118    #[must_use]
14119    pub const fn apply(value: u128) -> u128 {
14120        value
14121    }
14122}
14123
14124impl Embed<W120, W128> {
14125    /// Embed a `u128` value at W120 into a `u128` value at W128.
14126    #[inline]
14127    #[must_use]
14128    pub const fn apply(value: u128) -> u128 {
14129        value
14130    }
14131}
14132
14133impl Embed<W128, W128> {
14134    /// Embed a `u128` value at W128 into a `u128` value at W128.
14135    #[inline]
14136    #[must_use]
14137    pub const fn apply(value: u128) -> u128 {
14138        value
14139    }
14140}
14141
14142/// v0.2.2 Phase C.3: marker structs for Limbs-backed Witt levels.
14143/// Each level binds a const-generic `Limbs<N>` width at the type level.
14144/// W160 marker — 160-bit Witt level, Limbs-backed.
14145#[derive(Debug, Default, Clone, Copy)]
14146pub struct W160;
14147
14148/// W192 marker — 192-bit Witt level, Limbs-backed.
14149#[derive(Debug, Default, Clone, Copy)]
14150pub struct W192;
14151
14152/// W224 marker — 224-bit Witt level, Limbs-backed.
14153#[derive(Debug, Default, Clone, Copy)]
14154pub struct W224;
14155
14156/// W256 marker — 256-bit Witt level, Limbs-backed.
14157#[derive(Debug, Default, Clone, Copy)]
14158pub struct W256;
14159
14160/// W384 marker — 384-bit Witt level, Limbs-backed.
14161#[derive(Debug, Default, Clone, Copy)]
14162pub struct W384;
14163
14164/// W448 marker — 448-bit Witt level, Limbs-backed.
14165#[derive(Debug, Default, Clone, Copy)]
14166pub struct W448;
14167
14168/// W512 marker — 512-bit Witt level, Limbs-backed.
14169#[derive(Debug, Default, Clone, Copy)]
14170pub struct W512;
14171
14172/// W520 marker — 520-bit Witt level, Limbs-backed.
14173#[derive(Debug, Default, Clone, Copy)]
14174pub struct W520;
14175
14176/// W528 marker — 528-bit Witt level, Limbs-backed.
14177#[derive(Debug, Default, Clone, Copy)]
14178pub struct W528;
14179
14180/// W1024 marker — 1024-bit Witt level, Limbs-backed.
14181#[derive(Debug, Default, Clone, Copy)]
14182pub struct W1024;
14183
14184/// W2048 marker — 2048-bit Witt level, Limbs-backed.
14185#[derive(Debug, Default, Clone, Copy)]
14186pub struct W2048;
14187
14188/// W4096 marker — 4096-bit Witt level, Limbs-backed.
14189#[derive(Debug, Default, Clone, Copy)]
14190pub struct W4096;
14191
14192/// W8192 marker — 8192-bit Witt level, Limbs-backed.
14193#[derive(Debug, Default, Clone, Copy)]
14194pub struct W8192;
14195
14196/// W12288 marker — 12288-bit Witt level, Limbs-backed.
14197#[derive(Debug, Default, Clone, Copy)]
14198pub struct W12288;
14199
14200/// W16384 marker — 16384-bit Witt level, Limbs-backed.
14201#[derive(Debug, Default, Clone, Copy)]
14202pub struct W16384;
14203
14204/// W32768 marker — 32768-bit Witt level, Limbs-backed.
14205#[derive(Debug, Default, Clone, Copy)]
14206pub struct W32768;
14207
14208impl RingOp<W160> for Mul<W160> {
14209    type Operand = Limbs<3>;
14210    #[inline]
14211    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14212        a.wrapping_mul(b).mask_high_bits(160)
14213    }
14214}
14215
14216impl RingOp<W160> for Add<W160> {
14217    type Operand = Limbs<3>;
14218    #[inline]
14219    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14220        a.wrapping_add(b).mask_high_bits(160)
14221    }
14222}
14223
14224impl RingOp<W160> for Sub<W160> {
14225    type Operand = Limbs<3>;
14226    #[inline]
14227    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14228        a.wrapping_sub(b).mask_high_bits(160)
14229    }
14230}
14231
14232impl RingOp<W160> for Xor<W160> {
14233    type Operand = Limbs<3>;
14234    #[inline]
14235    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14236        a.xor(b).mask_high_bits(160)
14237    }
14238}
14239
14240impl RingOp<W160> for And<W160> {
14241    type Operand = Limbs<3>;
14242    #[inline]
14243    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14244        a.and(b).mask_high_bits(160)
14245    }
14246}
14247
14248impl RingOp<W160> for Or<W160> {
14249    type Operand = Limbs<3>;
14250    #[inline]
14251    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14252        a.or(b).mask_high_bits(160)
14253    }
14254}
14255
14256impl UnaryRingOp<W160> for Neg<W160> {
14257    type Operand = Limbs<3>;
14258    #[inline]
14259    fn apply(a: Limbs<3>) -> Limbs<3> {
14260        (Limbs::<3>::zero().wrapping_sub(a)).mask_high_bits(160)
14261    }
14262}
14263
14264impl UnaryRingOp<W160> for BNot<W160> {
14265    type Operand = Limbs<3>;
14266    #[inline]
14267    fn apply(a: Limbs<3>) -> Limbs<3> {
14268        (a.not()).mask_high_bits(160)
14269    }
14270}
14271
14272impl UnaryRingOp<W160> for Succ<W160> {
14273    type Operand = Limbs<3>;
14274    #[inline]
14275    fn apply(a: Limbs<3>) -> Limbs<3> {
14276        (a.wrapping_add(Limbs::<3>::from_words([1u64, 0u64, 0u64]))).mask_high_bits(160)
14277    }
14278}
14279
14280impl RingOp<W192> for Mul<W192> {
14281    type Operand = Limbs<3>;
14282    #[inline]
14283    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14284        a.wrapping_mul(b)
14285    }
14286}
14287
14288impl RingOp<W192> for Add<W192> {
14289    type Operand = Limbs<3>;
14290    #[inline]
14291    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14292        a.wrapping_add(b)
14293    }
14294}
14295
14296impl RingOp<W192> for Sub<W192> {
14297    type Operand = Limbs<3>;
14298    #[inline]
14299    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14300        a.wrapping_sub(b)
14301    }
14302}
14303
14304impl RingOp<W192> for Xor<W192> {
14305    type Operand = Limbs<3>;
14306    #[inline]
14307    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14308        a.xor(b)
14309    }
14310}
14311
14312impl RingOp<W192> for And<W192> {
14313    type Operand = Limbs<3>;
14314    #[inline]
14315    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14316        a.and(b)
14317    }
14318}
14319
14320impl RingOp<W192> for Or<W192> {
14321    type Operand = Limbs<3>;
14322    #[inline]
14323    fn apply(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
14324        a.or(b)
14325    }
14326}
14327
14328impl UnaryRingOp<W192> for Neg<W192> {
14329    type Operand = Limbs<3>;
14330    #[inline]
14331    fn apply(a: Limbs<3>) -> Limbs<3> {
14332        Limbs::<3>::zero().wrapping_sub(a)
14333    }
14334}
14335
14336impl UnaryRingOp<W192> for BNot<W192> {
14337    type Operand = Limbs<3>;
14338    #[inline]
14339    fn apply(a: Limbs<3>) -> Limbs<3> {
14340        a.not()
14341    }
14342}
14343
14344impl UnaryRingOp<W192> for Succ<W192> {
14345    type Operand = Limbs<3>;
14346    #[inline]
14347    fn apply(a: Limbs<3>) -> Limbs<3> {
14348        a.wrapping_add(Limbs::<3>::from_words([1u64, 0u64, 0u64]))
14349    }
14350}
14351
14352impl RingOp<W224> for Mul<W224> {
14353    type Operand = Limbs<4>;
14354    #[inline]
14355    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14356        a.wrapping_mul(b).mask_high_bits(224)
14357    }
14358}
14359
14360impl RingOp<W224> for Add<W224> {
14361    type Operand = Limbs<4>;
14362    #[inline]
14363    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14364        a.wrapping_add(b).mask_high_bits(224)
14365    }
14366}
14367
14368impl RingOp<W224> for Sub<W224> {
14369    type Operand = Limbs<4>;
14370    #[inline]
14371    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14372        a.wrapping_sub(b).mask_high_bits(224)
14373    }
14374}
14375
14376impl RingOp<W224> for Xor<W224> {
14377    type Operand = Limbs<4>;
14378    #[inline]
14379    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14380        a.xor(b).mask_high_bits(224)
14381    }
14382}
14383
14384impl RingOp<W224> for And<W224> {
14385    type Operand = Limbs<4>;
14386    #[inline]
14387    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14388        a.and(b).mask_high_bits(224)
14389    }
14390}
14391
14392impl RingOp<W224> for Or<W224> {
14393    type Operand = Limbs<4>;
14394    #[inline]
14395    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14396        a.or(b).mask_high_bits(224)
14397    }
14398}
14399
14400impl UnaryRingOp<W224> for Neg<W224> {
14401    type Operand = Limbs<4>;
14402    #[inline]
14403    fn apply(a: Limbs<4>) -> Limbs<4> {
14404        (Limbs::<4>::zero().wrapping_sub(a)).mask_high_bits(224)
14405    }
14406}
14407
14408impl UnaryRingOp<W224> for BNot<W224> {
14409    type Operand = Limbs<4>;
14410    #[inline]
14411    fn apply(a: Limbs<4>) -> Limbs<4> {
14412        (a.not()).mask_high_bits(224)
14413    }
14414}
14415
14416impl UnaryRingOp<W224> for Succ<W224> {
14417    type Operand = Limbs<4>;
14418    #[inline]
14419    fn apply(a: Limbs<4>) -> Limbs<4> {
14420        (a.wrapping_add(Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64]))).mask_high_bits(224)
14421    }
14422}
14423
14424impl RingOp<W256> for Mul<W256> {
14425    type Operand = Limbs<4>;
14426    #[inline]
14427    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14428        a.wrapping_mul(b)
14429    }
14430}
14431
14432impl RingOp<W256> for Add<W256> {
14433    type Operand = Limbs<4>;
14434    #[inline]
14435    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14436        a.wrapping_add(b)
14437    }
14438}
14439
14440impl RingOp<W256> for Sub<W256> {
14441    type Operand = Limbs<4>;
14442    #[inline]
14443    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14444        a.wrapping_sub(b)
14445    }
14446}
14447
14448impl RingOp<W256> for Xor<W256> {
14449    type Operand = Limbs<4>;
14450    #[inline]
14451    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14452        a.xor(b)
14453    }
14454}
14455
14456impl RingOp<W256> for And<W256> {
14457    type Operand = Limbs<4>;
14458    #[inline]
14459    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14460        a.and(b)
14461    }
14462}
14463
14464impl RingOp<W256> for Or<W256> {
14465    type Operand = Limbs<4>;
14466    #[inline]
14467    fn apply(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
14468        a.or(b)
14469    }
14470}
14471
14472impl UnaryRingOp<W256> for Neg<W256> {
14473    type Operand = Limbs<4>;
14474    #[inline]
14475    fn apply(a: Limbs<4>) -> Limbs<4> {
14476        Limbs::<4>::zero().wrapping_sub(a)
14477    }
14478}
14479
14480impl UnaryRingOp<W256> for BNot<W256> {
14481    type Operand = Limbs<4>;
14482    #[inline]
14483    fn apply(a: Limbs<4>) -> Limbs<4> {
14484        a.not()
14485    }
14486}
14487
14488impl UnaryRingOp<W256> for Succ<W256> {
14489    type Operand = Limbs<4>;
14490    #[inline]
14491    fn apply(a: Limbs<4>) -> Limbs<4> {
14492        a.wrapping_add(Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64]))
14493    }
14494}
14495
14496impl RingOp<W384> for Mul<W384> {
14497    type Operand = Limbs<6>;
14498    #[inline]
14499    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14500        a.wrapping_mul(b)
14501    }
14502}
14503
14504impl RingOp<W384> for Add<W384> {
14505    type Operand = Limbs<6>;
14506    #[inline]
14507    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14508        a.wrapping_add(b)
14509    }
14510}
14511
14512impl RingOp<W384> for Sub<W384> {
14513    type Operand = Limbs<6>;
14514    #[inline]
14515    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14516        a.wrapping_sub(b)
14517    }
14518}
14519
14520impl RingOp<W384> for Xor<W384> {
14521    type Operand = Limbs<6>;
14522    #[inline]
14523    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14524        a.xor(b)
14525    }
14526}
14527
14528impl RingOp<W384> for And<W384> {
14529    type Operand = Limbs<6>;
14530    #[inline]
14531    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14532        a.and(b)
14533    }
14534}
14535
14536impl RingOp<W384> for Or<W384> {
14537    type Operand = Limbs<6>;
14538    #[inline]
14539    fn apply(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
14540        a.or(b)
14541    }
14542}
14543
14544impl UnaryRingOp<W384> for Neg<W384> {
14545    type Operand = Limbs<6>;
14546    #[inline]
14547    fn apply(a: Limbs<6>) -> Limbs<6> {
14548        Limbs::<6>::zero().wrapping_sub(a)
14549    }
14550}
14551
14552impl UnaryRingOp<W384> for BNot<W384> {
14553    type Operand = Limbs<6>;
14554    #[inline]
14555    fn apply(a: Limbs<6>) -> Limbs<6> {
14556        a.not()
14557    }
14558}
14559
14560impl UnaryRingOp<W384> for Succ<W384> {
14561    type Operand = Limbs<6>;
14562    #[inline]
14563    fn apply(a: Limbs<6>) -> Limbs<6> {
14564        a.wrapping_add(Limbs::<6>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64]))
14565    }
14566}
14567
14568impl RingOp<W448> for Mul<W448> {
14569    type Operand = Limbs<7>;
14570    #[inline]
14571    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14572        a.wrapping_mul(b)
14573    }
14574}
14575
14576impl RingOp<W448> for Add<W448> {
14577    type Operand = Limbs<7>;
14578    #[inline]
14579    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14580        a.wrapping_add(b)
14581    }
14582}
14583
14584impl RingOp<W448> for Sub<W448> {
14585    type Operand = Limbs<7>;
14586    #[inline]
14587    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14588        a.wrapping_sub(b)
14589    }
14590}
14591
14592impl RingOp<W448> for Xor<W448> {
14593    type Operand = Limbs<7>;
14594    #[inline]
14595    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14596        a.xor(b)
14597    }
14598}
14599
14600impl RingOp<W448> for And<W448> {
14601    type Operand = Limbs<7>;
14602    #[inline]
14603    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14604        a.and(b)
14605    }
14606}
14607
14608impl RingOp<W448> for Or<W448> {
14609    type Operand = Limbs<7>;
14610    #[inline]
14611    fn apply(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
14612        a.or(b)
14613    }
14614}
14615
14616impl UnaryRingOp<W448> for Neg<W448> {
14617    type Operand = Limbs<7>;
14618    #[inline]
14619    fn apply(a: Limbs<7>) -> Limbs<7> {
14620        Limbs::<7>::zero().wrapping_sub(a)
14621    }
14622}
14623
14624impl UnaryRingOp<W448> for BNot<W448> {
14625    type Operand = Limbs<7>;
14626    #[inline]
14627    fn apply(a: Limbs<7>) -> Limbs<7> {
14628        a.not()
14629    }
14630}
14631
14632impl UnaryRingOp<W448> for Succ<W448> {
14633    type Operand = Limbs<7>;
14634    #[inline]
14635    fn apply(a: Limbs<7>) -> Limbs<7> {
14636        a.wrapping_add(Limbs::<7>::from_words([
14637            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14638        ]))
14639    }
14640}
14641
14642impl RingOp<W512> for Mul<W512> {
14643    type Operand = Limbs<8>;
14644    #[inline]
14645    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14646        a.wrapping_mul(b)
14647    }
14648}
14649
14650impl RingOp<W512> for Add<W512> {
14651    type Operand = Limbs<8>;
14652    #[inline]
14653    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14654        a.wrapping_add(b)
14655    }
14656}
14657
14658impl RingOp<W512> for Sub<W512> {
14659    type Operand = Limbs<8>;
14660    #[inline]
14661    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14662        a.wrapping_sub(b)
14663    }
14664}
14665
14666impl RingOp<W512> for Xor<W512> {
14667    type Operand = Limbs<8>;
14668    #[inline]
14669    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14670        a.xor(b)
14671    }
14672}
14673
14674impl RingOp<W512> for And<W512> {
14675    type Operand = Limbs<8>;
14676    #[inline]
14677    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14678        a.and(b)
14679    }
14680}
14681
14682impl RingOp<W512> for Or<W512> {
14683    type Operand = Limbs<8>;
14684    #[inline]
14685    fn apply(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
14686        a.or(b)
14687    }
14688}
14689
14690impl UnaryRingOp<W512> for Neg<W512> {
14691    type Operand = Limbs<8>;
14692    #[inline]
14693    fn apply(a: Limbs<8>) -> Limbs<8> {
14694        Limbs::<8>::zero().wrapping_sub(a)
14695    }
14696}
14697
14698impl UnaryRingOp<W512> for BNot<W512> {
14699    type Operand = Limbs<8>;
14700    #[inline]
14701    fn apply(a: Limbs<8>) -> Limbs<8> {
14702        a.not()
14703    }
14704}
14705
14706impl UnaryRingOp<W512> for Succ<W512> {
14707    type Operand = Limbs<8>;
14708    #[inline]
14709    fn apply(a: Limbs<8>) -> Limbs<8> {
14710        a.wrapping_add(Limbs::<8>::from_words([
14711            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14712        ]))
14713    }
14714}
14715
14716impl RingOp<W520> for Mul<W520> {
14717    type Operand = Limbs<9>;
14718    #[inline]
14719    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14720        a.wrapping_mul(b).mask_high_bits(520)
14721    }
14722}
14723
14724impl RingOp<W520> for Add<W520> {
14725    type Operand = Limbs<9>;
14726    #[inline]
14727    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14728        a.wrapping_add(b).mask_high_bits(520)
14729    }
14730}
14731
14732impl RingOp<W520> for Sub<W520> {
14733    type Operand = Limbs<9>;
14734    #[inline]
14735    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14736        a.wrapping_sub(b).mask_high_bits(520)
14737    }
14738}
14739
14740impl RingOp<W520> for Xor<W520> {
14741    type Operand = Limbs<9>;
14742    #[inline]
14743    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14744        a.xor(b).mask_high_bits(520)
14745    }
14746}
14747
14748impl RingOp<W520> for And<W520> {
14749    type Operand = Limbs<9>;
14750    #[inline]
14751    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14752        a.and(b).mask_high_bits(520)
14753    }
14754}
14755
14756impl RingOp<W520> for Or<W520> {
14757    type Operand = Limbs<9>;
14758    #[inline]
14759    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14760        a.or(b).mask_high_bits(520)
14761    }
14762}
14763
14764impl UnaryRingOp<W520> for Neg<W520> {
14765    type Operand = Limbs<9>;
14766    #[inline]
14767    fn apply(a: Limbs<9>) -> Limbs<9> {
14768        (Limbs::<9>::zero().wrapping_sub(a)).mask_high_bits(520)
14769    }
14770}
14771
14772impl UnaryRingOp<W520> for BNot<W520> {
14773    type Operand = Limbs<9>;
14774    #[inline]
14775    fn apply(a: Limbs<9>) -> Limbs<9> {
14776        (a.not()).mask_high_bits(520)
14777    }
14778}
14779
14780impl UnaryRingOp<W520> for Succ<W520> {
14781    type Operand = Limbs<9>;
14782    #[inline]
14783    fn apply(a: Limbs<9>) -> Limbs<9> {
14784        (a.wrapping_add(Limbs::<9>::from_words([
14785            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14786        ])))
14787        .mask_high_bits(520)
14788    }
14789}
14790
14791impl RingOp<W528> for Mul<W528> {
14792    type Operand = Limbs<9>;
14793    #[inline]
14794    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14795        a.wrapping_mul(b).mask_high_bits(528)
14796    }
14797}
14798
14799impl RingOp<W528> for Add<W528> {
14800    type Operand = Limbs<9>;
14801    #[inline]
14802    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14803        a.wrapping_add(b).mask_high_bits(528)
14804    }
14805}
14806
14807impl RingOp<W528> for Sub<W528> {
14808    type Operand = Limbs<9>;
14809    #[inline]
14810    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14811        a.wrapping_sub(b).mask_high_bits(528)
14812    }
14813}
14814
14815impl RingOp<W528> for Xor<W528> {
14816    type Operand = Limbs<9>;
14817    #[inline]
14818    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14819        a.xor(b).mask_high_bits(528)
14820    }
14821}
14822
14823impl RingOp<W528> for And<W528> {
14824    type Operand = Limbs<9>;
14825    #[inline]
14826    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14827        a.and(b).mask_high_bits(528)
14828    }
14829}
14830
14831impl RingOp<W528> for Or<W528> {
14832    type Operand = Limbs<9>;
14833    #[inline]
14834    fn apply(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
14835        a.or(b).mask_high_bits(528)
14836    }
14837}
14838
14839impl UnaryRingOp<W528> for Neg<W528> {
14840    type Operand = Limbs<9>;
14841    #[inline]
14842    fn apply(a: Limbs<9>) -> Limbs<9> {
14843        (Limbs::<9>::zero().wrapping_sub(a)).mask_high_bits(528)
14844    }
14845}
14846
14847impl UnaryRingOp<W528> for BNot<W528> {
14848    type Operand = Limbs<9>;
14849    #[inline]
14850    fn apply(a: Limbs<9>) -> Limbs<9> {
14851        (a.not()).mask_high_bits(528)
14852    }
14853}
14854
14855impl UnaryRingOp<W528> for Succ<W528> {
14856    type Operand = Limbs<9>;
14857    #[inline]
14858    fn apply(a: Limbs<9>) -> Limbs<9> {
14859        (a.wrapping_add(Limbs::<9>::from_words([
14860            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14861        ])))
14862        .mask_high_bits(528)
14863    }
14864}
14865
14866impl RingOp<W1024> for Mul<W1024> {
14867    type Operand = Limbs<16>;
14868    #[inline]
14869    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14870        a.wrapping_mul(b)
14871    }
14872}
14873
14874impl RingOp<W1024> for Add<W1024> {
14875    type Operand = Limbs<16>;
14876    #[inline]
14877    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14878        a.wrapping_add(b)
14879    }
14880}
14881
14882impl RingOp<W1024> for Sub<W1024> {
14883    type Operand = Limbs<16>;
14884    #[inline]
14885    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14886        a.wrapping_sub(b)
14887    }
14888}
14889
14890impl RingOp<W1024> for Xor<W1024> {
14891    type Operand = Limbs<16>;
14892    #[inline]
14893    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14894        a.xor(b)
14895    }
14896}
14897
14898impl RingOp<W1024> for And<W1024> {
14899    type Operand = Limbs<16>;
14900    #[inline]
14901    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14902        a.and(b)
14903    }
14904}
14905
14906impl RingOp<W1024> for Or<W1024> {
14907    type Operand = Limbs<16>;
14908    #[inline]
14909    fn apply(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
14910        a.or(b)
14911    }
14912}
14913
14914impl UnaryRingOp<W1024> for Neg<W1024> {
14915    type Operand = Limbs<16>;
14916    #[inline]
14917    fn apply(a: Limbs<16>) -> Limbs<16> {
14918        Limbs::<16>::zero().wrapping_sub(a)
14919    }
14920}
14921
14922impl UnaryRingOp<W1024> for BNot<W1024> {
14923    type Operand = Limbs<16>;
14924    #[inline]
14925    fn apply(a: Limbs<16>) -> Limbs<16> {
14926        a.not()
14927    }
14928}
14929
14930impl UnaryRingOp<W1024> for Succ<W1024> {
14931    type Operand = Limbs<16>;
14932    #[inline]
14933    fn apply(a: Limbs<16>) -> Limbs<16> {
14934        a.wrapping_add(Limbs::<16>::from_words([
14935            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
14936            0u64, 0u64,
14937        ]))
14938    }
14939}
14940
14941impl RingOp<W2048> for Mul<W2048> {
14942    type Operand = Limbs<32>;
14943    #[inline]
14944    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14945        a.wrapping_mul(b)
14946    }
14947}
14948
14949impl RingOp<W2048> for Add<W2048> {
14950    type Operand = Limbs<32>;
14951    #[inline]
14952    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14953        a.wrapping_add(b)
14954    }
14955}
14956
14957impl RingOp<W2048> for Sub<W2048> {
14958    type Operand = Limbs<32>;
14959    #[inline]
14960    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14961        a.wrapping_sub(b)
14962    }
14963}
14964
14965impl RingOp<W2048> for Xor<W2048> {
14966    type Operand = Limbs<32>;
14967    #[inline]
14968    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14969        a.xor(b)
14970    }
14971}
14972
14973impl RingOp<W2048> for And<W2048> {
14974    type Operand = Limbs<32>;
14975    #[inline]
14976    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14977        a.and(b)
14978    }
14979}
14980
14981impl RingOp<W2048> for Or<W2048> {
14982    type Operand = Limbs<32>;
14983    #[inline]
14984    fn apply(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
14985        a.or(b)
14986    }
14987}
14988
14989impl UnaryRingOp<W2048> for Neg<W2048> {
14990    type Operand = Limbs<32>;
14991    #[inline]
14992    fn apply(a: Limbs<32>) -> Limbs<32> {
14993        Limbs::<32>::zero().wrapping_sub(a)
14994    }
14995}
14996
14997impl UnaryRingOp<W2048> for BNot<W2048> {
14998    type Operand = Limbs<32>;
14999    #[inline]
15000    fn apply(a: Limbs<32>) -> Limbs<32> {
15001        a.not()
15002    }
15003}
15004
15005impl UnaryRingOp<W2048> for Succ<W2048> {
15006    type Operand = Limbs<32>;
15007    #[inline]
15008    fn apply(a: Limbs<32>) -> Limbs<32> {
15009        a.wrapping_add(Limbs::<32>::from_words([
15010            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15011            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15012            0u64, 0u64, 0u64, 0u64,
15013        ]))
15014    }
15015}
15016
15017impl RingOp<W4096> for Mul<W4096> {
15018    type Operand = Limbs<64>;
15019    #[inline]
15020    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15021        a.wrapping_mul(b)
15022    }
15023}
15024
15025impl RingOp<W4096> for Add<W4096> {
15026    type Operand = Limbs<64>;
15027    #[inline]
15028    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15029        a.wrapping_add(b)
15030    }
15031}
15032
15033impl RingOp<W4096> for Sub<W4096> {
15034    type Operand = Limbs<64>;
15035    #[inline]
15036    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15037        a.wrapping_sub(b)
15038    }
15039}
15040
15041impl RingOp<W4096> for Xor<W4096> {
15042    type Operand = Limbs<64>;
15043    #[inline]
15044    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15045        a.xor(b)
15046    }
15047}
15048
15049impl RingOp<W4096> for And<W4096> {
15050    type Operand = Limbs<64>;
15051    #[inline]
15052    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15053        a.and(b)
15054    }
15055}
15056
15057impl RingOp<W4096> for Or<W4096> {
15058    type Operand = Limbs<64>;
15059    #[inline]
15060    fn apply(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
15061        a.or(b)
15062    }
15063}
15064
15065impl UnaryRingOp<W4096> for Neg<W4096> {
15066    type Operand = Limbs<64>;
15067    #[inline]
15068    fn apply(a: Limbs<64>) -> Limbs<64> {
15069        Limbs::<64>::zero().wrapping_sub(a)
15070    }
15071}
15072
15073impl UnaryRingOp<W4096> for BNot<W4096> {
15074    type Operand = Limbs<64>;
15075    #[inline]
15076    fn apply(a: Limbs<64>) -> Limbs<64> {
15077        a.not()
15078    }
15079}
15080
15081impl UnaryRingOp<W4096> for Succ<W4096> {
15082    type Operand = Limbs<64>;
15083    #[inline]
15084    fn apply(a: Limbs<64>) -> Limbs<64> {
15085        a.wrapping_add(Limbs::<64>::from_words([
15086            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15087            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15088            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15089            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15090            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15091        ]))
15092    }
15093}
15094
15095impl RingOp<W8192> for Mul<W8192> {
15096    type Operand = Limbs<128>;
15097    #[inline]
15098    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15099        a.wrapping_mul(b)
15100    }
15101}
15102
15103impl RingOp<W8192> for Add<W8192> {
15104    type Operand = Limbs<128>;
15105    #[inline]
15106    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15107        a.wrapping_add(b)
15108    }
15109}
15110
15111impl RingOp<W8192> for Sub<W8192> {
15112    type Operand = Limbs<128>;
15113    #[inline]
15114    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15115        a.wrapping_sub(b)
15116    }
15117}
15118
15119impl RingOp<W8192> for Xor<W8192> {
15120    type Operand = Limbs<128>;
15121    #[inline]
15122    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15123        a.xor(b)
15124    }
15125}
15126
15127impl RingOp<W8192> for And<W8192> {
15128    type Operand = Limbs<128>;
15129    #[inline]
15130    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15131        a.and(b)
15132    }
15133}
15134
15135impl RingOp<W8192> for Or<W8192> {
15136    type Operand = Limbs<128>;
15137    #[inline]
15138    fn apply(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
15139        a.or(b)
15140    }
15141}
15142
15143impl UnaryRingOp<W8192> for Neg<W8192> {
15144    type Operand = Limbs<128>;
15145    #[inline]
15146    fn apply(a: Limbs<128>) -> Limbs<128> {
15147        Limbs::<128>::zero().wrapping_sub(a)
15148    }
15149}
15150
15151impl UnaryRingOp<W8192> for BNot<W8192> {
15152    type Operand = Limbs<128>;
15153    #[inline]
15154    fn apply(a: Limbs<128>) -> Limbs<128> {
15155        a.not()
15156    }
15157}
15158
15159impl UnaryRingOp<W8192> for Succ<W8192> {
15160    type Operand = Limbs<128>;
15161    #[inline]
15162    fn apply(a: Limbs<128>) -> Limbs<128> {
15163        a.wrapping_add(Limbs::<128>::from_words([
15164            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15165            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15166            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15167            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15168            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15169            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15170            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15171            0u64, 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,
15174        ]))
15175    }
15176}
15177
15178impl RingOp<W12288> for Mul<W12288> {
15179    type Operand = Limbs<192>;
15180    #[inline]
15181    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15182        a.wrapping_mul(b)
15183    }
15184}
15185
15186impl RingOp<W12288> for Add<W12288> {
15187    type Operand = Limbs<192>;
15188    #[inline]
15189    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15190        a.wrapping_add(b)
15191    }
15192}
15193
15194impl RingOp<W12288> for Sub<W12288> {
15195    type Operand = Limbs<192>;
15196    #[inline]
15197    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15198        a.wrapping_sub(b)
15199    }
15200}
15201
15202impl RingOp<W12288> for Xor<W12288> {
15203    type Operand = Limbs<192>;
15204    #[inline]
15205    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15206        a.xor(b)
15207    }
15208}
15209
15210impl RingOp<W12288> for And<W12288> {
15211    type Operand = Limbs<192>;
15212    #[inline]
15213    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15214        a.and(b)
15215    }
15216}
15217
15218impl RingOp<W12288> for Or<W12288> {
15219    type Operand = Limbs<192>;
15220    #[inline]
15221    fn apply(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
15222        a.or(b)
15223    }
15224}
15225
15226impl UnaryRingOp<W12288> for Neg<W12288> {
15227    type Operand = Limbs<192>;
15228    #[inline]
15229    fn apply(a: Limbs<192>) -> Limbs<192> {
15230        Limbs::<192>::zero().wrapping_sub(a)
15231    }
15232}
15233
15234impl UnaryRingOp<W12288> for BNot<W12288> {
15235    type Operand = Limbs<192>;
15236    #[inline]
15237    fn apply(a: Limbs<192>) -> Limbs<192> {
15238        a.not()
15239    }
15240}
15241
15242impl UnaryRingOp<W12288> for Succ<W12288> {
15243    type Operand = Limbs<192>;
15244    #[inline]
15245    fn apply(a: Limbs<192>) -> Limbs<192> {
15246        a.wrapping_add(Limbs::<192>::from_words([
15247            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15248            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15249            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15250            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15251            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15252            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15253            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15254            0u64, 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,
15261        ]))
15262    }
15263}
15264
15265impl RingOp<W16384> for Mul<W16384> {
15266    type Operand = Limbs<256>;
15267    #[inline]
15268    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15269        a.wrapping_mul(b)
15270    }
15271}
15272
15273impl RingOp<W16384> for Add<W16384> {
15274    type Operand = Limbs<256>;
15275    #[inline]
15276    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15277        a.wrapping_add(b)
15278    }
15279}
15280
15281impl RingOp<W16384> for Sub<W16384> {
15282    type Operand = Limbs<256>;
15283    #[inline]
15284    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15285        a.wrapping_sub(b)
15286    }
15287}
15288
15289impl RingOp<W16384> for Xor<W16384> {
15290    type Operand = Limbs<256>;
15291    #[inline]
15292    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15293        a.xor(b)
15294    }
15295}
15296
15297impl RingOp<W16384> for And<W16384> {
15298    type Operand = Limbs<256>;
15299    #[inline]
15300    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15301        a.and(b)
15302    }
15303}
15304
15305impl RingOp<W16384> for Or<W16384> {
15306    type Operand = Limbs<256>;
15307    #[inline]
15308    fn apply(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
15309        a.or(b)
15310    }
15311}
15312
15313impl UnaryRingOp<W16384> for Neg<W16384> {
15314    type Operand = Limbs<256>;
15315    #[inline]
15316    fn apply(a: Limbs<256>) -> Limbs<256> {
15317        Limbs::<256>::zero().wrapping_sub(a)
15318    }
15319}
15320
15321impl UnaryRingOp<W16384> for BNot<W16384> {
15322    type Operand = Limbs<256>;
15323    #[inline]
15324    fn apply(a: Limbs<256>) -> Limbs<256> {
15325        a.not()
15326    }
15327}
15328
15329impl UnaryRingOp<W16384> for Succ<W16384> {
15330    type Operand = Limbs<256>;
15331    #[inline]
15332    fn apply(a: Limbs<256>) -> Limbs<256> {
15333        a.wrapping_add(Limbs::<256>::from_words([
15334            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15335            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15336            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15337            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15338            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15339            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15340            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15341            0u64, 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,
15353        ]))
15354    }
15355}
15356
15357impl RingOp<W32768> for Mul<W32768> {
15358    type Operand = Limbs<512>;
15359    #[inline]
15360    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15361        a.wrapping_mul(b)
15362    }
15363}
15364
15365impl RingOp<W32768> for Add<W32768> {
15366    type Operand = Limbs<512>;
15367    #[inline]
15368    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15369        a.wrapping_add(b)
15370    }
15371}
15372
15373impl RingOp<W32768> for Sub<W32768> {
15374    type Operand = Limbs<512>;
15375    #[inline]
15376    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15377        a.wrapping_sub(b)
15378    }
15379}
15380
15381impl RingOp<W32768> for Xor<W32768> {
15382    type Operand = Limbs<512>;
15383    #[inline]
15384    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15385        a.xor(b)
15386    }
15387}
15388
15389impl RingOp<W32768> for And<W32768> {
15390    type Operand = Limbs<512>;
15391    #[inline]
15392    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15393        a.and(b)
15394    }
15395}
15396
15397impl RingOp<W32768> for Or<W32768> {
15398    type Operand = Limbs<512>;
15399    #[inline]
15400    fn apply(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
15401        a.or(b)
15402    }
15403}
15404
15405impl UnaryRingOp<W32768> for Neg<W32768> {
15406    type Operand = Limbs<512>;
15407    #[inline]
15408    fn apply(a: Limbs<512>) -> Limbs<512> {
15409        Limbs::<512>::zero().wrapping_sub(a)
15410    }
15411}
15412
15413impl UnaryRingOp<W32768> for BNot<W32768> {
15414    type Operand = Limbs<512>;
15415    #[inline]
15416    fn apply(a: Limbs<512>) -> Limbs<512> {
15417        a.not()
15418    }
15419}
15420
15421impl UnaryRingOp<W32768> for Succ<W32768> {
15422    type Operand = Limbs<512>;
15423    #[inline]
15424    fn apply(a: Limbs<512>) -> Limbs<512> {
15425        a.wrapping_add(Limbs::<512>::from_words([
15426            1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15427            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15428            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15429            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15430            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15431            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15432            0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
15433            0u64, 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,
15463        ]))
15464    }
15465}
15466
15467/// Phase L.2 (target §4.5): `const_ring_eval_w{n}` helpers for Limbs-backed
15468/// Witt levels. Each helper runs a `PrimitiveOp` over two `Limbs<N>` operands
15469/// and applies the level's bit-width mask to the result.
15470/// These helpers are always const-fn; whether `rustc` can complete a specific
15471/// compile-time evaluation within the developer's budget is a function of the
15472/// invocation (see target §4.5 Q2 practicality table).
15473#[inline]
15474#[must_use]
15475pub const fn const_ring_eval_w160(op: PrimitiveOp, a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
15476    let raw = match op {
15477        PrimitiveOp::Add => a.wrapping_add(b),
15478        PrimitiveOp::Sub => a.wrapping_sub(b),
15479        PrimitiveOp::Mul => a.wrapping_mul(b),
15480        PrimitiveOp::And => a.and(b),
15481        PrimitiveOp::Or => a.or(b),
15482        PrimitiveOp::Xor => a.xor(b),
15483        PrimitiveOp::Neg => Limbs::<3>::zero().wrapping_sub(a),
15484        PrimitiveOp::Bnot => a.not(),
15485        PrimitiveOp::Succ => a.wrapping_add(limbs_one_3()),
15486        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_3()),
15487        PrimitiveOp::Le => {
15488            if limbs_le_3(a, b) {
15489                limbs_one_3()
15490            } else {
15491                Limbs::<3>::zero()
15492            }
15493        }
15494        PrimitiveOp::Lt => {
15495            if limbs_lt_3(a, b) {
15496                limbs_one_3()
15497            } else {
15498                Limbs::<3>::zero()
15499            }
15500        }
15501        PrimitiveOp::Ge => {
15502            if limbs_le_3(b, a) {
15503                limbs_one_3()
15504            } else {
15505                Limbs::<3>::zero()
15506            }
15507        }
15508        PrimitiveOp::Gt => {
15509            if limbs_lt_3(b, a) {
15510                limbs_one_3()
15511            } else {
15512                Limbs::<3>::zero()
15513            }
15514        }
15515        PrimitiveOp::Concat => Limbs::<3>::zero(),
15516        PrimitiveOp::Div => {
15517            if limbs_is_zero_3(b) {
15518                Limbs::<3>::zero()
15519            } else {
15520                limbs_div_3(a, b)
15521            }
15522        }
15523        PrimitiveOp::Mod => {
15524            if limbs_is_zero_3(b) {
15525                Limbs::<3>::zero()
15526            } else {
15527                limbs_mod_3(a, b)
15528            }
15529        }
15530        PrimitiveOp::Pow => limbs_pow_3(a, b),
15531    };
15532    raw.mask_high_bits(160)
15533}
15534
15535#[inline]
15536#[must_use]
15537pub const fn const_ring_eval_w192(op: PrimitiveOp, a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
15538    match op {
15539        PrimitiveOp::Add => a.wrapping_add(b),
15540        PrimitiveOp::Sub => a.wrapping_sub(b),
15541        PrimitiveOp::Mul => a.wrapping_mul(b),
15542        PrimitiveOp::And => a.and(b),
15543        PrimitiveOp::Or => a.or(b),
15544        PrimitiveOp::Xor => a.xor(b),
15545        PrimitiveOp::Neg => Limbs::<3>::zero().wrapping_sub(a),
15546        PrimitiveOp::Bnot => a.not(),
15547        PrimitiveOp::Succ => a.wrapping_add(limbs_one_3()),
15548        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_3()),
15549        PrimitiveOp::Le => {
15550            if limbs_le_3(a, b) {
15551                limbs_one_3()
15552            } else {
15553                Limbs::<3>::zero()
15554            }
15555        }
15556        PrimitiveOp::Lt => {
15557            if limbs_lt_3(a, b) {
15558                limbs_one_3()
15559            } else {
15560                Limbs::<3>::zero()
15561            }
15562        }
15563        PrimitiveOp::Ge => {
15564            if limbs_le_3(b, a) {
15565                limbs_one_3()
15566            } else {
15567                Limbs::<3>::zero()
15568            }
15569        }
15570        PrimitiveOp::Gt => {
15571            if limbs_lt_3(b, a) {
15572                limbs_one_3()
15573            } else {
15574                Limbs::<3>::zero()
15575            }
15576        }
15577        PrimitiveOp::Concat => Limbs::<3>::zero(),
15578        PrimitiveOp::Div => {
15579            if limbs_is_zero_3(b) {
15580                Limbs::<3>::zero()
15581            } else {
15582                limbs_div_3(a, b)
15583            }
15584        }
15585        PrimitiveOp::Mod => {
15586            if limbs_is_zero_3(b) {
15587                Limbs::<3>::zero()
15588            } else {
15589                limbs_mod_3(a, b)
15590            }
15591        }
15592        PrimitiveOp::Pow => limbs_pow_3(a, b),
15593    }
15594}
15595
15596#[inline]
15597#[must_use]
15598pub const fn const_ring_eval_w224(op: PrimitiveOp, a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
15599    let raw = match op {
15600        PrimitiveOp::Add => a.wrapping_add(b),
15601        PrimitiveOp::Sub => a.wrapping_sub(b),
15602        PrimitiveOp::Mul => a.wrapping_mul(b),
15603        PrimitiveOp::And => a.and(b),
15604        PrimitiveOp::Or => a.or(b),
15605        PrimitiveOp::Xor => a.xor(b),
15606        PrimitiveOp::Neg => Limbs::<4>::zero().wrapping_sub(a),
15607        PrimitiveOp::Bnot => a.not(),
15608        PrimitiveOp::Succ => a.wrapping_add(limbs_one_4()),
15609        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_4()),
15610        PrimitiveOp::Le => {
15611            if limbs_le_4(a, b) {
15612                limbs_one_4()
15613            } else {
15614                Limbs::<4>::zero()
15615            }
15616        }
15617        PrimitiveOp::Lt => {
15618            if limbs_lt_4(a, b) {
15619                limbs_one_4()
15620            } else {
15621                Limbs::<4>::zero()
15622            }
15623        }
15624        PrimitiveOp::Ge => {
15625            if limbs_le_4(b, a) {
15626                limbs_one_4()
15627            } else {
15628                Limbs::<4>::zero()
15629            }
15630        }
15631        PrimitiveOp::Gt => {
15632            if limbs_lt_4(b, a) {
15633                limbs_one_4()
15634            } else {
15635                Limbs::<4>::zero()
15636            }
15637        }
15638        PrimitiveOp::Concat => Limbs::<4>::zero(),
15639        PrimitiveOp::Div => {
15640            if limbs_is_zero_4(b) {
15641                Limbs::<4>::zero()
15642            } else {
15643                limbs_div_4(a, b)
15644            }
15645        }
15646        PrimitiveOp::Mod => {
15647            if limbs_is_zero_4(b) {
15648                Limbs::<4>::zero()
15649            } else {
15650                limbs_mod_4(a, b)
15651            }
15652        }
15653        PrimitiveOp::Pow => limbs_pow_4(a, b),
15654    };
15655    raw.mask_high_bits(224)
15656}
15657
15658#[inline]
15659#[must_use]
15660pub const fn const_ring_eval_w256(op: PrimitiveOp, a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
15661    match op {
15662        PrimitiveOp::Add => a.wrapping_add(b),
15663        PrimitiveOp::Sub => a.wrapping_sub(b),
15664        PrimitiveOp::Mul => a.wrapping_mul(b),
15665        PrimitiveOp::And => a.and(b),
15666        PrimitiveOp::Or => a.or(b),
15667        PrimitiveOp::Xor => a.xor(b),
15668        PrimitiveOp::Neg => Limbs::<4>::zero().wrapping_sub(a),
15669        PrimitiveOp::Bnot => a.not(),
15670        PrimitiveOp::Succ => a.wrapping_add(limbs_one_4()),
15671        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_4()),
15672        PrimitiveOp::Le => {
15673            if limbs_le_4(a, b) {
15674                limbs_one_4()
15675            } else {
15676                Limbs::<4>::zero()
15677            }
15678        }
15679        PrimitiveOp::Lt => {
15680            if limbs_lt_4(a, b) {
15681                limbs_one_4()
15682            } else {
15683                Limbs::<4>::zero()
15684            }
15685        }
15686        PrimitiveOp::Ge => {
15687            if limbs_le_4(b, a) {
15688                limbs_one_4()
15689            } else {
15690                Limbs::<4>::zero()
15691            }
15692        }
15693        PrimitiveOp::Gt => {
15694            if limbs_lt_4(b, a) {
15695                limbs_one_4()
15696            } else {
15697                Limbs::<4>::zero()
15698            }
15699        }
15700        PrimitiveOp::Concat => Limbs::<4>::zero(),
15701        PrimitiveOp::Div => {
15702            if limbs_is_zero_4(b) {
15703                Limbs::<4>::zero()
15704            } else {
15705                limbs_div_4(a, b)
15706            }
15707        }
15708        PrimitiveOp::Mod => {
15709            if limbs_is_zero_4(b) {
15710                Limbs::<4>::zero()
15711            } else {
15712                limbs_mod_4(a, b)
15713            }
15714        }
15715        PrimitiveOp::Pow => limbs_pow_4(a, b),
15716    }
15717}
15718
15719#[inline]
15720#[must_use]
15721pub const fn const_ring_eval_w384(op: PrimitiveOp, a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
15722    match op {
15723        PrimitiveOp::Add => a.wrapping_add(b),
15724        PrimitiveOp::Sub => a.wrapping_sub(b),
15725        PrimitiveOp::Mul => a.wrapping_mul(b),
15726        PrimitiveOp::And => a.and(b),
15727        PrimitiveOp::Or => a.or(b),
15728        PrimitiveOp::Xor => a.xor(b),
15729        PrimitiveOp::Neg => Limbs::<6>::zero().wrapping_sub(a),
15730        PrimitiveOp::Bnot => a.not(),
15731        PrimitiveOp::Succ => a.wrapping_add(limbs_one_6()),
15732        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_6()),
15733        PrimitiveOp::Le => {
15734            if limbs_le_6(a, b) {
15735                limbs_one_6()
15736            } else {
15737                Limbs::<6>::zero()
15738            }
15739        }
15740        PrimitiveOp::Lt => {
15741            if limbs_lt_6(a, b) {
15742                limbs_one_6()
15743            } else {
15744                Limbs::<6>::zero()
15745            }
15746        }
15747        PrimitiveOp::Ge => {
15748            if limbs_le_6(b, a) {
15749                limbs_one_6()
15750            } else {
15751                Limbs::<6>::zero()
15752            }
15753        }
15754        PrimitiveOp::Gt => {
15755            if limbs_lt_6(b, a) {
15756                limbs_one_6()
15757            } else {
15758                Limbs::<6>::zero()
15759            }
15760        }
15761        PrimitiveOp::Concat => Limbs::<6>::zero(),
15762        PrimitiveOp::Div => {
15763            if limbs_is_zero_6(b) {
15764                Limbs::<6>::zero()
15765            } else {
15766                limbs_div_6(a, b)
15767            }
15768        }
15769        PrimitiveOp::Mod => {
15770            if limbs_is_zero_6(b) {
15771                Limbs::<6>::zero()
15772            } else {
15773                limbs_mod_6(a, b)
15774            }
15775        }
15776        PrimitiveOp::Pow => limbs_pow_6(a, b),
15777    }
15778}
15779
15780#[inline]
15781#[must_use]
15782pub const fn const_ring_eval_w448(op: PrimitiveOp, a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
15783    match op {
15784        PrimitiveOp::Add => a.wrapping_add(b),
15785        PrimitiveOp::Sub => a.wrapping_sub(b),
15786        PrimitiveOp::Mul => a.wrapping_mul(b),
15787        PrimitiveOp::And => a.and(b),
15788        PrimitiveOp::Or => a.or(b),
15789        PrimitiveOp::Xor => a.xor(b),
15790        PrimitiveOp::Neg => Limbs::<7>::zero().wrapping_sub(a),
15791        PrimitiveOp::Bnot => a.not(),
15792        PrimitiveOp::Succ => a.wrapping_add(limbs_one_7()),
15793        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_7()),
15794        PrimitiveOp::Le => {
15795            if limbs_le_7(a, b) {
15796                limbs_one_7()
15797            } else {
15798                Limbs::<7>::zero()
15799            }
15800        }
15801        PrimitiveOp::Lt => {
15802            if limbs_lt_7(a, b) {
15803                limbs_one_7()
15804            } else {
15805                Limbs::<7>::zero()
15806            }
15807        }
15808        PrimitiveOp::Ge => {
15809            if limbs_le_7(b, a) {
15810                limbs_one_7()
15811            } else {
15812                Limbs::<7>::zero()
15813            }
15814        }
15815        PrimitiveOp::Gt => {
15816            if limbs_lt_7(b, a) {
15817                limbs_one_7()
15818            } else {
15819                Limbs::<7>::zero()
15820            }
15821        }
15822        PrimitiveOp::Concat => Limbs::<7>::zero(),
15823        PrimitiveOp::Div => {
15824            if limbs_is_zero_7(b) {
15825                Limbs::<7>::zero()
15826            } else {
15827                limbs_div_7(a, b)
15828            }
15829        }
15830        PrimitiveOp::Mod => {
15831            if limbs_is_zero_7(b) {
15832                Limbs::<7>::zero()
15833            } else {
15834                limbs_mod_7(a, b)
15835            }
15836        }
15837        PrimitiveOp::Pow => limbs_pow_7(a, b),
15838    }
15839}
15840
15841#[inline]
15842#[must_use]
15843pub const fn const_ring_eval_w512(op: PrimitiveOp, a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
15844    match op {
15845        PrimitiveOp::Add => a.wrapping_add(b),
15846        PrimitiveOp::Sub => a.wrapping_sub(b),
15847        PrimitiveOp::Mul => a.wrapping_mul(b),
15848        PrimitiveOp::And => a.and(b),
15849        PrimitiveOp::Or => a.or(b),
15850        PrimitiveOp::Xor => a.xor(b),
15851        PrimitiveOp::Neg => Limbs::<8>::zero().wrapping_sub(a),
15852        PrimitiveOp::Bnot => a.not(),
15853        PrimitiveOp::Succ => a.wrapping_add(limbs_one_8()),
15854        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_8()),
15855        PrimitiveOp::Le => {
15856            if limbs_le_8(a, b) {
15857                limbs_one_8()
15858            } else {
15859                Limbs::<8>::zero()
15860            }
15861        }
15862        PrimitiveOp::Lt => {
15863            if limbs_lt_8(a, b) {
15864                limbs_one_8()
15865            } else {
15866                Limbs::<8>::zero()
15867            }
15868        }
15869        PrimitiveOp::Ge => {
15870            if limbs_le_8(b, a) {
15871                limbs_one_8()
15872            } else {
15873                Limbs::<8>::zero()
15874            }
15875        }
15876        PrimitiveOp::Gt => {
15877            if limbs_lt_8(b, a) {
15878                limbs_one_8()
15879            } else {
15880                Limbs::<8>::zero()
15881            }
15882        }
15883        PrimitiveOp::Concat => Limbs::<8>::zero(),
15884        PrimitiveOp::Div => {
15885            if limbs_is_zero_8(b) {
15886                Limbs::<8>::zero()
15887            } else {
15888                limbs_div_8(a, b)
15889            }
15890        }
15891        PrimitiveOp::Mod => {
15892            if limbs_is_zero_8(b) {
15893                Limbs::<8>::zero()
15894            } else {
15895                limbs_mod_8(a, b)
15896            }
15897        }
15898        PrimitiveOp::Pow => limbs_pow_8(a, b),
15899    }
15900}
15901
15902#[inline]
15903#[must_use]
15904pub const fn const_ring_eval_w520(op: PrimitiveOp, a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
15905    let raw = match op {
15906        PrimitiveOp::Add => a.wrapping_add(b),
15907        PrimitiveOp::Sub => a.wrapping_sub(b),
15908        PrimitiveOp::Mul => a.wrapping_mul(b),
15909        PrimitiveOp::And => a.and(b),
15910        PrimitiveOp::Or => a.or(b),
15911        PrimitiveOp::Xor => a.xor(b),
15912        PrimitiveOp::Neg => Limbs::<9>::zero().wrapping_sub(a),
15913        PrimitiveOp::Bnot => a.not(),
15914        PrimitiveOp::Succ => a.wrapping_add(limbs_one_9()),
15915        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_9()),
15916        PrimitiveOp::Le => {
15917            if limbs_le_9(a, b) {
15918                limbs_one_9()
15919            } else {
15920                Limbs::<9>::zero()
15921            }
15922        }
15923        PrimitiveOp::Lt => {
15924            if limbs_lt_9(a, b) {
15925                limbs_one_9()
15926            } else {
15927                Limbs::<9>::zero()
15928            }
15929        }
15930        PrimitiveOp::Ge => {
15931            if limbs_le_9(b, a) {
15932                limbs_one_9()
15933            } else {
15934                Limbs::<9>::zero()
15935            }
15936        }
15937        PrimitiveOp::Gt => {
15938            if limbs_lt_9(b, a) {
15939                limbs_one_9()
15940            } else {
15941                Limbs::<9>::zero()
15942            }
15943        }
15944        PrimitiveOp::Concat => Limbs::<9>::zero(),
15945        PrimitiveOp::Div => {
15946            if limbs_is_zero_9(b) {
15947                Limbs::<9>::zero()
15948            } else {
15949                limbs_div_9(a, b)
15950            }
15951        }
15952        PrimitiveOp::Mod => {
15953            if limbs_is_zero_9(b) {
15954                Limbs::<9>::zero()
15955            } else {
15956                limbs_mod_9(a, b)
15957            }
15958        }
15959        PrimitiveOp::Pow => limbs_pow_9(a, b),
15960    };
15961    raw.mask_high_bits(520)
15962}
15963
15964#[inline]
15965#[must_use]
15966pub const fn const_ring_eval_w528(op: PrimitiveOp, a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
15967    let raw = match op {
15968        PrimitiveOp::Add => a.wrapping_add(b),
15969        PrimitiveOp::Sub => a.wrapping_sub(b),
15970        PrimitiveOp::Mul => a.wrapping_mul(b),
15971        PrimitiveOp::And => a.and(b),
15972        PrimitiveOp::Or => a.or(b),
15973        PrimitiveOp::Xor => a.xor(b),
15974        PrimitiveOp::Neg => Limbs::<9>::zero().wrapping_sub(a),
15975        PrimitiveOp::Bnot => a.not(),
15976        PrimitiveOp::Succ => a.wrapping_add(limbs_one_9()),
15977        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_9()),
15978        PrimitiveOp::Le => {
15979            if limbs_le_9(a, b) {
15980                limbs_one_9()
15981            } else {
15982                Limbs::<9>::zero()
15983            }
15984        }
15985        PrimitiveOp::Lt => {
15986            if limbs_lt_9(a, b) {
15987                limbs_one_9()
15988            } else {
15989                Limbs::<9>::zero()
15990            }
15991        }
15992        PrimitiveOp::Ge => {
15993            if limbs_le_9(b, a) {
15994                limbs_one_9()
15995            } else {
15996                Limbs::<9>::zero()
15997            }
15998        }
15999        PrimitiveOp::Gt => {
16000            if limbs_lt_9(b, a) {
16001                limbs_one_9()
16002            } else {
16003                Limbs::<9>::zero()
16004            }
16005        }
16006        PrimitiveOp::Concat => Limbs::<9>::zero(),
16007        PrimitiveOp::Div => {
16008            if limbs_is_zero_9(b) {
16009                Limbs::<9>::zero()
16010            } else {
16011                limbs_div_9(a, b)
16012            }
16013        }
16014        PrimitiveOp::Mod => {
16015            if limbs_is_zero_9(b) {
16016                Limbs::<9>::zero()
16017            } else {
16018                limbs_mod_9(a, b)
16019            }
16020        }
16021        PrimitiveOp::Pow => limbs_pow_9(a, b),
16022    };
16023    raw.mask_high_bits(528)
16024}
16025
16026#[inline]
16027#[must_use]
16028pub const fn const_ring_eval_w1024(op: PrimitiveOp, a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
16029    match op {
16030        PrimitiveOp::Add => a.wrapping_add(b),
16031        PrimitiveOp::Sub => a.wrapping_sub(b),
16032        PrimitiveOp::Mul => a.wrapping_mul(b),
16033        PrimitiveOp::And => a.and(b),
16034        PrimitiveOp::Or => a.or(b),
16035        PrimitiveOp::Xor => a.xor(b),
16036        PrimitiveOp::Neg => Limbs::<16>::zero().wrapping_sub(a),
16037        PrimitiveOp::Bnot => a.not(),
16038        PrimitiveOp::Succ => a.wrapping_add(limbs_one_16()),
16039        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_16()),
16040        PrimitiveOp::Le => {
16041            if limbs_le_16(a, b) {
16042                limbs_one_16()
16043            } else {
16044                Limbs::<16>::zero()
16045            }
16046        }
16047        PrimitiveOp::Lt => {
16048            if limbs_lt_16(a, b) {
16049                limbs_one_16()
16050            } else {
16051                Limbs::<16>::zero()
16052            }
16053        }
16054        PrimitiveOp::Ge => {
16055            if limbs_le_16(b, a) {
16056                limbs_one_16()
16057            } else {
16058                Limbs::<16>::zero()
16059            }
16060        }
16061        PrimitiveOp::Gt => {
16062            if limbs_lt_16(b, a) {
16063                limbs_one_16()
16064            } else {
16065                Limbs::<16>::zero()
16066            }
16067        }
16068        PrimitiveOp::Concat => Limbs::<16>::zero(),
16069        PrimitiveOp::Div => {
16070            if limbs_is_zero_16(b) {
16071                Limbs::<16>::zero()
16072            } else {
16073                limbs_div_16(a, b)
16074            }
16075        }
16076        PrimitiveOp::Mod => {
16077            if limbs_is_zero_16(b) {
16078                Limbs::<16>::zero()
16079            } else {
16080                limbs_mod_16(a, b)
16081            }
16082        }
16083        PrimitiveOp::Pow => limbs_pow_16(a, b),
16084    }
16085}
16086
16087#[inline]
16088#[must_use]
16089pub const fn const_ring_eval_w2048(op: PrimitiveOp, a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
16090    match op {
16091        PrimitiveOp::Add => a.wrapping_add(b),
16092        PrimitiveOp::Sub => a.wrapping_sub(b),
16093        PrimitiveOp::Mul => a.wrapping_mul(b),
16094        PrimitiveOp::And => a.and(b),
16095        PrimitiveOp::Or => a.or(b),
16096        PrimitiveOp::Xor => a.xor(b),
16097        PrimitiveOp::Neg => Limbs::<32>::zero().wrapping_sub(a),
16098        PrimitiveOp::Bnot => a.not(),
16099        PrimitiveOp::Succ => a.wrapping_add(limbs_one_32()),
16100        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_32()),
16101        PrimitiveOp::Le => {
16102            if limbs_le_32(a, b) {
16103                limbs_one_32()
16104            } else {
16105                Limbs::<32>::zero()
16106            }
16107        }
16108        PrimitiveOp::Lt => {
16109            if limbs_lt_32(a, b) {
16110                limbs_one_32()
16111            } else {
16112                Limbs::<32>::zero()
16113            }
16114        }
16115        PrimitiveOp::Ge => {
16116            if limbs_le_32(b, a) {
16117                limbs_one_32()
16118            } else {
16119                Limbs::<32>::zero()
16120            }
16121        }
16122        PrimitiveOp::Gt => {
16123            if limbs_lt_32(b, a) {
16124                limbs_one_32()
16125            } else {
16126                Limbs::<32>::zero()
16127            }
16128        }
16129        PrimitiveOp::Concat => Limbs::<32>::zero(),
16130        PrimitiveOp::Div => {
16131            if limbs_is_zero_32(b) {
16132                Limbs::<32>::zero()
16133            } else {
16134                limbs_div_32(a, b)
16135            }
16136        }
16137        PrimitiveOp::Mod => {
16138            if limbs_is_zero_32(b) {
16139                Limbs::<32>::zero()
16140            } else {
16141                limbs_mod_32(a, b)
16142            }
16143        }
16144        PrimitiveOp::Pow => limbs_pow_32(a, b),
16145    }
16146}
16147
16148#[inline]
16149#[must_use]
16150pub const fn const_ring_eval_w4096(op: PrimitiveOp, a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
16151    match op {
16152        PrimitiveOp::Add => a.wrapping_add(b),
16153        PrimitiveOp::Sub => a.wrapping_sub(b),
16154        PrimitiveOp::Mul => a.wrapping_mul(b),
16155        PrimitiveOp::And => a.and(b),
16156        PrimitiveOp::Or => a.or(b),
16157        PrimitiveOp::Xor => a.xor(b),
16158        PrimitiveOp::Neg => Limbs::<64>::zero().wrapping_sub(a),
16159        PrimitiveOp::Bnot => a.not(),
16160        PrimitiveOp::Succ => a.wrapping_add(limbs_one_64()),
16161        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_64()),
16162        PrimitiveOp::Le => {
16163            if limbs_le_64(a, b) {
16164                limbs_one_64()
16165            } else {
16166                Limbs::<64>::zero()
16167            }
16168        }
16169        PrimitiveOp::Lt => {
16170            if limbs_lt_64(a, b) {
16171                limbs_one_64()
16172            } else {
16173                Limbs::<64>::zero()
16174            }
16175        }
16176        PrimitiveOp::Ge => {
16177            if limbs_le_64(b, a) {
16178                limbs_one_64()
16179            } else {
16180                Limbs::<64>::zero()
16181            }
16182        }
16183        PrimitiveOp::Gt => {
16184            if limbs_lt_64(b, a) {
16185                limbs_one_64()
16186            } else {
16187                Limbs::<64>::zero()
16188            }
16189        }
16190        PrimitiveOp::Concat => Limbs::<64>::zero(),
16191        PrimitiveOp::Div => {
16192            if limbs_is_zero_64(b) {
16193                Limbs::<64>::zero()
16194            } else {
16195                limbs_div_64(a, b)
16196            }
16197        }
16198        PrimitiveOp::Mod => {
16199            if limbs_is_zero_64(b) {
16200                Limbs::<64>::zero()
16201            } else {
16202                limbs_mod_64(a, b)
16203            }
16204        }
16205        PrimitiveOp::Pow => limbs_pow_64(a, b),
16206    }
16207}
16208
16209#[inline]
16210#[must_use]
16211pub const fn const_ring_eval_w8192(op: PrimitiveOp, a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
16212    match op {
16213        PrimitiveOp::Add => a.wrapping_add(b),
16214        PrimitiveOp::Sub => a.wrapping_sub(b),
16215        PrimitiveOp::Mul => a.wrapping_mul(b),
16216        PrimitiveOp::And => a.and(b),
16217        PrimitiveOp::Or => a.or(b),
16218        PrimitiveOp::Xor => a.xor(b),
16219        PrimitiveOp::Neg => Limbs::<128>::zero().wrapping_sub(a),
16220        PrimitiveOp::Bnot => a.not(),
16221        PrimitiveOp::Succ => a.wrapping_add(limbs_one_128()),
16222        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_128()),
16223        PrimitiveOp::Le => {
16224            if limbs_le_128(a, b) {
16225                limbs_one_128()
16226            } else {
16227                Limbs::<128>::zero()
16228            }
16229        }
16230        PrimitiveOp::Lt => {
16231            if limbs_lt_128(a, b) {
16232                limbs_one_128()
16233            } else {
16234                Limbs::<128>::zero()
16235            }
16236        }
16237        PrimitiveOp::Ge => {
16238            if limbs_le_128(b, a) {
16239                limbs_one_128()
16240            } else {
16241                Limbs::<128>::zero()
16242            }
16243        }
16244        PrimitiveOp::Gt => {
16245            if limbs_lt_128(b, a) {
16246                limbs_one_128()
16247            } else {
16248                Limbs::<128>::zero()
16249            }
16250        }
16251        PrimitiveOp::Concat => Limbs::<128>::zero(),
16252        PrimitiveOp::Div => {
16253            if limbs_is_zero_128(b) {
16254                Limbs::<128>::zero()
16255            } else {
16256                limbs_div_128(a, b)
16257            }
16258        }
16259        PrimitiveOp::Mod => {
16260            if limbs_is_zero_128(b) {
16261                Limbs::<128>::zero()
16262            } else {
16263                limbs_mod_128(a, b)
16264            }
16265        }
16266        PrimitiveOp::Pow => limbs_pow_128(a, b),
16267    }
16268}
16269
16270#[inline]
16271#[must_use]
16272pub const fn const_ring_eval_w12288(op: PrimitiveOp, a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
16273    match op {
16274        PrimitiveOp::Add => a.wrapping_add(b),
16275        PrimitiveOp::Sub => a.wrapping_sub(b),
16276        PrimitiveOp::Mul => a.wrapping_mul(b),
16277        PrimitiveOp::And => a.and(b),
16278        PrimitiveOp::Or => a.or(b),
16279        PrimitiveOp::Xor => a.xor(b),
16280        PrimitiveOp::Neg => Limbs::<192>::zero().wrapping_sub(a),
16281        PrimitiveOp::Bnot => a.not(),
16282        PrimitiveOp::Succ => a.wrapping_add(limbs_one_192()),
16283        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_192()),
16284        PrimitiveOp::Le => {
16285            if limbs_le_192(a, b) {
16286                limbs_one_192()
16287            } else {
16288                Limbs::<192>::zero()
16289            }
16290        }
16291        PrimitiveOp::Lt => {
16292            if limbs_lt_192(a, b) {
16293                limbs_one_192()
16294            } else {
16295                Limbs::<192>::zero()
16296            }
16297        }
16298        PrimitiveOp::Ge => {
16299            if limbs_le_192(b, a) {
16300                limbs_one_192()
16301            } else {
16302                Limbs::<192>::zero()
16303            }
16304        }
16305        PrimitiveOp::Gt => {
16306            if limbs_lt_192(b, a) {
16307                limbs_one_192()
16308            } else {
16309                Limbs::<192>::zero()
16310            }
16311        }
16312        PrimitiveOp::Concat => Limbs::<192>::zero(),
16313        PrimitiveOp::Div => {
16314            if limbs_is_zero_192(b) {
16315                Limbs::<192>::zero()
16316            } else {
16317                limbs_div_192(a, b)
16318            }
16319        }
16320        PrimitiveOp::Mod => {
16321            if limbs_is_zero_192(b) {
16322                Limbs::<192>::zero()
16323            } else {
16324                limbs_mod_192(a, b)
16325            }
16326        }
16327        PrimitiveOp::Pow => limbs_pow_192(a, b),
16328    }
16329}
16330
16331#[inline]
16332#[must_use]
16333pub const fn const_ring_eval_w16384(op: PrimitiveOp, a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
16334    match op {
16335        PrimitiveOp::Add => a.wrapping_add(b),
16336        PrimitiveOp::Sub => a.wrapping_sub(b),
16337        PrimitiveOp::Mul => a.wrapping_mul(b),
16338        PrimitiveOp::And => a.and(b),
16339        PrimitiveOp::Or => a.or(b),
16340        PrimitiveOp::Xor => a.xor(b),
16341        PrimitiveOp::Neg => Limbs::<256>::zero().wrapping_sub(a),
16342        PrimitiveOp::Bnot => a.not(),
16343        PrimitiveOp::Succ => a.wrapping_add(limbs_one_256()),
16344        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_256()),
16345        PrimitiveOp::Le => {
16346            if limbs_le_256(a, b) {
16347                limbs_one_256()
16348            } else {
16349                Limbs::<256>::zero()
16350            }
16351        }
16352        PrimitiveOp::Lt => {
16353            if limbs_lt_256(a, b) {
16354                limbs_one_256()
16355            } else {
16356                Limbs::<256>::zero()
16357            }
16358        }
16359        PrimitiveOp::Ge => {
16360            if limbs_le_256(b, a) {
16361                limbs_one_256()
16362            } else {
16363                Limbs::<256>::zero()
16364            }
16365        }
16366        PrimitiveOp::Gt => {
16367            if limbs_lt_256(b, a) {
16368                limbs_one_256()
16369            } else {
16370                Limbs::<256>::zero()
16371            }
16372        }
16373        PrimitiveOp::Concat => Limbs::<256>::zero(),
16374        PrimitiveOp::Div => {
16375            if limbs_is_zero_256(b) {
16376                Limbs::<256>::zero()
16377            } else {
16378                limbs_div_256(a, b)
16379            }
16380        }
16381        PrimitiveOp::Mod => {
16382            if limbs_is_zero_256(b) {
16383                Limbs::<256>::zero()
16384            } else {
16385                limbs_mod_256(a, b)
16386            }
16387        }
16388        PrimitiveOp::Pow => limbs_pow_256(a, b),
16389    }
16390}
16391
16392#[inline]
16393#[must_use]
16394pub const fn const_ring_eval_w32768(op: PrimitiveOp, a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
16395    match op {
16396        PrimitiveOp::Add => a.wrapping_add(b),
16397        PrimitiveOp::Sub => a.wrapping_sub(b),
16398        PrimitiveOp::Mul => a.wrapping_mul(b),
16399        PrimitiveOp::And => a.and(b),
16400        PrimitiveOp::Or => a.or(b),
16401        PrimitiveOp::Xor => a.xor(b),
16402        PrimitiveOp::Neg => Limbs::<512>::zero().wrapping_sub(a),
16403        PrimitiveOp::Bnot => a.not(),
16404        PrimitiveOp::Succ => a.wrapping_add(limbs_one_512()),
16405        PrimitiveOp::Pred => a.wrapping_sub(limbs_one_512()),
16406        PrimitiveOp::Le => {
16407            if limbs_le_512(a, b) {
16408                limbs_one_512()
16409            } else {
16410                Limbs::<512>::zero()
16411            }
16412        }
16413        PrimitiveOp::Lt => {
16414            if limbs_lt_512(a, b) {
16415                limbs_one_512()
16416            } else {
16417                Limbs::<512>::zero()
16418            }
16419        }
16420        PrimitiveOp::Ge => {
16421            if limbs_le_512(b, a) {
16422                limbs_one_512()
16423            } else {
16424                Limbs::<512>::zero()
16425            }
16426        }
16427        PrimitiveOp::Gt => {
16428            if limbs_lt_512(b, a) {
16429                limbs_one_512()
16430            } else {
16431                Limbs::<512>::zero()
16432            }
16433        }
16434        PrimitiveOp::Concat => Limbs::<512>::zero(),
16435        PrimitiveOp::Div => {
16436            if limbs_is_zero_512(b) {
16437                Limbs::<512>::zero()
16438            } else {
16439                limbs_div_512(a, b)
16440            }
16441        }
16442        PrimitiveOp::Mod => {
16443            if limbs_is_zero_512(b) {
16444                Limbs::<512>::zero()
16445            } else {
16446                limbs_mod_512(a, b)
16447            }
16448        }
16449        PrimitiveOp::Pow => limbs_pow_512(a, b),
16450    }
16451}
16452
16453/// Phase L.2: one-constant helpers for `Limbs<N>::from_words([1, 0, ...])`.
16454#[inline]
16455#[must_use]
16456const fn limbs_one_3() -> Limbs<3> {
16457    Limbs::<3>::from_words([1u64, 0u64, 0u64])
16458}
16459
16460#[inline]
16461#[must_use]
16462const fn limbs_one_4() -> Limbs<4> {
16463    Limbs::<4>::from_words([1u64, 0u64, 0u64, 0u64])
16464}
16465
16466#[inline]
16467#[must_use]
16468const fn limbs_one_6() -> Limbs<6> {
16469    Limbs::<6>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16470}
16471
16472#[inline]
16473#[must_use]
16474const fn limbs_one_7() -> Limbs<7> {
16475    Limbs::<7>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16476}
16477
16478#[inline]
16479#[must_use]
16480const fn limbs_one_8() -> Limbs<8> {
16481    Limbs::<8>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16482}
16483
16484#[inline]
16485#[must_use]
16486const fn limbs_one_9() -> Limbs<9> {
16487    Limbs::<9>::from_words([1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64])
16488}
16489
16490#[inline]
16491#[must_use]
16492const fn limbs_one_16() -> Limbs<16> {
16493    Limbs::<16>::from_words([
16494        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16495        0u64,
16496    ])
16497}
16498
16499#[inline]
16500#[must_use]
16501const fn limbs_one_32() -> Limbs<32> {
16502    Limbs::<32>::from_words([
16503        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16504        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16505        0u64, 0u64,
16506    ])
16507}
16508
16509#[inline]
16510#[must_use]
16511const fn limbs_one_64() -> Limbs<64> {
16512    Limbs::<64>::from_words([
16513        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16514        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16515        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16516        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16517        0u64, 0u64, 0u64, 0u64,
16518    ])
16519}
16520
16521#[inline]
16522#[must_use]
16523const fn limbs_one_128() -> Limbs<128> {
16524    Limbs::<128>::from_words([
16525        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16526        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16527        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16528        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16529        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16530        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16531        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16532        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16533        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16534    ])
16535}
16536
16537#[inline]
16538#[must_use]
16539const fn limbs_one_192() -> Limbs<192> {
16540    Limbs::<192>::from_words([
16541        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16542        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16543        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16544        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16545        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16546        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16547        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16548        0u64, 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,
16554    ])
16555}
16556
16557#[inline]
16558#[must_use]
16559const fn limbs_one_256() -> Limbs<256> {
16560    Limbs::<256>::from_words([
16561        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16562        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16563        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16564        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16565        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16566        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16567        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16568        0u64, 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,
16579    ])
16580}
16581
16582#[inline]
16583#[must_use]
16584const fn limbs_one_512() -> Limbs<512> {
16585    Limbs::<512>::from_words([
16586        1u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16587        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16588        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16589        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16590        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16591        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16592        0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64,
16593        0u64, 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,
16621    ])
16622}
16623
16624/// ADR-013/TR-08: const-fn limb comparisons used by `const_ring_eval_w{n}`
16625/// to lift the comparison primitives to 0/1-valued ring indicators.
16626#[inline]
16627#[must_use]
16628const fn limbs_lt_3(a: Limbs<3>, b: Limbs<3>) -> bool {
16629    let aw = a.words();
16630    let bw = b.words();
16631    let mut i = 3;
16632    while i > 0 {
16633        i -= 1;
16634        if aw[i] < bw[i] {
16635            return true;
16636        }
16637        if aw[i] > bw[i] {
16638            return false;
16639        }
16640    }
16641    false
16642}
16643
16644#[inline]
16645#[must_use]
16646const fn limbs_le_3(a: Limbs<3>, b: Limbs<3>) -> bool {
16647    let aw = a.words();
16648    let bw = b.words();
16649    let mut i = 3;
16650    while i > 0 {
16651        i -= 1;
16652        if aw[i] < bw[i] {
16653            return true;
16654        }
16655        if aw[i] > bw[i] {
16656            return false;
16657        }
16658    }
16659    true
16660}
16661
16662#[inline]
16663#[must_use]
16664const fn limbs_lt_4(a: Limbs<4>, b: Limbs<4>) -> bool {
16665    let aw = a.words();
16666    let bw = b.words();
16667    let mut i = 4;
16668    while i > 0 {
16669        i -= 1;
16670        if aw[i] < bw[i] {
16671            return true;
16672        }
16673        if aw[i] > bw[i] {
16674            return false;
16675        }
16676    }
16677    false
16678}
16679
16680#[inline]
16681#[must_use]
16682const fn limbs_le_4(a: Limbs<4>, b: Limbs<4>) -> bool {
16683    let aw = a.words();
16684    let bw = b.words();
16685    let mut i = 4;
16686    while i > 0 {
16687        i -= 1;
16688        if aw[i] < bw[i] {
16689            return true;
16690        }
16691        if aw[i] > bw[i] {
16692            return false;
16693        }
16694    }
16695    true
16696}
16697
16698#[inline]
16699#[must_use]
16700const fn limbs_lt_6(a: Limbs<6>, b: Limbs<6>) -> bool {
16701    let aw = a.words();
16702    let bw = b.words();
16703    let mut i = 6;
16704    while i > 0 {
16705        i -= 1;
16706        if aw[i] < bw[i] {
16707            return true;
16708        }
16709        if aw[i] > bw[i] {
16710            return false;
16711        }
16712    }
16713    false
16714}
16715
16716#[inline]
16717#[must_use]
16718const fn limbs_le_6(a: Limbs<6>, b: Limbs<6>) -> bool {
16719    let aw = a.words();
16720    let bw = b.words();
16721    let mut i = 6;
16722    while i > 0 {
16723        i -= 1;
16724        if aw[i] < bw[i] {
16725            return true;
16726        }
16727        if aw[i] > bw[i] {
16728            return false;
16729        }
16730    }
16731    true
16732}
16733
16734#[inline]
16735#[must_use]
16736const fn limbs_lt_7(a: Limbs<7>, b: Limbs<7>) -> bool {
16737    let aw = a.words();
16738    let bw = b.words();
16739    let mut i = 7;
16740    while i > 0 {
16741        i -= 1;
16742        if aw[i] < bw[i] {
16743            return true;
16744        }
16745        if aw[i] > bw[i] {
16746            return false;
16747        }
16748    }
16749    false
16750}
16751
16752#[inline]
16753#[must_use]
16754const fn limbs_le_7(a: Limbs<7>, b: Limbs<7>) -> bool {
16755    let aw = a.words();
16756    let bw = b.words();
16757    let mut i = 7;
16758    while i > 0 {
16759        i -= 1;
16760        if aw[i] < bw[i] {
16761            return true;
16762        }
16763        if aw[i] > bw[i] {
16764            return false;
16765        }
16766    }
16767    true
16768}
16769
16770#[inline]
16771#[must_use]
16772const fn limbs_lt_8(a: Limbs<8>, b: Limbs<8>) -> bool {
16773    let aw = a.words();
16774    let bw = b.words();
16775    let mut i = 8;
16776    while i > 0 {
16777        i -= 1;
16778        if aw[i] < bw[i] {
16779            return true;
16780        }
16781        if aw[i] > bw[i] {
16782            return false;
16783        }
16784    }
16785    false
16786}
16787
16788#[inline]
16789#[must_use]
16790const fn limbs_le_8(a: Limbs<8>, b: Limbs<8>) -> bool {
16791    let aw = a.words();
16792    let bw = b.words();
16793    let mut i = 8;
16794    while i > 0 {
16795        i -= 1;
16796        if aw[i] < bw[i] {
16797            return true;
16798        }
16799        if aw[i] > bw[i] {
16800            return false;
16801        }
16802    }
16803    true
16804}
16805
16806#[inline]
16807#[must_use]
16808const fn limbs_lt_9(a: Limbs<9>, b: Limbs<9>) -> bool {
16809    let aw = a.words();
16810    let bw = b.words();
16811    let mut i = 9;
16812    while i > 0 {
16813        i -= 1;
16814        if aw[i] < bw[i] {
16815            return true;
16816        }
16817        if aw[i] > bw[i] {
16818            return false;
16819        }
16820    }
16821    false
16822}
16823
16824#[inline]
16825#[must_use]
16826const fn limbs_le_9(a: Limbs<9>, b: Limbs<9>) -> bool {
16827    let aw = a.words();
16828    let bw = b.words();
16829    let mut i = 9;
16830    while i > 0 {
16831        i -= 1;
16832        if aw[i] < bw[i] {
16833            return true;
16834        }
16835        if aw[i] > bw[i] {
16836            return false;
16837        }
16838    }
16839    true
16840}
16841
16842#[inline]
16843#[must_use]
16844const fn limbs_lt_16(a: Limbs<16>, b: Limbs<16>) -> bool {
16845    let aw = a.words();
16846    let bw = b.words();
16847    let mut i = 16;
16848    while i > 0 {
16849        i -= 1;
16850        if aw[i] < bw[i] {
16851            return true;
16852        }
16853        if aw[i] > bw[i] {
16854            return false;
16855        }
16856    }
16857    false
16858}
16859
16860#[inline]
16861#[must_use]
16862const fn limbs_le_16(a: Limbs<16>, b: Limbs<16>) -> bool {
16863    let aw = a.words();
16864    let bw = b.words();
16865    let mut i = 16;
16866    while i > 0 {
16867        i -= 1;
16868        if aw[i] < bw[i] {
16869            return true;
16870        }
16871        if aw[i] > bw[i] {
16872            return false;
16873        }
16874    }
16875    true
16876}
16877
16878#[inline]
16879#[must_use]
16880const fn limbs_lt_32(a: Limbs<32>, b: Limbs<32>) -> bool {
16881    let aw = a.words();
16882    let bw = b.words();
16883    let mut i = 32;
16884    while i > 0 {
16885        i -= 1;
16886        if aw[i] < bw[i] {
16887            return true;
16888        }
16889        if aw[i] > bw[i] {
16890            return false;
16891        }
16892    }
16893    false
16894}
16895
16896#[inline]
16897#[must_use]
16898const fn limbs_le_32(a: Limbs<32>, b: Limbs<32>) -> bool {
16899    let aw = a.words();
16900    let bw = b.words();
16901    let mut i = 32;
16902    while i > 0 {
16903        i -= 1;
16904        if aw[i] < bw[i] {
16905            return true;
16906        }
16907        if aw[i] > bw[i] {
16908            return false;
16909        }
16910    }
16911    true
16912}
16913
16914#[inline]
16915#[must_use]
16916const fn limbs_lt_64(a: Limbs<64>, b: Limbs<64>) -> bool {
16917    let aw = a.words();
16918    let bw = b.words();
16919    let mut i = 64;
16920    while i > 0 {
16921        i -= 1;
16922        if aw[i] < bw[i] {
16923            return true;
16924        }
16925        if aw[i] > bw[i] {
16926            return false;
16927        }
16928    }
16929    false
16930}
16931
16932#[inline]
16933#[must_use]
16934const fn limbs_le_64(a: Limbs<64>, b: Limbs<64>) -> bool {
16935    let aw = a.words();
16936    let bw = b.words();
16937    let mut i = 64;
16938    while i > 0 {
16939        i -= 1;
16940        if aw[i] < bw[i] {
16941            return true;
16942        }
16943        if aw[i] > bw[i] {
16944            return false;
16945        }
16946    }
16947    true
16948}
16949
16950#[inline]
16951#[must_use]
16952const fn limbs_lt_128(a: Limbs<128>, b: Limbs<128>) -> bool {
16953    let aw = a.words();
16954    let bw = b.words();
16955    let mut i = 128;
16956    while i > 0 {
16957        i -= 1;
16958        if aw[i] < bw[i] {
16959            return true;
16960        }
16961        if aw[i] > bw[i] {
16962            return false;
16963        }
16964    }
16965    false
16966}
16967
16968#[inline]
16969#[must_use]
16970const fn limbs_le_128(a: Limbs<128>, b: Limbs<128>) -> bool {
16971    let aw = a.words();
16972    let bw = b.words();
16973    let mut i = 128;
16974    while i > 0 {
16975        i -= 1;
16976        if aw[i] < bw[i] {
16977            return true;
16978        }
16979        if aw[i] > bw[i] {
16980            return false;
16981        }
16982    }
16983    true
16984}
16985
16986#[inline]
16987#[must_use]
16988const fn limbs_lt_192(a: Limbs<192>, b: Limbs<192>) -> bool {
16989    let aw = a.words();
16990    let bw = b.words();
16991    let mut i = 192;
16992    while i > 0 {
16993        i -= 1;
16994        if aw[i] < bw[i] {
16995            return true;
16996        }
16997        if aw[i] > bw[i] {
16998            return false;
16999        }
17000    }
17001    false
17002}
17003
17004#[inline]
17005#[must_use]
17006const fn limbs_le_192(a: Limbs<192>, b: Limbs<192>) -> bool {
17007    let aw = a.words();
17008    let bw = b.words();
17009    let mut i = 192;
17010    while i > 0 {
17011        i -= 1;
17012        if aw[i] < bw[i] {
17013            return true;
17014        }
17015        if aw[i] > bw[i] {
17016            return false;
17017        }
17018    }
17019    true
17020}
17021
17022#[inline]
17023#[must_use]
17024const fn limbs_lt_256(a: Limbs<256>, b: Limbs<256>) -> bool {
17025    let aw = a.words();
17026    let bw = b.words();
17027    let mut i = 256;
17028    while i > 0 {
17029        i -= 1;
17030        if aw[i] < bw[i] {
17031            return true;
17032        }
17033        if aw[i] > bw[i] {
17034            return false;
17035        }
17036    }
17037    false
17038}
17039
17040#[inline]
17041#[must_use]
17042const fn limbs_le_256(a: Limbs<256>, b: Limbs<256>) -> bool {
17043    let aw = a.words();
17044    let bw = b.words();
17045    let mut i = 256;
17046    while i > 0 {
17047        i -= 1;
17048        if aw[i] < bw[i] {
17049            return true;
17050        }
17051        if aw[i] > bw[i] {
17052            return false;
17053        }
17054    }
17055    true
17056}
17057
17058#[inline]
17059#[must_use]
17060const fn limbs_lt_512(a: Limbs<512>, b: Limbs<512>) -> bool {
17061    let aw = a.words();
17062    let bw = b.words();
17063    let mut i = 512;
17064    while i > 0 {
17065        i -= 1;
17066        if aw[i] < bw[i] {
17067            return true;
17068        }
17069        if aw[i] > bw[i] {
17070            return false;
17071        }
17072    }
17073    false
17074}
17075
17076#[inline]
17077#[must_use]
17078const fn limbs_le_512(a: Limbs<512>, b: Limbs<512>) -> bool {
17079    let aw = a.words();
17080    let bw = b.words();
17081    let mut i = 512;
17082    while i > 0 {
17083        i -= 1;
17084        if aw[i] < bw[i] {
17085            return true;
17086        }
17087        if aw[i] > bw[i] {
17088            return false;
17089        }
17090    }
17091    true
17092}
17093
17094/// ADR-053: zero-check, binary-long-division, and square-and-multiply
17095/// helpers used by the const-fn `Div`/`Mod`/`Pow` arms of `const_ring_eval_w{n}`.
17096#[inline]
17097#[must_use]
17098const fn limbs_is_zero_3(a: Limbs<3>) -> bool {
17099    let aw = a.words();
17100    let mut i = 0usize;
17101    while i < 3 {
17102        if aw[i] != 0 {
17103            return false;
17104        }
17105        i += 1;
17106    }
17107    true
17108}
17109
17110#[inline]
17111#[must_use]
17112const fn limbs_shl1_3(a: Limbs<3>) -> Limbs<3> {
17113    let aw = a.words();
17114    let mut out = [0u64; 3];
17115    let mut carry: u64 = 0;
17116    let mut i = 0usize;
17117    while i < 3 {
17118        let v = aw[i];
17119        out[i] = (v << 1) | carry;
17120        carry = v >> 63;
17121        i += 1;
17122    }
17123    Limbs::<3>::from_words(out)
17124}
17125
17126#[inline]
17127#[must_use]
17128const fn limbs_set_bit0_3(a: Limbs<3>) -> Limbs<3> {
17129    let aw = a.words();
17130    let mut out = [0u64; 3];
17131    let mut i = 0usize;
17132    while i < 3 {
17133        out[i] = aw[i];
17134        i += 1;
17135    }
17136    out[0] |= 1u64;
17137    Limbs::<3>::from_words(out)
17138}
17139
17140#[inline]
17141#[must_use]
17142const fn limbs_bit_msb_3(a: Limbs<3>, msb_index: usize) -> u64 {
17143    let aw = a.words();
17144    let total_bits = 3 * 64;
17145    let lsb_index = total_bits - 1 - msb_index;
17146    let word = lsb_index / 64;
17147    let bit = lsb_index % 64;
17148    (aw[word] >> bit) & 1u64
17149}
17150
17151#[inline]
17152#[must_use]
17153const fn limbs_divmod_3(a: Limbs<3>, b: Limbs<3>) -> (Limbs<3>, Limbs<3>) {
17154    let mut q = Limbs::<3>::zero();
17155    let mut r = Limbs::<3>::zero();
17156    let total_bits = 3 * 64;
17157    let mut i = 0usize;
17158    while i < total_bits {
17159        r = limbs_shl1_3(r);
17160        if limbs_bit_msb_3(a, i) == 1 {
17161            r = limbs_set_bit0_3(r);
17162        }
17163        if limbs_le_3(b, r) {
17164            r = r.wrapping_sub(b);
17165            q = limbs_shl1_3(q);
17166            q = limbs_set_bit0_3(q);
17167        } else {
17168            q = limbs_shl1_3(q);
17169        }
17170        i += 1;
17171    }
17172    (q, r)
17173}
17174
17175#[inline]
17176#[must_use]
17177const fn limbs_div_3(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
17178    let (q, _) = limbs_divmod_3(a, b);
17179    q
17180}
17181
17182#[inline]
17183#[must_use]
17184const fn limbs_mod_3(a: Limbs<3>, b: Limbs<3>) -> Limbs<3> {
17185    let (_, r) = limbs_divmod_3(a, b);
17186    r
17187}
17188
17189#[inline]
17190#[must_use]
17191const fn limbs_pow_3(base: Limbs<3>, exp: Limbs<3>) -> Limbs<3> {
17192    let mut result = limbs_one_3();
17193    let mut b = base;
17194    let ew = exp.words();
17195    let mut word = 0usize;
17196    while word < 3 {
17197        let mut bit = 0u32;
17198        while bit < 64 {
17199            if ((ew[word] >> bit) & 1u64) == 1u64 {
17200                result = result.wrapping_mul(b);
17201            }
17202            b = b.wrapping_mul(b);
17203            bit += 1;
17204        }
17205        word += 1;
17206    }
17207    result
17208}
17209
17210#[inline]
17211#[must_use]
17212const fn limbs_is_zero_4(a: Limbs<4>) -> bool {
17213    let aw = a.words();
17214    let mut i = 0usize;
17215    while i < 4 {
17216        if aw[i] != 0 {
17217            return false;
17218        }
17219        i += 1;
17220    }
17221    true
17222}
17223
17224#[inline]
17225#[must_use]
17226const fn limbs_shl1_4(a: Limbs<4>) -> Limbs<4> {
17227    let aw = a.words();
17228    let mut out = [0u64; 4];
17229    let mut carry: u64 = 0;
17230    let mut i = 0usize;
17231    while i < 4 {
17232        let v = aw[i];
17233        out[i] = (v << 1) | carry;
17234        carry = v >> 63;
17235        i += 1;
17236    }
17237    Limbs::<4>::from_words(out)
17238}
17239
17240#[inline]
17241#[must_use]
17242const fn limbs_set_bit0_4(a: Limbs<4>) -> Limbs<4> {
17243    let aw = a.words();
17244    let mut out = [0u64; 4];
17245    let mut i = 0usize;
17246    while i < 4 {
17247        out[i] = aw[i];
17248        i += 1;
17249    }
17250    out[0] |= 1u64;
17251    Limbs::<4>::from_words(out)
17252}
17253
17254#[inline]
17255#[must_use]
17256const fn limbs_bit_msb_4(a: Limbs<4>, msb_index: usize) -> u64 {
17257    let aw = a.words();
17258    let total_bits = 4 * 64;
17259    let lsb_index = total_bits - 1 - msb_index;
17260    let word = lsb_index / 64;
17261    let bit = lsb_index % 64;
17262    (aw[word] >> bit) & 1u64
17263}
17264
17265#[inline]
17266#[must_use]
17267const fn limbs_divmod_4(a: Limbs<4>, b: Limbs<4>) -> (Limbs<4>, Limbs<4>) {
17268    let mut q = Limbs::<4>::zero();
17269    let mut r = Limbs::<4>::zero();
17270    let total_bits = 4 * 64;
17271    let mut i = 0usize;
17272    while i < total_bits {
17273        r = limbs_shl1_4(r);
17274        if limbs_bit_msb_4(a, i) == 1 {
17275            r = limbs_set_bit0_4(r);
17276        }
17277        if limbs_le_4(b, r) {
17278            r = r.wrapping_sub(b);
17279            q = limbs_shl1_4(q);
17280            q = limbs_set_bit0_4(q);
17281        } else {
17282            q = limbs_shl1_4(q);
17283        }
17284        i += 1;
17285    }
17286    (q, r)
17287}
17288
17289#[inline]
17290#[must_use]
17291const fn limbs_div_4(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
17292    let (q, _) = limbs_divmod_4(a, b);
17293    q
17294}
17295
17296#[inline]
17297#[must_use]
17298const fn limbs_mod_4(a: Limbs<4>, b: Limbs<4>) -> Limbs<4> {
17299    let (_, r) = limbs_divmod_4(a, b);
17300    r
17301}
17302
17303#[inline]
17304#[must_use]
17305const fn limbs_pow_4(base: Limbs<4>, exp: Limbs<4>) -> Limbs<4> {
17306    let mut result = limbs_one_4();
17307    let mut b = base;
17308    let ew = exp.words();
17309    let mut word = 0usize;
17310    while word < 4 {
17311        let mut bit = 0u32;
17312        while bit < 64 {
17313            if ((ew[word] >> bit) & 1u64) == 1u64 {
17314                result = result.wrapping_mul(b);
17315            }
17316            b = b.wrapping_mul(b);
17317            bit += 1;
17318        }
17319        word += 1;
17320    }
17321    result
17322}
17323
17324#[inline]
17325#[must_use]
17326const fn limbs_is_zero_6(a: Limbs<6>) -> bool {
17327    let aw = a.words();
17328    let mut i = 0usize;
17329    while i < 6 {
17330        if aw[i] != 0 {
17331            return false;
17332        }
17333        i += 1;
17334    }
17335    true
17336}
17337
17338#[inline]
17339#[must_use]
17340const fn limbs_shl1_6(a: Limbs<6>) -> Limbs<6> {
17341    let aw = a.words();
17342    let mut out = [0u64; 6];
17343    let mut carry: u64 = 0;
17344    let mut i = 0usize;
17345    while i < 6 {
17346        let v = aw[i];
17347        out[i] = (v << 1) | carry;
17348        carry = v >> 63;
17349        i += 1;
17350    }
17351    Limbs::<6>::from_words(out)
17352}
17353
17354#[inline]
17355#[must_use]
17356const fn limbs_set_bit0_6(a: Limbs<6>) -> Limbs<6> {
17357    let aw = a.words();
17358    let mut out = [0u64; 6];
17359    let mut i = 0usize;
17360    while i < 6 {
17361        out[i] = aw[i];
17362        i += 1;
17363    }
17364    out[0] |= 1u64;
17365    Limbs::<6>::from_words(out)
17366}
17367
17368#[inline]
17369#[must_use]
17370const fn limbs_bit_msb_6(a: Limbs<6>, msb_index: usize) -> u64 {
17371    let aw = a.words();
17372    let total_bits = 6 * 64;
17373    let lsb_index = total_bits - 1 - msb_index;
17374    let word = lsb_index / 64;
17375    let bit = lsb_index % 64;
17376    (aw[word] >> bit) & 1u64
17377}
17378
17379#[inline]
17380#[must_use]
17381const fn limbs_divmod_6(a: Limbs<6>, b: Limbs<6>) -> (Limbs<6>, Limbs<6>) {
17382    let mut q = Limbs::<6>::zero();
17383    let mut r = Limbs::<6>::zero();
17384    let total_bits = 6 * 64;
17385    let mut i = 0usize;
17386    while i < total_bits {
17387        r = limbs_shl1_6(r);
17388        if limbs_bit_msb_6(a, i) == 1 {
17389            r = limbs_set_bit0_6(r);
17390        }
17391        if limbs_le_6(b, r) {
17392            r = r.wrapping_sub(b);
17393            q = limbs_shl1_6(q);
17394            q = limbs_set_bit0_6(q);
17395        } else {
17396            q = limbs_shl1_6(q);
17397        }
17398        i += 1;
17399    }
17400    (q, r)
17401}
17402
17403#[inline]
17404#[must_use]
17405const fn limbs_div_6(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
17406    let (q, _) = limbs_divmod_6(a, b);
17407    q
17408}
17409
17410#[inline]
17411#[must_use]
17412const fn limbs_mod_6(a: Limbs<6>, b: Limbs<6>) -> Limbs<6> {
17413    let (_, r) = limbs_divmod_6(a, b);
17414    r
17415}
17416
17417#[inline]
17418#[must_use]
17419const fn limbs_pow_6(base: Limbs<6>, exp: Limbs<6>) -> Limbs<6> {
17420    let mut result = limbs_one_6();
17421    let mut b = base;
17422    let ew = exp.words();
17423    let mut word = 0usize;
17424    while word < 6 {
17425        let mut bit = 0u32;
17426        while bit < 64 {
17427            if ((ew[word] >> bit) & 1u64) == 1u64 {
17428                result = result.wrapping_mul(b);
17429            }
17430            b = b.wrapping_mul(b);
17431            bit += 1;
17432        }
17433        word += 1;
17434    }
17435    result
17436}
17437
17438#[inline]
17439#[must_use]
17440const fn limbs_is_zero_7(a: Limbs<7>) -> bool {
17441    let aw = a.words();
17442    let mut i = 0usize;
17443    while i < 7 {
17444        if aw[i] != 0 {
17445            return false;
17446        }
17447        i += 1;
17448    }
17449    true
17450}
17451
17452#[inline]
17453#[must_use]
17454const fn limbs_shl1_7(a: Limbs<7>) -> Limbs<7> {
17455    let aw = a.words();
17456    let mut out = [0u64; 7];
17457    let mut carry: u64 = 0;
17458    let mut i = 0usize;
17459    while i < 7 {
17460        let v = aw[i];
17461        out[i] = (v << 1) | carry;
17462        carry = v >> 63;
17463        i += 1;
17464    }
17465    Limbs::<7>::from_words(out)
17466}
17467
17468#[inline]
17469#[must_use]
17470const fn limbs_set_bit0_7(a: Limbs<7>) -> Limbs<7> {
17471    let aw = a.words();
17472    let mut out = [0u64; 7];
17473    let mut i = 0usize;
17474    while i < 7 {
17475        out[i] = aw[i];
17476        i += 1;
17477    }
17478    out[0] |= 1u64;
17479    Limbs::<7>::from_words(out)
17480}
17481
17482#[inline]
17483#[must_use]
17484const fn limbs_bit_msb_7(a: Limbs<7>, msb_index: usize) -> u64 {
17485    let aw = a.words();
17486    let total_bits = 7 * 64;
17487    let lsb_index = total_bits - 1 - msb_index;
17488    let word = lsb_index / 64;
17489    let bit = lsb_index % 64;
17490    (aw[word] >> bit) & 1u64
17491}
17492
17493#[inline]
17494#[must_use]
17495const fn limbs_divmod_7(a: Limbs<7>, b: Limbs<7>) -> (Limbs<7>, Limbs<7>) {
17496    let mut q = Limbs::<7>::zero();
17497    let mut r = Limbs::<7>::zero();
17498    let total_bits = 7 * 64;
17499    let mut i = 0usize;
17500    while i < total_bits {
17501        r = limbs_shl1_7(r);
17502        if limbs_bit_msb_7(a, i) == 1 {
17503            r = limbs_set_bit0_7(r);
17504        }
17505        if limbs_le_7(b, r) {
17506            r = r.wrapping_sub(b);
17507            q = limbs_shl1_7(q);
17508            q = limbs_set_bit0_7(q);
17509        } else {
17510            q = limbs_shl1_7(q);
17511        }
17512        i += 1;
17513    }
17514    (q, r)
17515}
17516
17517#[inline]
17518#[must_use]
17519const fn limbs_div_7(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
17520    let (q, _) = limbs_divmod_7(a, b);
17521    q
17522}
17523
17524#[inline]
17525#[must_use]
17526const fn limbs_mod_7(a: Limbs<7>, b: Limbs<7>) -> Limbs<7> {
17527    let (_, r) = limbs_divmod_7(a, b);
17528    r
17529}
17530
17531#[inline]
17532#[must_use]
17533const fn limbs_pow_7(base: Limbs<7>, exp: Limbs<7>) -> Limbs<7> {
17534    let mut result = limbs_one_7();
17535    let mut b = base;
17536    let ew = exp.words();
17537    let mut word = 0usize;
17538    while word < 7 {
17539        let mut bit = 0u32;
17540        while bit < 64 {
17541            if ((ew[word] >> bit) & 1u64) == 1u64 {
17542                result = result.wrapping_mul(b);
17543            }
17544            b = b.wrapping_mul(b);
17545            bit += 1;
17546        }
17547        word += 1;
17548    }
17549    result
17550}
17551
17552#[inline]
17553#[must_use]
17554const fn limbs_is_zero_8(a: Limbs<8>) -> bool {
17555    let aw = a.words();
17556    let mut i = 0usize;
17557    while i < 8 {
17558        if aw[i] != 0 {
17559            return false;
17560        }
17561        i += 1;
17562    }
17563    true
17564}
17565
17566#[inline]
17567#[must_use]
17568const fn limbs_shl1_8(a: Limbs<8>) -> Limbs<8> {
17569    let aw = a.words();
17570    let mut out = [0u64; 8];
17571    let mut carry: u64 = 0;
17572    let mut i = 0usize;
17573    while i < 8 {
17574        let v = aw[i];
17575        out[i] = (v << 1) | carry;
17576        carry = v >> 63;
17577        i += 1;
17578    }
17579    Limbs::<8>::from_words(out)
17580}
17581
17582#[inline]
17583#[must_use]
17584const fn limbs_set_bit0_8(a: Limbs<8>) -> Limbs<8> {
17585    let aw = a.words();
17586    let mut out = [0u64; 8];
17587    let mut i = 0usize;
17588    while i < 8 {
17589        out[i] = aw[i];
17590        i += 1;
17591    }
17592    out[0] |= 1u64;
17593    Limbs::<8>::from_words(out)
17594}
17595
17596#[inline]
17597#[must_use]
17598const fn limbs_bit_msb_8(a: Limbs<8>, msb_index: usize) -> u64 {
17599    let aw = a.words();
17600    let total_bits = 8 * 64;
17601    let lsb_index = total_bits - 1 - msb_index;
17602    let word = lsb_index / 64;
17603    let bit = lsb_index % 64;
17604    (aw[word] >> bit) & 1u64
17605}
17606
17607#[inline]
17608#[must_use]
17609const fn limbs_divmod_8(a: Limbs<8>, b: Limbs<8>) -> (Limbs<8>, Limbs<8>) {
17610    let mut q = Limbs::<8>::zero();
17611    let mut r = Limbs::<8>::zero();
17612    let total_bits = 8 * 64;
17613    let mut i = 0usize;
17614    while i < total_bits {
17615        r = limbs_shl1_8(r);
17616        if limbs_bit_msb_8(a, i) == 1 {
17617            r = limbs_set_bit0_8(r);
17618        }
17619        if limbs_le_8(b, r) {
17620            r = r.wrapping_sub(b);
17621            q = limbs_shl1_8(q);
17622            q = limbs_set_bit0_8(q);
17623        } else {
17624            q = limbs_shl1_8(q);
17625        }
17626        i += 1;
17627    }
17628    (q, r)
17629}
17630
17631#[inline]
17632#[must_use]
17633const fn limbs_div_8(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
17634    let (q, _) = limbs_divmod_8(a, b);
17635    q
17636}
17637
17638#[inline]
17639#[must_use]
17640const fn limbs_mod_8(a: Limbs<8>, b: Limbs<8>) -> Limbs<8> {
17641    let (_, r) = limbs_divmod_8(a, b);
17642    r
17643}
17644
17645#[inline]
17646#[must_use]
17647const fn limbs_pow_8(base: Limbs<8>, exp: Limbs<8>) -> Limbs<8> {
17648    let mut result = limbs_one_8();
17649    let mut b = base;
17650    let ew = exp.words();
17651    let mut word = 0usize;
17652    while word < 8 {
17653        let mut bit = 0u32;
17654        while bit < 64 {
17655            if ((ew[word] >> bit) & 1u64) == 1u64 {
17656                result = result.wrapping_mul(b);
17657            }
17658            b = b.wrapping_mul(b);
17659            bit += 1;
17660        }
17661        word += 1;
17662    }
17663    result
17664}
17665
17666#[inline]
17667#[must_use]
17668const fn limbs_is_zero_9(a: Limbs<9>) -> bool {
17669    let aw = a.words();
17670    let mut i = 0usize;
17671    while i < 9 {
17672        if aw[i] != 0 {
17673            return false;
17674        }
17675        i += 1;
17676    }
17677    true
17678}
17679
17680#[inline]
17681#[must_use]
17682const fn limbs_shl1_9(a: Limbs<9>) -> Limbs<9> {
17683    let aw = a.words();
17684    let mut out = [0u64; 9];
17685    let mut carry: u64 = 0;
17686    let mut i = 0usize;
17687    while i < 9 {
17688        let v = aw[i];
17689        out[i] = (v << 1) | carry;
17690        carry = v >> 63;
17691        i += 1;
17692    }
17693    Limbs::<9>::from_words(out)
17694}
17695
17696#[inline]
17697#[must_use]
17698const fn limbs_set_bit0_9(a: Limbs<9>) -> Limbs<9> {
17699    let aw = a.words();
17700    let mut out = [0u64; 9];
17701    let mut i = 0usize;
17702    while i < 9 {
17703        out[i] = aw[i];
17704        i += 1;
17705    }
17706    out[0] |= 1u64;
17707    Limbs::<9>::from_words(out)
17708}
17709
17710#[inline]
17711#[must_use]
17712const fn limbs_bit_msb_9(a: Limbs<9>, msb_index: usize) -> u64 {
17713    let aw = a.words();
17714    let total_bits = 9 * 64;
17715    let lsb_index = total_bits - 1 - msb_index;
17716    let word = lsb_index / 64;
17717    let bit = lsb_index % 64;
17718    (aw[word] >> bit) & 1u64
17719}
17720
17721#[inline]
17722#[must_use]
17723const fn limbs_divmod_9(a: Limbs<9>, b: Limbs<9>) -> (Limbs<9>, Limbs<9>) {
17724    let mut q = Limbs::<9>::zero();
17725    let mut r = Limbs::<9>::zero();
17726    let total_bits = 9 * 64;
17727    let mut i = 0usize;
17728    while i < total_bits {
17729        r = limbs_shl1_9(r);
17730        if limbs_bit_msb_9(a, i) == 1 {
17731            r = limbs_set_bit0_9(r);
17732        }
17733        if limbs_le_9(b, r) {
17734            r = r.wrapping_sub(b);
17735            q = limbs_shl1_9(q);
17736            q = limbs_set_bit0_9(q);
17737        } else {
17738            q = limbs_shl1_9(q);
17739        }
17740        i += 1;
17741    }
17742    (q, r)
17743}
17744
17745#[inline]
17746#[must_use]
17747const fn limbs_div_9(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
17748    let (q, _) = limbs_divmod_9(a, b);
17749    q
17750}
17751
17752#[inline]
17753#[must_use]
17754const fn limbs_mod_9(a: Limbs<9>, b: Limbs<9>) -> Limbs<9> {
17755    let (_, r) = limbs_divmod_9(a, b);
17756    r
17757}
17758
17759#[inline]
17760#[must_use]
17761const fn limbs_pow_9(base: Limbs<9>, exp: Limbs<9>) -> Limbs<9> {
17762    let mut result = limbs_one_9();
17763    let mut b = base;
17764    let ew = exp.words();
17765    let mut word = 0usize;
17766    while word < 9 {
17767        let mut bit = 0u32;
17768        while bit < 64 {
17769            if ((ew[word] >> bit) & 1u64) == 1u64 {
17770                result = result.wrapping_mul(b);
17771            }
17772            b = b.wrapping_mul(b);
17773            bit += 1;
17774        }
17775        word += 1;
17776    }
17777    result
17778}
17779
17780#[inline]
17781#[must_use]
17782const fn limbs_is_zero_16(a: Limbs<16>) -> bool {
17783    let aw = a.words();
17784    let mut i = 0usize;
17785    while i < 16 {
17786        if aw[i] != 0 {
17787            return false;
17788        }
17789        i += 1;
17790    }
17791    true
17792}
17793
17794#[inline]
17795#[must_use]
17796const fn limbs_shl1_16(a: Limbs<16>) -> Limbs<16> {
17797    let aw = a.words();
17798    let mut out = [0u64; 16];
17799    let mut carry: u64 = 0;
17800    let mut i = 0usize;
17801    while i < 16 {
17802        let v = aw[i];
17803        out[i] = (v << 1) | carry;
17804        carry = v >> 63;
17805        i += 1;
17806    }
17807    Limbs::<16>::from_words(out)
17808}
17809
17810#[inline]
17811#[must_use]
17812const fn limbs_set_bit0_16(a: Limbs<16>) -> Limbs<16> {
17813    let aw = a.words();
17814    let mut out = [0u64; 16];
17815    let mut i = 0usize;
17816    while i < 16 {
17817        out[i] = aw[i];
17818        i += 1;
17819    }
17820    out[0] |= 1u64;
17821    Limbs::<16>::from_words(out)
17822}
17823
17824#[inline]
17825#[must_use]
17826const fn limbs_bit_msb_16(a: Limbs<16>, msb_index: usize) -> u64 {
17827    let aw = a.words();
17828    let total_bits = 16 * 64;
17829    let lsb_index = total_bits - 1 - msb_index;
17830    let word = lsb_index / 64;
17831    let bit = lsb_index % 64;
17832    (aw[word] >> bit) & 1u64
17833}
17834
17835#[inline]
17836#[must_use]
17837const fn limbs_divmod_16(a: Limbs<16>, b: Limbs<16>) -> (Limbs<16>, Limbs<16>) {
17838    let mut q = Limbs::<16>::zero();
17839    let mut r = Limbs::<16>::zero();
17840    let total_bits = 16 * 64;
17841    let mut i = 0usize;
17842    while i < total_bits {
17843        r = limbs_shl1_16(r);
17844        if limbs_bit_msb_16(a, i) == 1 {
17845            r = limbs_set_bit0_16(r);
17846        }
17847        if limbs_le_16(b, r) {
17848            r = r.wrapping_sub(b);
17849            q = limbs_shl1_16(q);
17850            q = limbs_set_bit0_16(q);
17851        } else {
17852            q = limbs_shl1_16(q);
17853        }
17854        i += 1;
17855    }
17856    (q, r)
17857}
17858
17859#[inline]
17860#[must_use]
17861const fn limbs_div_16(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
17862    let (q, _) = limbs_divmod_16(a, b);
17863    q
17864}
17865
17866#[inline]
17867#[must_use]
17868const fn limbs_mod_16(a: Limbs<16>, b: Limbs<16>) -> Limbs<16> {
17869    let (_, r) = limbs_divmod_16(a, b);
17870    r
17871}
17872
17873#[inline]
17874#[must_use]
17875const fn limbs_pow_16(base: Limbs<16>, exp: Limbs<16>) -> Limbs<16> {
17876    let mut result = limbs_one_16();
17877    let mut b = base;
17878    let ew = exp.words();
17879    let mut word = 0usize;
17880    while word < 16 {
17881        let mut bit = 0u32;
17882        while bit < 64 {
17883            if ((ew[word] >> bit) & 1u64) == 1u64 {
17884                result = result.wrapping_mul(b);
17885            }
17886            b = b.wrapping_mul(b);
17887            bit += 1;
17888        }
17889        word += 1;
17890    }
17891    result
17892}
17893
17894#[inline]
17895#[must_use]
17896const fn limbs_is_zero_32(a: Limbs<32>) -> bool {
17897    let aw = a.words();
17898    let mut i = 0usize;
17899    while i < 32 {
17900        if aw[i] != 0 {
17901            return false;
17902        }
17903        i += 1;
17904    }
17905    true
17906}
17907
17908#[inline]
17909#[must_use]
17910const fn limbs_shl1_32(a: Limbs<32>) -> Limbs<32> {
17911    let aw = a.words();
17912    let mut out = [0u64; 32];
17913    let mut carry: u64 = 0;
17914    let mut i = 0usize;
17915    while i < 32 {
17916        let v = aw[i];
17917        out[i] = (v << 1) | carry;
17918        carry = v >> 63;
17919        i += 1;
17920    }
17921    Limbs::<32>::from_words(out)
17922}
17923
17924#[inline]
17925#[must_use]
17926const fn limbs_set_bit0_32(a: Limbs<32>) -> Limbs<32> {
17927    let aw = a.words();
17928    let mut out = [0u64; 32];
17929    let mut i = 0usize;
17930    while i < 32 {
17931        out[i] = aw[i];
17932        i += 1;
17933    }
17934    out[0] |= 1u64;
17935    Limbs::<32>::from_words(out)
17936}
17937
17938#[inline]
17939#[must_use]
17940const fn limbs_bit_msb_32(a: Limbs<32>, msb_index: usize) -> u64 {
17941    let aw = a.words();
17942    let total_bits = 32 * 64;
17943    let lsb_index = total_bits - 1 - msb_index;
17944    let word = lsb_index / 64;
17945    let bit = lsb_index % 64;
17946    (aw[word] >> bit) & 1u64
17947}
17948
17949#[inline]
17950#[must_use]
17951const fn limbs_divmod_32(a: Limbs<32>, b: Limbs<32>) -> (Limbs<32>, Limbs<32>) {
17952    let mut q = Limbs::<32>::zero();
17953    let mut r = Limbs::<32>::zero();
17954    let total_bits = 32 * 64;
17955    let mut i = 0usize;
17956    while i < total_bits {
17957        r = limbs_shl1_32(r);
17958        if limbs_bit_msb_32(a, i) == 1 {
17959            r = limbs_set_bit0_32(r);
17960        }
17961        if limbs_le_32(b, r) {
17962            r = r.wrapping_sub(b);
17963            q = limbs_shl1_32(q);
17964            q = limbs_set_bit0_32(q);
17965        } else {
17966            q = limbs_shl1_32(q);
17967        }
17968        i += 1;
17969    }
17970    (q, r)
17971}
17972
17973#[inline]
17974#[must_use]
17975const fn limbs_div_32(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
17976    let (q, _) = limbs_divmod_32(a, b);
17977    q
17978}
17979
17980#[inline]
17981#[must_use]
17982const fn limbs_mod_32(a: Limbs<32>, b: Limbs<32>) -> Limbs<32> {
17983    let (_, r) = limbs_divmod_32(a, b);
17984    r
17985}
17986
17987#[inline]
17988#[must_use]
17989const fn limbs_pow_32(base: Limbs<32>, exp: Limbs<32>) -> Limbs<32> {
17990    let mut result = limbs_one_32();
17991    let mut b = base;
17992    let ew = exp.words();
17993    let mut word = 0usize;
17994    while word < 32 {
17995        let mut bit = 0u32;
17996        while bit < 64 {
17997            if ((ew[word] >> bit) & 1u64) == 1u64 {
17998                result = result.wrapping_mul(b);
17999            }
18000            b = b.wrapping_mul(b);
18001            bit += 1;
18002        }
18003        word += 1;
18004    }
18005    result
18006}
18007
18008#[inline]
18009#[must_use]
18010const fn limbs_is_zero_64(a: Limbs<64>) -> bool {
18011    let aw = a.words();
18012    let mut i = 0usize;
18013    while i < 64 {
18014        if aw[i] != 0 {
18015            return false;
18016        }
18017        i += 1;
18018    }
18019    true
18020}
18021
18022#[inline]
18023#[must_use]
18024const fn limbs_shl1_64(a: Limbs<64>) -> Limbs<64> {
18025    let aw = a.words();
18026    let mut out = [0u64; 64];
18027    let mut carry: u64 = 0;
18028    let mut i = 0usize;
18029    while i < 64 {
18030        let v = aw[i];
18031        out[i] = (v << 1) | carry;
18032        carry = v >> 63;
18033        i += 1;
18034    }
18035    Limbs::<64>::from_words(out)
18036}
18037
18038#[inline]
18039#[must_use]
18040const fn limbs_set_bit0_64(a: Limbs<64>) -> Limbs<64> {
18041    let aw = a.words();
18042    let mut out = [0u64; 64];
18043    let mut i = 0usize;
18044    while i < 64 {
18045        out[i] = aw[i];
18046        i += 1;
18047    }
18048    out[0] |= 1u64;
18049    Limbs::<64>::from_words(out)
18050}
18051
18052#[inline]
18053#[must_use]
18054const fn limbs_bit_msb_64(a: Limbs<64>, msb_index: usize) -> u64 {
18055    let aw = a.words();
18056    let total_bits = 64 * 64;
18057    let lsb_index = total_bits - 1 - msb_index;
18058    let word = lsb_index / 64;
18059    let bit = lsb_index % 64;
18060    (aw[word] >> bit) & 1u64
18061}
18062
18063#[inline]
18064#[must_use]
18065const fn limbs_divmod_64(a: Limbs<64>, b: Limbs<64>) -> (Limbs<64>, Limbs<64>) {
18066    let mut q = Limbs::<64>::zero();
18067    let mut r = Limbs::<64>::zero();
18068    let total_bits = 64 * 64;
18069    let mut i = 0usize;
18070    while i < total_bits {
18071        r = limbs_shl1_64(r);
18072        if limbs_bit_msb_64(a, i) == 1 {
18073            r = limbs_set_bit0_64(r);
18074        }
18075        if limbs_le_64(b, r) {
18076            r = r.wrapping_sub(b);
18077            q = limbs_shl1_64(q);
18078            q = limbs_set_bit0_64(q);
18079        } else {
18080            q = limbs_shl1_64(q);
18081        }
18082        i += 1;
18083    }
18084    (q, r)
18085}
18086
18087#[inline]
18088#[must_use]
18089const fn limbs_div_64(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
18090    let (q, _) = limbs_divmod_64(a, b);
18091    q
18092}
18093
18094#[inline]
18095#[must_use]
18096const fn limbs_mod_64(a: Limbs<64>, b: Limbs<64>) -> Limbs<64> {
18097    let (_, r) = limbs_divmod_64(a, b);
18098    r
18099}
18100
18101#[inline]
18102#[must_use]
18103const fn limbs_pow_64(base: Limbs<64>, exp: Limbs<64>) -> Limbs<64> {
18104    let mut result = limbs_one_64();
18105    let mut b = base;
18106    let ew = exp.words();
18107    let mut word = 0usize;
18108    while word < 64 {
18109        let mut bit = 0u32;
18110        while bit < 64 {
18111            if ((ew[word] >> bit) & 1u64) == 1u64 {
18112                result = result.wrapping_mul(b);
18113            }
18114            b = b.wrapping_mul(b);
18115            bit += 1;
18116        }
18117        word += 1;
18118    }
18119    result
18120}
18121
18122#[inline]
18123#[must_use]
18124const fn limbs_is_zero_128(a: Limbs<128>) -> bool {
18125    let aw = a.words();
18126    let mut i = 0usize;
18127    while i < 128 {
18128        if aw[i] != 0 {
18129            return false;
18130        }
18131        i += 1;
18132    }
18133    true
18134}
18135
18136#[inline]
18137#[must_use]
18138const fn limbs_shl1_128(a: Limbs<128>) -> Limbs<128> {
18139    let aw = a.words();
18140    let mut out = [0u64; 128];
18141    let mut carry: u64 = 0;
18142    let mut i = 0usize;
18143    while i < 128 {
18144        let v = aw[i];
18145        out[i] = (v << 1) | carry;
18146        carry = v >> 63;
18147        i += 1;
18148    }
18149    Limbs::<128>::from_words(out)
18150}
18151
18152#[inline]
18153#[must_use]
18154const fn limbs_set_bit0_128(a: Limbs<128>) -> Limbs<128> {
18155    let aw = a.words();
18156    let mut out = [0u64; 128];
18157    let mut i = 0usize;
18158    while i < 128 {
18159        out[i] = aw[i];
18160        i += 1;
18161    }
18162    out[0] |= 1u64;
18163    Limbs::<128>::from_words(out)
18164}
18165
18166#[inline]
18167#[must_use]
18168const fn limbs_bit_msb_128(a: Limbs<128>, msb_index: usize) -> u64 {
18169    let aw = a.words();
18170    let total_bits = 128 * 64;
18171    let lsb_index = total_bits - 1 - msb_index;
18172    let word = lsb_index / 64;
18173    let bit = lsb_index % 64;
18174    (aw[word] >> bit) & 1u64
18175}
18176
18177#[inline]
18178#[must_use]
18179const fn limbs_divmod_128(a: Limbs<128>, b: Limbs<128>) -> (Limbs<128>, Limbs<128>) {
18180    let mut q = Limbs::<128>::zero();
18181    let mut r = Limbs::<128>::zero();
18182    let total_bits = 128 * 64;
18183    let mut i = 0usize;
18184    while i < total_bits {
18185        r = limbs_shl1_128(r);
18186        if limbs_bit_msb_128(a, i) == 1 {
18187            r = limbs_set_bit0_128(r);
18188        }
18189        if limbs_le_128(b, r) {
18190            r = r.wrapping_sub(b);
18191            q = limbs_shl1_128(q);
18192            q = limbs_set_bit0_128(q);
18193        } else {
18194            q = limbs_shl1_128(q);
18195        }
18196        i += 1;
18197    }
18198    (q, r)
18199}
18200
18201#[inline]
18202#[must_use]
18203const fn limbs_div_128(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
18204    let (q, _) = limbs_divmod_128(a, b);
18205    q
18206}
18207
18208#[inline]
18209#[must_use]
18210const fn limbs_mod_128(a: Limbs<128>, b: Limbs<128>) -> Limbs<128> {
18211    let (_, r) = limbs_divmod_128(a, b);
18212    r
18213}
18214
18215#[inline]
18216#[must_use]
18217const fn limbs_pow_128(base: Limbs<128>, exp: Limbs<128>) -> Limbs<128> {
18218    let mut result = limbs_one_128();
18219    let mut b = base;
18220    let ew = exp.words();
18221    let mut word = 0usize;
18222    while word < 128 {
18223        let mut bit = 0u32;
18224        while bit < 64 {
18225            if ((ew[word] >> bit) & 1u64) == 1u64 {
18226                result = result.wrapping_mul(b);
18227            }
18228            b = b.wrapping_mul(b);
18229            bit += 1;
18230        }
18231        word += 1;
18232    }
18233    result
18234}
18235
18236#[inline]
18237#[must_use]
18238const fn limbs_is_zero_192(a: Limbs<192>) -> bool {
18239    let aw = a.words();
18240    let mut i = 0usize;
18241    while i < 192 {
18242        if aw[i] != 0 {
18243            return false;
18244        }
18245        i += 1;
18246    }
18247    true
18248}
18249
18250#[inline]
18251#[must_use]
18252const fn limbs_shl1_192(a: Limbs<192>) -> Limbs<192> {
18253    let aw = a.words();
18254    let mut out = [0u64; 192];
18255    let mut carry: u64 = 0;
18256    let mut i = 0usize;
18257    while i < 192 {
18258        let v = aw[i];
18259        out[i] = (v << 1) | carry;
18260        carry = v >> 63;
18261        i += 1;
18262    }
18263    Limbs::<192>::from_words(out)
18264}
18265
18266#[inline]
18267#[must_use]
18268const fn limbs_set_bit0_192(a: Limbs<192>) -> Limbs<192> {
18269    let aw = a.words();
18270    let mut out = [0u64; 192];
18271    let mut i = 0usize;
18272    while i < 192 {
18273        out[i] = aw[i];
18274        i += 1;
18275    }
18276    out[0] |= 1u64;
18277    Limbs::<192>::from_words(out)
18278}
18279
18280#[inline]
18281#[must_use]
18282const fn limbs_bit_msb_192(a: Limbs<192>, msb_index: usize) -> u64 {
18283    let aw = a.words();
18284    let total_bits = 192 * 64;
18285    let lsb_index = total_bits - 1 - msb_index;
18286    let word = lsb_index / 64;
18287    let bit = lsb_index % 64;
18288    (aw[word] >> bit) & 1u64
18289}
18290
18291#[inline]
18292#[must_use]
18293const fn limbs_divmod_192(a: Limbs<192>, b: Limbs<192>) -> (Limbs<192>, Limbs<192>) {
18294    let mut q = Limbs::<192>::zero();
18295    let mut r = Limbs::<192>::zero();
18296    let total_bits = 192 * 64;
18297    let mut i = 0usize;
18298    while i < total_bits {
18299        r = limbs_shl1_192(r);
18300        if limbs_bit_msb_192(a, i) == 1 {
18301            r = limbs_set_bit0_192(r);
18302        }
18303        if limbs_le_192(b, r) {
18304            r = r.wrapping_sub(b);
18305            q = limbs_shl1_192(q);
18306            q = limbs_set_bit0_192(q);
18307        } else {
18308            q = limbs_shl1_192(q);
18309        }
18310        i += 1;
18311    }
18312    (q, r)
18313}
18314
18315#[inline]
18316#[must_use]
18317const fn limbs_div_192(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
18318    let (q, _) = limbs_divmod_192(a, b);
18319    q
18320}
18321
18322#[inline]
18323#[must_use]
18324const fn limbs_mod_192(a: Limbs<192>, b: Limbs<192>) -> Limbs<192> {
18325    let (_, r) = limbs_divmod_192(a, b);
18326    r
18327}
18328
18329#[inline]
18330#[must_use]
18331const fn limbs_pow_192(base: Limbs<192>, exp: Limbs<192>) -> Limbs<192> {
18332    let mut result = limbs_one_192();
18333    let mut b = base;
18334    let ew = exp.words();
18335    let mut word = 0usize;
18336    while word < 192 {
18337        let mut bit = 0u32;
18338        while bit < 64 {
18339            if ((ew[word] >> bit) & 1u64) == 1u64 {
18340                result = result.wrapping_mul(b);
18341            }
18342            b = b.wrapping_mul(b);
18343            bit += 1;
18344        }
18345        word += 1;
18346    }
18347    result
18348}
18349
18350#[inline]
18351#[must_use]
18352const fn limbs_is_zero_256(a: Limbs<256>) -> bool {
18353    let aw = a.words();
18354    let mut i = 0usize;
18355    while i < 256 {
18356        if aw[i] != 0 {
18357            return false;
18358        }
18359        i += 1;
18360    }
18361    true
18362}
18363
18364#[inline]
18365#[must_use]
18366const fn limbs_shl1_256(a: Limbs<256>) -> Limbs<256> {
18367    let aw = a.words();
18368    let mut out = [0u64; 256];
18369    let mut carry: u64 = 0;
18370    let mut i = 0usize;
18371    while i < 256 {
18372        let v = aw[i];
18373        out[i] = (v << 1) | carry;
18374        carry = v >> 63;
18375        i += 1;
18376    }
18377    Limbs::<256>::from_words(out)
18378}
18379
18380#[inline]
18381#[must_use]
18382const fn limbs_set_bit0_256(a: Limbs<256>) -> Limbs<256> {
18383    let aw = a.words();
18384    let mut out = [0u64; 256];
18385    let mut i = 0usize;
18386    while i < 256 {
18387        out[i] = aw[i];
18388        i += 1;
18389    }
18390    out[0] |= 1u64;
18391    Limbs::<256>::from_words(out)
18392}
18393
18394#[inline]
18395#[must_use]
18396const fn limbs_bit_msb_256(a: Limbs<256>, msb_index: usize) -> u64 {
18397    let aw = a.words();
18398    let total_bits = 256 * 64;
18399    let lsb_index = total_bits - 1 - msb_index;
18400    let word = lsb_index / 64;
18401    let bit = lsb_index % 64;
18402    (aw[word] >> bit) & 1u64
18403}
18404
18405#[inline]
18406#[must_use]
18407const fn limbs_divmod_256(a: Limbs<256>, b: Limbs<256>) -> (Limbs<256>, Limbs<256>) {
18408    let mut q = Limbs::<256>::zero();
18409    let mut r = Limbs::<256>::zero();
18410    let total_bits = 256 * 64;
18411    let mut i = 0usize;
18412    while i < total_bits {
18413        r = limbs_shl1_256(r);
18414        if limbs_bit_msb_256(a, i) == 1 {
18415            r = limbs_set_bit0_256(r);
18416        }
18417        if limbs_le_256(b, r) {
18418            r = r.wrapping_sub(b);
18419            q = limbs_shl1_256(q);
18420            q = limbs_set_bit0_256(q);
18421        } else {
18422            q = limbs_shl1_256(q);
18423        }
18424        i += 1;
18425    }
18426    (q, r)
18427}
18428
18429#[inline]
18430#[must_use]
18431const fn limbs_div_256(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
18432    let (q, _) = limbs_divmod_256(a, b);
18433    q
18434}
18435
18436#[inline]
18437#[must_use]
18438const fn limbs_mod_256(a: Limbs<256>, b: Limbs<256>) -> Limbs<256> {
18439    let (_, r) = limbs_divmod_256(a, b);
18440    r
18441}
18442
18443#[inline]
18444#[must_use]
18445const fn limbs_pow_256(base: Limbs<256>, exp: Limbs<256>) -> Limbs<256> {
18446    let mut result = limbs_one_256();
18447    let mut b = base;
18448    let ew = exp.words();
18449    let mut word = 0usize;
18450    while word < 256 {
18451        let mut bit = 0u32;
18452        while bit < 64 {
18453            if ((ew[word] >> bit) & 1u64) == 1u64 {
18454                result = result.wrapping_mul(b);
18455            }
18456            b = b.wrapping_mul(b);
18457            bit += 1;
18458        }
18459        word += 1;
18460    }
18461    result
18462}
18463
18464#[inline]
18465#[must_use]
18466const fn limbs_is_zero_512(a: Limbs<512>) -> bool {
18467    let aw = a.words();
18468    let mut i = 0usize;
18469    while i < 512 {
18470        if aw[i] != 0 {
18471            return false;
18472        }
18473        i += 1;
18474    }
18475    true
18476}
18477
18478#[inline]
18479#[must_use]
18480const fn limbs_shl1_512(a: Limbs<512>) -> Limbs<512> {
18481    let aw = a.words();
18482    let mut out = [0u64; 512];
18483    let mut carry: u64 = 0;
18484    let mut i = 0usize;
18485    while i < 512 {
18486        let v = aw[i];
18487        out[i] = (v << 1) | carry;
18488        carry = v >> 63;
18489        i += 1;
18490    }
18491    Limbs::<512>::from_words(out)
18492}
18493
18494#[inline]
18495#[must_use]
18496const fn limbs_set_bit0_512(a: Limbs<512>) -> Limbs<512> {
18497    let aw = a.words();
18498    let mut out = [0u64; 512];
18499    let mut i = 0usize;
18500    while i < 512 {
18501        out[i] = aw[i];
18502        i += 1;
18503    }
18504    out[0] |= 1u64;
18505    Limbs::<512>::from_words(out)
18506}
18507
18508#[inline]
18509#[must_use]
18510const fn limbs_bit_msb_512(a: Limbs<512>, msb_index: usize) -> u64 {
18511    let aw = a.words();
18512    let total_bits = 512 * 64;
18513    let lsb_index = total_bits - 1 - msb_index;
18514    let word = lsb_index / 64;
18515    let bit = lsb_index % 64;
18516    (aw[word] >> bit) & 1u64
18517}
18518
18519#[inline]
18520#[must_use]
18521const fn limbs_divmod_512(a: Limbs<512>, b: Limbs<512>) -> (Limbs<512>, Limbs<512>) {
18522    let mut q = Limbs::<512>::zero();
18523    let mut r = Limbs::<512>::zero();
18524    let total_bits = 512 * 64;
18525    let mut i = 0usize;
18526    while i < total_bits {
18527        r = limbs_shl1_512(r);
18528        if limbs_bit_msb_512(a, i) == 1 {
18529            r = limbs_set_bit0_512(r);
18530        }
18531        if limbs_le_512(b, r) {
18532            r = r.wrapping_sub(b);
18533            q = limbs_shl1_512(q);
18534            q = limbs_set_bit0_512(q);
18535        } else {
18536            q = limbs_shl1_512(q);
18537        }
18538        i += 1;
18539    }
18540    (q, r)
18541}
18542
18543#[inline]
18544#[must_use]
18545const fn limbs_div_512(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
18546    let (q, _) = limbs_divmod_512(a, b);
18547    q
18548}
18549
18550#[inline]
18551#[must_use]
18552const fn limbs_mod_512(a: Limbs<512>, b: Limbs<512>) -> Limbs<512> {
18553    let (_, r) = limbs_divmod_512(a, b);
18554    r
18555}
18556
18557#[inline]
18558#[must_use]
18559const fn limbs_pow_512(base: Limbs<512>, exp: Limbs<512>) -> Limbs<512> {
18560    let mut result = limbs_one_512();
18561    let mut b = base;
18562    let ew = exp.words();
18563    let mut word = 0usize;
18564    while word < 512 {
18565        let mut bit = 0u32;
18566        while bit < 64 {
18567            if ((ew[word] >> bit) & 1u64) == 1u64 {
18568                result = result.wrapping_mul(b);
18569            }
18570            b = b.wrapping_mul(b);
18571            bit += 1;
18572        }
18573        word += 1;
18574    }
18575    result
18576}
18577
18578/// Sealed marker trait for fragment classifiers (Is2SatShape, IsHornShape,
18579/// IsResidualFragment) emitted parametrically from the predicate individuals
18580/// referenced by `predicate:InhabitanceDispatchTable`.
18581pub trait FragmentMarker: fragment_sealed::Sealed {}
18582
18583mod fragment_sealed {
18584    /// Private supertrait.
18585    pub trait Sealed {}
18586    impl Sealed for super::Is2SatShape {}
18587    impl Sealed for super::IsHornShape {}
18588    impl Sealed for super::IsResidualFragment {}
18589}
18590
18591/// Fragment marker for `predicate:Is2SatShape`. Zero-sized.
18592#[derive(Debug, Default, Clone, Copy)]
18593pub struct Is2SatShape;
18594impl FragmentMarker for Is2SatShape {}
18595
18596/// Fragment marker for `predicate:IsHornShape`. Zero-sized.
18597#[derive(Debug, Default, Clone, Copy)]
18598pub struct IsHornShape;
18599impl FragmentMarker for IsHornShape {}
18600
18601/// Fragment marker for `predicate:IsResidualFragment`. Zero-sized.
18602#[derive(Debug, Default, Clone, Copy)]
18603pub struct IsResidualFragment;
18604impl FragmentMarker for IsResidualFragment {}
18605
18606/// A single dispatch rule entry pairing a predicate IRI, a target resolver
18607/// name, and an evaluation priority.
18608#[derive(Debug, Clone, Copy)]
18609pub struct DispatchRule {
18610    /// IRI of the predicate that selects this rule.
18611    pub predicate_iri: &'static str,
18612    /// IRI of the target resolver class invoked when the predicate holds.
18613    pub target_resolver_iri: &'static str,
18614    /// Evaluation order; lower values evaluate first.
18615    pub priority: u32,
18616}
18617
18618/// A static dispatch table — an ordered slice of `DispatchRule` entries.
18619pub type DispatchTable = &'static [DispatchRule];
18620
18621/// v0.2.1 dispatch table generated from `predicate:InhabitanceDispatchTable`.
18622pub const INHABITANCE_DISPATCH_TABLE: DispatchTable = &[
18623    DispatchRule {
18624        predicate_iri: "https://uor.foundation/predicate/Is2SatShape",
18625        target_resolver_iri: "https://uor.foundation/resolver/TwoSatDecider",
18626        priority: 0,
18627    },
18628    DispatchRule {
18629        predicate_iri: "https://uor.foundation/predicate/IsHornShape",
18630        target_resolver_iri: "https://uor.foundation/resolver/HornSatDecider",
18631        priority: 1,
18632    },
18633    DispatchRule {
18634        predicate_iri: "https://uor.foundation/predicate/IsResidualFragment",
18635        target_resolver_iri: "https://uor.foundation/resolver/ResidualVerdictResolver",
18636        priority: 2,
18637    },
18638];
18639
18640/// v0.2.1 `Deref` impl for `Validated<T: OntologyTarget>` so consumers can call
18641/// certificate methods directly: `cert.target_level()` rather than
18642/// `cert.inner().target_level()`. The bound `T: OntologyTarget` keeps the
18643/// auto-deref scoped to foundation-produced types.
18644impl<T: OntologyTarget> core::ops::Deref for Validated<T> {
18645    type Target = T;
18646    #[inline]
18647    fn deref(&self) -> &T {
18648        &self.inner
18649    }
18650}
18651
18652mod bound_constraint_sealed {
18653    /// Sealed supertrait for the closed Observable catalogue.
18654    pub trait ObservableSealed {}
18655    /// Sealed supertrait for the closed BoundShape catalogue.
18656    pub trait BoundShapeSealed {}
18657}
18658
18659/// Sealed marker trait identifying the closed catalogue of observables
18660/// admissible in BoundConstraint. Implemented by unit structs emitted
18661/// below per `observable:Observable` subclass referenced by a
18662/// BoundConstraint kind individual.
18663pub trait Observable: bound_constraint_sealed::ObservableSealed {
18664    /// Ontology IRI of this observable class.
18665    const IRI: &'static str;
18666}
18667
18668/// Sealed marker trait identifying the closed catalogue of bound shapes.
18669/// Exactly six individuals: EqualBound, LessEqBound, GreaterEqBound,
18670/// RangeContainBound, ResidueClassBound, AffineEqualBound.
18671pub trait BoundShape: bound_constraint_sealed::BoundShapeSealed {
18672    /// Ontology IRI of this bound shape individual.
18673    const IRI: &'static str;
18674}
18675
18676/// Observes a Datum's value modulo a configurable modulus.
18677#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18678pub struct ValueModObservable;
18679impl bound_constraint_sealed::ObservableSealed for ValueModObservable {}
18680impl Observable for ValueModObservable {
18681    const IRI: &'static str = "https://uor.foundation/observable/ValueModObservable";
18682}
18683
18684/// Distance between two ring elements under the Hamming metric.
18685#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18686pub struct HammingMetric;
18687impl bound_constraint_sealed::ObservableSealed for HammingMetric {}
18688impl Observable for HammingMetric {
18689    const IRI: &'static str = "https://uor.foundation/observable/HammingMetric";
18690}
18691
18692/// Observes the derivation depth of a Datum.
18693#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18694pub struct DerivationDepthObservable;
18695impl bound_constraint_sealed::ObservableSealed for DerivationDepthObservable {}
18696impl Observable for DerivationDepthObservable {
18697    const IRI: &'static str = "https://uor.foundation/derivation/DerivationDepthObservable";
18698}
18699
18700/// Observes the carry depth of a Datum in the W₂ tower.
18701#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18702pub struct CarryDepthObservable;
18703impl bound_constraint_sealed::ObservableSealed for CarryDepthObservable {}
18704impl Observable for CarryDepthObservable {
18705    const IRI: &'static str = "https://uor.foundation/carry/CarryDepthObservable";
18706}
18707
18708/// Observes the free-rank of the partition associated with a Datum.
18709#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18710pub struct FreeRankObservable;
18711impl bound_constraint_sealed::ObservableSealed for FreeRankObservable {}
18712impl Observable for FreeRankObservable {
18713    const IRI: &'static str = "https://uor.foundation/partition/FreeRankObservable";
18714}
18715
18716/// Predicate form: `observable(datum) == target`.
18717#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18718pub struct EqualBound;
18719impl bound_constraint_sealed::BoundShapeSealed for EqualBound {}
18720impl BoundShape for EqualBound {
18721    const IRI: &'static str = "https://uor.foundation/type/EqualBound";
18722}
18723
18724/// Predicate form: `observable(datum) <= bound`.
18725#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18726pub struct LessEqBound;
18727impl bound_constraint_sealed::BoundShapeSealed for LessEqBound {}
18728impl BoundShape for LessEqBound {
18729    const IRI: &'static str = "https://uor.foundation/type/LessEqBound";
18730}
18731
18732/// Predicate form: `observable(datum) >= bound`.
18733#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18734pub struct GreaterEqBound;
18735impl bound_constraint_sealed::BoundShapeSealed for GreaterEqBound {}
18736impl BoundShape for GreaterEqBound {
18737    const IRI: &'static str = "https://uor.foundation/type/GreaterEqBound";
18738}
18739
18740/// Predicate form: `lo <= observable(datum) <= hi`.
18741#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18742pub struct RangeContainBound;
18743impl bound_constraint_sealed::BoundShapeSealed for RangeContainBound {}
18744impl BoundShape for RangeContainBound {
18745    const IRI: &'static str = "https://uor.foundation/type/RangeContainBound";
18746}
18747
18748/// Predicate form: `observable(datum) ≡ residue (mod modulus)`.
18749#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18750pub struct ResidueClassBound;
18751impl bound_constraint_sealed::BoundShapeSealed for ResidueClassBound {}
18752impl BoundShape for ResidueClassBound {
18753    const IRI: &'static str = "https://uor.foundation/type/ResidueClassBound";
18754}
18755
18756/// Predicate form: `observable(datum) == offset + affine combination`.
18757#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18758pub struct AffineEqualBound;
18759impl bound_constraint_sealed::BoundShapeSealed for AffineEqualBound {}
18760impl BoundShape for AffineEqualBound {
18761    const IRI: &'static str = "https://uor.foundation/type/AffineEqualBound";
18762}
18763
18764/// Parameter value type for `BoundConstraint` arguments.
18765/// Sealed enum over the closed set of primitive kinds the bound-shape
18766/// catalogue requires. No heap, no `String`.
18767#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18768pub enum BoundArgValue {
18769    /// Unsigned 64-bit integer.
18770    U64(u64),
18771    /// Signed 64-bit integer.
18772    I64(i64),
18773    /// Fixed 32-byte content-addressed value.
18774    Bytes32([u8; 32]),
18775}
18776
18777/// Fixed-size arguments carrier for a `BoundConstraint`.
18778/// Holds up to eight `(name, value)` pairs inline. The closed
18779/// bound-shape catalogue requires at most three parameters per kind;
18780/// the extra slots are reserved for future kind additions without
18781/// changing the carrier layout.
18782#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18783pub struct BoundArguments {
18784    entries: [Option<BoundArgEntry>; 8],
18785}
18786
18787/// A single named parameter in a `BoundArguments` table.
18788#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18789pub struct BoundArgEntry {
18790    /// Parameter name (a `&'static str` intentional over heap-owned).
18791    pub name: &'static str,
18792    /// Parameter value.
18793    pub value: BoundArgValue,
18794}
18795
18796impl BoundArguments {
18797    /// Construct an empty argument table.
18798    #[inline]
18799    #[must_use]
18800    pub const fn empty() -> Self {
18801        Self { entries: [None; 8] }
18802    }
18803
18804    /// Construct a table with a single `(name, value)` pair.
18805    #[inline]
18806    #[must_use]
18807    pub const fn single(name: &'static str, value: BoundArgValue) -> Self {
18808        let mut entries = [None; 8];
18809        entries[0] = Some(BoundArgEntry { name, value });
18810        Self { entries }
18811    }
18812
18813    /// Construct a table with two `(name, value)` pairs.
18814    #[inline]
18815    #[must_use]
18816    pub const fn pair(
18817        first: (&'static str, BoundArgValue),
18818        second: (&'static str, BoundArgValue),
18819    ) -> Self {
18820        let mut entries = [None; 8];
18821        entries[0] = Some(BoundArgEntry {
18822            name: first.0,
18823            value: first.1,
18824        });
18825        entries[1] = Some(BoundArgEntry {
18826            name: second.0,
18827            value: second.1,
18828        });
18829        Self { entries }
18830    }
18831
18832    /// Access the stored entries.
18833    #[inline]
18834    #[must_use]
18835    pub const fn entries(&self) -> &[Option<BoundArgEntry>; 8] {
18836        &self.entries
18837    }
18838}
18839
18840/// Parametric constraint carrier (v0.2.2 Phase D).
18841/// Generic over `O: Observable` and `B: BoundShape`. The seven
18842/// legacy constraint kinds are preserved as type aliases over this
18843/// carrier; see `ResidueConstraint`, `HammingConstraint`, etc. below.
18844#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18845pub struct BoundConstraint<O: Observable, B: BoundShape> {
18846    observable: O,
18847    bound: B,
18848    args: BoundArguments,
18849    _sealed: (),
18850}
18851
18852impl<O: Observable, B: BoundShape> BoundConstraint<O, B> {
18853    /// Crate-internal constructor. Downstream obtains values through
18854    /// the per-type-alias `pub const fn new` constructors.
18855    #[inline]
18856    #[must_use]
18857    pub(crate) const fn from_parts(observable: O, bound: B, args: BoundArguments) -> Self {
18858        Self {
18859            observable,
18860            bound,
18861            args,
18862            _sealed: (),
18863        }
18864    }
18865
18866    /// Access the bound observable.
18867    #[inline]
18868    #[must_use]
18869    pub const fn observable(&self) -> &O {
18870        &self.observable
18871    }
18872
18873    /// Access the bound shape.
18874    #[inline]
18875    #[must_use]
18876    pub const fn bound(&self) -> &B {
18877        &self.bound
18878    }
18879
18880    /// Access the bound arguments.
18881    #[inline]
18882    #[must_use]
18883    pub const fn args(&self) -> &BoundArguments {
18884        &self.args
18885    }
18886}
18887
18888/// Parametric conjunction of `BoundConstraint` kinds (v0.2.2 Phase D).
18889/// Replaces the v0.2.1 `CompositeConstraint` enumeration; the legacy
18890/// name survives as the type alias `CompositeConstraint<N>` below.
18891#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18892pub struct Conjunction<const N: usize> {
18893    len: usize,
18894    _sealed: (),
18895}
18896
18897impl<const N: usize> Conjunction<N> {
18898    /// Construct a new Conjunction with `len` conjuncts.
18899    #[inline]
18900    #[must_use]
18901    pub const fn new(len: usize) -> Self {
18902        Self { len, _sealed: () }
18903    }
18904
18905    /// The number of conjuncts in this Conjunction.
18906    #[inline]
18907    #[must_use]
18908    pub const fn len(&self) -> usize {
18909        self.len
18910    }
18911
18912    /// Whether the Conjunction is empty.
18913    #[inline]
18914    #[must_use]
18915    pub const fn is_empty(&self) -> bool {
18916        self.len == 0
18917    }
18918}
18919
18920/// v0.2.1 legacy type alias: a `BoundConstraint` kind asserting
18921/// residue-class membership (`value mod m == r`).
18922pub type ResidueConstraint = BoundConstraint<ValueModObservable, ResidueClassBound>;
18923
18924impl ResidueConstraint {
18925    /// Construct a residue constraint with the given modulus and residue.
18926    #[inline]
18927    #[must_use]
18928    pub const fn new(modulus: u64, residue: u64) -> Self {
18929        let args = BoundArguments::pair(
18930            ("modulus", BoundArgValue::U64(modulus)),
18931            ("residue", BoundArgValue::U64(residue)),
18932        );
18933        BoundConstraint::from_parts(ValueModObservable, ResidueClassBound, args)
18934    }
18935}
18936
18937/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18938/// Hamming weight of the Datum (`weight <= bound`).
18939pub type HammingConstraint = BoundConstraint<HammingMetric, LessEqBound>;
18940
18941impl HammingConstraint {
18942    /// Construct a Hamming constraint with the given upper bound.
18943    #[inline]
18944    #[must_use]
18945    pub const fn new(bound: u64) -> Self {
18946        let args = BoundArguments::single("bound", BoundArgValue::U64(bound));
18947        BoundConstraint::from_parts(HammingMetric, LessEqBound, args)
18948    }
18949}
18950
18951/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18952/// derivation depth of the Datum.
18953pub type DepthConstraint = BoundConstraint<DerivationDepthObservable, LessEqBound>;
18954
18955impl DepthConstraint {
18956    /// Construct a depth constraint with min and max depths.
18957    #[inline]
18958    #[must_use]
18959    pub const fn new(min_depth: u64, max_depth: u64) -> Self {
18960        let args = BoundArguments::pair(
18961            ("min_depth", BoundArgValue::U64(min_depth)),
18962            ("max_depth", BoundArgValue::U64(max_depth)),
18963        );
18964        BoundConstraint::from_parts(DerivationDepthObservable, LessEqBound, args)
18965    }
18966}
18967
18968/// v0.2.1 legacy type alias: a `BoundConstraint` kind bounding the
18969/// carry depth of the Datum in the W₂ tower.
18970pub type CarryConstraint = BoundConstraint<CarryDepthObservable, LessEqBound>;
18971
18972impl CarryConstraint {
18973    /// Construct a carry constraint with the given upper bound.
18974    #[inline]
18975    #[must_use]
18976    pub const fn new(bound: u64) -> Self {
18977        let args = BoundArguments::single("bound", BoundArgValue::U64(bound));
18978        BoundConstraint::from_parts(CarryDepthObservable, LessEqBound, args)
18979    }
18980}
18981
18982/// v0.2.1 legacy type alias: a `BoundConstraint` kind pinning a
18983/// single site coordinate.
18984pub type SiteConstraint = BoundConstraint<FreeRankObservable, LessEqBound>;
18985
18986impl SiteConstraint {
18987    /// Construct a site constraint with the given site index.
18988    #[inline]
18989    #[must_use]
18990    pub const fn new(site_index: u64) -> Self {
18991        let args = BoundArguments::single("site_index", BoundArgValue::U64(site_index));
18992        BoundConstraint::from_parts(FreeRankObservable, LessEqBound, args)
18993    }
18994}
18995
18996/// v0.2.1 legacy type alias: a `BoundConstraint` kind pinning an
18997/// affine relationship on the Datum's value projection.
18998pub type AffineConstraint = BoundConstraint<ValueModObservable, AffineEqualBound>;
18999
19000impl AffineConstraint {
19001    /// Construct an affine constraint with the given offset.
19002    #[inline]
19003    #[must_use]
19004    pub const fn new(offset: u64) -> Self {
19005        let args = BoundArguments::single("offset", BoundArgValue::U64(offset));
19006        BoundConstraint::from_parts(ValueModObservable, AffineEqualBound, args)
19007    }
19008}
19009
19010/// v0.2.1 legacy type alias: a `Conjunction` over `N` BoundConstraint
19011/// kinds (`CompositeConstraint<3>` = 3-way conjunction).
19012pub type CompositeConstraint<const N: usize> = Conjunction<N>;
19013
19014/// v0.2.2 Phase E: sealed query handle.
19015#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19016pub struct Query {
19017    address: ContentAddress,
19018    _sealed: (),
19019}
19020
19021impl Query {
19022    /// Returns the content-hashed query address.
19023    #[inline]
19024    #[must_use]
19025    pub const fn address(&self) -> ContentAddress {
19026        self.address
19027    }
19028
19029    /// Crate-internal constructor.
19030    #[inline]
19031    #[must_use]
19032    #[allow(dead_code)]
19033    pub(crate) const fn new(address: ContentAddress) -> Self {
19034        Self {
19035            address,
19036            _sealed: (),
19037        }
19038    }
19039}
19040
19041/// v0.2.2 Phase E: typed query coordinate parametric over WittLevel.
19042#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19043pub struct Coordinate<L> {
19044    stratum: u64,
19045    spectrum: u64,
19046    address: u64,
19047    _level: PhantomData<L>,
19048    _sealed: (),
19049}
19050
19051impl<L> Coordinate<L> {
19052    /// Returns the stratum coordinate.
19053    #[inline]
19054    #[must_use]
19055    pub const fn stratum(&self) -> u64 {
19056        self.stratum
19057    }
19058
19059    /// Returns the spectrum coordinate.
19060    #[inline]
19061    #[must_use]
19062    pub const fn spectrum(&self) -> u64 {
19063        self.spectrum
19064    }
19065
19066    /// Returns the address coordinate.
19067    #[inline]
19068    #[must_use]
19069    pub const fn address(&self) -> u64 {
19070        self.address
19071    }
19072
19073    /// Crate-internal constructor.
19074    #[inline]
19075    #[must_use]
19076    #[allow(dead_code)]
19077    pub(crate) const fn new(stratum: u64, spectrum: u64, address: u64) -> Self {
19078        Self {
19079            stratum,
19080            spectrum,
19081            address,
19082            _level: PhantomData,
19083            _sealed: (),
19084        }
19085    }
19086}
19087
19088/// v0.2.2 Phase E: sealed binding query handle.
19089#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19090pub struct BindingQuery {
19091    address: ContentAddress,
19092    _sealed: (),
19093}
19094
19095impl BindingQuery {
19096    /// Returns the content-hashed binding query address.
19097    #[inline]
19098    #[must_use]
19099    pub const fn address(&self) -> ContentAddress {
19100        self.address
19101    }
19102
19103    /// Crate-internal constructor.
19104    #[inline]
19105    #[must_use]
19106    #[allow(dead_code)]
19107    pub(crate) const fn new(address: ContentAddress) -> Self {
19108        Self {
19109            address,
19110            _sealed: (),
19111        }
19112    }
19113}
19114
19115/// v0.2.2 Phase E: sealed Partition handle over the bridge:partition
19116/// component classification produced during grounding.
19117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19118pub struct Partition {
19119    component: PartitionComponent,
19120    _sealed: (),
19121}
19122
19123impl Partition {
19124    /// Returns the component classification.
19125    #[inline]
19126    #[must_use]
19127    pub const fn component(&self) -> PartitionComponent {
19128        self.component
19129    }
19130
19131    /// Crate-internal constructor.
19132    #[inline]
19133    #[must_use]
19134    #[allow(dead_code)]
19135    pub(crate) const fn new(component: PartitionComponent) -> Self {
19136        Self {
19137            component,
19138            _sealed: (),
19139        }
19140    }
19141}
19142
19143/// v0.2.2 Phase E: a single event in a derivation Trace.
19144/// Fixed-size event; content-addressed so Trace replays are stable
19145/// across builds. The verifier in `uor-foundation-verify` (Phase H)
19146/// reconstructs the witness chain by walking a `Trace` iterator.
19147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19148pub struct TraceEvent {
19149    /// Step index in the derivation.
19150    step_index: u32,
19151    /// Primitive op applied at this step.
19152    op: PrimitiveOp,
19153    /// Content-hashed target address the op produced.
19154    target: ContentAddress,
19155    /// Sealing marker.
19156    _sealed: (),
19157}
19158
19159impl TraceEvent {
19160    /// Returns the step index.
19161    #[inline]
19162    #[must_use]
19163    pub const fn step_index(&self) -> u32 {
19164        self.step_index
19165    }
19166
19167    /// Returns the primitive op applied at this step.
19168    #[inline]
19169    #[must_use]
19170    pub const fn op(&self) -> PrimitiveOp {
19171        self.op
19172    }
19173
19174    /// Returns the content-hashed target address.
19175    #[inline]
19176    #[must_use]
19177    pub const fn target(&self) -> ContentAddress {
19178        self.target
19179    }
19180
19181    /// Crate-internal constructor.
19182    #[inline]
19183    #[must_use]
19184    #[allow(dead_code)]
19185    pub(crate) const fn new(step_index: u32, op: PrimitiveOp, target: ContentAddress) -> Self {
19186        Self {
19187            step_index,
19188            op,
19189            target,
19190            _sealed: (),
19191        }
19192    }
19193}
19194
19195/// Fixed-capacity derivation trace. Holds up to `TR_MAX` events inline;
19196/// no heap. Produced by `Derivation::replay()` and consumed by
19197/// `uor-foundation-verify`. `TR_MAX` is the const-generic that carries
19198/// the application's selected `<MyBounds as HostBounds>::TRACE_MAX_EVENTS`;
19199/// the default const-generic resolves to the conventional 256.
19200/// Carries `witt_level_bits` and `content_fingerprint` so `verify_trace`
19201/// can reconstruct the source `GroundingCertificate` via structural-
19202/// validation + fingerprint passthrough (no hash recomputation).
19203#[derive(Debug, Clone, Copy)]
19204pub struct Trace<const TR_MAX: usize = 256> {
19205    events: [Option<TraceEvent>; TR_MAX],
19206    len: u16,
19207    /// Witt level the source grounding was minted at, packed
19208    /// by `Derivation::replay` from the parent `Grounded::witt_level_bits`.
19209    /// `verify_trace` reads this back to populate the certificate.
19210    witt_level_bits: u16,
19211    /// Parametric content fingerprint of the source unit's full state,
19212    /// computed at grounding time by the consumer-supplied `Hasher` and
19213    /// packed in by `Derivation::replay`. `verify_trace` passes it through
19214    /// unchanged. The fingerprint's `FP_MAX` follows the application's
19215    /// selected `<MyBounds as HostBounds>::FINGERPRINT_MAX_BYTES`; this
19216    /// field uses the default-bound `ContentFingerprint`.
19217    content_fingerprint: ContentFingerprint,
19218    _sealed: (),
19219}
19220
19221impl<const TR_MAX: usize> Trace<TR_MAX> {
19222    /// An empty Trace.
19223    #[inline]
19224    #[must_use]
19225    pub const fn empty() -> Self {
19226        Self {
19227            events: [None; TR_MAX],
19228            len: 0,
19229            witt_level_bits: 0,
19230            content_fingerprint: ContentFingerprint::zero(),
19231            _sealed: (),
19232        }
19233    }
19234
19235    /// Crate-internal ctor for `Derivation::replay()` only.
19236    /// Bypasses validation because `replay()` constructs events from
19237    /// foundation-guaranteed-valid state (monotonic, contiguous, non-zero
19238    /// seed). No public path reaches this constructor; downstream uses the
19239    /// validating `try_from_events` instead.
19240    #[inline]
19241    #[must_use]
19242    #[allow(dead_code)]
19243    pub(crate) const fn from_replay_events_const(
19244        events: [Option<TraceEvent>; TR_MAX],
19245        len: u16,
19246        witt_level_bits: u16,
19247        content_fingerprint: ContentFingerprint,
19248    ) -> Self {
19249        Self {
19250            events,
19251            len,
19252            witt_level_bits,
19253            content_fingerprint,
19254            _sealed: (),
19255        }
19256    }
19257
19258    /// Number of events recorded.
19259    #[inline]
19260    #[must_use]
19261    pub const fn len(&self) -> u16 {
19262        self.len
19263    }
19264
19265    /// Whether the Trace is empty.
19266    #[inline]
19267    #[must_use]
19268    pub const fn is_empty(&self) -> bool {
19269        self.len == 0
19270    }
19271
19272    /// Access the event at the given index, or `None` if out of range.
19273    #[inline]
19274    #[must_use]
19275    pub fn event(&self, index: usize) -> Option<&TraceEvent> {
19276        self.events.get(index).and_then(|e| e.as_ref())
19277    }
19278
19279    /// v0.2.2 T5: returns the Witt level the source grounding was minted at.
19280    /// Carried through replay so `verify_trace` can populate the certificate.
19281    #[inline]
19282    #[must_use]
19283    pub const fn witt_level_bits(&self) -> u16 {
19284        self.witt_level_bits
19285    }
19286
19287    /// v0.2.2 T5: returns the parametric content fingerprint of the source
19288    /// unit, computed at grounding time by the consumer-supplied `Hasher`.
19289    /// `verify_trace` passes this through unchanged into the re-derived
19290    /// certificate, upholding the round-trip property.
19291    #[inline]
19292    #[must_use]
19293    pub const fn content_fingerprint(&self) -> ContentFingerprint {
19294        self.content_fingerprint
19295    }
19296
19297    /// Validating constructor. Checks every invariant the verify path
19298    /// relies on: events are contiguous from index 0, no event has a zero
19299    /// target, and the slice fits within `TR_MAX` events.
19300    /// # Errors
19301    /// - `ReplayError::EmptyTrace` if `events.is_empty()`.
19302    /// - `ReplayError::CapacityExceeded { declared, provided }` if the
19303    ///   slice exceeds `TR_MAX`.
19304    /// - `ReplayError::OutOfOrderEvent { index }` if the event at `index`
19305    ///   has a `step_index` not equal to `index` (strict contiguity).
19306    /// - `ReplayError::ZeroTarget { index }` if any event carries a zero
19307    ///   `ContentAddress` target.
19308    pub fn try_from_events(
19309        events: &[TraceEvent],
19310        witt_level_bits: u16,
19311        content_fingerprint: ContentFingerprint,
19312    ) -> Result<Self, ReplayError> {
19313        if events.is_empty() {
19314            return Err(ReplayError::EmptyTrace);
19315        }
19316        if events.len() > TR_MAX {
19317            return Err(ReplayError::CapacityExceeded {
19318                declared: TR_MAX as u16,
19319                provided: events.len() as u32,
19320            });
19321        }
19322        let mut i = 0usize;
19323        while i < events.len() {
19324            let e = &events[i];
19325            if e.step_index() as usize != i {
19326                return Err(ReplayError::OutOfOrderEvent { index: i });
19327            }
19328            if e.target().is_zero() {
19329                return Err(ReplayError::ZeroTarget { index: i });
19330            }
19331            i += 1;
19332        }
19333        let mut arr = [None; TR_MAX];
19334        let mut j = 0usize;
19335        while j < events.len() {
19336            arr[j] = Some(events[j]);
19337            j += 1;
19338        }
19339        Ok(Self {
19340            events: arr,
19341            len: events.len() as u16,
19342            witt_level_bits,
19343            content_fingerprint,
19344            _sealed: (),
19345        })
19346    }
19347}
19348
19349impl<const TR_MAX: usize> Default for Trace<TR_MAX> {
19350    #[inline]
19351    fn default() -> Self {
19352        Self::empty()
19353    }
19354}
19355
19356/// v0.2.2 Phase E / T2.6: `Derivation::replay()` produces a content-addressed
19357/// Trace the verifier can re-walk without invoking the deciders. The trace
19358/// length matches the derivation's `step_count()`, and each event's
19359/// `step_index` reflects its position in the derivation.
19360impl Derivation {
19361    /// Replay this derivation as a fixed-size `Trace<TR_MAX>` whose length matches
19362    /// `self.step_count()` (capped at the application's `<HostBounds>::TRACE_MAX_EVENTS`).
19363    /// Callers either annotate the binding (`let trace: Trace = ...;` picks
19364    /// `Trace`'s default `TR_MAX` of 256) or use turbofish (`derivation.replay::<1024>()`).
19365    /// # Example
19366    /// ```no_run
19367    /// use uor_foundation::enforcement::{
19368    ///     replay, CompileUnitBuilder, ConstrainedTypeInput, Grounded, Term, Trace,
19369    /// };
19370    /// use uor_foundation::pipeline::run;
19371    /// use uor_foundation::{VerificationDomain, WittLevel};
19372    /// # use uor_foundation::enforcement::Hasher;
19373    /// # struct H; impl Hasher for H {
19374    /// #     const OUTPUT_BYTES: usize = 16;
19375    /// #     fn initial() -> Self { Self }
19376    /// #     fn fold_byte(self, _: u8) -> Self { self }
19377    /// #     fn finalize(self) -> [u8; 32] { [0; 32] } }
19378    /// // ADR-060: `Term`/`Grounded` carry an `INLINE_BYTES` const-generic the
19379    /// // application derives from its `HostBounds`; fix a concrete width and
19380    /// // thread it through `run`'s 4th const argument.
19381    /// const N: usize = 32;
19382    /// let terms: [Term<'static, N>; 1] = [uor_foundation::pipeline::literal_u64(7, WittLevel::W8)];
19383    /// let doms: [VerificationDomain; 1] = [VerificationDomain::Enumerative];
19384    /// let unit = CompileUnitBuilder::<N>::new()
19385    ///     .root_term(&terms).witt_level_ceiling(WittLevel::W32)
19386    ///     .thermodynamic_budget(1024).target_domains(&doms)
19387    ///     .result_type::<ConstrainedTypeInput>()
19388    ///     .validate().expect("unit well-formed");
19389    /// let grounded: Grounded<ConstrainedTypeInput, N> =
19390    ///     run::<ConstrainedTypeInput, _, H, N>(unit).expect("grounds");
19391    /// // Replay → round-trip verification. The trace's event-count
19392    /// // capacity comes from the application's `HostBounds`; here the
19393    /// // type-annotated binding defaults `Trace`'s `TR_MAX` to 256.
19394    /// let trace: Trace = grounded.derivation().replay();
19395    /// let recert = replay::certify_from_trace(&trace).expect("valid trace");
19396    /// assert_eq!(recert.certificate().content_fingerprint(),
19397    ///            grounded.content_fingerprint());
19398    /// ```
19399    #[inline]
19400    #[must_use]
19401    pub fn replay<const TR_MAX: usize>(&self) -> Trace<TR_MAX> {
19402        let steps = self.step_count() as usize;
19403        let len = if steps > TR_MAX { TR_MAX } else { steps };
19404        let mut events = [None; TR_MAX];
19405        // Seed targets from the leading 8 bytes of the source
19406        // `content_fingerprint` (substrate-computed). Combined with `| 1` so
19407        // the first event's target is guaranteed nonzero even when the
19408        // leading bytes are all zero, and XOR with `(i + 1)` keeps the
19409        // sequence non-degenerate.
19410        let fp = self.content_fingerprint.as_bytes();
19411        let seed =
19412            u64::from_be_bytes([fp[0], fp[1], fp[2], fp[3], fp[4], fp[5], fp[6], fp[7]]) as u128;
19413        let nonzero_seed = seed | 1u128;
19414        let mut i = 0usize;
19415        while i < len {
19416            let target_raw = nonzero_seed ^ ((i as u128) + 1u128);
19417            events[i] = Some(TraceEvent::new(
19418                i as u32,
19419                crate::PrimitiveOp::Add,
19420                ContentAddress::from_u128(target_raw),
19421            ));
19422            i += 1;
19423        }
19424        // Pack the source `witt_level_bits` and `content_fingerprint`
19425        // into the Trace so `verify_trace` can reproduce the source certificate
19426        // via passthrough. The fingerprint was computed at grounding time by the
19427        // consumer-supplied Hasher and stored on the parent Grounded; the
19428        // Derivation accessor read it through.
19429        Trace::from_replay_events_const(
19430            events,
19431            len as u16,
19432            self.witt_level_bits,
19433            self.content_fingerprint,
19434        )
19435    }
19436}
19437
19438/// v0.2.2 T5: errors emitted by the trace-replay re-derivation path.
19439#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19440#[non_exhaustive]
19441pub enum ReplayError {
19442    /// The trace was empty; nothing to replay.
19443    EmptyTrace,
19444    /// Event at `index` has a non-monotonic step_index.
19445    OutOfOrderEvent {
19446        /// The event index that was out of order.
19447        index: usize,
19448    },
19449    /// Event at `index` carries a zero ContentAddress (forbidden in well-formed traces).
19450    ZeroTarget {
19451        /// The event index that carried a zero target.
19452        index: usize,
19453    },
19454    /// v0.2.2 T5.8: event step indices do not form a contiguous sequence
19455    /// `[0, 1, ..., len-1]`. Replaces the misleadingly-named v0.2.1
19456    /// `LengthMismatch` variant. The trace has the right number of
19457    /// events, but their step indices skip values (e.g., `[0, 2, 5]`
19458    /// with `len = 3`).
19459    NonContiguousSteps {
19460        /// The trace's declared length (number of events).
19461        declared: u16,
19462        /// The largest step_index observed in the event sequence.
19463        /// Always strictly greater than `declared - 1` when this
19464        /// variant fires.
19465        last_step: u32,
19466    },
19467    /// A caller attempted to construct a `Trace<TR_MAX>` whose event count
19468    /// exceeds `TR_MAX` (the application's `<HostBounds>::TRACE_MAX_EVENTS`).
19469    /// Distinct from `NonContiguousSteps` because the recovery is different
19470    /// (truncate vs. close gaps). Returned by `Trace::try_from_events`,
19471    /// never by `verify_trace` (the verifier reads from an existing `Trace`
19472    /// whose capacity is already enforced by the type's storage).
19473    CapacityExceeded {
19474        /// The trace's hard capacity (`TR_MAX`).
19475        declared: u16,
19476        /// The actual event count the caller attempted to pack in.
19477        provided: u32,
19478    },
19479}
19480
19481impl core::fmt::Display for ReplayError {
19482    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
19483        match self {
19484            Self::EmptyTrace => f.write_str("trace was empty; nothing to replay"),
19485            Self::OutOfOrderEvent { index } => write!(
19486                f,
19487                "event at index {index} has out-of-order step index",
19488            ),
19489            Self::ZeroTarget { index } => write!(
19490                f,
19491                "event at index {index} has a zero ContentAddress target",
19492            ),
19493            Self::NonContiguousSteps { declared, last_step } => write!(
19494                f,
19495                "trace declares {declared} events but step indices skip values \
19496                 (last step {last_step})",
19497            ),
19498            Self::CapacityExceeded { declared, provided } => write!(
19499                f,
19500                "trace capacity exceeded: tried to pack {provided} events into a buffer of {declared}",
19501            ),
19502        }
19503    }
19504}
19505
19506impl core::error::Error for ReplayError {}
19507
19508/// v0.2.2 T5: trace-replay re-derivation module.
19509/// The foundation owns the certificate-construction boundary; the
19510/// `uor-foundation-verify` crate is a thin facade that delegates to
19511/// `replay::certify_from_trace`. This preserves sealing discipline:
19512/// `Certified::new` stays `pub(crate)` and no external crate can mint a
19513/// certificate.
19514pub mod replay {
19515    use super::{Certified, GroundingCertificate, ReplayError, Trace};
19516
19517    /// Re-derive the `Certified<GroundingCertificate>` that the foundation
19518    /// grounding path produced for the source unit.
19519    /// Validates the trace's structural invariants (monotonic, contiguous
19520    /// step indices; no zero targets; no None slots in the populated
19521    /// prefix) and re-packages the trace's stored `ContentFingerprint` and
19522    /// `witt_level_bits` into a fresh certificate. The verifier does NOT
19523    /// invoke a hash function: the fingerprint is *data carried by the
19524    /// Trace*, computed at mint time by the consumer-supplied `Hasher` and
19525    /// passed through unchanged.
19526    /// # Round-trip property
19527    /// For every `Grounded<T>` produced by `pipeline::run::<T, _, H>` with
19528    /// a conforming substrate `H: Hasher`:
19529    /// ```text
19530    /// verify_trace(&grounded.derivation().replay()).certificate()
19531    ///     == grounded.certificate()
19532    /// ```
19533    /// holds bit-identically. The contract is orthogonal to the substrate
19534    /// hasher choice and to the chosen `OUTPUT_BYTES` width.
19535    /// # Errors
19536    /// Returns:
19537    /// - `ReplayError::EmptyTrace` if `trace.is_empty()`.
19538    /// - `ReplayError::OutOfOrderEvent { index }` if step indices are not
19539    ///   strictly monotonic at position `index`.
19540    /// - `ReplayError::ZeroTarget { index }` if any event carries
19541    ///   `ContentAddress::zero()`.
19542    /// - `ReplayError::NonContiguousSteps { declared, last_step }` if
19543    ///   the event step indices skip values.
19544    pub fn certify_from_trace<const TR_MAX: usize>(
19545        trace: &Trace<TR_MAX>,
19546    ) -> Result<Certified<GroundingCertificate>, ReplayError> {
19547        let len = trace.len() as usize;
19548        if len == 0 {
19549            return Err(ReplayError::EmptyTrace);
19550        }
19551        // Structural validation: monotonic step indices, contiguous from 0,
19552        // no zero targets, no None slots in the populated prefix.
19553        let mut last_step: i64 = -1;
19554        let mut max_step_index: u32 = 0;
19555        let mut i = 0usize;
19556        while i < len {
19557            let event = match trace.event(i) {
19558                Some(e) => e,
19559                None => return Err(ReplayError::OutOfOrderEvent { index: i }),
19560            };
19561            let step_index = event.step_index();
19562            if (step_index as i64) <= last_step {
19563                return Err(ReplayError::OutOfOrderEvent { index: i });
19564            }
19565            if event.target().is_zero() {
19566                return Err(ReplayError::ZeroTarget { index: i });
19567            }
19568            if step_index > max_step_index {
19569                max_step_index = step_index;
19570            }
19571            last_step = step_index as i64;
19572            i += 1;
19573        }
19574        if (max_step_index as u16).saturating_add(1) != trace.len() {
19575            return Err(ReplayError::NonContiguousSteps {
19576                declared: trace.len(),
19577                last_step: max_step_index,
19578            });
19579        }
19580        // v0.2.2 T5: fingerprint passthrough. The trace was minted by the
19581        // foundation pipeline with a `ContentFingerprint` already computed by
19582        // the consumer-supplied `Hasher`. The verifier does not invoke any
19583        // hash function; it copies the fingerprint through unchanged. The
19584        // round-trip property holds by construction. v0.2.2 T6.5: the
19585        // FingerprintMissing variant is removed because under T6.3 / T6.10,
19586        // no public path can produce a Trace with a zero fingerprint.
19587        Ok(Certified::new(
19588            GroundingCertificate::with_level_and_fingerprint_const(
19589                trace.witt_level_bits(),
19590                trace.content_fingerprint(),
19591            ),
19592        ))
19593    }
19594}
19595
19596/// v0.2.2 Phase E: sealed builder for an InteractionDeclaration.
19597/// Validates the peer protocol, convergence predicate, and
19598/// commutator state class required by `conformance:InteractionShape`.
19599/// Phase F wires the full `InteractionDriver` on top of this builder.
19600#[derive(Debug, Clone, Copy, Default)]
19601pub struct InteractionDeclarationBuilder {
19602    peer_protocol: Option<u128>,
19603    convergence_predicate: Option<u128>,
19604    commutator_state_class: Option<u128>,
19605}
19606
19607impl InteractionDeclarationBuilder {
19608    /// Construct a new builder.
19609    #[inline]
19610    #[must_use]
19611    pub const fn new() -> Self {
19612        Self {
19613            peer_protocol: None,
19614            convergence_predicate: None,
19615            commutator_state_class: None,
19616        }
19617    }
19618
19619    /// Set the peer protocol content address.
19620    #[inline]
19621    #[must_use]
19622    pub const fn peer_protocol(mut self, address: u128) -> Self {
19623        self.peer_protocol = Some(address);
19624        self
19625    }
19626
19627    /// Set the convergence predicate content address.
19628    #[inline]
19629    #[must_use]
19630    pub const fn convergence_predicate(mut self, address: u128) -> Self {
19631        self.convergence_predicate = Some(address);
19632        self
19633    }
19634
19635    /// Set the commutator state class content address.
19636    #[inline]
19637    #[must_use]
19638    pub const fn commutator_state_class(mut self, address: u128) -> Self {
19639        self.commutator_state_class = Some(address);
19640        self
19641    }
19642
19643    /// Phase E.6: validate against `conformance:InteractionShape`.
19644    /// # Errors
19645    /// Returns `ShapeViolation` if any of the three required fields is missing.
19646    pub fn validate(&self) -> Result<Validated<InteractionShape>, ShapeViolation> {
19647        self.validate_common().map(|_| {
19648            Validated::new(InteractionShape {
19649                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19650            })
19651        })
19652    }
19653
19654    /// Phase E.6 + C.1: const-fn companion.
19655    /// # Errors
19656    /// Returns `ShapeViolation` if any required field is missing.
19657    pub const fn validate_const(
19658        &self,
19659    ) -> Result<Validated<InteractionShape, CompileTime>, ShapeViolation> {
19660        if self.peer_protocol.is_none() {
19661            return Err(ShapeViolation {
19662                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19663                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19664                property_iri: "https://uor.foundation/interaction/peerProtocol",
19665                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19666                min_count: 1,
19667                max_count: 1,
19668                kind: ViolationKind::Missing,
19669            });
19670        }
19671        if self.convergence_predicate.is_none() {
19672            return Err(ShapeViolation {
19673                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19674                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19675                property_iri: "https://uor.foundation/interaction/convergencePredicate",
19676                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19677                min_count: 1,
19678                max_count: 1,
19679                kind: ViolationKind::Missing,
19680            });
19681        }
19682        if self.commutator_state_class.is_none() {
19683            return Err(ShapeViolation {
19684                shape_iri: "https://uor.foundation/conformance/InteractionShape",
19685                constraint_iri: "https://uor.foundation/conformance/InteractionShape",
19686                property_iri: "https://uor.foundation/interaction/commutatorStateClass",
19687                expected_range: "http://www.w3.org/2002/07/owl#Thing",
19688                min_count: 1,
19689                max_count: 1,
19690                kind: ViolationKind::Missing,
19691            });
19692        }
19693        Ok(Validated::new(InteractionShape {
19694            shape_iri: "https://uor.foundation/conformance/InteractionShape",
19695        }))
19696    }
19697
19698    fn validate_common(&self) -> Result<(), ShapeViolation> {
19699        self.validate_const().map(|_| ())
19700    }
19701}
19702
19703/// Phase E.6: validated InteractionDeclaration per `conformance:InteractionShape`.
19704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19705pub struct InteractionShape {
19706    /// Shape IRI this declaration was validated against.
19707    pub shape_iri: &'static str,
19708}
19709
19710/// Phase E.5 (target §7.4): observability subscribe API.
19711/// When the `observability` feature is enabled, downstream may call
19712/// `subscribe_trace_events` with a handler closure that receives each
19713/// `TraceEvent` as the pipeline emits it. When the feature is off, this
19714/// function is entirely absent from the public API.
19715#[cfg(feature = "observability")]
19716pub fn subscribe_trace_events<F>(handler: F) -> ObservabilitySubscription<F>
19717where
19718    F: FnMut(&TraceEvent),
19719{
19720    ObservabilitySubscription {
19721        handler,
19722        _sealed: (),
19723    }
19724}
19725
19726#[cfg(feature = "observability")]
19727/// Phase E.5: sealed subscription handle returned by `subscribe_trace_events`.
19728#[cfg(feature = "observability")]
19729pub struct ObservabilitySubscription<F: FnMut(&TraceEvent)> {
19730    handler: F,
19731    _sealed: (),
19732}
19733
19734#[cfg(feature = "observability")]
19735impl<F: FnMut(&TraceEvent)> ObservabilitySubscription<F> {
19736    /// Dispatch a TraceEvent through the subscribed handler.
19737    pub fn emit(&mut self, event: &TraceEvent) {
19738        (self.handler)(event);
19739    }
19740}
19741
19742/// Phase F.2 (target §4.7): closed enumeration of the six constraint kinds.
19743/// `type-decl` bodies enumerate exactly these six kinds per `uor_term.ebnf`'s
19744/// `constraint-decl` production. `CompositeConstraint` — the implicit shape of
19745/// a multi-decl body — has no syntactic constructor and is therefore not a
19746/// variant of this enum.
19747#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19748#[non_exhaustive]
19749pub enum ConstraintKind {
19750    /// `type:ResidueConstraint` — value is congruent to `r (mod m)`.
19751    Residue,
19752    /// `type:CarryConstraint` — bounded carry depth.
19753    Carry,
19754    /// `type:DepthConstraint` — bounded derivation depth.
19755    Depth,
19756    /// `type:HammingConstraint` — bounded Hamming distance from a reference.
19757    Hamming,
19758    /// `type:SiteConstraint` — per-site cardinality or containment.
19759    Site,
19760    /// `type:AffineConstraint` — linear inequality over site values.
19761    Affine,
19762}
19763
19764/// Phase F.3 (target §4.7 carry): sealed per-ring-op carry profile.
19765#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19766pub struct CarryProfile {
19767    chain_length: u32,
19768    max_depth: u32,
19769    _sealed: (),
19770}
19771
19772impl CarryProfile {
19773    /// Length of the longest carry chain observed.
19774    #[inline]
19775    #[must_use]
19776    pub const fn chain_length(&self) -> u32 {
19777        self.chain_length
19778    }
19779
19780    /// Maximum carry depth across the op.
19781    #[inline]
19782    #[must_use]
19783    pub const fn max_depth(&self) -> u32 {
19784        self.max_depth
19785    }
19786
19787    /// Crate-internal constructor.
19788    #[inline]
19789    #[must_use]
19790    #[allow(dead_code)]
19791    pub(crate) const fn new(chain_length: u32, max_depth: u32) -> Self {
19792        Self {
19793            chain_length,
19794            max_depth,
19795            _sealed: (),
19796        }
19797    }
19798}
19799
19800/// Phase F.3 (target §4.7 carry): sealed carry-event witness — records the ring op
19801/// and two `Datum<L>` witt widths involved.
19802#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19803pub struct CarryEvent {
19804    left_bits: u16,
19805    right_bits: u16,
19806    _sealed: (),
19807}
19808
19809impl CarryEvent {
19810    /// Witt bit-width of the left operand.
19811    #[inline]
19812    #[must_use]
19813    pub const fn left_bits(&self) -> u16 {
19814        self.left_bits
19815    }
19816
19817    /// Witt bit-width of the right operand.
19818    #[inline]
19819    #[must_use]
19820    pub const fn right_bits(&self) -> u16 {
19821        self.right_bits
19822    }
19823
19824    /// Crate-internal constructor.
19825    #[inline]
19826    #[must_use]
19827    #[allow(dead_code)]
19828    pub(crate) const fn new(left_bits: u16, right_bits: u16) -> Self {
19829        Self {
19830            left_bits,
19831            right_bits,
19832            _sealed: (),
19833        }
19834    }
19835}
19836
19837/// Phase F.3 (target §4.7 convergence): sealed convergence-level witness at `L`.
19838#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19839pub struct ConvergenceLevel<L> {
19840    valuation: u32,
19841    _level: PhantomData<L>,
19842    _sealed: (),
19843}
19844
19845impl<L> ConvergenceLevel<L> {
19846    /// The v₂ valuation of the datum at this convergence level.
19847    #[inline]
19848    #[must_use]
19849    pub const fn valuation(&self) -> u32 {
19850        self.valuation
19851    }
19852
19853    /// Crate-internal constructor.
19854    #[inline]
19855    #[must_use]
19856    #[allow(dead_code)]
19857    pub(crate) const fn new(valuation: u32) -> Self {
19858        Self {
19859            valuation,
19860            _level: PhantomData,
19861            _sealed: (),
19862        }
19863    }
19864}
19865
19866/// Phase F.3 (target §4.7 division): sealed enum over the four normed division
19867/// algebras from Cayley-Dickson. No other admissible algebra exists (Hurwitz's theorem).
19868#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19869#[non_exhaustive]
19870pub enum DivisionAlgebraWitness {
19871    /// Real numbers ℝ (dimension 1).
19872    Real,
19873    /// Complex numbers ℂ (dimension 2).
19874    Complex,
19875    /// Quaternions ℍ (dimension 4, non-commutative).
19876    Quaternion,
19877    /// Octonions 𝕆 (dimension 8, non-commutative, non-associative).
19878    Octonion,
19879}
19880
19881/// Phase F.3 (target §4.7 monoidal): sealed monoidal-product witness.
19882#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19883pub struct MonoidalProduct<L, R> {
19884    _left: PhantomData<L>,
19885    _right: PhantomData<R>,
19886    _sealed: (),
19887}
19888
19889impl<L, R> MonoidalProduct<L, R> {
19890    /// Crate-internal constructor.
19891    #[inline]
19892    #[must_use]
19893    #[allow(dead_code)]
19894    pub(crate) const fn new() -> Self {
19895        Self {
19896            _left: PhantomData,
19897            _right: PhantomData,
19898            _sealed: (),
19899        }
19900    }
19901}
19902
19903/// Phase F.3 (target §4.7 monoidal): sealed monoidal-unit witness at `L`.
19904#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19905pub struct MonoidalUnit<L> {
19906    _level: PhantomData<L>,
19907    _sealed: (),
19908}
19909
19910impl<L> MonoidalUnit<L> {
19911    /// Crate-internal constructor.
19912    #[inline]
19913    #[must_use]
19914    #[allow(dead_code)]
19915    pub(crate) const fn new() -> Self {
19916        Self {
19917            _level: PhantomData,
19918            _sealed: (),
19919        }
19920    }
19921}
19922
19923/// Phase F.1 (target §4.7 operad): sealed operad-composition witness.
19924/// Every `type-app` form in the term grammar materializes a fresh `OperadComposition`
19925/// carrying the outer/inner type IRIs and composed site count, per `operad:` ontology.
19926#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19927pub struct OperadComposition {
19928    outer_type_iri: &'static str,
19929    inner_type_iri: &'static str,
19930    composed_site_count: u32,
19931    _sealed: (),
19932}
19933
19934impl OperadComposition {
19935    /// IRI of the outer `type:TypeDefinition`.
19936    #[inline]
19937    #[must_use]
19938    pub const fn outer_type_iri(&self) -> &'static str {
19939        self.outer_type_iri
19940    }
19941
19942    /// IRI of the inner `type:TypeDefinition`.
19943    #[inline]
19944    #[must_use]
19945    pub const fn inner_type_iri(&self) -> &'static str {
19946        self.inner_type_iri
19947    }
19948
19949    /// Site count of the composed type.
19950    #[inline]
19951    #[must_use]
19952    pub const fn composed_site_count(&self) -> u32 {
19953        self.composed_site_count
19954    }
19955
19956    /// Crate-internal constructor.
19957    #[inline]
19958    #[must_use]
19959    #[allow(dead_code)]
19960    pub(crate) const fn new(
19961        outer_type_iri: &'static str,
19962        inner_type_iri: &'static str,
19963        composed_site_count: u32,
19964    ) -> Self {
19965        Self {
19966            outer_type_iri,
19967            inner_type_iri,
19968            composed_site_count,
19969            _sealed: (),
19970        }
19971    }
19972}
19973
19974/// Phase F.3 (target §4.7 recursion): maximum depth of the recursion trace
19975/// witness. Bounded by the declared descent budget at builder-validate time;
19976/// the constant is a size-budget cap matching other foundation arenas.
19977/// Wiki ADR-037: a foundation-fixed conservative default for
19978/// [`crate::HostBounds::RECURSION_TRACE_DEPTH_MAX`].
19979pub const RECURSION_TRACE_MAX_DEPTH: usize = 16;
19980
19981/// Phase F.3 (target §4.7 recursion): sealed recursion trace with fixed-capacity
19982/// descent-measure sequence.
19983#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19984pub struct RecursionTrace {
19985    depth: u32,
19986    measure: [u32; RECURSION_TRACE_MAX_DEPTH],
19987    _sealed: (),
19988}
19989
19990impl RecursionTrace {
19991    /// Number of recursive descents in this trace.
19992    #[inline]
19993    #[must_use]
19994    pub const fn depth(&self) -> u32 {
19995        self.depth
19996    }
19997
19998    /// Descent-measure sequence.
19999    #[inline]
20000    #[must_use]
20001    pub const fn measure(&self) -> &[u32; RECURSION_TRACE_MAX_DEPTH] {
20002        &self.measure
20003    }
20004
20005    /// Crate-internal constructor.
20006    #[inline]
20007    #[must_use]
20008    #[allow(dead_code)]
20009    pub(crate) const fn new(depth: u32, measure: [u32; RECURSION_TRACE_MAX_DEPTH]) -> Self {
20010        Self {
20011            depth,
20012            measure,
20013            _sealed: (),
20014        }
20015    }
20016}
20017
20018/// Phase F.3 (target §4.7 region): sealed address-region witness.
20019#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20020pub struct AddressRegion {
20021    base: u128,
20022    extent: u64,
20023    _sealed: (),
20024}
20025
20026impl AddressRegion {
20027    /// Base address of the region.
20028    #[inline]
20029    #[must_use]
20030    pub const fn base(&self) -> u128 {
20031        self.base
20032    }
20033
20034    /// Extent (number of addressable cells).
20035    #[inline]
20036    #[must_use]
20037    pub const fn extent(&self) -> u64 {
20038        self.extent
20039    }
20040
20041    /// Crate-internal constructor.
20042    #[inline]
20043    #[must_use]
20044    #[allow(dead_code)]
20045    pub(crate) const fn new(base: u128, extent: u64) -> Self {
20046        Self {
20047            base,
20048            extent,
20049            _sealed: (),
20050        }
20051    }
20052}
20053
20054/// Phase F.3 (target §4.7 linear): sealed linear-resource budget.
20055#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20056pub struct LinearBudget {
20057    sites_remaining: u64,
20058    _sealed: (),
20059}
20060
20061impl LinearBudget {
20062    /// Number of linear sites still available for allocation.
20063    #[inline]
20064    #[must_use]
20065    pub const fn sites_remaining(&self) -> u64 {
20066        self.sites_remaining
20067    }
20068
20069    /// Crate-internal constructor.
20070    #[inline]
20071    #[must_use]
20072    #[allow(dead_code)]
20073    pub(crate) const fn new(sites_remaining: u64) -> Self {
20074        Self {
20075            sites_remaining,
20076            _sealed: (),
20077        }
20078    }
20079}
20080
20081/// Phase F.3 (target §4.7 linear): sealed lease-allocation witness.
20082#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20083pub struct LeaseAllocation {
20084    site_count: u32,
20085    scope_hash: u128,
20086    _sealed: (),
20087}
20088
20089impl LeaseAllocation {
20090    /// Number of linear sites taken by this allocation.
20091    #[inline]
20092    #[must_use]
20093    pub const fn site_count(&self) -> u32 {
20094        self.site_count
20095    }
20096
20097    /// Content-hash of the lease scope identifier.
20098    #[inline]
20099    #[must_use]
20100    pub const fn scope_hash(&self) -> u128 {
20101        self.scope_hash
20102    }
20103
20104    /// Crate-internal constructor.
20105    #[inline]
20106    #[must_use]
20107    #[allow(dead_code)]
20108    pub(crate) const fn new(site_count: u32, scope_hash: u128) -> Self {
20109        Self {
20110            site_count,
20111            scope_hash,
20112            _sealed: (),
20113        }
20114    }
20115}
20116
20117/// v0.2.2 Phase J: zero-sized token identifying the `Total` marker.
20118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20119pub struct TotalMarker;
20120
20121/// v0.2.2 Phase J: zero-sized token identifying the `Invertible` marker.
20122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20123pub struct InvertibleMarker;
20124
20125/// v0.2.2 Phase J: zero-sized token identifying the `PreservesStructure` marker.
20126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20127pub struct PreservesStructureMarker;
20128
20129mod marker_tuple_sealed {
20130    /// Private supertrait. Not implementable outside this crate.
20131    pub trait Sealed {}
20132}
20133
20134/// v0.2.2 Phase J: sealed marker-tuple trait. Implemented exhaustively by
20135/// the closed catalogue of six admissible marker tuples in canonical order
20136/// (Total, Invertible, PreservesStructure). Downstream cannot add new
20137/// marker tuples; the seal anchors Phase J's compile-time correctness claim.
20138pub trait MarkerTuple: marker_tuple_sealed::Sealed {}
20139
20140impl marker_tuple_sealed::Sealed for () {}
20141impl MarkerTuple for () {}
20142impl marker_tuple_sealed::Sealed for (TotalMarker,) {}
20143impl MarkerTuple for (TotalMarker,) {}
20144impl marker_tuple_sealed::Sealed for (TotalMarker, InvertibleMarker) {}
20145impl MarkerTuple for (TotalMarker, InvertibleMarker) {}
20146impl marker_tuple_sealed::Sealed for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {}
20147impl MarkerTuple for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {}
20148impl marker_tuple_sealed::Sealed for (InvertibleMarker,) {}
20149impl MarkerTuple for (InvertibleMarker,) {}
20150impl marker_tuple_sealed::Sealed for (InvertibleMarker, PreservesStructureMarker) {}
20151impl MarkerTuple for (InvertibleMarker, PreservesStructureMarker) {}
20152
20153/// v0.2.2 Phase J: type-level set intersection of two marker tuples.
20154/// Implemented exhaustively for every ordered pair in the closed catalogue.
20155/// Composition combinators (`then`, `and_then`) use this trait to compute
20156/// the output marker tuple of a composed primitive as the intersection of
20157/// its two inputs' tuples. Because the catalogue is closed, the result is
20158/// always another tuple in the catalogue — no open-world hazards.
20159pub trait MarkerIntersection<Other: MarkerTuple>: MarkerTuple {
20160    /// The intersection of `Self` and `Other` in the closed catalogue.
20161    type Output: MarkerTuple;
20162}
20163
20164impl MarkerIntersection<()> for () {
20165    type Output = ();
20166}
20167impl MarkerIntersection<(TotalMarker,)> for () {
20168    type Output = ();
20169}
20170impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for () {
20171    type Output = ();
20172}
20173impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)> for () {
20174    type Output = ();
20175}
20176impl MarkerIntersection<(InvertibleMarker,)> for () {
20177    type Output = ();
20178}
20179impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for () {
20180    type Output = ();
20181}
20182impl MarkerIntersection<()> for (TotalMarker,) {
20183    type Output = ();
20184}
20185impl MarkerIntersection<(TotalMarker,)> for (TotalMarker,) {
20186    type Output = (TotalMarker,);
20187}
20188impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (TotalMarker,) {
20189    type Output = (TotalMarker,);
20190}
20191impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20192    for (TotalMarker,)
20193{
20194    type Output = (TotalMarker,);
20195}
20196impl MarkerIntersection<(InvertibleMarker,)> for (TotalMarker,) {
20197    type Output = ();
20198}
20199impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for (TotalMarker,) {
20200    type Output = ();
20201}
20202impl MarkerIntersection<()> for (TotalMarker, InvertibleMarker) {
20203    type Output = ();
20204}
20205impl MarkerIntersection<(TotalMarker,)> for (TotalMarker, InvertibleMarker) {
20206    type Output = (TotalMarker,);
20207}
20208impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (TotalMarker, InvertibleMarker) {
20209    type Output = (TotalMarker, InvertibleMarker);
20210}
20211impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20212    for (TotalMarker, InvertibleMarker)
20213{
20214    type Output = (TotalMarker, InvertibleMarker);
20215}
20216impl MarkerIntersection<(InvertibleMarker,)> for (TotalMarker, InvertibleMarker) {
20217    type Output = (InvertibleMarker,);
20218}
20219impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20220    for (TotalMarker, InvertibleMarker)
20221{
20222    type Output = (InvertibleMarker,);
20223}
20224impl MarkerIntersection<()> for (TotalMarker, InvertibleMarker, PreservesStructureMarker) {
20225    type Output = ();
20226}
20227impl MarkerIntersection<(TotalMarker,)>
20228    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20229{
20230    type Output = (TotalMarker,);
20231}
20232impl MarkerIntersection<(TotalMarker, InvertibleMarker)>
20233    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20234{
20235    type Output = (TotalMarker, InvertibleMarker);
20236}
20237impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20238    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20239{
20240    type Output = (TotalMarker, InvertibleMarker, PreservesStructureMarker);
20241}
20242impl MarkerIntersection<(InvertibleMarker,)>
20243    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20244{
20245    type Output = (InvertibleMarker,);
20246}
20247impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20248    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20249{
20250    type Output = (InvertibleMarker, PreservesStructureMarker);
20251}
20252impl MarkerIntersection<()> for (InvertibleMarker,) {
20253    type Output = ();
20254}
20255impl MarkerIntersection<(TotalMarker,)> for (InvertibleMarker,) {
20256    type Output = ();
20257}
20258impl MarkerIntersection<(TotalMarker, InvertibleMarker)> for (InvertibleMarker,) {
20259    type Output = (InvertibleMarker,);
20260}
20261impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20262    for (InvertibleMarker,)
20263{
20264    type Output = (InvertibleMarker,);
20265}
20266impl MarkerIntersection<(InvertibleMarker,)> for (InvertibleMarker,) {
20267    type Output = (InvertibleMarker,);
20268}
20269impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)> for (InvertibleMarker,) {
20270    type Output = (InvertibleMarker,);
20271}
20272impl MarkerIntersection<()> for (InvertibleMarker, PreservesStructureMarker) {
20273    type Output = ();
20274}
20275impl MarkerIntersection<(TotalMarker,)> for (InvertibleMarker, PreservesStructureMarker) {
20276    type Output = ();
20277}
20278impl MarkerIntersection<(TotalMarker, InvertibleMarker)>
20279    for (InvertibleMarker, PreservesStructureMarker)
20280{
20281    type Output = (InvertibleMarker,);
20282}
20283impl MarkerIntersection<(TotalMarker, InvertibleMarker, PreservesStructureMarker)>
20284    for (InvertibleMarker, PreservesStructureMarker)
20285{
20286    type Output = (InvertibleMarker, PreservesStructureMarker);
20287}
20288impl MarkerIntersection<(InvertibleMarker,)> for (InvertibleMarker, PreservesStructureMarker) {
20289    type Output = (InvertibleMarker,);
20290}
20291impl MarkerIntersection<(InvertibleMarker, PreservesStructureMarker)>
20292    for (InvertibleMarker, PreservesStructureMarker)
20293{
20294    type Output = (InvertibleMarker, PreservesStructureMarker);
20295}
20296
20297/// v0.2.2 Phase J: compile-time check that a combinator's marker tuple
20298/// carries every property declared by the `GroundingMapKind` a program
20299/// claims. Implemented exhaustively by codegen for every valid `(tuple,
20300/// map)` pair; absent impls reject the mismatched declaration at the
20301/// `GroundingProgram::from_primitive` call site.
20302pub trait MarkersImpliedBy<Map: GroundingMapKind>: MarkerTuple {}
20303
20304/// v0.2.2 Phase J: bitmask encoding of a combinator's marker set.
20305/// Bit 0 = Total, bit 1 = Invertible, bit 2 = PreservesStructure.
20306#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20307pub struct MarkerBits(u8);
20308
20309impl MarkerBits {
20310    /// The `Total` marker bit.
20311    pub const TOTAL: Self = Self(1);
20312    /// The `Invertible` marker bit.
20313    pub const INVERTIBLE: Self = Self(2);
20314    /// The `PreservesStructure` marker bit.
20315    pub const PRESERVES_STRUCTURE: Self = Self(4);
20316    /// An empty marker set.
20317    pub const NONE: Self = Self(0);
20318
20319    /// Construct a marker bitmask from raw u8.
20320    #[inline]
20321    #[must_use]
20322    pub const fn from_u8(bits: u8) -> Self {
20323        Self(bits)
20324    }
20325
20326    /// Access the raw bitmask.
20327    #[inline]
20328    #[must_use]
20329    pub const fn as_u8(&self) -> u8 {
20330        self.0
20331    }
20332
20333    /// Bitwise OR of two marker bitmasks.
20334    #[inline]
20335    #[must_use]
20336    pub const fn union(self, other: Self) -> Self {
20337        Self(self.0 | other.0)
20338    }
20339
20340    /// Bitwise AND of two marker bitmasks (marker intersection).
20341    #[inline]
20342    #[must_use]
20343    pub const fn intersection(self, other: Self) -> Self {
20344        Self(self.0 & other.0)
20345    }
20346
20347    /// Whether this set contains all marker bits of `other`.
20348    #[inline]
20349    #[must_use]
20350    pub const fn contains(&self, other: Self) -> bool {
20351        (self.0 & other.0) == other.0
20352    }
20353}
20354
20355/// v0.2.2 Phase J: closed catalogue of grounding primitives.
20356/// Exactly 12 operations — read_bytes, interpret_le_integer,
20357/// interpret_be_integer, digest, decode_utf8, decode_json, select_field,
20358/// select_index, const_value, then, map_err, and_then. Adding a new
20359/// primitive is an ontology+grammar+codegen edit, not a Rust patch.
20360#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20361#[non_exhaustive]
20362pub enum GroundingPrimitiveOp {
20363    /// Read a fixed-size byte slice from the input.
20364    ReadBytes,
20365    /// Interpret bytes as a little-endian integer at the target WittLevel.
20366    InterpretLeInteger,
20367    /// Interpret bytes as a big-endian integer.
20368    InterpretBeInteger,
20369    /// Hash bytes via blake3 → 32-byte digest → `Datum<W256>`.
20370    /// # Scope
20371    /// `interpret_leaf_op` returns the first byte of the blake3 32-byte digest.
20372    /// The full digest is produced by `Datum<W256>` composition of 32 `Digest` leaves —
20373    /// the leaf-level output is the single-byte projection.
20374    Digest,
20375    /// Decode UTF-8 bytes; rejects malformed input.
20376    /// # Scope
20377    /// Only single-byte ASCII (`b < 0x80`) is decoded by `interpret_leaf_op`.
20378    /// Multi-byte UTF-8 is not decoded by this leaf; multi-byte sequences traverse the
20379    /// foundation via `GroundedTuple<N>` composition of single-byte leaves.
20380    DecodeUtf8,
20381    /// Decode JSON bytes; rejects malformed input.
20382    /// # Scope
20383    /// Only the leading byte of a JSON number scalar (`-` or ASCII digit) is parsed
20384    /// by `interpret_leaf_op`. Structured JSON values (objects, arrays, strings,
20385    /// multi-byte numbers) are not parsed by this leaf.
20386    DecodeJson,
20387    /// Select a field from a structured value.
20388    SelectField,
20389    /// Select an indexed element.
20390    SelectIndex,
20391    /// Inject a foundation-known constant.
20392    /// # Scope
20393    /// `interpret_leaf_op` returns `GroundedCoord::w8(0)` — the foundation-canonical
20394    /// zero constant. Non-zero constants are materialized through the const-fn frontier
20395    /// (`validate_const` paths) rather than through this leaf.
20396    ConstValue,
20397    /// Compose two combinators sequentially.
20398    Then,
20399    /// Map the error variant of a fallible combinator.
20400    MapErr,
20401    /// Conditional composition (and_then).
20402    AndThen,
20403}
20404
20405/// Max depth of a composed op chain retained inline inside
20406/// `GroundingPrimitive`. Depth-2 composites (`Then(leaf, leaf)`,
20407/// `AndThen(leaf, leaf)`) are the exercised shape today; 8 gives headroom
20408/// for nested composition while keeping `Copy` and `no_std` without alloc.
20409/// Wiki ADR-037: a foundation-fixed conservative default for
20410/// [`crate::HostBounds::OP_CHAIN_DEPTH_MAX`].
20411pub const MAX_OP_CHAIN_DEPTH: usize = 8;
20412
20413/// v0.2.2 Phase J: a single grounding primitive parametric over its output
20414/// type `Out` and its type-level marker tuple `Markers`.
20415/// Constructed only by the 12 enumerated combinator functions below;
20416/// downstream cannot construct one directly. The `Markers` parameter
20417/// defaults to `()` for backwards-compatible call sites, but each
20418/// combinator returns a specific tuple — see `combinators::digest` etc.
20419/// For leaf primitives `chain_len == 0`. For `Then`/`AndThen`/`MapErr`
20420/// composites, `chain[..chain_len as usize]` is the linearized post-order
20421/// sequence of leaf primitive ops the interpreter walks.
20422#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20423pub struct GroundingPrimitive<Out, Markers: MarkerTuple = ()> {
20424    op: GroundingPrimitiveOp,
20425    markers: MarkerBits,
20426    chain: [GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH],
20427    chain_len: u8,
20428    _out: PhantomData<Out>,
20429    _markers: PhantomData<Markers>,
20430    _sealed: (),
20431}
20432
20433impl<Out, Markers: MarkerTuple> GroundingPrimitive<Out, Markers> {
20434    /// Access the primitive op.
20435    #[inline]
20436    #[must_use]
20437    pub const fn op(&self) -> GroundingPrimitiveOp {
20438        self.op
20439    }
20440
20441    /// Access the runtime marker bitmask (mirrors the type-level tuple).
20442    #[inline]
20443    #[must_use]
20444    pub const fn markers(&self) -> MarkerBits {
20445        self.markers
20446    }
20447
20448    /// Access the recorded composition chain. Empty for leaf primitives;
20449    /// the post-order leaf-op sequence for `Then`/`AndThen`/`MapErr`.
20450    #[inline]
20451    #[must_use]
20452    pub fn chain(&self) -> &[GroundingPrimitiveOp] {
20453        &self.chain[..self.chain_len as usize]
20454    }
20455
20456    /// Crate-internal constructor for a leaf primitive (no recorded chain).
20457    /// The type-level `Markers` tuple is selected via turbofish at call
20458    /// sites inside the combinator functions.
20459    #[inline]
20460    #[must_use]
20461    #[allow(dead_code)]
20462    pub(crate) const fn from_parts(op: GroundingPrimitiveOp, markers: MarkerBits) -> Self {
20463        Self {
20464            op,
20465            markers,
20466            chain: [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH],
20467            chain_len: 0,
20468            _out: PhantomData,
20469            _markers: PhantomData,
20470            _sealed: (),
20471        }
20472    }
20473
20474    /// Crate-internal constructor for a composite primitive. Stores
20475    /// `chain[..chain_len]` inline; accessors expose only the prefix.
20476    #[inline]
20477    #[must_use]
20478    #[allow(dead_code)]
20479    pub(crate) const fn from_parts_with_chain(
20480        op: GroundingPrimitiveOp,
20481        markers: MarkerBits,
20482        chain: [GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH],
20483        chain_len: u8,
20484    ) -> Self {
20485        Self {
20486            op,
20487            markers,
20488            chain,
20489            chain_len,
20490            _out: PhantomData,
20491            _markers: PhantomData,
20492            _sealed: (),
20493        }
20494    }
20495}
20496
20497/// v0.2.2 Phase J: closed 12-combinator surface for building grounding
20498/// programs. See `GroundingProgram` for composition. Each leaf combinator
20499/// returns a `GroundingPrimitive<Out, M>` carrying a specific marker tuple;
20500/// the type parameter is what `GroundingProgram::from_primitive`'s
20501/// `MarkersImpliedBy<Map>` bound checks at compile time.
20502pub mod combinators {
20503    use super::{
20504        GroundingPrimitive, GroundingPrimitiveOp, InvertibleMarker, MarkerBits, MarkerIntersection,
20505        MarkerTuple, PreservesStructureMarker, TotalMarker, MAX_OP_CHAIN_DEPTH,
20506    };
20507
20508    /// Build the post-order leaf-op chain for a sequential composite:
20509    /// `first.chain ++ [first.op] ++ second.chain ++ [second.op]`.
20510    /// Saturated to `MAX_OP_CHAIN_DEPTH`.
20511    fn compose_chain<A, B, MA: MarkerTuple, MB: MarkerTuple>(
20512        first: &GroundingPrimitive<A, MA>,
20513        second: &GroundingPrimitive<B, MB>,
20514    ) -> ([GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH], u8) {
20515        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20516        let mut len: usize = 0;
20517        for &op in first.chain() {
20518            if len >= MAX_OP_CHAIN_DEPTH {
20519                return (chain, len as u8);
20520            }
20521            chain[len] = op;
20522            len += 1;
20523        }
20524        if len < MAX_OP_CHAIN_DEPTH {
20525            chain[len] = first.op();
20526            len += 1;
20527        }
20528        for &op in second.chain() {
20529            if len >= MAX_OP_CHAIN_DEPTH {
20530                return (chain, len as u8);
20531            }
20532            chain[len] = op;
20533            len += 1;
20534        }
20535        if len < MAX_OP_CHAIN_DEPTH {
20536            chain[len] = second.op();
20537            len += 1;
20538        }
20539        (chain, len as u8)
20540    }
20541
20542    /// Build the chain for `map_err(first)`: `first.chain ++ [first.op]`.
20543    fn map_err_chain<A, M: MarkerTuple>(
20544        first: &GroundingPrimitive<A, M>,
20545    ) -> ([GroundingPrimitiveOp; MAX_OP_CHAIN_DEPTH], u8) {
20546        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20547        let mut len: usize = 0;
20548        for &op in first.chain() {
20549            if len >= MAX_OP_CHAIN_DEPTH {
20550                return (chain, len as u8);
20551            }
20552            chain[len] = op;
20553            len += 1;
20554        }
20555        if len < MAX_OP_CHAIN_DEPTH {
20556            chain[len] = first.op();
20557            len += 1;
20558        }
20559        (chain, len as u8)
20560    }
20561
20562    /// Read a fixed-size byte slice from the input. `(Total, Invertible)`.
20563    #[inline]
20564    #[must_use]
20565    pub const fn read_bytes<Out>() -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker)> {
20566        GroundingPrimitive::from_parts(
20567            GroundingPrimitiveOp::ReadBytes,
20568            MarkerBits::TOTAL.union(MarkerBits::INVERTIBLE),
20569        )
20570    }
20571
20572    /// Interpret bytes as a little-endian integer at the target WittLevel.
20573    #[inline]
20574    #[must_use]
20575    pub const fn interpret_le_integer<Out>(
20576    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20577        GroundingPrimitive::from_parts(
20578            GroundingPrimitiveOp::InterpretLeInteger,
20579            MarkerBits::TOTAL
20580                .union(MarkerBits::INVERTIBLE)
20581                .union(MarkerBits::PRESERVES_STRUCTURE),
20582        )
20583    }
20584
20585    /// Interpret bytes as a big-endian integer.
20586    #[inline]
20587    #[must_use]
20588    pub const fn interpret_be_integer<Out>(
20589    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20590        GroundingPrimitive::from_parts(
20591            GroundingPrimitiveOp::InterpretBeInteger,
20592            MarkerBits::TOTAL
20593                .union(MarkerBits::INVERTIBLE)
20594                .union(MarkerBits::PRESERVES_STRUCTURE),
20595        )
20596    }
20597
20598    /// Hash bytes via blake3 → 32-byte digest → `Datum<W256>`. `(Total,)` only.
20599    #[inline]
20600    #[must_use]
20601    pub const fn digest<Out>() -> GroundingPrimitive<Out, (TotalMarker,)> {
20602        GroundingPrimitive::from_parts(GroundingPrimitiveOp::Digest, MarkerBits::TOTAL)
20603    }
20604
20605    /// Decode UTF-8 bytes. `(Invertible, PreservesStructure)` — not Total.
20606    #[inline]
20607    #[must_use]
20608    pub const fn decode_utf8<Out>(
20609    ) -> GroundingPrimitive<Out, (InvertibleMarker, PreservesStructureMarker)> {
20610        GroundingPrimitive::from_parts(
20611            GroundingPrimitiveOp::DecodeUtf8,
20612            MarkerBits::INVERTIBLE.union(MarkerBits::PRESERVES_STRUCTURE),
20613        )
20614    }
20615
20616    /// Decode JSON bytes. `(Invertible, PreservesStructure)` — not Total.
20617    #[inline]
20618    #[must_use]
20619    pub const fn decode_json<Out>(
20620    ) -> GroundingPrimitive<Out, (InvertibleMarker, PreservesStructureMarker)> {
20621        GroundingPrimitive::from_parts(
20622            GroundingPrimitiveOp::DecodeJson,
20623            MarkerBits::INVERTIBLE.union(MarkerBits::PRESERVES_STRUCTURE),
20624        )
20625    }
20626
20627    /// Select a field from a structured value. `(Invertible,)` — not Total.
20628    #[inline]
20629    #[must_use]
20630    pub const fn select_field<Out>() -> GroundingPrimitive<Out, (InvertibleMarker,)> {
20631        GroundingPrimitive::from_parts(GroundingPrimitiveOp::SelectField, MarkerBits::INVERTIBLE)
20632    }
20633
20634    /// Select an indexed element. `(Invertible,)` — not Total.
20635    #[inline]
20636    #[must_use]
20637    pub const fn select_index<Out>() -> GroundingPrimitive<Out, (InvertibleMarker,)> {
20638        GroundingPrimitive::from_parts(GroundingPrimitiveOp::SelectIndex, MarkerBits::INVERTIBLE)
20639    }
20640
20641    /// Inject a foundation-known constant. `(Total, Invertible, PreservesStructure)`.
20642    #[inline]
20643    #[must_use]
20644    pub const fn const_value<Out>(
20645    ) -> GroundingPrimitive<Out, (TotalMarker, InvertibleMarker, PreservesStructureMarker)> {
20646        GroundingPrimitive::from_parts(
20647            GroundingPrimitiveOp::ConstValue,
20648            MarkerBits::TOTAL
20649                .union(MarkerBits::INVERTIBLE)
20650                .union(MarkerBits::PRESERVES_STRUCTURE),
20651        )
20652    }
20653
20654    /// Compose two combinators sequentially. Markers are intersected at
20655    /// the type level via the `MarkerIntersection` trait. The recorded
20656    /// leaf-op chain lets the foundation's interpreter walk the operands
20657    /// at runtime.
20658    #[inline]
20659    #[must_use]
20660    pub fn then<A, B, MA, MB>(
20661        first: GroundingPrimitive<A, MA>,
20662        second: GroundingPrimitive<B, MB>,
20663    ) -> GroundingPrimitive<B, <MA as MarkerIntersection<MB>>::Output>
20664    where
20665        MA: MarkerTuple + MarkerIntersection<MB>,
20666        MB: MarkerTuple,
20667    {
20668        let (chain, chain_len) = compose_chain(&first, &second);
20669        GroundingPrimitive::from_parts_with_chain(
20670            GroundingPrimitiveOp::Then,
20671            first.markers().intersection(second.markers()),
20672            chain,
20673            chain_len,
20674        )
20675    }
20676
20677    /// Map an error variant of a fallible combinator. Marker tuple
20678    /// is preserved. The operand's op is recorded so the interpreter's
20679    /// `MapErr` arm can forward the success value.
20680    #[inline]
20681    #[must_use]
20682    pub fn map_err<A, M: MarkerTuple>(first: GroundingPrimitive<A, M>) -> GroundingPrimitive<A, M> {
20683        let (chain, chain_len) = map_err_chain(&first);
20684        GroundingPrimitive::from_parts_with_chain(
20685            GroundingPrimitiveOp::MapErr,
20686            first.markers(),
20687            chain,
20688            chain_len,
20689        )
20690    }
20691
20692    /// Conditional composition (and_then). Markers are intersected; the
20693    /// recorded chain mirrors `then` so the interpreter walks operands.
20694    #[inline]
20695    #[must_use]
20696    pub fn and_then<A, B, MA, MB>(
20697        first: GroundingPrimitive<A, MA>,
20698        second: GroundingPrimitive<B, MB>,
20699    ) -> GroundingPrimitive<B, <MA as MarkerIntersection<MB>>::Output>
20700    where
20701        MA: MarkerTuple + MarkerIntersection<MB>,
20702        MB: MarkerTuple,
20703    {
20704        let (chain, chain_len) = compose_chain(&first, &second);
20705        GroundingPrimitive::from_parts_with_chain(
20706            GroundingPrimitiveOp::AndThen,
20707            first.markers().intersection(second.markers()),
20708            chain,
20709            chain_len,
20710        )
20711    }
20712}
20713
20714/// v0.2.2 Phase J: sealed grounding program.
20715/// A composition of combinators with a statically tracked marker tuple.
20716/// Constructed only via `GroundingProgram::from_primitive`, which requires
20717/// via the `MarkersImpliedBy<Map>` trait bound that the primitive's marker
20718/// tuple carries every property declared by `Map: GroundingMapKind`.
20719#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20720pub struct GroundingProgram<Out, Map: GroundingMapKind> {
20721    primitive: GroundingPrimitive<Out>,
20722    _map: PhantomData<Map>,
20723    _sealed: (),
20724}
20725
20726impl<Out, Map: GroundingMapKind> GroundingProgram<Out, Map> {
20727    /// Foundation-verified constructor. Accepts a primitive whose marker
20728    /// tuple satisfies `MarkersImpliedBy<Map>`. Programs built from
20729    /// combinators whose marker tuple lacks a property `Map` requires are
20730    /// rejected at compile time — this is Phase J's marquee correctness
20731    /// claim: misdeclarations fail to compile.
20732    /// # Example: valid program
20733    /// ```
20734    /// use uor_foundation::enforcement::{GroundingProgram, IntegerGroundingMap, combinators};
20735    /// let prog: GroundingProgram<u64, IntegerGroundingMap> =
20736    ///     GroundingProgram::from_primitive(combinators::interpret_le_integer::<u64>());
20737    /// let _ = prog;
20738    /// ```
20739    /// # Example: rejected misdeclaration
20740    /// ```compile_fail
20741    /// use uor_foundation::enforcement::{GroundingProgram, IntegerGroundingMap, combinators};
20742    /// // digest returns (TotalMarker,) which does NOT satisfy
20743    /// // MarkersImpliedBy<IntegerGroundingMap> — the line below fails to compile.
20744    /// let prog: GroundingProgram<[u8; 32], IntegerGroundingMap> =
20745    ///     GroundingProgram::from_primitive(combinators::digest::<[u8; 32]>());
20746    /// let _ = prog;
20747    /// ```
20748    #[inline]
20749    #[must_use]
20750    pub fn from_primitive<Markers>(primitive: GroundingPrimitive<Out, Markers>) -> Self
20751    where
20752        Markers: MarkerTuple + MarkersImpliedBy<Map>,
20753    {
20754        // Preserve the composition chain so the interpreter can walk
20755        // operands of Then/AndThen/MapErr composites.
20756        let mut chain = [GroundingPrimitiveOp::ReadBytes; MAX_OP_CHAIN_DEPTH];
20757        let src = primitive.chain();
20758        let mut i = 0;
20759        while i < src.len() && i < MAX_OP_CHAIN_DEPTH {
20760            chain[i] = src[i];
20761            i += 1;
20762        }
20763        let erased = GroundingPrimitive::<Out, ()>::from_parts_with_chain(
20764            primitive.op(),
20765            primitive.markers(),
20766            chain,
20767            i as u8,
20768        );
20769        Self {
20770            primitive: erased,
20771            _map: PhantomData,
20772            _sealed: (),
20773        }
20774    }
20775
20776    /// Access the underlying primitive (erased marker tuple).
20777    #[inline]
20778    #[must_use]
20779    pub const fn primitive(&self) -> &GroundingPrimitive<Out> {
20780        &self.primitive
20781    }
20782}
20783
20784/// Phase K (target §4.3 / §9 criterion 1): foundation-supplied interpreter for
20785/// grounding programs whose `Out` is `GroundedCoord`. Handles every op in
20786/// the closed 12-combinator catalogue: leaf ops (`ReadBytes`,
20787/// `InterpretLeInteger`, `InterpretBeInteger`, `Digest`, `DecodeUtf8`,
20788/// `DecodeJson`, `ConstValue`, `SelectField`, `SelectIndex`) call
20789/// `interpret_leaf_op` directly; composition ops (`Then`, `AndThen`,
20790/// `MapErr`) walk the chain recorded in the primitive and thread
20791/// `external` through each leaf step. The interpreter surfaces
20792/// `GroundedCoord::w8(byte)` values; richer outputs compose through
20793/// combinator chains producing `GroundedTuple<N>`. No `ground()`
20794/// override exists after W4 closure — downstream provides only
20795/// `program()`, and `GroundingExt::ground` is foundation-authored.
20796impl<Map: GroundingMapKind> GroundingProgram<GroundedCoord, Map> {
20797    /// Run this program on external bytes, producing a `GroundedCoord`.
20798    /// Returns `None` if the input is malformed/undersized for the
20799    /// program's op chain.
20800    #[inline]
20801    #[must_use]
20802    pub fn run(&self, external: &[u8]) -> Option<GroundedCoord> {
20803        match self.primitive.op() {
20804            GroundingPrimitiveOp::Then | GroundingPrimitiveOp::AndThen => {
20805                let chain = self.primitive.chain();
20806                if chain.is_empty() {
20807                    return None;
20808                }
20809                let mut last: Option<GroundedCoord> = None;
20810                for &op in chain {
20811                    match interpret_leaf_op(op, external) {
20812                        Some(c) => last = Some(c),
20813                        None => return None,
20814                    }
20815                }
20816                last
20817            }
20818            GroundingPrimitiveOp::MapErr => self
20819                .primitive
20820                .chain()
20821                .first()
20822                .and_then(|&op| interpret_leaf_op(op, external)),
20823            leaf => interpret_leaf_op(leaf, external),
20824        }
20825    }
20826}
20827
20828/// W4 closure (target §4.3 + §9 criterion 1): foundation-supplied
20829/// interpreter for programs producing `GroundedTuple<N>`. Splits
20830/// `external` into `N` equal windows and runs the same dispatch
20831/// that `GroundingProgram<GroundedCoord, Map>::run` performs on
20832/// each window. Returns `None` if `N == 0`, the input is empty,
20833/// the input length isn't divisible by `N`, or any window fails.
20834impl<const N: usize, Map: GroundingMapKind> GroundingProgram<GroundedTuple<N>, Map> {
20835    /// Run this program on external bytes, producing a `GroundedTuple<N>`.
20836    #[inline]
20837    #[must_use]
20838    pub fn run(&self, external: &[u8]) -> Option<GroundedTuple<N>> {
20839        if N == 0 || external.is_empty() || external.len() % N != 0 {
20840            return None;
20841        }
20842        let window = external.len() / N;
20843        let mut coords: [GroundedCoord; N] = [const { GroundedCoord::w8(0) }; N];
20844        let mut i = 0usize;
20845        while i < N {
20846            let start = i * window;
20847            let end = start + window;
20848            let sub = &external[start..end];
20849            // Walk this window through the same leaf/composition
20850            // dispatch as the GroundedCoord interpreter above. A
20851            // helper that runs the chain is reused via the same
20852            // primitive accessors.
20853            let outcome = match self.primitive.op() {
20854                GroundingPrimitiveOp::Then | GroundingPrimitiveOp::AndThen => {
20855                    let chain = self.primitive.chain();
20856                    if chain.is_empty() {
20857                        return None;
20858                    }
20859                    let mut last: Option<GroundedCoord> = None;
20860                    for &op in chain {
20861                        match interpret_leaf_op(op, sub) {
20862                            Some(c) => last = Some(c),
20863                            None => return None,
20864                        }
20865                    }
20866                    last
20867                }
20868                GroundingPrimitiveOp::MapErr => self
20869                    .primitive
20870                    .chain()
20871                    .first()
20872                    .and_then(|&op| interpret_leaf_op(op, sub)),
20873                leaf => interpret_leaf_op(leaf, sub),
20874            };
20875            match outcome {
20876                Some(c) => {
20877                    coords[i] = c;
20878                }
20879                None => {
20880                    return None;
20881                }
20882            }
20883            i += 1;
20884        }
20885        Some(GroundedTuple::new(coords))
20886    }
20887}
20888
20889/// Foundation-canonical leaf-op interpreter. Called directly by
20890/// `GroundingProgram::run` for leaf primitives and step-by-step for
20891/// composition ops.
20892#[inline]
20893fn interpret_leaf_op(op: GroundingPrimitiveOp, external: &[u8]) -> Option<GroundedCoord> {
20894    match op {
20895        GroundingPrimitiveOp::ReadBytes | GroundingPrimitiveOp::InterpretLeInteger => {
20896            external.first().map(|&b| GroundedCoord::w8(b))
20897        }
20898        GroundingPrimitiveOp::InterpretBeInteger => external.last().map(|&b| GroundedCoord::w8(b)),
20899        GroundingPrimitiveOp::Digest => {
20900            // Foundation-canonical digest: first byte as `GroundedCoord` —
20901            // the full 32-byte digest requires a Datum<W256> sink that does
20902            // not fit in `GroundedCoord`. Downstream that needs the full
20903            // digest composes a richer program via Then/AndThen chains over
20904            // the 12 closed combinators — no `ground()` override exists after
20905            // W4 closure.
20906            external.first().map(|&b| GroundedCoord::w8(b))
20907        }
20908        GroundingPrimitiveOp::DecodeUtf8 => {
20909            // ASCII single-byte path — the canonical v0.2.2 semantics for
20910            // `Grounding::ground` over `GroundedCoord` outputs. Multi-byte
20911            // UTF-8 sequences are out of scope for w8-sized leaves; a richer
20912            // structured output composes via combinator chains into
20913            // `GroundedTuple<N>`.
20914            match external.first() {
20915                Some(&b) if b < 0x80 => Some(GroundedCoord::w8(b)),
20916                _ => None,
20917            }
20918        }
20919        GroundingPrimitiveOp::DecodeJson => {
20920            // Accept JSON number scalars (leading `-` or ASCII digit).
20921            match external.first() {
20922                Some(&b) if b == b'-' || b.is_ascii_digit() => Some(GroundedCoord::w8(b)),
20923                _ => None,
20924            }
20925        }
20926        GroundingPrimitiveOp::ConstValue => Some(GroundedCoord::w8(0)),
20927        GroundingPrimitiveOp::SelectField | GroundingPrimitiveOp::SelectIndex => {
20928            // Selector ops are composition-only in normal use; if invoked
20929            // directly, forward the first byte as a GroundedCoord.
20930            external.first().map(|&b| GroundedCoord::w8(b))
20931        }
20932        GroundingPrimitiveOp::Then
20933        | GroundingPrimitiveOp::AndThen
20934        | GroundingPrimitiveOp::MapErr => {
20935            // Composite ops are dispatched by `run()` through the chain;
20936            // they never reach the leaf interpreter.
20937            None
20938        }
20939    }
20940}
20941
20942/// v0.2.2 Phase J: MarkersImpliedBy impls for the closed catalogue of valid
20943/// (marker tuple, GroundingMapKind) pairs. These are the compile-time
20944/// witnesses the foundation accepts; every absent pair is a rejection.
20945impl MarkersImpliedBy<DigestGroundingMap> for (TotalMarker,) {}
20946impl MarkersImpliedBy<BinaryGroundingMap> for (TotalMarker, InvertibleMarker) {}
20947impl MarkersImpliedBy<DigestGroundingMap> for (TotalMarker, InvertibleMarker) {}
20948impl MarkersImpliedBy<BinaryGroundingMap>
20949    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20950{
20951}
20952impl MarkersImpliedBy<DigestGroundingMap>
20953    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20954{
20955}
20956impl MarkersImpliedBy<IntegerGroundingMap>
20957    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20958{
20959}
20960impl MarkersImpliedBy<JsonGroundingMap>
20961    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20962{
20963}
20964impl MarkersImpliedBy<Utf8GroundingMap>
20965    for (TotalMarker, InvertibleMarker, PreservesStructureMarker)
20966{
20967}
20968impl MarkersImpliedBy<JsonGroundingMap> for (InvertibleMarker, PreservesStructureMarker) {}
20969impl MarkersImpliedBy<Utf8GroundingMap> for (InvertibleMarker, PreservesStructureMarker) {}
20970
20971/// v0.2.2 T2.5: foundation-private test-only back-door module.
20972/// Exposes crate-internal constructors for `Trace`, `TraceEvent`, and
20973/// `MulContext` to the `uor-foundation-test-helpers` workspace member, which
20974/// re-exports them under stable test-only names. Not part of the public API.
20975#[doc(hidden)]
20976pub mod __test_helpers {
20977    use super::{ContentAddress, ContentFingerprint, MulContext, Trace, TraceEvent, Validated};
20978
20979    /// Test-only ctor: build a Trace from a slice of events with a
20980    /// `ContentFingerprint::zero()` placeholder. Tests that need a non-zero
20981    /// fingerprint use `trace_with_fingerprint` instead. Parametric in
20982    /// `TR_MAX` per the wiki's ADR-018; callers pick the trace event-count
20983    /// ceiling from their selected `HostBounds`.
20984    #[must_use]
20985    pub fn trace_from_events<const TR_MAX: usize>(events: &[TraceEvent]) -> Trace<TR_MAX> {
20986        trace_with_fingerprint(events, 0, ContentFingerprint::zero())
20987    }
20988
20989    /// Test-only ctor that takes an explicit `witt_level_bits` and
20990    /// `ContentFingerprint`. Used by round-trip tests that need to verify
20991    /// the verify-trace fingerprint passthrough invariant.
20992    #[must_use]
20993    pub fn trace_with_fingerprint<const TR_MAX: usize>(
20994        events: &[TraceEvent],
20995        witt_level_bits: u16,
20996        content_fingerprint: ContentFingerprint,
20997    ) -> Trace<TR_MAX> {
20998        let mut arr = [None; TR_MAX];
20999        let n = events.len().min(TR_MAX);
21000        let mut i = 0;
21001        while i < n {
21002            arr[i] = Some(events[i]);
21003            i += 1;
21004        }
21005        // The test-helpers back-door uses the foundation-private
21006        // `from_replay_events_const` to build malformed fixtures for error-path
21007        // tests. Downstream code uses `Trace::try_from_events` (validating).
21008        Trace::from_replay_events_const(arr, n as u16, witt_level_bits, content_fingerprint)
21009    }
21010
21011    /// Test-only ctor: build a TraceEvent.
21012    #[must_use]
21013    pub fn trace_event(step_index: u32, target: u128) -> TraceEvent {
21014        TraceEvent::new(
21015            step_index,
21016            crate::PrimitiveOp::Add,
21017            ContentAddress::from_u128(target),
21018        )
21019    }
21020
21021    /// Test-only ctor: build a MulContext.
21022    #[must_use]
21023    pub fn mul_context(stack_budget_bytes: u64, const_eval: bool, limb_count: usize) -> MulContext {
21024        MulContext::new(stack_budget_bytes, const_eval, limb_count)
21025    }
21026
21027    /// Test-only ctor: wrap any T in a Runtime-phase Validated. Used by
21028    /// integration tests to construct `Validated<Decl, P>` values that
21029    /// the public API otherwise can't construct directly.
21030    #[must_use]
21031    pub fn validated_runtime<T>(inner: T) -> Validated<T> {
21032        Validated::new(inner)
21033    }
21034}
21035
21036/// Tolerance for entropy equality checks in the Product/Coproduct
21037/// Completion Amendment mint primitives. Returns an absolute-error bound
21038/// scaled to the magnitude of `expected`, so PT_4 / ST_2 / CPT_5
21039/// verifications are robust to floating-point rounding accumulated through
21040/// Künneth products and componentwise sums. The default-host (f64) backing
21041/// is hidden behind the `DefaultDecimal` alias so the function signature
21042/// reads as host-typed; downstream that swaps `H::Decimal` reaches the
21043/// same surface via the alias rebind.
21044type DefaultDecimal = <crate::DefaultHostTypes as crate::HostTypes>::Decimal;
21045
21046#[inline]
21047const fn pc_entropy_tolerance(expected: DefaultDecimal) -> DefaultDecimal {
21048    let magnitude = if expected < 0.0 { -expected } else { expected };
21049    let scale = if magnitude > 1.0 { magnitude } else { 1.0 };
21050    1024.0 * <DefaultDecimal>::EPSILON * scale
21051}
21052
21053/// Validate an entropy value before participating in additivity checks.
21054/// Rejects NaN, ±∞, and negative values — the foundation's
21055/// `primitive_descent_metrics` produces `residual × LN_2` with
21056/// `residual: u32`, so valid entropies are non-negative finite Decimals.
21057#[inline]
21058fn pc_entropy_input_is_valid(value: DefaultDecimal) -> bool {
21059    value.is_finite() && value >= 0.0
21060}
21061
21062/// Check that `actual` matches `expected` within tolerance and that both
21063/// inputs are valid entropy values. Returns `false` if either input is
21064/// non-finite, negative, or differs from `expected` by more than
21065/// `pc_entropy_tolerance(expected)`.
21066#[inline]
21067fn pc_entropy_additivity_holds(actual: DefaultDecimal, expected: DefaultDecimal) -> bool {
21068    if !pc_entropy_input_is_valid(actual) || !pc_entropy_input_is_valid(expected) {
21069        return false;
21070    }
21071    let diff = actual - expected;
21072    let diff_abs = if diff < 0.0 { -diff } else { diff };
21073    diff_abs <= pc_entropy_tolerance(expected)
21074}
21075
21076/// Evidence bundle for `PartitionProductWitness`. Carries the PT_1 / PT_3 /
21077/// PT_4 input values used at mint time. Derives `PartialEq` only because
21078/// `f64` entropy fields exclude `Eq` / `Hash`; this is the auditing surface,
21079/// not a hash-map key.
21080#[derive(Debug, Clone, Copy, PartialEq)]
21081pub struct PartitionProductEvidence {
21082    /// Left operand `siteBudget` (data sites only, PT_1 input).
21083    pub left_site_budget: u16,
21084    /// Right operand `siteBudget`.
21085    pub right_site_budget: u16,
21086    /// Left operand `SITE_COUNT` (layout width, layout-invariant input).
21087    pub left_total_site_count: u16,
21088    /// Right operand `SITE_COUNT`.
21089    pub right_total_site_count: u16,
21090    /// Left operand Euler characteristic (PT_3 input).
21091    pub left_euler: i32,
21092    /// Right operand Euler characteristic.
21093    pub right_euler: i32,
21094    /// Left operand entropy in nats (PT_4 input).
21095    pub left_entropy_nats_bits: u64,
21096    /// Right operand entropy in nats.
21097    pub right_entropy_nats_bits: u64,
21098    /// Fingerprint of the source witness the evidence belongs to.
21099    pub source_witness_fingerprint: ContentFingerprint,
21100}
21101
21102/// Evidence bundle for `PartitionCoproductWitness`. Carries the
21103/// ST_1 / ST_2 / ST_9 / ST_10 input values used at mint time.
21104#[derive(Debug, Clone, Copy, PartialEq)]
21105pub struct PartitionCoproductEvidence {
21106    pub left_site_budget: u16,
21107    pub right_site_budget: u16,
21108    pub left_total_site_count: u16,
21109    pub right_total_site_count: u16,
21110    pub left_euler: i32,
21111    pub right_euler: i32,
21112    pub left_entropy_nats_bits: u64,
21113    pub right_entropy_nats_bits: u64,
21114    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21115    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21116    pub source_witness_fingerprint: ContentFingerprint,
21117}
21118
21119/// Evidence bundle for `CartesianProductWitness`. Carries the
21120/// CPT_1 / CPT_3 / CPT_4 / CPT_5 input values used at mint time, plus
21121/// `combined_entropy_nats` — the CartesianProductWitness itself does not
21122/// store entropy (see §1a), so the evidence sidecar preserves the
21123/// verification target value for re-audit.
21124#[derive(Debug, Clone, Copy, PartialEq)]
21125pub struct CartesianProductEvidence {
21126    pub left_site_budget: u16,
21127    pub right_site_budget: u16,
21128    pub left_total_site_count: u16,
21129    pub right_total_site_count: u16,
21130    pub left_euler: i32,
21131    pub right_euler: i32,
21132    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21133    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21134    pub left_entropy_nats_bits: u64,
21135    pub right_entropy_nats_bits: u64,
21136    pub combined_entropy_nats_bits: u64,
21137    pub source_witness_fingerprint: ContentFingerprint,
21138}
21139
21140/// Inputs to `PartitionProductWitness::mint_verified`. Mirrors the
21141/// underlying primitive's parameter list; each field is supplied by the
21142/// caller (typically a `product_shape!` macro expansion or a manual
21143/// construction following the amendment's Gap 2 pattern). Derives
21144/// `PartialEq` only because of the `f64` entropy fields.
21145#[derive(Debug, Clone, Copy, PartialEq)]
21146pub struct PartitionProductMintInputs {
21147    pub witt_bits: u16,
21148    pub left_fingerprint: ContentFingerprint,
21149    pub right_fingerprint: ContentFingerprint,
21150    pub left_site_budget: u16,
21151    pub right_site_budget: u16,
21152    pub left_total_site_count: u16,
21153    pub right_total_site_count: u16,
21154    pub left_euler: i32,
21155    pub right_euler: i32,
21156    pub left_entropy_nats_bits: u64,
21157    pub right_entropy_nats_bits: u64,
21158    pub combined_site_budget: u16,
21159    pub combined_site_count: u16,
21160    pub combined_euler: i32,
21161    pub combined_entropy_nats_bits: u64,
21162    pub combined_fingerprint: ContentFingerprint,
21163}
21164
21165/// Inputs to `PartitionCoproductWitness::mint_verified`. Adds three
21166/// structural fields beyond the other two MintInputs: the combined
21167/// constraint array, the boundary index between L and R regions, and the
21168/// tag site layout index. These feed `validate_coproduct_structure` at
21169/// mint time so ST_6 / ST_7 / ST_8 are verified numerically rather than
21170/// trusted from the caller.
21171/// Derives `Debug`, `Clone`, `Copy` only — no `PartialEq`. `ConstraintRef`
21172/// does not implement `PartialEq`, so deriving equality on a struct with a
21173/// `&[ConstraintRef]` field would not compile. MintInputs is not used as
21174/// an equality target in practice; downstream consumers compare the minted
21175/// witness (which derives `Eq` + `Hash`) instead.
21176#[derive(Debug, Clone, Copy)]
21177pub struct PartitionCoproductMintInputs {
21178    pub witt_bits: u16,
21179    pub left_fingerprint: ContentFingerprint,
21180    pub right_fingerprint: ContentFingerprint,
21181    pub left_site_budget: u16,
21182    pub right_site_budget: u16,
21183    pub left_total_site_count: u16,
21184    pub right_total_site_count: u16,
21185    pub left_euler: i32,
21186    pub right_euler: i32,
21187    pub left_entropy_nats_bits: u64,
21188    pub right_entropy_nats_bits: u64,
21189    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21190    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21191    pub combined_site_budget: u16,
21192    pub combined_site_count: u16,
21193    pub combined_euler: i32,
21194    pub combined_entropy_nats_bits: u64,
21195    pub combined_betti: [u32; MAX_BETTI_DIMENSION],
21196    pub combined_fingerprint: ContentFingerprint,
21197    pub combined_constraints: &'static [crate::pipeline::ConstraintRef],
21198    pub left_constraint_count: usize,
21199    pub tag_site: u16,
21200}
21201
21202/// Inputs to `CartesianProductWitness::mint_verified`. Matches the
21203/// CartesianProduct mint primitive's parameter list.
21204#[derive(Debug, Clone, Copy, PartialEq)]
21205pub struct CartesianProductMintInputs {
21206    pub witt_bits: u16,
21207    pub left_fingerprint: ContentFingerprint,
21208    pub right_fingerprint: ContentFingerprint,
21209    pub left_site_budget: u16,
21210    pub right_site_budget: u16,
21211    pub left_total_site_count: u16,
21212    pub right_total_site_count: u16,
21213    pub left_euler: i32,
21214    pub right_euler: i32,
21215    pub left_betti: [u32; MAX_BETTI_DIMENSION],
21216    pub right_betti: [u32; MAX_BETTI_DIMENSION],
21217    pub left_entropy_nats_bits: u64,
21218    pub right_entropy_nats_bits: u64,
21219    pub combined_site_budget: u16,
21220    pub combined_site_count: u16,
21221    pub combined_euler: i32,
21222    pub combined_betti: [u32; MAX_BETTI_DIMENSION],
21223    pub combined_entropy_nats_bits: u64,
21224    pub combined_fingerprint: ContentFingerprint,
21225}
21226
21227/// Sealed PartitionProduct witness — content-addressed assertion that a
21228/// partition decomposes as `PartitionProduct(left, right)` per PT_2a.
21229/// Minting is gated on PT_1, PT_3, PT_4, and the foundation
21230/// `ProductLayoutWidth` invariant being verified against component
21231/// shapes. Existence of an instance is the attestation — there is no
21232/// partial or unverified form.
21233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21234pub struct PartitionProductWitness {
21235    witt_bits: u16,
21236    content_fingerprint: ContentFingerprint,
21237    left_fingerprint: ContentFingerprint,
21238    right_fingerprint: ContentFingerprint,
21239    combined_site_budget: u16,
21240    combined_site_count: u16,
21241}
21242
21243impl PartitionProductWitness {
21244    /// Witt level at which the witness was minted.
21245    #[inline]
21246    #[must_use]
21247    pub const fn witt_bits(&self) -> u16 {
21248        self.witt_bits
21249    }
21250    /// Content fingerprint of the combined (A × B) shape.
21251    #[inline]
21252    #[must_use]
21253    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21254        self.content_fingerprint
21255    }
21256    /// Content fingerprint of the left factor A.
21257    #[inline]
21258    #[must_use]
21259    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21260        self.left_fingerprint
21261    }
21262    /// Content fingerprint of the right factor B.
21263    #[inline]
21264    #[must_use]
21265    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21266        self.right_fingerprint
21267    }
21268    /// `siteBudget(A × B)` per PT_1.
21269    #[inline]
21270    #[must_use]
21271    pub const fn combined_site_budget(&self) -> u16 {
21272        self.combined_site_budget
21273    }
21274    /// `SITE_COUNT(A × B)` — the foundation layout width.
21275    #[inline]
21276    #[must_use]
21277    pub const fn combined_site_count(&self) -> u16 {
21278        self.combined_site_count
21279    }
21280    /// Crate-internal mint entry. Only the verified mint primitive may call this.
21281    #[inline]
21282    #[must_use]
21283    #[allow(clippy::too_many_arguments)]
21284    pub(crate) const fn with_level_fingerprints_and_sites(
21285        witt_bits: u16,
21286        content_fingerprint: ContentFingerprint,
21287        left_fingerprint: ContentFingerprint,
21288        right_fingerprint: ContentFingerprint,
21289        combined_site_budget: u16,
21290        combined_site_count: u16,
21291    ) -> Self {
21292        Self {
21293            witt_bits,
21294            content_fingerprint,
21295            left_fingerprint,
21296            right_fingerprint,
21297            combined_site_budget,
21298            combined_site_count,
21299        }
21300    }
21301}
21302
21303/// Sealed PartitionCoproduct witness — content-addressed assertion that a
21304/// partition decomposes as `PartitionCoproduct(left, right)` per PT_2b.
21305/// Minting verifies ST_1, ST_2, ST_6, ST_7, ST_8, ST_9, ST_10, the
21306/// foundation `CoproductLayoutWidth` invariant, and — for ST_6/ST_7/ST_8 —
21307/// walks the supplied constraint array through `validate_coproduct_structure`.
21308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21309pub struct PartitionCoproductWitness {
21310    witt_bits: u16,
21311    content_fingerprint: ContentFingerprint,
21312    left_fingerprint: ContentFingerprint,
21313    right_fingerprint: ContentFingerprint,
21314    combined_site_budget: u16,
21315    combined_site_count: u16,
21316    tag_site_index: u16,
21317}
21318
21319impl PartitionCoproductWitness {
21320    #[inline]
21321    #[must_use]
21322    pub const fn witt_bits(&self) -> u16 {
21323        self.witt_bits
21324    }
21325    #[inline]
21326    #[must_use]
21327    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21328        self.content_fingerprint
21329    }
21330    #[inline]
21331    #[must_use]
21332    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21333        self.left_fingerprint
21334    }
21335    #[inline]
21336    #[must_use]
21337    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21338        self.right_fingerprint
21339    }
21340    /// `siteBudget(A + B)` per ST_1 = max(siteBudget(A), siteBudget(B)).
21341    #[inline]
21342    #[must_use]
21343    pub const fn combined_site_budget(&self) -> u16 {
21344        self.combined_site_budget
21345    }
21346    /// `SITE_COUNT(A + B)` — the foundation layout width including the new tag site.
21347    #[inline]
21348    #[must_use]
21349    pub const fn combined_site_count(&self) -> u16 {
21350        self.combined_site_count
21351    }
21352    /// Index of the tag site in the layout convention of §4b'.
21353    /// Equals `max(SITE_COUNT(A), SITE_COUNT(B))`.
21354    #[inline]
21355    #[must_use]
21356    pub const fn tag_site_index(&self) -> u16 {
21357        self.tag_site_index
21358    }
21359    #[inline]
21360    #[must_use]
21361    #[allow(clippy::too_many_arguments)]
21362    pub(crate) const fn with_level_fingerprints_sites_and_tag(
21363        witt_bits: u16,
21364        content_fingerprint: ContentFingerprint,
21365        left_fingerprint: ContentFingerprint,
21366        right_fingerprint: ContentFingerprint,
21367        combined_site_budget: u16,
21368        combined_site_count: u16,
21369        tag_site_index: u16,
21370    ) -> Self {
21371        Self {
21372            witt_bits,
21373            content_fingerprint,
21374            left_fingerprint,
21375            right_fingerprint,
21376            combined_site_budget,
21377            combined_site_count,
21378            tag_site_index,
21379        }
21380    }
21381}
21382
21383/// Sealed CartesianPartitionProduct witness — content-addressed
21384/// assertion that a shape is `CartesianPartitionProduct(left, right)`
21385/// per CPT_2a. Minting verifies CPT_1, CPT_3, CPT_4, CPT_5, and the
21386/// foundation `CartesianLayoutWidth` invariant. The witness stores
21387/// a snapshot of the combined topological invariants (χ, Betti profile)
21388/// because the construction is axiomatic at the invariant level per §3c.
21389/// Entropy is not stored here (f64 has no Eq/Hash); use the paired
21390/// `CartesianProductEvidence` for entropy re-audit.
21391#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21392pub struct CartesianProductWitness {
21393    witt_bits: u16,
21394    content_fingerprint: ContentFingerprint,
21395    left_fingerprint: ContentFingerprint,
21396    right_fingerprint: ContentFingerprint,
21397    combined_site_budget: u16,
21398    combined_site_count: u16,
21399    combined_euler: i32,
21400    combined_betti: [u32; MAX_BETTI_DIMENSION],
21401}
21402
21403impl CartesianProductWitness {
21404    #[inline]
21405    #[must_use]
21406    pub const fn witt_bits(&self) -> u16 {
21407        self.witt_bits
21408    }
21409    #[inline]
21410    #[must_use]
21411    pub const fn content_fingerprint(&self) -> ContentFingerprint {
21412        self.content_fingerprint
21413    }
21414    #[inline]
21415    #[must_use]
21416    pub const fn left_fingerprint(&self) -> ContentFingerprint {
21417        self.left_fingerprint
21418    }
21419    #[inline]
21420    #[must_use]
21421    pub const fn right_fingerprint(&self) -> ContentFingerprint {
21422        self.right_fingerprint
21423    }
21424    #[inline]
21425    #[must_use]
21426    pub const fn combined_site_budget(&self) -> u16 {
21427        self.combined_site_budget
21428    }
21429    #[inline]
21430    #[must_use]
21431    pub const fn combined_site_count(&self) -> u16 {
21432        self.combined_site_count
21433    }
21434    #[inline]
21435    #[must_use]
21436    pub const fn combined_euler(&self) -> i32 {
21437        self.combined_euler
21438    }
21439    #[inline]
21440    #[must_use]
21441    pub const fn combined_betti(&self) -> [u32; MAX_BETTI_DIMENSION] {
21442        self.combined_betti
21443    }
21444    #[inline]
21445    #[must_use]
21446    #[allow(clippy::too_many_arguments)]
21447    pub(crate) const fn with_level_fingerprints_and_invariants(
21448        witt_bits: u16,
21449        content_fingerprint: ContentFingerprint,
21450        left_fingerprint: ContentFingerprint,
21451        right_fingerprint: ContentFingerprint,
21452        combined_site_budget: u16,
21453        combined_site_count: u16,
21454        combined_euler: i32,
21455        combined_betti: [u32; MAX_BETTI_DIMENSION],
21456    ) -> Self {
21457        Self {
21458            witt_bits,
21459            content_fingerprint,
21460            left_fingerprint,
21461            right_fingerprint,
21462            combined_site_budget,
21463            combined_site_count,
21464            combined_euler,
21465            combined_betti,
21466        }
21467    }
21468}
21469
21470impl Certificate for PartitionProductWitness {
21471    const IRI: &'static str = "https://uor.foundation/partition/PartitionProduct";
21472    type Evidence = PartitionProductEvidence;
21473}
21474
21475impl Certificate for PartitionCoproductWitness {
21476    const IRI: &'static str = "https://uor.foundation/partition/PartitionCoproduct";
21477    type Evidence = PartitionCoproductEvidence;
21478}
21479
21480impl Certificate for CartesianProductWitness {
21481    const IRI: &'static str = "https://uor.foundation/partition/CartesianPartitionProduct";
21482    type Evidence = CartesianProductEvidence;
21483}
21484
21485impl core::fmt::Display for PartitionProductWitness {
21486    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21487        f.write_str("PartitionProductWitness")
21488    }
21489}
21490impl core::error::Error for PartitionProductWitness {}
21491
21492impl core::fmt::Display for PartitionCoproductWitness {
21493    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21494        f.write_str("PartitionCoproductWitness")
21495    }
21496}
21497impl core::error::Error for PartitionCoproductWitness {}
21498
21499impl core::fmt::Display for CartesianProductWitness {
21500    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21501        f.write_str("CartesianProductWitness")
21502    }
21503}
21504impl core::error::Error for CartesianProductWitness {}
21505
21506/// Sealed mint path for certificates that require multi-theorem verification
21507/// before minting. Introduced by the Product/Coproduct Completion Amendment
21508/// §1c; distinct from `MintWithLevelFingerprint` (which is the generic
21509/// partial-mint path for sealed shims). `VerifiedMint` implementors are
21510/// the three partition-algebra witnesses, each routing through a
21511/// foundation-internal mint primitive that verifies the relevant theorems.
21512/// The trait is public so external callers can invoke `mint_verified`
21513/// directly, but the `Certificate` supertrait's `certificate_sealed::Sealed`
21514/// bound keeps the implementor set closed to this crate.
21515pub trait VerifiedMint: Certificate {
21516    /// Caller-supplied input bundle — one `*MintInputs` struct per witness.
21517    type Inputs;
21518    /// Failure kind — always `GenericImpossibilityWitness` citing the
21519    /// specific op-namespace theorem or foundation-namespace layout
21520    /// invariant that was violated.
21521    type Error;
21522    /// Verify the theorems and invariants against `inputs`, then mint a
21523    /// witness or return a typed impossibility witness.
21524    /// # Errors
21525    /// Returns a `GenericImpossibilityWitness::for_identity(iri)` when any
21526    /// of the gated theorems or foundation invariants fails. The IRI
21527    /// identifies exactly which identity failed — `op/PT_*`, `op/ST_*`,
21528    /// `op/CPT_*`, or `foundation/*LayoutWidth` / `foundation/CoproductTagEncoding`.
21529    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error>
21530    where
21531        Self: Sized;
21532}
21533
21534/// Recursive classifier used by `validate_coproduct_structure`. Inspects
21535/// one `ConstraintRef`, tallies tag-pinner sightings via mutable references,
21536/// and recurses into `Conjunction` conjuncts up to `max_depth` levels. See
21537/// plan §A4 for the depth bound rationale.
21538#[allow(clippy::too_many_arguments)]
21539fn pc_classify_constraint(
21540    c: &crate::pipeline::ConstraintRef,
21541    in_left_region: bool,
21542    tag_site: u16,
21543    max_depth: u32,
21544    left_pins: &mut u32,
21545    right_pins: &mut u32,
21546    left_bias_ok: &mut bool,
21547    right_bias_ok: &mut bool,
21548) -> Result<(), GenericImpossibilityWitness> {
21549    match c {
21550        crate::pipeline::ConstraintRef::Site { position } => {
21551            if (*position as u16) >= tag_site {
21552                return Err(GenericImpossibilityWitness::for_identity(
21553                    "https://uor.foundation/op/ST_6",
21554                ));
21555            }
21556        }
21557        crate::pipeline::ConstraintRef::Carry { site } => {
21558            if (*site as u16) >= tag_site {
21559                return Err(GenericImpossibilityWitness::for_identity(
21560                    "https://uor.foundation/op/ST_6",
21561                ));
21562            }
21563        }
21564        crate::pipeline::ConstraintRef::Affine { coefficients, coefficient_count, bias } => {
21565            let count = *coefficient_count as usize;
21566            let mut nonzero_count: u32 = 0;
21567            let mut nonzero_index: usize = 0;
21568            let mut max_nonzero_index: usize = 0;
21569            let mut i: usize = 0;
21570            while i < count && i < crate::pipeline::AFFINE_MAX_COEFFS {
21571                if coefficients[i] != 0 {
21572                    nonzero_count = nonzero_count.saturating_add(1);
21573                    nonzero_index = i;
21574                    if i > max_nonzero_index { max_nonzero_index = i; }
21575                }
21576                i += 1;
21577            }
21578            let touches_tag_site = nonzero_count > 0
21579                && (max_nonzero_index as u16) >= tag_site;
21580            let is_canonical_tag_pinner = nonzero_count == 1
21581                && (nonzero_index as u16) == tag_site
21582                && coefficients[nonzero_index] == 1;
21583            if is_canonical_tag_pinner {
21584                if *bias != 0 && *bias != -1 {
21585                    return Err(GenericImpossibilityWitness::for_identity(
21586                        "https://uor.foundation/foundation/CoproductTagEncoding",
21587                    ));
21588                }
21589                if in_left_region {
21590                    *left_pins = left_pins.saturating_add(1);
21591                    if *bias != 0 { *left_bias_ok = false; }
21592                } else {
21593                    *right_pins = right_pins.saturating_add(1);
21594                    if *bias != -1 { *right_bias_ok = false; }
21595                }
21596            } else if touches_tag_site {
21597                let nonzero_only_at_tag_site = nonzero_count == 1
21598                    && (nonzero_index as u16) == tag_site;
21599                if nonzero_only_at_tag_site {
21600                    return Err(GenericImpossibilityWitness::for_identity(
21601                        "https://uor.foundation/foundation/CoproductTagEncoding",
21602                    ));
21603                } else {
21604                    return Err(GenericImpossibilityWitness::for_identity(
21605                        "https://uor.foundation/op/ST_6",
21606                    ));
21607                }
21608            }
21609        }
21610        crate::pipeline::ConstraintRef::Conjunction { conjuncts, conjunct_count } => {
21611            if max_depth == 0 {
21612                return Err(GenericImpossibilityWitness::for_identity(
21613                    "https://uor.foundation/op/ST_6",
21614                ));
21615            }
21616            let count = *conjunct_count as usize;
21617            let mut idx: usize = 0;
21618            while idx < count && idx < crate::pipeline::CONJUNCTION_MAX_TERMS {
21619                let lifted = conjuncts[idx].into_constraint();
21620                pc_classify_constraint(
21621                    &lifted,
21622                    in_left_region,
21623                    tag_site,
21624                    max_depth - 1,
21625                    left_pins,
21626                    right_pins,
21627                    left_bias_ok,
21628                    right_bias_ok,
21629                )?;
21630                idx += 1;
21631            }
21632        }
21633        crate::pipeline::ConstraintRef::Residue { .. }
21634        | crate::pipeline::ConstraintRef::Hamming { .. }
21635        | crate::pipeline::ConstraintRef::Depth { .. }
21636        | crate::pipeline::ConstraintRef::SatClauses { .. }
21637        | crate::pipeline::ConstraintRef::Bound { .. }
21638        // ADR-057: Recurse references a shape by content-addressed IRI;
21639        // no site references at this level to check.
21640        | crate::pipeline::ConstraintRef::Recurse { .. } => {
21641            // No site references at this level; nothing to check.
21642        }
21643    }
21644    Ok(())
21645}
21646
21647/// Validates ST_6 / ST_7 / ST_8 for a PartitionCoproduct construction by
21648/// walking the emitted constraint array. Recurses into
21649/// `ConstraintRef::Conjunction` conjuncts up to depth 8 (bounded by
21650/// `NERVE_CONSTRAINTS_CAP`) so nested constructions are audited without
21651/// unbounded recursion.
21652/// # Errors
21653/// Returns `GenericImpossibilityWitness::for_identity(...)` citing the
21654/// specific failed identity: `op/ST_6`, `op/ST_7`, or
21655/// `foundation/CoproductTagEncoding`. ST_8 is implied by ST_6 ∧ ST_7 and
21656/// is not cited separately on failure.
21657pub(crate) fn validate_coproduct_structure(
21658    combined_constraints: &[crate::pipeline::ConstraintRef],
21659    left_constraint_count: usize,
21660    tag_site: u16,
21661) -> Result<(), GenericImpossibilityWitness> {
21662    let mut left_pins: u32 = 0;
21663    let mut right_pins: u32 = 0;
21664    let mut left_bias_ok: bool = true;
21665    let mut right_bias_ok: bool = true;
21666    let mut idx: usize = 0;
21667    while idx < combined_constraints.len() {
21668        let in_left_region = idx < left_constraint_count;
21669        pc_classify_constraint(
21670            &combined_constraints[idx],
21671            in_left_region,
21672            tag_site,
21673            NERVE_CONSTRAINTS_CAP as u32,
21674            &mut left_pins,
21675            &mut right_pins,
21676            &mut left_bias_ok,
21677            &mut right_bias_ok,
21678        )?;
21679        idx += 1;
21680    }
21681    if left_pins != 1 || right_pins != 1 {
21682        return Err(GenericImpossibilityWitness::for_identity(
21683            "https://uor.foundation/op/ST_6",
21684        ));
21685    }
21686    if !left_bias_ok || !right_bias_ok {
21687        return Err(GenericImpossibilityWitness::for_identity(
21688            "https://uor.foundation/op/ST_7",
21689        ));
21690    }
21691    Ok(())
21692}
21693
21694/// Mint a `PartitionProductWitness` after verifying PT_1, PT_3, PT_4, and
21695/// the `ProductLayoutWidth` layout invariant. PT_2a is structural (the
21696/// witness existing is the claim); no separate check is needed once the
21697/// invariants match.
21698#[allow(clippy::too_many_arguments)]
21699pub(crate) fn pc_primitive_partition_product(
21700    witt_bits: u16,
21701    left_fingerprint: ContentFingerprint,
21702    right_fingerprint: ContentFingerprint,
21703    left_site_budget: u16,
21704    right_site_budget: u16,
21705    left_total_site_count: u16,
21706    right_total_site_count: u16,
21707    left_euler: i32,
21708    right_euler: i32,
21709    left_entropy_nats_bits: u64,
21710    right_entropy_nats_bits: u64,
21711    combined_site_budget: u16,
21712    combined_site_count: u16,
21713    combined_euler: i32,
21714    combined_entropy_nats_bits: u64,
21715    combined_fingerprint: ContentFingerprint,
21716) -> Result<PartitionProductWitness, GenericImpossibilityWitness> {
21717    let left_entropy_nats =
21718        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21719    let right_entropy_nats =
21720        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21721    let combined_entropy_nats =
21722        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21723    if combined_site_budget != left_site_budget.saturating_add(right_site_budget) {
21724        return Err(GenericImpossibilityWitness::for_identity(
21725            "https://uor.foundation/op/PT_1",
21726        ));
21727    }
21728    if combined_site_count != left_total_site_count.saturating_add(right_total_site_count) {
21729        return Err(GenericImpossibilityWitness::for_identity(
21730            "https://uor.foundation/foundation/ProductLayoutWidth",
21731        ));
21732    }
21733    if combined_euler != left_euler.saturating_add(right_euler) {
21734        return Err(GenericImpossibilityWitness::for_identity(
21735            "https://uor.foundation/op/PT_3",
21736        ));
21737    }
21738    if !pc_entropy_input_is_valid(left_entropy_nats)
21739        || !pc_entropy_input_is_valid(right_entropy_nats)
21740        || !pc_entropy_input_is_valid(combined_entropy_nats)
21741    {
21742        return Err(GenericImpossibilityWitness::for_identity(
21743            "https://uor.foundation/op/PT_4",
21744        ));
21745    }
21746    let expected_entropy = left_entropy_nats + right_entropy_nats;
21747    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21748        return Err(GenericImpossibilityWitness::for_identity(
21749            "https://uor.foundation/op/PT_4",
21750        ));
21751    }
21752    Ok(PartitionProductWitness::with_level_fingerprints_and_sites(
21753        witt_bits,
21754        combined_fingerprint,
21755        left_fingerprint,
21756        right_fingerprint,
21757        combined_site_budget,
21758        combined_site_count,
21759    ))
21760}
21761
21762/// Mint a `PartitionCoproductWitness` after verifying ST_1, ST_2, ST_6,
21763/// ST_7, ST_8, ST_9, ST_10, the `CoproductLayoutWidth` layout invariant,
21764/// the tag-site alignment against §4b', and running
21765/// `validate_coproduct_structure` over the supplied constraint array.
21766#[allow(clippy::too_many_arguments)]
21767pub(crate) fn pc_primitive_partition_coproduct(
21768    witt_bits: u16,
21769    left_fingerprint: ContentFingerprint,
21770    right_fingerprint: ContentFingerprint,
21771    left_site_budget: u16,
21772    right_site_budget: u16,
21773    left_total_site_count: u16,
21774    right_total_site_count: u16,
21775    left_euler: i32,
21776    right_euler: i32,
21777    left_entropy_nats_bits: u64,
21778    right_entropy_nats_bits: u64,
21779    left_betti: [u32; MAX_BETTI_DIMENSION],
21780    right_betti: [u32; MAX_BETTI_DIMENSION],
21781    combined_site_budget: u16,
21782    combined_site_count: u16,
21783    combined_euler: i32,
21784    combined_entropy_nats_bits: u64,
21785    combined_betti: [u32; MAX_BETTI_DIMENSION],
21786    combined_fingerprint: ContentFingerprint,
21787    combined_constraints: &[crate::pipeline::ConstraintRef],
21788    left_constraint_count: usize,
21789    tag_site: u16,
21790) -> Result<PartitionCoproductWitness, GenericImpossibilityWitness> {
21791    let left_entropy_nats =
21792        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21793    let right_entropy_nats =
21794        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21795    let combined_entropy_nats =
21796        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21797    let expected_budget = if left_site_budget > right_site_budget {
21798        left_site_budget
21799    } else {
21800        right_site_budget
21801    };
21802    if combined_site_budget != expected_budget {
21803        return Err(GenericImpossibilityWitness::for_identity(
21804            "https://uor.foundation/op/ST_1",
21805        ));
21806    }
21807    let max_total = if left_total_site_count > right_total_site_count {
21808        left_total_site_count
21809    } else {
21810        right_total_site_count
21811    };
21812    let expected_total = max_total.saturating_add(1);
21813    if combined_site_count != expected_total {
21814        return Err(GenericImpossibilityWitness::for_identity(
21815            "https://uor.foundation/foundation/CoproductLayoutWidth",
21816        ));
21817    }
21818    if !pc_entropy_input_is_valid(left_entropy_nats)
21819        || !pc_entropy_input_is_valid(right_entropy_nats)
21820        || !pc_entropy_input_is_valid(combined_entropy_nats)
21821    {
21822        return Err(GenericImpossibilityWitness::for_identity(
21823            "https://uor.foundation/op/ST_2",
21824        ));
21825    }
21826    let max_operand_entropy = if left_entropy_nats > right_entropy_nats {
21827        left_entropy_nats
21828    } else {
21829        right_entropy_nats
21830    };
21831    let expected_entropy = core::f64::consts::LN_2 + max_operand_entropy;
21832    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21833        return Err(GenericImpossibilityWitness::for_identity(
21834            "https://uor.foundation/op/ST_2",
21835        ));
21836    }
21837    if tag_site != max_total {
21838        return Err(GenericImpossibilityWitness::for_identity(
21839            "https://uor.foundation/foundation/CoproductLayoutWidth",
21840        ));
21841    }
21842    validate_coproduct_structure(combined_constraints, left_constraint_count, tag_site)?;
21843    if combined_euler != left_euler.saturating_add(right_euler) {
21844        return Err(GenericImpossibilityWitness::for_identity(
21845            "https://uor.foundation/op/ST_9",
21846        ));
21847    }
21848    let mut k: usize = 0;
21849    while k < MAX_BETTI_DIMENSION {
21850        if combined_betti[k] != left_betti[k].saturating_add(right_betti[k]) {
21851            return Err(GenericImpossibilityWitness::for_identity(
21852                "https://uor.foundation/op/ST_10",
21853            ));
21854        }
21855        k += 1;
21856    }
21857    Ok(
21858        PartitionCoproductWitness::with_level_fingerprints_sites_and_tag(
21859            witt_bits,
21860            combined_fingerprint,
21861            left_fingerprint,
21862            right_fingerprint,
21863            combined_site_budget,
21864            combined_site_count,
21865            max_total,
21866        ),
21867    )
21868}
21869
21870/// Mint a `CartesianProductWitness` after verifying CPT_1, CPT_3, CPT_4,
21871/// CPT_5, and the `CartesianLayoutWidth` layout invariant. Checks
21872/// caller-supplied Künneth-composed invariants against the component
21873/// values (the witness defines these axiomatically per §3c).
21874#[allow(clippy::too_many_arguments)]
21875pub(crate) fn pc_primitive_cartesian_product(
21876    witt_bits: u16,
21877    left_fingerprint: ContentFingerprint,
21878    right_fingerprint: ContentFingerprint,
21879    left_site_budget: u16,
21880    right_site_budget: u16,
21881    left_total_site_count: u16,
21882    right_total_site_count: u16,
21883    left_euler: i32,
21884    right_euler: i32,
21885    left_betti: [u32; MAX_BETTI_DIMENSION],
21886    right_betti: [u32; MAX_BETTI_DIMENSION],
21887    left_entropy_nats_bits: u64,
21888    right_entropy_nats_bits: u64,
21889    combined_site_budget: u16,
21890    combined_site_count: u16,
21891    combined_euler: i32,
21892    combined_betti: [u32; MAX_BETTI_DIMENSION],
21893    combined_entropy_nats_bits: u64,
21894    combined_fingerprint: ContentFingerprint,
21895) -> Result<CartesianProductWitness, GenericImpossibilityWitness> {
21896    let left_entropy_nats =
21897        <f64 as crate::DecimalTranscendental>::from_bits(left_entropy_nats_bits);
21898    let right_entropy_nats =
21899        <f64 as crate::DecimalTranscendental>::from_bits(right_entropy_nats_bits);
21900    let combined_entropy_nats =
21901        <f64 as crate::DecimalTranscendental>::from_bits(combined_entropy_nats_bits);
21902    if combined_site_budget != left_site_budget.saturating_add(right_site_budget) {
21903        return Err(GenericImpossibilityWitness::for_identity(
21904            "https://uor.foundation/op/CPT_1",
21905        ));
21906    }
21907    if combined_site_count != left_total_site_count.saturating_add(right_total_site_count) {
21908        return Err(GenericImpossibilityWitness::for_identity(
21909            "https://uor.foundation/foundation/CartesianLayoutWidth",
21910        ));
21911    }
21912    if combined_euler != left_euler.saturating_mul(right_euler) {
21913        return Err(GenericImpossibilityWitness::for_identity(
21914            "https://uor.foundation/op/CPT_3",
21915        ));
21916    }
21917    let kunneth = crate::pipeline::kunneth_compose(&left_betti, &right_betti);
21918    let mut k: usize = 0;
21919    while k < MAX_BETTI_DIMENSION {
21920        if combined_betti[k] != kunneth[k] {
21921            return Err(GenericImpossibilityWitness::for_identity(
21922                "https://uor.foundation/op/CPT_4",
21923            ));
21924        }
21925        k += 1;
21926    }
21927    if !pc_entropy_input_is_valid(left_entropy_nats)
21928        || !pc_entropy_input_is_valid(right_entropy_nats)
21929        || !pc_entropy_input_is_valid(combined_entropy_nats)
21930    {
21931        return Err(GenericImpossibilityWitness::for_identity(
21932            "https://uor.foundation/op/CPT_5",
21933        ));
21934    }
21935    let expected_entropy = left_entropy_nats + right_entropy_nats;
21936    if !pc_entropy_additivity_holds(combined_entropy_nats, expected_entropy) {
21937        return Err(GenericImpossibilityWitness::for_identity(
21938            "https://uor.foundation/op/CPT_5",
21939        ));
21940    }
21941    Ok(
21942        CartesianProductWitness::with_level_fingerprints_and_invariants(
21943            witt_bits,
21944            combined_fingerprint,
21945            left_fingerprint,
21946            right_fingerprint,
21947            combined_site_budget,
21948            combined_site_count,
21949            combined_euler,
21950            combined_betti,
21951        ),
21952    )
21953}
21954
21955impl VerifiedMint for PartitionProductWitness {
21956    type Inputs = PartitionProductMintInputs;
21957    type Error = GenericImpossibilityWitness;
21958    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
21959        pc_primitive_partition_product(
21960            inputs.witt_bits,
21961            inputs.left_fingerprint,
21962            inputs.right_fingerprint,
21963            inputs.left_site_budget,
21964            inputs.right_site_budget,
21965            inputs.left_total_site_count,
21966            inputs.right_total_site_count,
21967            inputs.left_euler,
21968            inputs.right_euler,
21969            inputs.left_entropy_nats_bits,
21970            inputs.right_entropy_nats_bits,
21971            inputs.combined_site_budget,
21972            inputs.combined_site_count,
21973            inputs.combined_euler,
21974            inputs.combined_entropy_nats_bits,
21975            inputs.combined_fingerprint,
21976        )
21977    }
21978}
21979
21980impl VerifiedMint for PartitionCoproductWitness {
21981    type Inputs = PartitionCoproductMintInputs;
21982    type Error = GenericImpossibilityWitness;
21983    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
21984        pc_primitive_partition_coproduct(
21985            inputs.witt_bits,
21986            inputs.left_fingerprint,
21987            inputs.right_fingerprint,
21988            inputs.left_site_budget,
21989            inputs.right_site_budget,
21990            inputs.left_total_site_count,
21991            inputs.right_total_site_count,
21992            inputs.left_euler,
21993            inputs.right_euler,
21994            inputs.left_entropy_nats_bits,
21995            inputs.right_entropy_nats_bits,
21996            inputs.left_betti,
21997            inputs.right_betti,
21998            inputs.combined_site_budget,
21999            inputs.combined_site_count,
22000            inputs.combined_euler,
22001            inputs.combined_entropy_nats_bits,
22002            inputs.combined_betti,
22003            inputs.combined_fingerprint,
22004            inputs.combined_constraints,
22005            inputs.left_constraint_count,
22006            inputs.tag_site,
22007        )
22008    }
22009}
22010
22011impl VerifiedMint for CartesianProductWitness {
22012    type Inputs = CartesianProductMintInputs;
22013    type Error = GenericImpossibilityWitness;
22014    fn mint_verified(inputs: Self::Inputs) -> Result<Self, Self::Error> {
22015        pc_primitive_cartesian_product(
22016            inputs.witt_bits,
22017            inputs.left_fingerprint,
22018            inputs.right_fingerprint,
22019            inputs.left_site_budget,
22020            inputs.right_site_budget,
22021            inputs.left_total_site_count,
22022            inputs.right_total_site_count,
22023            inputs.left_euler,
22024            inputs.right_euler,
22025            inputs.left_betti,
22026            inputs.right_betti,
22027            inputs.left_entropy_nats_bits,
22028            inputs.right_entropy_nats_bits,
22029            inputs.combined_site_budget,
22030            inputs.combined_site_count,
22031            inputs.combined_euler,
22032            inputs.combined_betti,
22033            inputs.combined_entropy_nats_bits,
22034            inputs.combined_fingerprint,
22035        )
22036    }
22037}
22038
22039/// Data record of a partition's runtime-queried properties. Produced at
22040/// witness-mint time and consulted by consumer code that holds a
22041/// `PartitionHandle` and a `PartitionResolver`. Phase 9 stores entropy
22042/// as the IEEE-754 `u64` bit-pattern (`entropy_nats_bits`) so the record
22043/// derives `Eq + Hash` cleanly; consumers project to `H::Decimal` via
22044/// `<H::Decimal as DecimalTranscendental>::from_bits`.
22045#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22046pub struct PartitionRecord<H: crate::HostTypes> {
22047    /// Data sites only — the partition's `siteBudget`, not its layout width.
22048    pub site_budget: u16,
22049    /// Euler characteristic of the partition's nerve.
22050    pub euler: i32,
22051    /// Betti profile of the partition's nerve, padded to `MAX_BETTI_DIMENSION`.
22052    pub betti: [u32; MAX_BETTI_DIMENSION],
22053    /// Shannon entropy in nats (matches `LandauerBudget::nats()` convention).
22054    pub entropy_nats_bits: u64,
22055    _phantom: core::marker::PhantomData<H>,
22056}
22057
22058impl<H: crate::HostTypes> PartitionRecord<H> {
22059    /// Construct a new record. The phantom marker ensures records are
22060    /// parameterized by the host types they originate from.
22061    #[inline]
22062    #[must_use]
22063    pub const fn new(
22064        site_budget: u16,
22065        euler: i32,
22066        betti: [u32; MAX_BETTI_DIMENSION],
22067        entropy_nats_bits: u64,
22068    ) -> Self {
22069        Self {
22070            site_budget,
22071            euler,
22072            betti,
22073            entropy_nats_bits,
22074            _phantom: core::marker::PhantomData,
22075        }
22076    }
22077}
22078
22079/// Resolver mapping content fingerprints to `PartitionRecord`s. Provided
22080/// by the host application — typically a persistent store, an in-memory
22081/// registry populated from witness mint-time data, or a chain-of-witnesses
22082/// trail that can reconstruct properties.
22083pub trait PartitionResolver<H: crate::HostTypes> {
22084    /// Look up partition data by fingerprint. Returns `None` if the
22085    /// resolver has no record for the handle. Handles remain valid as
22086    /// identity tokens regardless of resolver presence.
22087    fn resolve(&self, fp: ContentFingerprint) -> Option<PartitionRecord<H>>;
22088}
22089
22090/// Content-addressed identity token for a partition. Carries only a
22091/// fingerprint; partition data is recovered by pairing the handle with a
22092/// `PartitionResolver` via `resolve_with`. Handles compare and hash by
22093/// fingerprint, so they can serve as keys in content-addressed indices
22094/// without resolver access.
22095#[derive(Debug)]
22096pub struct PartitionHandle<H: crate::HostTypes> {
22097    fingerprint: ContentFingerprint,
22098    _phantom: core::marker::PhantomData<H>,
22099}
22100impl<H: crate::HostTypes> Copy for PartitionHandle<H> {}
22101impl<H: crate::HostTypes> Clone for PartitionHandle<H> {
22102    #[inline]
22103    fn clone(&self) -> Self {
22104        *self
22105    }
22106}
22107impl<H: crate::HostTypes> PartialEq for PartitionHandle<H> {
22108    #[inline]
22109    fn eq(&self, other: &Self) -> bool {
22110        self.fingerprint == other.fingerprint
22111    }
22112}
22113impl<H: crate::HostTypes> Eq for PartitionHandle<H> {}
22114impl<H: crate::HostTypes> core::hash::Hash for PartitionHandle<H> {
22115    #[inline]
22116    fn hash<S: core::hash::Hasher>(&self, state: &mut S) {
22117        self.fingerprint.hash(state);
22118    }
22119}
22120
22121impl<H: crate::HostTypes> PartitionHandle<H> {
22122    /// Construct a handle from a content fingerprint.
22123    #[inline]
22124    #[must_use]
22125    pub const fn from_fingerprint(fingerprint: ContentFingerprint) -> Self {
22126        Self {
22127            fingerprint,
22128            _phantom: core::marker::PhantomData,
22129        }
22130    }
22131    /// Return the content fingerprint this handle references.
22132    #[inline]
22133    #[must_use]
22134    pub const fn fingerprint(&self) -> ContentFingerprint {
22135        self.fingerprint
22136    }
22137    /// Resolve this handle against a consumer-supplied resolver.
22138    /// Returns `None` if the resolver has no record for this fingerprint.
22139    #[inline]
22140    pub fn resolve_with<R: PartitionResolver<H>>(
22141        &self,
22142        resolver: &R,
22143    ) -> Option<PartitionRecord<H>> {
22144        resolver.resolve(self.fingerprint)
22145    }
22146}
22147
22148/// Resolver-absent default `Element<H>`. Returns empty defaults via the
22149/// `HostTypes::EMPTY_*` constants — used by `NullDatum<H>` and
22150/// `NullTypeDefinition<H>` to satisfy their `Element` associated types.
22151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22152pub struct NullElement<H: HostTypes> {
22153    _phantom: core::marker::PhantomData<H>,
22154}
22155impl<H: HostTypes> Default for NullElement<H> {
22156    fn default() -> Self {
22157        Self {
22158            _phantom: core::marker::PhantomData,
22159        }
22160    }
22161}
22162impl<H: HostTypes> crate::kernel::address::Element<H> for NullElement<H> {
22163    fn length(&self) -> u64 {
22164        0
22165    }
22166    fn addresses(&self) -> &H::HostString {
22167        H::EMPTY_HOST_STRING
22168    }
22169    fn digest(&self) -> &H::HostString {
22170        H::EMPTY_HOST_STRING
22171    }
22172    fn digest_algorithm(&self) -> &H::HostString {
22173        H::EMPTY_HOST_STRING
22174    }
22175    fn canonical_bytes(&self) -> &H::WitnessBytes {
22176        H::EMPTY_WITNESS_BYTES
22177    }
22178    fn witt_length(&self) -> u64 {
22179        0
22180    }
22181}
22182
22183/// Resolver-absent default `Datum<H>`. All numeric methods return 0.
22184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22185pub struct NullDatum<H: HostTypes> {
22186    element: NullElement<H>,
22187    _phantom: core::marker::PhantomData<H>,
22188}
22189impl<H: HostTypes> Default for NullDatum<H> {
22190    fn default() -> Self {
22191        Self {
22192            element: NullElement::default(),
22193            _phantom: core::marker::PhantomData,
22194        }
22195    }
22196}
22197impl<H: HostTypes> crate::kernel::schema::Datum<H> for NullDatum<H> {
22198    fn value(&self) -> u64 {
22199        0
22200    }
22201    fn witt_length(&self) -> u64 {
22202        0
22203    }
22204    fn stratum(&self) -> u64 {
22205        0
22206    }
22207    fn spectrum(&self) -> u64 {
22208        0
22209    }
22210    type Element = NullElement<H>;
22211    fn element(&self) -> &Self::Element {
22212        &self.element
22213    }
22214}
22215
22216/// Resolver-absent default `TermExpression<H>`. Empty marker trait, no methods.
22217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22218pub struct NullTermExpression<H: HostTypes> {
22219    _phantom: core::marker::PhantomData<H>,
22220}
22221impl<H: HostTypes> Default for NullTermExpression<H> {
22222    fn default() -> Self {
22223        Self {
22224            _phantom: core::marker::PhantomData,
22225        }
22226    }
22227}
22228impl<H: HostTypes> crate::kernel::schema::TermExpression<H> for NullTermExpression<H> {}
22229
22230/// Resolver-absent default `SiteIndex<H>`. Self-recursive: `ancilla_site()`
22231/// returns `&self` (no ancilla pairing in the default).
22232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22233pub struct NullSiteIndex<H: HostTypes> {
22234    _phantom: core::marker::PhantomData<H>,
22235}
22236impl<H: HostTypes> Default for NullSiteIndex<H> {
22237    fn default() -> Self {
22238        Self {
22239            _phantom: core::marker::PhantomData,
22240        }
22241    }
22242}
22243impl<H: HostTypes> crate::bridge::partition::SiteIndex<H> for NullSiteIndex<H> {
22244    fn site_position(&self) -> u64 {
22245        0
22246    }
22247    fn site_state(&self) -> u64 {
22248        0
22249    }
22250    type SiteIndexTarget = NullSiteIndex<H>;
22251    fn ancilla_site(&self) -> &Self::SiteIndexTarget {
22252        self
22253    }
22254}
22255
22256/// Resolver-absent default `TagSite<H>`. Embeds an inline `NullSiteIndex`
22257/// field so the inherited `ancilla_site()` accessor returns a valid
22258/// reference; `tag_value()` returns false.
22259#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22260pub struct NullTagSite<H: HostTypes> {
22261    ancilla: NullSiteIndex<H>,
22262}
22263impl<H: HostTypes> Default for NullTagSite<H> {
22264    fn default() -> Self {
22265        Self {
22266            ancilla: NullSiteIndex::default(),
22267        }
22268    }
22269}
22270impl<H: HostTypes> crate::bridge::partition::SiteIndex<H> for NullTagSite<H> {
22271    fn site_position(&self) -> u64 {
22272        0
22273    }
22274    fn site_state(&self) -> u64 {
22275        0
22276    }
22277    type SiteIndexTarget = NullSiteIndex<H>;
22278    fn ancilla_site(&self) -> &Self::SiteIndexTarget {
22279        &self.ancilla
22280    }
22281}
22282impl<H: HostTypes> crate::bridge::partition::TagSite<H> for NullTagSite<H> {
22283    fn tag_value(&self) -> bool {
22284        false
22285    }
22286}
22287
22288/// Resolver-absent default `SiteBinding<H>`. Embeds inline `NullConstraint`
22289/// and `NullSiteIndex` so the trait's reference accessors work via &self.field.
22290#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22291pub struct NullSiteBinding<H: HostTypes> {
22292    constraint: NullConstraint<H>,
22293    site_index: NullSiteIndex<H>,
22294}
22295impl<H: HostTypes> Default for NullSiteBinding<H> {
22296    fn default() -> Self {
22297        Self {
22298            constraint: NullConstraint::default(),
22299            site_index: NullSiteIndex::default(),
22300        }
22301    }
22302}
22303impl<H: HostTypes> crate::bridge::partition::SiteBinding<H> for NullSiteBinding<H> {
22304    type Constraint = NullConstraint<H>;
22305    fn pinned_by(&self) -> &Self::Constraint {
22306        &self.constraint
22307    }
22308    type SiteIndex = NullSiteIndex<H>;
22309    fn pins_coordinate(&self) -> &Self::SiteIndex {
22310        &self.site_index
22311    }
22312}
22313
22314/// Resolver-absent default `Constraint<H>`. Returns Vertical metric axis,
22315/// empty pinned-sites slice, and zero crossing cost.
22316#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22317pub struct NullConstraint<H: HostTypes> {
22318    _phantom: core::marker::PhantomData<H>,
22319}
22320impl<H: HostTypes> Default for NullConstraint<H> {
22321    fn default() -> Self {
22322        Self {
22323            _phantom: core::marker::PhantomData,
22324        }
22325    }
22326}
22327impl<H: HostTypes> crate::user::type_::Constraint<H> for NullConstraint<H> {
22328    fn metric_axis(&self) -> MetricAxis {
22329        MetricAxis::Vertical
22330    }
22331    type SiteIndex = NullSiteIndex<H>;
22332    fn pins_sites(&self) -> &[Self::SiteIndex] {
22333        &[]
22334    }
22335    fn crossing_cost(&self) -> u64 {
22336        0
22337    }
22338}
22339
22340/// Resolver-absent default `FreeRank<H>`. Empty budget — `is_closed()` true,
22341/// zero counts. Empty `has_site` / `has_binding` slices.
22342#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22343pub struct NullFreeRank<H: HostTypes> {
22344    _phantom: core::marker::PhantomData<H>,
22345}
22346impl<H: HostTypes> Default for NullFreeRank<H> {
22347    fn default() -> Self {
22348        Self {
22349            _phantom: core::marker::PhantomData,
22350        }
22351    }
22352}
22353impl<H: HostTypes> crate::bridge::partition::FreeRank<H> for NullFreeRank<H> {
22354    fn total_sites(&self) -> u64 {
22355        0
22356    }
22357    fn pinned_count(&self) -> u64 {
22358        0
22359    }
22360    fn free_rank(&self) -> u64 {
22361        0
22362    }
22363    fn is_closed(&self) -> bool {
22364        true
22365    }
22366    type SiteIndex = NullSiteIndex<H>;
22367    fn has_site(&self) -> &[Self::SiteIndex] {
22368        &[]
22369    }
22370    type SiteBinding = NullSiteBinding<H>;
22371    fn has_binding(&self) -> &[Self::SiteBinding] {
22372        &[]
22373    }
22374    fn reversible_strategy(&self) -> bool {
22375        false
22376    }
22377}
22378
22379/// Resolver-absent default `IrreducibleSet<H>`. Implements `Component<H>` with empty
22380/// `member` slice and zero `cardinality`.
22381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22382pub struct NullIrreducibleSet<H: HostTypes> {
22383    _phantom: core::marker::PhantomData<H>,
22384}
22385impl<H: HostTypes> Default for NullIrreducibleSet<H> {
22386    fn default() -> Self {
22387        Self {
22388            _phantom: core::marker::PhantomData,
22389        }
22390    }
22391}
22392impl<H: HostTypes> crate::bridge::partition::Component<H> for NullIrreducibleSet<H> {
22393    type Datum = NullDatum<H>;
22394    fn member(&self) -> &[Self::Datum] {
22395        &[]
22396    }
22397    fn cardinality(&self) -> u64 {
22398        0
22399    }
22400}
22401impl<H: HostTypes> crate::bridge::partition::IrreducibleSet<H> for NullIrreducibleSet<H> {}
22402
22403/// Resolver-absent default `ReducibleSet<H>`. Implements `Component<H>` with empty
22404/// `member` slice and zero `cardinality`.
22405#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22406pub struct NullReducibleSet<H: HostTypes> {
22407    _phantom: core::marker::PhantomData<H>,
22408}
22409impl<H: HostTypes> Default for NullReducibleSet<H> {
22410    fn default() -> Self {
22411        Self {
22412            _phantom: core::marker::PhantomData,
22413        }
22414    }
22415}
22416impl<H: HostTypes> crate::bridge::partition::Component<H> for NullReducibleSet<H> {
22417    type Datum = NullDatum<H>;
22418    fn member(&self) -> &[Self::Datum] {
22419        &[]
22420    }
22421    fn cardinality(&self) -> u64 {
22422        0
22423    }
22424}
22425impl<H: HostTypes> crate::bridge::partition::ReducibleSet<H> for NullReducibleSet<H> {}
22426
22427/// Resolver-absent default `UnitGroup<H>`. Implements `Component<H>` with empty
22428/// `member` slice and zero `cardinality`.
22429#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22430pub struct NullUnitGroup<H: HostTypes> {
22431    _phantom: core::marker::PhantomData<H>,
22432}
22433impl<H: HostTypes> Default for NullUnitGroup<H> {
22434    fn default() -> Self {
22435        Self {
22436            _phantom: core::marker::PhantomData,
22437        }
22438    }
22439}
22440impl<H: HostTypes> crate::bridge::partition::Component<H> for NullUnitGroup<H> {
22441    type Datum = NullDatum<H>;
22442    fn member(&self) -> &[Self::Datum] {
22443        &[]
22444    }
22445    fn cardinality(&self) -> u64 {
22446        0
22447    }
22448}
22449impl<H: HostTypes> crate::bridge::partition::UnitGroup<H> for NullUnitGroup<H> {}
22450
22451/// Resolver-absent default `Complement<H>`. Implements `Component<H>` plus
22452/// the `exterior_criteria()` accessor returning a reference to an embedded
22453/// `NullTermExpression`.
22454#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22455pub struct NullComplement<H: HostTypes> {
22456    term: NullTermExpression<H>,
22457}
22458impl<H: HostTypes> Default for NullComplement<H> {
22459    fn default() -> Self {
22460        Self {
22461            term: NullTermExpression::default(),
22462        }
22463    }
22464}
22465impl<H: HostTypes> crate::bridge::partition::Component<H> for NullComplement<H> {
22466    type Datum = NullDatum<H>;
22467    fn member(&self) -> &[Self::Datum] {
22468        &[]
22469    }
22470    fn cardinality(&self) -> u64 {
22471        0
22472    }
22473}
22474impl<H: HostTypes> crate::bridge::partition::Complement<H> for NullComplement<H> {
22475    type TermExpression = NullTermExpression<H>;
22476    fn exterior_criteria(&self) -> &Self::TermExpression {
22477        &self.term
22478    }
22479}
22480
22481/// Resolver-absent default `TypeDefinition<H>`. Embeds inline `NullElement`
22482/// for the content_address accessor.
22483#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22484pub struct NullTypeDefinition<H: HostTypes> {
22485    element: NullElement<H>,
22486}
22487impl<H: HostTypes> Default for NullTypeDefinition<H> {
22488    fn default() -> Self {
22489        Self {
22490            element: NullElement::default(),
22491        }
22492    }
22493}
22494impl<H: HostTypes> crate::user::type_::TypeDefinition<H> for NullTypeDefinition<H> {
22495    type Element = NullElement<H>;
22496    fn content_address(&self) -> &Self::Element {
22497        &self.element
22498    }
22499}
22500
22501/// Resolver-absent default `Partition<H>`. Embeds inline stubs for every
22502/// sub-trait associated type so `Partition<H>` accessors return references
22503/// to fields rather than to statics. The only meaningful state is the
22504/// `fingerprint`; everything else uses `HostTypes::EMPTY_*` defaults.
22505/// Returned by the three witness trait impls' `left_factor` / `right_factor`
22506/// / `left_summand` / etc. accessors as the resolver-absent value pathway.
22507/// Consumers needing real partition data pair the sibling `PartitionHandle`
22508/// with a `PartitionResolver` instead.
22509#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22510pub struct NullPartition<H: HostTypes> {
22511    irreducibles: NullIrreducibleSet<H>,
22512    reducibles: NullReducibleSet<H>,
22513    units: NullUnitGroup<H>,
22514    exterior: NullComplement<H>,
22515    free_rank: NullFreeRank<H>,
22516    tag_site: NullTagSite<H>,
22517    source_type: NullTypeDefinition<H>,
22518    fingerprint: ContentFingerprint,
22519}
22520
22521impl<H: HostTypes> NullPartition<H> {
22522    /// Construct a NullPartition with the given content fingerprint.
22523    /// All other fields are resolver-absent defaults.
22524    #[inline]
22525    #[must_use]
22526    pub fn from_fingerprint(fingerprint: ContentFingerprint) -> Self {
22527        Self {
22528            irreducibles: NullIrreducibleSet::default(),
22529            reducibles: NullReducibleSet::default(),
22530            units: NullUnitGroup::default(),
22531            exterior: NullComplement::default(),
22532            free_rank: NullFreeRank::default(),
22533            tag_site: NullTagSite::default(),
22534            source_type: NullTypeDefinition::default(),
22535            fingerprint,
22536        }
22537    }
22538    /// Returns the content fingerprint identifying which Partition this stub stands in for.
22539    #[inline]
22540    #[must_use]
22541    pub const fn fingerprint(&self) -> ContentFingerprint {
22542        self.fingerprint
22543    }
22544    /// Phase 2 (orphan-closure): absent-value sentinel used by Null stubs
22545    /// in other namespaces to satisfy `&Self::Partition` return borrows.
22546    pub const ABSENT: NullPartition<H> = NullPartition {
22547        irreducibles: NullIrreducibleSet {
22548            _phantom: core::marker::PhantomData,
22549        },
22550        reducibles: NullReducibleSet {
22551            _phantom: core::marker::PhantomData,
22552        },
22553        units: NullUnitGroup {
22554            _phantom: core::marker::PhantomData,
22555        },
22556        exterior: NullComplement {
22557            term: NullTermExpression {
22558                _phantom: core::marker::PhantomData,
22559            },
22560        },
22561        free_rank: NullFreeRank {
22562            _phantom: core::marker::PhantomData,
22563        },
22564        tag_site: NullTagSite {
22565            ancilla: NullSiteIndex {
22566                _phantom: core::marker::PhantomData,
22567            },
22568        },
22569        source_type: NullTypeDefinition {
22570            element: NullElement {
22571                _phantom: core::marker::PhantomData,
22572            },
22573        },
22574        fingerprint: ContentFingerprint::zero(),
22575    };
22576}
22577
22578impl<H: HostTypes> crate::bridge::partition::Partition<H> for NullPartition<H> {
22579    type IrreducibleSet = NullIrreducibleSet<H>;
22580    fn irreducibles(&self) -> &Self::IrreducibleSet {
22581        &self.irreducibles
22582    }
22583    type ReducibleSet = NullReducibleSet<H>;
22584    fn reducibles(&self) -> &Self::ReducibleSet {
22585        &self.reducibles
22586    }
22587    type UnitGroup = NullUnitGroup<H>;
22588    fn units(&self) -> &Self::UnitGroup {
22589        &self.units
22590    }
22591    type Complement = NullComplement<H>;
22592    fn exterior(&self) -> &Self::Complement {
22593        &self.exterior
22594    }
22595    fn density(&self) -> H::Decimal {
22596        H::EMPTY_DECIMAL
22597    }
22598    type TypeDefinition = NullTypeDefinition<H>;
22599    fn source_type(&self) -> &Self::TypeDefinition {
22600        &self.source_type
22601    }
22602    fn witt_length(&self) -> u64 {
22603        0
22604    }
22605    type FreeRank = NullFreeRank<H>;
22606    fn site_budget(&self) -> &Self::FreeRank {
22607        &self.free_rank
22608    }
22609    fn is_exhaustive(&self) -> bool {
22610        true
22611    }
22612    type TagSite = NullTagSite<H>;
22613    fn tag_site_of(&self) -> &Self::TagSite {
22614        &self.tag_site
22615    }
22616    fn product_category_level(&self) -> &H::HostString {
22617        H::EMPTY_HOST_STRING
22618    }
22619}
22620
22621impl<H: HostTypes> crate::bridge::partition::PartitionProduct<H> for PartitionProductWitness {
22622    type Partition = NullPartition<H>;
22623    fn left_factor(&self) -> Self::Partition {
22624        NullPartition::from_fingerprint(self.left_fingerprint)
22625    }
22626    fn right_factor(&self) -> Self::Partition {
22627        NullPartition::from_fingerprint(self.right_fingerprint)
22628    }
22629}
22630
22631impl<H: HostTypes> crate::bridge::partition::PartitionCoproduct<H> for PartitionCoproductWitness {
22632    type Partition = NullPartition<H>;
22633    fn left_summand(&self) -> Self::Partition {
22634        NullPartition::from_fingerprint(self.left_fingerprint)
22635    }
22636    fn right_summand(&self) -> Self::Partition {
22637        NullPartition::from_fingerprint(self.right_fingerprint)
22638    }
22639}
22640
22641impl<H: HostTypes> crate::bridge::partition::CartesianPartitionProduct<H>
22642    for CartesianProductWitness
22643{
22644    type Partition = NullPartition<H>;
22645    fn left_cartesian_factor(&self) -> Self::Partition {
22646        NullPartition::from_fingerprint(self.left_fingerprint)
22647    }
22648    fn right_cartesian_factor(&self) -> Self::Partition {
22649        NullPartition::from_fingerprint(self.right_fingerprint)
22650    }
22651}
22652
22653/// v0.2.1 ergonomics prelude. Re-exports the core symbols downstream crates
22654/// need for the consumer-facing one-liners.
22655/// Ontology-driven: the set of certificate / type / builder symbols is
22656/// sourced from `conformance:PreludeExport` individuals. Adding a new
22657/// symbol to the prelude is an ontology edit, verified against the
22658/// codegen's known-name mapping at build time.
22659pub mod prelude {
22660    pub use super::calibrations;
22661    pub use super::Add;
22662    pub use super::And;
22663    pub use super::BNot;
22664    pub use super::BinaryGroundingMap;
22665    pub use super::BindingEntry;
22666    pub use super::BindingsTable;
22667    pub use super::BornRuleVerification;
22668    pub use super::Calibration;
22669    pub use super::CalibrationError;
22670    pub use super::CanonicalTimingPolicy;
22671    pub use super::Certificate;
22672    pub use super::Certified;
22673    pub use super::ChainAuditTrail;
22674    pub use super::CompileTime;
22675    pub use super::CompileUnit;
22676    pub use super::CompileUnitBuilder;
22677    pub use super::CompletenessAuditTrail;
22678    pub use super::CompletenessCertificate;
22679    pub use super::ConstrainedTypeInput;
22680    pub use super::ContentAddress;
22681    pub use super::ContentFingerprint;
22682    pub use super::Datum;
22683    pub use super::DigestGroundingMap;
22684    pub use super::Embed;
22685    pub use super::FragmentMarker;
22686    pub use super::GenericImpossibilityWitness;
22687    pub use super::GeodesicCertificate;
22688    pub use super::GeodesicEvidenceBundle;
22689    pub use super::Grounded;
22690    pub use super::GroundedCoord;
22691    pub use super::GroundedShape;
22692    pub use super::GroundedTuple;
22693    pub use super::GroundedValue;
22694    pub use super::Grounding;
22695    pub use super::GroundingCertificate;
22696    pub use super::GroundingExt;
22697    pub use super::GroundingMapKind;
22698    pub use super::GroundingProgram;
22699    pub use super::Hasher;
22700    pub use super::ImpossibilityWitnessKind;
22701    pub use super::InhabitanceCertificate;
22702    pub use super::InhabitanceImpossibilityWitness;
22703    pub use super::IntegerGroundingMap;
22704    pub use super::Invertible;
22705    pub use super::InvolutionCertificate;
22706    pub use super::IsometryCertificate;
22707    pub use super::JsonGroundingMap;
22708    pub use super::LandauerBudget;
22709    pub use super::LiftChainCertificate;
22710    pub use super::MeasurementCertificate;
22711    pub use super::Mul;
22712    pub use super::Nanos;
22713    pub use super::Neg;
22714    pub use super::OntologyTarget;
22715    pub use super::Or;
22716    pub use super::PipelineFailure;
22717    pub use super::PreservesMetric;
22718    pub use super::PreservesStructure;
22719    pub use super::RingOp;
22720    pub use super::Runtime;
22721    pub use super::ShapeViolation;
22722    pub use super::Sub;
22723    pub use super::Succ;
22724    pub use super::Term;
22725    pub use super::TermArena;
22726    pub use super::TimingPolicy;
22727    pub use super::Total;
22728    pub use super::TransformCertificate;
22729    pub use super::Triad;
22730    pub use super::UnaryRingOp;
22731    pub use super::UorTime;
22732    pub use super::Utf8GroundingMap;
22733    pub use super::ValidLevelEmbedding;
22734    pub use super::Validated;
22735    pub use super::ValidationPhase;
22736    pub use super::Xor;
22737    pub use super::W16;
22738    pub use super::W8;
22739    pub use crate::pipeline::empty_bindings_table;
22740    pub use crate::pipeline::{
22741        validate_constrained_type, validate_constrained_type_const, ConstrainedTypeShape,
22742        ConstraintRef, FragmentKind,
22743    };
22744    pub use crate::{DecimalTranscendental, DefaultHostTypes, HostTypes, WittLevel};
22745}