uor-foundation 0.4.9

UOR Foundation — typed Rust traits for the complete ontology. Import and implement.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// @generated by uor-crate from uor-ontology — do not edit manually

//! UOR Foundation — typed Rust traits for the complete ontology.
//!
//! Version: 0.4.9
//!
//! This crate exports every ontology class as a trait, every property as a
//! method, and every named individual as a constant. Implementations import
//! these traits and provide concrete types.
//!
//! # Principal data path
//!
//! v0.2.2 establishes a single sanctioned API path. Everything else has been
//! deleted (no proc-macro back-doors, no second constructor for sealed types):
//!
//! ```text
//!  host bytes  ──▶  impl Grounding<Map = …>  ──▶  Datum<L>   [W4: kind-typed]
//!//!//!  builder.validate_const() │ .validate()  ──▶  Validated<T, Phase>
//!                                                  │            [W2 + W13]
//!//!  pipeline::run::<T, P>(unit)  ──▶  Grounded<T>
//!                                       │            [W14]
//!//!                            .triad() → Triad<L>     [W8]
//!                            .certificate()          [W11: Certified<C>]
//! ```
//!
//! Every contract is enforced at the type and visibility level. Sealed traits,
//! `pub(crate)` constructors, and the v0.2.2 conformance suite (W5 ψ-leakage gate,
//! W6 public-API snapshot) catch any deviation.
//!
//! # Substitution axes (per the UOR-Framework wiki)
//!
//! The wiki names three substitution axes the application author selects
//! against — `HostTypes`, `HostBounds`, `Hasher`. The foundation defines
//! the trait surface; downstream substrates declare the bound the trait
//! must satisfy; the application's crate selects the implementation.
//!
//! ## `HostTypes` (target §4.1 W10)
//!
//! Downstream chooses representations only for the three slots that genuinely
//! vary across host environments. Witt-level integers, booleans, IRIs, canonical
//! bytes, and `UorTime` are foundation-owned and derived from `WittLevel`.
//!
//! ```no_run
//! use uor_foundation::{HostTypes, DefaultHostTypes};
//!
//! // Use the canonical defaults: f64 / str / [u8].
//! type H = DefaultHostTypes;
//!
//! // Or override one slot:
//! struct EmbeddedHost;
//! impl HostTypes for EmbeddedHost {
//!     type Decimal = f32;          // override: tighter precision budget
//!     type HostString = str;       // default
//!     type WitnessBytes = [u8];    // default
//!     const EMPTY_DECIMAL: f32 = 0.0;
//!     const EMPTY_HOST_STRING: &'static str = "";
//!     const EMPTY_WITNESS_BYTES: &'static [u8] = &[];
//! }
//! ```
//!
//! ## `HostBounds` (wiki ADR-018)
//!
//! Carries every capacity bound that varies along the principal data
//! path: the fingerprint output width range, the trace event-count
//! ceiling, the algebraic-level bit-width ceiling. Per ADR-018 the
//! architecture admits no capacity bound outside `HostBounds`.
//!
//! ```no_run
//! use uor_foundation::{HostBounds, DefaultHostBounds};
//!
//! type B = DefaultHostBounds;
//! assert_eq!(<B as HostBounds>::FINGERPRINT_MAX_BYTES, 32);
//! ```
//!
//!
//! # Module structure
//!
//! - [`kernel`] — Immutable foundation: addressing, schema, operations
//! - [`bridge`] — Kernel-computed, user-consumed: queries, resolution, partitions, proofs
//! - [`user`] — Runtime declarations: types, morphisms, state
//! - [`enforcement`] — Sealed types and the principal-path entry surface
//! - [`pipeline`] — `pipeline::run::<T, P>` and the resolver dispatch
//!
//! # Enforcement layer
//!
//! [`enforcement`] provides the sealed types that v0.2.2 forbids downstream
//! from constructing directly:
//!
//! **Layer 1 — Opaque witnesses.** [`enforcement::Datum`],
//! [`enforcement::Validated`], [`enforcement::Derivation`],
//! [`enforcement::FreeRank`], [`enforcement::Grounded`],
//! [`enforcement::Certified`], [`enforcement::Triad`]: sealed types with
//! private fields. Only the foundation's pipeline / resolver paths produce them.
//!
//! **Layer 2 — Declarative builders.** [`enforcement::CompileUnitBuilder`]
//! and 8 others collect declarations and emit `Validated<T, Phase>` on
//! success or [`enforcement::ShapeViolation`] with a machine-readable IRI.
//!
//! **Layer 3 — Term AST.** [`enforcement::Term`] and
//! [`enforcement::TermArena`]: stack-resident, `#![no_std]`-safe expression
//! trees. The `Term` enum's struct-variant constructors are the canonical
//! builder API — there is no DSL macro in v0.2.2.
//!
//! # Foundation as a signature category (wiki ADR-019)
//!
//! `uor-foundation`'s vocabulary is the **signature category** of Prism's
//! typed routes. Objects are [`pipeline::ConstrainedTypeShape`] impls under
//! the substitution-axis selections; morphisms are typed compositions of
//! [`PrimitiveOp`] discriminants and [`enforcement::Term::Application`]
//! constructions.
//!
//! The category supports a **signature endofunctor** F whose enriched
//! signature has one branch per [`enforcement::Term`] variant — the four
//! first-order constructors (`Literal`, `Application`, `Lift`, `Project`),
//! plus binding (`Variable`), case analysis (`Match`), explicit fixed-point
//! (`Recurse`), explicit unfold (`Unfold`), and failure-promote (`Try`).
//!
//! [`enforcement::Term`] is F's **initial algebra**: any well-typed term
//! tree is an element of the free term language F generates from its
//! enriched signature, and any carrier supporting the same enriched
//! structure admits a *unique* structure-preserving map from `Term`.
//!
//! [`pipeline::run`] is the **catamorphism** into the runtime carrier
//! parameterized by the substitution axes (`HostTypes`, `HostBounds`,
//! `Hasher`). Its dual, the **anamorphism**, is the trace-replay surface
//! ([`enforcement::Derivation::replay`] +
//! [`enforcement::replay::certify_from_trace`]); the trace is the
//! anamorphism's witness object. The four UOR-domain sealed types
//! ([`enforcement::Datum`], [`enforcement::Triad`],
//! [`enforcement::Derivation`], [`enforcement::FreeRank`]) and the three
//! Prism-mechanism sealed types ([`enforcement::Validated`],
//! [`enforcement::Grounded`], [`enforcement::Certified`]) are **fixed
//! points** of the typed pipeline endofunctor (distinct from F; see wiki
//! section 8, Fixed Points).
//!
//! Initiality and uniqueness of the catamorphism hold *within each fixed
//! choice of the three substitution axes*: for a given
//! `(HostTypes, HostBounds, Hasher)` selection, there is exactly one
//! F-algebra homomorphism from `Term` to the corresponding carrier. The
//! categorical statement of ADR-018's capacity completeness is that the
//! indexing of carriers is *total* over `HostBounds` — every
//! capacity-bounded width that varies along the principal data path is
//! part of the index. The substrate-vs-implementor split (ADR-007's
//! three-position pattern) extends naturally: foundation defines F and
//! the initial algebra; the runtime declares the bound any application's
//! `Route` MUST satisfy and the catamorphism that compiles it; the
//! application author selects the F-algebra by writing the model.
//!
//! # `PrismModel` — the application author's typed iso (wiki ADR-020)
//!
//! [`pipeline::PrismModel`] codifies the iso the application author
//! declares: an `Input` feature type, an `Output` label type, and a
//! type-level `Route` witness of the term tree mapping one to the other.
//! The `Route` associated type is bound by [`pipeline::FoundationClosed`]
//! — closure under foundation vocabulary, enforced at the application's
//! compile time per UORassembly (TC-04, ADR-006). `forward()` is the
//! catamorphism into [`pipeline::run`]'s runtime carrier; together with
//! the `Trace`-witnessed anamorphism through
//! [`enforcement::replay::certify_from_trace`] it forms the verifiable
//! round-trip described in the wiki.
//!
//! # Witness minting (Phases 10 + 12 + 14 + 15)
//!
//! Path-2 ontology classes (theorem-attesting witnesses such as
//! [`witness_scaffolds::MintBornRuleVerification`],
//! [`witness_scaffolds::MintCompletenessWitness`], etc.) implement the
//! sealed [`OntologyVerifiedMint`] trait. Mint a witness by populating
//! its `Mint{Foo}Inputs<H>` bundle with non-zero handles + true
//! attestation flags + non-empty strings, then calling
//! `Mint{Foo}::ontology_mint::<H>(inputs)`. On structural-invariant
//! failure each `verify_*` primitive in `crate::primitives::{family}`
//! returns a typed [`enforcement::GenericImpossibilityWitness`] whose
//! IRI cites the specific failing op-namespace identity (BR_*,
//! CC_*, IH_*, FX_4, WLS_*, surfaceSymmetry).
//!
//! # Per-class observable views (Phase 16)
//!
//! [`enforcement::Validated<T, Phase>`] does not directly implement
//! the kind-specific `Observable<H>` trait — Rust forbids multiple
//! `Observable<H>` impls per type, and the bare blanket would return
//! a sentinel for every kind. Consumers select an explicit kind via
//! the inherent accessors
//! [`Validated::as_landauer`](enforcement::Validated::as_landauer),
//! [`Validated::as_jacobian`](enforcement::Validated::as_jacobian),
//! [`Validated::as_carry_depth`](enforcement::Validated::as_carry_depth),
//! [`Validated::as_derivation_depth`](enforcement::Validated::as_derivation_depth),
//! and [`Validated::as_free_rank`](enforcement::Validated::as_free_rank).
//! Each returns a zero-cost newtype view in [`blanket_impls`] whose
//! `Observable<H>::value()` body delegates to the relevant primitive
//! (`primitive_descent_metrics`, `primitive_curvature_jacobian`,
//! `primitive_dihedral_signature`, etc.).
//!
//! Calling `.landauer_nats()` on the view requires the
//! `bridge::observable::LandauerBudget` *trait* to be in scope —
//! distinct from the `enforcement::LandauerBudget` *struct*
//! re-exported at the crate root. Likewise for `as_jacobian` →
//! `bridge::observable::JacobianObservable`,
//! `as_carry_depth` → `kernel::carry::CarryDepthObservable`,
//! `as_derivation_depth` →
//! `bridge::derivation::DerivationDepthObservable`, and
//! `as_free_rank` → `bridge::partition::FreeRankObservable`.
//! `<_ as Observable<H>>::value(&view)` works for every view
//! once `Observable` itself is in scope.
//!
//! # Resolvers (v0.2.2 W12)
//!
//! Verdict-producing resolvers are free functions in module-per-resolver
//! organization. Each function returns a `Result<Certified<Cert>, Witness>`:
//!
//! - `enforcement::resolver::inhabitance::certify(input)` — inhabitance verdict
//! - `enforcement::resolver::tower_completeness::certify(input)` — tower completeness
//! - `enforcement::resolver::incremental_completeness::certify(input)` — incremental
//! - `enforcement::resolver::grounding_aware::certify(unit)` — grounding-aware
//!
//! # Features
//!
//! The crate ships this feature-flag layout. Every capability the `default`
//! build omits is opt-in; the default is `#![no_std]`-pure and alloc-free.
//!
//! | Feature         | Default | Adds | When to enable |
//! |-----------------|---------|------|----------------|
//! | `alloc`         | off     | `extern crate alloc`; alloc-backed diagnostic helpers | Heap available but no OS |
//! | `std`           | off     | `alloc` + std-specific paths | Hosted platforms |
//! | `libm`          | **on** (unconditional dep) | `libm`-backed `ln`, `exp`, `sqrt` for transcendental observables | Always on — required by `xsd:decimal` observables (see target §1.6) |
//! | `serde`         | off     | `serde::{Serialize, Deserialize}` on `Trace`, `TraceEvent`, and other carriers | Exporting traces to external verifiers |
//! | `observability` | off     | `alloc` + a `subscribe(handler: FnMut(&TraceEvent))` surface | Runtime observation of the reduction pipeline |
//!
//! The `default = []` posture means bare-metal targets (`thumbv7em-none-eabihf`)
//! build without any feature flag. CI validates three configurations: the
//! bare-metal `no_std` cross-build, the `alloc`-additive hosted build, and
//! the `--all-features` composite. See target §1.6 and §7.5.
//!
//! # Scope note
//!
//! This crate is conformance-first: every surface the ontology specifies
//! is present, and every surface it rejects (e.g., the deleted v0.2.1
//! `Primitives` trait and unit-struct resolver façades) is absent. There
//! is no migration layer, no deprecation aliases, and no compatibility
//! shims — the crate is either in conformance with the ontology or it isn't.

