clm-kernel 0.0.0

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use std::fs;
use clap::Subcommand;
use std::io::Write;
use std::path::Path;
use std::time::SystemTime;

fn get_consolidated_mapping(fn_name: &str) -> Option<&'static str> {
    match fn_name {
        "mcard_utils" | "sql_repository" | "clm_path_utils" | "yaml_query" | "jsonl_emit" | "mcard_cache" | "memorize_mcard" => Some("mcard_storage.sh"),
        "sign_clm" | "evidence_lifecycle" | "verify_precondition" | "validate_postcondition" | "instantiate_contract_agent" => Some("mcard_verification.sh"),
        "baldwin_algebra" | "pcard_operators" | "decompose_clm" | "serialize_pcard" | "resolve_composite" | "symbol_extractor" | "clm_meta" => Some("clm_algebra.sh"),
        "init_tridb" | "register_core_pcards" => Some("clm_bootstrap.sh"),
        _ => None
    }
}

fn get_max_mtime_recursive(dir: &Path) -> Option<SystemTime> {
    let mut max_mtime = None;
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if let Some(mtime) = get_max_mtime_recursive(&path) {
                    max_mtime = Some(max_mtime.map_or(mtime, |max| std::cmp::max(max, mtime)));
                }
            } else if path.is_file() {
                if let Ok(meta) = fs::metadata(&path) {
                    if let Ok(mtime) = meta.modified() {
                        max_mtime = Some(max_mtime.map_or(mtime, |max| std::cmp::max(max, mtime)));
                    }
                }
            }
        }
    }
    max_mtime
}

fn is_cache_fresh(clm_root: &Path, cache_path: &Path) -> bool {
    let cache_mtime = match fs::metadata(cache_path).and_then(|m| m.modified()) {
        Ok(t) => t,
        Err(_) => return false,
    };

    let check_dirs = [
        clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator"),
        clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/governance"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer1_cpn_vm"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer2_storage"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer3_network"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator"),
        clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/governance"),
    ];

    for dir in &check_dirs {
        if dir.is_dir() {
            if let Some(mtime) = get_max_mtime_recursive(dir) {
                if mtime > cache_mtime {
                    return false;
                }
            }
        }
    }
    true
}

