clm-kernel 0.0.21

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
// @generated by tools/types/sync_runtime_contract.py from types/lattice/runtime_contract.json
// DO NOT EDIT MANUALLY — run `python3 tools/types/sync_runtime_contract.py --write`
// Normative Invariant: INV-489 (Declarative Runtime Contract Univalence)

use std::path::{Path, PathBuf};

pub const RUNTIME_CONTRACT_VERSION: &str = "3.1.0";
pub const TRI_DB_DEFAULT_DIR: &str = "db";

#[path = "runtime_env.rs"]
mod runtime_env;
pub use runtime_env::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TriDbPillar {
    ContentMemory,
    ExecutionLog,
    AgentIdentities,
}

impl TriDbPillar {
    pub const fn canonical_name(self) -> &'static str {
        match self {
            Self::ContentMemory => "content_memory",
            Self::ExecutionLog => "execution_log",
            Self::AgentIdentities => "agent_identities",
        }
    }
    pub const fn filename(self) -> &'static str {
        match self {
            Self::ContentMemory => "content_memory.db",
            Self::ExecutionLog => "execution_log.db",
            Self::AgentIdentities => "agent_identities.db",
        }
    }

    pub const fn legacy_aliases(self) -> &'static [&'static str] {
        match self {
            Self::ContentMemory => &["mcard_state.db", "layer0_function_memory.mcard.db"],
            Self::ExecutionLog => &[],
            Self::AgentIdentities => &["sovereign_identity.db"],
        }
    }
}

/// Resolve a Tri-DB pillar path under `root`, checking canonical `data/db/<filename>` first,
/// then legacy aliases if an existing database file is present.
pub fn resolve_tri_db_path(root: &Path, pillar: TriDbPillar) -> PathBuf {
    let db_dir_rel = resolve_env_or_default(ClmEnvVar::DbDir);
    let canonical_dir = root.join(&db_dir_rel);
    let canonical_path = canonical_dir.join(pillar.filename());
    if canonical_path.exists() {
        return canonical_path;
    }
    for alias in pillar.legacy_aliases() {
        let candidate = canonical_dir.join(alias);
        if candidate.exists() {
            return candidate;
        }
    }
    canonical_path
}

pub const SQLITE_PRAGMAS: &str = "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=NORMAL;\nPRAGMA foreign_keys=ON;\nPRAGMA busy_timeout=5000;";
pub const SQLITE_DDL_V3_1: &str = "CREATE TABLE IF NOT EXISTS card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);\nCREATE TABLE IF NOT EXISTS handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, updated_at TEXT NOT NULL, FOREIGN KEY (current_hash) REFERENCES card(hash));\nCREATE INDEX IF NOT EXISTS idx_handle_current_hash ON handle_registry(current_hash);\nCREATE TABLE IF NOT EXISTS handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL, FOREIGN KEY (handle) REFERENCES handle_registry(handle), FOREIGN KEY (previous_hash) REFERENCES card(hash));\nCREATE INDEX IF NOT EXISTS idx_handle_history_handle ON handle_history(handle);";

pub mod knowledge_paths {
    pub const VERIFY_PRECONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml";
    pub const VALIDATE_POSTCONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml";
    pub const GATE_PAYLOAD_NONEMPTY: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml";
    pub const GATE_RESULT_SEALED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml";
    pub const GATE_AGENT_AUTHORIZED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/agent_authorized.yaml";
    pub const GATE_DB_ACCESSIBLE: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/db_accessible.yaml";
    pub const GATE_FILE_EXISTS: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/file_exists.yaml";
    pub const AGENT_WRITE_SCOPE: &str = "types/governance/agent_write_scope.yaml";
    pub const ESCALATION_GATE: &str = "types/governance/escalation_gate.yaml";
    pub const CLM_FEATURES: &str = "types/lattice/clm_features.yaml";
    pub const TYPE_DICTIONARY: &str = "types/lattice/type_dictionary.json";
    pub const RUNTIME_CONTRACT: &str = "types/lattice/runtime_contract.json";
    pub const MCARD_SCHEMA_SQL: &str = "types/schemas/mcard_schema.sql";
    pub const META_TOP: &str = "types/meta/top.yaml";
    pub const META_BOTTOM: &str = "types/meta/bottom.yaml";
    pub const META_A_MCARD: &str = "types/meta/a_mcard.yaml";
    pub const META_B_MCARD: &str = "types/meta/b_mcard.yaml";
    pub const META_C_MCARD: &str = "types/meta/c_mcard.yaml";
    pub const EXECUTION_LOGS_DIR: &str = "data/execution_logs";
    pub const EXECUTION_TMP_DIR: &str = "data/execution_logs/.tmp";
}

