Skip to main content

domainforge_core/policy/
core.rs

1use super::expression::{BinaryOp, Expression, UnaryOp};
2use super::violation::{Severity, Violation};
3use crate::graph::Graph;
4use crate::policy::ThreeValuedBool;
5use crate::units::get_default_registry;
6use crate::{ConceptId, SemanticVersion};
7use rust_decimal::prelude::{FromPrimitive, FromStr};
8use rust_decimal::Decimal;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub enum PolicyModality {
13    Obligation,
14    Prohibition,
15    Permission,
16}
17
18/// Backwards-compatible alias used by existing tests and documentation
19#[allow(unused_imports)]
20pub use PolicyModality as DeonticModality;
21
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub enum PolicyKind {
24    Constraint,
25    Derivation,
26    Obligation,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Policy {
31    pub id: ConceptId,
32    pub name: String,
33    pub namespace: String,
34    pub version: SemanticVersion,
35    expression: Expression,
36    pub modality: PolicyModality,
37    pub kind: PolicyKind,
38    pub priority: i32,
39    pub rationale: Option<String>,
40    pub tags: Vec<String>,
41    #[serde(skip)]
42    cached_normalized_expr: std::sync::OnceLock<super::NormalizedExpression>,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct EvaluationResult {
47    /// Backwards compatible boolean representing whether a policy was satisfied.
48    /// Defaults to `false` if the evaluator produced an unknown (NULL) result.
49    pub is_satisfied: bool,
50    /// Tri-state evaluation result: Some(true/false) or None when evaluation is unknown.
51    pub is_satisfied_tristate: Option<bool>,
52    pub violations: Vec<Violation>,
53}
54
55/// One instance the outermost quantifier of a policy ranged over, with the
56/// truth value the existing evaluator assigns to the quantified condition for
57/// that instance (`None` = unknown).
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct BindingResult {
60    pub entity: Option<String>,
61    pub namespace: Option<String>,
62    pub instance: String,
63    pub instance_id: Option<String>,
64    pub result: Option<bool>,
65}
66
67/// Policy result plus per-instance results of the outermost quantifier.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct PolicyBindingReport {
70    /// Same value as `Policy::evaluate(..).is_satisfied_tristate`.
71    pub result: Option<bool>,
72    /// Instances the outermost quantifier ranged over; `None` when the policy
73    /// expression is not a quantifier. `Some(0)` marks vacuous truth.
74    pub support: Option<usize>,
75    pub bindings: Vec<BindingResult>,
76}
77
78impl Policy {
79    /// Evaluate the policy and, when its expression is a quantifier, report
80    /// the per-instance truth value of the outermost quantifier.
81    ///
82    /// The policy-level result is produced by [`Policy::evaluate`] unchanged;
83    /// each binding result is the same evaluator applied to the quantified
84    /// condition with that instance substituted. Nested quantifiers inside the
85    /// condition are folded into the binding's result (outermost binding only).
86    pub fn evaluate_bindings(&self, graph: &Graph) -> Result<PolicyBindingReport, String> {
87        let result = self.evaluate(graph)?.is_satisfied_tristate;
88        let Expression::Quantifier {
89            variable,
90            collection,
91            condition,
92            ..
93        } = &self.expression
94        else {
95            return Ok(PolicyBindingReport {
96                result,
97                support: None,
98                bindings: vec![],
99            });
100        };
101        let items = Expression::get_collection(collection, graph)?;
102        let support = items.len();
103        let mut bindings = Vec::with_capacity(support);
104        for item in items {
105            let expanded = condition.substitute(variable, &item)?.expand(graph)?;
106            let item_result = if graph.use_three_valued_logic() {
107                match self.evaluate_expression_three_valued(&expanded, graph)? {
108                    ThreeValuedBool::True => Some(true),
109                    ThreeValuedBool::False => Some(false),
110                    ThreeValuedBool::Null => None,
111                }
112            } else {
113                Some(self.evaluate_expression_boolean(&expanded, graph)?)
114            };
115            let text = |key: &str| item.get(key).and_then(|v| v.as_str()).map(str::to_string);
116            let id = text("id");
117            bindings.push(BindingResult {
118                entity: text("entity"),
119                namespace: text("namespace"),
120                instance: text("name").or_else(|| id.clone()).unwrap_or_default(),
121                instance_id: id,
122                result: item_result,
123            });
124        }
125        bindings.sort_by(|a, b| {
126            (a.instance.as_str(), a.instance_id.as_deref())
127                .cmp(&(b.instance.as_str(), b.instance_id.as_deref()))
128        });
129        Ok(PolicyBindingReport {
130            result,
131            support: Some(support),
132            bindings,
133        })
134    }
135
136    /// Returns the normalized canonical form of this policy's expression.
137    ///
138    /// Useful for caching, equivalence checking, and deterministic display.
139    #[must_use]
140    pub fn normalized_expression(&self) -> &super::NormalizedExpression {
141        self.cached_normalized_expr
142            .get_or_init(|| self.expression.normalize())
143    }
144
145    /// Get the policy expression.
146    pub fn expression(&self) -> &Expression {
147        &self.expression
148    }
149
150    /// Set the policy expression and invalidate the normalized cache.
151    pub fn set_expression(&mut self, expr: Expression) {
152        self.expression = expr;
153        // Invalidate cache by creating a new empty lock
154        self.cached_normalized_expr = std::sync::OnceLock::new();
155    }
156
157    pub fn new(name: impl Into<String>, expression: Expression) -> Self {
158        let name = name.into();
159        Self {
160            id: ConceptId::from_concept("default", &name),
161            name,
162            namespace: "default".to_string(),
163            version: SemanticVersion::default(),
164            expression,
165            modality: PolicyModality::Obligation,
166            kind: PolicyKind::Constraint,
167            priority: 0,
168            rationale: None,
169            tags: Vec::new(),
170            cached_normalized_expr: std::sync::OnceLock::new(),
171        }
172    }
173
174    pub fn new_with_namespace(
175        name: impl Into<String>,
176        namespace: impl Into<String>,
177        expression: Expression,
178    ) -> Self {
179        let namespace = namespace.into();
180        let name = name.into();
181        let id = ConceptId::from_concept(&namespace, &name);
182
183        Self {
184            id,
185            name,
186            namespace,
187            version: SemanticVersion::default(),
188            expression,
189            modality: PolicyModality::Obligation,
190            kind: PolicyKind::Constraint,
191            priority: 0,
192            rationale: None,
193            tags: Vec::new(),
194            cached_normalized_expr: std::sync::OnceLock::new(),
195        }
196    }
197
198    pub fn with_modality(mut self, modality: PolicyModality) -> Self {
199        self.modality = modality;
200        self
201    }
202
203    pub fn with_version(mut self, version: SemanticVersion) -> Self {
204        self.version = version;
205        self
206    }
207
208    pub fn with_kind(mut self, kind: PolicyKind) -> Self {
209        self.kind = kind;
210        self
211    }
212
213    pub fn with_priority(mut self, priority: i32) -> Self {
214        self.priority = priority;
215        self
216    }
217
218    pub fn with_rationale(mut self, rationale: impl Into<String>) -> Self {
219        self.rationale = Some(rationale.into());
220        self
221    }
222
223    pub fn with_tags<I, S>(mut self, tags: I) -> Self
224    where
225        I: IntoIterator<Item = S>,
226        S: Into<String>,
227    {
228        self.tags = tags.into_iter().map(Into::into).collect();
229        self
230    }
231
232    pub fn with_metadata(
233        mut self,
234        kind: Option<PolicyKind>,
235        modality: Option<PolicyModality>,
236        priority: Option<i32>,
237        rationale: Option<String>,
238        tags: Vec<String>,
239    ) -> Self {
240        if let Some(kind) = kind {
241            self.kind = kind;
242        }
243        if let Some(modality) = modality {
244            self.modality = modality;
245        }
246        if let Some(priority) = priority {
247            self.priority = priority;
248        }
249        self.rationale = rationale;
250        if !tags.is_empty() {
251            self.tags = tags;
252        }
253        self
254    }
255
256    pub fn kind(&self) -> &PolicyKind {
257        &self.kind
258    }
259
260    pub fn evaluate(&self, graph: &Graph) -> Result<EvaluationResult, String> {
261        self.evaluate_with_mode(graph, graph.use_three_valued_logic())
262    }
263
264    pub fn evaluate_with_mode(
265        &self,
266        graph: &Graph,
267        use_three_valued_logic: bool,
268    ) -> Result<EvaluationResult, String> {
269        Self::validate_aggregation_usage(&self.expression, true)?;
270
271        let expanded = self.expression.expand(graph)?;
272
273        // Evaluate expression; runtime toggle chooses three-valued vs boolean path.
274        // We compute the tri-state result and derive a backward-compatible boolean (false when Null).
275        let is_satisfied_tristate: Option<bool> = if use_three_valued_logic {
276            match self.evaluate_expression_three_valued(&expanded, graph)? {
277                ThreeValuedBool::True => Some(true),
278                ThreeValuedBool::False => Some(false),
279                ThreeValuedBool::Null => None,
280            }
281        } else {
282            Some(self.evaluate_expression_boolean(&expanded, graph)?)
283        };
284
285        let is_satisfied = is_satisfied_tristate.unwrap_or(false);
286
287        let violations = if is_satisfied_tristate == Some(true) {
288            vec![]
289        } else if is_satisfied_tristate == Some(false) {
290            vec![Violation::new(
291                &self.name,
292                format!("Policy '{}' was violated", self.name),
293                self.modality.to_severity(),
294            )]
295        } else {
296            // Unknown (NULL) evaluation: severity follows the policy modality.
297            vec![Violation::new(
298                &self.name,
299                format!("Policy '{}' evaluation is UNKNOWN (NULL)", self.name),
300                self.modality.to_severity(),
301            )]
302        };
303
304        Ok(EvaluationResult {
305            is_satisfied,
306            is_satisfied_tristate,
307            violations,
308        })
309    }
310
311    fn validate_aggregation_usage(
312        expr: &Expression,
313        in_boolean_context: bool,
314    ) -> Result<(), String> {
315        match expr {
316            Expression::Aggregation { .. } | Expression::AggregationComprehension { .. } => {
317                if in_boolean_context {
318                    Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string())
319                } else {
320                    Ok(())
321                }
322            }
323            Expression::Binary { op, left, right } => {
324                let child_boolean = matches!(op, BinaryOp::And | BinaryOp::Or);
325                Self::validate_aggregation_usage(left, child_boolean)?;
326                Self::validate_aggregation_usage(right, child_boolean)?;
327                Ok(())
328            }
329            Expression::Unary { op, operand } => {
330                let child_boolean = matches!(op, UnaryOp::Not);
331                Self::validate_aggregation_usage(operand, child_boolean)
332            }
333            Expression::Quantifier {
334                collection,
335                condition,
336                ..
337            } => {
338                Self::validate_aggregation_usage(collection, false)?;
339                Self::validate_aggregation_usage(condition, true)
340            }
341            Expression::GroupBy {
342                collection,
343                filter,
344                key,
345                condition,
346                ..
347            } => {
348                Self::validate_aggregation_usage(collection, false)?;
349                if let Some(f) = filter {
350                    Self::validate_aggregation_usage(f, true)?;
351                }
352                Self::validate_aggregation_usage(key, false)?;
353                Self::validate_aggregation_usage(condition, true)
354            }
355            _ => Ok(()),
356        }
357    }
358
359    fn evaluate_expression_boolean(
360        &self,
361        expr: &Expression,
362        graph: &Graph,
363    ) -> Result<bool, String> {
364        match expr {
365            Expression::Literal(v) => v
366                .as_bool()
367                .ok_or_else(|| format!("Expected boolean literal, got: {}", v)),
368            Expression::Variable(name) => {
369                Err(format!("Cannot evaluate unexpanded variable: {}", name))
370            }
371            Expression::Cast { .. } => {
372                let val = Self::get_runtime_value(expr, graph)?;
373                val.as_bool()
374                    .ok_or_else(|| format!("Expected boolean from cast, got: {}", val))
375            }
376            Expression::Binary { op, left, right } => match op {
377                BinaryOp::And | BinaryOp::Or => {
378                    let left_val = self.evaluate_expression_boolean(left, graph)?;
379                    let right_val = self.evaluate_expression_boolean(right, graph)?;
380
381                    Ok(match op {
382                        BinaryOp::And => left_val && right_val,
383                        BinaryOp::Or => left_val || right_val,
384                        _ => unreachable!(),
385                    })
386                }
387                BinaryOp::Equal | BinaryOp::NotEqual => {
388                    self.compare_values(left, right, graph, |l, r| match op {
389                        BinaryOp::Equal => l == r,
390                        BinaryOp::NotEqual => l != r,
391                        _ => unreachable!(),
392                    })
393                }
394                BinaryOp::GreaterThan
395                | BinaryOp::LessThan
396                | BinaryOp::GreaterThanOrEqual
397                | BinaryOp::LessThanOrEqual => {
398                    self.compare_numeric(left, right, graph, |l, r| match op {
399                        BinaryOp::GreaterThan => l > r,
400                        BinaryOp::LessThan => l < r,
401                        BinaryOp::GreaterThanOrEqual => l >= r,
402                        BinaryOp::LessThanOrEqual => l <= r,
403                        _ => unreachable!(),
404                    })
405                }
406                BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
407                    Err("Arithmetic operations not supported in boolean context".to_string())
408                }
409                BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => self
410                    .compare_strings(left, right, graph, |l, r| match op {
411                        BinaryOp::Contains => l.contains(r),
412                        BinaryOp::StartsWith => l.starts_with(r),
413                        BinaryOp::EndsWith => l.ends_with(r),
414                        _ => unreachable!(),
415                    }),
416                BinaryOp::HasRole => self.evaluate_has_role(left, right, graph),
417                BinaryOp::Matches => self.evaluate_pattern_match(left, right, graph),
418                BinaryOp::Before | BinaryOp::After | BinaryOp::During => {
419                    // Temporal operators - parse and compare ISO 8601 timestamps
420                    let left_str = self.get_string_value(left, graph)?;
421                    let right_str = self.get_string_value(right, graph)?;
422
423                    // Parse timestamps using timefmt
424                    let left_dt = crate::timefmt::parse_rfc3339(&left_str).map_err(|e| {
425                        format!("Failed to parse left timestamp '{}': {}", left_str, e)
426                    })?;
427                    let right_dt = crate::timefmt::parse_rfc3339(&right_str).map_err(|e| {
428                        format!("Failed to parse right timestamp '{}': {}", right_str, e)
429                    })?;
430
431                    let result = match op {
432                        BinaryOp::Before => left_dt < right_dt,
433                        BinaryOp::After => left_dt > right_dt,
434                        BinaryOp::During => {
435                            return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string())
436                        }
437                        _ => unreachable!(),
438                    };
439                    Ok(result)
440                }
441            },
442            Expression::Unary { op, operand } => {
443                let val = self.evaluate_expression_boolean(operand, graph)?;
444                Ok(match op {
445                    UnaryOp::Not => !val,
446                    UnaryOp::Negate => {
447                        return Err("Negate operator not supported in boolean context".to_string())
448                    }
449                })
450            }
451            Expression::Quantifier { .. } => {
452                Err("Cannot evaluate non-expanded quantifier".to_string())
453            }
454            Expression::MemberAccess { object, member } => {
455                let value = Self::get_runtime_value(expr, graph)?;
456                match value {
457                    serde_json::Value::Bool(v) => Ok(v),
458                    serde_json::Value::Null => Ok(false),
459                    _ => Err(format!(
460                        "Expected boolean value for member '{}.{}', but found {:?}",
461                        object, member, value
462                    )),
463                }
464            }
465            Expression::Aggregation { .. } => {
466                Err("Cannot evaluate non-expanded aggregation".to_string())
467            }
468            Expression::AggregationComprehension { .. } => {
469                Err("Cannot evaluate non-expanded aggregation comprehension".to_string())
470            }
471            Expression::QuantityLiteral { .. } => {
472                Err("Cannot evaluate quantity literal in boolean context".to_string())
473            }
474            Expression::TimeLiteral(_) => {
475                Err("Cannot evaluate time literal in boolean context".to_string())
476            }
477            Expression::IntervalLiteral { .. } => {
478                Err("Cannot evaluate interval literal in boolean context".to_string())
479            }
480            Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
481            Expression::RoleReference { .. } => {
482                Err("Cannot evaluate role reference outside application policy context".to_string())
483            }
484        }
485    }
486
487    fn evaluate_expression_three_valued(
488        &self,
489        expr: &Expression,
490        graph: &Graph,
491    ) -> Result<ThreeValuedBool, String> {
492        use ThreeValuedBool as T;
493
494        match expr {
495            Expression::Literal(v) => Ok(T::from_option_bool(v.as_bool())),
496            Expression::Variable(name) => Err(format!("Cannot evaluate unexpanded variable: {}", name)),
497            Expression::Cast { .. } => {
498                let val = Self::get_runtime_value(expr, graph)?;
499                Ok(T::from_option_bool(val.as_bool()))
500            }
501            Expression::Binary { op, left, right } => match op {
502                BinaryOp::And | BinaryOp::Or => {
503                    let l = self.evaluate_expression_three_valued(left, graph)?;
504                    let r = self.evaluate_expression_three_valued(right, graph)?;
505                    Ok(match op {
506                        BinaryOp::And => l.and(r),
507                        BinaryOp::Or => l.or(r),
508                        _ => unreachable!(),
509                    })
510                }
511                BinaryOp::Equal | BinaryOp::NotEqual => {
512                    let left_val = Self::get_runtime_value(left, graph);
513                    let right_val = Self::get_runtime_value(right, graph);
514                    match (left_val, right_val) {
515                        (Ok(lv), Ok(rv)) => {
516                            // If either operand is JSON Null, the comparison yields Null.
517                            if lv.is_null() || rv.is_null() {
518                                Ok(T::Null)
519                            } else {
520                                let numeric_eq = match (
521                                    Self::parse_numeric_with_unit_value(&lv),
522                                    Self::parse_numeric_with_unit_value(&rv),
523                                ) {
524                                    (Ok(ln), Ok(rn)) => {
525                                        self.normalize_units_nullable(ln, rn)?
526                                            .map(|(l, r)| l == r)
527                                    }
528                                    _ => None,
529                                };
530
531                                let equality = if let Some(eq) = numeric_eq {
532                                    Some(eq)
533                                } else if lv.is_number() || rv.is_number() {
534                                    None
535                                } else {
536                                    Some(lv == rv)
537                                };
538
539                                let eq = match (op, equality) {
540                                    (_, None) => return Ok(T::Null),
541                                    (BinaryOp::Equal, Some(true)) => true,
542                                    (BinaryOp::Equal, Some(false)) => false,
543                                    (BinaryOp::NotEqual, Some(true)) => false,
544                                    (BinaryOp::NotEqual, Some(false)) => true,
545                                    _ => unreachable!(),
546                                };
547
548                                Ok(T::from_option_bool(Some(eq)))
549                            }
550                        }
551                        _ => Ok(T::Null),
552                    }
553                }
554                BinaryOp::GreaterThan
555                | BinaryOp::LessThan
556                | BinaryOp::GreaterThanOrEqual
557                | BinaryOp::LessThanOrEqual => {
558                    let left_v = Self::get_runtime_value(left, graph);
559                    let right_v = Self::get_runtime_value(right, graph);
560                    match (left_v, right_v) {
561                        (Ok(lv), Ok(rv)) => {
562                            if lv.is_null() || rv.is_null() {
563                                Ok(T::Null)
564                            } else {
565                                let numeric = self
566                                    .normalize_units_nullable(
567                                        Self::parse_numeric_with_unit_value(&lv)
568                                            .ok()
569                                            .flatten(),
570                                        Self::parse_numeric_with_unit_value(&rv)
571                                            .ok()
572                                            .flatten(),
573                                    )?
574                                    .map(|(l, r)| match op {
575                                        BinaryOp::GreaterThan => l > r,
576                                        BinaryOp::LessThan => l < r,
577                                        BinaryOp::GreaterThanOrEqual => l >= r,
578                                        BinaryOp::LessThanOrEqual => l <= r,
579                                        _ => unreachable!(),
580                                    });
581
582                                Ok(T::from_option_bool(numeric))
583                            }
584                        }
585                        _ => Ok(T::Null),
586                    }
587                }
588                BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
589                    Err("Arithmetic operations not supported in boolean context".to_string())
590                }
591                BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
592                    let left_v = Self::get_runtime_value(left, graph);
593                    let right_v = Self::get_runtime_value(right, graph);
594                    match (left_v, right_v) {
595                        (Ok(lv), Ok(rv)) => {
596                            if lv.is_null() || rv.is_null() {
597                                Ok(T::Null)
598                            } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
599                                let ok = match op {
600                                    BinaryOp::Contains => ls.contains(rs),
601                                    BinaryOp::StartsWith => ls.starts_with(rs),
602                                    BinaryOp::EndsWith => ls.ends_with(rs),
603                                    _ => unreachable!(),
604                                };
605                                Ok(T::from_option_bool(Some(ok)))
606                            } else {
607                                Ok(T::Null)
608                            }
609                        }
610                        _ => Ok(T::Null),
611                    }
612                }
613                BinaryOp::HasRole => {
614                    let role_check = self.evaluate_has_role(left, right, graph)?;
615                    Ok(T::from_option_bool(Some(role_check)))
616                }
617                BinaryOp::Matches => {
618                    let left_v = Self::get_runtime_value(left, graph);
619                    let right_v = Self::get_runtime_value(right, graph);
620
621                    match (left_v, right_v) {
622                        (Ok(lv), Ok(rv)) => {
623                            if lv.is_null() || rv.is_null() {
624                                return Ok(T::Null);
625                            }
626
627                            if let (Some(candidate), Some(pattern_name)) = (lv.as_str(), rv.as_str()) {
628                                let pattern = graph
629                                    .find_pattern(pattern_name, Some(&self.namespace))
630                                    .ok_or_else(|| {
631                                        format!(
632                                            "Pattern '{}' not found in namespace '{}'",
633                                            pattern_name, self.namespace
634                                        )
635                                    })?;
636                                let is_match = pattern.is_match(candidate).map_err(|e| {
637                                    format!(
638                                        "Pattern '{}' failed to evaluate: {}",
639                                        pattern_name, e
640                                    )
641                                })?;
642                                Ok(T::from_option_bool(Some(is_match)))
643                            } else {
644                                Ok(T::Null)
645                            }
646                        }
647                        _ => Ok(T::Null),
648                    }
649                }
650                BinaryOp::Before | BinaryOp::After | BinaryOp::During => {
651                    // Temporal operators
652                    if matches!(op, BinaryOp::During) {
653                        return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string());
654                    }
655
656                    // Parse and compare ISO 8601 timestamps
657                    let left_v = Self::get_runtime_value(left, graph);
658                    let right_v = Self::get_runtime_value(right, graph);
659                    match (left_v, right_v) {
660                        (Ok(lv), Ok(rv)) => {
661                            if lv.is_null() || rv.is_null() {
662                                Ok(T::Null)
663                            } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
664                                // Parse timestamps using timefmt
665                                let left_dt = match crate::timefmt::parse_rfc3339(ls) {
666                                    Ok(dt) => dt,
667                                    Err(_) => return Ok(T::Null), // Invalid timestamp -> Null
668                                };
669                                let right_dt = match crate::timefmt::parse_rfc3339(rs) {
670                                    Ok(dt) => dt,
671                                    Err(_) => return Ok(T::Null), // Invalid timestamp -> Null
672                                };
673
674                                let result = match op {
675                                    BinaryOp::Before => left_dt < right_dt,
676                                    BinaryOp::After => left_dt > right_dt,
677                                    _ => unreachable!(),
678                                };
679                                Ok(T::from_option_bool(Some(result)))
680                            } else {
681                                Ok(T::Null)
682                            }
683                        }
684                        _ => Ok(T::Null),
685                    }
686                }
687            },
688            Expression::Unary { op, operand } => {
689                let v = self.evaluate_expression_three_valued(operand, graph)?;
690                Ok(match op {
691                    UnaryOp::Not => v.not(),
692                    UnaryOp::Negate => return Err("Negate operator not supported in boolean context".to_string()),
693                })
694            }
695            Expression::Quantifier { quantifier, variable, collection, condition } => {
696                // Evaluate quantifiers with three-valued semantics
697                let items = Expression::get_collection(collection, graph)?;
698                use super::expression::Quantifier as Q;
699
700                let mut saw_true = 0usize;
701                let mut saw_false = 0usize;
702                let mut saw_null = 0usize;
703
704                for item in items {
705                    let substituted = condition.substitute(variable, &item)?;
706                    let val = self.evaluate_expression_three_valued(&substituted, graph)?;
707                    match val {
708                        T::True => saw_true += 1,
709                        T::False => saw_false += 1,
710                        T::Null => saw_null += 1,
711                    }
712                }
713
714                match quantifier {
715                    Q::ForAll => {
716                        if saw_false > 0 { return Ok(T::False); }
717                        if saw_null > 0 { return Ok(T::Null); }
718                        Ok(T::True)
719                    }
720                    Q::Exists => {
721                        if saw_true > 0 { return Ok(T::True); }
722                        if saw_null > 0 { return Ok(T::Null); }
723                        Ok(T::False)
724                    }
725                    Q::ExistsUnique => {
726                        if saw_true > 1 { return Ok(T::False); }
727                        if saw_true == 1 && saw_null == 0 { return Ok(T::True); }
728                        if saw_true == 1 && saw_null > 0 { return Ok(T::Null); }
729                        if saw_true == 0 && saw_null > 0 { return Ok(T::Null); }
730                        Ok(T::False)
731                    }
732                }
733            }
734            Expression::MemberAccess { object: _, member: _ } => {
735                // Resolve object/member to a runtime value and convert to bool
736                let value = Self::get_runtime_value(expr, graph)?;
737                Ok(T::from_option_bool(value.as_bool()))
738            }
739            Expression::Aggregation { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
740            Expression::AggregationComprehension { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
741            Expression::QuantityLiteral { .. } => Err("Cannot convert quantity to boolean; compare against a threshold instead".to_string()),
742            Expression::TimeLiteral(_) => Err("Cannot convert time to boolean; use temporal comparison operators".to_string()),
743            Expression::IntervalLiteral { .. } => Err("Cannot convert interval to boolean; use temporal comparison operators".to_string()),
744            Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
745            Expression::RoleReference { .. } => Err(
746                "Cannot evaluate role reference outside application policy context".to_string(),
747            ),
748        }
749    }
750
751    fn compare_values<F>(
752        &self,
753        left: &Expression,
754        right: &Expression,
755        graph: &Graph,
756        op: F,
757    ) -> Result<bool, String>
758    where
759        F: Fn(&serde_json::Value, &serde_json::Value) -> bool,
760    {
761        let left_val = self
762            .get_literal_value(left)
763            .or_else(|_| Self::get_runtime_value(left, graph))?;
764        let right_val = self
765            .get_literal_value(right)
766            .or_else(|_| Self::get_runtime_value(right, graph))?;
767        Ok(op(&left_val, &right_val))
768    }
769
770    fn compare_numeric<F>(
771        &self,
772        left: &Expression,
773        right: &Expression,
774        graph: &Graph,
775        op: F,
776    ) -> Result<bool, String>
777    where
778        F: Fn(Decimal, Decimal) -> bool,
779    {
780        let left_val = self.resolve_numeric_with_unit(left, graph)?;
781        let right_val = self.resolve_numeric_with_unit(right, graph)?;
782        let (left_aligned, right_aligned) = self.normalize_units_strict(left_val, right_val)?;
783        Ok(op(left_aligned, right_aligned))
784    }
785
786    fn compare_strings<F>(
787        &self,
788        left: &Expression,
789        right: &Expression,
790        graph: &Graph,
791        op: F,
792    ) -> Result<bool, String>
793    where
794        F: Fn(&str, &str) -> bool,
795    {
796        let left_val = self.get_string_value(left, graph)?;
797        let right_val = self.get_string_value(right, graph)?;
798        Ok(op(&left_val, &right_val))
799    }
800
801    fn evaluate_pattern_match(
802        &self,
803        left: &Expression,
804        right: &Expression,
805        graph: &Graph,
806    ) -> Result<bool, String> {
807        let candidate = self.get_string_value(left, graph)?;
808        let pattern_name = self.get_string_value(right, graph)?;
809
810        let pattern = graph
811            .find_pattern(&pattern_name, Some(&self.namespace))
812            .ok_or_else(|| {
813                format!(
814                    "Pattern '{}' not found in namespace '{}'",
815                    pattern_name, self.namespace
816                )
817            })?;
818
819        pattern
820            .is_match(&candidate)
821            .map_err(|e| format!("Pattern '{}' failed to evaluate: {}", pattern_name, e))
822    }
823
824    fn evaluate_has_role(
825        &self,
826        left: &Expression,
827        right: &Expression,
828        graph: &Graph,
829    ) -> Result<bool, String> {
830        let target_role = self.get_string_value(right, graph)?;
831        let roles = self.collect_roles(left, graph)?;
832
833        Ok(roles
834            .iter()
835            .any(|role| role.eq_ignore_ascii_case(&target_role)))
836    }
837
838    fn collect_roles(&self, expr: &Expression, graph: &Graph) -> Result<Vec<String>, String> {
839        let value = Self::get_runtime_value(expr, graph)?;
840
841        if let Some(arr) = value.as_array() {
842            return Ok(arr
843                .iter()
844                .filter_map(|v| v.as_str().map(|s| s.to_string()))
845                .collect());
846        }
847
848        if let Some(obj) = value.as_object() {
849            if let Some(roles) = obj.get("roles").and_then(|r| r.as_array()) {
850                return Ok(roles
851                    .iter()
852                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
853                    .collect());
854            }
855
856            if let Some(name) = obj.get("name").and_then(|v| v.as_str()) {
857                if let Some(entity_id) = graph.find_entity_by_name(name) {
858                    return Ok(graph.role_names_for_entity(&entity_id));
859                }
860            }
861        }
862
863        if let Some(name) = value.as_str() {
864            if let Some(entity_id) = graph.find_entity_by_name(name) {
865                return Ok(graph.role_names_for_entity(&entity_id));
866            }
867
868            if let Some(role_id) = graph.find_role_by_name(name) {
869                if let Some(role) = graph.get_role(&role_id) {
870                    return Ok(vec![role.name().to_string()]);
871                }
872            }
873        }
874
875        Ok(Vec::new())
876    }
877
878    fn get_literal_value(&self, expr: &Expression) -> Result<serde_json::Value, String> {
879        match expr {
880            Expression::Literal(v) => Ok(v.clone()),
881            _ => Err("Expected literal value".to_string()),
882        }
883    }
884
885    fn parse_decimal_value(value: &serde_json::Value) -> Result<Decimal, String> {
886        if let Some(s) = value.as_str() {
887            Decimal::from_str(s).map_err(|e| e.to_string())
888        } else if let Some(f) = value.as_f64() {
889            Decimal::from_f64(f).ok_or_else(|| format!("Unable to represent {} as Decimal", f))
890        } else if let Some(i) = value.as_i64() {
891            Ok(Decimal::from(i))
892        } else if let Some(u) = value.as_u64() {
893            Decimal::from_u64(u).ok_or_else(|| format!("Unable to represent {} as Decimal", u))
894        } else {
895            Err(format!("Expected numeric value, got: {}", value))
896        }
897    }
898
899    fn parse_numeric_with_unit_value(
900        value: &serde_json::Value,
901    ) -> Result<Option<(Decimal, Option<String>)>, String> {
902        if let Some(obj) = value.as_object() {
903            match (obj.get("__quantity_value"), obj.get("__quantity_unit")) {
904                (Some(q_val), Some(q_unit)) => {
905                    let unit_str = q_unit
906                        .as_str()
907                        .ok_or_else(|| {
908                            format!("Expected __quantity_unit to be string, got: {}", q_unit)
909                        })?
910                        .to_string();
911                    let value_dec = Self::parse_decimal_value(q_val)
912                        .map_err(|e| format!("Invalid __quantity_value: {}", e))?;
913                    return Ok(Some((value_dec, Some(unit_str))));
914                }
915                (Some(_), None) | (None, Some(_)) => {
916                    return Err(
917                        "Quantity object must include both __quantity_value and __quantity_unit"
918                            .to_string(),
919                    )
920                }
921                _ => {}
922            }
923        }
924
925        if value.is_number() || value.is_string() {
926            return Ok(Some((Self::parse_decimal_value(value)?, None)));
927        }
928
929        Ok(None)
930    }
931
932    fn resolve_numeric_with_unit(
933        &self,
934        expr: &Expression,
935        graph: &Graph,
936    ) -> Result<(Decimal, Option<String>), String> {
937        let value = self
938            .get_literal_value(expr)
939            .or_else(|_| Self::get_runtime_value(expr, graph))?;
940        Self::parse_numeric_with_unit_value(&value)?
941            .ok_or_else(|| format!("Expected numeric value, got: {}", value))
942    }
943
944    fn normalize_units_strict(
945        &self,
946        left: (Decimal, Option<String>),
947        right: (Decimal, Option<String>),
948    ) -> Result<(Decimal, Decimal), String> {
949        match (left.1, right.1) {
950            (Some(l_unit), Some(r_unit)) => {
951                let registry = get_default_registry();
952                let registry = registry
953                    .read()
954                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
955
956                if l_unit == r_unit {
957                    Ok((left.0, right.0))
958                } else {
959                    let from = registry
960                        .get_unit(&r_unit)
961                        .map_err(|e| format!("Invalid unit '{}': {}", r_unit, e))?;
962                    let to = registry
963                        .get_unit(&l_unit)
964                        .map_err(|e| format!("Invalid unit '{}': {}", l_unit, e))?;
965                    let converted = registry
966                        .convert(right.0, from, to)
967                        .map_err(|e| format!("Unit conversion failed: {}", e))?;
968                    Ok((left.0, converted))
969                }
970            }
971            (None, None) => Ok((left.0, right.0)),
972            (Some(l_unit), None) => Err(format!(
973                "Cannot compare quantity with unit '{}' to unitless value",
974                l_unit
975            )),
976            (None, Some(r_unit)) => Err(format!(
977                "Cannot compare unitless value to quantity with unit '{}'",
978                r_unit
979            )),
980        }
981    }
982
983    fn normalize_units_nullable(
984        &self,
985        left: Option<(Decimal, Option<String>)>,
986        right: Option<(Decimal, Option<String>)>,
987    ) -> Result<Option<(Decimal, Decimal)>, String> {
988        let (left, right) = match (left, right) {
989            (Some(l), Some(r)) => (l, r),
990            _ => return Ok(None),
991        };
992
993        match (left.1.clone(), right.1.clone()) {
994            (Some(l_unit), Some(r_unit)) => {
995                let registry = get_default_registry();
996                let registry = registry
997                    .read()
998                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
999                if l_unit == r_unit {
1000                    Ok(Some((left.0, right.0)))
1001                } else {
1002                    let from = registry.get_unit(&r_unit);
1003                    let to = registry.get_unit(&l_unit);
1004                    if let (Ok(from), Ok(to)) = (from, to) {
1005                        match registry.convert(right.0, from, to) {
1006                            Ok(converted) => Ok(Some((left.0, converted))),
1007                            Err(_) => Ok(None),
1008                        }
1009                    } else {
1010                        Ok(None)
1011                    }
1012                }
1013            }
1014            (None, None) => Ok(Some((left.0, right.0))),
1015            _ => Ok(None),
1016        }
1017    }
1018
1019    fn get_string_value(&self, expr: &Expression, graph: &Graph) -> Result<String, String> {
1020        let v = self
1021            .get_literal_value(expr)
1022            .or_else(|_| Self::get_runtime_value(expr, graph))?;
1023        v.as_str()
1024            .map(|s| s.to_string())
1025            .ok_or_else(|| "Expected string value".to_string())
1026    }
1027
1028    fn get_runtime_value(expr: &Expression, graph: &Graph) -> Result<serde_json::Value, String> {
1029        match expr {
1030            Expression::Literal(v) => Ok(v.clone()),
1031            Expression::MemberAccess { object, member } => {
1032                // Try resolving as entity
1033                if let Some(id) = graph.find_entity_by_name(object) {
1034                    if let Some(entity) = graph.get_entity(&id) {
1035                        // Special known members
1036                        if member == "id" {
1037                            return Ok(serde_json::json!(entity.id().to_string()));
1038                        } else if member == "name" {
1039                            return Ok(serde_json::json!(entity.name()));
1040                        } else if member == "namespace" {
1041                            return Ok(serde_json::json!(entity.namespace()));
1042                        }
1043                        if let Some(val) = entity.get_attribute(member) {
1044                            if val.is_null() {
1045                                log::debug!(
1046                                    "Entity '{}' member '{}' present but NULL; returning Null",
1047                                    object,
1048                                    member
1049                                );
1050                            }
1051                            return Ok(val.clone());
1052                        }
1053                        log::debug!(
1054                            "Entity '{}' found but member '{}' missing; returning Null",
1055                            object,
1056                            member
1057                        );
1058                        return Ok(serde_json::Value::Null);
1059                    } else {
1060                        log::debug!(
1061                            "Entity lookup for '{}' returned id {} but entity missing; returning Null",
1062                            object, id
1063                        );
1064                    }
1065                } else {
1066                    log::debug!(
1067                        "Entity '{}' not found while resolving member '{}'; continuing lookup",
1068                        object,
1069                        member
1070                    );
1071                }
1072
1073                if let Some(id) = graph.find_resource_by_name(object) {
1074                    if let Some(resource) = graph.get_resource(&id) {
1075                        if member == "id" {
1076                            return Ok(serde_json::json!(resource.id().to_string()));
1077                        } else if member == "name" {
1078                            return Ok(serde_json::json!(resource.name()));
1079                        } else if member == "unit" {
1080                            return Ok(serde_json::json!(resource.unit()));
1081                        }
1082                        if let Some(val) = resource.get_attribute(member) {
1083                            if val.is_null() {
1084                                log::debug!(
1085                                    "Resource '{}' member '{}' present but NULL; returning Null",
1086                                    object,
1087                                    member
1088                                );
1089                            }
1090                            return Ok(val.clone());
1091                        }
1092                        log::debug!(
1093                            "Resource '{}' found but member '{}' missing; returning Null",
1094                            object,
1095                            member
1096                        );
1097                        return Ok(serde_json::Value::Null);
1098                    } else {
1099                        log::debug!(
1100                            "Resource lookup for '{}' returned id {} but resource missing; returning Null",
1101                            object, id
1102                        );
1103                    }
1104                } else {
1105                    log::debug!(
1106                        "Resource '{}' not found while resolving member '{}'; returning Null",
1107                        object,
1108                        member
1109                    );
1110                }
1111
1112                // Not found: return Null to indicate unknown member
1113                log::debug!(
1114                    "Member access '{}.{}' did not resolve to entity or resource; returning Null",
1115                    object,
1116                    member
1117                );
1118                Ok(serde_json::Value::Null)
1119            }
1120            Expression::Aggregation {
1121                function,
1122                collection,
1123                field,
1124                filter,
1125            } => {
1126                let v =
1127                    Expression::evaluate_aggregation(function, collection, field, filter, graph)?;
1128                Ok(v)
1129            }
1130            Expression::AggregationComprehension {
1131                function,
1132                variable,
1133                collection,
1134                window,
1135                predicate,
1136                projection,
1137                target_unit,
1138            } => {
1139                let v = Expression::evaluate_aggregation_comprehension(
1140                    function,
1141                    variable,
1142                    collection,
1143                    window,
1144                    predicate,
1145                    projection,
1146                    target_unit.as_deref(),
1147                    graph,
1148                )?;
1149                Ok(v)
1150            }
1151            Expression::Cast {
1152                operand,
1153                target_type,
1154            } => {
1155                let val = Self::get_runtime_value(operand, graph)?;
1156                let (value_dec, source_unit) = Self::parse_numeric_with_unit_value(&val)
1157                    .map_err(|e| format!("Invalid cast operand: {}", e))?
1158                    .ok_or_else(|| {
1159                        format!("Cannot cast non-numeric value {} to {}", val, target_type)
1160                    })?;
1161
1162                let registry = get_default_registry();
1163                let registry = registry
1164                    .read()
1165                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
1166                let target_unit = registry
1167                    .get_unit(target_type)
1168                    .map_err(|e| format!("Unknown target unit '{}': {}", target_type, e))?;
1169
1170                let converted_value = if let Some(from_unit_symbol) = source_unit {
1171                    let from_unit = registry
1172                        .get_unit(&from_unit_symbol)
1173                        .map_err(|e| format!("Unknown unit '{}': {}", from_unit_symbol, e))?;
1174                    if from_unit.dimension() != target_unit.dimension() {
1175                        return Err(format!(
1176                            "Cannot cast from '{}' ({:?}) to '{}' ({:?})",
1177                            from_unit_symbol,
1178                            from_unit.dimension(),
1179                            target_type,
1180                            target_unit.dimension()
1181                        ));
1182                    }
1183                    registry
1184                        .convert(value_dec, from_unit, target_unit)
1185                        .map_err(|e| format!("Unit conversion failed: {}", e))?
1186                } else {
1187                    value_dec
1188                };
1189
1190                Ok(serde_json::json!({
1191                    "__quantity_value": converted_value.to_string(),
1192                    "__quantity_unit": target_type
1193                }))
1194            }
1195            Expression::QuantityLiteral { value, unit } => Ok(
1196                serde_json::json!({"__quantity_value": value.to_string(), "__quantity_unit": unit}),
1197            ),
1198            Expression::TimeLiteral(timestamp) => Ok(serde_json::json!(timestamp)),
1199            Expression::IntervalLiteral { start, end } => {
1200                Ok(serde_json::json!({"__interval_start": start, "__interval_end": end}))
1201            }
1202            _ => Err(
1203                "Expected a runtime-resolvable expression (literal, member access, or aggregation)"
1204                    .to_string(),
1205            ),
1206        }
1207    }
1208}
1209
1210impl PolicyModality {
1211    pub fn to_severity(&self) -> Severity {
1212        match self {
1213            Self::Obligation => Severity::Error,
1214            Self::Prohibition => Severity::Error,
1215            Self::Permission => Severity::Info,
1216        }
1217    }
1218}
1219
1220impl EvaluationResult {
1221    pub fn has_errors(&self) -> bool {
1222        self.violations
1223            .iter()
1224            .any(|v| v.severity == Severity::Error)
1225    }
1226
1227    pub fn error_count(&self) -> usize {
1228        self.violations
1229            .iter()
1230            .filter(|v| v.severity == Severity::Error)
1231            .count()
1232    }
1233}