pub fn compile_evaluator_cache(clm_root: &Path, quiet: bool) -> Result<(), String> {
    let cache_path = clm_root.join("data/ipc/evaluator_cache.sh");
    if std::env::var("CLM_CACHE_FRESH").as_deref() == Ok("1") && cache_path.exists() {
        if !quiet {
            eprintln!("[clmEval-rs] Cache assumed fresh (CLM_CACHE_FRESH=1).");
        }
        return Ok(());
    }
    if is_cache_fresh(clm_root, &cache_path) {
        if !quiet {
            eprintln!("[clmEval-rs] Cache is up-to-date.");
        }
        return Ok(());
    }

    if !quiet {
        eprintln!("[clmEval-rs] Cache is stale or missing, compiling cache...");
    }

    let evaluator_dir = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator");
    let governance_dir = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/governance");

    let mut eval_files = Vec::new();
    if let Ok(entries) = fs::read_dir(&evaluator_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("yaml") {
                if path.file_name().and_then(|s| s.to_str()) != Some("clmEval.yaml") {
                    eval_files.push(path);
                }
            }
        }
    }
    eval_files.sort();

    let mut gov_files = Vec::new();
    if governance_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&governance_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("yaml") {
                    gov_files.push(path);
                }
            }
        }
    }
    gov_files.sort();

    let mut functions = Vec::new();
    let mut seen_master_files = std::collections::HashSet::new();

    let mut all_files = Vec::new();
    for f in eval_files {
        all_files.push(f);
    }
    for f in gov_files {
        all_files.push(f);
    }

    for fn_clm in all_files {
        let content = fs::read_to_string(&fn_clm)
            .map_err(|e| format!("Failed to read YAML file {:?}: {}", fn_clm, e))?;
        
        let data: serde_yaml::Value = serde_yaml::from_str(&content)
            .map_err(|e| format!("Failed to parse YAML from {:?}: {}", fn_clm, e))?;

        let clm_data = data.get("clm").unwrap_or(&data);
        let concrete_impl = match clm_data.get("concrete_impl") {
            Some(val) => val,
            None => continue,
        };

        let fn_name = match concrete_impl.get("operation").and_then(|v| v.as_str()) {
            Some(name) => name.to_string(),
            None => continue,
        };

        let process = match concrete_impl.get("process") {
            Some(p) => p,
            None => continue,
        };

        let (script_handle, script) = match process {
            serde_yaml::Value::Mapping(map) => {
                let handle = map.get("script_handle").and_then(|v| v.as_str()).map(|s| s.to_string());
                let script = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
                (handle, script)
            }
            serde_yaml::Value::Sequence(seq) => {
                let mut handle = None;
                let mut script = None;
                for val in seq {
                    if let serde_yaml::Value::Mapping(map) = val {
                        if map.get("type").and_then(|v| v.as_str()) == Some("shell") {
                            handle = map.get("script_handle").and_then(|v| v.as_str()).map(|s| s.to_string());
                            script = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
                            break;
                        }
                    }
                }
                (handle, script)
            }
            _ => (None, None),
        };

        let mut body = None;

        if let Some(ref handle_val) = script_handle {
            if handle_val != "null" {
                let mut sh_path = None;
                if let Some(master_file) = get_consolidated_mapping(&fn_name) {
                    let candidate = clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core").join(master_file);
                    if candidate.exists() {
                        sh_path = Some(candidate);
                    }
                }

                if sh_path.is_none() {
                    let filename = format!("{}.sh", fn_clm.file_stem().unwrap().to_string_lossy());
                    for layer in &["layer0_core", "layer1_cpn_vm", "layer2_storage", "layer3_network", "evaluator", "governance"] {
                        let candidate = clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap").join(layer).join(&filename);
                        if candidate.exists() {
                            sh_path = Some(candidate);
                            break;
                        }
                    }
                }

                if let Some(ref path) = sh_path {
                    if seen_master_files.contains(path) {
                        body = Some("".to_string());
                    } else {
                        match fs::read_to_string(path) {
                            Ok(content) => {
                                body = Some(content);
                                seen_master_files.insert(path.clone());
                            }
                            Err(e) => {
                                return Err(format!("Failed to read source file {:?}: {}", path, e));
                            }
                        }
                    }
                }
            }
        }

        if body.is_none() {
            body = script;
        }

        if let Some(body_content) = body {
            if body_content == "null" {
                continue;
            }
            functions.push((fn_name, body_content, fn_clm.clone()));
        }
    }

    let out_dir = clm_root.join("data/ipc");
    fs::create_dir_all(&out_dir).map_err(|e| format!("Failed to create directory {:?}: {}", out_dir, e))?;
    let mut out_file = fs::File::create(&cache_path).map_err(|e| format!("Failed to create file {:?}: {}", cache_path, e))?;

    writeln!(out_file, "#!/usr/bin/env bash")
        .map_err(|e| format!("Failed to write cache header: {}", e))?;
    writeln!(out_file, "# =============================================================================")
        .map_err(|e| format!("Failed to write cache header: {}", e))?;
    writeln!(out_file, "# Cubical Logic Model (CLM) Evaluator Cache")
        .map_err(|e| format!("Failed to write cache header: {}", e))?;
    writeln!(out_file, "# Generated automatically by clm_rust_core evaluate. DO NOT EDIT MANUALLY.")
        .map_err(|e| format!("Failed to write cache header: {}", e))?;
    writeln!(out_file, "# =============================================================================\n")
        .map_err(|e| format!("Failed to write cache header: {}", e))?;

    for (fn_name, body_content, fn_clm) in functions {
        let rel_path = match fn_clm.strip_prefix(clm_root) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => fn_clm.to_string_lossy().to_string(),
        };
        writeln!(out_file, "# --- Source: {} ---", rel_path)
            .map_err(|e| format!("Failed to write source comment: {}", e))?;
        let trimmed = body_content.trim();
        if !trimmed.is_empty() {
            let normalized = trimmed.replace("\r", "");
            writeln!(out_file, "{}", normalized)
                .map_err(|e| format!("Failed to write function body: {}", e))?;
        }
        writeln!(out_file, "export -f {}\n", fn_name)
            .map_err(|e| format!("Failed to write function export: {}", e))?;
    }

    if !quiet {
        eprintln!("[clmEval-rs] Cache compiled successfully.");
    }
    Ok(())
}

