// @generated by tools/sync_runtime_contract.py from types/lattice/runtime_contract.json
// DO NOT EDIT MANUALLY — run `python3 tools/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";
/// Canonical environment variable keys (28 canonical variables).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClmEnvVar {
Runtime,
Root,
DbDir,
DbBackend,
ZeroFs,
AgentDid,
SponsorDid,
ExecutionLocaleHash,
LocaleTrust,
HashAlgo,
HashConfig,
TargetFile,
Payload,
RunId,
StateToken,
BindingType,
EventLogPath,
GateOverride,
SkipConditions,
SkipGrammar,
PetriHalt,
PetriKenotic,
PetriMarkingDir,
PetriVisual,
MembrokerPort,
MembrokerNoDisk,
MembrokerSnapDir,
ForbidSubprocess,
}
impl ClmEnvVar {
pub const fn canonical_name(self) -> &'static str {
match self {
Self::Runtime => "CLM_RUNTIME",
Self::Root => "CLM_ROOT",
Self::DbDir => "CLM_DB_DIR",
Self::DbBackend => "CLM_DB_BACKEND",
Self::ZeroFs => "CLM_ZERO_FS",
Self::AgentDid => "CLM_AGENT_DID",
Self::SponsorDid => "CLM_SPONSOR_DID",
Self::ExecutionLocaleHash => "CLM_EXECUTION_LOCALE_HASH",
Self::LocaleTrust => "CLM_LOCALE_TRUST",
Self::HashAlgo => "CLM_HASH_ALGO",
Self::HashConfig => "CLM_HASH_CONFIG",
Self::TargetFile => "CLM_TARGET_FILE",
Self::Payload => "CLM_PAYLOAD",
Self::RunId => "CLM_RUN_ID",
Self::StateToken => "CLM_STATE_TOKEN",
Self::BindingType => "CLM_BINDING_TYPE",
Self::EventLogPath => "CLM_EVENT_LOG_PATH",
Self::GateOverride => "CLM_GATE_OVERRIDE",
Self::SkipConditions => "CLM_SKIP_CONDITIONS",
Self::SkipGrammar => "CLM_SKIP_GRAMMAR",
Self::PetriHalt => "CLM_PETRI_HALT",
Self::PetriKenotic => "CLM_PETRI_KENOTIC",
Self::PetriMarkingDir => "CLM_PETRI_MARKING_DIR",
Self::PetriVisual => "CLM_PETRI_VISUAL",
Self::MembrokerPort => "CLM_MEMBROKER_PORT",
Self::MembrokerNoDisk => "CLM_MEMBROKER_NO_DISK",
Self::MembrokerSnapDir => "CLM_MEMBROKER_SNAP_DIR",
Self::ForbidSubprocess => "CLM_FORBID_SUBPROCESS",
}
}
pub const fn default_value(self) -> &'static str {
match self {
Self::Runtime => "rust",
Self::Root => ".",
Self::DbDir => "db",
Self::DbBackend => "sqlite",
Self::ZeroFs => "false",
Self::AgentDid => "did:clm:system:bootstrap",
Self::SponsorDid => "",
Self::ExecutionLocaleHash => "locale:local:default",
Self::LocaleTrust => "sovereign",
Self::HashAlgo => "blake3",
Self::HashConfig => "types/lattice/clm_features.yaml",
Self::TargetFile => "",
Self::Payload => "",
Self::RunId => "",
Self::StateToken => "",
Self::BindingType => "native",
Self::EventLogPath => "data/execution_logs",
Self::GateOverride => "",
Self::SkipConditions => "false",
Self::SkipGrammar => "false",
Self::PetriHalt => "false",
Self::PetriKenotic => "false",
Self::PetriMarkingDir => "data/execution_logs/markings",
Self::PetriVisual => "false",
Self::MembrokerPort => "0",
Self::MembrokerNoDisk => "false",
Self::MembrokerSnapDir => "data/db/snapshots",
Self::ForbidSubprocess => "false",
}
}
pub const fn aliases(self) -> &'static [&'static str] {
match self {
Self::Runtime => &["CLM_RUNTIME", "CLM_RUNNER", "CLM_RUNTIME_BACKEND", "CLM_POLYGLOT_RUNTIME"],
Self::Root => &["CLM_ROOT", "PROJECT_ROOT", "CLM_PROJECT_ROOT", "CLM_HOME"],
Self::DbDir => &["CLM_DB_DIR", "CLM_DB_PATH", "CLM_DB_FILE", "CLM_MCARD_DB", "MCARD_DB_PATH"],
Self::DbBackend => &["CLM_DB_BACKEND", "CLM_MEM_TRIDB", "CLM_ISOLATED_DB", "CLM_SANDBOX"],
Self::ZeroFs => &["CLM_ZERO_FS", "CLM_MEMBROKER_NO_DISK"],
Self::AgentDid => &["CLM_AGENT_DID", "ACTIVE_AGENT_DID", "CLM_AUTHOR_DID"],
Self::SponsorDid => &["CLM_SPONSOR_DID", "CLM_KENOTIC_SPONSOR_DID", "CLM_DELEGATED_PARENT_DID", "CLM_RESOLVE_ALLOWED_SPONSORS"],
Self::ExecutionLocaleHash => &["CLM_EXECUTION_LOCALE_HASH", "CLM_KENOTIC_CURRENT_MARKING_HASH"],
Self::LocaleTrust => &["CLM_LOCALE_TRUST", "CLM_RUNTIME_FACTS"],
Self::HashAlgo => &["CLM_HASH_ALGO", "CLM_HASH_DEFAULT"],
Self::HashConfig => &["CLM_HASH_CONFIG", "CLM_LAST_MCARD_HASH"],
Self::TargetFile => &["CLM_TARGET_FILE", "CLM_ACTIVE_FILE", "CLM_FILE", "TARGET_FILE", "CLM_NESTED_FILE", "CLM_LAST_MCARD_FILE"],
Self::Payload => &["CLM_PAYLOAD", "CLM_MLP_CONTEXT", "CLM_TRANSPORT_REF"],
Self::RunId => &["CLM_RUN_ID", "CLM_NESTED_EXEC"],
Self::StateToken => &["CLM_STATE_TOKEN", "CLM_DISPATCH_SOCK"],
Self::BindingType => &["CLM_BINDING_TYPE"],
Self::EventLogPath => &["CLM_EVENT_LOG_PATH", "CLM_REPL_TRACE"],
Self::GateOverride => &["CLM_GATE_OVERRIDE", "CLM_MOCK_LLM_BEHAVIOR", "CLM_MOCK_OI_BEHAVIOR"],
Self::SkipConditions => &["CLM_SKIP_CONDITIONS"],
Self::SkipGrammar => &["CLM_SKIP_GRAMMAR"],
Self::PetriHalt => &["CLM_PETRI_HALT"],
Self::PetriKenotic => &["CLM_PETRI_KENOTIC"],
Self::PetriMarkingDir => &["CLM_PETRI_MARKING_DIR"],
Self::PetriVisual => &["CLM_PETRI_VISUAL", "CLM_DEBUG", "CLM_VERBOSE"],
Self::MembrokerPort => &["CLM_MEMBROKER_PORT"],
Self::MembrokerNoDisk => &["CLM_MEMBROKER_NO_DISK"],
Self::MembrokerSnapDir => &["CLM_MEMBROKER_SNAP_DIR"],
Self::ForbidSubprocess => &["CLM_FORBID_SUBPROCESS", "CLM_SOVEREIGN_STRICT"],
}
}
}
/// Resolve a canonical environment variable by checking its canonical name and deprecated aliases in order.
pub fn resolve_env(var: ClmEnvVar) -> Option<String> {
for key in var.aliases() {
if let Ok(val) = std::env::var(key) {
if !val.is_empty() {
return Some(val);
}
}
}
None
}
pub fn resolve_env_or_default(var: ClmEnvVar) -> String {
resolve_env(var).unwrap_or_else(|| var.default_value().to_string())
}
pub const ENV_PASSTHROUGH_WHITELIST: &[&str; 67] = &[
"CLM_RUNTIME",
"CLM_RUNNER",
"CLM_RUNTIME_BACKEND",
"CLM_POLYGLOT_RUNTIME",
"CLM_ROOT",
"PROJECT_ROOT",
"CLM_DB_DIR",
"CLM_DB_PATH",
"CLM_DB_BACKEND",
"CLM_MEM_TRIDB",
"CLM_ZERO_FS",
"CLM_AGENT_DID",
"ACTIVE_AGENT_DID",
"CLM_SPONSOR_DID",
"CLM_KENOTIC_SPONSOR_DID",
"CLM_EXECUTION_LOCALE_HASH",
"CLM_KENOTIC_CURRENT_MARKING_HASH",
"CLM_LOCALE_TRUST",
"CLM_HASH_ALGO",
"CLM_HASH_CONFIG",
"CLM_TARGET_FILE",
"CLM_ACTIVE_FILE",
"CLM_FILE",
"TARGET_FILE",
"CLM_PAYLOAD",
"CLM_PAYLOAD_FILE",
"CLM_RUN_ID",
"CLM_STATE_TOKEN",
"CLM_BINDING_TYPE",
"CLM_EVENT_LOG_PATH",
"CLM_GATE_OVERRIDE",
"CLM_SKIP_CONDITIONS",
"CLM_SKIP_GRAMMAR",
"CLM_PETRI_HALT",
"CLM_PETRI_KENOTIC",
"CLM_PETRI_MARKING_DIR",
"CLM_PETRI_VISUAL",
"CLM_FORBID_SUBPROCESS",
"CLM_NESTED_EXEC",
"CLM_RUST_DAEMON_PORT",
"CLM_RUST_PORT_FILE",
"CLM_ACTIVE_A_HASH",
"CLM_ACTIVE_B_HASH",
"CLM_ACTIVE_C_HASH",
"CLM_MLP_CONTEXT",
"CLM_SESSION_DELEGATION",
"CLM_TRANSPORT_REF",
"CLM_REPL_TRACE",
"CLM_NO_SANDBOX",
"CLM_SYMBOL_HANDLES",
"CLM_MEMBROKER_PORT",
"CLM_MEMBROKER_NO_DISK",
"CLM_MEMBROKER_SNAP_DIR",
"CLM_SCRATCH",
"CLM_TEST_FAST_BOOT",
"CLM_QUIET",
"CLM_NATIVE_PETRI_VM",
"CLM_DISPATCH_SOCK",
"CLM_SCRIPT_CONTENT",
"CLM_ENTRY_POINT",
"CLM_TARGET_PATH",
"CLM_AGENT_CLASS",
"CLM_AGENT_ROLE",
"CLM_RISK_LEVEL",
"CLM_EOA_APPROVAL",
"CLM_LAST_MCARD_HASH",
"CLM_LAST_MCARD_FILE",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TriDbPillar {
ContentMemory,
ExecutionLog,
AgentIdentities,
}
impl TriDbPillar {
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,
PreconditionOrBoundaryViolation = 5,
PostconditionOrCycleViolation = 6,
Timeout = 124,
}
impl ClmExitCode {
pub const fn code(self) -> i32 {
self as i32
}
}
pub fn resolve_env_from_map<S: ::std::hash::BuildHasher>(
var: ClmEnvVar,
env: &std::collections::HashMap<String, String, S>,
) -> Option<String> {
for key in var.aliases() {
if let Some(val) = env.get(*key) {
if !val.is_empty() {
return Some(val.clone());
}
}
}
None
}
#[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);
}
}