clm-kernel 0.0.7

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! # Universal TypeInterpreter & Programmatic Judgment Engine
//!
//! Sprint 447 / Invariant INV-447.
//! High-performance native Rust implementation of the CLM 5-phase deterministic
//! type judgment pipeline with embedded SSOT `schema/type_dictionary.json` via `include_str!`.
//! Supports zero-copy slice inspection, dynamic type registration, and PyO3 C-extension exports.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Raw canonical dictionary embedded at compile time for zero-IO, self-contained crates.io distribution.
pub static CANONICAL_DICTIONARY_JSON: &str = include_str!("../schema/type_dictionary.json");

/// Byte-level magic signature for fast, deterministic binary identification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicSignature {
    pub offset: usize,
    pub hex: String,
    pub mask: Option<String>,
    pub description: Option<String>,
}

impl MagicSignature {
    pub fn matches(&self, data: &[u8]) -> bool {
        let clean_hex: String = self.hex.chars().filter(|c| c.is_ascii_hexdigit()).collect();
        if !clean_hex.len().is_multiple_of(2) || clean_hex.is_empty() {
            return false;
        }

        let sig_bytes = match hex::decode(&clean_hex) {
            Ok(b) => b,
            Err(_) => return false,
        };

        let required_len = self.offset + sig_bytes.len();
        if data.len() < required_len {
            return false;
        }

        let target_slice = &data[self.offset..required_len];

        if let Some(mask_str) = &self.mask {
            let clean_mask: String = mask_str.chars().filter(|c| c.is_ascii_hexdigit()).collect();
            if let Ok(mask_bytes) = hex::decode(&clean_mask) {
                for (i, (&b, &sig)) in target_slice.iter().zip(sig_bytes.iter()).enumerate() {
                    let m = if i < mask_bytes.len() { mask_bytes[i] } else { 0xff };
                    if (b & m) != sig {
                        return false;
                    }
                }
                return true;
            }
        }

        target_slice == sig_bytes.as_slice()
    }

    pub fn byte_length(&self) -> usize {
        let clean: String = self.hex.chars().filter(|c| c.is_ascii_hexdigit()).collect();
        clean.len() / 2
    }
}

/// Declarative and programmatic type specification in Rust.
#[derive(Clone)]
pub struct TypeDefinition {
    pub mime: String,
    pub extensions: Vec<String>,
    pub universe: String,
    pub is_binary: bool,
    pub category: String,
    pub description: String,
    pub magic_bytes: Vec<MagicSignature>,
    pub text_patterns: Vec<String>,
    pub validator: Option<Arc<dyn Fn(&[u8]) -> bool + Send + Sync>>,
    pub priority: i32,
    pub metadata: HashMap<String, String>,
}

impl Default for TypeDefinition {
    fn default() -> Self {
        Self {
            mime: String::new(),
            extensions: Vec::new(),
            universe: "U0".to_string(),
            is_binary: false,
            category: "text".to_string(),
            description: String::new(),
            magic_bytes: Vec::new(),
            text_patterns: Vec::new(),
            validator: None,
            priority: 0,
            metadata: HashMap::new(),
        }
    }
}

/// Deterministic result of evaluating content and metadata against the TypeInterpreter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeJudgment {
    pub mime: String,
    pub universe: String,
    pub is_binary: bool,
    pub confidence: f32,
    pub matched_rule: String,
    pub extension: Option<String>,
    pub category: String,
    pub metadata: HashMap<String, String>,
}

/// Schema layout for parsing `schema/type_dictionary.json`.
#[derive(Debug, Deserialize)]
struct RawDictionary {
    #[serde(default)]
    types: std::collections::BTreeMap<String, RawTypeEntry>,
}

#[derive(Debug, Deserialize)]
struct RawTypeEntry {
    #[serde(default)]
    extensions: Vec<String>,
    #[serde(default = "default_universe")]
    universe: String,
    #[serde(default)]
    is_binary: bool,
    #[serde(default = "default_category")]
    category: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    magic_bytes: Vec<MagicSignature>,
    #[serde(default)]
    text_patterns: Vec<String>,
}

fn default_universe() -> String {
    "U0".to_string()
}
fn default_category() -> String {
    "text".to_string()
}