pub fn extract_bootstrap_script(clm_root: &Path) -> Result<String, String> {
    let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
    if !self_clm.exists() {
        return Err(format!("clmEval.yaml not found at {:?}", self_clm));
    }
    let content = fs::read_to_string(&self_clm)
        .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
    
    let data: serde_yaml::Value = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse clmEval.yaml: {}", e))?;
    
    let clm_data = data.get("clm").unwrap_or(&data);
    let concrete_impl = clm_data.get("concrete_impl").ok_or("No concrete_impl in clmEval.yaml")?;
    let process = concrete_impl.get("process").ok_or("No process in clmEval.yaml")?;
    
    let script = match process {
        serde_yaml::Value::Mapping(map) => {
            map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string())
        }
        serde_yaml::Value::Sequence(seq) => {
            let mut s = None;
            for val in seq {
                if let serde_yaml::Value::Mapping(map) = val {
                    if map.get("type").and_then(|v| v.as_str()) == Some("shell") {
                        s = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
                        break;
                    }
                }
            }
            s
        }
        _ => None,
    };
    
    script.ok_or_else(|| "Could not extract shell bootstrap script from clmEval.yaml".to_string())
}

#[derive(Subcommand, Debug, Clone)]
pub enum ToolCommands {
    #[command(name = "run")]
    Run {
        tool_handle: String,
        #[arg(long)]
        source_dir: Option<String>,
        #[arg(num_args = 0..)]
        args: Vec<String>,
    },
    #[command(name = "document")]
    Document,
}

#[derive(Subcommand, Debug, Clone)]
pub enum EvolveCommands {
    #[command(name = "status")]
    Status {
        #[arg(long)]
        timeslot: Option<String>,
    },
    #[command(name = "step")]
    Step,
    #[command(name = "report")]
    Report,
}

pub fn run_tool_dispatcher(cmd: ToolCommands, clm_root: &str) -> Result<String, String> {
    match cmd {
        ToolCommands::Run { tool_handle, source_dir, args } => {
            let clm_path = Path::new(clm_root);
            
            // Map tool handle to yaml file, e.g., tool:foo -> tool_foo.yaml
            let yaml_filename = format!("{}.yaml", tool_handle.replace(":", "_"));
            let yaml_path = clm_path.join("types/governance").join(&yaml_filename);
            
            if !yaml_path.exists() {
                return Err(format!("[ERROR] Tool spec not found: {:?}", yaml_path));
            }
            
            let yaml_content = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
            let spec: serde_yaml::Value = serde_yaml::from_str(&yaml_content).map_err(|e| e.to_string())?;
            
            let script_val = spec.get("clm")
                .and_then(|v| v.get("concrete_impl"))
                .and_then(|v| v.get("process"))
                .and_then(|v| v.get("script"))
                .and_then(|v| v.as_str());
                
            if let Some(script_rel_path) = script_val {
                let script_path = clm_path.join(script_rel_path);
                if !script_path.exists() {
                    return Err(format!("[ERROR] Script not found: {:?}", script_path));
                }
                
                let mut cmd = std::process::Command::new("python3");
                cmd.arg(&script_path);
                
                if let Some(dir) = source_dir {
                    cmd.arg("--source_dir");
                    cmd.arg(&dir);
                }
                for arg in args {
                    cmd.arg(&arg);
                }
                
                let res = cmd.output().map_err(|e| e.to_string())?;
                let mut out = format!("[TOOL DISPATCHER] Executed tool: {}\n", tool_handle);
                out.push_str(&String::from_utf8_lossy(&res.stdout));
                if !res.stderr.is_empty() {
                    out.push_str("\n[STDERR]\n");
                    out.push_str(&String::from_utf8_lossy(&res.stderr));
                }
                Ok(out)
            } else {
                Err(format!("[ERROR] Invalid tool spec in {:?}: missing clm.concrete_impl.process.script", yaml_path))
            }
        }
        ToolCommands::Document => {
            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())
        }
    }
}

