clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::layer0::vocabulary::{HANDLE_MCARD};
use std::fs;
use std::path::Path;
use crate::utils::indent_lines;


pub fn file_to_mcard(source_file: &str, output_dir: &str, clm_root: &str) -> Result<String, String> {
    let source_path = Path::new(source_file);
    if !source_path.exists() {
        return Err(format!("[MCARD_ENC] ❌ File not found: {}", source_file));
    }

    let file_bytes = fs::read(source_path)
        .map_err(|e| format!("Failed to read source file: {}", e))?;
    let file_size = file_bytes.len();

    let filename = source_path.file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_default();

    // 1. Compute content_hash (delegates to central hash module — INV-02)
    let content_hash = crate::hash::raw_hash_bytes(&file_bytes);

    // 2. Compute g_time
    let g_time = crate::fs_utils::compute_g_time();
    let unix_ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    // 3. Load dynamic content types and detect MIME type
    let ext_hint = source_path.extension().and_then(|s| s.to_str()).unwrap_or("").to_lowercase();
    let mime_type = crate::mime::detect_mime(&file_bytes, &ext_hint, clm_root);

    // 4. Determine if binary vs text
    let is_binary = crate::mime::is_binary(&file_bytes);

    // 5. Select encoding and content representation
    let (content_encoding, content) = if is_binary {
        let b64 = base64_encode(&file_bytes);
        ("base64", b64)
    } else {
        let content_str = String::from_utf8_lossy(&file_bytes).into_owned();
        let line_count = content_str.lines().count();
        if line_count < 64 {
            ("inline", content_str)
        } else {
            ("sha256_ref", crate::hash::prefixed(&content_hash))
        }
    };

    // 6. Write output file
    let out_dir = Path::new(output_dir);
    let _ = fs::create_dir_all(out_dir);
    let mcard_file = out_dir.join(format!("mcard_{}_{}.yaml", unix_ts, &content_hash[..8]));

    // Format content block
    let content_block = match content_encoding {
        "inline" => {
            format!("  content: |\n{}", indent_lines(&content, 4))
        }
        "base64" => {
            let folded = fold_string(&content, 76);
            format!("  content: |\n{}", indent_lines(&folded, 4))
        }
        _ => {
            format!("  content: \"{}\"", content.as_str())
        }
    };

    let mcard_yaml = format!(
        "{HANDLE_MCARD}\n  g_time: \"{}\"\n  content_hash: \"{}\"\n  source:\n    filename: \"{}\"\n    mime_type: \"{}\"\n    size_bytes: {}\n    encoding: \"{}\"\n{}",
        g_time, content_hash, filename, mime_type, file_size, content_encoding, content_block
    );

    fs::write(&mcard_file, mcard_yaml)
        .map_err(|e| format!("Failed to write MCard file: {}", e))?;

    // Print standard output logs matching legacy script
    if is_binary {
        eprintln!("[MCARD_ENC] Binary file detected ({}, {} bytes)", mime_type, file_size);
    } else {
        let line_count = String::from_utf8_lossy(&file_bytes).lines().count();
        if line_count < 64 {
            eprintln!("[MCARD_ENC] Small text file ({} lines, {} bytes)", line_count, file_size);
        } else {
            eprintln!("[MCARD_ENC] Large text file ({} lines) — stored as hash reference", line_count);
        }
    }

    let mcard_path_str = mcard_file.to_string_lossy().to_string();
    println!("[MCARD_ENC] ✅ MCard generated: {}", mcard_path_str);
    println!("[MCARD_ENC]   source:       {} ({})", filename, mime_type);
    println!("[MCARD_ENC]   encoding:     {}", content_encoding);
    println!("[MCARD_ENC]   content_hash: {}", content_hash);
    println!("[MCARD_ENC]   g_time:       {}", g_time);
    println!("[MCARD_ENC]   size:         {} bytes", file_size);

    Ok(mcard_path_str)
}

fn base64_encode(data: &[u8]) -> String {
    // Hand-rolled base64 encoder to avoid adding external base64 crate dependency
    const CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut result = String::new();
    let mut i = 0;
    while i < data.len() {
        let chunk_len = std::cmp::min(data.len() - i, 3);
        let mut b = 0u32;
        for j in 0..chunk_len {
            b |= (data[i + j] as u32) << (16 - j * 8);
        }
        
        let enc1 = (b >> 18) & 63;
        let enc2 = (b >> 12) & 63;
        let enc3 = (b >> 6) & 63;
        let enc4 = b & 63;

        result.push(CHARSET[enc1 as usize] as char);
        result.push(CHARSET[enc2 as usize] as char);
        if chunk_len > 1 {
            result.push(CHARSET[enc3 as usize] as char);
        } else {
            result.push('=');
        }
        if chunk_len > 2 {
            result.push(CHARSET[enc4 as usize] as char);
        } else {
            result.push('=');
        }
        i += 3;
    }
    result
}

fn fold_string(s: &str, width: usize) -> String {
    let mut result = String::new();
    let mut i = 0;
    let chars: Vec<char> = s.chars().collect();
    while i < chars.len() {
        let chunk_len = std::cmp::min(chars.len() - i, width);
        let chunk: String = chars[i..i + chunk_len].iter().collect();
        result.push_str(&chunk);
        result.push('\n');
        i += width;
    }
    result
}