/// Universal Native TypeInterpreter.
pub struct TypeInterpreter {
    types: HashMap<String, TypeDefinition>,
    ext_map: HashMap<String, String>,
    magic_signatures: Vec<(MagicSignature, String)>,
    compiled_patterns: Vec<(regex::Regex, String)>,
}

impl Default for TypeInterpreter {
    fn default() -> Self {
        Self::new()
    }
}

impl TypeInterpreter {
    pub fn new() -> Self {
        Self {
            types: HashMap::new(),
            ext_map: HashMap::new(),
            magic_signatures: Vec::new(),
            compiled_patterns: Vec::new(),
        }
    }

    /// Instantiate a TypeInterpreter pre-loaded with the canonical SSOT type dictionary.
    pub fn create_default() -> Self {
        let mut interpreter = Self::new();
        if let Ok(dict) = serde_json::from_str::<RawDictionary>(CANONICAL_DICTIONARY_JSON) {
            for (mime, raw) in dict.types {
                let def = TypeDefinition {
                    mime: mime.clone(),
                    extensions: raw.extensions,
                    universe: raw.universe,
                    is_binary: raw.is_binary,
                    category: raw.category,
                    description: raw.description,
                    magic_bytes: raw.magic_bytes,
                    text_patterns: raw.text_patterns,
                    validator: None,
                    priority: 0,
                    metadata: HashMap::new(),
                };
                interpreter.register_type(def);
            }
        }
        interpreter
    }

    /// Programmatically register or override a TypeDefinition.
    pub fn register_type(&mut self, mut type_def: TypeDefinition) {
        // Normalize extensions to lowercase with leading dot
        let mut norm_exts = Vec::new();
        for ext in &type_def.extensions {
            let clean = ext.trim().to_lowercase();
            let standardized = if clean.starts_with('.') {
                clean
            } else {
                format!(".{}", clean)
            };
            if !norm_exts.contains(&standardized) {
                norm_exts.push(standardized);
            }
        }
        type_def.extensions = norm_exts;

        // Index in extension map
        for ext in &type_def.extensions {
            self.ext_map.insert(ext.clone(), type_def.mime.clone());
        }

        // Index magic signatures
        for sig in &type_def.magic_bytes {
            self.magic_signatures.push((sig.clone(), type_def.mime.clone()));
        }

        // Sort magic signatures by byte length descending
        self.magic_signatures.sort_by_key(|a| std::cmp::Reverse(a.0.byte_length()));

        // Compile text patterns
        for pat in &type_def.text_patterns {
            if let Ok(re) = regex::Regex::new(pat) {
                self.compiled_patterns.push((re, type_def.mime.clone()));
            }
        }

        self.types.insert(type_def.mime.clone(), type_def);
    }

    pub fn get_type(&self, mime: &str) -> Option<&TypeDefinition> {
        self.types.get(mime)
    }

    pub fn types_count(&self) -> usize {
        self.types.len()
    }