#![no_std]

pub mod blanket_impls;
pub mod bridge;
pub mod enforcement;
pub mod enums;
pub mod kernel;
pub mod pipeline;
pub mod primitives;
pub mod user;
pub mod witness_scaffolds;

pub use enums::*;

pub use witness_scaffolds::OntologyVerifiedMint;

pub use enforcement::{
    BindingEntry, BindingsTable, BindingsTableError, BoundConstraint, Calibration,
    CalibrationError, Certificate, CertificateKind, Certified, CompileUnit, CompileUnitBuilder,
    ContentAddress, ContentFingerprint, Derivation, Grounded, GroundingCertificate, Hasher,
    LandauerBudget, MultiplicationCertificate, Nanos, PipelineFailure, ReplayError, ShapeViolation,
    Term, TermArena, TermList, Trace, TraceEvent, UorTime, Validated, TRACE_REPLAY_FORMAT_VERSION,
};

pub use enforcement::{
    CartesianProductEvidence, CartesianProductMintInputs, CartesianProductWitness,
    GenericImpossibilityWitness, NullPartition, PartitionCoproductEvidence,
    PartitionCoproductMintInputs, PartitionCoproductWitness, PartitionHandle,
    PartitionProductEvidence, PartitionProductMintInputs, PartitionProductWitness, PartitionRecord,
    PartitionResolver, VerifiedMint,
};

