uor-foundation 0.1.3

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
// @generated by uor-crate from uor-ontology — do not edit manually

//! Shared enumerations derived from the UOR Foundation ontology.

use core::fmt;

/// Kernel/user/bridge classification for each namespace module.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Space {
    /// Immutable kernel-space: compiled into ROM.
    Kernel,
    /// Parameterizable user-space: runtime declarations.
    User,
    /// Bridge: kernel-computed, user-consumed.
    Bridge,
}

impl fmt::Display for Space {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Kernel => f.write_str("kernel"),
            Self::User => f.write_str("user"),
            Self::Bridge => f.write_str("bridge"),
        }
    }
}

/// The 10 primitive operations defined in the UOR Foundation.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PrimitiveOp {
    /// Ring reflection: neg(x) = (-x) mod 2^n. One of the two generators of the dihedral group D_{2^n}. neg(neg(x)) = x (involution property).
    Neg,
    /// Hypercube reflection: bnot(x) = (2^n - 1) ⊕ x (bitwise complement). The second generator of D_{2^n}. bnot(bnot(x)) = x.
    Bnot,
    /// Successor: succ(x) = neg(bnot(x)) = (x + 1) mod 2^n. The critical identity: succ is the composition neg ∘ bnot.
    Succ,
    /// Predecessor: pred(x) = bnot(neg(x)) = (x - 1) mod 2^n. The inverse of succ. pred is the composition bnot ∘ neg.
    Pred,
    /// Ring addition: add(x, y) = (x + y) mod 2^n. Commutative, associative; identity element is 0.
    Add,
    /// Ring subtraction: sub(x, y) = (x - y) mod 2^n. Not commutative, not associative.
    Sub,
    /// Ring multiplication: mul(x, y) = (x × y) mod 2^n. Commutative, associative; identity element is 1.
    Mul,
    /// Bitwise exclusive or: xor(x, y) = x ⊕ y. Commutative, associative; identity element is 0.
    Xor,
    /// Bitwise and: and(x, y) = x ∧ y. Commutative, associative.
    And,
    /// Bitwise or: or(x, y) = x ∨ y. Commutative, associative.
    Or,
}

impl fmt::Display for PrimitiveOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Neg => f.write_str("neg"),
            Self::Bnot => f.write_str("bnot"),
            Self::Succ => f.write_str("succ"),
            Self::Pred => f.write_str("pred"),
            Self::Add => f.write_str("add"),
            Self::Sub => f.write_str("sub"),
            Self::Mul => f.write_str("mul"),
            Self::Xor => f.write_str("xor"),
            Self::And => f.write_str("and"),
            Self::Or => f.write_str("or"),
        }
    }
}

/// The three metric axes in the UOR tri-metric classification.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MetricAxis {
    /// The vertical (ring/additive) metric axis. Constraints on this axis operate through ring arithmetic: residue classes, divisibility, and additive structure.
    Vertical,
    /// The horizontal (Hamming/bitwise) metric axis. Constraints on this axis operate through bitwise structure: carry patterns, bit positions, and Hamming distance.
    Horizontal,
    /// The diagonal (incompatibility) metric axis. Constraints on this axis measure the gap between ring and Hamming metrics — the curvature of UOR geometry.
    Diagonal,
}

impl fmt::Display for MetricAxis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Vertical => f.write_str("vertical"),
            Self::Horizontal => f.write_str("horizontal"),
            Self::Diagonal => f.write_str("diagonal"),
        }
    }
}

/// The state of a fiber coordinate: pinned or free.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FiberState {
    /// Fiber is determined by a constraint.
    Pinned,
    /// Fiber is still available for refinement.
    Free,
}

impl fmt::Display for FiberState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pinned => f.write_str("pinned"),
            Self::Free => f.write_str("free"),
        }
    }
}

