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#[path = "runtime_env.rs"]
11mod runtime_env;
12pub use runtime_env::*;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum TriDbPillar {
16 ContentMemory,
17 ExecutionLog,
18 AgentIdentities,
19}
20
21impl TriDbPillar {
22 pub const fn canonical_name(self) -> &'static str {
23 match self {
24 Self::ContentMemory => "content_memory",
25 Self::ExecutionLog => "execution_log",
26 Self::AgentIdentities => "agent_identities",
27 }
28 }
29 pub const fn filename(self) -> &'static str {
30 match self {
31 Self::ContentMemory => "content_memory.db",
32 Self::ExecutionLog => "execution_log.db",
33 Self::AgentIdentities => "agent_identities.db",
34 }
35 }
36
37 pub const fn legacy_aliases(self) -> &'static [&'static str] {
38 match self {
39 Self::ContentMemory => &["mcard_state.db", "layer0_function_memory.mcard.db"],
40 Self::ExecutionLog => &[],
41 Self::AgentIdentities => &["sovereign_identity.db"],
42 }
43 }
44}
45
46pub fn resolve_tri_db_path(root: &Path, pillar: TriDbPillar) -> PathBuf {
49 let db_dir_rel = resolve_env_or_default(ClmEnvVar::DbDir);
50 let canonical_dir = root.join(&db_dir_rel);
51 let canonical_path = canonical_dir.join(pillar.filename());
52 if canonical_path.exists() {
53 return canonical_path;
54 }
55 for alias in pillar.legacy_aliases() {
56 let candidate = canonical_dir.join(alias);
57 if candidate.exists() {
58 return candidate;
59 }
60 }
61 canonical_path
62}
63
64pub const SQLITE_PRAGMAS: &str = "PRAGMA journal_mode=WAL;\nPRAGMA synchronous=NORMAL;\nPRAGMA foreign_keys=ON;\nPRAGMA busy_timeout=5000;";
65pub 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);";
66
67pub mod knowledge_paths {
68 pub const VERIFY_PRECONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml";
69 pub const VALIDATE_POSTCONDITION: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml";
70 pub const GATE_PAYLOAD_NONEMPTY: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml";
71 pub const GATE_RESULT_SEALED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml";
72 pub const GATE_AGENT_AUTHORIZED: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/agent_authorized.yaml";
73 pub const GATE_DB_ACCESSIBLE: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/db_accessible.yaml";
74 pub const GATE_FILE_EXISTS: &str = "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/file_exists.yaml";
75 pub const AGENT_WRITE_SCOPE: &str = "types/governance/agent_write_scope.yaml";
76 pub const ESCALATION_GATE: &str = "types/governance/escalation_gate.yaml";
77 pub const CLM_FEATURES: &str = "types/lattice/clm_features.yaml";
78 pub const TYPE_DICTIONARY: &str = "types/lattice/type_dictionary.json";
79 pub const RUNTIME_CONTRACT: &str = "types/lattice/runtime_contract.json";
80 pub const MCARD_SCHEMA_SQL: &str = "types/schemas/mcard_schema.sql";
81 pub const META_TOP: &str = "types/meta/top.yaml";
82 pub const META_BOTTOM: &str = "types/meta/bottom.yaml";
83 pub const META_A_MCARD: &str = "types/meta/a_mcard.yaml";
84 pub const META_B_MCARD: &str = "types/meta/b_mcard.yaml";
85 pub const META_C_MCARD: &str = "types/meta/c_mcard.yaml";
86 pub const EXECUTION_LOGS_DIR: &str = "data/execution_logs";
87 pub const EXECUTION_TMP_DIR: &str = "data/execution_logs/.tmp";
88}
89
90pub mod uri_schemes {
91 pub const MCARD: &str = "mcard://";
92 pub const CLM: &str = "clm://";
93 pub const GATE: &str = "gate:";
94 pub const SCRIPT: &str = "script:";
95 pub const FILE: &str = "file:";
96 pub const DB: &str = "db://";
97 pub const VCARD_CALLBACK: &str = "vcard:callback:";
98 pub const VCARD_DISPATCH: &str = "vcard:dispatch:";
99 pub const DID_CLM: &str = "did:clm:";
100 pub const URN_MCARD: &str = "urn:mcard:";
101}
102
103pub mod hash_prefixes {
104 pub const SHA256: &str = "sha256:";
105 pub const BLAKE3: &str = "blake3:";
106 pub const SHA512: &str = "sha512:";
107 pub const SHA3_256: &str = "sha3-256:";
108 pub const SHA1: &str = "sha1:";
109 pub const MD5: &str = "md5:";
110}
111
112#[repr(i32)]
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114pub enum ClmExitCode {
115 Ok = 0,
116 GeneralError = 1,
117 ContentMissing = 2,
118 TamperOrSignatureFailure = 3,
119 PreconditionOrBoundaryViolation = 5,
120 PostconditionOrCycleViolation = 6,
121 Timeout = 124,
122}
123
124impl ClmExitCode {
125 pub const fn code(self) -> i32 {
126 self as i32
127 }
128}
129
130#[cfg(test)]
131#[allow(clippy::module_inception)]
132mod runtime_contract {
133 use super::*;
134 use std::collections::HashMap;
135
136 #[test]
137 fn test_runtime_contract_ssot_constants() {
138 assert_eq!(RUNTIME_CONTRACT_VERSION, "3.1.0");
139 assert_eq!(ClmEnvVar::Runtime.canonical_name(), "CLM_RUNTIME");
140 assert_eq!(TriDbPillar::ContentMemory.filename(), "content_memory.db");
141 assert_eq!(ClmExitCode::PreconditionOrBoundaryViolation.code(), 5);
142 assert_eq!(ClmExitCode::PostconditionOrCycleViolation.code(), 6);
143 assert!(SQLITE_DDL_V3_1.contains("CREATE TABLE IF NOT EXISTS handle_registry"));
144 }
145
146 #[test]
147 fn test_synonym_alias_resolution_from_map() {
148 let mut m = HashMap::new();
149 m.insert("CLM_RUNNER".to_string(), "node".to_string());
150 m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
151 m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
152 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
153 assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
154 assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
155 }
156 #[test]
157 fn alias_vectors() {
158 let mut m = HashMap::new();
159 m.insert("CLM_RUNNER".to_string(), "node".to_string());
160 m.insert("TARGET_FILE".to_string(), "spec.yaml".to_string());
161 m.insert("ACTIVE_AGENT_DID".to_string(), "did:clm:agent:alice".to_string());
162 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("node"));
163 assert_eq!(resolve_env_from_map(ClmEnvVar::TargetFile, &m).as_deref(), Some("spec.yaml"));
164 assert_eq!(resolve_env_from_map(ClmEnvVar::AgentDid, &m).as_deref(), Some("did:clm:agent:alice"));
165 m.insert("CLM_RUNTIME".to_string(), "rust".to_string());
167 assert_eq!(resolve_env_from_map(ClmEnvVar::Runtime, &m).as_deref(), Some("rust"));
168 }
169
170 #[test]
171 fn hash_algorithm_vectors() {
172 use sha2::{Digest, Sha256, Sha512};
173 let payload = b"clm-tri-runtime-univalence-v3.1.0";
174 let b3 = format!("{}{}", hash_prefixes::BLAKE3, blake3::hash(payload).to_hex());
175 let s256 = format!("{}{}", hash_prefixes::SHA256, hex::encode(Sha256::digest(payload)));
176 let s512 = format!("{}{}", hash_prefixes::SHA512, hex::encode(Sha512::digest(payload)));
177 assert!(b3.starts_with("blake3:"));
178 assert_eq!(b3.len(), 7 + 64);
179 assert!(s256.starts_with("sha256:"));
180 assert_eq!(s256.len(), 7 + 64);
181 assert!(s512.starts_with("sha512:"));
182 assert_eq!(s512.len(), 7 + 128);
183 }
184}
185
186#[repr(i32)]
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub enum RouteHandleOutcome {
189 Ok = 0,
190 NotFound = 1,
191 NetworkError = 2,
192 StaleFallback = 3,
193}
194
195pub const fn route_handle_exit_code(outcome: RouteHandleOutcome) -> ClmExitCode {
196 match outcome {
197 RouteHandleOutcome::Ok => ClmExitCode::Ok,
198 RouteHandleOutcome::NotFound => ClmExitCode::ContentMissing,
199 RouteHandleOutcome::NetworkError => ClmExitCode::GeneralError,
200 RouteHandleOutcome::StaleFallback => ClmExitCode::Ok,
201 }
202}
203
204pub const SQLITE_BUSY_TIMEOUT_MS: u32 = 5000;
205pub const SQLITE_COMPACTION_BUSY_TIMEOUT_MS: u32 = 30000;
206pub const SQLITE_LOCK_RETRY_MAX: u32 = 5;
207pub const SQLITE_LOCK_RETRY_BACKOFF_MS: u32 = 50;
208pub const CODEC_B64_CHUNK_BYTES: usize = 12288;
209pub const TEXT_ENCODING: &str = "utf-8";
210pub const NETWORK_GATEWAY_TIMEOUT_MS: u32 = 10000;
211pub const TERM_REDUCTION_FUEL: u32 = 1000;
212pub const RUNTIME_ADAPTER_TIMEOUT_S: u32 = 10;
213pub const PETRI_BINDING_TIMEOUT_S: u32 = 60;
214pub const PETRI_BINDING_ATTEMPTS: u32 = 2;
215pub const CEL_TEST_SUITE_TIMEOUT_S: u32 = 300;
216pub const PETRI_FUNCTION_POOL_DB: &str = "db/layer0_function_memory.mcard.db";
217pub const MEMBRANE_CONTINUATION_PARK_TTL_MS: u32 = 300000;
218
219pub const SQLITE_BUSY: i32 = 5;
220pub const SQLITE_LOCKED: i32 = 6;
221pub const SQLITE_READONLY: i32 = 8;
222pub const SQLITE_PRIMARY_CODE_MASK: i32 = 255;
223
224pub const fn sqlite_lock_retry_delay_ms(retry: u32) -> u32 {
225 let bounded = if retry > SQLITE_LOCK_RETRY_MAX { SQLITE_LOCK_RETRY_MAX } else { retry };
226 bounded * SQLITE_LOCK_RETRY_BACKOFF_MS
227}