clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Epiplexity VM integration scaffold for Stage 5.
//!
//! Implements the bounded-learning metrics `S_T`, `H_T`, `L = S_T - H_T`, and
//! `ΔL`. These are attached to VCard witnesses after PCard firings so that
//! Baldwin operator refactors can be evaluated by their Epiplexity delta.
//!
//! GitNexus cluster data is accepted as an input rather than queried inline;
//! this keeps the module WASM-safe and free of subprocess dependencies.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct EpiplexityMetrics {
    pub s_t: f64,
    pub h_t: f64,
    pub l: f64,
    pub delta_l: f64,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GitNexusCluster {
    pub id: String,
    pub label: String,
    pub cohesion: f64,
    pub symbol_count: u32,
}

/// Compute structural signal `S_T` as the cohesion-weighted symbol count.
pub fn compute_s_t(clusters: &[GitNexusCluster]) -> f64 {
    clusters.iter().map(|c| c.cohesion * c.symbol_count as f64).sum()
}

/// Compute residual entropy `H_T` as the raw node + edge count of the affected
/// subgraph. In the scaffold `nodes` and `edges` are supplied directly.
pub fn compute_h_t(nodes: u32, edges: u32) -> f64 {
    nodes as f64 + edges as f64
}

/// Compute the Software Lagrangian `L = S_T - H_T`.
pub fn compute_l(s_t: f64, h_t: f64) -> f64 {
    s_t - h_t
}

/// Compute the Epiplexity delta between two metric snapshots.
pub fn compute_delta_l(pre: &EpiplexityMetrics, post: &EpiplexityMetrics) -> f64 {
    post.l - pre.l
}

/// Full Epiplexity snapshot for a transition.
pub fn compute_epiplexity_for_transition(
    affected_clusters: &[GitNexusCluster],
    nodes: u32,
    edges: u32,
    pre_metrics: Option<&EpiplexityMetrics>,
) -> EpiplexityMetrics {
    let s_t = compute_s_t(affected_clusters);
    let h_t = compute_h_t(nodes, edges);
    let l = compute_l(s_t, h_t);
    let delta_l = pre_metrics.map(|pre| compute_delta_l(pre, &EpiplexityMetrics { s_t, h_t, l, delta_l: 0.0 })).unwrap_or(0.0);
    EpiplexityMetrics {
        s_t,
        h_t,
        l,
        delta_l,
    }
}

/// Forecast the Epiplexity delta of a proposed refactor.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EpiplexityForecast {
    pub predicted_s_t: f64,
    pub predicted_h_t: f64,
    pub predicted_l: f64,
    pub predicted_delta_l: f64,
    pub confidence: f64,
    pub affected_clusters: Vec<String>,
}

/// Meta-Epiplexity score (A²I): the Epiplexity of the Epiplexity extractor itself.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct MetaEpiplexityScore {
    pub meta_s_t: f64,
    pub meta_h_t: f64,
    pub meta_l: f64,
    pub meta_delta_l: f64,
}

/// GitNexus index metadata loaded from `.gitnexus/meta.json`.
#[derive(Debug, Clone, Default, Deserialize)]
struct GitNexusMeta {
    #[serde(default)]
    nodes: u32,
    #[serde(default)]
    edges: u32,
    #[serde(default)]
    symbols: u32,
}

/// Read GitNexus index stats from `.gitnexus/meta.json` and compute first-order
/// Epiplexity metrics. Returns `EpiplexityMetrics` with `S_T` (cohesion-weighted
/// symbol count approximated as total symbols), `H_T` (nodes + edges), `L`, and
/// `ΔL = 0` (no prior snapshot).
pub fn measure_epiplexity(repo: &str) -> Result<EpiplexityMetrics, String> {
    let meta_path = std::path::Path::new(repo).join(".gitnexus").join("meta.json");
    let meta_str = std::fs::read_to_string(&meta_path)
        .map_err(|e| format!("Failed to read .gitnexus/meta.json at {}: {}", meta_path.display(), e))?;
    let meta: GitNexusMeta = serde_json::from_str(&meta_str)
        .map_err(|e| format!("Failed to parse .gitnexus/meta.json: {}", e))?;

    let s_t = meta.symbols as f64;
    let h_t = compute_h_t(meta.nodes, meta.edges);
    let l = compute_l(s_t, h_t);
    Ok(EpiplexityMetrics {
        s_t,
        h_t,
        l,
        delta_l: 0.0,
    })
}

