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