/// The geometric character of an operation.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GeometricCharacter {
    /// Reflection through the origin of the additive ring: neg(x) = -x mod 2^n. One of the two generators of D_{2^n}.
    RingReflection,
    /// Reflection through the centre of the hypercube: bnot(x) = (2^n-1) ⊕ x. The second generator of D_{2^n}.
    HypercubeReflection,
    /// Rotation by one step: succ(x) = (x+1) mod 2^n. The composition of the two reflections.
    Rotation,
    /// Rotation by one step in the reverse direction: pred(x) = (x-1) mod 2^n.
    RotationInverse,
    /// Translation along the ring axis: add(x,y), sub(x,y). Preserves Hamming distance locally.
    Translation,
    /// Scaling along the ring axis: mul(x,y) = (x×y) mod 2^n.
    Scaling,
    /// Translation along the hypercube axis: xor(x,y) = x ⊕ y. Preserves ring distance locally.
    HypercubeTranslation,
    /// Projection onto a hypercube face: and(x,y) = x ∧ y. Idempotent; collapses dimensions.
    HypercubeProjection,
    /// Join on the hypercube lattice: or(x,y) = x ∨ y. Idempotent; dual to projection.
    HypercubeJoin,
    /// Geometric character of dispatch: constraint-guided selection over the resolver registry lattice.
    ConstraintSelection,
    /// Geometric character of inference: traversal through the φ-pipeline resolution graph P ∘ Π ∘ G.
    ResolutionTraversal,
    /// Geometric character of accumulation: progressive pinning of fiber states in the context lattice.
    FiberPinning,
    /// Geometric character of lease partition: splitting a shared context into disjoint fiber-set leases.
    FiberPartition,
    /// Geometric character of session composition: merging disjoint lease sessions into a unified resolution context.
    SessionMerge,
}

impl fmt::Display for GeometricCharacter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RingReflection => f.write_str("ring_reflection"),
            Self::HypercubeReflection => f.write_str("hypercube_reflection"),
            Self::Rotation => f.write_str("rotation"),
            Self::RotationInverse => f.write_str("rotation_inverse"),
            Self::Translation => f.write_str("translation"),
            Self::Scaling => f.write_str("scaling"),
            Self::HypercubeTranslation => f.write_str("hypercube_translation"),
            Self::HypercubeProjection => f.write_str("hypercube_projection"),
            Self::HypercubeJoin => f.write_str("hypercube_join"),
            Self::ConstraintSelection => f.write_str("constraint_selection"),
            Self::ResolutionTraversal => f.write_str("resolution_traversal"),
            Self::FiberPinning => f.write_str("fiber_pinning"),
            Self::FiberPartition => f.write_str("fiber_partition"),
            Self::SessionMerge => f.write_str("session_merge"),
        }
    }
}

/// The mathematical domain in which an identity is established.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VerificationDomain {
    /// Established by exhaustive traversal of R_n. Valid for all identities where the ring is finite.
    Enumerative,
    /// Established by equational reasoning from ring or group axioms. Covers derivations via associativity, commutativity, inverse laws, and group presentations.
    Algebraic,
    /// Established by isometry, symmetry, or GeometricCharacter arguments. Covers dihedral actions, fixed-point analysis, automorphism groups, and affine embeddings.
    Geometric,
    /// Established via discrete differential calculus or metric analysis. Covers ring/Hamming derivatives (DC_), metric divergence (AM_), and adiabatic scheduling (AR_).
    Analytical,
    /// Established via entropy, Landauer bounds, or Boltzmann distributions. Covers fiber entropy (TH_), reversible computation (RC_), and phase transitions.
    Thermodynamic,
    /// Established via simplicial homology, cohomology, or constraint nerve analysis. Covers homological algebra (HA_) and ψ-pipeline identities.
    Topological,
    /// Established by the inter-algebra map structure of the resolution pipeline. Covers φ-maps (phi_1–phi_6) and ψ-maps (psi_1–psi_6).
    Pipeline,
    /// Established by the composition of Analytical and Topological reasoning. The only domain requiring multiple op:verificationDomain assertions. Covers the UOR Index Theorem (IT_7a–IT_7d).
    IndexTheoretic,
    /// Established by superposition analysis of fiber states. Covers identities involving superposed (non-classical) fiber assignments where fibers carry complex amplitudes.
    SuperpositionDomain,
    /// Established by the intersection of quantum superposition analysis and classical thermodynamic reasoning. Covers identities relating von Neumann entropy of superposed states to Landauer costs of projective collapse (QM_).
    QuantumThermodynamic,
    /// Established by number-theoretic valuation arguments including p-adic absolute values, the Ostrowski product formula, and the arithmetic of global fields. Covers identities grounded in the product formula |x|_p · |x|_∞ = 1 and the Witt–Ostrowski derivation chain.
    ArithmeticValuation,
    /// Verification domain for composed operation identities — algebraic properties of operator compositions including dispatch, inference, accumulation, lease, and session composition operations.
    ComposedAlgebraic,
}

