Skip to main content

clm_rust_core/evaluator/
cli.rs

1use std::fs;
2use clap::Subcommand;
3use std::io::Write;
4use std::path::Path;
5use std::time::SystemTime;
6
7fn get_consolidated_mapping(fn_name: &str) -> Option<&'static str> {
8    match fn_name {
9        "mcard_utils" | "sql_repository" | "clm_path_utils" | "yaml_query" | "jsonl_emit" | "mcard_cache" | "memorize_mcard" => Some("mcard_storage.sh"),
10        "sign_clm" | "evidence_lifecycle" | "verify_precondition" | "validate_postcondition" | "instantiate_contract_agent" => Some("mcard_verification.sh"),
11        "baldwin_algebra" | "pcard_operators" | "decompose_clm" | "serialize_pcard" | "resolve_composite" | "symbol_extractor" | "clm_meta" => Some("clm_algebra.sh"),
12        "init_tridb" | "register_core_pcards" => Some("clm_bootstrap.sh"),
13        _ => None
14    }
15}
16
17fn get_max_mtime_recursive(dir: &Path) -> Option<SystemTime> {
18    let mut max_mtime = None;
19    if let Ok(entries) = fs::read_dir(dir) {
20        for entry in entries.flatten() {
21            let path = entry.path();
22            if path.is_dir() {
23                if let Some(mtime) = get_max_mtime_recursive(&path) {
24                    max_mtime = Some(max_mtime.map_or(mtime, |max| std::cmp::max(max, mtime)));
25                }
26            } else if path.is_file()
27                && let Ok(meta) = fs::metadata(&path)
28                    && let Ok(mtime) = meta.modified() {
29                        max_mtime = Some(max_mtime.map_or(mtime, |max| std::cmp::max(max, mtime)));
30                    }
31        }
32    }
33    max_mtime
34}
35
36fn is_cache_fresh(clm_root: &Path, cache_path: &Path) -> bool {
37    let cache_mtime = match fs::metadata(cache_path).and_then(|m| m.modified()) {
38        Ok(t) => t,
39        Err(_) => return false,
40    };
41
42    let check_dirs = [
43        clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator"),
44        clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/governance"),
45        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core"),
46        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer1_cpn_vm"),
47        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer2_storage"),
48        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer3_network"),
49        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator"),
50        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/governance"),
51    ];
52
53    for dir in &check_dirs {
54        if dir.is_dir()
55            && let Some(mtime) = get_max_mtime_recursive(dir)
56                && mtime > cache_mtime {
57                    return false;
58                }
59    }
60    true
61}
62
63pub fn compile_evaluator_cache(clm_root: &Path, quiet: bool) -> Result<(), String> {
64    let cache_path = clm_root.join("data/ipc/evaluator_cache.sh");
65    if std::env::var("CLM_CACHE_FRESH").as_deref() == Ok("1") && cache_path.exists() {
66        if !quiet {
67            eprintln!("[clmEval-rs] Cache assumed fresh (CLM_CACHE_FRESH=1).");
68        }
69        return Ok(());
70    }
71    if is_cache_fresh(clm_root, &cache_path) {
72        if !quiet {
73            eprintln!("[clmEval-rs] Cache is up-to-date.");
74        }
75        return Ok(());
76    }
77
78    if !quiet {
79        eprintln!("[clmEval-rs] Cache is stale or missing, compiling cache...");
80    }
81
82    let evaluator_dir = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator");
83    let governance_dir = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/governance");
84
85    let mut eval_files = Vec::new();
86    if let Ok(entries) = fs::read_dir(&evaluator_dir) {
87        for entry in entries.flatten() {
88            let path = entry.path();
89            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("yaml")
90                && path.file_name().and_then(|s| s.to_str()) != Some("clmEval.yaml") {
91                    eval_files.push(path);
92                }
93        }
94    }
95    eval_files.sort();
96
97    let mut gov_files = Vec::new();
98    if governance_dir.is_dir()
99        && let Ok(entries) = fs::read_dir(&governance_dir) {
100            for entry in entries.flatten() {
101                let path = entry.path();
102                if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("yaml") {
103                    gov_files.push(path);
104                }
105            }
106        }
107    gov_files.sort();
108
109    let mut functions = Vec::new();
110    let mut seen_master_files = std::collections::HashSet::new();
111
112    let mut all_files = Vec::new();
113    for f in eval_files {
114        all_files.push(f);
115    }
116    for f in gov_files {
117        all_files.push(f);
118    }
119
120    for fn_clm in all_files {
121        let content = fs::read_to_string(&fn_clm)
122            .map_err(|e| format!("Failed to read YAML file {:?}: {}", fn_clm, e))?;
123        
124        let data: serde_yaml::Value = serde_yaml::from_str(&content)
125            .map_err(|e| format!("Failed to parse YAML from {:?}: {}", fn_clm, e))?;
126
127        let clm_data = data.get("clm").unwrap_or(&data);
128        let concrete_impl = match clm_data.get("concrete_impl") {
129            Some(val) => val,
130            None => continue,
131        };
132
133        let fn_name = match concrete_impl.get("operation").and_then(|v| v.as_str()) {
134            Some(name) => name.to_string(),
135            None => continue,
136        };
137
138        let process = match concrete_impl.get("process") {
139            Some(p) => p,
140            None => continue,
141        };
142
143        let (script_handle, script) = match process {
144            serde_yaml::Value::Mapping(map) => {
145                let handle = map.get("script_handle").and_then(|v| v.as_str()).map(|s| s.to_string());
146                let script = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
147                (handle, script)
148            }
149            serde_yaml::Value::Sequence(seq) => {
150                let mut handle = None;
151                let mut script = None;
152                for val in seq {
153                    if let serde_yaml::Value::Mapping(map) = val
154                        && map.get("type").and_then(|v| v.as_str()) == Some("shell") {
155                            handle = map.get("script_handle").and_then(|v| v.as_str()).map(|s| s.to_string());
156                            script = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
157                            break;
158                        }
159                }
160                (handle, script)
161            }
162            _ => (None, None),
163        };
164
165        let mut body = None;
166
167        if let Some(ref handle_val) = script_handle
168            && handle_val != "null" {
169                let mut sh_path = None;
170                if let Some(master_file) = get_consolidated_mapping(&fn_name) {
171                    let candidate = clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core").join(master_file);
172                    if candidate.exists() {
173                        sh_path = Some(candidate);
174                    }
175                }
176
177                if sh_path.is_none() {
178                    let filename = format!("{}.sh", fn_clm.file_stem().unwrap().to_string_lossy());
179                    for layer in &["layer0_core", "layer1_cpn_vm", "layer2_storage", "layer3_network", "evaluator", "governance"] {
180                        let candidate = clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap").join(layer).join(&filename);
181                        if candidate.exists() {
182                            sh_path = Some(candidate);
183                            break;
184                        }
185                    }
186                }
187
188                if let Some(ref path) = sh_path {
189                    if seen_master_files.contains(path) {
190                        body = Some("".to_string());
191                    } else {
192                        match fs::read_to_string(path) {
193                            Ok(content) => {
194                                body = Some(content);
195                                seen_master_files.insert(path.clone());
196                            }
197                            Err(e) => {
198                                return Err(format!("Failed to read source file {:?}: {}", path, e));
199                            }
200                        }
201                    }
202                }
203            }
204
205        if body.is_none() {
206            body = script;
207        }
208
209        if let Some(body_content) = body {
210            if body_content == "null" {
211                continue;
212            }
213            functions.push((fn_name, body_content, fn_clm.clone()));
214        }
215    }
216
217    let out_dir = clm_root.join("data/ipc");
218    fs::create_dir_all(&out_dir).map_err(|e| format!("Failed to create directory {:?}: {}", out_dir, e))?;
219    let mut out_file = fs::File::create(&cache_path).map_err(|e| format!("Failed to create file {:?}: {}", cache_path, e))?;
220
221    writeln!(out_file, "#!/usr/bin/env bash")
222        .map_err(|e| format!("Failed to write cache header: {}", e))?;
223    writeln!(out_file, "# =============================================================================")
224        .map_err(|e| format!("Failed to write cache header: {}", e))?;
225    writeln!(out_file, "# Cubical Logic Model (CLM) Evaluator Cache")
226        .map_err(|e| format!("Failed to write cache header: {}", e))?;
227    writeln!(out_file, "# Generated automatically by clm_rust_core evaluate. DO NOT EDIT MANUALLY.")
228        .map_err(|e| format!("Failed to write cache header: {}", e))?;
229    writeln!(out_file, "# =============================================================================\n")
230        .map_err(|e| format!("Failed to write cache header: {}", e))?;
231
232    for (fn_name, body_content, fn_clm) in functions {
233        let rel_path = match fn_clm.strip_prefix(clm_root) {
234            Ok(p) => p.to_string_lossy().to_string(),
235            Err(_) => fn_clm.to_string_lossy().to_string(),
236        };
237        writeln!(out_file, "# --- Source: {} ---", rel_path)
238            .map_err(|e| format!("Failed to write source comment: {}", e))?;
239        let trimmed = body_content.trim();
240        if !trimmed.is_empty() {
241            let normalized = trimmed.replace("\r", "");
242            writeln!(out_file, "{}", normalized)
243                .map_err(|e| format!("Failed to write function body: {}", e))?;
244        }
245        writeln!(out_file, "export -f {}\n", fn_name)
246            .map_err(|e| format!("Failed to write function export: {}", e))?;
247    }
248
249    if !quiet {
250        eprintln!("[clmEval-rs] Cache compiled successfully.");
251    }
252    Ok(())
253}
254
255pub fn extract_bootstrap_script(clm_root: &Path) -> Result<String, String> {
256    let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
257    if !self_clm.exists() {
258        return Err(format!("clmEval.yaml not found at {:?}", self_clm));
259    }
260    let content = fs::read_to_string(&self_clm)
261        .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
262    
263    let data: serde_yaml::Value = serde_yaml::from_str(&content)
264        .map_err(|e| format!("Failed to parse clmEval.yaml: {}", e))?;
265    
266    let clm_data = data.get("clm").unwrap_or(&data);
267    let concrete_impl = clm_data.get("concrete_impl").ok_or("No concrete_impl in clmEval.yaml")?;
268    let process = concrete_impl.get("process").ok_or("No process in clmEval.yaml")?;
269    
270    let script = match process {
271        serde_yaml::Value::Mapping(map) => {
272            map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string())
273        }
274        serde_yaml::Value::Sequence(seq) => {
275            let mut s = None;
276            for val in seq {
277                if let serde_yaml::Value::Mapping(map) = val
278                    && map.get("type").and_then(|v| v.as_str()) == Some("shell") {
279                        s = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
280                        break;
281                    }
282            }
283            s
284        }
285        _ => None,
286    };
287    
288    script.ok_or_else(|| "Could not extract shell bootstrap script from clmEval.yaml".to_string())
289}
290
291#[derive(Subcommand, Debug, Clone)]
292pub enum ToolCommands {
293    #[command(name = "run")]
294    Run {
295        tool_handle: String,
296        #[arg(long)]
297        source_dir: Option<String>,
298        #[arg(num_args = 0..)]
299        args: Vec<String>,
300    },
301    #[command(name = "document")]
302    Document,
303}
304
305#[derive(Subcommand, Debug, Clone)]
306pub enum EvolveCommands {
307    #[command(name = "status")]
308    Status {
309        #[arg(long)]
310        timeslot: Option<String>,
311    },
312    #[command(name = "step")]
313    Step,
314    #[command(name = "report")]
315    Report,
316}
317
318pub fn run_tool_dispatcher(cmd: ToolCommands, clm_root: &str) -> Result<String, String> {
319    match cmd {
320        ToolCommands::Run { tool_handle, source_dir, args } => {
321            let clm_path = Path::new(clm_root);
322            
323            // Map tool handle to yaml file, e.g., tool:foo -> tool_foo.yaml
324            let yaml_filename = format!("{}.yaml", tool_handle.replace(":", "_"));
325            let yaml_path = clm_path.join("types/governance").join(&yaml_filename);
326            
327            if !yaml_path.exists() {
328                return Err(format!("[ERROR] Tool spec not found: {:?}", yaml_path));
329            }
330            
331            let yaml_content = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
332            let spec: serde_yaml::Value = serde_yaml::from_str(&yaml_content).map_err(|e| e.to_string())?;
333            
334            let script_val = spec.get("clm")
335                .and_then(|v| v.get("concrete_impl"))
336                .and_then(|v| v.get("process"))
337                .and_then(|v| v.get("script"))
338                .and_then(|v| v.as_str());
339                
340            if let Some(script_rel_path) = script_val {
341                let script_path = clm_path.join(script_rel_path);
342                if !script_path.exists() {
343                    return Err(format!("[ERROR] Script not found: {:?}", script_path));
344                }
345                
346                let mut cmd = std::process::Command::new("python3");
347                cmd.arg(&script_path);
348                
349                if let Some(dir) = source_dir {
350                    cmd.arg("--source_dir");
351                    cmd.arg(&dir);
352                }
353                for arg in args {
354                    cmd.arg(&arg);
355                }
356                
357                let res = cmd.output().map_err(|e| e.to_string())?;
358                let mut out = format!("[TOOL DISPATCHER] Executed tool: {}\n", tool_handle);
359                out.push_str(&String::from_utf8_lossy(&res.stdout));
360                if !res.stderr.is_empty() {
361                    out.push_str("\n[STDERR]\n");
362                    out.push_str(&String::from_utf8_lossy(&res.stderr));
363                }
364                Ok(out)
365            } else {
366                Err(format!("[ERROR] Invalid tool spec in {:?}: missing clm.concrete_impl.process.script", yaml_path))
367            }
368        }
369        ToolCommands::Document => {
370            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())
371        }
372    }
373}
374
375pub fn run_evolve_dispatcher(cmd: EvolveCommands, clm_root: &str) -> Result<String, String> {
376    match cmd {
377        EvolveCommands::Status { timeslot } => {
378            let slot = timeslot.unwrap_or_else(|| {
379                let now = chrono::Local::now();
380                let iso_week = chrono::Datelike::iso_week(&now);
381                format!("{:04}_w{:02}", iso_week.year(), iso_week.week())
382            });
383            let db_name = format!("pkc_evol_{}.db", slot);
384            
385            let count = if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
386                conn.query_row(
387                    "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE 'run:evolution:transition:%'",
388                    [],
389                    |row| row.get::<_, i64>(0)
390                ).unwrap_or(0)
391            } else {
392                0
393            };
394            
395            Ok(format!(
396                "[EVOLVE STATUS] Active Time-Slot: {}\nDatabase: {}\nVerified Transitions: {}\nStatus: Ready for next step.\n",
397                slot, db_name, count
398            ))
399        }
400        EvolveCommands::Step => {
401            let gov_dir = Path::new(clm_root).join("types/governance");
402            if !gov_dir.exists() {
403                return Err(format!("Governance directory not found: {:?}", gov_dir));
404            }
405            
406            let mut executed_count = 0;
407            let mut failed_count = 0;
408            let mut skipped_count = 0;
409            
410            for entry in fs::read_dir(&gov_dir).map_err(|e| e.to_string())? {
411                let entry = entry.map_err(|e| e.to_string())?;
412                let path = entry.path();
413                let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
414                
415                if file_name.starts_with("b_mcard_") && file_name.ends_with(".yaml") {
416                    let b_mcard_name = file_name.trim_start_matches("b_mcard_").trim_end_matches(".yaml");
417                    let handle_name = format!("run:evolution:transition:{}", b_mcard_name);
418                    
419                    if let Ok(Some(_)) = crate::db::resolve_handle_hash("evolution", clm_root, &handle_name) {
420                        skipped_count += 1;
421                        continue;
422                    }
423                    
424                    let path_str = path.to_string_lossy().to_string();
425                    let val = match crate::parser::parse_manifest(&path_str) {
426                        Ok(v) => v,
427                        Err(e) => {
428                            failed_count += 1;
429                            println!("[EVOLVE STEP] Failed to parse B-MCard {:?}: {}", path, e);
430                            continue;
431                        }
432                    };
433                    
434                    let polyglot_cases = val.pointer("/clm/balanced_exp/polyglot_cases")
435                        .and_then(|v| v.as_array());
436                        
437                    if let Some(cases) = polyglot_cases {
438                        let mut b_mcard_ok = true;
439                        println!("[EVOLVE STEP] Verifying transition '{}'...", b_mcard_name);
440                        
441                        for case in cases {
442                            let name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed");
443                            let assertions = case.get("then").and_then(|v| v.as_array());
444                            
445                            if let Some(asserts) = assertions {
446                                for assertion in asserts {
447                                    if let Some(cmd_str) = assertion.get("assert_success").and_then(|v| v.as_str()) {
448                                        let mut command = std::process::Command::new("sh");
449                                        command.arg("-c").arg(cmd_str);
450                                        let output = match command.output() {
451                                            Ok(out) => out,
452                                            Err(e) => {
453                                                b_mcard_ok = false;
454                                                println!("  ❌ Case '{}' failed: could not execute: {}", name, e);
455                                                break;
456                                            }
457                                        };
458                                        if !output.status.success() {
459                                            b_mcard_ok = false;
460                                            println!("  ❌ Case '{}' failed (exit code = {}).", name, output.status.code().unwrap_or(1));
461                                            let stderr = String::from_utf8_lossy(&output.stderr);
462                                            if !stderr.is_empty() {
463                                                println!("     Stderr: {}", stderr.trim());
464                                            }
465                                            break;
466                                        } else {
467                                            println!("  ✅ Case '{}' assertion passed.", name);
468                                        }
469                                    }
470                                }
471                            }
472                            if !b_mcard_ok {
473                                break;
474                            }
475                        }
476                        
477                        if b_mcard_ok {
478                            let g_time = crate::fs_utils::compute_g_time();
479                            let sponsor_did = std::env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:pkc:ca:darwin:root-agent".to_string());
480                            let pre_hash = val.pointer("/clm/abstract_spec/invariants/preconditions")
481                                .and_then(|v| v.as_array())
482                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
483                                .unwrap_or_default();
484                            let post_hash = val.pointer("/clm/abstract_spec/invariants/postconditions")
485                                .and_then(|v| v.as_array())
486                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
487                                .unwrap_or_default();
488                                
489                            let vcard_content = format!(
490                                "vcard:\n  g_time: \"{}\"\n  transition: \"{}\"\n  status: \"VERIFIED\"\n  pre_hash: \"{}\"\n  post_hash: \"{}\"\n  sponsor_did: \"{}\"\n",
491                                g_time, b_mcard_name, pre_hash, post_hash, sponsor_did
492                            );
493                            let content_hash = crate::fs_utils::compute_content_hash(&vcard_content);
494                            
495                            if let Err(e) = crate::db::handle_register_batch(
496                                "evolution",
497                                clm_root,
498                                &handle_name,
499                                &crate::hash::prefixed(&content_hash),
500                                &vcard_content,
501                            ) {
502                                failed_count += 1;
503                                println!("[EVOLVE STEP] Failed to register transition handle: {}", e);
504                            } else {
505                                executed_count += 1;
506                                println!("[EVOLVE STEP] Verified and registered transition '{}'.", b_mcard_name);
507                            }
508                        } else {
509                            failed_count += 1;
510                        }
511                    }
512                }
513            }
514            
515            Ok(format!(
516                "[EVOLVE STEP] Completed. Executed: {}, Skipped: {}, Failed: {}\n",
517                executed_count, skipped_count, failed_count
518            ))
519        }
520        EvolveCommands::Report => {
521            generate_evolution_audit_report(clm_root)
522        }
523    }
524}
525
526pub fn generate_evolution_audit_report(clm_root: &str) -> Result<String, String> {
527    let mut table_rows = Vec::new();
528    
529    if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
530        let mut stmt = match conn.prepare(
531            "SELECT hr.handle, hr.current_hash, hr.updated_at, c.content \
532             FROM handle_registry hr \
533             JOIN card c ON hr.current_hash = c.hash \
534             WHERE hr.handle LIKE 'run:evolution:transition:%' \
535             ORDER BY hr.updated_at ASC;"
536        ) {
537            Ok(s) => s,
538            Err(e) => return Err(e.to_string()),
539        };
540        
541        let mut rows = match stmt.query([]) {
542            Ok(r) => r,
543            Err(e) => return Err(e.to_string()),
544        };
545        
546        while let Ok(Some(row)) = rows.next() {
547            let handle: String = row.get(0).unwrap_or_default();
548            let _current_hash: String = row.get(1).unwrap_or_default();
549            let updated_at: String = row.get(2).unwrap_or_default();
550            let content: String = row.get(3).unwrap_or_default();
551            
552            let mut transition = handle.trim_start_matches("run:evolution:transition:").to_string();
553            let mut status = "UNKNOWN".to_string();
554            let mut sponsor_did = "UNKNOWN".to_string();
555            let mut pre_hash = "UNKNOWN".to_string();
556            let mut post_hash = "UNKNOWN".to_string();
557            
558            for line in content.lines() {
559                let line_trimmed = line.trim();
560                if line_trimmed.starts_with("transition:") {
561                    transition = line_trimmed.trim_start_matches("transition:").trim_matches('"').trim().to_string();
562                } else if line_trimmed.starts_with("status:") {
563                    status = line_trimmed.trim_start_matches("status:").trim_matches('"').trim().to_string();
564                } else if line_trimmed.starts_with("sponsor_did:") {
565                    sponsor_did = line_trimmed.trim_start_matches("sponsor_did:").trim_matches('"').trim().to_string();
566                } else if line_trimmed.starts_with("pre_hash:") {
567                    pre_hash = line_trimmed.trim_start_matches("pre_hash:").trim_matches('"').trim().to_string();
568                } else if line_trimmed.starts_with("post_hash:") {
569                    post_hash = line_trimmed.trim_start_matches("post_hash:").trim_matches('"').trim().to_string();
570                }
571            }
572            
573            table_rows.push(format!(
574                "| {} | {} | {} | {} | `{}` | `{}` |",
575                updated_at, transition, status, sponsor_did, pre_hash, post_hash
576            ));
577        }
578    }
579    
580    let rows_str = if table_rows.is_empty() {
581        "No transitions recorded in the current epoch.\n".to_string()
582    } else {
583        let mut table = "| Timestamp | Transition | Status | Sponsor DID | Pre Ingress Hash | Post Egress Hash |\n".to_string();
584        table.push_str("| --- | --- | --- | --- | --- | --- |\n");
585        for r in table_rows {
586            table.push_str(&r);
587            table.push('\n');
588        }
589        table
590    };
591    
592    let report_content = format!(
593        "# CLM Evolution Audit Report\n\n\
594         Generated: {}\n\n\
595         ## Verified Transitions\n\n\
596         {}\n",
597        chrono::Local::now().to_rfc2822(),
598        rows_str
599    );
600    
601    let path = Path::new(clm_root).join("docs/spec/consensus_audit_report.md");
602    if let Some(parent) = path.parent() {
603        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
604    }
605    std::fs::write(&path, &report_content).map_err(|e| e.to_string())?;
606    
607    Ok(format!("Evolution audit report generated at: {:?}", path))
608}