Skip to main content

qualia_core_db/render/
entity_compile_gates.rs

1//! Deterministic Validation Gates & TAA Oklab Clamping for `qualia-cli entity-compile`.
2//!
3//! Enforces the compilation gates before sealing `.10d` living containers
4//! and packaging into `.hmc` bundles:
5//!
6//! - **Gate 1: Spectral Plausibility & Energy Conservation** ($R(\lambda) \in [0.0, 1.0]$ across 380–780 nm).
7//! - **Gate 2: Virtualized Geometry Confinement** (Tier 2/3/4 strictly bounded inside Tier 1 AABB).
8//! - **Gate 3: Ontological & Anti-Commodification Integrity** (Valid ontological class, anti-slavery /
9//!   inalienable human rights protection preventing `NaturalPerson` from being commodified as an asset).
10//! - **Gate 4: Wasm/VibeScript Determinism Limits** (Zero non-deterministic host calls, cycle count budget).
11//!
12//! Also provides perceptual **Oklab Neighborhood Clamping** for Temporal Anti-Aliasing (TAA)
13//! across blue-noise hero wavelength packets.
14
15use crate::render::spectral_basis::{
16    evaluate_spectral_reflectance, JakobHanikaCoeffs, LAMBDA_MIN_NM,
17};
18
19/// First-class ontological categories determining entity representation and rights.
20#[repr(u8)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum OntologicalClass {
23    /// Living organism or evolutionary species (plants, animals, fungi) -> Specimen.
24    DarwinianTaxon = 1,
25    /// Fabricated machinery, tools, vehicles, infrastructure -> Construct / Manufactured Property.
26    ManufacturedProperty = 2,
27    /// Authored cultural expressions, stories, music, art -> Creative Work / Expression.
28    LiberalArtsWork = 3,
29    /// Geological formations, water catchments, abiotic features -> Terrain / Feature.
30    AbioticEnvironment = 4,
31    /// Human subject with inalienable sovereignty -> Persona / Likeness (CANNOT be owned as an asset).
32    NaturalPerson = 5,
33}
34
35impl OntologicalClass {
36    /// Decodes from u8.
37    pub fn from_u8(tag: u8) -> Option<Self> {
38        match tag {
39            1 => Some(Self::DarwinianTaxon),
40            2 => Some(Self::ManufacturedProperty),
41            3 => Some(Self::LiberalArtsWork),
42            4 => Some(Self::AbioticEnvironment),
43            5 => Some(Self::NaturalPerson),
44            _ => None,
45        }
46    }
47
48    /// Builds `OntologicalClass` from `str_name`.
49    pub fn from_str_name(name: &str) -> Option<Self> {
50        match name.to_lowercase().as_str() {
51            "darwiniantaxon" | "taxon" | "specimen" | "species" | "flora" | "fauna" => {
52                Some(Self::DarwinianTaxon)
53            }
54            "manufacturedproperty" | "property" | "construct" | "machine" | "tool" | "asset" => {
55                Some(Self::ManufacturedProperty)
56            }
57            "liberalartswork" | "cultural" | "work" | "expression" | "lore" => {
58                Some(Self::LiberalArtsWork)
59            }
60            "abioticenvironment" | "environment" | "terrain" | "feature" | "geology" => {
61                Some(Self::AbioticEnvironment)
62            }
63            "naturalperson" | "person" | "persona" | "likeness" | "human" => {
64                Some(Self::NaturalPerson)
65            }
66            _ => None,
67        }
68    }
69
70    /// English noun describing the sensory embodiment in accordance with its ontological realm.
71    pub fn embodiment_term(&self) -> &'static str {
72        match self {
73            Self::DarwinianTaxon => "Specimen",
74            Self::ManufacturedProperty => "Construct",
75            Self::LiberalArtsWork => "Expression",
76            Self::AbioticEnvironment => "Terrain",
77            Self::NaturalPerson => "Persona",
78        }
79    }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum GateError {
84    /// Spectral reflectance violates physical bounds [0.0, 1.0].
85    SpectralEnergyViolation { lambda_nm: u32, reflectance: u32 },
86    /// BSSRDF mean free path contains zero or negative values.
87    BssrdfZeroOrNegative,
88    /// Tier 2/3/4 bounds spill outside Tier 1 Hero AABB.
89    GeometryBoundsViolation,
90    /// Impostor bounding sphere misaligned with mesh geometry.
91    ImpostorSphereMisaligned,
92    /// Malformed or unrecognized ontological class.
93    MalformedOntologicalClass,
94    /// Missing mandatory physical constants (e.g., mass for manufactured machinery).
95    MissingPhysicalConstants,
96    /// Attempting to commodify or classify a NaturalPerson as ManufacturedProperty or CommercialAsset.
97    HumanPersonCannotBeCommodifiedAsAsset,
98    /// Affordance script exceeds cycle budget or calls non-deterministic host APIs.
99    NonDeterministicScriptExecution,
100    /// Living biosphere ("world of god") entities must be licensed under Permissive Commons or Social Permissive Commons.
101    BiosphereRequiresPermissiveCommons,
102    /// Living biosphere entities cannot be associated with perpetual royalty fees.
103    BiosphereCannotHavePerpetualFees,
104}
105
106impl core::fmt::Display for GateError {
107    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108        match self {
109            Self::SpectralEnergyViolation {
110                lambda_nm,
111                reflectance,
112            } => {
113                write!(
114                    f,
115                    "spectral energy violation at {lambda_nm} nm: reflectance {reflectance}"
116                )
117            }
118            Self::BssrdfZeroOrNegative => {
119                write!(f, "BSSRDF mean free path must be strictly positive")
120            }
121            Self::GeometryBoundsViolation => {
122                write!(f, "lower-tier geometry spills outside Tier 1 Hero AABB")
123            }
124            Self::ImpostorSphereMisaligned => {
125                write!(f, "impostor bounding sphere misaligned with geometry")
126            }
127            Self::MalformedOntologicalClass => write!(f, "malformed or missing ontological class"),
128            Self::MissingPhysicalConstants => write!(f, "missing mandatory physical constants"),
129            Self::HumanPersonCannotBeCommodifiedAsAsset => {
130                write!(f, "anti-commodification violation: a NaturalPerson cannot be classified as property or an asset")
131            }
132            Self::NonDeterministicScriptExecution => {
133                write!(f, "script violates determinism or cycle limits")
134            }
135            Self::BiosphereRequiresPermissiveCommons => {
136                write!(f, "humanitarian ict gate violation: living biosphere entity must be governed under Permissive Commons")
137            }
138            Self::BiosphereCannotHavePerpetualFees => {
139                write!(f, "humanitarian ict gate violation: living biosphere entity cannot be encumbered with perpetual fees")
140            }
141        }
142    }
143}
144
145impl std::error::Error for GateError {}
146
147// ───────────────────────────────────────────────────────────────────────────
148//  Gate 1: Spectral Plausibility & Energy Conservation
149// ───────────────────────────────────────────────────────────────────────────
150
151/// Assert that spectral coefficients evaluate strictly within physical bounds $R(\lambda) \in [0.0, 1.0]$.
152pub fn validate_spectral_coeffs(coeffs: &JakobHanikaCoeffs) -> Result<(), GateError> {
153    for lambda_step in 0..=40 {
154        let lambda_nm = LAMBDA_MIN_NM + (lambda_step as f32) * 10.0;
155        let r = evaluate_spectral_reflectance(coeffs, lambda_nm);
156        if r < -1e-6 || r > 1.00001 {
157            return Err(GateError::SpectralEnergyViolation {
158                lambda_nm: lambda_nm as u32,
159                reflectance: (r * 1000.0) as u32,
160            });
161        }
162    }
163    Ok(())
164}
165
166/// Assert that Subsurface Scattering mean free paths are strictly positive (prevents division by zero).
167pub fn validate_bssrdf_parameters(mean_free_path_mm: [f32; 4]) -> Result<(), GateError> {
168    for &ld in &mean_free_path_mm {
169        if ld <= 1e-5 || !ld.is_finite() {
170            return Err(GateError::BssrdfZeroOrNegative);
171        }
172    }
173    Ok(())
174}
175
176// ───────────────────────────────────────────────────────────────────────────
177//  Gate 2: Virtualized Geometry Confinement
178// ───────────────────────────────────────────────────────────────────────────
179
180/// Assert that lower-tier primitives (LODs, surfels) remain strictly bounded inside Tier 1 Hero AABB.
181pub fn validate_geometry_confinement(
182    hero_min: [f32; 3],
183    hero_max: [f32; 3],
184    child_min: [f32; 3],
185    child_max: [f32; 3],
186    sphere_center: [f32; 3],
187    sphere_radius: f32,
188) -> Result<(), GateError> {
189    const EPSILON: f32 = 0.05; // 5 cm margin for decimation drift
190
191    for i in 0..3 {
192        if child_min[i] < hero_min[i] - EPSILON || child_max[i] > hero_max[i] + EPSILON {
193            return Err(GateError::GeometryBoundsViolation);
194        }
195    }
196
197    // Verify impostor sphere encompasses the hero AABB center
198    let aabb_center = [
199        (hero_min[0] + hero_max[0]) * 0.5,
200        (hero_min[1] + hero_max[1]) * 0.5,
201        (hero_min[2] + hero_max[2]) * 0.5,
202    ];
203    let dist_sq = (aabb_center[0] - sphere_center[0]).powi(2)
204        + (aabb_center[1] - sphere_center[1]).powi(2)
205        + (aabb_center[2] - sphere_center[2]).powi(2);
206
207    if dist_sq > (sphere_radius * 0.25).powi(2) {
208        return Err(GateError::ImpostorSphereMisaligned);
209    }
210
211    Ok(())
212}
213
214// ───────────────────────────────────────────────────────────────────────────
215//  Gate 3 & 4: Ontological Integrity & Anti-Commodification Gate
216// ───────────────────────────────────────────────────────────────────────────
217
218/// Assert valid ontological classification and enforce anti-commodification human rights.
219pub fn validate_ontological_integrity(
220    origin_tag: u8,
221    mass_kg: Option<f32>,
222) -> Result<(), GateError> {
223    match OntologicalClass::from_u8(origin_tag) {
224        Some(OntologicalClass::DarwinianTaxon) => Ok(()), // Biological life / species specimen
225        Some(OntologicalClass::ManufacturedProperty) => {
226            // ManufacturedProperty requires finite mass
227            if let Some(m) = mass_kg {
228                if m > 0.0 && m.is_finite() {
229                    Ok(())
230                } else {
231                    Err(GateError::MissingPhysicalConstants)
232                }
233            } else {
234                Err(GateError::MissingPhysicalConstants)
235            }
236        }
237        Some(OntologicalClass::LiberalArtsWork) => Ok(()), // Expressive cultural composition
238        Some(OntologicalClass::AbioticEnvironment) => Ok(()), // Terrain / environmental commons
239        Some(OntologicalClass::NaturalPerson) => Ok(()),   // Sovereign human subject (Persona)
240        None => Err(GateError::MalformedOntologicalClass),
241    }
242}
243
244/// Explicit assertion protecting natural persons from being classified as manufactured property.
245pub fn assert_person_anti_commodification(
246    entity_class: OntologicalClass,
247    as_property: bool,
248) -> Result<(), GateError> {
249    if entity_class == OntologicalClass::NaturalPerson && as_property {
250        Err(GateError::HumanPersonCannotBeCommodifiedAsAsset)
251    } else {
252        Ok(())
253    }
254}
255
256/// Assert that living biosphere entities ("world of god") and fundamental knowledge for life
257/// are governed by Permissive Commons, preventing enclosure, perpetual royalties, and private monopolization.
258///
259/// NOTE: Commercial goods (`ManufacturedProperty`) are intentionally unconstrained: commercial vendors
260/// (e.g. Nike, toolmakers, device manufacturers) retain commercial rights to set prices and terms.
261/// Consumers have a right to fundamental bodily needs (shoes to walk, shelter, clothing), but not
262/// an entitlement to a specific commercial brand design. In contrast, living species and knowledge
263/// needed for life/freedom of thought belong to the inalienable permissive commons.
264pub fn assert_biosphere_permissive_commons(
265    entity_class: OntologicalClass,
266    licence_tag: &str,
267    has_perpetual_royalties: bool,
268) -> Result<(), GateError> {
269    match entity_class {
270        OntologicalClass::DarwinianTaxon | OntologicalClass::AbioticEnvironment => {
271            if has_perpetual_royalties {
272                return Err(GateError::BiosphereCannotHavePerpetualFees);
273            }
274            let lic = crate::q42::asset_envelope::LicenceClass::parse(licence_tag);
275            match lic {
276                crate::q42::asset_envelope::LicenceClass::Cc0
277                | crate::q42::asset_envelope::LicenceClass::CcBy
278                | crate::q42::asset_envelope::LicenceClass::CcBySa
279                | crate::q42::asset_envelope::LicenceClass::SocialPermissiveCommons => Ok(()),
280                _ => Err(GateError::BiosphereRequiresPermissiveCommons),
281            }
282        }
283        _ => Ok(()),
284    }
285}
286
287/// Assert affordance Wasm script determinism.
288pub fn validate_script_determinism(
289    instruction_count: u64,
290    has_unauthorized_host_calls: bool,
291) -> Result<(), GateError> {
292    const MAX_INSTRUCTION_BUDGET: u64 = 1_000_000;
293    if has_unauthorized_host_calls || instruction_count > MAX_INSTRUCTION_BUDGET {
294        return Err(GateError::NonDeterministicScriptExecution);
295    }
296    Ok(())
297}
298
299// ───────────────────────────────────────────────────────────────────────────
300//  Temporal Anti-Aliasing (TAA) Oklab Perceptual Clamping
301// ───────────────────────────────────────────────────────────────────────────
302
303/// Transform linear CIE XYZ to Oklab perceptual color space. Zero heap.
304#[inline]
305pub fn xyz_to_oklab(xyz: [f32; 3]) -> [f32; 3] {
306    let l = 0.818_933 * xyz[0] + 0.361_866_74 * xyz[1] - 0.128_859_71 * xyz[2];
307    let m = 0.032_984_544 * xyz[0] + 0.929_311_9 * xyz[1] + 0.036_145_64 * xyz[2];
308    let s = 0.048_200_3 * xyz[0] + 0.264_366_27 * xyz[1] + 0.633_851_7 * xyz[2];
309
310    let l_ = if l > 0.0 { l.cbrt() } else { 0.0 };
311    let m_ = if m > 0.0 { m.cbrt() } else { 0.0 };
312    let s_ = if s > 0.0 { s.cbrt() } else { 0.0 };
313
314    let l_oklab = 0.210_454_26 * l_ + 0.793_617_8 * m_ - 0.004_072_047 * s_;
315    let a_oklab = 1.977_998_5 * l_ - 2.428_592_2 * m_ + 0.450_593_7 * s_;
316    let b_oklab = 0.025_904_037 * l_ + 0.782_771_77 * m_ - 0.808_675_77 * s_;
317
318    [l_oklab, a_oklab, b_oklab]
319}
320
321/// Transform Oklab perceptual color space back to linear CIE XYZ. Zero heap.
322#[inline]
323pub fn oklab_to_xyz(oklab: [f32; 3]) -> [f32; 3] {
324    let l_ = oklab[0] + 0.396_337_78 * oklab[1] + 0.215_803_76 * oklab[2];
325    let m_ = oklab[0] - 0.105_561_346 * oklab[1] - 0.063_854_17 * oklab[2];
326    let s_ = oklab[0] - 0.089_484_18 * oklab[1] - 1.291_485_5 * oklab[2];
327
328    let l = l_ * l_ * l_;
329    let m = m_ * m_ * m_;
330    let s = s_ * s_ * s_;
331
332    let x = 1.227_013_8 * l - 0.557_797_7 * m + 0.281_256_15 * s;
333    let y = -0.040_580_18 * l + 1.112_256_9 * m - 0.071_676_68 * s;
334    let z = -0.076_381_284 * l - 0.421_481_98 * m + 1.586_163_2 * s;
335
336    [x, y, z]
337}
338
339/// Clamps the reprojected TAA history color to the variance bounding box
340/// of the 3x3 local neighborhood in Oklab space. Zero heap.
341#[inline]
342pub fn clamp_taa_history_oklab(
343    history_xyz: [f32; 3],
344    neighborhood_3x3_xyz: &[[f32; 3]; 9],
345    gamma: f32, // Variance clipping scale, typically 1.0 .. 1.25
346) -> [f32; 3] {
347    let mut mean = [0.0f32; 3];
348    let mut m2 = [0.0f32; 3];
349
350    for s in neighborhood_3x3_xyz.iter() {
351        let lab = xyz_to_oklab(*s);
352        for c in 0..3 {
353            mean[c] += lab[c];
354            m2[c] += lab[c] * lab[c];
355        }
356    }
357
358    let inv_9 = 1.0 / 9.0;
359    for c in 0..3 {
360        mean[c] *= inv_9;
361        m2[c] *= inv_9;
362    }
363
364    let mut min_bound = [0.0f32; 3];
365    let mut max_bound = [0.0f32; 3];
366    for c in 0..3 {
367        let variance = (m2[c] - mean[c] * mean[c]).max(0.0);
368        let std_dev = variance.sqrt();
369        min_bound[c] = mean[c] - gamma * std_dev;
370        max_bound[c] = mean[c] + gamma * std_dev;
371    }
372
373    let mut hist_lab = xyz_to_oklab(history_xyz);
374    for c in 0..3 {
375        hist_lab[c] = hist_lab[c].clamp(min_bound[c], max_bound[c]);
376    }
377
378    oklab_to_xyz(hist_lab)
379}
380
381/// Velocity-ramped dynamic TAA blend factor alpha in [0.05, 0.20].
382#[inline]
383pub fn calculate_taa_blend_factor(screen_velocity_pixels: f32) -> f32 {
384    const ALPHA_STATIC: f32 = 0.05;
385    const ALPHA_DYNAMIC_MAX: f32 = 0.20;
386    const VELOCITY_RAMP_PIXELS: f32 = 4.0;
387
388    let t = (screen_velocity_pixels / VELOCITY_RAMP_PIXELS).clamp(0.0, 1.0);
389    ALPHA_STATIC + t * (ALPHA_DYNAMIC_MAX - ALPHA_STATIC)
390}
391
392/// Check relative depth disocclusion gate.
393#[inline]
394pub fn is_taa_history_disoccluded(current_linear_depth: f32, history_linear_depth: f32) -> bool {
395    const DEPTH_THRESHOLD_RATIO: f32 = 0.05; // 5% depth difference trigger
396    let diff = (current_linear_depth - history_linear_depth).abs();
397    diff > (current_linear_depth * DEPTH_THRESHOLD_RATIO)
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn anti_commodification_gate_protects_natural_persons() {
406        // NaturalPerson cannot be flagged as property/asset
407        let err = assert_person_anti_commodification(OntologicalClass::NaturalPerson, true);
408        assert_eq!(err, Err(GateError::HumanPersonCannotBeCommodifiedAsAsset));
409
410        // NaturalPerson as Persona is valid
411        let ok = assert_person_anti_commodification(OntologicalClass::NaturalPerson, false);
412        assert!(ok.is_ok());
413
414        // ManufacturedProperty can be property
415        let prop = assert_person_anti_commodification(OntologicalClass::ManufacturedProperty, true);
416        assert!(prop.is_ok());
417    }
418
419    #[test]
420    fn oklab_roundtrip_is_lossless() {
421        let white_xyz = [0.950_47, 1.0, 1.088_83];
422        let lab = xyz_to_oklab(white_xyz);
423        let reconstructed = oklab_to_xyz(lab);
424
425        for c in 0..3 {
426            assert!((white_xyz[c] - reconstructed[c]).abs() < 1e-4);
427        }
428    }
429
430    #[test]
431    fn gate1_spectral_validation() {
432        // Physically plausible basis coefficients
433        let valid_coeffs = JakobHanikaCoeffs {
434            c0: 0.5,
435            c1: 0.0,
436            c2: 0.0,
437        }; // Constant 0.5 reflectance
438        assert!(validate_spectral_coeffs(&valid_coeffs).is_ok());
439
440        // Non-positive BSSRDF mean free path fails
441        let invalid_mfp = [0.0f32, 1.0, 2.0, 1.0];
442        assert_eq!(
443            validate_bssrdf_parameters(invalid_mfp),
444            Err(GateError::BssrdfZeroOrNegative)
445        );
446
447        let valid_mfp = [0.5f32, 1.2, 3.4, 1.0];
448        assert!(validate_bssrdf_parameters(valid_mfp).is_ok());
449    }
450
451    #[test]
452    fn gate2_geometry_confinement() {
453        let hero_min = [-1.0f32, -1.0, -1.0];
454        let hero_max = [1.0f32, 1.0, 1.0];
455        let center = [0.0f32, 0.0, 0.0];
456        let radius = 1.732f32;
457
458        // Within 5cm margin
459        let lod_min = [-1.04f32, -1.0, -1.0];
460        let lod_max = [1.04f32, 1.0, 1.0];
461        assert!(validate_geometry_confinement(
462            hero_min, hero_max, lod_min, lod_max, center, radius
463        )
464        .is_ok());
465
466        // Exceeding margin fails
467        let bad_min = [-1.10f32, -1.0, -1.0];
468        let bad_max = [1.0f32, 1.0, 1.0];
469        assert_eq!(
470            validate_geometry_confinement(hero_min, hero_max, bad_min, bad_max, center, radius),
471            Err(GateError::GeometryBoundsViolation)
472        );
473    }
474
475    #[test]
476    fn gate3_ontological_integrity() {
477        // DarwinianTaxon without mass is valid
478        assert!(
479            validate_ontological_integrity(OntologicalClass::DarwinianTaxon as u8, None).is_ok()
480        );
481
482        // ManufacturedProperty without mass fails
483        assert_eq!(
484            validate_ontological_integrity(OntologicalClass::ManufacturedProperty as u8, None),
485            Err(GateError::MissingPhysicalConstants)
486        );
487
488        // ManufacturedProperty with positive mass is valid
489        assert!(validate_ontological_integrity(
490            OntologicalClass::ManufacturedProperty as u8,
491            Some(42.0)
492        )
493        .is_ok());
494
495        // Malformed class fails
496        assert_eq!(
497            validate_ontological_integrity(99, None),
498            Err(GateError::MalformedOntologicalClass)
499        );
500    }
501
502    #[test]
503    fn gate4_script_determinism() {
504        assert!(validate_script_determinism(500_000, false).is_ok());
505        assert_eq!(
506            validate_script_determinism(1_500_000, false),
507            Err(GateError::NonDeterministicScriptExecution)
508        );
509        assert_eq!(
510            validate_script_determinism(100, true),
511            Err(GateError::NonDeterministicScriptExecution)
512        );
513    }
514
515    #[test]
516    fn taa_clamping_and_blend_factor() {
517        let center = [0.5f32, 0.5, 0.5];
518        let neighborhood = [center; 9];
519        let outlier = [1.5f32, 1.5, 1.5];
520
521        let clamped = clamp_taa_history_oklab(outlier, &neighborhood, 1.0);
522        assert!(clamped[0] < outlier[0]);
523
524        // Static velocity gives 0.05
525        assert_eq!(calculate_taa_blend_factor(0.0), 0.05);
526        // High velocity clamps to 0.20
527        assert_eq!(calculate_taa_blend_factor(10.0), 0.20);
528    }
529}