clm-kernel 0.0.2

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
// 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) = std::env::var("HOME") {
        Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
    } else if let Ok(user_profile) = std::env::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("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)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_platform() {
        let platform = detect_platform();
        assert!(!platform.is_empty());
        assert!(platform.contains('-'));
    }

    #[test]
    fn test_verify_hash_match() {
        let dir = std::env::temp_dir().join("clm_manifest_test_hash_match");
        let _ = fs::create_dir_all(&dir);
        let test_file = dir.join("test_binary.bin");
        fs::write(&test_file, b"hello world").unwrap();

        let mut hasher = Sha256::new();
        hasher.update(b"hello world");
        let expected = format!("{:x}", hasher.finalize());

        assert!(verify_hash(&test_file, &expected).is_ok());

        let _ = fs::remove_file(&test_file);
        let _ = fs::remove_dir(&dir);
    }

    #[test]
    fn test_verify_hash_mismatch() {
        let dir = std::env::temp_dir().join("clm_manifest_test_hash_mismatch");
        let _ = fs::create_dir_all(&dir);
        let test_file = dir.join("test_binary_mismatch.bin");
        fs::write(&test_file, b"hello world").unwrap();

        let wrong_hash = "0".repeat(64);
        let result = verify_hash(&test_file, &wrong_hash);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Hash mismatch"));

        let _ = fs::remove_file(&test_file);
        let _ = fs::remove_dir(&dir);
    }

    #[test]
    fn test_compute_file_hash() {
        let dir = std::env::temp_dir().join("clm_manifest_test_compute_hash");
        let _ = fs::create_dir_all(&dir);
        let test_file = dir.join("compute_hash_test.bin");
        fs::write(&test_file, b"test content for hashing").unwrap();

        let hash = compute_file_hash(&test_file).unwrap();
        assert_eq!(hash.len(), 64);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));

        let _ = fs::remove_file(&test_file);
        let _ = fs::remove_dir(&dir);
    }

    #[test]
    fn test_local_provider_found() {
        let dir = std::env::temp_dir().join("clm_manifest_test_local_provider");
        let _ = fs::create_dir_all(&dir);
        let source = dir.join("source.bin");
        fs::write(&source, b"binary content").unwrap();

        let dest = dir.join("dest.bin");
        let provider = Provider {
            provider_type: "local".to_string(),
            url: None,
            path: Some(source.to_string_lossy().to_string()),
        };

        let result = fetch_from_provider(&provider, "/tmp", &dest);
        assert!(result.is_ok());
        assert!(dest.exists());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_local_provider_not_found() {
        let provider = Provider {
            provider_type: "local".to_string(),
            url: None,
            path: Some("/nonexistent/path/to/binary".to_string()),
        };

        let result = fetch_from_provider(&provider, "/tmp", Path::new("/tmp/dest.bin"));
        assert!(result.is_err());
    }

    #[test]
    fn test_provider_chain_fallback() {
        let dir = std::env::temp_dir().join("clm_manifest_test_chain");
        let _ = fs::create_dir_all(&dir);
        let source = dir.join("source_chain.bin");
        fs::write(&source, b"chain content").unwrap();

        let dest = dir.join("dest_chain.bin");
        let providers = vec![
            Provider {
                provider_type: "local".to_string(),
                url: None,
                path: Some("/nonexistent/path".to_string()),
            },
            Provider {
                provider_type: "local".to_string(),
                url: None,
                path: Some(source.to_string_lossy().to_string()),
            },
        ];

        let result = fetch_from_providers(&providers, "/tmp", &dest);
        assert!(result.is_ok());
        assert!(dest.exists());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cache_hit() {
        let dir = std::env::temp_dir().join("clm_manifest_test_cache_hit");
        let _ = fs::create_dir_all(&dir);
        let source = dir.join("source_cache.bin");
        fs::write(&source, b"cacheable content").unwrap();

        let mut hasher = Sha256::new();
        hasher.update(b"cacheable content");
        let hash = format!("{:x}", hasher.finalize());

        // First call caches the binary
        let cached1 = cache_binary(&source, &hash).unwrap();
        assert!(cached1.exists());

        // Second call should be a cache hit
        let cached2 = cache_binary(&source, &hash).unwrap();
        assert_eq!(cached1, cached2);

        let _ = fs::remove_dir_all(&dir);
        // Clean up cache
        let cache_dir = dirs_cache_dir().unwrap();
        let _ = fs::remove_file(cache_dir.join(&hash));
    }

    #[test]
    fn test_cache_miss_then_hit() {
        let dir = std::env::temp_dir().join("clm_manifest_test_cache_miss");
        let _ = fs::create_dir_all(&dir);
        let source = dir.join("source_miss.bin");
        fs::write(&source, b"miss then hit content").unwrap();

        let mut hasher = Sha256::new();
        hasher.update(b"miss then hit content");
        let hash = format!("{:x}", hasher.finalize());

        let cache_dir = dirs_cache_dir().unwrap();
        let cache_path = cache_dir.join(&hash);
        let _ = fs::remove_file(&cache_path);

        // Cache miss — should copy
        let cached = cache_binary(&source, &hash).unwrap();
        assert!(cached.exists());

        // Clean up
        let _ = fs::remove_dir_all(&dir);
        let _ = fs::remove_file(&cache_path);
    }

    #[test]
    fn test_manifest_deserialization() {
        let json = r#"{
            "name": "test_binary",
            "version": "1.0.0",
            "platforms": {
                "darwin-arm64": {
                    "path": "/usr/local/bin/test",
                    "hash": "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
                    "size": 1024,
                    "format": "raw",
                    "providers": [
                        {"type": "local", "path": "/usr/local/bin/test"}
                    ]
                }
            }
        }"#;
        let manifest: ExecutableManifest = serde_json::from_str(json).unwrap();
        assert_eq!(manifest.name.as_deref(), Some("test_binary"));
        assert_eq!(manifest.platforms.len(), 1);
        let entry = manifest.platforms.get("darwin-arm64").unwrap();
        assert_eq!(entry.format, ArchiveFormat::Raw);
        assert_eq!(entry.providers.len(), 1);
    }
}