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()
}
pub const TYPE_REGISTRY_SUBDIRS: &'static [&'static str] = &[
"meta",
"primitives",
"runtime",
"content",
"transport",
"codegen",
"governance",
"identity",
"payment",
"observability",
"storage",
"core_features",
"chat",
];
pub const EXCLUDED_TYPE_SUBDIRS: &'static [&'static str] = &[
"schemas",
"lattice",
];
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),
}
}
}
}
}
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),
}
}
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 }
}
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,
}
}
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,
}
}
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,
}
}
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,
}
}
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
}
}
#[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;
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
}
pub const CLM_FEATURES_YAML: &str = include_str!("../types/lattice/clm_features.yaml");