/// Closed arithmetic and transcendental math for the `HostTypes::Decimal`
/// slot. `f64` and `f32` implement this via `libm`. Downstream `HostTypes`
/// impls are free to bring their own implementation (interval arithmetic,
/// arbitrary precision, fixed-point, etc.).
pub trait DecimalTranscendental:
    Copy
    + Default
    + core::fmt::Debug
    + PartialEq
    + PartialOrd
    + core::ops::Add<Output = Self>
    + core::ops::Sub<Output = Self>
    + core::ops::Mul<Output = Self>
    + core::ops::Div<Output = Self>
{
    /// Construct from an unsigned 32-bit integer. f32 / f64 use `as` widening; downstream impls bring their own promotion.
    fn from_u32(value: u32) -> Self;
    /// Construct from an unsigned 64-bit integer (rewrite-step counts, etc.).
    fn from_u64(value: u64) -> Self;
    /// Saturating projection to `u64`. Used by `UorTime::min_wall_clock` to convert a wall-clock seconds-Decimal into integer nanoseconds.
    fn as_u64_saturating(self) -> u64;
    /// Natural logarithm.
    fn ln(self) -> Self;
    /// Exponential `e^x`.
    fn exp(self) -> Self;
    /// Square root.
    fn sqrt(self) -> Self;
    /// Construct from an IEEE-754 bit pattern (default-host f64 round-trip).
    fn from_bits(bits: u64) -> Self;
    /// Project to an IEEE-754 bit pattern (default-host f64 round-trip).
    fn to_bits(self) -> u64;
    /// Entropy contribution `x * ln(x)`, with the convention `0 * ln(0) = 0`.
    #[inline]
    fn entropy_term_nats(self) -> Self {
        if self == Self::default() {
            return Self::default();
        }
        self * self.ln()
    }
}

