clm-kernel 0.0.9

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

#[allow(dead_code)]
pub fn augment(clm_file: &str, aug_source: &str, clm_root: &str) -> Result<String, String> {
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    let aug_content = if Path::new(aug_source).exists() {
        fs::read_to_string(aug_source)
            .map_err(|e| format!("Failed to read augmentation file: {}", e))?
    } else {
        aug_source.to_string()
    };

    let aug_val: Value = serde_yaml::from_str(&aug_content)
        .map_err(|e| format!("Failed to parse augmentation YAML: {}", e))?;

    if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
            && let Some(obj) = concrete_impl.as_object_mut() {
                obj.insert("precondition".to_string(), pre.clone());
            }
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let invariants = obj.entry("invariants".to_string())
                    .or_insert_with(|| serde_json::json!({
                        "preconditions": Vec::<String>::new(),
                        "postconditions": Vec::<String>::new()
                    }));
                if let Some(inv_obj) = invariants.as_object_mut() {
                    let pre_list = inv_obj.entry("preconditions".to_string())
                        .or_insert_with(|| Value::Array(Vec::new()));
                    if let Some(arr) = pre_list.as_array_mut() {
                        if let Some(new_arr) = pre.as_array() {
                            arr.extend(new_arr.clone());
                        } else {
                            if !arr.contains(pre) {
                                arr.push(pre.clone());
                            }
                        }
                    }
                }
            }
    } else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
            && let Some(obj) = concrete_impl.as_object_mut() {
                obj.insert("postcondition".to_string(), post.clone());
            }
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let invariants = obj.entry("invariants".to_string())
                    .or_insert_with(|| serde_json::json!({
                        "preconditions": Vec::<String>::new(),
                        "postconditions": Vec::<String>::new()
                    }));
                if let Some(inv_obj) = invariants.as_object_mut() {
                    let post_list = inv_obj.entry("postconditions".to_string())
                        .or_insert_with(|| Value::Array(Vec::new()));
                    if let Some(arr) = post_list.as_array_mut() {
                        if let Some(new_arr) = post.as_array() {
                            arr.extend(new_arr.clone());
                        } else {
                            if !arr.contains(post) {
                                arr.push(post.clone());
                            }
                        }
                    }
                }
            }
    }
 else if let Some(pending) = aug_val.get("pending_cases") {
        if let Some(balanced_exp) = clm.get_mut("balanced_exp")
            && let Some(obj) = balanced_exp.as_object_mut() {
                let existing = obj.entry("pending_cases".to_string())
                    .or_insert(Value::Array(Vec::new()));
                if let Some(arr) = existing.as_array_mut() {
                    if let Some(new_arr) = pending.as_array() {
                        arr.extend(new_arr.clone());
                    } else {
                        arr.push(pending.clone());
                    }
                }
            }
    } else if let Some(criteria) = aug_val.get("success_criteria") {
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let existing = obj.entry("success_criteria".to_string())
                    .or_insert(Value::Array(Vec::new()));
                if let Some(arr) = existing.as_array_mut() {
                    if let Some(new_arr) = criteria.as_array() {
                        arr.extend(new_arr.clone());
                    } else {
                        arr.push(criteria.clone());
                    }
                }
            }
    } else {
        if let Some(obj) = clm.as_object_mut()
            && let Some(aug_obj) = aug_val.as_object() {
                for (k, v) in aug_obj {
                    obj.insert(k.clone(), v.clone());
                }
            }
    }

    let aug_hash = sha256_hash_string(&aug_content);
    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);
    let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));

    let new_yaml = serde_yaml::to_string(&clm_val)
        .map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
    fs::write(&aug_file, &new_yaml)
        .map_err(|e| format!("Failed to write augmented file: {}", e))?;

    // Register CLM handles in Database
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
        &aug_hash[..12], prefixed(&aug_hash)
    );
    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);

    Ok(aug_file.to_string_lossy().to_string())
}

// ── Sprint 167: Dynamic Baldwin Modularity & Fiber HMR ──────────────────────

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct SubsumptionReport {
    pub fiber_id: String,
    pub old_hash: String,
    pub new_hash: String,
    pub pre_subsumed: bool,
    pub post_subsumed: bool,
    pub subsumption_valid: bool,
    pub witness: String,
}

