Skip to main content

clm_rust_core/evaluator/
cli.rs

1use std::fs;
2use clap::Subcommand;
3use std::path::Path;
4
5pub fn compile_evaluator_cache(_clm_root: &Path, _quiet: bool) -> Result<(), String> {
6    // Legacy shell evaluator cache compilation is retired in Sprint 483/487 (INV-483 / INV-487).
7    // Native Rust, Python, and JS evaluators execute in-process without sourcing evaluator_cache.
8    Ok(())
9}
10
11pub fn extract_bootstrap_script(clm_root: &Path) -> Result<String, String> {
12    let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
13    if !self_clm.exists() {
14        return Err(format!("clmEval.yaml not found at {:?}", self_clm));
15    }
16    let content = fs::read_to_string(&self_clm)
17        .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
18    
19    let data: serde_yaml::Value = serde_yaml::from_str(&content)
20        .map_err(|e| format!("Failed to parse clmEval.yaml: {}", e))?;
21    
22    let clm_data = data.get("clm").unwrap_or(&data);
23    let concrete_impl = clm_data.get("concrete_impl").ok_or("No concrete_impl in clmEval.yaml")?;
24    let process = concrete_impl.get("process").ok_or("No process in clmEval.yaml")?;
25    
26    let script = match process {
27        serde_yaml::Value::Mapping(map) => {
28            map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string())
29        }
30        serde_yaml::Value::Sequence(seq) => {
31            let mut s = None;
32            for val in seq {
33                if let serde_yaml::Value::Mapping(map) = val
34                    && map.get("type").and_then(|v| v.as_str()) == Some("shell") {
35                        s = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
36                        break;
37                    }
38            }
39            s
40        }
41        _ => None,
42    };
43    
44    script.ok_or_else(|| "Could not extract shell bootstrap script from clmEval.yaml".to_string())
45}
46
47#[derive(Subcommand, Debug, Clone)]
48pub enum ToolCommands {
49    #[command(name = "run")]
50    Run {
51        tool_handle: String,
52        #[arg(long)]
53        source_dir: Option<String>,
54        #[arg(num_args = 0..)]
55        args: Vec<String>,
56    },
57    #[command(name = "document")]
58    Document,
59}
60
61#[derive(Subcommand, Debug, Clone)]
62pub enum EvolveCommands {
63    #[command(name = "status")]
64    Status {
65        #[arg(long)]
66        timeslot: Option<String>,
67    },
68    #[command(name = "step")]
69    Step,
70    #[command(name = "report")]
71    Report,
72}
73
74pub fn run_tool_dispatcher(cmd: ToolCommands, clm_root: &str) -> Result<String, String> {
75    match cmd {
76        ToolCommands::Run { tool_handle, source_dir, args } => {
77            let clm_path = Path::new(clm_root);
78            
79            // Map tool handle to yaml file, e.g., tool:foo -> tool_foo.yaml
80            let yaml_filename = format!("{}.yaml", tool_handle.replace(":", "_"));
81            let yaml_path = clm_path.join("types/governance").join(&yaml_filename);
82            
83            if !yaml_path.exists() {
84                return Err(format!("[ERROR] Tool spec not found: {:?}", yaml_path));
85            }
86            
87            let yaml_content = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
88            let spec: serde_yaml::Value = serde_yaml::from_str(&yaml_content).map_err(|e| e.to_string())?;
89            
90            let script_val = spec.get("clm")
91                .and_then(|v| v.get("concrete_impl"))
92                .and_then(|v| v.get("process"))
93                .and_then(|v| v.get("script"))
94                .and_then(|v| v.as_str());
95                
96            if let Some(script_rel_path) = script_val {
97                let script_path = clm_path.join(script_rel_path);
98                if !script_path.exists() {
99                    return Err(format!("[ERROR] Script not found: {:?}", script_path));
100                }
101                
102                let mut cmd = std::process::Command::new("python3");
103                cmd.arg(&script_path);
104                
105                if let Some(dir) = source_dir {
106                    cmd.arg("--source_dir");
107                    cmd.arg(&dir);
108                }
109                for arg in args {
110                    cmd.arg(&arg);
111                }
112                
113                let res = cmd.output().map_err(|e| e.to_string())?;
114                let mut out = format!("[TOOL DISPATCHER] Executed tool: {}\n", tool_handle);
115                out.push_str(&String::from_utf8_lossy(&res.stdout));
116                if !res.stderr.is_empty() {
117                    out.push_str("\n[STDERR]\n");
118                    out.push_str(&String::from_utf8_lossy(&res.stderr));
119                }
120                Ok(out)
121            } else {
122                Err(format!("[ERROR] Invalid tool spec in {:?}: missing clm.concrete_impl.process.script", yaml_path))
123            }
124        }
125        ToolCommands::Document => {
126            Ok("# CLM Executable Tools Registry\n\n- `tool:layer_boundary_checker`: Verifies layer boundaries across the Rust workspace.\n- `tool:rust_interpreter_reporter`: Analyzes the Rust CLM Interpreter and generates an architecture report.\n".to_string())
127        }
128    }
129}
130
131pub fn run_evolve_dispatcher(cmd: EvolveCommands, clm_root: &str) -> Result<String, String> {
132    match cmd {
133        EvolveCommands::Status { timeslot } => {
134            let slot = timeslot.unwrap_or_else(|| {
135                let now = chrono::Local::now();
136                let iso_week = chrono::Datelike::iso_week(&now);
137                format!("{:04}_w{:02}", iso_week.year(), iso_week.week())
138            });
139            let db_name = format!("pkc_evol_{}.db", slot);
140            
141            let count = if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
142                conn.query_row(
143                    "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE 'run:evolution:transition:%'",
144                    [],
145                    |row| row.get::<_, i64>(0)
146                ).unwrap_or(0)
147            } else {
148                0
149            };
150            
151            Ok(format!(
152                "[EVOLVE STATUS] Active Time-Slot: {}\nDatabase: {}\nVerified Transitions: {}\nStatus: Ready for next step.\n",
153                slot, db_name, count
154            ))
155        }
156        EvolveCommands::Step => {
157            let gov_dir = Path::new(clm_root).join("types/governance");
158            if !gov_dir.exists() {
159                return Err(format!("Governance directory not found: {:?}", gov_dir));
160            }
161            
162            let mut executed_count = 0;
163            let mut failed_count = 0;
164            let mut skipped_count = 0;
165            
166            for entry in fs::read_dir(&gov_dir).map_err(|e| e.to_string())? {
167                let entry = entry.map_err(|e| e.to_string())?;
168                let path = entry.path();
169                let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
170                
171                if file_name.starts_with("b_mcard_") && file_name.ends_with(".yaml") {
172                    let b_mcard_name = file_name.trim_start_matches("b_mcard_").trim_end_matches(".yaml");
173                    let handle_name = format!("run:evolution:transition:{}", b_mcard_name);
174                    
175                    if let Ok(Some(_)) = crate::db::resolve_handle_hash("evolution", clm_root, &handle_name) {
176                        skipped_count += 1;
177                        continue;
178                    }
179                    
180                    let path_str = path.to_string_lossy().to_string();
181                    let val = match crate::parser::parse_manifest(&path_str) {
182                        Ok(v) => v,
183                        Err(e) => {
184                            failed_count += 1;
185                            println!("[EVOLVE STEP] Failed to parse B-MCard {:?}: {}", path, e);
186                            continue;
187                        }
188                    };
189                    
190                    let polyglot_cases = val.pointer("/clm/balanced_exp/polyglot_cases")
191                        .and_then(|v| v.as_array());
192                        
193                    if let Some(cases) = polyglot_cases {
194                        let mut b_mcard_ok = true;
195                        println!("[EVOLVE STEP] Verifying transition '{}'...", b_mcard_name);
196                        
197                        for case in cases {
198                            let name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed");
199                            let assertions = case.get("then").and_then(|v| v.as_array());
200                            
201                            if let Some(asserts) = assertions {
202                                for assertion in asserts {
203                                    if let Some(cmd_str) = assertion.get("assert_success").and_then(|v| v.as_str()) {
204                                        let mut command = std::process::Command::new("sh");
205                                        command.arg("-c").arg(cmd_str);
206                                        let output = match command.output() {
207                                            Ok(out) => out,
208                                            Err(e) => {
209                                                b_mcard_ok = false;
210                                                println!("  ❌ Case '{}' failed: could not execute: {}", name, e);
211                                                break;
212                                            }
213                                        };
214                                        if !output.status.success() {
215                                            b_mcard_ok = false;
216                                            println!("  ❌ Case '{}' failed (exit code = {}).", name, output.status.code().unwrap_or(1));
217                                            let stderr = String::from_utf8_lossy(&output.stderr);
218                                            if !stderr.is_empty() {
219                                                println!("     Stderr: {}", stderr.trim());
220                                            }
221                                            break;
222                                        } else {
223                                            println!("  ✅ Case '{}' assertion passed.", name);
224                                        }
225                                    }
226                                }
227                            }
228                            if !b_mcard_ok {
229                                break;
230                            }
231                        }
232                        
233                        if b_mcard_ok {
234                            let g_time = crate::fs_utils::compute_g_time();
235                            let sponsor_did = std::env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:pkc:ca:darwin:root-agent".to_string());
236                            let pre_hash = val.pointer("/clm/abstract_spec/invariants/preconditions")
237                                .and_then(|v| v.as_array())
238                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
239                                .unwrap_or_default();
240                            let post_hash = val.pointer("/clm/abstract_spec/invariants/postconditions")
241                                .and_then(|v| v.as_array())
242                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
243                                .unwrap_or_default();
244                                
245                            let vcard_content = format!(
246                                "vcard:\n  g_time: \"{}\"\n  transition: \"{}\"\n  status: \"VERIFIED\"\n  pre_hash: \"{}\"\n  post_hash: \"{}\"\n  sponsor_did: \"{}\"\n",
247                                g_time, b_mcard_name, pre_hash, post_hash, sponsor_did
248                            );
249                            let content_hash = crate::fs_utils::compute_content_hash(&vcard_content);
250                            
251                            if let Err(e) = crate::db::handle_register_batch(
252                                "evolution",
253                                clm_root,
254                                &handle_name,
255                                &crate::hash::prefixed(&content_hash),
256                                &vcard_content,
257                            ) {
258                                failed_count += 1;
259                                println!("[EVOLVE STEP] Failed to register transition handle: {}", e);
260                            } else {
261                                executed_count += 1;
262                                println!("[EVOLVE STEP] Verified and registered transition '{}'.", b_mcard_name);
263                            }
264                        } else {
265                            failed_count += 1;
266                        }
267                    }
268                }
269            }
270            
271            Ok(format!(
272                "[EVOLVE STEP] Completed. Executed: {}, Skipped: {}, Failed: {}\n",
273                executed_count, skipped_count, failed_count
274            ))
275        }
276        EvolveCommands::Report => {
277            generate_evolution_audit_report(clm_root)
278        }
279    }
280}
281
282pub fn generate_evolution_audit_report(clm_root: &str) -> Result<String, String> {
283    let mut table_rows = Vec::new();
284    
285    if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
286        let mut stmt = match conn.prepare(
287            "SELECT hr.handle, hr.current_hash, hr.updated_at, c.content \
288             FROM handle_registry hr \
289             JOIN card c ON hr.current_hash = c.hash \
290             WHERE hr.handle LIKE 'run:evolution:transition:%' \
291             ORDER BY hr.updated_at ASC;"
292        ) {
293            Ok(s) => s,
294            Err(e) => return Err(e.to_string()),
295        };
296        
297        let mut rows = match stmt.query([]) {
298            Ok(r) => r,
299            Err(e) => return Err(e.to_string()),
300        };
301        
302        while let Ok(Some(row)) = rows.next() {
303            let handle: String = row.get(0).unwrap_or_default();
304            let _current_hash: String = row.get(1).unwrap_or_default();
305            let updated_at: String = row.get(2).unwrap_or_default();
306            let content: String = row.get(3).unwrap_or_default();
307            
308            let mut transition = handle.trim_start_matches("run:evolution:transition:").to_string();
309            let mut status = "UNKNOWN".to_string();
310            let mut sponsor_did = "UNKNOWN".to_string();
311            let mut pre_hash = "UNKNOWN".to_string();
312            let mut post_hash = "UNKNOWN".to_string();
313            
314            for line in content.lines() {
315                let line_trimmed = line.trim();
316                if line_trimmed.starts_with("transition:") {
317                    transition = line_trimmed.trim_start_matches("transition:").trim_matches('"').trim().to_string();
318                } else if line_trimmed.starts_with("status:") {
319                    status = line_trimmed.trim_start_matches("status:").trim_matches('"').trim().to_string();
320                } else if line_trimmed.starts_with("sponsor_did:") {
321                    sponsor_did = line_trimmed.trim_start_matches("sponsor_did:").trim_matches('"').trim().to_string();
322                } else if line_trimmed.starts_with("pre_hash:") {
323                    pre_hash = line_trimmed.trim_start_matches("pre_hash:").trim_matches('"').trim().to_string();
324                } else if line_trimmed.starts_with("post_hash:") {
325                    post_hash = line_trimmed.trim_start_matches("post_hash:").trim_matches('"').trim().to_string();
326                }
327            }
328            
329            table_rows.push(format!(
330                "| {} | {} | {} | {} | `{}` | `{}` |",
331                updated_at, transition, status, sponsor_did, pre_hash, post_hash
332            ));
333        }
334    }
335    
336    let rows_str = if table_rows.is_empty() {
337        "No transitions recorded in the current epoch.\n".to_string()
338    } else {
339        let mut table = "| Timestamp | Transition | Status | Sponsor DID | Pre Ingress Hash | Post Egress Hash |\n".to_string();
340        table.push_str("| --- | --- | --- | --- | --- | --- |\n");
341        for r in table_rows {
342            table.push_str(&r);
343            table.push('\n');
344        }
345        table
346    };
347    
348    let report_content = format!(
349        "# CLM Evolution Audit Report\n\n\
350         Generated: {}\n\n\
351         ## Verified Transitions\n\n\
352         {}\n",
353        chrono::Local::now().to_rfc2822(),
354        rows_str
355    );
356    
357    let path = Path::new(clm_root).join("docs/spec/consensus_audit_report.md");
358    if let Some(parent) = path.parent() {
359        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
360    }
361    std::fs::write(&path, &report_content).map_err(|e| e.to_string())?;
362    
363    Ok(format!("Evolution audit report generated at: {:?}", path))
364}