impl DecimalTranscendental for f64 {
    #[inline]
    fn from_u32(value: u32) -> Self {
        f64::from(value)
    }
    #[inline]
    fn from_u64(value: u64) -> Self {
        // u64 -> f64 is lossy above 2^53; documented at use sites.
        value as f64
    }
    #[inline]
    fn as_u64_saturating(self) -> u64 {
        if self.partial_cmp(&0.0).is_none_or(|o| o.is_lt()) {
            return 0;
        }
        if self >= u64::MAX as f64 {
            return u64::MAX;
        }
        self as u64
    }
    #[inline]
    fn ln(self) -> Self {
        libm::log(self)
    }
    #[inline]
    fn exp(self) -> Self {
        libm::exp(self)
    }
    #[inline]
    fn sqrt(self) -> Self {
        libm::sqrt(self)
    }
    #[inline]
    fn from_bits(bits: u64) -> Self {
        f64::from_bits(bits)
    }
    #[inline]
    fn to_bits(self) -> u64 {
        f64::to_bits(self)
    }
}

impl DecimalTranscendental for f32 {
    #[inline]
    fn from_u32(value: u32) -> Self {
        // u32 -> f32 is lossy at high values; this is the documented
        // host-default behavior for arithmetic constants.
        value as f32
    }
    #[inline]
    fn from_u64(value: u64) -> Self {
        // u64 -> f32 is lossy above 2^24; documented at use sites.
        value as f32
    }
    #[inline]
    fn as_u64_saturating(self) -> u64 {
        if self.partial_cmp(&0.0).is_none_or(|o| o.is_lt()) {
            return 0;
        }
        if self >= u64::MAX as f32 {
            return u64::MAX;
        }
        self as u64
    }
    #[inline]
    fn ln(self) -> Self {
        libm::logf(self)
    }
    #[inline]
    fn exp(self) -> Self {
        libm::expf(self)
    }
    #[inline]
    fn sqrt(self) -> Self {
        libm::sqrtf(self)
    }
    #[inline]
    fn from_bits(bits: u64) -> Self {
        // f32 has no native u64-bit constructor; widen via f64 then narrow.
        f64::from_bits(bits) as f32
    }
    #[inline]
    fn to_bits(self) -> u64 {
        (self as f64).to_bits()
    }
}