pub mod uri_schemes {
    pub const MCARD: &str = "mcard://";
    pub const CLM: &str = "clm://";
    pub const GATE: &str = "gate:";
    pub const SCRIPT: &str = "script:";
    pub const FILE: &str = "file:";
    pub const DB: &str = "db://";
    pub const VCARD_CALLBACK: &str = "vcard:callback:";
    pub const VCARD_DISPATCH: &str = "vcard:dispatch:";
    pub const DID_CLM: &str = "did:clm:";
    pub const URN_MCARD: &str = "urn:mcard:";
}

pub mod hash_prefixes {
    pub const SHA256: &str = "sha256:";
    pub const BLAKE3: &str = "blake3:";
    pub const SHA512: &str = "sha512:";
    pub const SHA3_256: &str = "sha3-256:";
    pub const SHA1: &str = "sha1:";
    pub const MD5: &str = "md5:";
}

#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClmExitCode {
    Ok = 0,
    GeneralError = 1,
    ContentMissing = 2,
    TamperOrSignatureFailure = 3,
    PreconditionOrBoundaryViolation = 5,
    PostconditionOrCycleViolation = 6,
    Timeout = 124,
}

impl ClmExitCode {
    pub const fn code(self) -> i32 {
        self as i32
    }
}

#[cfg(test)]
#[allow(clippy::module_inception)]
mod runtime_contract {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_runtime_contract_ssot_constants() {
        assert_eq!(RUNTIME_CONTRACT_VERSION, "3.1.0");
        assert_eq!(ClmEnvVar::Runtime.canonical_name(), "CLM_RUNTIME");
        assert_eq!(TriDbPillar::ContentMemory.filename(), "content_memory.db");
        assert_eq!(ClmExitCode::PreconditionOrBoundaryViolation.code(), 5);
        assert_eq!(ClmExitCode::PostconditionOrCycleViolation.code(), 6);
        assert!(SQLITE_DDL_V3_1.contains("CREATE TABLE IF NOT EXISTS handle_registry"));
    }

    #[test]
    fn test_synonym_alias_resolution_from_map() {
        let mut m = HashMap::new();
        m.insert("CLM_RUNNER".to_string(), "node".to_string());
        m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
        m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
        assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
        assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
    }
    #[test]
    fn alias_vectors() {
        let mut m = HashMap::new();
        m.insert("CLM_RUNNER".to_string(), "node".to_string());
        m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
        m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
        assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
        assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
        // Canonical key wins over deprecated alias
        m.insert("CLM_RUNTIME".to_string(), "rust".to_string());
        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("rust"));
    }

    #[test]
    fn hash_algorithm_vectors() {
        use sha2::{Digest, Sha256, Sha512};
        let payload = b"clm-tri-runtime-univalence-v3.1.0";
        let b3 = format!("{}{}", hash_prefixes::BLAKE3, blake3::hash(payload).to_hex());
        let s256 = format!("{}{}", hash_prefixes::SHA256, hex::encode(Sha256::digest(payload)));
        let s512 = format!("{}{}", hash_prefixes::SHA512, hex::encode(Sha512::digest(payload)));
        assert!(b3.starts_with("blake3:"));
        assert_eq!(b3.len(), 7 + 64);
        assert!(s256.starts_with("sha256:"));
        assert_eq!(s256.len(), 7 + 64);
        assert!(s512.starts_with("sha512:"));
        assert_eq!(s512.len(), 7 + 128);
    }
}

#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RouteHandleOutcome {
    Ok = 0,
    NotFound = 1,
    NetworkError = 2,
    StaleFallback = 3,
}

pub const fn route_handle_exit_code(outcome: RouteHandleOutcome) -> ClmExitCode {
    match outcome {
        RouteHandleOutcome::Ok => ClmExitCode::Ok,
        RouteHandleOutcome::NotFound => ClmExitCode::ContentMissing,
        RouteHandleOutcome::NetworkError => ClmExitCode::GeneralError,
        RouteHandleOutcome::StaleFallback => ClmExitCode::Ok,
    }
}

pub const SQLITE_BUSY_TIMEOUT_MS: u32 = 5000;
pub const SQLITE_COMPACTION_BUSY_TIMEOUT_MS: u32 = 30000;
pub const SQLITE_LOCK_RETRY_MAX: u32 = 5;
pub const SQLITE_LOCK_RETRY_BACKOFF_MS: u32 = 50;
pub const CODEC_B64_CHUNK_BYTES: usize = 12288;
pub const TEXT_ENCODING: &str = "utf-8";
pub const NETWORK_GATEWAY_TIMEOUT_MS: u32 = 10000;

pub const SQLITE_BUSY: i32 = 5;
pub const SQLITE_LOCKED: i32 = 6;
pub const SQLITE_READONLY: i32 = 8;
pub const SQLITE_PRIMARY_CODE_MASK: i32 = 255;

pub const fn sqlite_lock_retry_delay_ms(retry: u32) -> u32 {
    let bounded = if retry > SQLITE_LOCK_RETRY_MAX { SQLITE_LOCK_RETRY_MAX } else { retry };
    bounded * SQLITE_LOCK_RETRY_BACKOFF_MS
}