pub fn run_evolve_dispatcher(cmd: EvolveCommands, clm_root: &str) -> Result<String, String> {
    match cmd {
        EvolveCommands::Status { timeslot } => {
            let slot = timeslot.unwrap_or_else(|| {
                let now = chrono::Local::now();
                let iso_week = chrono::Datelike::iso_week(&now);
                format!("{:04}_w{:02}", iso_week.year(), iso_week.week())
            });
            let db_name = format!("pkc_evol_{}.db", slot);
            
            let count = if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
                conn.query_row(
                    "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE 'run:evolution:transition:%'",
                    [],
                    |row| row.get::<_, i64>(0)
                ).unwrap_or(0)
            } else {
                0
            };
            
            Ok(format!(
                "[EVOLVE STATUS] Active Time-Slot: {}\nDatabase: {}\nVerified Transitions: {}\nStatus: Ready for next step.\n",
                slot, db_name, count
            ))
        }
        EvolveCommands::Step => {
            let gov_dir = Path::new(clm_root).join("types/governance");
            if !gov_dir.exists() {
                return Err(format!("Governance directory not found: {:?}", gov_dir));
            }
            
            let mut executed_count = 0;
            let mut failed_count = 0;
            let mut skipped_count = 0;
            
            for entry in fs::read_dir(&gov_dir).map_err(|e| e.to_string())? {
                let entry = entry.map_err(|e| e.to_string())?;
                let path = entry.path();
                let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
                
                if file_name.starts_with("b_mcard_") && file_name.ends_with(".yaml") {
                    let b_mcard_name = file_name.trim_start_matches("b_mcard_").trim_end_matches(".yaml");
                    let handle_name = format!("run:evolution:transition:{}", b_mcard_name);
                    
                    if let Ok(Some(_)) = crate::db::resolve_handle_hash("evolution", clm_root, &handle_name) {
                        skipped_count += 1;
                        continue;
                    }
                    
                    let path_str = path.to_string_lossy().to_string();
                    let val = match crate::parser::parse_manifest(&path_str) {
                        Ok(v) => v,
                        Err(e) => {
                            failed_count += 1;
                            println!("[EVOLVE STEP] Failed to parse B-MCard {:?}: {}", path, e);
                            continue;
                        }
                    };
                    
                    let polyglot_cases = val.pointer("/clm/balanced_exp/polyglot_cases")
                        .and_then(|v| v.as_array());
                        
                    if let Some(cases) = polyglot_cases {
                        let mut b_mcard_ok = true;
                        println!("[EVOLVE STEP] Verifying transition '{}'...", b_mcard_name);
                        
                        for case in cases {
                            let name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed");
                            let assertions = case.get("then").and_then(|v| v.as_array());
                            
                            if let Some(asserts) = assertions {
                                for assertion in asserts {
                                    if let Some(cmd_str) = assertion.get("assert_success").and_then(|v| v.as_str()) {
                                        let mut command = std::process::Command::new("sh");
                                        command.arg("-c").arg(cmd_str);
                                        let output = match command.output() {
                                            Ok(out) => out,
                                            Err(e) => {
                                                b_mcard_ok = false;
                                                println!("  ❌ Case '{}' failed: could not execute: {}", name, e);
                                                break;
                                            }
                                        };
                                        if !output.status.success() {
                                            b_mcard_ok = false;
                                            println!("  ❌ Case '{}' failed (exit code = {}).", name, output.status.code().unwrap_or(1));
                                            let stderr = String::from_utf8_lossy(&output.stderr);
                                            if !stderr.is_empty() {
                                                println!("     Stderr: {}", stderr.trim());
                                            }
                                            break;
                                        } else {
                                            println!("  ✅ Case '{}' assertion passed.", name);
                                        }
                                    }
                                }
                            }
                            if !b_mcard_ok {
                                break;
                            }
                        }
                        
                        if b_mcard_ok {
                            let g_time = crate::fs_utils::compute_g_time();
                            let sponsor_did = std::env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:pkc:ca:darwin:root-agent".to_string());
                            let pre_hash = val.pointer("/clm/abstract_spec/invariants/preconditions")
                                .and_then(|v| v.as_array())
                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
                                .unwrap_or_default();
                            let post_hash = val.pointer("/clm/abstract_spec/invariants/postconditions")
                                .and_then(|v| v.as_array())
                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
                                .unwrap_or_default();
                                
                            let vcard_content = format!(
                                "vcard:\n  g_time: \"{}\"\n  transition: \"{}\"\n  status: \"VERIFIED\"\n  pre_hash: \"{}\"\n  post_hash: \"{}\"\n  sponsor_did: \"{}\"\n",
                                g_time, b_mcard_name, pre_hash, post_hash, sponsor_did
                            );
                            let content_hash = crate::fs_utils::compute_content_hash(&vcard_content);
                            
                            if let Err(e) = crate::db::handle_register_batch(
                                "evolution",
                                clm_root,
                                &handle_name,
                                &crate::hash::prefixed(&content_hash),
                                &vcard_content,
                            ) {
                                failed_count += 1;
                                println!("[EVOLVE STEP] Failed to register transition handle: {}", e);
                            } else {
                                executed_count += 1;
                                println!("[EVOLVE STEP] Verified and registered transition '{}'.", b_mcard_name);
                            }
                        } else {
                            failed_count += 1;
                        }
                    }
                }
            }
            
            Ok(format!(
                "[EVOLVE STEP] Completed. Executed: {}, Skipped: {}, Failed: {}\n",
                executed_count, skipped_count, failed_count
            ))
        }
        EvolveCommands::Report => {
            generate_evolution_audit_report(clm_root)
        }
    }
}

