clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 2 Hash Collision Audit and Handle Migration over SQLite storage.
use crate::layer0::gtime::{DEFAULT_G_TIME_LOCALE};

use crate::hash::{global_registry, strip_prefix};

pub fn content_equivalent(
    conn: &rusqlite::Connection,
    hash_a: &str,
    hash_b: &str,
) -> Result<bool, String> {
    let content_a = crate::layer2::record_store::read_record(conn, hash_a).map_err(|e| e.to_string())?;
    let content_b = crate::layer2::record_store::read_record(conn, hash_b).map_err(|e| e.to_string())?;
    Ok(matches!((content_a, content_b), (Some(a), Some(b)) if a.content == b.content))
}

// ── 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> {
    const SELECT_CURRENT_HASH: &str = "SELECT current_hash FROM handle_registry WHERE handle = ?";
    const SELECT_MIGRATION_SOURCE: &str = "SELECT content, g_time FROM card WHERE hash = ? OR hash = ? ORDER BY CASE WHEN hash = ? THEN 0 ELSE 1 END LIMIT 1";

    // 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,
            rusqlite::params![handle],
            |row| row.get(0),
        )
        .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;

    // 2. Resolve and verify the source row before authorizing a migration.
    let bare_hash = strip_prefix(&current_hash);
    let (content, g_time): (Vec<u8>, String) = conn.query_row(
        SELECT_MIGRATION_SOURCE,
        rusqlite::params![&current_hash, bare_hash, &current_hash],
        |row| Ok((row.get(0)?, row.get(1)?)),
    ).map_err(|_| format!("Content not found in CAS for hash '{}'", current_hash))?;
    let source = crate::layer0::mcard_record::MCardRecord {
        hash: current_hash.clone(), content: content.clone(), g_time,
    };
    if !matches!(crate::layer0::mcard_record::verify_record(&source),
        crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }) {
        return Err("hash migration source is not a verified declared record".to_string());
    }

    // 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),
        DEFAULT_G_TIME_LOCALE,
    )?;
    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 = (|| {
            // Recheck the head and source under the same transaction as the update.
            let current: String = tx.query_row(
                SELECT_CURRENT_HASH,
                rusqlite::params![handle], |row| row.get(0),
            ).map_err(|e| e.to_string())?;
            if current != current_hash {
                return Err("handle changed during hash migration".to_string());
            }
            let stored_source: (Vec<u8>, String) = tx.query_row(
                SELECT_MIGRATION_SOURCE,
                rusqlite::params![&current_hash, bare_hash, &current_hash],
                |row| Ok((row.get(0)?, row.get(1)?)),
            ).map_err(|e| e.to_string())?;
            if stored_source.0 != source.content || stored_source.1 != source.g_time {
                return Err("source changed during hash migration".to_string());
            }
            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())?;
            let target: crate::layer0::mcard_record::MCardRecord = tx.query_row(
                "SELECT content, g_time FROM card WHERE hash = ?", rusqlite::params![&record.hash],
                |row| Ok(crate::layer0::mcard_record::MCardRecord {
                    hash: new_hash.clone(), content: row.get(0)?, g_time: row.get(1)?,
                }),
            ).map_err(|e| e.to_string())?;
            if target.content != record.content || !matches!(
                crate::layer0::mcard_record::verify_record(&target),
                crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
            ) {
                return Err("existing migration target conflicts with verified content".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))
}