clm-kernel 0.0.12

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
409
//! Compiled univalent type lattice (Stage 2).
//!
//! This is a Rust port of `kernel/scripts/clm/layer0/type_registry.py`.
//! It loads type manifests from `types/` YAML files, stores them in a
//! content-addressed registry, and validates payloads against their schemas
//! while enforcing universe stratification (U0–U3).

use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TypeInfo {
    pub name: String,
    pub path: String,
    pub universe_level: u8,
    pub schema: serde_yaml::Value,
    pub concrete: serde_yaml::Value,
}

#[derive(Debug, Clone, Default)]
pub struct TypeLattice {
    pub registry: HashMap<String, TypeInfo>,
    pub content_types: HashMap<String, TypeInfo>,
    pub transport_types: HashMap<String, TypeInfo>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TypeValidationError {
    UnknownType(String),
    StratificationError {
        type_name: String,
        level: u8,
        parent_level: u8,
    },
    PatternViolation {
        type_name: String,
        value: String,
        pattern: String,
    },
    TypeCheckFailure {
        type_name: String,
        value: String,
        expected: String,
    },
    MissingRequiredField {
        type_name: String,
        field: String,
    },
    EnumViolation {
        type_name: String,
        field: String,
        value: String,
    },
    StructuralError {
        type_name: String,
        reason: String,
    },
}

impl std::fmt::Display for TypeValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TypeValidationError::UnknownType(t) => write!(f, "Unknown type '{}'", t),
            TypeValidationError::StratificationError { type_name, level, parent_level } => {
                write!(f, "STRATIFICATION_ERROR: Type '{}' at Level {} cannot be nested inside a Level {} parent type context.", type_name, level, parent_level)
            }
            TypeValidationError::PatternViolation { type_name, value, pattern } => {
                write!(f, "Value '{}' violates pattern '{}' for type '{}'", value, pattern, type_name)
            }
            TypeValidationError::TypeCheckFailure { type_name, value, expected } => {
                write!(f, "Value '{}' is not a valid {} for type '{}'", value, expected, type_name)
            }
            TypeValidationError::MissingRequiredField { type_name, field } => {
                write!(f, "Missing required field '{}' in type '{}'", field, type_name)
            }
            TypeValidationError::EnumViolation { type_name, field, value } => {
                write!(f, "Value '{}' is not in enum for field '{}' in type '{}'", value, field, type_name)
            }
            TypeValidationError::StructuralError { type_name, reason } => {
                write!(f, "Structural error for type '{}': {}", type_name, reason)
            }
        }
    }
}

impl std::error::Error for TypeValidationError {}

impl TypeLattice {
    pub fn new() -> Self {
        Self::default()
    }