impl fmt::Display for VerificationDomain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Enumerative => f.write_str("enumerative"),
            Self::Algebraic => f.write_str("algebraic"),
            Self::Geometric => f.write_str("geometric"),
            Self::Analytical => f.write_str("analytical"),
            Self::Thermodynamic => f.write_str("thermodynamic"),
            Self::Topological => f.write_str("topological"),
            Self::Pipeline => f.write_str("pipeline"),
            Self::IndexTheoretic => f.write_str("index_theoretic"),
            Self::SuperpositionDomain => f.write_str("superposition_domain"),
            Self::QuantumThermodynamic => f.write_str("quantum_thermodynamic"),
            Self::ArithmeticValuation => f.write_str("arithmetic_valuation"),
            Self::ComposedAlgebraic => f.write_str("composed_algebraic"),
        }
    }
}

/// The computational complexity classification of a resolver.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ComplexityClass {
    /// O(1) complexity — the resolver runs in constant time regardless of ring size.
    Constant,
    /// O(log n) complexity — the resolver runs in logarithmic time in the quantum level.
    Logarithmic,
    /// O(n) complexity — the resolver runs in time linear in the quantum level.
    Linear,
    /// O(2^n) complexity — the resolver runs in time exponential in the quantum level.
    Exponential,
}

impl fmt::Display for ComplexityClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Constant => f.write_str("constant"),
            Self::Logarithmic => f.write_str("logarithmic"),
            Self::Linear => f.write_str("linear"),
            Self::Exponential => f.write_str("exponential"),
        }
    }
}

/// A named rewrite rule used in term rewriting derivations.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RewriteRule {
    /// The rewrite rule applying the critical identity: neg(bnot(x)) → succ(x). Grounded in op:criticalIdentity.
    CriticalIdentity,
    /// The rewrite rule applying involution cancellation: f(f(x)) → x for any involution f.
    Involution,
    /// The rewrite rule applying associativity to re-bracket nested binary operations.
    Associativity,
    /// The rewrite rule applying commutativity to reorder operands of commutative operations.
    Commutativity,
    /// The rewrite rule eliminating identity elements: add(x, 0) → x, mul(x, 1) → x, xor(x, 0) → x.
    IdentityElement,
    /// The rewrite rule normalizing compound expressions to canonical ordering (e.g., sorting operands by address).
    Normalization,
}

impl fmt::Display for RewriteRule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CriticalIdentity => f.write_str("critical_identity"),
            Self::Involution => f.write_str("involution"),
            Self::Associativity => f.write_str("associativity"),
            Self::Commutativity => f.write_str("commutativity"),
            Self::IdentityElement => f.write_str("identity_element"),
            Self::Normalization => f.write_str("normalization"),
        }
    }
}

/// A unit of measurement for observable quantities.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MeasurementUnit {
    /// Information-theoretic unit: the measurement is in bits (e.g., Hamming weight, entropy).
    Bits,
    /// Ring-arithmetic unit: the measurement is in ring distance steps (|x - y| mod 2^n).
    RingSteps,
    /// Dimensionless unit: the measurement is a pure number (e.g., winding number, Betti number, spectral gap).
    Dimensionless,
    /// Natural information unit: entropy measured in nats (using natural logarithm). S_residual is expressed in nats when computed as (Σ κ_k − χ) × ln 2.
    Nats,
}

impl fmt::Display for MeasurementUnit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bits => f.write_str("bits"),
            Self::RingSteps => f.write_str("ring_steps"),
            Self::Dimensionless => f.write_str("dimensionless"),
            Self::Nats => f.write_str("nats"),
        }
    }
}

/// A classification of coordinate types for coordinate queries.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CoordinateKind {
    /// The stratum coordinate: the layer position of a datum within the ring's stratification.
    Stratum,
    /// The spectrum coordinate: the spectral decomposition of a datum under the ring's Fourier analysis.
    Spectrum,
    /// The address coordinate: the content-addressable position of a datum in the Braille glyph encoding.
    Address,
}

