clm-kernel 0.0.18

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 3: Satori Speech-Act Transducers & Binary AST Encoding
//! Canonical Path: kernel/clm_rust_core/src/layer3/satori.rs

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub use crate::mesh::reticulum_satori::{
    compute_receipt_token, decode_satori_binary, encode_satori_binary, opcode_from_type,
    type_from_opcode, ReticulumSatoriError, SatoriBinaryElement, OP_ACTION, OP_AT, OP_AUDIO,
    OP_BUTTON, OP_CARD, OP_CUSTOM, OP_EXECUTE, OP_IMAGE, OP_MESSAGE, OP_QUOTE, OP_TEXT, OP_VIDEO,
    OP_WITNESS,
};

/// The five canonical Searle-Austin speech act categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpeechActType {
    Assertive,
    Directive,
    Commissive,
    Expressive,
    Declarative,
}

impl SpeechActType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Assertive => "assertive",
            Self::Directive => "directive",
            Self::Commissive => "commissive",
            Self::Expressive => "expressive",
            Self::Declarative => "declarative",
        }
    }
}

/// Classifies a Satori AST binary element into a Searle-Austin speech act.
pub fn classify_speech_act(elem: &SatoriBinaryElement) -> SpeechActType {
    // 1. Check explicit attribute
    if let Some(val) = elem.attrs.get("speech_act_type").and_then(|v| v.as_str()) {
        match val.to_lowercase().as_str() {
            "assertive" => return SpeechActType::Assertive,
            "directive" => return SpeechActType::Directive,
            "commissive" => return SpeechActType::Commissive,
            "expressive" => return SpeechActType::Expressive,
            "declarative" | "declaration" => return SpeechActType::Declarative,
            _ => {}
        }
    }

    // 2. Opcode-level heuristics
    if elem.element_type == "action" || elem.element_type == "execute" {
        return SpeechActType::Directive;
    }
    if elem.element_type == "witness" {
        return SpeechActType::Declarative;
    }

    // 3. Inspect text content across children
    let text = extract_all_text(elem);
    let lower = text.to_lowercase();
    if lower.contains("?") || lower.starts_with("run ") || lower.starts_with("can you") || lower.starts_with("show ") {
        SpeechActType::Directive
    } else if lower.contains("i will") || lower.contains("promise") || lower.contains("commit") {
        SpeechActType::Commissive
    } else if lower.contains("hello") || lower.contains("thanks") || lower.contains("great") || lower.contains("morning") {
        SpeechActType::Expressive
    } else if lower.contains("declare") || lower.contains("approve") || lower.contains("hereby") {
        SpeechActType::Declarative
    } else {
        SpeechActType::Assertive
    }
}

fn extract_all_text(elem: &SatoriBinaryElement) -> String {
    let mut buf = String::new();
    if let Some(t) = elem.attrs.get("text").and_then(|v| v.as_str()) {
        buf.push_str(t);
        buf.push(' ');
    }
    for child in &elem.children {
        buf.push_str(&extract_all_text(child));
        buf.push(' ');
    }
    buf.trim().to_string()
}

/// Maxwell's Demon verification receipt (§3.2, INV-362-04).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, 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 binary message speech act via Maxwell's Demon (§3.2, INV-362-04).
/// Gated check ensuring zero cohomology obstruction H^1 = 0 before wire transmission.
pub fn audit_maxwell_demon(msg: &SatoriBinaryElement) -> MaxwellReceipt {
    let encoded = encode_satori_binary(msg);
    let hash = hex::encode(Sha256::digest(&encoded));

    let user_did = msg
        .attrs
        .get("user_did")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // 1. Identity grounding check: DID must start with "did:"
    if !user_did.starts_with("did:") {
        return MaxwellReceipt {
            verified: false,
            cohomology_h1: 1,
            lagrangian_delta: -1,
            hash,
            rejection_reason: Some(format!(
                "Cohomology Class H^1 != 0: Un-grounded DID contributor identity '{}'",
                user_did
            )),
        };
    }

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

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

    MaxwellReceipt {
        verified: true,
        cohomology_h1: 0,
        lagrangian_delta: 1,
        hash,
        rejection_reason: None,
    }
}