clm-kernel 0.0.3

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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! 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`).
    #[cfg(not(target_arch = "wasm32"))]
    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)
// ─────────────────────────────────────────────────────────────────────

/// Pre-computed type manifest for O(1) verification.
#[derive(Debug, Clone)]
pub struct CompiledTypeManifest {
    pub type_name: String,
    pub type_hash: [u8; 32],
    pub universe_level: u8,
    pub schema_hash: [u8; 32],
    pub compiled_regex: Option<Regex>,
    pub enum_hashes: HashSet<[u8; 32]>,
    pub required_field_hashes: HashSet<[u8; 32]>,
}

/// A compiled type lattice with pre-computed manifests for fast verification.
#[derive(Debug, Clone)]
pub struct CompiledTypeLattice {
    pub manifests: HashMap<String, CompiledTypeManifest>,
}

impl CompiledTypeLattice {
    /// Verify a value against a named type using pre-compiled manifests.
    /// Uses pre-compiled regexes and hash sets for faster matching than
    /// the recursive validation path.
    pub fn verify(
        &self,
        type_name: &str,
        value: &str,
        parent_level: u8,
        lattice: &TypeLattice,
    ) -> Result<(), TypeValidationError> {
        let manifest = self.manifests.get(&type_name.to_lowercase())
            .ok_or_else(|| TypeValidationError::UnknownType(type_name.to_string()))?;

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

        // Fast path for primitive types with pre-compiled regex.
        let info = lattice.get_type_info(type_name).unwrap();
        let style = detect_style(&info.schema);
        match style {
            SchemaStyle::Primitive => {
                let parsed = parse_value(value);
                // Use pre-compiled regex if available.
                if let Some(ref re) = manifest.compiled_regex
                    && !re.is_match(value) {
                        return Err(TypeValidationError::PatternViolation {
                            type_name: type_name.to_string(),
                            value: value.to_string(),
                            pattern: re.as_str().to_string(),
                        });
                    }
                // Check type_check constraints (no regex needed).
                validate_type_check(type_name, value, &parsed, &info.schema)
            }
            SchemaStyle::FieldList | SchemaStyle::JsonSchema => {
                // Complex types still need recursive validation.
                lattice.validate(type_name, value, parent_level)
            }
        }
    }

    /// O(1) fast path: verify by comparing pre-computed hashes.
    /// Returns true if the value hash matches an allowed hash for the type.
    /// This is only applicable for enum-constrained types; for other types,
    /// it returns false (caller should fall back to `verify`).
    pub fn verify_by_hash(&self, type_name: &str, value_hash: &[u8; 32]) -> bool {
        let manifest = self.manifests.get(&type_name.to_lowercase());
        match manifest {
            Some(m) if !m.enum_hashes.is_empty() => m.enum_hashes.contains(value_hash),
            _ => false,
        }
    }
}

/// Global cached compiled lattice for zero-cost repeated lookups.
static COMPILED_LATTICE: OnceLock<CompiledTypeLattice> = OnceLock::new();

/// Get the globally cached compiled lattice, initializing it from
/// `default_lattice()` on first call.
pub fn compiled_lattice() -> &'static CompiledTypeLattice {
    COMPILED_LATTICE.get_or_init(|| default_lattice().compile())
}

/// Compute content hash of a type name.
pub fn hash_type_name(name: &str) -> [u8; 32] {
    crate::hash::raw_hash_bytes_32(name.as_bytes())
}

/// Compute content hash of a value (for enum matching).
pub fn hash_value(value: &str) -> [u8; 32] {
    crate::hash::raw_hash_bytes_32(value.as_bytes())
}

/// Compute content hash of a schema (for content-addressed manifest lookup).
fn hash_schema(schema: &serde_yaml::Value) -> [u8; 32] {
    let yaml_str = serde_yaml::to_string(schema).unwrap_or_default();
    crate::hash::raw_hash_bytes_32(yaml_str.as_bytes())
}

/// Extract a compiled regex from a primitive schema's constraints.
fn extract_regex(schema: &serde_yaml::Value) -> Option<Regex> {
    let constraints = schema.get("constraints")?;
    let pattern = constraints.get("pattern")?.as_str()?;
    if pattern == "null" {
        return None;
    }
    Regex::new(pattern).ok()
}

/// Extract pre-computed hashes for enum-allowed values.
fn extract_enum_hashes(schema: &serde_yaml::Value) -> HashSet<[u8; 32]> {
    let mut hashes = HashSet::new();
    if let Some(constraints) = schema.get("constraints")
        && let Some(en) = constraints.get("enum").and_then(|v| v.as_sequence()) {
            for val in en {
                let s = yaml_to_str(val);
                hashes.insert(hash_value(&s));
            }
        }
    // Also check field_list schemas for field-level enums.
    if let Some(required) = schema.get("required_fields").and_then(|v| v.as_sequence()) {
        for field in required {
            if let Some(en) = field.get("constraints").and_then(|v| v.get("enum")).and_then(|v| v.as_sequence()) {
                for val in en {
                    let s = yaml_to_str(val);
                    hashes.insert(hash_value(&s));
                }
            }
        }
    }
    hashes
}

/// Extract pre-computed hashes for required field names.
fn extract_required_field_hashes(schema: &serde_yaml::Value) -> HashSet<[u8; 32]> {
    let mut hashes = HashSet::new();
    if let Some(required) = schema.get("required_fields").and_then(|v| v.as_sequence()) {
        for field in required {
            if let Some(name) = field.get("name").and_then(|v| v.as_str()) {
                hashes.insert(hash_value(name));
            }
        }
    }
    if let Some(required) = schema.get("required").and_then(|v| v.as_sequence()) {
        for val in required {
            if let Some(name) = val.as_str() {
                hashes.insert(hash_value(name));
            }
        }
    }
    hashes
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum SchemaStyle {
    Primitive,
    FieldList,
    JsonSchema,
}

fn detect_style(schema: &serde_yaml::Value) -> SchemaStyle {
    if schema.get("constraints").is_some() {
        return SchemaStyle::Primitive;
    }
    if schema.get("required_fields").is_some() || schema.get("optional_fields").is_some() {
        return SchemaStyle::FieldList;
    }
    if schema.get("required").is_some() || schema.get("properties").is_some() {
        return SchemaStyle::JsonSchema;
    }
    SchemaStyle::Primitive
}

fn parse_manifest(name: &str, path: &str, body: &str) -> Result<TypeInfo, String> {
    let manifest: serde_yaml::Value = serde_yaml::from_str(body).map_err(|e| e.to_string())?;
    let inner = manifest.get("clm").unwrap_or(&manifest);
    let concrete = inner
        .get("concrete_impl")
        .or_else(|| inner.get("concrete"))
        .cloned()
        .unwrap_or(serde_yaml::Value::Null);
    let universe_level = if let Some(v) = concrete.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else if let Some(v) = inner.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else if let Some(v) = manifest.get("universe_level").and_then(|v| v.as_u64()) {
        v as u8
    } else {
        // Infer default level by subdirectory path if not explicitly declared
        if path.contains("/meta/") {
            0
        } else if path.contains("/primitives/") {
            0
        } else if path.contains("/runtime/") {
            2
        } else if path.contains("/content/") {
            1
        } else if path.contains("/transport/") {
            3
        } else if path.contains("/codegen/") {
            1
        } else if path.contains("/governance/") {
            1
        } else if path.contains("/identity/") {
            3
        } else if path.contains("/payment/") {
            4
        } else if path.contains("/observability/") {
            2
        } else if path.contains("/storage/") {
            2
        } else if path.contains("/core_features/") {
            1
        } else if path.contains("/chat/") {
            4
        } else {
            0
        }
    };
    let schema = concrete
        .get("schema")
        .or_else(|| inner.get("schema"))
        .cloned()
        .unwrap_or(serde_yaml::Value::Null);
    Ok(TypeInfo {
        name: name.to_string(),
        path: path.to_string(),
        universe_level,
        schema,
        concrete,
    })
}

fn parse_value(value: &str) -> JsonValue {
    let trimmed = value.trim();
    if ((trimmed.starts_with('{') && trimmed.ends_with('}'))
        || (trimmed.starts_with('[') && trimmed.ends_with(']')))
        && let Ok(v) = serde_json::from_str::<JsonValue>(trimmed) {
            return v;
        }
    JsonValue::String(value.to_string())
}

fn validate_primitive(
    _registry: &TypeLattice,
    type_name: &str,
    raw_value: &str,
    parsed: &JsonValue,
    schema: &serde_yaml::Value,
    _level: u8,
) -> Result<(), TypeValidationError> {
    let constraints = schema.get("constraints").cloned().unwrap_or(serde_yaml::Value::Null);

    if let Some(pattern) = constraints.get("pattern").and_then(|v| v.as_str())
        && pattern != "null" && !pattern.is_empty() {
            let re = Regex::new(pattern).map_err(|e| {
                TypeValidationError::StructuralError {
                    type_name: type_name.to_string(),
                    reason: format!("invalid regex '{}': {}", pattern, e),
                }
            })?;
            if !re.is_match(raw_value) {
                return Err(TypeValidationError::PatternViolation {
                    type_name: type_name.to_string(),
                    value: raw_value.to_string(),
                    pattern: pattern.to_string(),
                });
            }
        }

    if let Some(type_check) = constraints.get("type_check").and_then(|v| v.as_str())
        && type_check != "null" {
            match type_check {
                "is_integer" => {
                    if !Regex::new(r"^-?[0-9]+$")
                        .unwrap()
                        .is_match(raw_value)
                    {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "integer".to_string(),
                        });
                    }
                }
                "is_boolean" => {
                    let lower = raw_value.to_lowercase();
                    if lower != "true" && lower != "false" {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "boolean".to_string(),
                        });
                    }
                }
                "is_string" => {
                    if parsed.is_object() || parsed.is_array() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "string".to_string(),
                        });
                    }
                    if Regex::new(r"^-?[0-9]+(\.[0-9]+)?$").unwrap().is_match(raw_value)
                        || ["true", "false"].contains(&lower_cased(raw_value).as_str())
                    {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "string".to_string(),
                        });
                    }
                }
                "is_list" => {
                    if !parsed.is_array() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "list".to_string(),
                        });
                    }
                }
                "is_map" => {
                    if !parsed.is_object() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "map".to_string(),
                        });
                    }
                }
                "is_process_payload"
                    if !parsed.is_object() && !parsed.is_array() => {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "process payload".to_string(),
                        });
                    }
                _ => {}
            }
        }

    Ok(())
}

/// Standalone type_check validation (used by CompiledTypeLattice fast path).
/// Uses cached regexes via OnceLock to avoid recompilation on every call.
fn validate_type_check(
    type_name: &str,
    raw_value: &str,
    parsed: &JsonValue,
    schema: &serde_yaml::Value,
) -> Result<(), TypeValidationError> {
    let constraints = schema.get("constraints").cloned().unwrap_or(serde_yaml::Value::Null);

    if let Some(type_check) = constraints.get("type_check").and_then(|v| v.as_str())
        && type_check != "null" {
            match type_check {
                "is_integer" => {
                    static INT_RE: OnceLock<Regex> = OnceLock::new();
                    let re = INT_RE.get_or_init(|| Regex::new(r"^-?[0-9]+$").unwrap());
                    if !re.is_match(raw_value) {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "integer".to_string(),
                        });
                    }
                }
                "is_boolean" => {
                    let lower = raw_value.to_lowercase();
                    if lower != "true" && lower != "false" {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "boolean".to_string(),
                        });
                    }
                }
                "is_string" => {
                    if parsed.is_object() || parsed.is_array() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "string".to_string(),
                        });
                    }
                    static NUM_RE: OnceLock<Regex> = OnceLock::new();
                    let num_re = NUM_RE.get_or_init(|| Regex::new(r"^-?[0-9]+(\.[0-9]+)?$").unwrap());
                    if num_re.is_match(raw_value)
                        || ["true", "false"].contains(&lower_cased(raw_value).as_str())
                    {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "string".to_string(),
                        });
                    }
                }
                "is_list" => {
                    if !parsed.is_array() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "list".to_string(),
                        });
                    }
                }
                "is_map" => {
                    if !parsed.is_object() {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "map".to_string(),
                        });
                    }
                }
                "is_process_payload"
                    if !parsed.is_object() && !parsed.is_array() => {
                        return Err(TypeValidationError::TypeCheckFailure {
                            type_name: type_name.to_string(),
                            value: raw_value.to_string(),
                            expected: "process payload".to_string(),
                        });
                    }
                _ => {}
            }
        }

    Ok(())
}

fn validate_field_list(
    registry: &TypeLattice,
    type_name: &str,
    parsed: &JsonValue,
    schema: &serde_yaml::Value,
    level: u8,
) -> Result<(), TypeValidationError> {
    let map = parsed.as_object().ok_or_else(|| TypeValidationError::StructuralError {
        type_name: type_name.to_string(),
        reason: "value is not a map/object".to_string(),
    })?;

    let required = schema.get("required_fields").and_then(|v| v.as_sequence()).cloned().unwrap_or_default();
    let optional = schema.get("optional_fields").and_then(|v| v.as_sequence()).cloned().unwrap_or_default();

    for field in &required {
        let f_name = field.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let f_type = field.get("type").and_then(|v| v.as_str()).unwrap_or("");
        let value = map.get(f_name).ok_or_else(|| TypeValidationError::MissingRequiredField {
            type_name: type_name.to_string(),
            field: f_name.to_string(),
        })?;
        registry.validate(f_type, &json_to_str(value), level)?;
        check_enum(type_name, f_name, value, field)?;
    }

    for field in &optional {
        let f_name = field.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let f_type = field.get("type").and_then(|v| v.as_str()).unwrap_or("");
        if let Some(value) = map.get(f_name)
            && !value.is_null() && json_to_str(value) != "null" {
                registry.validate(f_type, &json_to_str(value), level)?;
                check_enum(type_name, f_name, value, field)?;
            }
    }

    Ok(())
}

fn validate_json_schema(
    registry: &TypeLattice,
    type_name: &str,
    parsed: &JsonValue,
    schema: &serde_yaml::Value,
    level: u8,
) -> Result<(), TypeValidationError> {
    let map = parsed.as_object().ok_or_else(|| TypeValidationError::StructuralError {
        type_name: type_name.to_string(),
        reason: "value is not a map/object".to_string(),
    })?;

    let required = schema.get("required").and_then(|v| v.as_sequence()).cloned().unwrap_or_default();
    let properties = schema.get("properties").and_then(|v| v.as_mapping()).cloned().unwrap_or_default();

    for f_name_value in required {
        let f_name = f_name_value.as_str().unwrap_or("");
        let value = map.get(f_name).ok_or_else(|| TypeValidationError::MissingRequiredField {
            type_name: type_name.to_string(),
            field: f_name.to_string(),
        })?;
        let f_info = properties.get(&f_name_value).cloned().unwrap_or(serde_yaml::Value::Null);
        validate_json_schema_field(registry, type_name, f_name, value, &f_info, level)?;
    }

    Ok(())
}

fn validate_json_schema_field(
    registry: &TypeLattice,
    type_name: &str,
    _field: &str,
    value: &JsonValue,
    info: &serde_yaml::Value,
    level: u8,
) -> Result<(), TypeValidationError> {
    if let Some(pattern) = info.get("pattern").and_then(|v| v.as_str()) {
        let re = Regex::new(pattern).map_err(|e| TypeValidationError::StructuralError {
            type_name: type_name.to_string(),
            reason: format!("invalid regex '{}': {}", pattern, e),
        })?;
        if !re.is_match(&json_to_str(value)) {
            return Err(TypeValidationError::PatternViolation {
                type_name: type_name.to_string(),
                value: json_to_str(value),
                pattern: pattern.to_string(),
            });
        }
    }

    if let Some(f_type) = info.get("type").and_then(|v| v.as_str()) {
        let resolved = match f_type {
            "array" => "list",
            "object" => "map",
            other => other,
        };
        registry.validate(resolved, &json_to_str(value), level)?;
    }

    Ok(())
}

fn check_enum(
    type_name: &str,
    field: &str,
    value: &JsonValue,
    field_spec: &serde_yaml::Value,
) -> Result<(), TypeValidationError> {
    if let Some(en) = field_spec.get("constraints").and_then(|v| v.get("enum")).and_then(|v| v.as_sequence()) {
        let val_str = json_to_str(value);
        let allowed: Vec<String> = en.iter().map(yaml_to_str).collect();
        if !allowed.contains(&val_str) {
            return Err(TypeValidationError::EnumViolation {
                type_name: type_name.to_string(),
                field: field.to_string(),
                value: val_str,
            });
        }
    }
    Ok(())
}

fn json_to_str(value: &JsonValue) -> String {
    match value {
        JsonValue::String(s) => s.clone(),
        JsonValue::Number(n) => n.to_string(),
        JsonValue::Bool(b) => b.to_string(),
        JsonValue::Null => "null".to_string(),
        other => other.to_string(),
    }
}

fn yaml_to_str(value: &serde_yaml::Value) -> String {
    match value {
        serde_yaml::Value::String(s) => s.clone(),
        serde_yaml::Value::Number(n) => n.to_string(),
        serde_yaml::Value::Bool(b) => b.to_string(),
        serde_yaml::Value::Null => "null".to_string(),
        other => serde_yaml::to_string(other).unwrap_or_default().trim().to_string(),
    }
}

fn lower_cased(s: &str) -> String {
    s.to_lowercase()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_validate_string_and_integer() {
        let lattice = default_lattice();
        assert!(lattice.validate("string", "hello", 99).is_ok());
        assert!(lattice.validate("integer", "42", 99).is_ok());
        assert!(lattice.validate("integer", "3.14", 99).is_err());
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_universe_levels() {
        let lattice = default_lattice();
        let string_info = lattice.get_type_info("string").unwrap();
        let integer_info = lattice.get_type_info("integer").unwrap();
        let a_mcard_info = lattice.get_type_info("a_mcard").unwrap();
        assert_eq!(string_info.universe_level, 0);
        assert_eq!(integer_info.universe_level, 0);
        assert_eq!(a_mcard_info.universe_level, 1);
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_stratification_error() {
        let lattice = default_lattice();
        // agent is U2 nested inside a_mcard (U1) context should fail.
        assert!(lattice.validate("agent", r#"{"did":"did:key:z123"}"#, 1).is_err());
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_vcard_token_field_list() {
        let lattice = default_lattice();
        let payload = r#"{"gate_type":"callback","result":"pass","pcard_hash":"sha256:abc","agent_did":"did:key:z6MkNodeA"}"#;
        assert!(lattice.validate("vcard_token", payload, 99).is_ok());
    }

    // ── Compiled Type Lattice tests (Story 139.2.2) ──

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_compile_produces_manifests() {
        let lattice = default_lattice();
        let compiled = lattice.compile();
        assert!(compiled.manifests.contains_key("string"));
        assert!(compiled.manifests.contains_key("integer"));
        assert!(compiled.manifests.contains_key("a_mcard"));
        assert!(compiled.manifests.contains_key("vcard_token"));
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_compiled_verify_matches_recursive() {
        let lattice = default_lattice();
        let compiled = lattice.compile();
        // Positive cases
        assert!(compiled.verify("string", "hello", 99, &lattice).is_ok());
        assert!(compiled.verify("integer", "42", 99, &lattice).is_ok());
        // Negative cases
        assert!(compiled.verify("integer", "3.14", 99, &lattice).is_err());
        assert!(compiled.verify("agent", r#"{"did":"did:key:z123"}"#, 1, &lattice).is_err());
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_verify_by_hash_enum_type() {
        let lattice = default_lattice();
        let compiled = lattice.compile();
        // vcard_token has enum constraints on gate_type and result.
        // verify_by_hash should work for enum values.
        let valid_hash = hash_value("callback");
        let invalid_hash = hash_value("nonexistent_gate");
        // For enum-constrained types, verify_by_hash should return true
        // for allowed values and false for disallowed ones.
        // Note: verify_by_hash checks if the hash is in the enum set.
        // If vcard_token has enum hashes, this should work.
        let manifest = compiled.manifests.get("vcard_token");
        if let Some(m) = manifest {
            if !m.enum_hashes.is_empty() {
                assert!(compiled.verify_by_hash("vcard_token", &valid_hash) || !m.enum_hashes.contains(&valid_hash));
                assert!(!compiled.verify_by_hash("vcard_token", &invalid_hash));
            }
        }
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_compiled_lattice_cached() {
        // Calling compiled_lattice() twice should return the same reference.
        let a = compiled_lattice();
        let b = compiled_lattice();
        assert!(std::ptr::eq(a, b));
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_hash_type_name_deterministic() {
        let h1 = hash_type_name("string");
        let h2 = hash_type_name("string");
        assert_eq!(h1, h2);
        let h3 = hash_type_name("integer");
        assert_ne!(h1, h3);
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_benchmark_compiled_vs_recursive() {
        let lattice = default_lattice();
        let compiled = lattice.compile();
        let n = 10_000;

        // Benchmark recursive validation (baseline — still recompiles regexes).
        let start = std::time::Instant::now();
        for _ in 0..n {
            let _ = lattice.validate("integer", "42", 99);
        }
        let recursive_time = start.elapsed();

        // Benchmark compiled verification (uses pre-compiled regexes).
        let start = std::time::Instant::now();
        for _ in 0..n {
            let _ = compiled.verify("integer", "42", 99, &lattice);
        }
        let compiled_time = start.elapsed();

        // DoD: 10,000 compiled validations must complete in < 100ms.
        assert!(
            compiled_time.as_millis() < 100,
            "compiled verification took {}ms for {} iterations (DoD: < 100ms)",
            compiled_time.as_millis(),
            n
        );
        // Compiled path should be faster than recursive.
        assert!(
            compiled_time <= recursive_time,
            "compiled ({}) should be <= recursive ({})",
            compiled_time.as_millis(),
            recursive_time.as_millis()
        );
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_verify_by_hash_o1_characteristic() {
        let lattice = default_lattice();
        let compiled = lattice.compile();
        let h = hash_value("test");

        // verify_by_hash should be O(1) — constant time regardless of
        // the number of types or manifest complexity.
        let start = std::time::Instant::now();
        for _ in 0..10_000 {
            let _ = compiled.verify_by_hash("string", &h);
        }
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 10,
            "10k verify_by_hash calls took {}ms",
            elapsed.as_millis()
        );
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_lattice_meet_and_join() {
        let lattice = default_lattice();
        let t_str = lattice.get_type_info("string").unwrap();
        let t_int = lattice.get_type_info("integer").unwrap();

        // Meet: Product / Intersection
        let meet = lattice.meet(&t_str, &t_int);
        assert_eq!(meet.name, "(string ∧ integer)");

        // Join: Sum / Union
        let join = lattice.join(&t_str, &t_int);
        assert_eq!(join.name, "(string ∨ integer)");

        // Identities: Top & Bottom
        let top = TypeLattice::top();
        let bottom = TypeLattice::bottom();

        assert_eq!(lattice.meet(&t_str, &top).name, "string");
        assert_eq!(lattice.meet(&t_str, &bottom).name, "Bottom");
        assert_eq!(lattice.join(&t_str, &top).name, "Top");
        assert_eq!(lattice.join(&t_str, &bottom).name, "string");

        // Subtyping
        assert!(lattice.is_subtype(&meet, &t_str));
        assert!(lattice.is_subtype(&meet, &t_int));
        assert!(lattice.is_subtype(&t_str, &join));
        assert!(lattice.is_subtype(&t_int, &join));
        assert!(lattice.is_subtype(&bottom, &t_str));
        assert!(lattice.is_subtype(&t_str, &top));
    }

    #[test]
    fn test_governance_type_validation_and_stratification() {
        let manifest_body = include_str!("../types/governance/agent_write_scope.yaml");
        let mut lattice = TypeLattice::new();
        let info = parse_manifest("agent_write_scope", "types/governance/agent_write_scope.yaml", manifest_body)
            .expect("parse agent_write_scope manifest");
        assert_eq!(info.universe_level, 1, "agent_write_scope must be Universe Level 1");
        lattice.add_type("agent_write_scope".to_string(), info);

        // Validating with parent_level >= 1 succeeds
        let valid_payload = r#"{"agent_role": "winston", "agent_class": "EOA", "target_path": "docs/test.md"}"#;
        assert!(lattice.validate("agent_write_scope", valid_payload, 1).is_ok());
        assert!(lattice.validate("agent_write_scope", valid_payload, 2).is_ok());

        // Validating under parent_level 0 MUST trigger StratificationError
        let res = lattice.validate("agent_write_scope", valid_payload, 0);
        match res {
            Err(TypeValidationError::StratificationError { type_name, level, parent_level }) => {
                assert_eq!(type_name, "agent_write_scope");
                assert_eq!(level, 1);
                assert_eq!(parent_level, 0);
            }
            other => panic!("Expected StratificationError, got: {:?}", other),
        }
    }

    #[test]
    fn test_all_subdirs_loaded_and_census() {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let clm_root = std::path::Path::new(manifest_dir)
            .parent()
            .and_then(|p| p.parent());
        let types_dir = clm_root
            .map(|r| r.join("types"))
            .filter(|p| p.exists())
            .unwrap_or_else(|| std::path::Path::new(manifest_dir).join("types"));
        let root_str = types_dir.parent().unwrap_or(std::path::Path::new(manifest_dir)).to_string_lossy().to_string();
        let mut lattice = TypeLattice::new();
        lattice.load_registry(&root_str);

        // Assert all 12 subdirectories are recognized and checked
        for &subdir in TypeLattice::TYPE_REGISTRY_SUBDIRS {
            let subdir_path = types_dir.join(subdir);
            if subdir_path.exists() {
                let yaml_count = std::fs::read_dir(&subdir_path)
                    .unwrap()
                    .flatten()
                    .filter(|e| {
                        let name = e.file_name().to_string_lossy().to_string();
                        name.ends_with(".yaml") || name.ends_with(".yml")
                    })
                    .count();
                assert!(yaml_count > 0, "Subdir {} must contain at least one YAML manifest", subdir);
            }
        }

        // Census count assertion: All 110 types across 12 subdirectories are registered
        assert!(
            lattice.registry.len() >= 110,
            "Lattice registry census: expected >= 110 types across 12 subdirectories, found {}",
            lattice.registry.len()
        );

        // Every registered type must have a valid universe level (0..=4)
        for (name, info) in &lattice.registry {
            assert!(
                info.universe_level <= 4,
                "Type '{}' has invalid universe level: {}",
                name,
                info.universe_level
            );
        }
    }
}

/// 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");