1use std::path::{Path, PathBuf};
6
7pub const RUNTIME_CONTRACT_VERSION: &str = "3.1.0";
8pub const TRI_DB_DEFAULT_DIR: &str = "db";
9
10#[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
144pub 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; 67] = &[
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];
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231pub enum TriDbPillar {
232 ContentMemory,
233 ExecutionLog,
234 AgentIdentities,
235}
236
237impl TriDbPillar {
238 pub const fn filename(self) -> &'static str {
239 match self {
240 Self::ContentMemory => "content_memory.db",
241 Self::ExecutionLog => "execution_log.db",
242 Self::AgentIdentities => "agent_identities.db",
243 }
244 }
245
246 pub const fn legacy_aliases(self) -> &'static [&'static str] {
247 match self {
248 Self::ContentMemory => &["mcard_state.db", "layer0_function_memory.mcard.db"],
249 Self::ExecutionLog => &[],
250 Self::AgentIdentities => &["sovereign_identity.db"],
251 }
252 }
253}
254
255pub fn resolve_tri_db_path(root: &Path, pillar: TriDbPillar) -> PathBuf {
258 let db_dir_rel = resolve_env_or_default(ClmEnvVar::DbDir);
259 let canonical_dir = root.join(&db_dir_rel);
260 let canonical_path = canonical_dir.join(pillar.filename());
261 if canonical_path.exists() {
262 return canonical_path;
263 }
264 for alias in pillar.legacy_aliases() {
265 let candidate = canonical_dir.join(alias);
266 if candidate.exists() {
267 return candidate;
268 }
269 }
270 canonical_path
271}
272
273pub const SQLITE_PRAGMAS: &str = "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=NORMAL;\nPRAGMA foreign_keys=ON;\nPRAGMA busy_timeout=5000;";
274pub 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);";
275
276pub mod knowledge_paths {
277 pub const VERIFY_PRECONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml";
278 pub const VALIDATE_POSTCONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml";
279 pub const GATE_PAYLOAD_NONEMPTY: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml";
280 pub const GATE_RESULT_SEALED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml";
281 pub const GATE_AGENT_AUTHORIZED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/agent_authorized.yaml";
282 pub const GATE_DB_ACCESSIBLE: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/db_accessible.yaml";
283 pub const GATE_FILE_EXISTS: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/file_exists.yaml";
284 pub const AGENT_WRITE_SCOPE: &str = "types/governance/agent_write_scope.yaml";
285 pub const ESCALATION_GATE: &str = "types/governance/escalation_gate.yaml";
286 pub const CLM_FEATURES: &str = "types/lattice/clm_features.yaml";
287 pub const TYPE_DICTIONARY: &str = "types/lattice/type_dictionary.json";
288 pub const RUNTIME_CONTRACT: &str = "types/lattice/runtime_contract.json";
289 pub const MCARD_SCHEMA_SQL: &str = "types/schemas/mcard_schema.sql";
290 pub const META_TOP: &str = "types/meta/top.yaml";
291 pub const META_BOTTOM: &str = "types/meta/bottom.yaml";
292 pub const META_A_MCARD: &str = "types/meta/a_mcard.yaml";
293 pub const META_B_MCARD: &str = "types/meta/b_mcard.yaml";
294 pub const META_C_MCARD: &str = "types/meta/c_mcard.yaml";
295 pub const EXECUTION_LOGS_DIR: &str = "data/execution_logs";
296 pub const EXECUTION_TMP_DIR: &str = "data/execution_logs/.tmp";
297}
298
299pub mod uri_schemes {
300 pub const MCARD: &str = "mcard://";
301 pub const CLM: &str = "clm://";
302 pub const GATE: &str = "gate:";
303 pub const SCRIPT: &str = "script:";
304 pub const FILE: &str = "file:";
305 pub const DB: &str = "db://";
306 pub const VCARD_CALLBACK: &str = "vcard:callback:";
307 pub const VCARD_DISPATCH: &str = "vcard:dispatch:";
308 pub const DID_CLM: &str = "did:clm:";
309 pub const URN_MCARD: &str = "urn:mcard:";
310}
311
312pub mod hash_prefixes {
313 pub const SHA256: &str = "sha256:";
314 pub const BLAKE3: &str = "blake3:";
315 pub const SHA512: &str = "sha512:";
316 pub const SHA3_256: &str = "sha3-256:";
317 pub const SHA1: &str = "sha1:";
318 pub const MD5: &str = "md5:";
319}
320
321#[repr(i32)]
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
323pub enum ClmExitCode {
324 Ok = 0,
325 GeneralError = 1,
326 ContentMissing = 2,
327 PreconditionOrBoundaryViolation = 5,
328 PostconditionOrCycleViolation = 6,
329 Timeout = 124,
330}
331
332impl ClmExitCode {
333 pub const fn code(self) -> i32 {
334 self as i32
335 }
336}
337
338pub fn resolve_env_from_map<S: ::std::hash::BuildHasher>(
339 var: ClmEnvVar,
340 env: &std::collections::HashMap<String, String, S>,
341) -> Option<String> {
342 for key in var.aliases() {
343 if let Some(val) = env.get(*key) {
344 if !val.is_empty() {
345 return Some(val.clone());
346 }
347 }
348 }
349 None
350}
351
352#[cfg(test)]
353#[allow(clippy::module_inception)]
354mod runtime_contract {
355 use super::*;
356 use std::collections::HashMap;
357
358 #[test]
359 fn test_runtime_contract_ssot_constants() {
360 assert_eq!(RUNTIME_CONTRACT_VERSION, "3.1.0");
361 assert_eq!(ClmEnvVar::Runtime.canonical_name(), "CLM_RUNTIME");
362 assert_eq!(TriDbPillar::ContentMemory.filename(), "content_memory.db");
363 assert_eq!(ClmExitCode::PreconditionOrBoundaryViolation.code(), 5);
364 assert_eq!(ClmExitCode::PostconditionOrCycleViolation.code(), 6);
365 assert!(SQLITE_DDL_V3_1.contains("CREATE TABLE IF NOT EXISTS handle_registry"));
366 }
367
368 #[test]
369 fn test_synonym_alias_resolution_from_map() {
370 let mut m = HashMap::new();
371 m.insert("CLM_RUNNER".to_string(), "node".to_string());
372 m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
373 m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
374 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
375 assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
376 assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
377 }
378 #[test]
379 fn alias_vectors() {
380 let mut m = HashMap::new();
381 m.insert("CLM_RUNNER".to_string(), "node".to_string());
382 m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
383 m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
384 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
385 assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
386 assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
387 m.insert("CLM_RUNTIME".to_string(), "rust".to_string());
389 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("rust"));
390 }
391
392 #[test]
393 fn hash_algorithm_vectors() {
394 use sha2::{Digest, Sha256, Sha512};
395 let payload = b"clm-tri-runtime-univalence-v3.1.0";
396 let b3 = format!("{}{}", hash_prefixes::BLAKE3, blake3::hash(payload).to_hex());
397 let s256 = format!("{}{}", hash_prefixes::SHA256, hex::encode(Sha256::digest(payload)));
398 let s512 = format!("{}{}", hash_prefixes::SHA512, hex::encode(Sha512::digest(payload)));
399 assert!(b3.starts_with("blake3:"));
400 assert_eq!(b3.len(), 7 + 64);
401 assert!(s256.starts_with("sha256:"));
402 assert_eq!(s256.len(), 7 + 64);
403 assert!(s512.starts_with("sha512:"));
404 assert_eq!(s512.len(), 7 + 128);
405 }
406}