pub fn generate_evolution_audit_report(clm_root: &str) -> Result<String, String> {
    let mut table_rows = Vec::new();
    
    if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
        let mut stmt = match conn.prepare(
            "SELECT hr.handle, hr.current_hash, hr.updated_at, c.content \
             FROM handle_registry hr \
             JOIN card c ON hr.current_hash = c.hash \
             WHERE hr.handle LIKE 'run:evolution:transition:%' \
             ORDER BY hr.updated_at ASC;"
        ) {
            Ok(s) => s,
            Err(e) => return Err(e.to_string()),
        };
        
        let mut rows = match stmt.query([]) {
            Ok(r) => r,
            Err(e) => return Err(e.to_string()),
        };
        
        while let Ok(Some(row)) = rows.next() {
            let handle: String = row.get(0).unwrap_or_default();
            let _current_hash: String = row.get(1).unwrap_or_default();
            let updated_at: String = row.get(2).unwrap_or_default();
            let content: String = row.get(3).unwrap_or_default();
            
            let mut transition = handle.trim_start_matches("run:evolution:transition:").to_string();
            let mut status = "UNKNOWN".to_string();
            let mut sponsor_did = "UNKNOWN".to_string();
            let mut pre_hash = "UNKNOWN".to_string();
            let mut post_hash = "UNKNOWN".to_string();
            
            for line in content.lines() {
                let line_trimmed = line.trim();
                if line_trimmed.starts_with("transition:") {
                    transition = line_trimmed.trim_start_matches("transition:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("status:") {
                    status = line_trimmed.trim_start_matches("status:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("sponsor_did:") {
                    sponsor_did = line_trimmed.trim_start_matches("sponsor_did:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("pre_hash:") {
                    pre_hash = line_trimmed.trim_start_matches("pre_hash:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("post_hash:") {
                    post_hash = line_trimmed.trim_start_matches("post_hash:").trim_matches('"').trim().to_string();
                }
            }
            
            table_rows.push(format!(
                "| {} | {} | {} | {} | `{}` | `{}` |",
                updated_at, transition, status, sponsor_did, pre_hash, post_hash
            ));
        }
    }
    
    let rows_str = if table_rows.is_empty() {
        "No transitions recorded in the current epoch.\n".to_string()
    } else {
        let mut table = "| Timestamp | Transition | Status | Sponsor DID | Pre Ingress Hash | Post Egress Hash |\n".to_string();
        table.push_str("| --- | --- | --- | --- | --- | --- |\n");
        for r in table_rows {
            table.push_str(&r);
            table.push_str("\n");
        }
        table
    };
    
    let report_content = format!(
        "# CLM Evolution Audit Report\n\n\
         Generated: {}\n\n\
         ## Verified Transitions\n\n\
         {}\n",
        chrono::Local::now().to_rfc2822(),
        rows_str
    );
    
    let path = Path::new(clm_root).join("docs/spec/consensus_audit_report.md");
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    std::fs::write(&path, &report_content).map_err(|e| e.to_string())?;
    
    Ok(format!("Evolution audit report generated at: {:?}", path))
}