clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

/// Pre-computed type manifest for O(1) verification.
#[derive(Debug, Clone)]
pub struct CompiledTypeManifest {
    pub type_name: String,
    pub type_hash: [u8; 32],
    pub universe_level: u8,
    pub schema_hash: [u8; 32],
    pub compiled_regex: Option<Regex>,
    pub enum_hashes: HashSet<[u8; 32]>,
    pub required_field_hashes: HashSet<[u8; 32]>,
}

/// A compiled type lattice with pre-computed manifests for fast verification.
#[derive(Debug, Clone)]
pub struct CompiledTypeLattice {
    pub manifests: HashMap<String, CompiledTypeManifest>,
}

impl CompiledTypeLattice {
    /// Verify a value against a named type using pre-compiled manifests.
    /// Uses pre-compiled regexes and hash sets for faster matching than
    /// the recursive validation path.
    pub fn verify(
        &self,
        type_name: &str,
        value: &str,
        parent_level: u8,
        lattice: &TypeLattice,
    ) -> Result<(), TypeValidationError> {
        let manifest = self.manifests.get(&type_name.to_lowercase())
            .ok_or_else(|| TypeValidationError::UnknownType(type_name.to_string()))?;

        if manifest.universe_level > parent_level {
            return Err(TypeValidationError::StratificationError {
                type_name: type_name.to_string(),
                level: manifest.universe_level,
                parent_level,
            });
        }

        // Fast path for primitive types with pre-compiled regex.
        let info = lattice.get_type_info(type_name).unwrap();
        let style = detect_style(&info.schema);
        match style {
            SchemaStyle::Primitive => {
                let parsed = parse_value(value);
                // Use pre-compiled regex if available.
                if let Some(ref re) = manifest.compiled_regex
                    && !re.is_match(value) {
                        return Err(TypeValidationError::PatternViolation {
                            type_name: type_name.to_string(),
                            value: value.to_string(),
                            pattern: re.as_str().to_string(),
                        });
                    }
                // Check type_check constraints (no regex needed).
                validate_type_check(type_name, value, &parsed, &info.schema)
            }
            SchemaStyle::FieldList | SchemaStyle::JsonSchema => {
                // Complex types still need recursive validation.
                lattice.validate(type_name, value, parent_level)
            }
        }
    }

    /// O(1) fast path: verify by comparing pre-computed hashes.
    /// Returns true if the value hash matches an allowed hash for the type.
    /// This is only applicable for enum-constrained types; for other types,
    /// it returns false (caller should fall back to `verify`).
    pub fn verify_by_hash(&self, type_name: &str, value_hash: &[u8; 32]) -> bool {
        let manifest = self.manifests.get(&type_name.to_lowercase());
        match manifest {
            Some(m) if !m.enum_hashes.is_empty() => m.enum_hashes.contains(value_hash),
            _ => false,
        }
    }
}

/// Global cached compiled lattice for zero-cost repeated lookups.
pub(super) static COMPILED_LATTICE: OnceLock<CompiledTypeLattice> = OnceLock::new();

/// Get the globally cached compiled lattice, initializing it from
/// `default_lattice()` on first call.
pub fn compiled_lattice() -> &'static CompiledTypeLattice {
    COMPILED_LATTICE.get_or_init(|| default_lattice().compile())
}

/// Compute content hash of a type name.
pub fn hash_type_name(name: &str) -> [u8; 32] {
    crate::hash::raw_hash_bytes_32(name.as_bytes())
}

/// Compute content hash of a value (for enum matching).
pub fn hash_value(value: &str) -> [u8; 32] {
    crate::hash::raw_hash_bytes_32(value.as_bytes())
}

/// Compute content hash of a schema (for content-addressed manifest lookup).
pub(super) fn hash_schema(schema: &serde_yaml::Value) -> [u8; 32] {
    let yaml_str = serde_yaml::to_string(schema).unwrap_or_default();
    crate::hash::raw_hash_bytes_32(yaml_str.as_bytes())
}

/// Extract a compiled regex from a primitive schema's constraints.
pub(super) fn extract_regex(schema: &serde_yaml::Value) -> Option<Regex> {
    let constraints = schema.get("constraints")?;
    let pattern = constraints.get("pattern")?.as_str()?;
    if pattern == "null" {
        return None;
    }
    Regex::new(pattern).ok()
}

