Skip to main content

clm_rust_core/layer0/
runtime_contract.rs

1// @generated by tools/sync_runtime_contract.py from types/lattice/runtime_contract.json
2// DO NOT EDIT MANUALLY — run `python3 tools/sync_runtime_contract.py --write`
3// Normative Invariant: INV-489 (Declarative Runtime Contract Univalence)
4
5use std::path::{Path, PathBuf};
6
7pub const RUNTIME_CONTRACT_VERSION: &str = "3.1.0";
8pub const TRI_DB_DEFAULT_DIR: &str = "db";
9
10/// Canonical environment variable keys (28 canonical variables).
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum ClmEnvVar {
13    Runtime,
14    Root,
15    DbDir,
16    DbBackend,
17    ZeroFs,
18    AgentDid,
19    SponsorDid,
20    ExecutionLocaleHash,
21    LocaleTrust,
22    HashAlgo,
23    HashConfig,
24    TargetFile,
25    Payload,
26    RunId,
27    StateToken,
28    BindingType,
29    EventLogPath,
30    GateOverride,
31    SkipConditions,
32    SkipGrammar,
33    PetriHalt,
34    PetriKenotic,
35    PetriMarkingDir,
36    PetriVisual,
37    MembrokerPort,
38    MembrokerNoDisk,
39    MembrokerSnapDir,
40    ForbidSubprocess,
41}
42
43impl ClmEnvVar {
44    pub const fn canonical_name(self) -> &'static str {
45        match self {
46            Self::Runtime => "CLM_RUNTIME",
47            Self::Root => "CLM_ROOT",
48            Self::DbDir => "CLM_DB_DIR",
49            Self::DbBackend => "CLM_DB_BACKEND",
50            Self::ZeroFs => "CLM_ZERO_FS",
51            Self::AgentDid => "CLM_AGENT_DID",
52            Self::SponsorDid => "CLM_SPONSOR_DID",
53            Self::ExecutionLocaleHash => "CLM_EXECUTION_LOCALE_HASH",
54            Self::LocaleTrust => "CLM_LOCALE_TRUST",
55            Self::HashAlgo => "CLM_HASH_ALGO",
56            Self::HashConfig => "CLM_HASH_CONFIG",
57            Self::TargetFile => "CLM_TARGET_FILE",
58            Self::Payload => "CLM_PAYLOAD",
59            Self::RunId => "CLM_RUN_ID",
60            Self::StateToken => "CLM_STATE_TOKEN",
61            Self::BindingType => "CLM_BINDING_TYPE",
62            Self::EventLogPath => "CLM_EVENT_LOG_PATH",
63            Self::GateOverride => "CLM_GATE_OVERRIDE",
64            Self::SkipConditions => "CLM_SKIP_CONDITIONS",
65            Self::SkipGrammar => "CLM_SKIP_GRAMMAR",
66            Self::PetriHalt => "CLM_PETRI_HALT",
67            Self::PetriKenotic => "CLM_PETRI_KENOTIC",
68            Self::PetriMarkingDir => "CLM_PETRI_MARKING_DIR",
69            Self::PetriVisual => "CLM_PETRI_VISUAL",
70            Self::MembrokerPort => "CLM_MEMBROKER_PORT",
71            Self::MembrokerNoDisk => "CLM_MEMBROKER_NO_DISK",
72            Self::MembrokerSnapDir => "CLM_MEMBROKER_SNAP_DIR",
73            Self::ForbidSubprocess => "CLM_FORBID_SUBPROCESS",
74        }
75    }
76
77    pub const fn default_value(self) -> &'static str {
78        match self {
79            Self::Runtime => "rust",
80            Self::Root => ".",
81            Self::DbDir => "db",
82            Self::DbBackend => "sqlite",
83            Self::ZeroFs => "false",
84            Self::AgentDid => "did:clm:system:bootstrap",
85            Self::SponsorDid => "",
86            Self::ExecutionLocaleHash => "locale:local:default",
87            Self::LocaleTrust => "sovereign",
88            Self::HashAlgo => "blake3",
89            Self::HashConfig => "types/lattice/clm_features.yaml",
90            Self::TargetFile => "",
91            Self::Payload => "",
92            Self::RunId => "",
93            Self::StateToken => "",
94            Self::BindingType => "native",
95            Self::EventLogPath => "data/execution_logs",
96            Self::GateOverride => "",
97            Self::SkipConditions => "false",
98            Self::SkipGrammar => "false",
99            Self::PetriHalt => "false",
100            Self::PetriKenotic => "false",
101            Self::PetriMarkingDir => "data/execution_logs/markings",
102            Self::PetriVisual => "false",
103            Self::MembrokerPort => "0",
104            Self::MembrokerNoDisk => "false",
105            Self::MembrokerSnapDir => "data/db/snapshots",
106            Self::ForbidSubprocess => "false",
107        }
108    }
109
110    pub const fn aliases(self) -> &'static [&'static str] {
111        match self {
112            Self::Runtime => &["CLM_RUNTIME", "CLM_RUNNER", "CLM_RUNTIME_BACKEND", "CLM_POLYGLOT_RUNTIME"],
113            Self::Root => &["CLM_ROOT", "PROJECT_ROOT", "CLM_PROJECT_ROOT", "CLM_HOME"],
114            Self::DbDir => &["CLM_DB_DIR", "CLM_DB_PATH", "CLM_DB_FILE", "CLM_MCARD_DB", "MCARD_DB_PATH"],
115            Self::DbBackend => &["CLM_DB_BACKEND", "CLM_MEM_TRIDB", "CLM_ISOLATED_DB", "CLM_SANDBOX"],
116            Self::ZeroFs => &["CLM_ZERO_FS", "CLM_MEMBROKER_NO_DISK"],
117            Self::AgentDid => &["CLM_AGENT_DID", "ACTIVE_AGENT_DID", "CLM_AUTHOR_DID"],
118            Self::SponsorDid => &["CLM_SPONSOR_DID", "CLM_KENOTIC_SPONSOR_DID", "CLM_DELEGATED_PARENT_DID", "CLM_RESOLVE_ALLOWED_SPONSORS"],
119            Self::ExecutionLocaleHash => &["CLM_EXECUTION_LOCALE_HASH", "CLM_KENOTIC_CURRENT_MARKING_HASH"],
120            Self::LocaleTrust => &["CLM_LOCALE_TRUST", "CLM_RUNTIME_FACTS"],
121            Self::HashAlgo => &["CLM_HASH_ALGO", "CLM_HASH_DEFAULT"],
122            Self::HashConfig => &["CLM_HASH_CONFIG", "CLM_LAST_MCARD_HASH"],
123            Self::TargetFile => &["CLM_TARGET_FILE", "CLM_ACTIVE_FILE", "CLM_FILE", "TARGET_FILE", "CLM_NESTED_FILE", "CLM_LAST_MCARD_FILE"],
124            Self::Payload => &["CLM_PAYLOAD", "CLM_MLP_CONTEXT", "CLM_TRANSPORT_REF"],
125            Self::RunId => &["CLM_RUN_ID", "CLM_NESTED_EXEC"],
126            Self::StateToken => &["CLM_STATE_TOKEN", "CLM_DISPATCH_SOCK"],
127            Self::BindingType => &["CLM_BINDING_TYPE"],
128            Self::EventLogPath => &["CLM_EVENT_LOG_PATH", "CLM_REPL_TRACE"],
129            Self::GateOverride => &["CLM_GATE_OVERRIDE", "CLM_MOCK_LLM_BEHAVIOR", "CLM_MOCK_OI_BEHAVIOR"],
130            Self::SkipConditions => &["CLM_SKIP_CONDITIONS"],
131            Self::SkipGrammar => &["CLM_SKIP_GRAMMAR"],
132            Self::PetriHalt => &["CLM_PETRI_HALT"],
133            Self::PetriKenotic => &["CLM_PETRI_KENOTIC"],
134            Self::PetriMarkingDir => &["CLM_PETRI_MARKING_DIR"],
135            Self::PetriVisual => &["CLM_PETRI_VISUAL", "CLM_DEBUG", "CLM_VERBOSE"],
136            Self::MembrokerPort => &["CLM_MEMBROKER_PORT"],
137            Self::MembrokerNoDisk => &["CLM_MEMBROKER_NO_DISK"],
138            Self::MembrokerSnapDir => &["CLM_MEMBROKER_SNAP_DIR"],
139            Self::ForbidSubprocess => &["CLM_FORBID_SUBPROCESS", "CLM_SOVEREIGN_STRICT"],
140        }
141    }
142}
143
144/// Resolve a canonical environment variable by checking its canonical name and deprecated aliases in order.
145pub fn resolve_env(var: ClmEnvVar) -> Option<String> {
146    for key in var.aliases() {
147        if let Ok(val) = std::env::var(key) {
148            if !val.is_empty() {
149                return Some(val);
150            }
151        }
152    }
153    None
154}
155
156pub fn resolve_env_or_default(var: ClmEnvVar) -> String {
157    resolve_env(var).unwrap_or_else(|| var.default_value().to_string())
158}
159
160pub const ENV_PASSTHROUGH_WHITELIST: &[&str; 69] = &[
161    "CLM_RUNTIME",
162    "CLM_RUNNER",
163    "CLM_RUNTIME_BACKEND",
164    "CLM_POLYGLOT_RUNTIME",
165    "CLM_ROOT",
166    "PROJECT_ROOT",
167    "CLM_DB_DIR",
168    "CLM_DB_PATH",
169    "CLM_DB_BACKEND",
170    "CLM_MEM_TRIDB",
171    "CLM_ZERO_FS",
172    "CLM_AGENT_DID",
173    "ACTIVE_AGENT_DID",
174    "CLM_SPONSOR_DID",
175    "CLM_KENOTIC_SPONSOR_DID",
176    "CLM_EXECUTION_LOCALE_HASH",
177    "CLM_KENOTIC_CURRENT_MARKING_HASH",
178    "CLM_LOCALE_TRUST",
179    "CLM_HASH_ALGO",
180    "CLM_HASH_CONFIG",
181    "CLM_TARGET_FILE",
182    "CLM_ACTIVE_FILE",
183    "CLM_FILE",
184    "TARGET_FILE",
185    "CLM_PAYLOAD",
186    "CLM_PAYLOAD_FILE",
187    "CLM_RUN_ID",
188    "CLM_STATE_TOKEN",
189    "CLM_BINDING_TYPE",
190    "CLM_EVENT_LOG_PATH",
191    "CLM_GATE_OVERRIDE",
192    "CLM_SKIP_CONDITIONS",
193    "CLM_SKIP_GRAMMAR",
194    "CLM_PETRI_HALT",
195    "CLM_PETRI_KENOTIC",
196    "CLM_PETRI_MARKING_DIR",
197    "CLM_PETRI_VISUAL",
198    "CLM_FORBID_SUBPROCESS",
199    "CLM_NESTED_EXEC",
200    "CLM_RUST_DAEMON_PORT",
201    "CLM_RUST_PORT_FILE",
202    "CLM_ACTIVE_A_HASH",
203    "CLM_ACTIVE_B_HASH",
204    "CLM_ACTIVE_C_HASH",
205    "CLM_MLP_CONTEXT",
206    "CLM_SESSION_DELEGATION",
207    "CLM_TRANSPORT_REF",
208    "CLM_REPL_TRACE",
209    "CLM_NO_SANDBOX",
210    "CLM_SYMBOL_HANDLES",
211    "CLM_MEMBROKER_PORT",
212    "CLM_MEMBROKER_NO_DISK",
213    "CLM_MEMBROKER_SNAP_DIR",
214    "CLM_SCRATCH",
215    "CLM_TEST_FAST_BOOT",
216    "CLM_QUIET",
217    "CLM_NATIVE_PETRI_VM",
218    "CLM_DISPATCH_SOCK",
219    "CLM_SCRIPT_CONTENT",
220    "CLM_ENTRY_POINT",
221    "CLM_TARGET_PATH",
222    "CLM_AGENT_CLASS",
223    "CLM_AGENT_ROLE",
224    "CLM_RISK_LEVEL",
225    "CLM_EOA_APPROVAL",
226    "CLM_LAST_MCARD_HASH",
227    "CLM_LAST_MCARD_FILE",
228    "ELAN_HOME",
229    "TLA2TOOLS_JAR",
230];
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233pub enum TriDbPillar {
234    ContentMemory,
235    ExecutionLog,
236    AgentIdentities,
237}
238
239impl TriDbPillar {
240    pub const fn filename(self) -> &'static str {
241        match self {
242            Self::ContentMemory => "content_memory.db",
243            Self::ExecutionLog => "execution_log.db",
244            Self::AgentIdentities => "agent_identities.db",
245        }
246    }
247
248    pub const fn legacy_aliases(self) -> &'static [&'static str] {
249        match self {
250            Self::ContentMemory => &["mcard_state.db", "layer0_function_memory.mcard.db"],
251            Self::ExecutionLog => &[],
252            Self::AgentIdentities => &["sovereign_identity.db"],
253        }
254    }
255}
256
257/// Resolve a Tri-DB pillar path under `root`, checking canonical `data/db/<filename>` first,
258/// then legacy aliases if an existing database file is present.
259pub fn resolve_tri_db_path(root: &Path, pillar: TriDbPillar) -> PathBuf {
260    let db_dir_rel = resolve_env_or_default(ClmEnvVar::DbDir);
261    let canonical_dir = root.join(&db_dir_rel);
262    let canonical_path = canonical_dir.join(pillar.filename());
263    if canonical_path.exists() {
264        return canonical_path;
265    }
266    for alias in pillar.legacy_aliases() {
267        let candidate = canonical_dir.join(alias);
268        if candidate.exists() {
269            return candidate;
270        }
271    }
272    canonical_path
273}
274
275pub const SQLITE_PRAGMAS: &str = "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=NORMAL;\nPRAGMA foreign_keys=ON;\nPRAGMA busy_timeout=5000;";
276pub 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);";
277
278pub mod knowledge_paths {
279    pub const VERIFY_PRECONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml";
280    pub const VALIDATE_POSTCONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml";
281    pub const GATE_PAYLOAD_NONEMPTY: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml";
282    pub const GATE_RESULT_SEALED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml";
283    pub const GATE_AGENT_AUTHORIZED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/agent_authorized.yaml";
284    pub const GATE_DB_ACCESSIBLE: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/db_accessible.yaml";
285    pub const GATE_FILE_EXISTS: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/file_exists.yaml";
286    pub const AGENT_WRITE_SCOPE: &str = "types/governance/agent_write_scope.yaml";
287    pub const ESCALATION_GATE: &str = "types/governance/escalation_gate.yaml";
288    pub const CLM_FEATURES: &str = "types/lattice/clm_features.yaml";
289    pub const TYPE_DICTIONARY: &str = "types/lattice/type_dictionary.json";
290    pub const RUNTIME_CONTRACT: &str = "types/lattice/runtime_contract.json";
291    pub const MCARD_SCHEMA_SQL: &str = "types/schemas/mcard_schema.sql";
292    pub const META_TOP: &str = "types/meta/top.yaml";
293    pub const META_BOTTOM: &str = "types/meta/bottom.yaml";
294    pub const META_A_MCARD: &str = "types/meta/a_mcard.yaml";
295    pub const META_B_MCARD: &str = "types/meta/b_mcard.yaml";
296    pub const META_C_MCARD: &str = "types/meta/c_mcard.yaml";
297    pub const EXECUTION_LOGS_DIR: &str = "data/execution_logs";
298    pub const EXECUTION_TMP_DIR: &str = "data/execution_logs/.tmp";
299}
300
301pub mod uri_schemes {
302    pub const MCARD: &str = "mcard://";
303    pub const CLM: &str = "clm://";
304    pub const GATE: &str = "gate:";
305    pub const SCRIPT: &str = "script:";
306    pub const FILE: &str = "file:";
307    pub const DB: &str = "db://";
308    pub const VCARD_CALLBACK: &str = "vcard:callback:";
309    pub const VCARD_DISPATCH: &str = "vcard:dispatch:";
310    pub const DID_CLM: &str = "did:clm:";
311    pub const URN_MCARD: &str = "urn:mcard:";
312}
313
314pub mod hash_prefixes {
315    pub const SHA256: &str = "sha256:";
316    pub const BLAKE3: &str = "blake3:";
317    pub const SHA512: &str = "sha512:";
318    pub const SHA3_256: &str = "sha3-256:";
319    pub const SHA1: &str = "sha1:";
320    pub const MD5: &str = "md5:";
321}
322
323#[repr(i32)]
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
325pub enum ClmExitCode {
326    Ok = 0,
327    GeneralError = 1,
328    ContentMissing = 2,
329    PreconditionOrBoundaryViolation = 5,
330    PostconditionOrCycleViolation = 6,
331    Timeout = 124,
332}
333
334impl ClmExitCode {
335    pub const fn code(self) -> i32 {
336        self as i32
337    }
338}
339
340pub fn resolve_env_from_map<S: ::std::hash::BuildHasher>(
341    var: ClmEnvVar,
342    env: &std::collections::HashMap<String, String, S>,
343) -> Option<String> {
344    for key in var.aliases() {
345        if let Some(val) = env.get(*key) {
346            if !val.is_empty() {
347                return Some(val.clone());
348            }
349        }
350    }
351    None
352}
353
354#[cfg(test)]
355#[allow(clippy::module_inception)]
356mod runtime_contract {
357    use super::*;
358    use std::collections::HashMap;
359
360    #[test]
361    fn test_runtime_contract_ssot_constants() {
362        assert_eq!(RUNTIME_CONTRACT_VERSION, "3.1.0");
363        assert_eq!(ClmEnvVar::Runtime.canonical_name(), "CLM_RUNTIME");
364        assert_eq!(TriDbPillar::ContentMemory.filename(), "content_memory.db");
365        assert_eq!(ClmExitCode::PreconditionOrBoundaryViolation.code(), 5);
366        assert_eq!(ClmExitCode::PostconditionOrCycleViolation.code(), 6);
367        assert!(SQLITE_DDL_V3_1.contains("CREATE TABLE IF NOT EXISTS handle_registry"));
368    }
369
370    #[test]
371    fn test_synonym_alias_resolution_from_map() {
372        let mut m = HashMap::new();
373        m.insert("CLM_RUNNER".to_string(), "node".to_string());
374        m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
375        m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
376        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
377        assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
378        assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
379    }
380    #[test]
381    fn alias_vectors() {
382        let mut m = HashMap::new();
383        m.insert("CLM_RUNNER".to_string(), "node".to_string());
384        m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
385        m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
386        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
387        assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
388        assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
389        // Canonical key wins over deprecated alias
390        m.insert("CLM_RUNTIME".to_string(), "rust".to_string());
391        assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("rust"));
392    }
393
394    #[test]
395    fn hash_algorithm_vectors() {
396        use sha2::{Digest, Sha256, Sha512};
397        let payload = b"clm-tri-runtime-univalence-v3.1.0";
398        let b3 = format!("{}{}", hash_prefixes::BLAKE3, blake3::hash(payload).to_hex());
399        let s256 = format!("{}{}", hash_prefixes::SHA256, hex::encode(Sha256::digest(payload)));
400        let s512 = format!("{}{}", hash_prefixes::SHA512, hex::encode(Sha512::digest(payload)));
401        assert!(b3.starts_with("blake3:"));
402        assert_eq!(b3.len(), 7 + 64);
403        assert!(s256.starts_with("sha256:"));
404        assert_eq!(s256.len(), 7 + 64);
405        assert!(s512.starts_with("sha512:"));
406        assert_eq!(s512.len(), 7 + 128);
407    }
408}