clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

pub(super) async fn execute_clm(
    clm_file: &str,
    clm_payload: &str,
    writer: &WsWriter,
) -> Result<(), String> {
    let clm_root = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ROOT).unwrap_or_else(|_| ".".to_string());
    let path_buf = PathBuf::from(clm_file);
    let absolute_path = if path_buf.is_absolute() {
        path_buf
    } else {
        Path::new(&clm_root).join(clm_file)
    };

    if !absolute_path.exists() {
        send_error(writer, &format!("CLM file not found: {}", clm_file), None).await;
        return Ok(());
    }

    let file_name = absolute_path.file_name().and_then(|s| s.to_str()).unwrap_or("");
    send_status(writer, "started", file_name, clm_payload).await;

    // Execute via IPC Dispatcher
    let dispatch_sock = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_DISPATCH_SOCK).unwrap_or_default();
    if dispatch_sock.is_empty() {
        send_error(writer, "IPC dispatcher not configured (CLM_DISPATCH_SOCK missing)", None).await;
        return Ok(());
    }

    #[cfg(unix)]
    {
        match UnixStream::connect(&dispatch_sock).await {
            Ok(unix_stream) => {
                let (ipc_read, mut ipc_write) = unix_stream.into_split();
                let request = serde_json::json!({
                    "action": "execute",
                    "clm_file": absolute_path.to_string_lossy(),
                    "payload": clm_payload
                }).to_string() + "\n";

                if ipc_write.write_all(request.as_bytes()).await.is_ok() {
                    let mut ipc_reader = tokio::io::BufReader::new(ipc_read);
                    let mut line = String::new();
                    use tokio::io::AsyncBufReadExt;

                    while let Ok(n) = ipc_reader.read_line(&mut line).await {
                        if n == 0 {
                            break;
                        }
                        let trimmed = line.trim();
                        if trimmed.is_empty() {
                            line.clear();
                            continue;
                        }

                        if let Ok(parsed) = serde_json::from_str::<Value>(trimmed) {
                            let msg_type = parsed.get("type").and_then(|t| t.as_str()).unwrap_or("");
                            if msg_type == "stdout" {
                                if let Some(stdout_data) = parsed.get("data").and_then(|d| d.as_str())
                                    && stdout_data.contains("CLM_TRACE_JSON:")
                                        && let Some(idx) = stdout_data.find("CLM_TRACE_JSON:") {
                                            let mut json_str = stdout_data[idx + "CLM_TRACE_JSON:".len()..].trim().to_string();
                                            // Strip ANSI escape codes
                                            if let Ok(ansi_re) = Regex::new(r"\x1B\[[0-9;]*m") {
                                                json_str = ansi_re.replace_all(&json_str, "").to_string();
                                            }
                                            if let Ok(trace_val) = serde_json::from_str::<Value>(&json_str) {
                                                let mut writer_lock = writer.lock().await;
                                                let _ = writer_lock.send(Message::Text(trace_val.to_string())).await;
                                            }
                                        }
                            } else if msg_type == "stderr" {
                                if let Some(stderr_data) = parsed.get("data").and_then(|d| d.as_str()) {
                                    send_log(writer, stderr_data).await;
                                }
                            } else if msg_type == "completed" {
                                let exit_code = parsed.get("exit_code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
                                if exit_code != 0 {
                                    send_error(writer, &format!("Execution failed with exit code {}", exit_code), Some(exit_code)).await;
                                } else {
                                    let witness_hash = parsed.get("witness_hash").and_then(|w| w.as_str());
                                    let witness_yaml = parsed.get("witness_yaml").and_then(|w| w.as_str());
                                    
                                    send_completed(
                                        writer,
                                        0,
                                        witness_hash,
                                        witness_yaml,
                                        if witness_hash.is_none() { Some("Execution completed successfully") } else { None },
                                    ).await;
                                }
                                break;
                            } else if msg_type == "error" {
                                let err_msg = parsed.get("error").and_then(|e| e.as_str()).unwrap_or("Unknown dispatch error");
                                send_error(writer, err_msg, None).await;
                                break;
                            }
                        }
                        line.clear();
                    }
                }
            }
            Err(e) => {
                send_error(writer, &format!("IPC dispatch connection failed: {}", e), None).await;
            }
        }
    }

    #[cfg(not(unix))]
    {
        send_error(writer, "IPC Unix domain sockets are only supported on Unix targets", None).await;
    }

    Ok(())
}