/// Compute the A²I (Abstract² Interpretation) meta-Epiplexity score.
///
/// This measures the Epiplexity of the GitNexus extractor's own code structure.
/// `extractor_clusters` are the functional areas of the extractor code itself,
/// `extractor_nodes` and `extractor_edges` are the graph stats of the extractor.
pub fn compute_a2i_score(
    extractor_clusters: &[GitNexusCluster],
    extractor_nodes: u32,
    extractor_edges: u32,
) -> MetaEpiplexityScore {
    let meta_s_t = compute_s_t(extractor_clusters);
    let meta_h_t = compute_h_t(extractor_nodes, extractor_edges);
    let meta_l = compute_l(meta_s_t, meta_h_t);
    MetaEpiplexityScore {
        meta_s_t,
        meta_h_t,
        meta_l,
        meta_delta_l: 0.0,
    }
}

/// Seal the A²I meta-Epiplexity score as a VCard witness and store it as the
/// `meta/a2i_epiplexity` MCard in the execution_log database.
///
/// Returns the VCard hash on success.
#[cfg(feature = "native")]
pub fn seal_a2i_mcard(
    conn: &rusqlite::Connection,
    score: &MetaEpiplexityScore,
    clm_root: &str,
) -> Result<String, String> {
    let timestamp = crate::utils::now_iso8601();

    let vcard_yaml = format!(
        "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"pass\"\n  meta_epiplexity_score:\n    meta_s_t: {}\n    meta_h_t: {}\n    meta_l: {}\n    meta_delta_l: {}\n  timestamp: \"{}\"",
        score.meta_s_t, score.meta_h_t, score.meta_l, score.meta_delta_l, timestamp
    );

    let vcard_hash = crate::hash::raw_hash_string(&vcard_yaml);
    // The stored coordinate must name the algorithm that produced `vcard_hash` (charter L2);
    // the bare ISO value stays inside the hashed YAML as content.
    let g_time = crate::fs_utils::compute_g_time();

    crate::layer2::record_store::insert_record(conn, &crate::layer0::mcard_record::MCardRecord {
        hash: vcard_hash.clone(), content: vcard_yaml.as_bytes().to_vec(), g_time,
    })
    .map_err(|e| format!("Failed to insert A²I MCard: {}", e))?;

    let handle = "meta/a2i_epiplexity";
    conn.execute(
        "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
        rusqlite::params![handle, vcard_hash, timestamp],
    )
    .map_err(|e| format!("Failed to bind handle {}: {}", handle, e))?;

    let kv_args = vec![
        format!("vcard_hash={}", vcard_hash),
        "gate_type=dispatch".to_string(),
        format!("handle={}", handle),
    ];
    let _ = crate::jsonl::jsonl_emit("a2i_mcard_sealed", kv_args, clm_root);

    Ok(vcard_hash)
}

