clm-kernel 0.0.20

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::fs;
use std::path::{Path, PathBuf};
use std::io::{self, Read};

// Explicit SHA-256 computation for legacy/specific SHA-256 contracts.
pub fn compute_sha256_hex(content: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(content);
    format!("{:x}", hasher.finalize())
}

pub fn compute_content_hash(input: &str) -> String {
    if input == "-" {
        let mut buffer = Vec::new();
        let mut stdin = io::stdin();
        let _ = stdin.read_to_end(&mut buffer);
        crate::hash::raw_hash_bytes(&buffer)
    } else if let Ok(metadata) = fs::metadata(input) {
        if metadata.is_file()
            && let Ok(data) = fs::read(input) {
                return crate::hash::raw_hash_bytes(&data);
            }
        crate::hash::raw_hash_bytes(input.as_bytes())
    } else {
        crate::hash::raw_hash_bytes(input.as_bytes())
    }
}

pub fn compute_stripped_file_hash(path: &Path) -> io::Result<String> {
    let content = fs::read_to_string(path)?;
    // Emulate bash's $(cat file) which strips trailing newlines (\n and \r)
    let trimmed = content.trim_end_matches(['\n', '\r']);
    Ok(crate::hash::raw_hash_bytes(trimmed.as_bytes()))
}

pub fn get_file_handle(raw_path: &str, clm_root: Option<&str>) -> String {
    // 1. Resolve absolute path
    let path = Path::new(raw_path);
    let abs_path = if path.is_absolute() {
        path.to_path_buf()
    } else if let Ok(curr) = std::env::current_dir() {
        curr.join(path)
    } else {
        path.to_path_buf()
    };

    // 2. Canonicalize path representation (resolve parent dirs/dots, but keep as String)
    // We do clean normalization manually to avoid issues with non-existent paths.
    let mut components = Vec::new();
    for component in abs_path.components() {
        match component {
            std::path::Component::Prefix(prefix) => {
                // Windows prefix (e.g. C:) -> map to lowercase /c/
                let prefix_str = prefix.as_os_str().to_string_lossy().to_string();
                if prefix_str.len() >= 2 && prefix_str.ends_with(':') {
                    let drive = prefix_str[0..1].to_lowercase();
                    components.push(format!("/{}", drive));
                } else {
                    components.push(prefix_str);
                }
            }
            std::path::Component::RootDir => {
                // Root is implicit if components start with /
            }
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                components.pop();
            }
            std::path::Component::Normal(val) => {
                components.push(val.to_string_lossy().to_string());
            }
        }
    }

    let mut norm_abs = components.join("/");
    if !norm_abs.starts_with('/') {
        norm_abs = format!("/{}", norm_abs);
    }
    // Remove duplicate slashes
    while norm_abs.contains("//") {
        norm_abs = norm_abs.replace("//", "/");
    }
    if norm_abs.len() > 1 && norm_abs.ends_with('/') {
        norm_abs.pop();
    }

    // Normalize CLM_ROOT
    let root_path = clm_root.map(PathBuf::from).unwrap_or_else(|| {
        std::env::var("CLM_ROOT")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("."))
    });
    
    let abs_root = if root_path.is_absolute() {
        root_path
    } else if let Ok(curr) = std::env::current_dir() {
        curr.join(root_path)
    } else {
        root_path
    };

    let mut root_components = Vec::new();
    for component in abs_root.components() {
        match component {
            std::path::Component::Prefix(prefix) => {
                let prefix_str = prefix.as_os_str().to_string_lossy().to_string();
                if prefix_str.len() >= 2 && prefix_str.ends_with(':') {
                    let drive = prefix_str[0..1].to_lowercase();
                    root_components.push(format!("/{}", drive));
                } else {
                    root_components.push(prefix_str);
                }
            }
            std::path::Component::RootDir => {}
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                root_components.pop();
            }
            std::path::Component::Normal(val) => {
                root_components.push(val.to_string_lossy().to_string());
            }
        }
    }
    let mut norm_root = root_components.join("/");
    if !norm_root.starts_with('/') {
        norm_root = format!("/{}", norm_root);
    }
    while norm_root.contains("//") {
        norm_root = norm_root.replace("//", "/");
    }
    if norm_root.len() > 1 && norm_root.ends_with('/') {
        norm_root.pop();
    }

    // Check if norm_abs is under norm_root
    let rel_path = if norm_abs == norm_root {
        ".".to_string()
    } else if norm_abs.starts_with(&format!("{}/", norm_root)) {
        norm_abs[norm_root.len() + 1..].to_string()
    } else {
        // Fallback to filename
        path.file_name()
            .map(|f| f.to_string_lossy().to_string())
            .unwrap_or_default()
    };

    format!("file:{}", rel_path)
}