/// Helper to extract invariant sets from CLM AST
pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
    let mut set = std::collections::HashSet::new();
    let root = if let Some(clm) = val.get("clm") { clm } else { val };

    if let Some(arr) = root.get("abstract_spec")
        .and_then(|a| a.get("invariants"))
        .and_then(|inv| inv.get(field))
        .and_then(|f| f.as_array())
    {
        for item in arr {
            if let Some(s) = item.as_str() {
                set.insert(s.to_string());
            }
        }
    }
    if let Some(arr) = root.get("invariants")
        .and_then(|inv| inv.get(field))
        .and_then(|f| f.as_array())
    {
        for item in arr {
            if let Some(s) = item.as_str() {
                set.insert(s.to_string());
            }
        }
    }
    set
}

/// Verifies the Type Lattice Subsumption Criterion:
/// Subsumes(F_new, F_old) <=> (V_pre^new <= V_pre^old) AND (V_post^new >= V_post^old)
pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
    let old_pre = extract_invariants(old_ast, "preconditions");
    let new_pre = extract_invariants(new_ast, "preconditions");
    let old_post = extract_invariants(old_ast, "postconditions");
    let new_post = extract_invariants(new_ast, "postconditions");

    // Precondition Contravariance: V_pre^new <= V_pre^old
    // new_pre must be a subset of old_pre (new cannot require MORE than old).
    let pre_subsumed = new_pre.is_subset(&old_pre);

    // Postcondition Covariance: V_post^new >= V_post^old
    // old_post must be a subset of new_post (new must guarantee AT LEAST what old guaranteed).
    let post_subsumed = old_post.is_subset(&new_post);

    let subsumption_valid = pre_subsumed && post_subsumed;

    let witness = format!(
        "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
        pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
    );

    let report = SubsumptionReport {
        fiber_id: String::new(),
        old_hash: String::new(),
        new_hash: String::new(),
        pre_subsumed,
        post_subsumed,
        subsumption_valid,
        witness,
    };

    if subsumption_valid {
        Ok(report)
    } else {
        Err(format!("Subsumption check failed: {}", report.witness))
    }
}

/// Dynamic Baldwin Operator: Substitute (=) via Hot Module Replacement (HMR)
/// Replaces an active PCard fiber with a new implementation without dropping tokens.
pub fn substitute_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    new_clm_file: &str,
    clm_root: &str,
) -> Result<SubsumptionReport, String> {
    // 1. Locate existing fiber in active context
    let old_fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;

    // 2. Read new implementation file
    let path = Path::new(new_clm_file);
    let resolved_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        Path::new(clm_root).join(new_clm_file)
    };
    if !resolved_path.exists() {
        return Err(format!("New CLM file not found: {}", resolved_path.display()));
    }
    let yaml_content = fs::read_to_string(&resolved_path)
        .map_err(|e| format!("Failed to read new CLM file: {}", e))?;

    let new_ast: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
    let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
    let new_hash = sha256_hash_string(&new_json_str);

    // 3. Verify Type Lattice Subsumption against old fiber's AST
    let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
    let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
    let old_hash = sha256_hash_string(&old_json_str);

    let mut report = verify_subsumption(&old_ast, &new_ast)?;
    report.fiber_id = fiber_id.to_string();
    report.old_hash = old_hash;
    report.new_hash = new_hash;

    // 4. Homotopy Lifting Property: pause old fiber & unwind disposables
    old_fiber.pause()?;
    let _ = old_fiber.unwind_disposables();

    // 5. Mount replacement fiber in Active state
    ctx.remove_fiber(fiber_id);
    let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
    new_fiber.set_ast(new_ast);
    new_fiber.activate()?;

    Ok(report)
}

/// Dynamic Baldwin Operator: Split (//)
/// Splits an active fiber into an isolated sub-context sandbox.
pub fn split_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    allowed_coeffects: &[&str],
) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
    let child_ctx = ctx.isolate(allowed_coeffects);
    let child_id = format!("{}_split", fiber_id);
    let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
    child_fiber.activate()?;
    Ok(child_fiber)
}

/// Dynamic Baldwin Operator: Augment (+)
/// Injects a new coeffect capability to satisfy pending fiber requirements.
pub fn augment_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    coeffect: &str,
) -> Result<(), String> {
    let fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
    ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
    fiber.satisfy_coeffect(coeffect);
    Ok(())
}

/// Dynamic Baldwin Operator: Exclude (-)
/// Quarantines and cleanly disposes an active fiber, releasing all its resources.
pub fn exclude_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
) -> Result<(), String> {
    let fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
    let _ = fiber.dispose();
    ctx.remove_fiber(fiber_id);
    Ok(())
}