/// Extract pre-computed hashes for enum-allowed values.
pub(super) fn extract_enum_hashes(schema: &serde_yaml::Value) -> HashSet<[u8; 32]> {
    let mut hashes = HashSet::new();
    if let Some(constraints) = schema.get("constraints")
        && let Some(en) = constraints.get("enum").and_then(|v| v.as_sequence()) {
            for val in en {
                let s = yaml_to_str(val);
                hashes.insert(hash_value(&s));
            }
        }
    // Also check field_list schemas for field-level enums.
    if let Some(required) = schema.get("required_fields").and_then(|v| v.as_sequence()) {
        for field in required {
            if let Some(en) = field.get("constraints").and_then(|v| v.get("enum")).and_then(|v| v.as_sequence()) {
                for val in en {
                    let s = yaml_to_str(val);
                    hashes.insert(hash_value(&s));
                }
            }
        }
    }
    hashes
}

/// Extract pre-computed hashes for required field names.
pub(super) fn extract_required_field_hashes(schema: &serde_yaml::Value) -> HashSet<[u8; 32]> {
    let mut hashes = HashSet::new();
    if let Some(required) = schema.get("required_fields").and_then(|v| v.as_sequence()) {
        for field in required {
            if let Some(name) = field.get("name").and_then(|v| v.as_str()) {
                hashes.insert(hash_value(name));
            }
        }
    }
    if let Some(required) = schema.get("required").and_then(|v| v.as_sequence()) {
        for val in required {
            if let Some(name) = val.as_str() {
                hashes.insert(hash_value(name));
            }
        }
    }
    hashes
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum SchemaStyle {
    Primitive,
    FieldList,
    JsonSchema,
}

pub(super) fn detect_style(schema: &serde_yaml::Value) -> SchemaStyle {
    if schema.get("constraints").is_some() {
        return SchemaStyle::Primitive;
    }
    if schema.get("required_fields").is_some() || schema.get("optional_fields").is_some() {
        return SchemaStyle::FieldList;
    }
    if schema.get("required").is_some() || schema.get("properties").is_some() {
        return SchemaStyle::JsonSchema;
    }
    SchemaStyle::Primitive
}

pub(super) fn parse_manifest(name: &str, path: &str, body: &str) -> Result<TypeInfo, String> {
    let manifest: serde_yaml::Value = serde_yaml::from_str(body).map_err(|e| e.to_string())?;
    let inner = manifest.get("clm").unwrap_or(&manifest);
    let concrete = inner
        .get("concrete_impl")
        .or_else(|| inner.get("concrete"))
        .cloned()
        .unwrap_or(serde_yaml::Value::Null);
    let universe_level = if let Some(v) = concrete.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else if let Some(v) = inner.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else if let Some(v) = manifest.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else {
        // Infer default level by subdirectory path if not explicitly declared
        if path.contains("/meta/") {
            0
        } else if path.contains("/primitives/") {
            0
        } else if path.contains("/runtime/") {
            2
        } else if path.contains("/content/") {
            1
        } else if path.contains("/transport/") {
            3
        } else if path.contains("/codegen/") {
            1
        } else if path.contains("/governance/") {
            1
        } else if path.contains("/identity/") {
            3
        } else if path.contains("/payment/") {
            4
        } else if path.contains("/observability/") {
            2
        } else if path.contains("/storage/") {
            2
        } else if path.contains("/core_features/") {
            1
        } else if path.contains("/chat/") {
            4
        } else {
            0
        }
    };
    let schema = concrete
        .get("schema")
        .or_else(|| inner.get("schema"))
        .cloned()
        .unwrap_or(serde_yaml::Value::Null);
    Ok(TypeInfo {
        name: name.to_string(),
        path: path.to_string(),
        universe_level,
        schema,
        concrete,
    })
}

pub(super) fn parse_value(value: &str) -> JsonValue {
    let trimmed = value.trim();
    if ((trimmed.starts_with('{') && trimmed.ends_with('}'))
        || (trimmed.starts_with('[') && trimmed.ends_with(']')))
        && let Ok(v) = serde_json::from_str::<JsonValue>(trimmed) {
            return v;
        }
    JsonValue::String(value.to_string())
}