pub(super) async fn process_message(
    text: &str,
    writer: &WsWriter,
    shutdown_trigger: &Arc<tokio::sync::Notify>,
) -> Result<bool, String> {
    if text == "shutdown" || text.contains("\"type\":\"shutdown\"") {
        println!("[GATEWAY] Graceful shutdown requested.");
        let reply = serde_json::json!({ "type": "shutdown", "status": "ok" }).to_string();
        {
            let mut writer_lock = writer.lock().await;
            let _ = writer_lock.send(Message::Text(reply)).await;
        }
        shutdown_trigger.notify_one();
        return Ok(true);
    }

    let mut clm_file = String::new();
    let mut clm_payload = String::new();
    let mut is_ping = false;

    let mut json_msg: Option<Value> = None;
    if let Ok(val) = serde_json::from_str::<Value>(text) {
        json_msg = Some(val.clone());
        if let Some(msg_type) = val.get("type").and_then(|t| t.as_str()) {
            if msg_type == "execute" {
                clm_file = val.get("clm_file").and_then(|f| f.as_str()).unwrap_or("").to_string();
                clm_payload = val.get("payload").and_then(|p| p.as_str()).unwrap_or("").to_string();
            } else if msg_type == "ping" {
                is_ping = true;
            }
        }
    } else if text == "ping" {
        is_ping = true;
    }

    if is_ping {
        let reply = serde_json::json!({ "type": "pong" }).to_string();
        let mut writer_lock = writer.lock().await;
        let _ = writer_lock.send(Message::Text(reply)).await;
        return Ok(false);
    }

    // Extract message content
    let mut query_text = text.to_string();
    if let Some(val) = &json_msg
        && val.get("type").and_then(|t| t.as_str()) == Some("chat") {
            query_text = val.get("message").and_then(|m| m.as_str()).unwrap_or("").to_string();
        }

    if clm_file.is_empty() {
        let lower = query_text.to_lowercase();
        if lower.contains("hello world") || lower.contains("hello_world") {
            clm_file = "computable_knowledge/Abstract/layer5_system/playbooks/hello_world.yaml".to_string();
        } else if lower.contains("gcd") {
            clm_file = "tests/test_fixtures/fixture_python_gcd.yaml".to_string();
            if let Ok(num_re) = Regex::new(r"\d+") {
                let nums: Vec<&str> = num_re.find_iter(&query_text).map(|m| m.as_str()).collect();
                if nums.len() >= 2 {
                    clm_payload = format!("{} {}", nums[0], nums[1]);
                } else {
                    clm_payload = "24 36".to_string();
                }
            }
        } else if lower.contains("lcm") {
            clm_file = "tests/test_fixtures/fixture_python_lcm.yaml".to_string();
            if let Ok(num_re) = Regex::new(r"\d+") {
                let nums: Vec<&str> = num_re.find_iter(&query_text).map(|m| m.as_str()).collect();
                if nums.len() >= 2 {
                    clm_payload = format!("{} {}", nums[0], nums[1]);
                } else {
                    clm_payload = "12 18".to_string();
                }
            }
        } else if lower.contains("fibonacci") || lower.contains("fib") {
            clm_file = "tests/test_fixtures/fixture_python_fib.yaml".to_string();
            if let Ok(num_re) = Regex::new(r"\d+") {
                if let Some(m) = num_re.find(&query_text) {
                    clm_payload = m.as_str().to_string();
                } else {
                    clm_payload = "10".to_string();
                }
            }
        } else {
            execute_ollama(&query_text, &json_msg, writer).await?;
            return Ok(false);
        }
    }

    execute_clm(&clm_file, &clm_payload, writer).await?;
    Ok(false)
}

pub(super) async fn handle_connection(
    stream: TcpStream,
    _active_connections: Arc<Mutex<HashSet<String>>>,
    shutdown_trigger: Arc<tokio::sync::Notify>,
) -> Result<(), String> {
    let ws_stream = accept_async(stream).await
        .map_err(|e| format!("WebSocket handshake failed: {}", e))?;

    println!("[GATEWAY] Client connected successfully.");
    let (ws_writer, mut ws_reader) = ws_stream.split();
    let ws_writer = Arc::new(Mutex::new(ws_writer));

    while let Some(msg_res) = ws_reader.next().await {
        let msg = match msg_res {
            Ok(m) => m,
            Err(e) => return Err(format!("Error reading WS message: {}", e)),
        };

        if msg.is_text() || msg.is_binary() {
            let text = msg.to_text().unwrap_or("").trim();
            println!("[GATEWAY] Received: {}", text);

            let should_exit = process_message(text, &ws_writer, &shutdown_trigger).await?;
            if should_exit {
                return Ok(());
            }
        }
    }

    println!("[GATEWAY] Client disconnected.");
    Ok(())
}