/// Stamps a canonical `g_time` coordinate under an explicit algorithm and timestamp.
pub fn compute_g_time_at(algorithm: &str, timestamp: &str, locale: &str) -> Result<String, String> {
    let algo = algorithm.trim().trim_end_matches(':').to_lowercase();
    if !crate::hash::list_algorithms()
        .iter()
        .any(|registered| registered.trim_end_matches(':') == algo)
    {
        return Err(format!("Unsupported g_time hash algorithm: {algo}"));
    }
    if locale.contains('|') {
        return Err("g_time locale cannot contain the pipe delimiter".to_string());
    }

    let parsed = match chrono::DateTime::parse_from_rfc3339(timestamp) {
        Ok(parsed) => parsed,
        Err(original_error) => {
            if timestamp.len() < 5 {
                return Err(format!("Invalid g_time timestamp: {original_error}"));
            }
            let offset_start = timestamp.len() - 5;
            let offset = &timestamp[offset_start..];
            if (offset.starts_with('+') || offset.starts_with('-'))
                && offset[1..].chars().all(|ch| ch.is_ascii_digit())
            {
                let normalized = format!("{}{}:{}", &timestamp[..offset_start], &offset[..3], &offset[3..]);
                chrono::DateTime::parse_from_rfc3339(&normalized)
                    .map_err(|error| format!("Invalid g_time timestamp: {error}"))?
            } else {
                return Err(format!("Invalid g_time timestamp: {original_error}"));
            }
        }
    };
    let canonical_timestamp = parsed.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
    Ok(format!("{algo}|{canonical_timestamp}|{locale}"))
}

/// Stamps a `g_time` coordinate under an explicit algorithm.
///
/// The algorithm is a parameter so the label always matches the function that produced the
/// digest. Grammar: `algorithm|timestamp|locale` (charter ยง3.1.1).
pub fn compute_g_time_for(algorithm: &str) -> String {
    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
    let tz_name = if let Ok(link) = std::fs::read_link("/etc/localtime") {
        if let Some(pos) = link.to_string_lossy().find("/zoneinfo/") {
            link.to_string_lossy()[pos + 10..].to_string()
        } else {
            "UTC".to_string()
        }
    } else {
        "UTC".to_string()
    };
    compute_g_time_at(algorithm, &now, &tz_name).expect("registered writer algorithm and timestamp")
}

/// Stamps a `g_time` coordinate under the runtime's resolved active hash policy.
pub fn compute_g_time() -> String {
    compute_g_time_for(crate::hash::config().active_algorithm)
}

pub fn get_clm_root() -> PathBuf {
    let raw = std::env::var("CLM_ROOT").unwrap_or_else(|_| ".".into());
    normalize_windows_path(Path::new(&raw))
}

pub fn get_data_dir(clm_root: &str, pillar: &str) -> PathBuf {
    let zero_fs = crate::utils::is_zero_fs();
    if zero_fs {
        let tmp = std::env::var("TMPDIR").unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().to_string());
        PathBuf::from(tmp).join("data").join(pillar)
    } else {
        Path::new(clm_root).join("data").join(pillar)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sha256() {
        assert_eq!(
            compute_sha256_hex(b"hello"),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }
}

pub fn get_bash_command() -> String {
    if cfg!(target_os = "windows") {
        if let Ok(bash_env) = std::env::var("BASH")
            && Path::new(&bash_env).exists() {
                return bash_env;
            }
        let git_bash = "C:\\Program Files\\Git\\bin\\bash.exe";
        if Path::new(git_bash).exists() {
            return git_bash.to_string();
        }
    }
    "bash".to_string()
}

pub fn normalize_windows_path(p: &Path) -> PathBuf {
    if cfg!(target_os = "windows") {
        let s = p.to_string_lossy().to_string();
        if s.starts_with('/') && s.len() >= 3 && s.chars().nth(2) == Some('/') {
            let drive = s.chars().nth(1).unwrap().to_uppercase().to_string();
            let rest = &s[2..];
            return PathBuf::from(format!("{}:{}", drive, rest));
        } else if s.starts_with('/') && s.len() == 2 {
            let drive = s.chars().nth(1).unwrap().to_uppercase().to_string();
            return PathBuf::from(format!("{}:\\", drive));
        }
    }
    p.to_path_buf()
}