clm-kernel 0.0.6

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Test Suite: Layer 5 Continuous Learning Stratum & Karpathy Quarantine (Sprint 415 / AC-415-1).
//! Canonical Path: kernel/clm_rust_core/tests/test_layer5_learning.rs

use clm_rust_core::layer5::{
    advance_boundary, close_gamma_loop, compute_delta_e, evaluate_epistemic_fitness,
    get_universe_coordinates, is_stratified, seal_epoch, validate_universe_level,
    ContinuousLearningEngine, LearningHypothesis,
    LoopGammaTelemetryHook, UniverseLevel,
};

#[test]
fn test_compute_delta_e_precision() {
    assert_eq!(compute_delta_e(1.0, 1.0), 0.0);
    assert_eq!(compute_delta_e(1.0, 1.08421), 0.08421);
    assert_eq!(compute_delta_e(0.85, 0.92), 0.07);
    assert_eq!(compute_delta_e(0.95, 0.80), -0.15);
    // 6 decimal rounding
    assert_eq!(compute_delta_e(0.1234567, 0.2234567), 0.1);
    assert_eq!(compute_delta_e(0.0, 0.0000014), 0.000001);
    assert_eq!(compute_delta_e(0.0, 0.0000016), 0.000002);
}

#[test]
fn test_evaluate_epistemic_fitness() {
    let rep_adv = evaluate_epistemic_fitness(0.95, 0.90, "spec_advancement");
    assert!(rep_adv.monotonic);
    assert_eq!(rep_adv.status, "COMMITTED");
    assert_eq!(rep_adv.delta_e, 0.05);

    let rep_reg = evaluate_epistemic_fitness(0.80, 0.90, "spec_regression");
    assert!(!rep_reg.monotonic);
    assert_eq!(rep_reg.status, "REJECTED_REGRESSION");
    assert_eq!(rep_reg.delta_e, -0.10);

    let rep_flat = evaluate_epistemic_fitness(0.90, 0.90, "spec_invariant_preserved");
    assert!(rep_flat.monotonic);
    assert_eq!(rep_flat.status, "COMMITTED");
    assert_eq!(rep_flat.delta_e, 0.0);
}

#[test]
fn test_epoch_sealing_and_advancement() {
    let sealed = seal_epoch(1, 0.05, "bafk_hypo_01", 1.0);
    assert_eq!(sealed.epoch_id, 1);
    assert_eq!(sealed.baseline_fitness, 1.0);
    assert_eq!(sealed.hypothesis_history, vec!["bafk_hypo_01".to_string()]);
    assert!(!sealed.epoch_hash.is_empty());

    let next = advance_boundary(&sealed, 1.05);
    assert_eq!(next.epoch_id, 2);
    assert_eq!(next.baseline_fitness, 1.05);
    assert_eq!(next.hypothesis_history, vec!["bafk_hypo_01".to_string()]);
    assert!(!next.epoch_hash.is_empty());
}

#[test]
fn test_close_gamma_loop_advancement() {
    let current_epoch = seal_epoch(1, 0.0, "", 0.80);
    let hypothesis = LearningHypothesis {
        hypothesis_id: "hyp_test_01".to_string(),
        author_did: "did:clm:agent-amira".to_string(),
        epoch_id: 1,
        candidate_state_hash: "state_hash_01".to_string(),
        candidate_patches: vec![],
        target_invariants: vec!["INV-14".to_string()],
        status: "QUARANTINED".to_string(),
    };

    // Monotonic advancement (0.80 -> 0.90)
    let (success, next_epoch, report) = close_gamma_loop(
        &hypothesis,
        &current_epoch,
        "spec:test",
        |_h, _s| 0.90,
    );
    assert!(success);
    assert_eq!(next_epoch.epoch_id, 2);
    assert_eq!(next_epoch.baseline_fitness, 0.90);
    assert_eq!(report.delta_e, 0.10);
    assert!(report.monotonic);

    // Regression rejection (0.90 -> 0.70)
    let (success_reg, retained_epoch, report_reg) = close_gamma_loop(
        &hypothesis,
        &next_epoch,
        "spec:test_regression",
        |_h, _s| 0.70,
    );
    assert!(!success_reg);
    assert_eq!(retained_epoch.epoch_id, 2);
    assert_eq!(report_reg.delta_e, -0.20);
    assert!(!report_reg.monotonic);
}

