Skip to main content

clm_rust_core/layer2/
manifest.rs

1// manifest.rs — DotSlash-style executable manifest resolver (GAP-15)
2//
3// Resolves runtime binaries via declarative manifests stored as MCards in the
4// content_memory pillar. Each manifest maps platform identifiers to binary
5// entries with provider chains, content hash verification, and read-only
6// caching.
7//
8// Public API:
9//   resolve_binary(handle, clm_root) -> Result<PathBuf, String>
10//   detect_platform() -> String
11//   verify_hash(path, expected_hash) -> Result<(), String>
12//   cache_binary(source, hash) -> Result<PathBuf, String>
13
14use std::fs;
15use std::io::Read;
16use std::path::{Path, PathBuf};
17use sha2::{Sha256, Digest};
18use serde::Deserialize;
19
20use crate::db;
21
22/// Archive format for downloaded artifacts.
23#[derive(Debug, Clone, PartialEq, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum ArchiveFormat {
26    Raw,
27    TarGz,
28    Zip,
29}
30
31impl std::fmt::Display for ArchiveFormat {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            ArchiveFormat::Raw => write!(f, "raw"),
35            ArchiveFormat::TarGz => write!(f, "tar.gz"),
36            ArchiveFormat::Zip => write!(f, "zip"),
37        }
38    }
39}
40
41/// Provider entry in a platform's provider chain.
42#[derive(Debug, Clone, Deserialize)]
43pub struct Provider {
44    #[serde(rename = "type")]
45    pub provider_type: String,
46    #[serde(default)]
47    pub url: Option<String>,
48    #[serde(default)]
49    pub path: Option<String>,
50}
51
52/// Platform-specific binary entry in the manifest.
53#[derive(Debug, Clone, Deserialize)]
54pub struct PlatformEntry {
55    pub path: String,
56    pub hash: String,
57    pub size: u64,
58    pub format: ArchiveFormat,
59    pub providers: Vec<Provider>,
60}
61
62/// Executable manifest mapping platform identifiers to binary entries.
63#[derive(Debug, Clone, Deserialize)]
64pub struct ExecutableManifest {
65    #[serde(default)]
66    pub name: Option<String>,
67    #[serde(default)]
68    pub version: Option<String>,
69    pub platforms: std::collections::HashMap<String, PlatformEntry>,
70}
71
72/// Detect the current platform identifier (e.g., "darwin-arm64", "linux-x86_64").
73pub fn detect_platform() -> String {
74    let os = std::env::consts::OS;
75    let arch = std::env::consts::ARCH;
76    match (os, arch) {
77        ("macos", "aarch64") => "darwin-arm64".to_string(),
78        ("macos", "x86_64") => "darwin-x86_64".to_string(),
79        ("linux", "x86_64") => "linux-x86_64".to_string(),
80        ("windows", "x86_64") => "windows-amd64".to_string(),
81        _ => format!("{}-{}", os, arch),
82    }
83}
84
85/// Compute SHA-256 hash of a file, returning hex string.
86pub fn compute_file_hash(path: &Path) -> Result<String, String> {
87    let mut file = fs::File::open(path)
88        .map_err(|e| format!("Failed to open file {:?}: {}", path, e))?;
89    let mut hasher = Sha256::new();
90    let mut buffer = [0u8; 8192];
91    loop {
92        let n = file.read(&mut buffer)
93            .map_err(|e| format!("Failed to read file: {}", e))?;
94        if n == 0 {
95            break;
96        }
97        hasher.update(&buffer[..n]);
98    }
99    Ok(format!("{:x}", hasher.finalize()))
100}
101
102/// Verify that a file's SHA-256 hash matches the expected hash.
103pub fn verify_hash(path: &Path, expected_hash: &str) -> Result<(), String> {
104    let actual = compute_file_hash(path)?;
105    if actual == expected_hash {
106        Ok(())
107    } else {
108        Err(format!(
109            "Hash mismatch for {:?}: expected {}, got {}",
110            path, expected_hash, actual
111        ))
112    }
113}
114
115/// Copy a binary to the read-only cache directory (~/.clm/cache/bin/<hash>).
116/// Sets permissions to 0o555 on Unix. Returns the cached path.
117pub fn cache_binary(source: &Path, hash: &str) -> Result<PathBuf, String> {
118    let cache_dir = dirs_cache_dir()?;
119    let cache_path = cache_dir.join(hash);
120
121    if cache_path.exists() {
122        // Cache hit — verify hash matches
123        if verify_hash(&cache_path, hash).is_ok() {
124            return Ok(cache_path);
125        }
126        // Hash mismatch — remove stale cache entry
127        #[cfg(unix)]
128        {
129            use std::os::unix::fs::PermissionsExt;
130            let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
131        }
132        let _ = fs::remove_file(&cache_path);
133    }
134
135    // Copy file to cache via a unique, writable temporary file
136    fs::create_dir_all(&cache_dir)
137        .map_err(|e| format!("Failed to create cache dir: {}", e))?;
138
139    let nonce = std::time::SystemTime::now()
140        .duration_since(std::time::UNIX_EPOCH)
141        .map(|d| d.as_nanos())
142        .unwrap_or(0);
143    let tmp_path = cache_dir.join(format!("{}.tmp.{}.{}", hash, std::process::id(), nonce));
144
145    fs::copy(source, &tmp_path)
146        .map_err(|e| format!("Failed to copy to cache tmp file: {}", e))?;
147
148    // Move temporary file into place
149    if let Err(_e) = fs::rename(&tmp_path, &cache_path) {
150        let _ = fs::remove_file(&tmp_path);
151        // If rename failed (e.g. destination existed and was read-only on BSD), verify or overwrite
152        if verify_hash(&cache_path, hash).is_err() {
153            #[cfg(unix)]
154            {
155                use std::os::unix::fs::PermissionsExt;
156                let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
157            }
158            let _ = fs::remove_file(&cache_path);
159            let _ = fs::copy(source, &cache_path);
160        }
161    }
162
163    // Set read-only permissions on final cache path
164    #[cfg(unix)]
165    {
166        use std::os::unix::fs::PermissionsExt;
167        let perms = fs::Permissions::from_mode(0o555);
168        let _ = fs::set_permissions(&cache_path, perms);
169    }
170
171    Ok(cache_path)
172}
173
174fn dirs_cache_dir() -> Result<PathBuf, String> {
175    if let Ok(home) = crate::layer0::environment::var("HOME") {
176        Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
177    } else if let Ok(user_profile) = crate::layer0::environment::var("USERPROFILE") {
178        Ok(PathBuf::from(user_profile).join(".clm").join("cache").join("bin"))
179    } else {
180        Ok(PathBuf::from("/tmp").join("clm-cache").join("bin"))
181    }
182}
183
184/// Try to fetch a binary from a single provider.
185fn fetch_from_provider(
186    provider: &Provider,
187    clm_root: &str,
188    dest: &Path,
189) -> Result<PathBuf, String> {
190    match provider.provider_type.as_str() {
191        "local" => {
192            let local_path = provider.path.as_ref().ok_or("Local provider missing path")?;
193            // Try relative to clm_root first, then absolute
194            let candidate = if Path::new(local_path).is_absolute() {
195                PathBuf::from(local_path)
196            } else {
197                PathBuf::from(clm_root).join(local_path)
198            };
199            if candidate.exists() && candidate.is_file() {
200                // Copy to dest
201                if dest != candidate {
202                    fs::copy(&candidate, dest)
203                        .map_err(|e| format!("Failed to copy from local provider: {}", e))?;
204                }
205                Ok(dest.to_path_buf())
206            } else {
207                Err(format!("Local provider path not found: {}", candidate.display()))
208            }
209        }
210        "http" | "github-release" => {
211            // HTTP/github-release providers require reqwest (not yet a dependency).
212            // Future: add reqwest as optional dependency and implement download.
213            Err(format!("Provider type '{}' not yet implemented (requires HTTP dependency)", provider.provider_type))
214        }
215        _ => Err(format!("Unknown provider type: {}", provider.provider_type)),
216    }
217}
218
219/// Try each provider in the provider chain until one succeeds.
220#[allow(dead_code)]
221fn fetch_from_providers(
222    providers: &[Provider],
223    clm_root: &str,
224    dest: &Path,
225) -> Result<PathBuf, String> {
226    let mut errors = Vec::new();
227    for provider in providers {
228        match fetch_from_provider(provider, clm_root, dest) {
229            Ok(path) => return Ok(path),
230            Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
231        }
232    }
233    Err(format!("All providers failed: {}", errors.join("; ")))
234}
235
236/// Look up a manifest MCard by handle from the content_memory pillar.
237pub fn lookup_manifest(handle: &str, clm_root: &str) -> Result<ExecutableManifest, String> {
238    let content = db::resolve_handle_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, handle)
239        .map_err(|e| format!("DB error looking up handle '{}': {}", handle, e))?
240        .ok_or_else(|| format!("Handle '{}' not found in content_memory", handle))?;
241
242    let manifest: ExecutableManifest = serde_json::from_str(&content)
243        .map_err(|e| format!("Failed to parse manifest JSON: {}", e))?;
244
245    Ok(manifest)
246}
247
248/// Resolve a binary by handle via the executable manifest system.
249///
250/// 1. Look up the manifest MCard by handle in content_memory.
251/// 2. Select the platform entry for the current OS/arch.
252/// 3. Try each provider in the provider chain to fetch the binary.
253/// 4. Verify the SHA-256 hash.
254/// 5. Cache the binary in read-only mode.
255/// 6. Return the cached path.
256pub fn resolve_binary(handle: &str, clm_root: &str) -> Result<PathBuf, String> {
257    let manifest = lookup_manifest(handle, clm_root)?;
258
259    let platform = detect_platform();
260    let entry = manifest.platforms.get(&platform)
261        .ok_or_else(|| format!("Platform '{}' not found in manifest for handle '{}'", platform, handle))?;
262
263    // Create temp destination for the fetched binary
264    let temp_dir = std::env::temp_dir().join("clm-manifest-resolve");
265    let _ = fs::create_dir_all(&temp_dir);
266    let temp_dest = temp_dir.join(format!("{}_{}", handle.replace(':', "_"), &entry.hash[..12]));
267
268    // Try providers — verify hash inside the loop so a mismatch falls through
269    let mut errors = Vec::new();
270    let fetched = {
271        let mut result: Option<PathBuf> = None;
272        for provider in &entry.providers {
273            match fetch_from_provider(provider, clm_root, &temp_dest) {
274                Ok(path) => {
275                    // Verify hash (skip if hash is all zeros — placeholder)
276                    if !entry.hash.chars().all(|c| c == '0') {
277                        match verify_hash(&path, &entry.hash) {
278                            Ok(()) => {
279                                result = Some(path);
280                                break;
281                            }
282                            Err(e) => {
283                                errors.push(format!("{}: hash mismatch ({})", provider.provider_type, e));
284                                continue;
285                            }
286                        }
287                    } else {
288                        result = Some(path);
289                        break;
290                    }
291                }
292                Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
293            }
294        }
295        match result {
296            Some(p) => p,
297            None => return Err(format!("All providers failed: {}", errors.join("; "))),
298        }
299    };
300
301    // Cache the binary
302    let cached = cache_binary(&fetched, &entry.hash)?;
303
304    // Clean up temp file if different from cached
305    if cached != fetched {
306        let _ = fs::remove_file(&fetched);
307    }
308
309    Ok(cached)
310}
311
312#[cfg(test)]
313#[path = "manifest_tests.rs"]
314mod tests;