clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
// manifest.rs — DotSlash-style executable manifest resolver (GAP-15)
//
// Resolves runtime binaries via declarative manifests stored as MCards in the
// content_memory pillar. Each manifest maps platform identifiers to binary
// entries with provider chains, content hash verification, and read-only
// caching.
//
// Public API:
//   resolve_binary(handle, clm_root) -> Result<PathBuf, String>
//   detect_platform() -> String
//   verify_hash(path, expected_hash) -> Result<(), String>
//   cache_binary(source, hash) -> Result<PathBuf, String>

use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use sha2::{Sha256, Digest};
use serde::Deserialize;

use crate::db;

/// Archive format for downloaded artifacts.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ArchiveFormat {
    Raw,
    TarGz,
    Zip,
}

impl std::fmt::Display for ArchiveFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ArchiveFormat::Raw => write!(f, "raw"),
            ArchiveFormat::TarGz => write!(f, "tar.gz"),
            ArchiveFormat::Zip => write!(f, "zip"),
        }
    }
}

/// Provider entry in a platform's provider chain.
#[derive(Debug, Clone, Deserialize)]
pub struct Provider {
    #[serde(rename = "type")]
    pub provider_type: String,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub path: Option<String>,
}

/// Platform-specific binary entry in the manifest.
#[derive(Debug, Clone, Deserialize)]
pub struct PlatformEntry {
    pub path: String,
    pub hash: String,
    pub size: u64,
    pub format: ArchiveFormat,
    pub providers: Vec<Provider>,
}

/// Executable manifest mapping platform identifiers to binary entries.
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutableManifest {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    pub platforms: std::collections::HashMap<String, PlatformEntry>,
}

/// Detect the current platform identifier (e.g., "darwin-arm64", "linux-x86_64").
pub fn detect_platform() -> String {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    match (os, arch) {
        ("macos", "aarch64") => "darwin-arm64".to_string(),
        ("macos", "x86_64") => "darwin-x86_64".to_string(),
        ("linux", "x86_64") => "linux-x86_64".to_string(),
        ("windows", "x86_64") => "windows-amd64".to_string(),
        _ => format!("{}-{}", os, arch),
    }
}

/// Compute SHA-256 hash of a file, returning hex string.
pub fn compute_file_hash(path: &Path) -> Result<String, String> {
    let mut file = fs::File::open(path)
        .map_err(|e| format!("Failed to open file {:?}: {}", path, e))?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];
    loop {
        let n = file.read(&mut buffer)
            .map_err(|e| format!("Failed to read file: {}", e))?;
        if n == 0 {
            break;
        }
        hasher.update(&buffer[..n]);
    }
    Ok(format!("{:x}", hasher.finalize()))
}

/// Verify that a file's SHA-256 hash matches the expected hash.
pub fn verify_hash(path: &Path, expected_hash: &str) -> Result<(), String> {
    let actual = compute_file_hash(path)?;
    if actual == expected_hash {
        Ok(())
    } else {
        Err(format!(
            "Hash mismatch for {:?}: expected {}, got {}",
            path, expected_hash, actual
        ))
    }
}

/// Copy a binary to the read-only cache directory (~/.clm/cache/bin/<hash>).
/// Sets permissions to 0o555 on Unix. Returns the cached path.
pub fn cache_binary(source: &Path, hash: &str) -> Result<PathBuf, String> {
    let cache_dir = dirs_cache_dir()?;
    let cache_path = cache_dir.join(hash);

    if cache_path.exists() {
        // Cache hit — verify hash matches
        if verify_hash(&cache_path, hash).is_ok() {
            return Ok(cache_path);
        }
        // Hash mismatch — remove stale cache entry
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
        }
        let _ = fs::remove_file(&cache_path);
    }

    // Copy file to cache via a unique, writable temporary file
    fs::create_dir_all(&cache_dir)
        .map_err(|e| format!("Failed to create cache dir: {}", e))?;

    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let tmp_path = cache_dir.join(format!("{}.tmp.{}.{}", hash, std::process::id(), nonce));

    fs::copy(source, &tmp_path)
        .map_err(|e| format!("Failed to copy to cache tmp file: {}", e))?;

    // Move temporary file into place
    if let Err(_e) = fs::rename(&tmp_path, &cache_path) {
        let _ = fs::remove_file(&tmp_path);
        // If rename failed (e.g. destination existed and was read-only on BSD), verify or overwrite
        if verify_hash(&cache_path, hash).is_err() {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
            }
            let _ = fs::remove_file(&cache_path);
            let _ = fs::copy(source, &cache_path);
        }
    }

    // Set read-only permissions on final cache path
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = fs::Permissions::from_mode(0o555);
        let _ = fs::set_permissions(&cache_path, perms);
    }

    Ok(cache_path)
}

