clm-kernel 0.0.11

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
#![allow(unused_imports)]
use super::*;

/// Configuration policy for hash algorithm selection and collision handling.
///
/// This struct governs:
/// - Which algorithm is used for **new** content (`active_algorithm`)
/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
/// - The order of fallback algorithms if the active one is compromised
///
/// The config is stored in a global `OnceLock` and can be loaded from a
/// configuration file or environment variable at startup.
#[derive(Debug, Clone)]
pub struct HashConfig {
    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
    pub active_algorithm: &'static str,
    /// Number of collisions before triggering an upgrade.
    pub collision_threshold: u32,
    /// Ordered list of fallback algorithm prefixes.
    /// If the active algorithm is compromised, the first available fallback
    /// becomes the new active algorithm.
    pub fallback_order: Vec<&'static str>,
}

impl Default for HashConfig {
    fn default() -> Self {
        Self {
            active_algorithm: DEFAULT_HASH_PREFIX,
            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
        }
    }
}

pub(super) fn normalize_prefix(value: &str) -> &'static str {
    let normalized = value.trim().trim_end_matches(':').to_lowercase();
    Box::leak(format!("{}:", normalized).into_boxed_str())
}

impl HashConfig {
    /// Load hash configuration from environment variables.
    ///
    /// Checks in order:
    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
    ///    Example: `blake3:|2|blake3:,sha256:`
    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
    ///
    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
    pub fn from_env() -> Self {
        let configured = std::env::var("CLM_HASH_CONFIG")
            .ok()
            .filter(|raw| !raw.trim().is_empty())
            .map(|raw| Self::parse_config(&raw))
            .or_else(|| {
                std::env::var("CLM_HASH_ALGO")
                    .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
                    .ok()
                    .filter(|algo| !algo.trim().is_empty())
                    .map(|algo| {
                        let prefix = normalize_prefix(&algo);
                        Self {
                            active_algorithm: prefix,
                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
                        }
                    })
            });

        let Some(config) = configured else {
            return Self::default();
        };
        config
    }

    pub(super) fn parse_config(raw: &str) -> Self {
        let parts: Vec<&str> = raw.splitn(3, '|').collect();
        if parts.len() < 2 {
            return Self::default();
        }
        let active = if parts[0].is_empty() {
            DEFAULT_HASH_PREFIX
        } else {
            normalize_prefix(parts[0])
        };
        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
            parts[2]
                .split(',')
                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
                .collect()
        } else {
            vec![active]
        };
        Self {
            active_algorithm: active,
            collision_threshold: threshold,
            fallback_order: fallbacks,
        }
    }
}

pub(super) fn global_config() -> &'static HashConfig {
    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
    CONFIG.get_or_init(HashConfig::from_env)
}

/// Get the current hash configuration.
pub fn config() -> &'static HashConfig {
    global_config()
}

// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────

/// Extract the algorithm prefix from a stored hash string.
///
/// Returns `Some(prefix)` if the string contains a `:` separator,
/// `None` if there is no prefix (assumed to be the default algorithm).
pub fn extract_prefix(prefixed: &str) -> Option<&str> {
    prefixed.find(':').map(|pos| &prefixed[..=pos])
}

/// Verify a stored hash against content by dispatching to the correct provider.
///
/// This function parses the algorithm prefix from `stored_hash`, looks up
/// the corresponding provider in the registry, and checks whether the
/// content matches.
///
/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
/// or the provider is unknown.
pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
    let reg = global_registry().lock().unwrap();
    let provider = reg.get(prefix).ok_or_else(|| {
        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
    })?;
    let computed = provider.hash(content);
    let stored_raw = strip_prefix(stored_hash);
    if computed == stored_raw {
        Ok(())
    } else {
        Err(format!(
            "Hash mismatch: expected {}..., got {}...",
            &stored_raw[..stored_raw.len().min(16)],
            &computed[..computed.len().min(16)]
        ))
    }
}

// ── Collision detection (Step 5) ──────────────────────────────────────────

/// Result of a collision check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollisionCheckResult {
    /// No collision — the hash is unique.
    NoCollision,
    /// Collision detected — the same hash already exists with different content.
    Collision { hash: String, collision_count: u32 },
    /// Threshold exceeded — the active algorithm should be upgraded.
    ThresholdExceeded {
        hash: String,
        collision_count: u32,
        recommended_algorithm: &'static str,
    },
}

