clm-kernel 0.0.8

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! CLM Layer 5: Continuous Learning Stratum & Meta-Circular Loop Γ.
//! Canonical Path: kernel/clm_rust_core/src/layer5/learning.rs
//!
//! Implements:
//! - Epistemic Fitness Scoring (ΔE = S_candidate - S_baseline).
//! - Monotonicity verification (candidate state cannot regress existing invariants: ΔE >= 0).
//! - Meta-Circular Learning Loop (Γ) closure and epoch advancement.
//! - Karpathy write-scope quarantine governance (INV-14).

use std::collections::HashMap;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

/// Report detailing the epistemic fitness assessment of a candidate state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpistemicFitnessReport {
    pub baseline_score: f64,
    pub candidate_score: f64,
    pub delta_e: f64,
    pub monotonic: bool,
    pub status: String,
    pub timestamp: String,
    pub details: serde_json::Value,
}

/// Immutable record of an epoch boundary state in the continuous learning cycle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpochState {
    pub epoch_id: u64,
    pub epoch_hash: String,
    pub baseline_fitness: f64,
    pub sealed_at: String,
    pub hypothesis_history: Vec<String>,
}

/// Candidate mutation or refinement hypothesis evaluated under Loop Γ.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LearningHypothesis {
    pub hypothesis_id: String,
    pub author_did: String,
    pub epoch_id: u64,
    pub candidate_state_hash: String,
    #[serde(default)]
    pub candidate_patches: Vec<serde_json::Value>,
    #[serde(default)]
    pub target_invariants: Vec<String>,
    #[serde(default = "default_quarantined_status")]
    pub status: String,
}

fn default_quarantined_status() -> String {
    "QUARANTINED".to_string()
}

/// Compute differential epistemic fitness gain ΔE.
///
/// ΔE = round(S_candidate - S_baseline, 6)
/// A positive ΔE denotes epistemic advancement. A negative ΔE indicates architectural regression.
pub fn compute_delta_e(baseline_score: f64, candidate_score: f64) -> f64 {
    let diff = candidate_score - baseline_score;
    (diff * 1_000_000.0).round() / 1_000_000.0
}

/// Helper to compute SHA-256 hex string.
fn sha256_hex(data: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data.as_bytes());
    format!("{:x}", hasher.finalize())
}

/// Evaluate candidate state against objective verification specifications.
pub fn evaluate_epistemic_fitness(
    candidate_score: f64,
    baseline_score: f64,
    evaluation_spec: &str,
) -> EpistemicFitnessReport {
    let delta = compute_delta_e(baseline_score, candidate_score);
    let monotonic = delta >= 0.0;
    let status = if monotonic {
        "COMMITTED".to_string()
    } else {
        "REJECTED_REGRESSION".to_string()
    };

    EpistemicFitnessReport {
        baseline_score,
        candidate_score,
        delta_e: delta,
        monotonic,
        status,
        timestamp: Utc::now().to_rfc3339(),
        details: serde_json::json!({ "evaluation_spec": evaluation_spec }),
    }
}

/// Seal current learning epoch and mint an immutable epoch boundary token.
pub fn seal_epoch(
    epoch_id: u64,
    delta_e: f64,
    hypothesis_hash: &str,
    baseline_fitness: f64,
) -> EpochState {
    let state_repr = format!("epoch:{epoch_id}:fitness:{baseline_fitness}:delta:{delta_e}:hyp:{hypothesis_hash}");
    let epoch_hash = sha256_hex(&state_repr);

    EpochState {
        epoch_id,
        epoch_hash,
        baseline_fitness,
        sealed_at: Utc::now().to_rfc3339(),
        hypothesis_history: if hypothesis_hash.is_empty() {
            vec![]
        } else {
            vec![hypothesis_hash.to_string()]
        },
    }
}

/// Advance epoch boundary to epoch N+1 with updated baseline fitness.
pub fn advance_boundary(current_epoch: &EpochState, new_fitness: f64) -> EpochState {
    let next_id = current_epoch.epoch_id + 1;
    let state_repr = format!("epoch:{next_id}:parent:{}:fitness:{new_fitness}", current_epoch.epoch_hash);
    let next_hash = sha256_hex(&state_repr);

    EpochState {
        epoch_id: next_id,
        epoch_hash: next_hash,
        baseline_fitness: new_fitness,
        sealed_at: Utc::now().to_rfc3339(),
        hypothesis_history: current_epoch.hypothesis_history.clone(),
    }
}