/// Phase B (target §4.1 W10): narrow host-types trait — the only carrier for
/// the slots that genuinely vary across host environments. Foundation-owned
/// types (Witt-level integers, booleans, IRIs, canonicalBytes, `UorTime`) are
/// derived from the `WittLevel` family and not exposed here.
/// Three slots: `Decimal` (real-number representation), `HostString` (opaque
/// host string, NOT a foundation IRI), and `WitnessBytes` (opaque host byte
/// sequence, NOT a foundation `canonicalBytes` constant). The v0.2.1 `DateTime`
/// slot is removed; downstream associates timestamps out-of-band.
/// # Example
/// ```
/// use uor_foundation::{HostTypes, DefaultHostTypes};
/// // Canonical defaults: f64 / str / [u8].
/// type DefaultH = DefaultHostTypes;
/// // Override the Decimal slot for embedded targets with tighter precision:
/// struct EmbeddedHost;
/// impl HostTypes for EmbeddedHost {
///     type Decimal = f32;          // override
///     type HostString = str;       // default
///     type WitnessBytes = [u8];    // default
///     const EMPTY_DECIMAL: f32 = 0.0;
///     const EMPTY_HOST_STRING: &'static str = "";
///     const EMPTY_WITNESS_BYTES: &'static [u8] = &[];
/// }
/// # let _ = (core::marker::PhantomData::<DefaultH>, core::marker::PhantomData::<EmbeddedHost>);
/// ```
pub trait HostTypes {
    /// Real-number representation for kernel observables (entropies, amplitudes, rates).
    /// `DefaultHostTypes` selects `f64`. Override with higher-precision or interval
    /// arithmetic as needed.
    ///
    /// Phase 9 bound: every `Decimal` must implement [`DecimalTranscendental`] —
    /// closed arithmetic + ln/exp/sqrt + IEEE-754 bit-pattern round-trip. The
    /// in-tree `f64` and `f32` impls satisfy this via `libm`.
    type Decimal: DecimalTranscendental;

    /// Host-supplied opaque string (NOT a foundation IRI).
    /// `DefaultHostTypes` selects `str`. Override with owned `String`, `Cow<'_, str>`,
    /// etc. for embedded / host-heap environments.
    /// The `'static` bound is required by the Product/Coproduct Completion
    /// Amendment §B1 `EMPTY_HOST_STRING` constant — every conforming `H`
    /// must be able to expose a `&'static HostString`. All in-tree impls
    /// (`DefaultHostTypes::HostString = str`) already satisfy this.
    type HostString: ?Sized + 'static;

    /// Host-supplied opaque byte sequence (NOT a foundation `canonicalBytes` constant).
    /// `DefaultHostTypes` selects `[u8]`. Override with owned `Vec<u8>`, `Bytes`,
    /// etc. for host-heap environments.
    /// The `'static` bound mirrors `HostString` for the same reason — see
    /// the `EMPTY_WITNESS_BYTES` constant below.
    type WitnessBytes: ?Sized + 'static;

