clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// @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; 69] = &[
    "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",
    "ELAN_HOME",
    "TLA2TOOLS_JAR",
];

#[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);
    }
}