#[test]
fn test_karpathy_quarantine_governance() {
    let mut engine = ContinuousLearningEngine::new(1, 1.0);
    let hyp = engine.submit_hypothesis(
        "hyp_opt_01",
        "did:clm:agent-winston",
        "hash_candidate_01",
        vec![serde_json::json!({"action": "optimize_cache"})],
        vec!["INV-14".to_string()],
    );

    // 1. Verify initial status is QUARANTINED
    assert_eq!(hyp.status, "QUARANTINED");
    assert_eq!(engine.quarantined_mutations.len(), 1);

    // 2. Reject regression (fitness 0.95 vs baseline 1.0)
    let res_reg = engine.evaluate_and_commit("hyp_opt_01", "spec:optimize", 0.95).unwrap();
    assert!(!res_reg.0);
    assert_eq!(res_reg.1.status, "REJECTED_REGRESSION");
    assert!(!engine.can_commit_to_handle_registry(&hyp, &res_reg.1));
    assert_eq!(engine.quarantined_mutations.len(), 0); // purged

    // 3. Re-submit and accept monotonic advancement (fitness 1.05 vs baseline 1.0)
    let hyp2 = engine.submit_hypothesis(
        "hyp_opt_02",
        "did:clm:agent-winston",
        "hash_candidate_02",
        vec![],
        vec!["INV-14".to_string()],
    );
    let res_adv = engine.evaluate_and_commit("hyp_opt_02", "spec:optimize_v2", 1.05).unwrap();
    assert!(res_adv.0);
    assert_eq!(res_adv.1.status, "COMMITTED");
    assert!(engine.can_commit_to_handle_registry(&hyp2, &res_adv.1));
    assert_eq!(engine.current_epoch.epoch_id, 2);
    assert_eq!(engine.current_epoch.baseline_fitness, 1.05);
}

#[test]
fn test_telemetry_hook_closed_loop() {
    let mut hook = LoopGammaTelemetryHook::new(None, None);

    // Non-failure event is ignored
    let ok_rep = hook.on_telemetry_event(
        "task_complete",
        &serde_json::json!({"success": true, "status": "ok"}),
        None::<fn(&LearningHypothesis, &serde_json::Value) -> f64>,
    );
    assert!(ok_rep.is_none());

    // Failure event triggers closed loop
    let fail_rep = hook.simulate_anomaly_and_evaluate("Database lock contention", 1.0);
    assert_eq!(fail_rep.status, "COMMITTED");
    assert_eq!(hook.hypotheses.len(), 1);
    assert_eq!(hook.evaluated_reports.len(), 1);
}

#[test]
fn test_type_lattice_stratification_and_coordinates() {
    let coords = get_universe_coordinates();
    assert_eq!(coords.len(), 6);
    assert_eq!(coords[0].identifier, "U0");
    assert_eq!(coords[0].stratum_name, "mcard_cas");
    assert_eq!(coords[1].identifier, "U1");
    assert_eq!(coords[1].stratum_name, "pcard_net");
    assert_eq!(coords[2].identifier, "U2");
    assert_eq!(coords[2].stratum_name, "vcard_proof");
    assert_eq!(coords[3].identifier, "U3");
    assert_eq!(coords[3].stratum_name, "satori_fiber");
    assert_eq!(coords[4].identifier, "U4");
    assert_eq!(coords[4].stratum_name, "membrane_ui");
    assert_eq!(coords[5].identifier, "U5");
    assert_eq!(coords[5].stratum_name, "meta_gamma");

    // Stratification checks: U_inner <= U_outer
    assert!(is_stratified(0, 0));
    assert!(is_stratified(0, 5));
    assert!(is_stratified(1, 3));
    assert!(!is_stratified(3, 1));
    assert!(!is_stratified(5, 4));

    // Bounds checking
    assert_eq!(validate_universe_level(0).unwrap(), UniverseLevel::U0Mcard);
    assert_eq!(validate_universe_level(5).unwrap(), UniverseLevel::U5MetaGamma);
    assert!(validate_universe_level(6).is_err());
}