    /// Empty / zero `Decimal` value for resolver-absent partition accessors.
    /// `DefaultHostTypes` selects `0.0`. Used by `NullPartition::density()`
    /// and analogous H-typed defaults.
    const EMPTY_DECIMAL: Self::Decimal;

    /// Empty `&'static HostString` reference for resolver-absent accessors.
    /// `DefaultHostTypes` selects `&""` coerced to `&str`. Used by
    /// `NullPartition::product_category_level()` and the address-typed
    /// string accessors on `NullElement<H>`.
    const EMPTY_HOST_STRING: &'static Self::HostString;

    /// Empty `&'static WitnessBytes` reference for resolver-absent accessors.
    /// `DefaultHostTypes` selects `&[]` coerced to `&[u8]`. Used by
    /// `NullElement<H>::canonical_bytes()`.
    const EMPTY_WITNESS_BYTES: &'static Self::WitnessBytes;
}

/// Phase B: canonical default impl of [`HostTypes`]. Selects `f64`/`str`/`[u8]`.
/// Use as `type H = uor_foundation::DefaultHostTypes;` to inherit the defaults;
/// replace with a downstream marker struct if any slot needs an override.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DefaultHostTypes;

/// π · ℏ = `core::f64::consts::PI * 1.054_571_817e-34` J·s, in IEEE-754 bits.
/// Half of one orthogonal-state-transition Margolus-Levitin bound.
pub const PI_TIMES_H_BAR_BITS: u64 = f64::to_bits(core::f64::consts::PI * 1.054_571_817e-34_f64);

/// Nanoseconds per second (`1.0e9`) in IEEE-754 bits. Used by `UorTime::min_wall_clock`.
pub const NANOS_PER_SECOND_BITS: u64 = f64::to_bits(1.0e9_f64);

/// Natural logarithm of 2, in IEEE-754 bits. Drives the Landauer bit-erasure unit.
pub const LN_2_BITS: u64 = f64::to_bits(core::f64::consts::LN_2);

/// Lower bound for `Calibration::k_b_t` (1e-30 J), in IEEE-754 bits.
pub const CALIBRATION_KBT_LO_BITS: u64 = f64::to_bits(1.0e-30_f64);

/// Upper bound for `Calibration::k_b_t` (1e-15 J), in IEEE-754 bits.
pub const CALIBRATION_KBT_HI_BITS: u64 = f64::to_bits(1.0e-15_f64);

/// Upper bound for `Calibration::thermal_power` (1e9 W), in IEEE-754 bits.
pub const CALIBRATION_THERMAL_POWER_HI_BITS: u64 = f64::to_bits(1.0e9_f64);

/// Upper bound for `Calibration::characteristic_energy` (1e3 J), in IEEE-754 bits.
pub const CALIBRATION_CHAR_ENERGY_HI_BITS: u64 = f64::to_bits(1.0e3_f64);

impl HostTypes for DefaultHostTypes {
    type Decimal = f64;
    type HostString = str;
    type WitnessBytes = [u8];
    const EMPTY_DECIMAL: Self::Decimal = 0.0;
    const EMPTY_HOST_STRING: &'static str = "";
    const EMPTY_WITNESS_BYTES: &'static [u8] = &[];
}