    /// Execute 5-phase deterministic type judgment.
    pub fn judge(
        &self,
        data: Option<&[u8]>,
        filename: Option<&str>,
        ext_hint: Option<&str>,
    ) -> TypeJudgment {
        let raw_bytes = data.unwrap_or(&[]);
        let resolved_ext = self.resolve_extension(filename, ext_hint);

        // ── Phase 1: High-Priority Programmatic Predicates ─────────────────
        for def in self.types.values() {
            if def.priority > 0
                && let Some(ref val) = def.validator
                    && val(raw_bytes) {
                        return TypeJudgment {
                            mime: def.mime.clone(),
                            universe: def.universe.clone(),
                            is_binary: def.is_binary,
                            confidence: 1.0,
                            matched_rule: "programmatic_predicate_high_priority".to_string(),
                            extension: def.extensions.first().cloned().or(resolved_ext),
                            category: def.category.clone(),
                            metadata: def.metadata.clone(),
                        };
                    }
        }

        // ── Phase 2: Binary Magic Byte Signatures ──────────────────────────
        if !raw_bytes.is_empty() {
            let mut matching: Vec<(&MagicSignature, &TypeDefinition)> = Vec::new();
            for (sig, mime) in &self.magic_signatures {
                if sig.matches(raw_bytes)
                    && let Some(def) = self.types.get(mime) {
                        matching.push((sig, def));
                    }
            }

            if !matching.is_empty() {
                let mut best = matching[0];
                if let Some(ref ext) = resolved_ext {
                    if let Some(ext_match) = matching.iter().find(|(_, def)| def.extensions.contains(ext)) {
                        best = *ext_match;
                    }
                } else if let Some(base_match) = matching.iter().find(|(_, def)| !def.mime.contains('+')) {
                    best = *base_match;
                }

                let (best_sig, best_def) = best;
                let mut meta = HashMap::new();
                meta.insert("signature_hex".to_string(), best_sig.hex.clone());
                return TypeJudgment {
                    mime: best_def.mime.clone(),
                    universe: best_def.universe.clone(),
                    is_binary: best_def.is_binary,
                    confidence: 0.99,
                    matched_rule: "magic_bytes".to_string(),
                    extension: best_def.extensions.first().cloned().or(resolved_ext),
                    category: best_def.category.clone(),
                    metadata: meta,
                };
            }
        }

        // ── Phase 3: Entropy / Binary Heuristic ───────────────────────────
        let is_bin = self.is_binary_payload(raw_bytes);

        // ── Phase 4: Explicit Extension Hint ──────────────────────────────
        if let Some(ref ext) = resolved_ext
            && let Some(mime) = self.ext_map.get(ext)
                && let Some(def) = self.types.get(mime) {
                    return TypeJudgment {
                        mime: def.mime.clone(),
                        universe: def.universe.clone(),
                        is_binary: def.is_binary,
                        confidence: 0.95,
                        matched_rule: "extension_hint".to_string(),
                        extension: Some(ext.clone()),
                        category: def.category.clone(),
                        metadata: HashMap::new(),
                    };
                }

        // ── Phase 5: Structured Text Probing (if not binary) ───────────────
        if !is_bin && !raw_bytes.is_empty()
            && let Ok(text) = std::str::from_utf8(raw_bytes) {
                let trimmed = text.trim();

                // 5a. Concrete format probes (SVG, HTML, JSON, TikZ, LaTeX, Markdown)
                if let Some((mime, rule, conf)) = self.probe_structured_text(trimmed) {
                    let def_opt = self.types.get(&mime);
                    return TypeJudgment {
                        mime: mime.clone(),
                        universe: def_opt.map(|d| d.universe.clone()).unwrap_or_else(|| "U0".to_string()),
                        is_binary: false,
                        confidence: conf,
                        matched_rule: rule,
                        extension: def_opt.and_then(|d| d.extensions.first().cloned()).or(resolved_ext),
                        category: def_opt.map(|d| d.category.clone()).unwrap_or_else(|| "text".to_string()),
                        metadata: HashMap::new(),
                    };
                }

                // 5b. Regex patterns
                for (re, mime) in &self.compiled_patterns {
                    if re.is_match(trimmed)
                        && let Some(def) = self.types.get(mime) {
                            return TypeJudgment {
                                mime: def.mime.clone(),
                                universe: def.universe.clone(),
                                is_binary: false,
                                confidence: 0.95,
                                matched_rule: "text_pattern".to_string(),
                                extension: def.extensions.first().cloned().or(resolved_ext),
                                category: def.category.clone(),
                                metadata: HashMap::new(),
                            };
                        }
                }
            }

        // ── Phase 6: Standard Programmatic Predicates (Priority 0) ─────────
        for def in self.types.values() {
            if def.priority == 0
                && let Some(ref val) = def.validator
                    && val(raw_bytes) {
                        return TypeJudgment {
                            mime: def.mime.clone(),
                            universe: def.universe.clone(),
                            is_binary: def.is_binary,
                            confidence: 0.92,
                            matched_rule: "programmatic_predicate".to_string(),
                            extension: def.extensions.first().cloned().or(resolved_ext),
                            category: def.category.clone(),
                            metadata: def.metadata.clone(),
                        };
                    }
        }

        // ── Fallback Classification ────────────────────────────────────────
        if is_bin {
            TypeJudgment {
                mime: "application/octet-stream".to_string(),
                universe: "U0".to_string(),
                is_binary: true,
                confidence: 0.50,
                matched_rule: "binary_fallback".to_string(),
                extension: resolved_ext.or_else(|| Some(".bin".to_string())),
                category: "binary".to_string(),
                metadata: HashMap::new(),
            }
        } else {
            TypeJudgment {
                mime: "text/plain".to_string(),
                universe: "U0".to_string(),
                is_binary: false,
                confidence: 0.50,
                matched_rule: "text_fallback".to_string(),
                extension: resolved_ext.or_else(|| Some(".txt".to_string())),
                category: "text".to_string(),
                metadata: HashMap::new(),
            }
        }
    }