fn dirs_cache_dir() -> Result<PathBuf, String> {
    if let Ok(home) = crate::layer0::environment::var("HOME") {
        Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
    } else if let Ok(user_profile) = crate::layer0::environment::var("USERPROFILE") {
        Ok(PathBuf::from(user_profile).join(".clm").join("cache").join("bin"))
    } else {
        Ok(PathBuf::from("/tmp").join("clm-cache").join("bin"))
    }
}

/// Try to fetch a binary from a single provider.
fn fetch_from_provider(
    provider: &Provider,
    clm_root: &str,
    dest: &Path,
) -> Result<PathBuf, String> {
    match provider.provider_type.as_str() {
        "local" => {
            let local_path = provider.path.as_ref().ok_or("Local provider missing path")?;
            // Try relative to clm_root first, then absolute
            let candidate = if Path::new(local_path).is_absolute() {
                PathBuf::from(local_path)
            } else {
                PathBuf::from(clm_root).join(local_path)
            };
            if candidate.exists() && candidate.is_file() {
                // Copy to dest
                if dest != candidate {
                    fs::copy(&candidate, dest)
                        .map_err(|e| format!("Failed to copy from local provider: {}", e))?;
                }
                Ok(dest.to_path_buf())
            } else {
                Err(format!("Local provider path not found: {}", candidate.display()))
            }
        }
        "http" | "github-release" => {
            // HTTP/github-release providers require reqwest (not yet a dependency).
            // Future: add reqwest as optional dependency and implement download.
            Err(format!("Provider type '{}' not yet implemented (requires HTTP dependency)", provider.provider_type))
        }
        _ => Err(format!("Unknown provider type: {}", provider.provider_type)),
    }
}

/// Try each provider in the provider chain until one succeeds.
#[allow(dead_code)]
fn fetch_from_providers(
    providers: &[Provider],
    clm_root: &str,
    dest: &Path,
) -> Result<PathBuf, String> {
    let mut errors = Vec::new();
    for provider in providers {
        match fetch_from_provider(provider, clm_root, dest) {
            Ok(path) => return Ok(path),
            Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
        }
    }
    Err(format!("All providers failed: {}", errors.join("; ")))
}

/// Look up a manifest MCard by handle from the content_memory pillar.
pub fn lookup_manifest(handle: &str, clm_root: &str) -> Result<ExecutableManifest, String> {
    let content = db::resolve_handle_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, handle)
        .map_err(|e| format!("DB error looking up handle '{}': {}", handle, e))?
        .ok_or_else(|| format!("Handle '{}' not found in content_memory", handle))?;

    let manifest: ExecutableManifest = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse manifest JSON: {}", e))?;

    Ok(manifest)
}

/// Resolve a binary by handle via the executable manifest system.
///
/// 1. Look up the manifest MCard by handle in content_memory.
/// 2. Select the platform entry for the current OS/arch.
/// 3. Try each provider in the provider chain to fetch the binary.
/// 4. Verify the SHA-256 hash.
/// 5. Cache the binary in read-only mode.
/// 6. Return the cached path.
pub fn resolve_binary(handle: &str, clm_root: &str) -> Result<PathBuf, String> {
    let manifest = lookup_manifest(handle, clm_root)?;

    let platform = detect_platform();
    let entry = manifest.platforms.get(&platform)
        .ok_or_else(|| format!("Platform '{}' not found in manifest for handle '{}'", platform, handle))?;

    // Create temp destination for the fetched binary
    let temp_dir = std::env::temp_dir().join("clm-manifest-resolve");
    let _ = fs::create_dir_all(&temp_dir);
    let temp_dest = temp_dir.join(format!("{}_{}", handle.replace(':', "_"), &entry.hash[..12]));

    // Try providers — verify hash inside the loop so a mismatch falls through
    let mut errors = Vec::new();
    let fetched = {
        let mut result: Option<PathBuf> = None;
        for provider in &entry.providers {
            match fetch_from_provider(provider, clm_root, &temp_dest) {
                Ok(path) => {
                    // Verify hash (skip if hash is all zeros — placeholder)
                    if !entry.hash.chars().all(|c| c == '0') {
                        match verify_hash(&path, &entry.hash) {
                            Ok(()) => {
                                result = Some(path);
                                break;
                            }
                            Err(e) => {
                                errors.push(format!("{}: hash mismatch ({})", provider.provider_type, e));
                                continue;
                            }
                        }
                    } else {
                        result = Some(path);
                        break;
                    }
                }
                Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
            }
        }
        match result {
            Some(p) => p,
            None => return Err(format!("All providers failed: {}", errors.join("; "))),
        }
    };

    // Cache the binary
    let cached = cache_binary(&fetched, &entry.hash)?;

    // Clean up temp file if different from cached
    if cached != fetched {
        let _ = fs::remove_file(&fetched);
    }

    Ok(cached)
}

#[cfg(test)]
#[path = "manifest_tests.rs"]
mod tests;