/// Execute the Meta-Circular Learning Loop (Γ) closure.
pub fn close_gamma_loop<F>(
    hypothesis: &LearningHypothesis,
    current_epoch: &EpochState,
    evaluation_spec: &str,
    evaluator: F,
) -> (bool, EpochState, EpistemicFitnessReport)
where
    F: FnOnce(&LearningHypothesis, &str) -> f64,
{
    let candidate_score = evaluator(hypothesis, evaluation_spec);
    let report = evaluate_epistemic_fitness(
        candidate_score,
        current_epoch.baseline_fitness,
        evaluation_spec,
    );

    if !report.monotonic {
        return (false, current_epoch.clone(), report);
    }

    let sealed = seal_epoch(
        current_epoch.epoch_id,
        report.delta_e,
        &hypothesis.candidate_state_hash,
        report.candidate_score,
    );
    let next_epoch = advance_boundary(&sealed, report.candidate_score);

    (true, next_epoch, report)
}

/// The Layer 5 Continuous Learning Engine.
/// Governs Loop Γ, enforces Karpathy write-scope quarantine boundaries (INV-14),
/// tracks epistemic fitness history, and orchestrates autonomous system adaptation.
#[derive(Debug, Clone)]
pub struct ContinuousLearningEngine {
    pub current_epoch: EpochState,
    pub history: Vec<EpistemicFitnessReport>,
    pub quarantined_mutations: HashMap<String, LearningHypothesis>,
}

impl ContinuousLearningEngine {
    pub fn new(initial_epoch: u64, initial_fitness: f64) -> Self {
        let genesis_repr = format!("genesis:{initial_epoch}");
        let epoch_hash = sha256_hex(&genesis_repr);

        Self {
            current_epoch: EpochState {
                epoch_id: initial_epoch,
                epoch_hash,
                baseline_fitness: initial_fitness,
                sealed_at: Utc::now().to_rfc3339(),
                hypothesis_history: vec![],
            },
            history: vec![],
            quarantined_mutations: HashMap::new(),
        }
    }

    /// Submit candidate refinement under write-scope quarantine (INV-14).
    pub fn submit_hypothesis(
        &mut self,
        hypothesis_id: &str,
        author_did: &str,
        candidate_state_hash: &str,
        patches: Vec<serde_json::Value>,
        target_invariants: Vec<String>,
    ) -> LearningHypothesis {
        let hyp = LearningHypothesis {
            hypothesis_id: hypothesis_id.to_string(),
            author_did: author_did.to_string(),
            epoch_id: self.current_epoch.epoch_id,
            candidate_state_hash: candidate_state_hash.to_string(),
            candidate_patches: patches,
            target_invariants,
            status: "QUARANTINED".to_string(),
        };
        self.quarantined_mutations.insert(hypothesis_id.to_string(), hyp.clone());
        hyp
    }

    /// Evaluate a quarantined hypothesis and commit if monotonic.
    pub fn evaluate_and_commit(
        &mut self,
        hypothesis_id: &str,
        evaluation_spec: &str,
        candidate_fitness: f64,
    ) -> Result<(bool, EpistemicFitnessReport), String> {
        let hyp = self
            .quarantined_mutations
            .get(hypothesis_id)
            .cloned()
            .ok_or_else(|| format!("No quarantined hypothesis found for {}", hypothesis_id))?;

        let (success, next_epoch, mut report) = close_gamma_loop(
            &hyp,
            &self.current_epoch,
            evaluation_spec,
            |_h, _s| candidate_fitness,
        );

        if success {
            report.status = "COMMITTED".to_string();
            self.current_epoch = next_epoch;
            self.quarantined_mutations.remove(hypothesis_id);
            self.history.push(report.clone());
            Ok((true, report))
        } else {
            report.status = "REJECTED_REGRESSION".to_string();
            // Purge rejected hypothesis from quarantine
            self.quarantined_mutations.remove(hypothesis_id);
            self.history.push(report.clone());
            Ok((false, report))
        }
    }

    /// Karpathy write-scope quarantine security check (INV-14).
    /// Prevents modifying production handle_registry unless the candidate
    /// has achieved monotonic verification (ΔE >= 0, status == COMMITTED).
    pub fn can_commit_to_handle_registry(
        &self,
        hypothesis: &LearningHypothesis,
        report: &EpistemicFitnessReport,
    ) -> bool {
        if hypothesis.status == "QUARANTINED" && report.status != "COMMITTED" {
            return false;
        }
        report.monotonic && report.delta_e >= 0.0 && report.status == "COMMITTED"
    }
}