clm-kernel 0.0.16

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 0: Serde-based CLM Chapter & Manifest Loader.
//! Canonical Path: kernel/clm_rust_core/src/layer0/loader.rs
//!
//! Parses YAML/JSON chapter files, validates BLAKE3 content hashes,
//! and constructs typed `ParsedClmAst` representations.

use std::fs;
use std::path::Path;
use serde_json::Value;

use super::ast::{AbstractComponent, BalancedComponent, ClmChapter, ConcreteComponent, ParsedClmAst};
use super::hash::compute_blake3;

/// Serde-based chapter and component loader for CLM manifests.
pub struct ClmLoader;

impl ClmLoader {
    /// Parses a raw YAML or JSON string into a strongly-typed `ParsedClmAst`.
    pub fn load_from_str(content: &str) -> Result<ParsedClmAst, String> {
        let raw_value: Value = serde_yaml::from_str(content)
            .map_err(|e| format!("YAML deserialization error: {}", e))?;

        Self::from_value(raw_value)
    }

    /// Loads and parses a CLM manifest file from the filesystem.
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<ParsedClmAst, String> {
        let path_ref = path.as_ref();
        let content = fs::read_to_string(path_ref)
            .map_err(|e| format!("Failed to read file {}: {}", path_ref.display(), e))?;

        let mut ast = Self::load_from_str(&content)?;
        if ast.content_hash.is_none() {
            let hash = compute_blake3(content.as_bytes());
            ast.content_hash = Some(hash);
        }
        Ok(ast)
    }

    /// Loads all YAML manifests within a given chapter directory.
    pub fn load_chapter_dir<P: AsRef<Path>>(dir_path: P) -> Result<Vec<ParsedClmAst>, String> {
        let path_ref = dir_path.as_ref();
        if !path_ref.is_dir() {
            return Err(format!("Path is not a directory: {}", path_ref.display()));
        }

        let mut entries = fs::read_dir(path_ref)
            .map_err(|e| format!("Failed to read dir {}: {}", path_ref.display(), e))?
            .filter_map(|res| res.ok())
            .map(|entry| entry.path())
            .filter(|p| {
                if let Some(ext) = p.extension() {
                    let ext_str = ext.to_string_lossy();
                    ext_str == "yaml" || ext_str == "yml"
                } else {
                    false
                }
            })
            .collect::<Vec<_>>();

        entries.sort();

        let mut parsed_list = Vec::new();
        for file_path in entries {
            let ast = Self::load_from_file(&file_path)
                .map_err(|e| format!("Failed to parse {}: {}", file_path.display(), e))?;
            parsed_list.push(ast);
        }

        Ok(parsed_list)
    }

    /// Constructs a `ParsedClmAst` from a raw JSON `Value` tree.
    pub fn from_value(raw_value: Value) -> Result<ParsedClmAst, String> {
        let version = raw_value.get("version").and_then(|v| v.as_str()).map(|s| s.to_string());

        // Extract chapter metadata if present
        let chapter: Option<ClmChapter> = if let Some(ch_val) = raw_value.get("chapter") {
            serde_json::from_value(ch_val.clone()).ok()
        } else {
            None
        };

        // Extract clm root or fallback to top-level
        let clm_block = raw_value.get("clm").unwrap_or(&raw_value);

        // Extract abstract spec
        let abstract_val = clm_block.get("abstract")
            .or_else(|| clm_block.get("abstract_spec"))
            .unwrap_or(&Value::Null);
        let abstract_spec: AbstractComponent = serde_json::from_value(abstract_val.clone())
            .unwrap_or_default();

        // Extract concrete spec
        let concrete_val = clm_block.get("concrete")
            .or_else(|| clm_block.get("concrete_spec"))
            .unwrap_or(&Value::Null);
        let concrete_spec: ConcreteComponent = serde_json::from_value(concrete_val.clone())
            .unwrap_or_default();

        // Extract balanced spec
        let balanced_val = clm_block.get("balanced")
            .or_else(|| clm_block.get("balanced_spec"))
            .unwrap_or(&Value::Null);
        let balanced_spec: BalancedComponent = serde_json::from_value(balanced_val.clone())
            .unwrap_or_default();

        // Extract pre/post conditions
        let mut preconditions = Vec::new();
        let mut postconditions = Vec::new();

        if let Some(invs) = abstract_val.get("invariants") {
            if let Some(pre) = invs.get("preconditions").and_then(|v| v.as_array()) {
                for item in pre {
                    if let Some(s) = item.as_str() {
                        preconditions.push(s.to_string());
                    }
                }
            }
            if let Some(post) = invs.get("postconditions").and_then(|v| v.as_array()) {
                for item in post {
                    if let Some(s) = item.as_str() {
                        postconditions.push(s.to_string());
                    }
                }
            }
        }

        let canonical_str = serde_json::to_string(&raw_value).unwrap_or_default();
        let content_hash = Some(compute_blake3(canonical_str.as_bytes()));

        Ok(ParsedClmAst {
            version,
            chapter,
            abstract_spec,
            concrete_spec,
            balanced_spec,
            preconditions,
            postconditions,
            content_hash,
            raw: raw_value,
        })
    }
}