clm-kernel 0.0.16

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Delimited Continuations and Maxwell's Demon Auditing for Cordis Fibers.
//!
//! Enables conversational programming by suspending active fibers awaiting user input,
//! resuming on Satori message events, and gating state changes through Maxwell's Demon
//! (zero cohomology obstruction H^1 = 0, Lagrangian tracking L = S_T - H_T).

use crate::fiber::{EventBus, Fiber, FiberState};
use super::element::{SatoriElement, SatoriMessage};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

/// Verification receipt generated by Maxwell's Demon.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaxwellReceipt {
    pub verified: bool,
    pub cohomology_h1: u32,
    pub lagrangian_delta: i64,
    pub hash: String,
    pub rejection_reason: Option<String>,
}

/// Audits a Satori message using Maxwell's Demon (ยง3.2, INV-03).
/// Verifies DID identity, content addressability, and absence of hallucinated tokens.
pub fn audit_maxwell_demon(msg: &SatoriMessage) -> Result<MaxwellReceipt, String> {
    // 1. Identity grounding check: DID must be well-formed (did:key:... or did:pkc:...)
    if !msg.user_did.starts_with("did:") {
        return Ok(MaxwellReceipt {
            verified: false,
            cohomology_h1: 1, // Sheaf gluing failure: H^1 != 0
            lagrangian_delta: -1,
            hash: msg.content_hash(),
            rejection_reason: Some(format!(
                "Cohomology Class H^1 != 0: Un-grounded DID contributor identity '{}'",
                msg.user_did
            )),
        });
    }

    // 2. Non-empty grounding check
    if msg.elements.is_empty() {
        return Ok(MaxwellReceipt {
            verified: false,
            cohomology_h1: 1,
            lagrangian_delta: -1,
            hash: msg.content_hash(),
            rejection_reason: Some(
                "Cohomology Class H^1 != 0: Empty message section cannot glue into Data Harness".to_string(),
            ),
        });
    }

    // 3. Hallucination check: reject forbidden ungrounded synthetic tokens
    for elem in &msg.elements {
        if let SatoriElement::Text { text } = elem
            && (text.contains("[HALLUCINATED]") || text.contains("<hallucination>")) {
                return Ok(MaxwellReceipt {
                    verified: false,
                    cohomology_h1: 1,
                    lagrangian_delta: -1,
                    hash: msg.content_hash(),
                    rejection_reason: Some(
                        "Cohomology Class H^1 != 0: Detected ungrounded hallucinated tokens in execution section".to_string(),
                    ),
                });
            }
    }

    // 4. Content-address verification (hash match)
    let hash = msg.content_hash();
    if hash.is_empty() {
        return Err("Failed to compute BLAKE3 content hash".to_string());
    }

    // All checks pass: H^1 = 0 (cohomology obstruction vanishes)
    Ok(MaxwellReceipt {
        verified: true,
        cohomology_h1: 0,
        lagrangian_delta: 1, // S_T increases, H_T decreases
        hash,
        rejection_reason: None,
    })
}

/// Represents an active Delimited Continuation waiting for user input.
pub struct DelimitedContinuation {
    pub fiber_id: String,
    pub channel_id: String,
    pub topic: String,
    pub prompt: String,
    pub ttl_ms: u64,
    pub created_at: u64,
    pub resumed_message: Arc<Mutex<Option<SatoriMessage>>>,
}

impl DelimitedContinuation {
    pub fn new(
        fiber_id: impl Into<String>,
        channel_id: impl Into<String>,
        prompt: impl Into<String>,
        ttl_ms: u64,
    ) -> Self {
        let channel = channel_id.into();
        let topic = format!("message:received:{}", channel);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);

        Self {
            fiber_id: fiber_id.into(),
            channel_id: channel,
            topic,
            prompt: prompt.into(),
            ttl_ms,
            created_at: now,
            resumed_message: Arc::new(Mutex::new(None)),
        }
    }
}

/// Parks the active Fiber awaiting a Satori message event on the EventBus.
/// Registers an RAII disposable with the fiber to unregister on cancellation or timeout.
pub fn park_fiber_continuation(
    fiber: &Arc<Fiber>,
    event_bus: &EventBus,
    continuation: &DelimitedContinuation,
) -> Result<Box<dyn FnOnce() -> Result<(), String> + Send>, String> {
    // Ensure fiber is currently active
    if fiber.get_state() != FiberState::Active {
        return Err(format!(
            "Cannot park fiber in state {:?}",
            fiber.get_state()
        ));
    }

    // Transition fiber to Suspended
    fiber.suspend()?;

    let fiber_ref = Arc::downgrade(fiber);
    let msg_storage = continuation.resumed_message.clone();

    // Subscribe to continuation topic
    let unregister = event_bus.subscribe(&continuation.topic, move |payload| {
        if let Ok(msg) = serde_json::from_value::<SatoriMessage>(payload.clone()) {
            // Verify via Maxwell's Demon before resuming
            if let Ok(receipt) = audit_maxwell_demon(&msg)
                && receipt.verified {
                    let mut stored = msg_storage.lock().unwrap();
                    *stored = Some(msg);

                    if let Some(f) = fiber_ref.upgrade() {
                        let _ = f.resume();
                    }
                    return Ok(serde_json::to_value(receipt).unwrap_or(payload));
                }
        }
        Ok(payload)
    });

    Ok(unregister)
}

/// Resumes a parked fiber manually with a given verified SatoriMessage.
pub fn resume_continuation(
    fiber: &Fiber,
    continuation: &DelimitedContinuation,
    msg: SatoriMessage,
) -> Result<MaxwellReceipt, String> {
    let receipt = audit_maxwell_demon(&msg)?;
    if !receipt.verified {
        return Err(receipt.rejection_reason.unwrap_or_else(|| "Maxwell's Demon rejected message".to_string()));
    }

    {
        let mut stored = continuation.resumed_message.lock().unwrap();
        *stored = Some(msg);
    }

    fiber.resume()?;
    Ok(receipt)
}

/// Simulates or executes a timeout on a parked fiber, unwinding all registered disposables.
pub fn timeout_continuation(fiber: &Fiber) -> Result<(), String> {
    fiber
        .transition_to(FiberState::Unloading)
        .map_err(|e| format!("Failed to transition to Unloading: {}", e))?;

    let unwind_res = fiber.unwind_disposables();

    fiber
        .transition_to(FiberState::Failed("Continuation timeout: disposables unwound".to_string()))
        .map_err(|e| format!("Failed to set Failed state: {}", e))?;

    match unwind_res {
        Ok(()) => Ok(()),
        Err(errors) => Err(format!("Errors during timeout disposal: {:?}", errors)),
    }
}