    /// All 12 canonical type subdirectories scanned by the runtime lattice (Sprint 162 — Finding 4).
    pub const TYPE_REGISTRY_SUBDIRS: &'static [&'static str] = &[
        "meta",
        "primitives",
        "runtime",
        "content",
        "transport",
        "codegen",
        "governance",
        "identity",
        "payment",
        "observability",
        "storage",
        "core_features",
        "chat",
    ];

    /// Directories in `types/` deliberately excluded from type manifest scanning.
    /// `schemas` contains raw DDL and specification definitions (`.sql`, `.json`, CEL schemas),
    /// rather than MCard type manifests.
    pub const EXCLUDED_TYPE_SUBDIRS: &'static [&'static str] = &[
        "schemas",
        "lattice",
    ];

    /// Load type manifests from the filesystem (`types/` subdirectories).
    /// Scans all 12 canonical subdirectories: `meta`, `primitives`, `runtime`, `content`,
    /// `transport`, `codegen`, `governance`, `identity`, `payment`, `observability`, `storage`, `core_features`.
    /// Only available on native targets (WASM uses `load_from_map`).
    pub fn load_registry(&mut self, clm_root: &str) {
        use std::path::Path;
        let mut types_dir = Path::new(clm_root).join("types");
        if !types_dir.exists() {
            let local_types = Path::new(env!("CARGO_MANIFEST_DIR")).join("types");
            if local_types.exists() {
                types_dir = local_types;
            } else {
                return;
            }
        }
        for subdir in Self::TYPE_REGISTRY_SUBDIRS {
            let subdir_path = types_dir.join(subdir);
            if !subdir_path.exists() {
                continue;
            }
            if let Ok(entries) = std::fs::read_dir(&subdir_path) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    let fname = match path.file_name().and_then(|n| n.to_str()) {
                        Some(n) => n,
                        None => continue,
                    };
                    if !fname.ends_with(".yaml") && !fname.ends_with(".yml") {
                        continue;
                    }
                    let name = fname.trim_end_matches(".yaml").trim_end_matches(".yml");
                    let body = match std::fs::read_to_string(&path) {
                        Ok(b) => b,
                        Err(e) => {
                            eprintln!("[type_lattice] ERROR: Failed to read manifest file '{}': {}", path.display(), e);
                            continue;
                        }
                    };
                    let path_str = path.to_string_lossy().to_string();
                    match parse_manifest(name, &path_str, &body) {
                        Ok(info) => self.add_type(name.to_string(), info),
                        Err(e) => eprintln!("[type_lattice] ERROR: Failed to parse manifest '{}' at '{}': {}", name, path_str, e),
                    }
                }
            }
        }
    }

    /// Load type manifests from a map of filename -> YAML body.
    /// Used in WASM where filesystem access is unavailable.
    pub fn load_from_map(&mut self, yamls: HashMap<String, String>) {
        for (fname, body) in yamls {
            let name = fname
                .trim_end_matches(".yaml")
                .trim_end_matches(".yml")
                .to_string();
            match parse_manifest(&name, &format!("types/<wasm>/{}", fname), &body) {
                Ok(info) => self.add_type(name, info),
                Err(e) => eprintln!("[type_lattice] ERROR: Failed to parse manifest '{}': {}", fname, e),
            }
        }
    }

    fn add_type(&mut self, name: String, info: TypeInfo) {
        let key = name.to_lowercase();
        self.registry.insert(key.clone(), info.clone());

        if let Some(ct) = info.concrete.get("content_type")
            && let Some(mime) = ct.get("mime").and_then(|v| v.as_str()) {
                self.content_types.insert(mime.to_string(), info.clone());
            }
        if let Some(tp) = info.concrete.get("transport")
            && let Some(proto) = tp.get("protocol").and_then(|v| v.as_str()) {
                self.transport_types.insert(proto.to_string(), info.clone());
            }
    }

    pub fn get_type_info(&self, type_name: &str) -> Option<&TypeInfo> {
        self.registry.get(&type_name.to_lowercase())
    }

    pub fn validate(&self, type_name: &str, value: &str, parent_level: u8) -> Result<(), TypeValidationError> {
        let info = self.get_type_info(type_name)
            .ok_or_else(|| TypeValidationError::UnknownType(type_name.to_string()))?;

        let level = info.universe_level;
        if level > parent_level {
            return Err(TypeValidationError::StratificationError {
                type_name: type_name.to_string(),
                level,
                parent_level,
            });
        }

        let parsed = parse_value(value);
        let style = detect_style(&info.schema);
        match style {
            SchemaStyle::Primitive => validate_primitive(self, type_name, value, &parsed, &info.schema, level),
            SchemaStyle::FieldList => validate_field_list(self, type_name, &parsed, &info.schema, level),
            SchemaStyle::JsonSchema => validate_json_schema(self, type_name, &parsed, &info.schema, level),
        }
    }

    /// Compile the lattice into pre-computed manifests for O(1) verification.
    pub fn compile(&self) -> CompiledTypeLattice {
        let mut manifests = HashMap::new();
        for (name, info) in &self.registry {
            let type_hash = hash_type_name(name);
            let schema_hash = hash_schema(&info.schema);
            let compiled_regex = extract_regex(&info.schema);
            let enum_hashes = extract_enum_hashes(&info.schema);
            let required_field_hashes = extract_required_field_hashes(&info.schema);
            manifests.insert(name.clone(), CompiledTypeManifest {
                type_name: name.clone(),
                type_hash,
                universe_level: info.universe_level,
                schema_hash,
                compiled_regex,
                enum_hashes,
                required_field_hashes,
            });
        }
        CompiledTypeLattice { manifests }
    }

    /// Returns the universal Top type (⊤ / Any), satisfied by all MCards (U0).
    pub fn top() -> TypeInfo {
        TypeInfo {
            name: "Top".to_string(),
            path: "types/meta/top.yaml".to_string(),
            universe_level: 0,
            schema: serde_yaml::Value::String("any".to_string()),
            concrete: serde_yaml::Value::Null,
        }
    }

    /// Returns the empty Bottom type (⊥ / Never), with zero inhabitants.
    pub fn bottom() -> TypeInfo {
        TypeInfo {
            name: "Bottom".to_string(),
            path: "types/meta/bottom.yaml".to_string(),
            universe_level: 0,
            schema: serde_yaml::Value::String("never".to_string()),
            concrete: serde_yaml::Value::Null,
        }
    }

    /// Computes the Meet (∧) / Greatest Lower Bound (Product / Intersection Type).
    /// Used for composite preconditions: V_pre = V_1 ∧ V_2.
    pub fn meet(&self, t1: &TypeInfo, t2: &TypeInfo) -> TypeInfo {
        if t1.name == "Bottom" || t2.name == "Bottom" {
            return Self::bottom();
        }
        if t1.name == "Top" {
            return t2.clone();
        }
        if t2.name == "Top" {
            return t1.clone();
        }
        if t1.name == t2.name {
            return t1.clone();
        }

        let universe_level = t1.universe_level.max(t2.universe_level);
        let name = format!("({} ∧ {})", t1.name, t2.name);
        let path = format!("types/derived/{}_{}.yaml", t1.name, t2.name);

        let mut combined_schema = serde_yaml::Mapping::new();
        combined_schema.insert(
            serde_yaml::Value::String("type".to_string()),
            serde_yaml::Value::String("intersection".to_string()),
        );
        combined_schema.insert(
            serde_yaml::Value::String("all_of".to_string()),
            serde_yaml::Value::Sequence(vec![t1.schema.clone(), t2.schema.clone()]),
        );

        TypeInfo {
            name,
            path,
            universe_level,
            schema: serde_yaml::Value::Mapping(combined_schema),
            concrete: serde_yaml::Value::Null,
        }
    }

    /// Computes the Join (∨) / Least Upper Bound (Sum / Union Type).
    /// Used for alternative solver consensus paths: tau_out = tau_A ∨ tau_B.
    pub fn join(&self, t1: &TypeInfo, t2: &TypeInfo) -> TypeInfo {
        if t1.name == "Top" || t2.name == "Top" {
            return Self::top();
        }
        if t1.name == "Bottom" {
            return t2.clone();
        }
        if t2.name == "Bottom" {
            return t1.clone();
        }
        if t1.name == t2.name {
            return t1.clone();
        }

        let universe_level = t1.universe_level.max(t2.universe_level);
        let name = format!("({} ∨ {})", t1.name, t2.name);
        let path = format!("types/derived/{}_{}.yaml", t1.name, t2.name);

        let mut combined_schema = serde_yaml::Mapping::new();
        combined_schema.insert(
            serde_yaml::Value::String("type".to_string()),
            serde_yaml::Value::String("union".to_string()),
        );
        combined_schema.insert(
            serde_yaml::Value::String("any_of".to_string()),
            serde_yaml::Value::Sequence(vec![t1.schema.clone(), t2.schema.clone()]),
        );

        TypeInfo {
            name,
            path,
            universe_level,
            schema: serde_yaml::Value::Mapping(combined_schema),
            concrete: serde_yaml::Value::Null,
        }
    }

    /// Checks information ordering / subtyping: sub <= sup.
    pub fn is_subtype(&self, sub: &TypeInfo, sup: &TypeInfo) -> bool {
        if sup.name == "Top" || sub.name == "Bottom" || sub.name == sup.name {
            return true;
        }
        if sub.name == "Top" || sup.name == "Bottom" {
            return false;
        }
        if sub.name.starts_with('(') && sub.name.contains('∧')
            && sub.name.contains(&sup.name) {
                return true;
            }
        if sup.name.starts_with('(') && sup.name.contains('∨')
            && sup.name.contains(&sub.name) {
                return true;
            }
        sub.universe_level <= sup.universe_level
    }
}