/// Substitution axis 2 of 3 (per the UOR-Framework wiki). Carries every
/// capacity bound that varies along the principal data path: the fingerprint
/// output width range, the trace event-count ceiling, and the algebraic-level
/// bit-width ceiling. The application author selects an impl; the foundation
/// (this trait) declares the contract.
/// Per the wiki's ADR-018, the architecture admits no capacity bound outside
/// `HostBounds`. Foundation's `Hasher`, `ContentFingerprint`, and `Trace` are
/// const-generic over their capacity bounds; applications populate each
/// type's const-generic with `<MyBounds as HostBounds>::CONST`. There are no
/// free-standing capacity constants on the public surface — collapsing the
/// substitution axis is exactly what ADR-018 rejects.
/// # Example
/// ```
/// use uor_foundation::{HostBounds, DefaultHostBounds};
/// // Inherit the canonical defaults (16 / 32 / 256 / 64).
/// type B = DefaultHostBounds;
/// assert_eq!(<B as HostBounds>::FINGERPRINT_MAX_BYTES, 32);
/// // Or declare an application-specific capacity profile:
/// struct BitcoinPow;
/// impl HostBounds for BitcoinPow {
///     const FINGERPRINT_MIN_BYTES: usize = 32;
///     const FINGERPRINT_MAX_BYTES: usize = 32;
///     const TRACE_MAX_EVENTS: usize = 1024;
///     const WITT_LEVEL_MAX_BITS: u32 = 256;
///     // ADR-037: 14 data-shape capacity caps. Match the
///     // DefaultHostBounds defaults unless the application has a
///     // specific reason to vary them.
///     const TERM_VALUE_MAX_BYTES: usize = 4096;
///     const AXIS_OUTPUT_BYTES_MAX: usize = 4096;
///     const FOLD_UNROLL_THRESHOLD: usize = 8;
///     const BETTI_DIMENSION_MAX: usize = 8;
///     const NERVE_CONSTRAINTS_MAX: usize = 8;
///     const NERVE_SITES_MAX: usize = 8;
///     const JACOBIAN_SITES_MAX: usize = 8;
///     const RECURSION_TRACE_DEPTH_MAX: usize = 16;
///     const OP_CHAIN_DEPTH_MAX: usize = 8;
///     const AFFINE_COEFFS_MAX: usize = 8;
///     const CONJUNCTION_TERMS_MAX: usize = 8;
///     const ROUTE_INPUT_BUFFER_BYTES: usize = 4096;
///     const ROUTE_OUTPUT_BUFFER_BYTES: usize = 4096;
///     const UNFOLD_ITERATIONS_MAX: usize = 256;
///     // ADR-037: 8 ψ-stage resolver output byte-buffer ceilings.
///     const NERVE_OUTPUT_BYTES_MAX: usize = 4096;
///     const CHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize = 4096;
///     const HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
///     const COCHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize = 4096;
///     const COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
///     const POSTNIKOV_TOWER_OUTPUT_BYTES_MAX: usize = 4096;
///     const HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
///     const K_INVARIANTS_OUTPUT_BYTES_MAX: usize = 4096;
/// }
/// ```
pub trait HostBounds {
    /// Minimum content-fingerprint width in bytes that the application's
    /// selected `Hasher` impl MUST produce. Derived from the application's
    /// collision-probability target (16 bytes ≈ 2^-64 under the birthday
    /// bound; raise to 32 to reach 2^-128).
    const FINGERPRINT_MIN_BYTES: usize;

    /// Maximum content-fingerprint width in bytes — the inline buffer
    /// capacity carried by every `ContentFingerprint`. The application's
    /// selected `Hasher` MUST produce output no wider than this.
    const FINGERPRINT_MAX_BYTES: usize;

    /// Maximum number of `TraceEvent` values a `Trace` may carry.
    /// Bounds the inline event buffer and caps verification time.
    const TRACE_MAX_EVENTS: usize;

    /// Algebraic-level bit-width ceiling. Caps the Witt-level any value
    /// along the principal data path may compute against. The
    /// `DefaultHostBounds` value of 64 corresponds to `WittLevel::W64`.
    const WITT_LEVEL_MAX_BITS: u32;

    /// ADR-037: maximum `TermValue` inline buffer width in bytes.
    /// Caps the catamorphism's per-fold-rule scratch size and the
    /// `TermValue::from_slice` capacity.
    const TERM_VALUE_MAX_BYTES: usize;

    /// ADR-037: maximum axis-kernel output byte-buffer width — the
    /// upper bound on the substitution-axis `dispatch()` return value's
    /// `out` slice length. Sized at least as wide as the largest
    /// axis-kernel output across the application's `AxisTuple`.
    const AXIS_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: threshold below which `fold_n(n, init, step)` lowers to
    /// an unrolled `Term::Application` chain (one application per
    /// iteration). Counts `n >= FOLD_UNROLL_THRESHOLD` lower to
    /// `Term::Recurse` instead.
    const FOLD_UNROLL_THRESHOLD: usize;

    /// ADR-037: maximum dimension index for `BettiNumbers` arrays —
    /// `β_k(K)` is stored for `k` in `0..BETTI_DIMENSION_MAX`.
    const BETTI_DIMENSION_MAX: usize;

    /// ADR-037: maximum number of constraints in a single constraint
    /// nerve's array representation.
    const NERVE_CONSTRAINTS_MAX: usize;

    /// ADR-037: maximum number of sites in a single constraint nerve's
    /// array representation.
    const NERVE_SITES_MAX: usize;