impl fmt::Display for CoordinateKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stratum => f.write_str("stratum"),
            Self::Spectrum => f.write_str("spectrum"),
            Self::Address => f.write_str("address"),
        }
    }
}

/// The reason type for a session context-reset boundary.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SessionBoundaryType {
    /// The caller explicitly requested a context reset. All accumulated bindings are discarded.
    ExplicitReset,
    /// The session resolver determined that no further queries can reduce the aggregate fiber deficit.
    ConvergenceBoundary,
    /// A new query produced a type contradiction with an accumulated binding. Context must reset before resolution can continue.
    ContradictionBoundary,
}

impl fmt::Display for SessionBoundaryType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ExplicitReset => f.write_str("explicit_reset"),
            Self::ConvergenceBoundary => f.write_str("convergence_boundary"),
            Self::ContradictionBoundary => f.write_str("contradiction_boundary"),
        }
    }
}

/// A classification of phase boundary in the catastrophe diagram.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PhaseBoundaryType {
    /// A phase boundary where g divides 2^n − 1, meaning g is a period of the multiplicative structure of R_n.
    Period,
    /// A phase boundary where g = 2^k, meaning g aligns with the binary stratification of R_n.
    PowerOfTwo,
}

impl fmt::Display for PhaseBoundaryType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Period => f.write_str("period"),
            Self::PowerOfTwo => f.write_str("power_of_two"),
        }
    }
}

/// The phase of context saturation towards the ground state.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SaturationPhase {
    /// The context has σ = 0: no bindings accumulated, all fibers are free. The initial phase of every session.
    Unsaturated,
    /// The context has 0 < σ < 1: some fibers are pinned by accumulated bindings, but free fibers remain. The accumulation phase.
    PartialSaturation,
    /// The context has σ = 1: all fibers are pinned, freeCount = 0. The ground state. All subsequent queries resolve in O(1) via SC_5.
    FullSaturation,
}

impl fmt::Display for SaturationPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsaturated => f.write_str("unsaturated"),
            Self::PartialSaturation => f.write_str("partial_saturation"),
            Self::FullSaturation => f.write_str("full_saturation"),
        }
    }
}

/// Whether a signature is achievable or forbidden in the morphospace.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AchievabilityStatus {
    /// The signature has been empirically verified as achievable at some quantum level by an EmpiricalVerification record.
    Achievable,
    /// The signature has been formally proven impossible by an ImpossibilityWitness deriving from MS_1, MS_2, or other impossibility theorems.
    Forbidden,
}

impl fmt::Display for AchievabilityStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Achievable => f.write_str("achievable"),
            Self::Forbidden => f.write_str("forbidden"),
        }
    }
}

/// The scope of validity for an identity across quantum levels.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ValidityScopeKind {
    /// Holds for all k in N. No minimum k constraint.
    Universal,
    /// Holds for all k >= k_min, where k_min is given by validKMin.
    ParametricLower,
    /// Holds for k_min <= k <= k_max. Both validKMin and validKMax required.
    ParametricRange,
    /// Holds only at exactly one level, given by a QuantumLevelBinding.
    LevelSpecific,
}

impl fmt::Display for ValidityScopeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Universal => f.write_str("universal"),
            Self::ParametricLower => f.write_str("parametric_lower"),
            Self::ParametricRange => f.write_str("parametric_range"),
            Self::LevelSpecific => f.write_str("level_specific"),
        }
    }
}

/// A typed controlled vocabulary for ExecutionPolicy scheduling strategies.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ExecutionPolicyKind {
    /// Process queries in arrival order. The implicit pre-Amendment 48 behavior.
    FifoPolicy,
    /// Process the query with the smallest targetFiber.freeCount first. Favors cheapest resolutions, accelerating early saturation gain.
    MinFreeCountFirst,
    /// Process the query with the largest targetFiber.freeCount first. Favors hardest resolutions, maximizing information gain per step.
    MaxFreeCountFirst,
    /// Process queries whose targetFiber is disjoint from all other pending queries' fiber sets first. Minimizes contention when operating against a SharedContext.
    DisjointFirst,
}

impl fmt::Display for ExecutionPolicyKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FifoPolicy => f.write_str("fifo_policy"),
            Self::MinFreeCountFirst => f.write_str("min_free_count_first"),
            Self::MaxFreeCountFirst => f.write_str("max_free_count_first"),
            Self::DisjointFirst => f.write_str("disjoint_first"),
        }
    }
}