// ─────────────────────────────────────────────────────────────────────
// O(1) Compiled Type Lattice (Story 139.2.2)
// ─────────────────────────────────────────────────────────────────────


#[path = "type_lattice_compiled.rs"]
mod type_lattice_compiled;
#[allow(unused_imports)]
pub use type_lattice_compiled::*;
#[path = "type_lattice_validate.rs"]
mod type_lattice_validate;
#[allow(unused_imports)]
pub use type_lattice_validate::*;
#[cfg(test)]
#[path = "type_lattice_tests.rs"]
mod tests;

/// A minimal lattice embedded at compile time for testing and the WASM bootstrap.
/// Loads a curated subset of `types/` manifests so validation can run without
/// runtime filesystem access.
pub fn default_lattice() -> TypeLattice {
    let files: &[(&str, &str)] = &[
        ("string.yaml", include_str!("../types/primitives/string.yaml")),
        ("integer.yaml", include_str!("../types/primitives/integer.yaml")),
        ("boolean.yaml", include_str!("../types/primitives/boolean.yaml")),
        ("a_mcard.yaml", include_str!("../types/meta/a_mcard.yaml")),
        ("b_mcard.yaml", include_str!("../types/meta/b_mcard.yaml")),
        ("vcard_token.yaml", include_str!("../types/meta/vcard_token.yaml")),
        ("agent.yaml", include_str!("../types/runtime/agent.yaml")),
        ("clmEval.yaml", include_str!("../types/runtime/clmEval.yaml")),
    ];
    let mut map = HashMap::new();
    for (name, body) in files {
        map.insert(name.to_string(), (*body).to_string());
    }
    let mut lattice = TypeLattice::new();
    lattice.load_from_map(map);
    lattice
}

/// SSOT Feature Registry embedded from `types/lattice/clm_features.yaml`
pub const CLM_FEATURES_YAML: &str = include_str!("../types/lattice/clm_features.yaml");