    pub fn detect_content_type(&self, data: &[u8], ext_hint: Option<&str>) -> (String, String) {
        let judgment = self.judge(Some(data), None, ext_hint);
        let clean_ext = judgment.extension.map(|e| e.trim_start_matches('.').to_string()).unwrap_or_default();
        (judgment.mime, clean_ext)
    }

    pub fn is_binary_content(&self, data: &[u8]) -> bool {
        self.is_binary_payload(data)
    }

    fn resolve_extension(&self, filename: Option<&str>, ext_hint: Option<&str>) -> Option<String> {
        let mut target = ext_hint.unwrap_or("").trim().to_lowercase();
        if target.is_empty()
            && let Some(name) = filename
                && let Some(idx) = name.rfind('.') {
                    target = name[idx..].trim().to_lowercase();
                }
        if target.is_empty() {
            None
        } else if target.starts_with('.') {
            Some(target)
        } else {
            Some(format!(".{}", target))
        }
    }

    fn is_binary_payload(&self, data: &[u8]) -> bool {
        if data.is_empty() {
            return false;
        }
        let limit = std::cmp::min(data.len(), 4096);
        let sample = &data[..limit];

        // Null byte indicates binary
        if sample.contains(&0) {
            return true;
        }

        let non_text = sample
            .iter()
            .filter(|&&b| b < 9 || (b > 13 && b < 32) || b > 127)
            .count();

        (non_text as f32 / limit as f32) > 0.30
    }

    fn probe_structured_text(&self, text: &str) -> Option<(String, String, f32)> {
        // JSON probe (including specialized MCard/PCard/VCard carriers)
        if ((text.starts_with('{') && text.ends_with('}')) || (text.starts_with('[') && text.ends_with(']')))
            && serde_json::from_str::<serde_json::Value>(text).is_ok() {
                if text.contains("\"mcard_version\"") {
                    return Some(("application/vnd.mcard+json".to_string(), "structured_mcard_probe".to_string(), 0.99));
                }
                if text.contains("\"pcard_version\"") {
                    return Some(("application/vnd.pcard+json".to_string(), "structured_pcard_probe".to_string(), 0.99));
                }
                if text.contains("\"vcard_version\"") {
                    return Some(("application/vnd.vcard+json".to_string(), "structured_vcard_probe".to_string(), 0.99));
                }
                return Some(("application/json".to_string(), "structured_json_probe".to_string(), 0.98));
            }

        // SVG / XML probe
        if text.starts_with("<?xml") || text.to_lowercase().contains("<svg") {
            if text.to_lowercase().contains("<svg") {
                return Some(("image/svg+xml".to_string(), "structured_svg_probe".to_string(), 0.96));
            }
            return Some(("application/xml".to_string(), "structured_xml_probe".to_string(), 0.92));
        }

        // HTML probe
        let lower = text.to_lowercase();
        if lower.contains("<!doctype html") || lower.contains("<html") {
            return Some(("text/html".to_string(), "structured_html_probe".to_string(), 0.95));
        }

        // Markdown frontmatter
        if text.starts_with("---") && text[3..].contains("\n---") {
            return Some(("text/markdown".to_string(), "markdown_frontmatter_probe".to_string(), 0.90));
        }

        // TikZ / LaTeX probe
        if text.contains("\\documentclass") || text.contains("\\begin{tikzpicture}") || text.contains("\\begin{document}") {
            if text.contains("\\begin{tikzpicture}") {
                return Some(("text/x-tikz".to_string(), "structured_tikz_probe".to_string(), 0.95));
            }
            return Some(("text/x-tex".to_string(), "structured_latex_probe".to_string(), 0.92));
        }

        None
    }
}