/// Check whether a hash collision has occurred and whether the threshold
/// for algorithm upgrade has been exceeded.
///
/// Callers should invoke this *before* inserting a new card into the database.
/// If `existing_content` is `Some` and differs from `new_content`, a collision
/// is recorded. When the collision count for the active algorithm reaches
/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
/// with the recommended fallback algorithm.
pub fn check_collision(
    hash: &str,
    new_content: &[u8],
    existing_content: Option<&[u8]>,
    collision_count: u32,
) -> CollisionCheckResult {
    match existing_content {
        None => CollisionCheckResult::NoCollision,
        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
        Some(_) => {
            let count = collision_count + 1;
            let cfg = config();
            if count >= cfg.collision_threshold {
                // Find the first fallback that isn't the current active algorithm
                let recommended = cfg
                    .fallback_order
                    .iter()
                    .find(|&&algo| algo != cfg.active_algorithm)
                    .copied()
                    .unwrap_or(cfg.active_algorithm);
                CollisionCheckResult::ThresholdExceeded {
                    hash: hash.to_string(),
                    collision_count: count,
                    recommended_algorithm: recommended,
                }
            } else {
                CollisionCheckResult::Collision {
                    hash: hash.to_string(),
                    collision_count: count,
                }
            }
        }
    }
}

// ── Convenience functions (delegate to the active provider) ──────────────

/// Compute the raw hex digest of bytes using the active provider (no prefix).
///
/// This is the canonical "common function signature" shared with Python's
/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
pub fn raw_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash(content)
}

/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
    let prefix = format!("{}:", normalized);
    let reg = global_registry().lock().map_err(|e| e.to_string())?;
    let provider = reg.get(&prefix).ok_or_else(|| {
        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
    })?;
    Ok(provider.hash(content))
}

/// Compute the raw hex digest of a string using the active provider (no prefix).
pub fn raw_hash_string(s: &str) -> String {
    raw_hash_bytes(s.as_bytes())
}

/// Compute the raw digest as a 32-byte array using the active provider.
///
/// Used by Merkle tree and type lattice code that needs the raw bytes
/// rather than a hex string.
pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash_bytes(content)
}

/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    let provider = reg.active(config().active_algorithm);
    format!("{}{}", provider.prefix(), provider.hash(content))
}

/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_string(s: &str) -> String {
    prefixed_hash_bytes(s.as_bytes())
}

/// Prepend the active algorithm prefix to an already-computed raw hex digest.
pub fn prefixed(raw_hex: &str) -> String {
    format!("{}{}", config().active_algorithm, raw_hex)
}

/// Strip a known algorithm prefix from a hash string.
///
/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
/// the unprefixed hex is returned. Otherwise the input is returned as-is.
pub fn strip_prefix(prefixed: &str) -> &str {
    // Try the active algorithm prefix first
    let active = config().active_algorithm;
    if let Some(rest) = prefixed.strip_prefix(active) {
        return rest;
    }
    // Try the default prefix
    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
        return rest;
    }
    // Generic fallback: strip any `<algo>:` prefix
    if let Some(pos) = prefixed.find(':')
        && pos + 1 < prefixed.len() {
            return &prefixed[pos + 1..];
        }
    prefixed
}

/// Returns the default hash provider (currently `Blake3Provider`).
///
/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
pub fn default_provider() -> impl HashProvider {
    Blake3Provider
}

// ── Content-equivalence operator (Gap 2) ──────────────────────────────────

/// Check whether two hashes point to the same content in the CAS.
///
/// This is the Rust equivalent of the shell `clm_content_equivalent` operator.
/// Two hashes generated by different algorithms (e.g. `sha256:abc` and
/// `sha512:def`) will never match as strings, but they may point to the same
/// underlying content. This function resolves both hashes to their stored
/// content and compares the raw bytes.
///
/// Returns `Ok(true)` if both hashes exist and point to identical content,
/// `Ok(false)` if they differ or one is not found, `Err` on DB error.
#[cfg(feature = "native")]
pub fn content_equivalent(
    conn: &rusqlite::Connection,
    hash_a: &str,
    hash_b: &str,
) -> Result<bool, String> {
    if hash_a == hash_b {
        return Ok(true);
    }
    let content_a = lookup_content(conn, hash_a);
    let content_b = lookup_content(conn, hash_b);
    match (content_a, content_b) {
        (Some(a), Some(b)) => Ok(a == b),
        _ => Ok(false),
    }
}