/// The variance of a structural type position under operad composition.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VarianceAnnotation {
    /// The structural position preserves TypeInclusion: if T₁ ≤ T₂, then F(T₁) ≤ F(T₂).
    Covariant,
    /// The structural position reverses TypeInclusion: if T₁ ≤ T₂, then F(T₂) ≤ F(T₁).
    Contravariant,
    /// The structural position requires exact type equality: F(T₁) ≤ F(T₂) only if T₁ = T₂.
    Invariant,
    /// The structural position ignores the type parameter: F(T₁) ≤ F(T₂) for all T₁, T₂.
    Bivariant,
}

impl fmt::Display for VarianceAnnotation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Covariant => f.write_str("covariant"),
            Self::Contravariant => f.write_str("contravariant"),
            Self::Invariant => f.write_str("invariant"),
            Self::Bivariant => f.write_str("bivariant"),
        }
    }
}

/// The modality of a proof: computation (exhaustive verification at a specific quantum level) or axiomatic (derivation from ring axioms).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ProofModality {
    /// A proof confirmed by exhaustive execution over R_n at a specific quantum level.
    Computation,
    /// A proof derived from ring axioms that holds at all quantum levels.
    Axiomatic,
    /// A proof verified empirically across a bounded range of quantum levels.
    Empirical,
    /// A proof by structural induction on the quantum level parameter k.
    Inductive,
}

impl fmt::Display for ProofModality {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Computation => f.write_str("computation"),
            Self::Axiomatic => f.write_str("axiomatic"),
            Self::Empirical => f.write_str("empirical"),
            Self::Inductive => f.write_str("inductive"),
        }
    }
}

/// A quantum level Q_k at which the UOR ring R_k = Z/2^(8*(k+1))Z operates.
/// Corresponds to `schema:QuantumLevel` in the uor.foundation ontology.
/// The class is open: any non-negative integer k identifies a valid level.
/// Named levels Q0 through Q3 are provided as associated constants.
/// Arbitrary levels can be constructed with `QuantumLevel::new(k)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct QuantumLevel {
    /// The quantum index k in Q_k. Maps to `schema:quantumIndex`.
    index: u32,
}

impl QuantumLevel {
    /// Quantum level 0: 8-bit ring Z/256Z, 256 states. The reference level for all ComputationCertificate proofs in the spec.
    pub const Q0: Self = Self { index: 0 };
    /// Quantum level 1: 16-bit ring Z/65536Z, 65,536 states.
    pub const Q1: Self = Self { index: 1 };
    /// Quantum level 2: 24-bit ring Z/16777216Z, 16,777,216 states.
    pub const Q2: Self = Self { index: 2 };
    /// Quantum level 3: 32-bit ring Z/4294967296Z, 4,294,967,296 states. The highest named level in the spec.
    pub const Q3: Self = Self { index: 3 };

    /// Construct an arbitrary quantum level Q_k. `k` need not be one of the spec-named individuals; Prism implementations may use any level.
    #[inline]
    pub const fn new(index: u32) -> Self {
        Self { index }
    }

    /// The quantum index k. Maps to `schema:quantumIndex`.
    #[inline]
    pub const fn index(self) -> u32 {
        self.index
    }

    /// Bit width of the ring at this level: 8*(k+1). Maps to `schema:bitsWidth`. This is a derived property, not a stored field — the formula is definitional.
    #[inline]
    pub const fn bits_width(self) -> u32 {
        8 * (self.index + 1)
    }

    /// Number of distinct ring states at this level: 2^(8*(k+1)). Maps to `schema:cycleSize`. Returns `None` if the result exceeds `u128` (i.e. for k >= 15).
    #[inline]
    pub const fn cycle_size(self) -> Option<u128> {
        1u128.checked_shl(self.bits_width())
    }

    /// The next quantum level in the chain: Q_k -> Q_{k+1}. Maps to `schema:nextLevel`. Always well-defined; the chain is unbounded.
    #[inline]
    pub const fn next_level(self) -> Self {
        Self {
            index: self.index + 1,
        }
    }
}

impl fmt::Display for QuantumLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "q{}", self.index)
    }
}