Skip to main content

qualia_core_db/inference/conditioning/
validate.rs

1//! Specification validation, bounds, reference, and conflict checking.
2
3use super::authority::AuthorityView;
4use super::requirement::RequirementClass;
5use super::spec::{ConditioningError, ConditioningSpec};
6
7pub const MAX_PROFILE_ID_LEN: usize = 256;
8pub const MAX_OBJECTIVE_LEN: usize = 4096;
9pub const MAX_REQUIREMENTS_COUNT: usize = 64;
10pub const MAX_DOMAIN_REFS_COUNT: usize = 16;
11pub const SUPPORTED_SCHEMA_VERSION: u16 = 1;
12
13/// Validate a conditioning specification against schema constraints and authority view.
14pub fn validate_spec<'a>(
15    spec: &ConditioningSpec<'a>,
16    authority: &AuthorityView<'a>,
17) -> Result<(), ConditioningError> {
18    if spec.schema_version != SUPPORTED_SCHEMA_VERSION {
19        return Err(ConditioningError::UnsupportedVersion);
20    }
21
22    if spec.profile_id.is_empty() || spec.profile_id.len() > MAX_PROFILE_ID_LEN {
23        return Err(ConditioningError::ValidationFailed);
24    }
25
26    if spec.objective.is_empty() || spec.objective.len() > MAX_OBJECTIVE_LEN {
27        return Err(ConditioningError::ValidationFailed);
28    }
29
30    if spec.requirements.len() > MAX_REQUIREMENTS_COUNT {
31        return Err(ConditioningError::ContextBudgetExceeded);
32    }
33
34    if spec.domain_refs.len() > MAX_DOMAIN_REFS_COUNT {
35        return Err(ConditioningError::ContextBudgetExceeded);
36    }
37
38    if spec.budget.max_bytes == 0 || spec.budget.input_tokens == 0 {
39        return Err(ConditioningError::ValidationFailed);
40    }
41
42    // Check duplicate requirement IDs and enforce validator requirements
43    for (i, req) in spec.requirements.iter().enumerate() {
44        if req.id.is_empty() || req.rule.is_empty() {
45            return Err(ConditioningError::ValidationFailed);
46        }
47
48        // An Enforced requirement MUST provide a non-empty validator reference
49        if req.class == RequirementClass::Enforced {
50            match req.validator {
51                Some(v) if !v.trim().is_empty() => {}
52                _ => return Err(ConditioningError::ValidationFailed),
53            }
54        }
55
56        // Check duplicates
57        for other in &spec.requirements[i + 1..] {
58            if req.id == other.id {
59                return Err(ConditioningError::DuplicateRequirement);
60            }
61        }
62    }
63
64    // If tools are required by budget (tool_rounds > 0) but authority disallows tools
65    if spec.budget.tool_rounds > 0 && !authority.tools_allowed {
66        return Err(ConditioningError::DisclosureDenied);
67    }
68
69    Ok(())
70}