/// Resolve a stored row by reference, accepting either the bare digest or a qualified form.
///
/// The digest column holds bare hex (DEC-12); references that leave a row are qualified. A
/// lookup therefore tries the reference as given, then its unprefixed form, so both a legacy
/// prefixed row and a canonical bare row resolve.
#[cfg(feature = "native")]
pub(super) fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
    let raw = strip_prefix(reference);
    let mut candidates = vec![reference];
    if raw != reference {
        candidates.push(raw);
    }
    for candidate in candidates {
        if let Ok(content) = conn.query_row(
            "SELECT content FROM card WHERE hash = ?",
            rusqlite::params![candidate],
            |row| row.get::<_, Vec<u8>>(0),
        ) {
            return Some(content);
        }
    }
    None
}

// ── Handle migration lifecycle (Gap 3) ────────────────────────────────────

/// Migrate a handle to use a different hash algorithm.
///
/// This is the Rust equivalent of the shell `clm_migrate_handle_hash` operator.
/// It resolves the handle to its current hash, retrieves the content from the
/// CAS, computes a new hash under the target algorithm, and transactionally
/// inserts the new card, records handle history, and updates the handle pointer.
///
/// # Arguments
/// * `conn` - SQLite connection to the content_memory database.
/// * `handle` - The handle name to migrate (e.g. `"test:migration_handle"`).
/// * `target_algo` - Target algorithm prefix (e.g. `"sha256:"`, `"custom-1024:"`).
///   Must be a registered provider.
///
/// Returns `Ok(new_hash)` on success, `Err(message)` on failure.
#[cfg(feature = "native")]
pub fn migrate_handle_hash(
    conn: &mut rusqlite::Connection,
    handle: &str,
    target_algo: &str,
) -> Result<String, String> {
    // Validate target algorithm is registered
    {
        let reg = global_registry().lock().unwrap();
        if reg.get(target_algo).is_none() {
            return Err(format!(
                "Unsupported target algorithm: '{}' (registered: {:?})",
                target_algo,
                reg.algorithms()
            ));
        }
    }

    // 1. Resolve the handle to its current, possibly-qualified reference.
    let current_hash: String = conn
        .query_row(
            "SELECT current_hash FROM handle_registry WHERE handle = ?",
            rusqlite::params![handle],
            |row| row.get(0),
        )
        .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;

    // 2. Retrieve the exact existing content preimage.
    let content: Vec<u8> = lookup_content(conn, &current_hash)
        .ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;

    // 3. Create a fresh self-verifying record under the requested provider.
    let now_utc = chrono::Utc::now().to_rfc3339();
    let record = crate::layer0::mcard_record::MCardRecord::create_at(
        &content,
        Some(target_algo),
        Some(&now_utc),
        "UTC",
    )?;
    if !matches!(
        crate::layer0::mcard_record::verify_record(&record),
        crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
    ) {
        return Err("hash migration produced an invalid self-verifying record".to_string());
    }
    let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);

    // 4. Transactional update with retry for WAL lock contention.

    let max_attempts = 3;
    let mut last_err = String::new();
    for attempt in 0..max_attempts {
        let tx = match conn.transaction() {
            Ok(tx) => tx,
            Err(e) => {
                last_err = e.to_string();
                std::thread::sleep(std::time::Duration::from_millis(200));
                continue;
            }
        };
        let result = (|| {
            tx.execute(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                rusqlite::params![&record.hash, &record.content, &record.g_time],
            )
            .map_err(|e| e.to_string())?;
            tx.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
                rusqlite::params![handle, &current_hash, &now_utc],
            )
            .map_err(|e| e.to_string())?;
            tx.execute(
                "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
                rusqlite::params![&new_hash, &now_utc, handle],
            )
            .map_err(|e| e.to_string())?;
            tx.commit().map_err(|e| e.to_string())
        })();

        match result {
            Ok(()) => return Ok(new_hash),
            Err(e) => {
                last_err = e;
                if attempt + 1 < max_attempts {
                    std::thread::sleep(std::time::Duration::from_millis(200));
                }
            }
        }
    }

    Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
}