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",
];
#[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),
}
}
}
}
}
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") {
if 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") {
if 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('∧') {
if sub.name.contains(&sup.name) {
return true;
}
}
if sup.name.starts_with('(') && sup.name.contains('∨') {
if sup.name.contains(&sub.name) {
return true;
}
}
sub.universe_level <= sup.universe_level
}
}
#[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]>,
}
#[derive(Debug, Clone)]
pub struct CompiledTypeLattice {
pub manifests: HashMap<String, CompiledTypeManifest>,
}
impl CompiledTypeLattice {
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,
});
}
let info = lattice.get_type_info(type_name).unwrap();
let style = detect_style(&info.schema);
match style {
SchemaStyle::Primitive => {
let parsed = parse_value(value);
if let Some(ref re) = manifest.compiled_regex {
if !re.is_match(value) {
return Err(TypeValidationError::PatternViolation {
type_name: type_name.to_string(),
value: value.to_string(),
pattern: re.as_str().to_string(),
});
}
}
validate_type_check(type_name, value, &parsed, &info.schema)
}
SchemaStyle::FieldList | SchemaStyle::JsonSchema => {
lattice.validate(type_name, value, parent_level)
}
}
}
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,
}
}
}
static COMPILED_LATTICE: OnceLock<CompiledTypeLattice> = OnceLock::new();
pub fn compiled_lattice() -> &'static CompiledTypeLattice {
COMPILED_LATTICE.get_or_init(|| default_lattice().compile())
}
pub fn hash_type_name(name: &str) -> [u8; 32] {
crate::hash::raw_hash_bytes_32(name.as_bytes())
}
pub fn hash_value(value: &str) -> [u8; 32] {
crate::hash::raw_hash_bytes_32(value.as_bytes())
}
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())
}
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()
}
fn extract_enum_hashes(schema: &serde_yaml::Value) -> HashSet<[u8; 32]> {
let mut hashes = HashSet::new();
if let Some(constraints) = schema.get("constraints") {
if 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));
}
}
}
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
}
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 {
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(']'))
{
if 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()) {
if 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()) {
if 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(())
}
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()) {
if 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) {
if !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(|v| yaml_to_str(v)).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();
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());
}
#[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();
assert!(compiled.verify("string", "hello", 99, &lattice).is_ok());
assert!(compiled.verify("integer", "42", 99, &lattice).is_ok());
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();
let valid_hash = hash_value("callback");
let invalid_hash = hash_value("nonexistent_gate");
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() {
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;
let start = std::time::Instant::now();
for _ in 0..n {
let _ = lattice.validate("integer", "42", 99);
}
let recursive_time = start.elapsed();
let start = std::time::Instant::now();
for _ in 0..n {
let _ = compiled.verify("integer", "42", 99, &lattice);
}
let compiled_time = start.elapsed();
assert!(
compiled_time.as_millis() < 100,
"compiled verification took {}ms for {} iterations (DoD: < 100ms)",
compiled_time.as_millis(),
n
);
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");
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();
let meet = lattice.meet(&t_str, &t_int);
assert_eq!(meet.name, "(string ∧ integer)");
let join = lattice.join(&t_str, &t_int);
assert_eq!(join.name, "(string ∨ integer)");
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");
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);
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());
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);
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);
}
}
assert!(
lattice.registry.len() >= 110,
"Lattice registry census: expected >= 110 types across 12 subdirectories, found {}",
lattice.registry.len()
);
for (name, info) in &lattice.registry {
assert!(
info.universe_level <= 4,
"Type '{}' has invalid universe level: {}",
name,
info.universe_level
);
}
}
}
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: &'static str = include_str!("../types/lattice/clm_features.yaml");