Skip to main content

clm_rust_core/layer0/
loader.rs

1//! Layer 0: Serde-based CLM Chapter & Manifest Loader.
2//! Canonical Path: kernel/clm_rust_core/src/layer0/loader.rs
3//!
4//! Parses YAML/JSON chapter files, validates BLAKE3 content hashes,
5//! and constructs typed `ParsedClmAst` representations.
6
7use std::fs;
8use std::path::Path;
9use serde_json::Value;
10
11use super::ast::{AbstractComponent, BalancedComponent, ClmChapter, ConcreteComponent, ParsedClmAst};
12use super::hash::compute_blake3;
13
14/// Serde-based chapter and component loader for CLM manifests.
15pub struct ClmLoader;
16
17impl ClmLoader {
18    /// Parses a raw YAML or JSON string into a strongly-typed `ParsedClmAst`.
19    pub fn load_from_str(content: &str) -> Result<ParsedClmAst, String> {
20        let raw_value: Value = serde_yaml::from_str(content)
21            .map_err(|e| format!("YAML deserialization error: {}", e))?;
22
23        Self::from_value(raw_value)
24    }
25
26    /// Loads and parses a CLM manifest file from the filesystem.
27    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<ParsedClmAst, String> {
28        let path_ref = path.as_ref();
29        let content = fs::read_to_string(path_ref)
30            .map_err(|e| format!("Failed to read file {}: {}", path_ref.display(), e))?;
31
32        let mut ast = Self::load_from_str(&content)?;
33        if ast.content_hash.is_none() {
34            let hash = compute_blake3(content.as_bytes());
35            ast.content_hash = Some(hash);
36        }
37        Ok(ast)
38    }
39
40    /// Loads all YAML manifests within a given chapter directory.
41    pub fn load_chapter_dir<P: AsRef<Path>>(dir_path: P) -> Result<Vec<ParsedClmAst>, String> {
42        let path_ref = dir_path.as_ref();
43        if !path_ref.is_dir() {
44            return Err(format!("Path is not a directory: {}", path_ref.display()));
45        }
46
47        let mut entries = fs::read_dir(path_ref)
48            .map_err(|e| format!("Failed to read dir {}: {}", path_ref.display(), e))?
49            .filter_map(|res| res.ok())
50            .map(|entry| entry.path())
51            .filter(|p| {
52                if let Some(ext) = p.extension() {
53                    let ext_str = ext.to_string_lossy();
54                    ext_str == "yaml" || ext_str == "yml"
55                } else {
56                    false
57                }
58            })
59            .collect::<Vec<_>>();
60
61        entries.sort();
62
63        let mut parsed_list = Vec::new();
64        for file_path in entries {
65            let ast = Self::load_from_file(&file_path)
66                .map_err(|e| format!("Failed to parse {}: {}", file_path.display(), e))?;
67            parsed_list.push(ast);
68        }
69
70        Ok(parsed_list)
71    }
72
73    /// Constructs a `ParsedClmAst` from a raw JSON `Value` tree.
74    pub fn from_value(raw_value: Value) -> Result<ParsedClmAst, String> {
75        let version = raw_value.get("version").and_then(|v| v.as_str()).map(|s| s.to_string());
76
77        // Extract chapter metadata if present
78        let chapter: Option<ClmChapter> = if let Some(ch_val) = raw_value.get("chapter") {
79            serde_json::from_value(ch_val.clone()).ok()
80        } else {
81            None
82        };
83
84        // Extract clm root or fallback to top-level
85        let clm_block = raw_value.get("clm").unwrap_or(&raw_value);
86
87        // Extract abstract spec
88        let abstract_val = clm_block.get("abstract")
89            .or_else(|| clm_block.get("abstract_spec"))
90            .unwrap_or(&Value::Null);
91        let abstract_spec: AbstractComponent = serde_json::from_value(abstract_val.clone())
92            .unwrap_or_default();
93
94        // Extract concrete spec
95        let concrete_val = clm_block.get("concrete")
96            .or_else(|| clm_block.get("concrete_spec"))
97            .unwrap_or(&Value::Null);
98        let concrete_spec: ConcreteComponent = serde_json::from_value(concrete_val.clone())
99            .unwrap_or_default();
100
101        // Extract balanced spec
102        let balanced_val = clm_block.get("balanced")
103            .or_else(|| clm_block.get("balanced_spec"))
104            .unwrap_or(&Value::Null);
105        let balanced_spec: BalancedComponent = serde_json::from_value(balanced_val.clone())
106            .unwrap_or_default();
107
108        // Extract pre/post conditions
109        let mut preconditions = Vec::new();
110        let mut postconditions = Vec::new();
111
112        if let Some(invs) = abstract_val.get("invariants") {
113            if let Some(pre) = invs.get("preconditions").and_then(|v| v.as_array()) {
114                for item in pre {
115                    if let Some(s) = item.as_str() {
116                        preconditions.push(s.to_string());
117                    }
118                }
119            }
120            if let Some(post) = invs.get("postconditions").and_then(|v| v.as_array()) {
121                for item in post {
122                    if let Some(s) = item.as_str() {
123                        postconditions.push(s.to_string());
124                    }
125                }
126            }
127        }
128
129        let canonical_str = serde_json::to_string(&raw_value).unwrap_or_default();
130        let content_hash = Some(compute_blake3(canonical_str.as_bytes()));
131
132        Ok(ParsedClmAst {
133            version,
134            chapter,
135            abstract_spec,
136            concrete_spec,
137            balanced_spec,
138            preconditions,
139            postconditions,
140            content_hash,
141            raw: raw_value,
142        })
143    }
144}