    /// ADR-037: maximum number of sites for which a Jacobian matrix
    /// can be stored inline.
    const JACOBIAN_SITES_MAX: usize;

    /// ADR-037: maximum recursion depth for the trace-replay stack.
    const RECURSION_TRACE_DEPTH_MAX: usize;

    /// ADR-037: maximum operator-chain depth in a single operation.
    const OP_CHAIN_DEPTH_MAX: usize;

    /// ADR-037: maximum number of affine coefficients per
    /// `ConstraintRef::Affine`.
    const AFFINE_COEFFS_MAX: usize;

    /// ADR-037: maximum number of conjuncts per
    /// `ConstraintRef::Conjunction`.
    const CONJUNCTION_TERMS_MAX: usize;

    /// ADR-037: maximum byte width of the route input buffer per
    /// ADR-023's `IntoBindingValue` serialization.
    const ROUTE_INPUT_BUFFER_BYTES: usize;

    /// ADR-037: maximum byte width of the route output buffer per
    /// ADR-028's `Grounded::output_bytes` payload.
    const ROUTE_OUTPUT_BUFFER_BYTES: usize;

    /// ADR-037: maximum iteration count for `Term::Unfold` evaluation.
    const UNFOLD_ITERATIONS_MAX: usize;

    /// ADR-037: maximum byte width of ψ_1 `NerveResolver::resolve`'s
    /// `out` buffer (the SimplicialComplex serialization).
    const NERVE_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_2 `ChainComplexResolver::resolve`
    /// output.
    const CHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_3
    /// `HomologyGroupResolver::resolve` output.
    const HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_5
    /// `CochainComplexResolver::resolve` output.
    const COCHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_6
    /// `CohomologyGroupResolver::resolve` output.
    const COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_7 `PostnikovResolver::resolve`
    /// output (the Postnikov-tower serialization).
    const POSTNIKOV_TOWER_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_8
    /// `HomotopyGroupResolver::resolve` output.
    const HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX: usize;

    /// ADR-037: maximum byte width of ψ_9 `KInvariantResolver::resolve`
    /// output (the κ-label byte serialization at ψ_9).
    const K_INVARIANTS_OUTPUT_BYTES_MAX: usize;
}

/// Canonical default impl of [`HostBounds`]. Carries the values the default
/// const-generic on `Hasher`, `ContentFingerprint`, and `Trace` resolves to.
/// Use as `type B = uor_foundation::DefaultHostBounds;` to inherit; replace
/// with a downstream marker struct when an application needs different
/// capacity bounds (per ADR-018, this is the only sanctioned way to vary).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DefaultHostBounds;

impl HostBounds for DefaultHostBounds {
    const FINGERPRINT_MIN_BYTES: usize = 16;
    const FINGERPRINT_MAX_BYTES: usize = 32;
    const TRACE_MAX_EVENTS: usize = 256;
    const WITT_LEVEL_MAX_BITS: u32 = 64;
    const TERM_VALUE_MAX_BYTES: usize = 4096;
    const AXIS_OUTPUT_BYTES_MAX: usize = 4096;
    const FOLD_UNROLL_THRESHOLD: usize = 8;
    const BETTI_DIMENSION_MAX: usize = 8;
    const NERVE_CONSTRAINTS_MAX: usize = 8;
    const NERVE_SITES_MAX: usize = 8;
    const JACOBIAN_SITES_MAX: usize = 8;
    const RECURSION_TRACE_DEPTH_MAX: usize = 16;
    const OP_CHAIN_DEPTH_MAX: usize = 8;
    const AFFINE_COEFFS_MAX: usize = 8;
    const CONJUNCTION_TERMS_MAX: usize = 8;
    const ROUTE_INPUT_BUFFER_BYTES: usize = 4096;
    const ROUTE_OUTPUT_BUFFER_BYTES: usize = 4096;
    const UNFOLD_ITERATIONS_MAX: usize = 256;
    const NERVE_OUTPUT_BYTES_MAX: usize = 4096;
    const CHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize = 4096;
    const HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
    const COCHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize = 4096;
    const COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
    const POSTNIKOV_TOWER_OUTPUT_BYTES_MAX: usize = 4096;
    const HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX: usize = 4096;
    const K_INVARIANTS_OUTPUT_BYTES_MAX: usize = 4096;
}