/// Predict metrics for a Baldwin `Split` or generic refactor.
pub fn evaluate_refactor(
    affected_clusters: &[GitNexusCluster],
    added_nodes: u32,
    added_edges: u32,
    current_metrics: &EpiplexityMetrics,
) -> EpiplexityForecast {
    // Baldwin Split heuristic: cohesion improves by 10%, entropy grows by
    // added nodes/edges. Generic changes keep cohesion flat.
    let split_bonus: f64 = 1.10;
    let predicted_s_t: f64 = affected_clusters
        .iter()
        .map(|c| c.cohesion * split_bonus * c.symbol_count as f64)
        .sum();
    let predicted_h_t = current_metrics.h_t + compute_h_t(added_nodes, added_edges);
    let predicted_l = compute_l(predicted_s_t, predicted_h_t);
    let predicted_delta_l = predicted_l - current_metrics.l;
    EpiplexityForecast {
        predicted_s_t,
        predicted_h_t,
        predicted_l,
        predicted_delta_l,
        confidence: 0.5,
        affected_clusters: affected_clusters.iter().map(|c| c.id.clone()).collect(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_s_t_sum() {
        let clusters = vec![
            GitNexusCluster {
                id: "a".to_string(),
                label: "A".to_string(),
                cohesion: 0.8,
                symbol_count: 10,
            },
            GitNexusCluster {
                id: "b".to_string(),
                label: "B".to_string(),
                cohesion: 0.5,
                symbol_count: 20,
            },
        ];
        assert!((compute_s_t(&clusters) - 18.0).abs() < 1e-9);
    }

    #[test]
    fn test_h_t_and_l() {
        let s_t = compute_s_t(&[GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }]);
        let h_t = compute_h_t(5, 3);
        assert_eq!(h_t, 8.0);
        assert_eq!(compute_l(s_t, h_t), 2.0);
    }

    #[test]
    fn test_delta_l_positive_for_split() {
        let pre = EpiplexityMetrics {
            s_t: 10.0,
            h_t: 8.0,
            l: 2.0,
            delta_l: 0.0,
        };
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        let forecast = evaluate_refactor(&clusters, 0, 0, &pre);
        assert!(forecast.predicted_delta_l > 0.0);
    }

    #[test]
    fn test_delta_l_negative_for_entropy_increase() {
        let pre = EpiplexityMetrics {
            s_t: 10.0,
            h_t: 8.0,
            l: 2.0,
            delta_l: 0.0,
        };
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        // Add many nodes/edges without cohesion gain.
        let forecast = evaluate_refactor(&clusters, 100, 50, &pre);
        assert!(forecast.predicted_delta_l < 0.0);
    }

    #[test]
    fn test_compute_transition_metrics() {
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        let pre = EpiplexityMetrics {
            s_t: 8.0,
            h_t: 5.0,
            l: 3.0,
            delta_l: 0.0,
        };
        let post = compute_epiplexity_for_transition(&clusters, 2, 1, Some(&pre));
        assert_eq!(post.s_t, 10.0);
        assert_eq!(post.h_t, 3.0);
        assert_eq!(post.l, 7.0);
        assert_eq!(post.delta_l, 4.0);
    }

    #[test]
    fn test_measure_epiplexity_with_meta_json() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let gn_dir = tmp.path().join(".gitnexus");
        std::fs::create_dir_all(&gn_dir).expect("create .gitnexus dir");
        let meta = serde_json::json!({
            "nodes": 100,
            "edges": 200,
            "symbols": 50
        });
        std::fs::write(gn_dir.join("meta.json"), meta.to_string()).expect("write meta.json");
        let result = measure_epiplexity(tmp.path().to_str().unwrap()).expect("measure_epiplexity should succeed");
        assert_eq!(result.s_t, 50.0);
        assert_eq!(result.h_t, 300.0);
        assert_eq!(result.l, -250.0);
        assert_eq!(result.delta_l, 0.0);
    }

    #[test]
    fn test_measure_epiplexity_no_index() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let result = measure_epiplexity(tmp.path().to_str().unwrap());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Failed to read"));
    }

    #[test]
    fn test_compute_a2i_score_nonzero() {
        let extractor_clusters = vec![
            GitNexusCluster {
                id: "extractor_a".to_string(),
                label: "GraphBuilder".to_string(),
                cohesion: 0.8,
                symbol_count: 30,
            },
            GitNexusCluster {
                id: "extractor_b".to_string(),
                label: "Clusterer".to_string(),
                cohesion: 0.6,
                symbol_count: 20,
            },
        ];
        let score = compute_a2i_score(&extractor_clusters, 40, 60);
        assert!(score.meta_s_t > 0.0);
        assert_eq!(score.meta_s_t, 0.8 * 30.0 + 0.6 * 20.0);
        assert_eq!(score.meta_h_t, 100.0);
        assert_eq!(score.meta_l, score.meta_s_t - score.meta_h_t);
    }

    #[test]
    fn test_compute_a2i_score_empty() {
        let score = compute_a2i_score(&[], 0, 0);
        assert_eq!(score.meta_s_t, 0.0);
        assert_eq!(score.meta_h_t, 0.0);
        assert_eq!(score.meta_l, 0.0);
    }

    #[cfg(feature = "native")]
    #[test]
    fn test_a2i_mcard_sealed_and_queryable() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)
            .unwrap();

        let score = MetaEpiplexityScore {
            meta_s_t: 36.0,
            meta_h_t: 100.0,
            meta_l: -64.0,
            meta_delta_l: 0.0,
        };

        let vcard_hash = seal_a2i_mcard(&conn, &score, "/tmp/clm_root").expect("seal_a2i_mcard should succeed");

        // Verify MCard content contains meta-epiplexity fields
        let content = crate::layer2::record_store::read_text(&conn, &vcard_hash).unwrap().unwrap();
        assert!(content.contains("meta_epiplexity_score:"));
        assert!(content.contains("meta_s_t: 36"));
        assert!(content.contains("meta_h_t: 100"));
        assert!(content.contains("meta_l: -64"));

        // Verify handle is bound
        let handle_hash: String = conn
            .query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = 'meta/a2i_epiplexity'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(handle_hash, vcard_hash);
    }
}