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 chrono
424                    let left_dt = chrono::DateTime::parse_from_rfc3339(&left_str).map_err(|e| {
425                        format!("Failed to parse left timestamp '{}': {}", left_str, e)
426                    })?;
427                    let right_dt =
428                        chrono::DateTime::parse_from_rfc3339(&right_str).map_err(|e| {
429                            format!("Failed to parse right timestamp '{}': {}", right_str, e)
430                        })?;
431
432                    let result = match op {
433                        BinaryOp::Before => left_dt < right_dt,
434                        BinaryOp::After => left_dt > right_dt,
435                        BinaryOp::During => {
436                            return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string())
437                        }
438                        _ => unreachable!(),
439                    };
440                    Ok(result)
441                }
442            },
443            Expression::Unary { op, operand } => {
444                let val = self.evaluate_expression_boolean(operand, graph)?;
445                Ok(match op {
446                    UnaryOp::Not => !val,
447                    UnaryOp::Negate => {
448                        return Err("Negate operator not supported in boolean context".to_string())
449                    }
450                })
451            }
452            Expression::Quantifier { .. } => {
453                Err("Cannot evaluate non-expanded quantifier".to_string())
454            }
455            Expression::MemberAccess { object, member } => {
456                let value = Self::get_runtime_value(expr, graph)?;
457                match value {
458                    serde_json::Value::Bool(v) => Ok(v),
459                    serde_json::Value::Null => Ok(false),
460                    _ => Err(format!(
461                        "Expected boolean value for member '{}.{}', but found {:?}",
462                        object, member, value
463                    )),
464                }
465            }
466            Expression::Aggregation { .. } => {
467                Err("Cannot evaluate non-expanded aggregation".to_string())
468            }
469            Expression::AggregationComprehension { .. } => {
470                Err("Cannot evaluate non-expanded aggregation comprehension".to_string())
471            }
472            Expression::QuantityLiteral { .. } => {
473                Err("Cannot evaluate quantity literal in boolean context".to_string())
474            }
475            Expression::TimeLiteral(_) => {
476                Err("Cannot evaluate time literal in boolean context".to_string())
477            }
478            Expression::IntervalLiteral { .. } => {
479                Err("Cannot evaluate interval literal in boolean context".to_string())
480            }
481            Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
482            Expression::RoleReference { .. } => {
483                Err("Cannot evaluate role reference outside application policy context".to_string())
484            }
485        }
486    }
487
488    fn evaluate_expression_three_valued(
489        &self,
490        expr: &Expression,
491        graph: &Graph,
492    ) -> Result<ThreeValuedBool, String> {
493        use ThreeValuedBool as T;
494
495        match expr {
496            Expression::Literal(v) => Ok(T::from_option_bool(v.as_bool())),
497            Expression::Variable(name) => Err(format!("Cannot evaluate unexpanded variable: {}", name)),
498            Expression::Cast { .. } => {
499                let val = Self::get_runtime_value(expr, graph)?;
500                Ok(T::from_option_bool(val.as_bool()))
501            }
502            Expression::Binary { op, left, right } => match op {
503                BinaryOp::And | BinaryOp::Or => {
504                    let l = self.evaluate_expression_three_valued(left, graph)?;
505                    let r = self.evaluate_expression_three_valued(right, graph)?;
506                    Ok(match op {
507                        BinaryOp::And => l.and(r),
508                        BinaryOp::Or => l.or(r),
509                        _ => unreachable!(),
510                    })
511                }
512                BinaryOp::Equal | BinaryOp::NotEqual => {
513                    let left_val = Self::get_runtime_value(left, graph);
514                    let right_val = Self::get_runtime_value(right, graph);
515                    match (left_val, right_val) {
516                        (Ok(lv), Ok(rv)) => {
517                            // If either operand is JSON Null, the comparison yields Null.
518                            if lv.is_null() || rv.is_null() {
519                                Ok(T::Null)
520                            } else {
521                                let numeric_eq = match (
522                                    Self::parse_numeric_with_unit_value(&lv),
523                                    Self::parse_numeric_with_unit_value(&rv),
524                                ) {
525                                    (Ok(ln), Ok(rn)) => {
526                                        self.normalize_units_nullable(ln, rn)?
527                                            .map(|(l, r)| l == r)
528                                    }
529                                    _ => None,
530                                };
531
532                                let equality = if let Some(eq) = numeric_eq {
533                                    Some(eq)
534                                } else if lv.is_number() || rv.is_number() {
535                                    None
536                                } else {
537                                    Some(lv == rv)
538                                };
539
540                                let eq = match (op, equality) {
541                                    (_, None) => return Ok(T::Null),
542                                    (BinaryOp::Equal, Some(true)) => true,
543                                    (BinaryOp::Equal, Some(false)) => false,
544                                    (BinaryOp::NotEqual, Some(true)) => false,
545                                    (BinaryOp::NotEqual, Some(false)) => true,
546                                    _ => unreachable!(),
547                                };
548
549                                Ok(T::from_option_bool(Some(eq)))
550                            }
551                        }
552                        _ => Ok(T::Null),
553                    }
554                }
555                BinaryOp::GreaterThan
556                | BinaryOp::LessThan
557                | BinaryOp::GreaterThanOrEqual
558                | BinaryOp::LessThanOrEqual => {
559                    let left_v = Self::get_runtime_value(left, graph);
560                    let right_v = Self::get_runtime_value(right, graph);
561                    match (left_v, right_v) {
562                        (Ok(lv), Ok(rv)) => {
563                            if lv.is_null() || rv.is_null() {
564                                Ok(T::Null)
565                            } else {
566                                let numeric = self
567                                    .normalize_units_nullable(
568                                        Self::parse_numeric_with_unit_value(&lv)
569                                            .ok()
570                                            .flatten(),
571                                        Self::parse_numeric_with_unit_value(&rv)
572                                            .ok()
573                                            .flatten(),
574                                    )?
575                                    .map(|(l, r)| match op {
576                                        BinaryOp::GreaterThan => l > r,
577                                        BinaryOp::LessThan => l < r,
578                                        BinaryOp::GreaterThanOrEqual => l >= r,
579                                        BinaryOp::LessThanOrEqual => l <= r,
580                                        _ => unreachable!(),
581                                    });
582
583                                Ok(T::from_option_bool(numeric))
584                            }
585                        }
586                        _ => Ok(T::Null),
587                    }
588                }
589                BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
590                    Err("Arithmetic operations not supported in boolean context".to_string())
591                }
592                BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
593                    let left_v = Self::get_runtime_value(left, graph);
594                    let right_v = Self::get_runtime_value(right, graph);
595                    match (left_v, right_v) {
596                        (Ok(lv), Ok(rv)) => {
597                            if lv.is_null() || rv.is_null() {
598                                Ok(T::Null)
599                            } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
600                                let ok = match op {
601                                    BinaryOp::Contains => ls.contains(rs),
602                                    BinaryOp::StartsWith => ls.starts_with(rs),
603                                    BinaryOp::EndsWith => ls.ends_with(rs),
604                                    _ => unreachable!(),
605                                };
606                                Ok(T::from_option_bool(Some(ok)))
607                            } else {
608                                Ok(T::Null)
609                            }
610                        }
611                        _ => Ok(T::Null),
612                    }
613                }
614                BinaryOp::HasRole => {
615                    let role_check = self.evaluate_has_role(left, right, graph)?;
616                    Ok(T::from_option_bool(Some(role_check)))
617                }
618                BinaryOp::Matches => {
619                    let left_v = Self::get_runtime_value(left, graph);
620                    let right_v = Self::get_runtime_value(right, graph);
621
622                    match (left_v, right_v) {
623                        (Ok(lv), Ok(rv)) => {
624                            if lv.is_null() || rv.is_null() {
625                                return Ok(T::Null);
626                            }
627
628                            if let (Some(candidate), Some(pattern_name)) = (lv.as_str(), rv.as_str()) {
629                                let pattern = graph
630                                    .find_pattern(pattern_name, Some(&self.namespace))
631                                    .ok_or_else(|| {
632                                        format!(
633                                            "Pattern '{}' not found in namespace '{}'",
634                                            pattern_name, self.namespace
635                                        )
636                                    })?;
637                                let is_match = pattern.is_match(candidate).map_err(|e| {
638                                    format!(
639                                        "Pattern '{}' failed to evaluate: {}",
640                                        pattern_name, e
641                                    )
642                                })?;
643                                Ok(T::from_option_bool(Some(is_match)))
644                            } else {
645                                Ok(T::Null)
646                            }
647                        }
648                        _ => Ok(T::Null),
649                    }
650                }
651                BinaryOp::Before | BinaryOp::After | BinaryOp::During => {
652                    // Temporal operators
653                    if matches!(op, BinaryOp::During) {
654                        return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string());
655                    }
656
657                    // Parse and compare ISO 8601 timestamps
658                    let left_v = Self::get_runtime_value(left, graph);
659                    let right_v = Self::get_runtime_value(right, graph);
660                    match (left_v, right_v) {
661                        (Ok(lv), Ok(rv)) => {
662                            if lv.is_null() || rv.is_null() {
663                                Ok(T::Null)
664                            } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
665                                // Parse timestamps using chrono
666                                let left_dt = match chrono::DateTime::parse_from_rfc3339(ls) {
667                                    Ok(dt) => dt,
668                                    Err(_) => return Ok(T::Null), // Invalid timestamp -> Null
669                                };
670                                let right_dt = match chrono::DateTime::parse_from_rfc3339(rs) {
671                                    Ok(dt) => dt,
672                                    Err(_) => return Ok(T::Null), // Invalid timestamp -> Null
673                                };
674
675                                let result = match op {
676                                    BinaryOp::Before => left_dt < right_dt,
677                                    BinaryOp::After => left_dt > right_dt,
678                                    _ => unreachable!(),
679                                };
680                                Ok(T::from_option_bool(Some(result)))
681                            } else {
682                                Ok(T::Null)
683                            }
684                        }
685                        _ => Ok(T::Null),
686                    }
687                }
688            },
689            Expression::Unary { op, operand } => {
690                let v = self.evaluate_expression_three_valued(operand, graph)?;
691                Ok(match op {
692                    UnaryOp::Not => v.not(),
693                    UnaryOp::Negate => return Err("Negate operator not supported in boolean context".to_string()),
694                })
695            }
696            Expression::Quantifier { quantifier, variable, collection, condition } => {
697                // Evaluate quantifiers with three-valued semantics
698                let items = Expression::get_collection(collection, graph)?;
699                use super::expression::Quantifier as Q;
700
701                let mut saw_true = 0usize;
702                let mut saw_false = 0usize;
703                let mut saw_null = 0usize;
704
705                for item in items {
706                    let substituted = condition.substitute(variable, &item)?;
707                    let val = self.evaluate_expression_three_valued(&substituted, graph)?;
708                    match val {
709                        T::True => saw_true += 1,
710                        T::False => saw_false += 1,
711                        T::Null => saw_null += 1,
712                    }
713                }
714
715                match quantifier {
716                    Q::ForAll => {
717                        if saw_false > 0 { return Ok(T::False); }
718                        if saw_null > 0 { return Ok(T::Null); }
719                        Ok(T::True)
720                    }
721                    Q::Exists => {
722                        if saw_true > 0 { return Ok(T::True); }
723                        if saw_null > 0 { return Ok(T::Null); }
724                        Ok(T::False)
725                    }
726                    Q::ExistsUnique => {
727                        if saw_true > 1 { return Ok(T::False); }
728                        if saw_true == 1 && saw_null == 0 { return Ok(T::True); }
729                        if saw_true == 1 && saw_null > 0 { return Ok(T::Null); }
730                        if saw_true == 0 && saw_null > 0 { return Ok(T::Null); }
731                        Ok(T::False)
732                    }
733                }
734            }
735            Expression::MemberAccess { object: _, member: _ } => {
736                // Resolve object/member to a runtime value and convert to bool
737                let value = Self::get_runtime_value(expr, graph)?;
738                Ok(T::from_option_bool(value.as_bool()))
739            }
740            Expression::Aggregation { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
741            Expression::AggregationComprehension { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
742            Expression::QuantityLiteral { .. } => Err("Cannot convert quantity to boolean; compare against a threshold instead".to_string()),
743            Expression::TimeLiteral(_) => Err("Cannot convert time to boolean; use temporal comparison operators".to_string()),
744            Expression::IntervalLiteral { .. } => Err("Cannot convert interval to boolean; use temporal comparison operators".to_string()),
745            Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
746            Expression::RoleReference { .. } => Err(
747                "Cannot evaluate role reference outside application policy context".to_string(),
748            ),
749        }
750    }
751
752    fn compare_values<F>(
753        &self,
754        left: &Expression,
755        right: &Expression,
756        graph: &Graph,
757        op: F,
758    ) -> Result<bool, String>
759    where
760        F: Fn(&serde_json::Value, &serde_json::Value) -> bool,
761    {
762        let left_val = self
763            .get_literal_value(left)
764            .or_else(|_| Self::get_runtime_value(left, graph))?;
765        let right_val = self
766            .get_literal_value(right)
767            .or_else(|_| Self::get_runtime_value(right, graph))?;
768        Ok(op(&left_val, &right_val))
769    }
770
771    fn compare_numeric<F>(
772        &self,
773        left: &Expression,
774        right: &Expression,
775        graph: &Graph,
776        op: F,
777    ) -> Result<bool, String>
778    where
779        F: Fn(Decimal, Decimal) -> bool,
780    {
781        let left_val = self.resolve_numeric_with_unit(left, graph)?;
782        let right_val = self.resolve_numeric_with_unit(right, graph)?;
783        let (left_aligned, right_aligned) = self.normalize_units_strict(left_val, right_val)?;
784        Ok(op(left_aligned, right_aligned))
785    }
786
787    fn compare_strings<F>(
788        &self,
789        left: &Expression,
790        right: &Expression,
791        graph: &Graph,
792        op: F,
793    ) -> Result<bool, String>
794    where
795        F: Fn(&str, &str) -> bool,
796    {
797        let left_val = self.get_string_value(left, graph)?;
798        let right_val = self.get_string_value(right, graph)?;
799        Ok(op(&left_val, &right_val))
800    }
801
802    fn evaluate_pattern_match(
803        &self,
804        left: &Expression,
805        right: &Expression,
806        graph: &Graph,
807    ) -> Result<bool, String> {
808        let candidate = self.get_string_value(left, graph)?;
809        let pattern_name = self.get_string_value(right, graph)?;
810
811        let pattern = graph
812            .find_pattern(&pattern_name, Some(&self.namespace))
813            .ok_or_else(|| {
814                format!(
815                    "Pattern '{}' not found in namespace '{}'",
816                    pattern_name, self.namespace
817                )
818            })?;
819
820        pattern
821            .is_match(&candidate)
822            .map_err(|e| format!("Pattern '{}' failed to evaluate: {}", pattern_name, e))
823    }
824
825    fn evaluate_has_role(
826        &self,
827        left: &Expression,
828        right: &Expression,
829        graph: &Graph,
830    ) -> Result<bool, String> {
831        let target_role = self.get_string_value(right, graph)?;
832        let roles = self.collect_roles(left, graph)?;
833
834        Ok(roles
835            .iter()
836            .any(|role| role.eq_ignore_ascii_case(&target_role)))
837    }
838
839    fn collect_roles(&self, expr: &Expression, graph: &Graph) -> Result<Vec<String>, String> {
840        let value = Self::get_runtime_value(expr, graph)?;
841
842        if let Some(arr) = value.as_array() {
843            return Ok(arr
844                .iter()
845                .filter_map(|v| v.as_str().map(|s| s.to_string()))
846                .collect());
847        }
848
849        if let Some(obj) = value.as_object() {
850            if let Some(roles) = obj.get("roles").and_then(|r| r.as_array()) {
851                return Ok(roles
852                    .iter()
853                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
854                    .collect());
855            }
856
857            if let Some(name) = obj.get("name").and_then(|v| v.as_str()) {
858                if let Some(entity_id) = graph.find_entity_by_name(name) {
859                    return Ok(graph.role_names_for_entity(&entity_id));
860                }
861            }
862        }
863
864        if let Some(name) = value.as_str() {
865            if let Some(entity_id) = graph.find_entity_by_name(name) {
866                return Ok(graph.role_names_for_entity(&entity_id));
867            }
868
869            if let Some(role_id) = graph.find_role_by_name(name) {
870                if let Some(role) = graph.get_role(&role_id) {
871                    return Ok(vec![role.name().to_string()]);
872                }
873            }
874        }
875
876        Ok(Vec::new())
877    }
878
879    fn get_literal_value(&self, expr: &Expression) -> Result<serde_json::Value, String> {
880        match expr {
881            Expression::Literal(v) => Ok(v.clone()),
882            _ => Err("Expected literal value".to_string()),
883        }
884    }
885
886    fn parse_decimal_value(value: &serde_json::Value) -> Result<Decimal, String> {
887        if let Some(s) = value.as_str() {
888            Decimal::from_str(s).map_err(|e| e.to_string())
889        } else if let Some(f) = value.as_f64() {
890            Decimal::from_f64(f).ok_or_else(|| format!("Unable to represent {} as Decimal", f))
891        } else if let Some(i) = value.as_i64() {
892            Ok(Decimal::from(i))
893        } else if let Some(u) = value.as_u64() {
894            Decimal::from_u64(u).ok_or_else(|| format!("Unable to represent {} as Decimal", u))
895        } else {
896            Err(format!("Expected numeric value, got: {}", value))
897        }
898    }
899
900    fn parse_numeric_with_unit_value(
901        value: &serde_json::Value,
902    ) -> Result<Option<(Decimal, Option<String>)>, String> {
903        if let Some(obj) = value.as_object() {
904            match (obj.get("__quantity_value"), obj.get("__quantity_unit")) {
905                (Some(q_val), Some(q_unit)) => {
906                    let unit_str = q_unit
907                        .as_str()
908                        .ok_or_else(|| {
909                            format!("Expected __quantity_unit to be string, got: {}", q_unit)
910                        })?
911                        .to_string();
912                    let value_dec = Self::parse_decimal_value(q_val)
913                        .map_err(|e| format!("Invalid __quantity_value: {}", e))?;
914                    return Ok(Some((value_dec, Some(unit_str))));
915                }
916                (Some(_), None) | (None, Some(_)) => {
917                    return Err(
918                        "Quantity object must include both __quantity_value and __quantity_unit"
919                            .to_string(),
920                    )
921                }
922                _ => {}
923            }
924        }
925
926        if value.is_number() || value.is_string() {
927            return Ok(Some((Self::parse_decimal_value(value)?, None)));
928        }
929
930        Ok(None)
931    }
932
933    fn resolve_numeric_with_unit(
934        &self,
935        expr: &Expression,
936        graph: &Graph,
937    ) -> Result<(Decimal, Option<String>), String> {
938        let value = self
939            .get_literal_value(expr)
940            .or_else(|_| Self::get_runtime_value(expr, graph))?;
941        Self::parse_numeric_with_unit_value(&value)?
942            .ok_or_else(|| format!("Expected numeric value, got: {}", value))
943    }
944
945    fn normalize_units_strict(
946        &self,
947        left: (Decimal, Option<String>),
948        right: (Decimal, Option<String>),
949    ) -> Result<(Decimal, Decimal), String> {
950        match (left.1, right.1) {
951            (Some(l_unit), Some(r_unit)) => {
952                let registry = get_default_registry();
953                let registry = registry
954                    .read()
955                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
956
957                if l_unit == r_unit {
958                    Ok((left.0, right.0))
959                } else {
960                    let from = registry
961                        .get_unit(&r_unit)
962                        .map_err(|e| format!("Invalid unit '{}': {}", r_unit, e))?;
963                    let to = registry
964                        .get_unit(&l_unit)
965                        .map_err(|e| format!("Invalid unit '{}': {}", l_unit, e))?;
966                    let converted = registry
967                        .convert(right.0, from, to)
968                        .map_err(|e| format!("Unit conversion failed: {}", e))?;
969                    Ok((left.0, converted))
970                }
971            }
972            (None, None) => Ok((left.0, right.0)),
973            (Some(l_unit), None) => Err(format!(
974                "Cannot compare quantity with unit '{}' to unitless value",
975                l_unit
976            )),
977            (None, Some(r_unit)) => Err(format!(
978                "Cannot compare unitless value to quantity with unit '{}'",
979                r_unit
980            )),
981        }
982    }
983
984    fn normalize_units_nullable(
985        &self,
986        left: Option<(Decimal, Option<String>)>,
987        right: Option<(Decimal, Option<String>)>,
988    ) -> Result<Option<(Decimal, Decimal)>, String> {
989        let (left, right) = match (left, right) {
990            (Some(l), Some(r)) => (l, r),
991            _ => return Ok(None),
992        };
993
994        match (left.1.clone(), right.1.clone()) {
995            (Some(l_unit), Some(r_unit)) => {
996                let registry = get_default_registry();
997                let registry = registry
998                    .read()
999                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
1000                if l_unit == r_unit {
1001                    Ok(Some((left.0, right.0)))
1002                } else {
1003                    let from = registry.get_unit(&r_unit);
1004                    let to = registry.get_unit(&l_unit);
1005                    if let (Ok(from), Ok(to)) = (from, to) {
1006                        match registry.convert(right.0, from, to) {
1007                            Ok(converted) => Ok(Some((left.0, converted))),
1008                            Err(_) => Ok(None),
1009                        }
1010                    } else {
1011                        Ok(None)
1012                    }
1013                }
1014            }
1015            (None, None) => Ok(Some((left.0, right.0))),
1016            _ => Ok(None),
1017        }
1018    }
1019
1020    fn get_string_value(&self, expr: &Expression, graph: &Graph) -> Result<String, String> {
1021        let v = self
1022            .get_literal_value(expr)
1023            .or_else(|_| Self::get_runtime_value(expr, graph))?;
1024        v.as_str()
1025            .map(|s| s.to_string())
1026            .ok_or_else(|| "Expected string value".to_string())
1027    }
1028
1029    fn get_runtime_value(expr: &Expression, graph: &Graph) -> Result<serde_json::Value, String> {
1030        match expr {
1031            Expression::Literal(v) => Ok(v.clone()),
1032            Expression::MemberAccess { object, member } => {
1033                // Try resolving as entity
1034                if let Some(id) = graph.find_entity_by_name(object) {
1035                    if let Some(entity) = graph.get_entity(&id) {
1036                        // Special known members
1037                        if member == "id" {
1038                            return Ok(serde_json::json!(entity.id().to_string()));
1039                        } else if member == "name" {
1040                            return Ok(serde_json::json!(entity.name()));
1041                        } else if member == "namespace" {
1042                            return Ok(serde_json::json!(entity.namespace()));
1043                        }
1044                        if let Some(val) = entity.get_attribute(member) {
1045                            if val.is_null() {
1046                                log::debug!(
1047                                    "Entity '{}' member '{}' present but NULL; returning Null",
1048                                    object,
1049                                    member
1050                                );
1051                            }
1052                            return Ok(val.clone());
1053                        }
1054                        log::debug!(
1055                            "Entity '{}' found but member '{}' missing; returning Null",
1056                            object,
1057                            member
1058                        );
1059                        return Ok(serde_json::Value::Null);
1060                    } else {
1061                        log::debug!(
1062                            "Entity lookup for '{}' returned id {} but entity missing; returning Null",
1063                            object, id
1064                        );
1065                    }
1066                } else {
1067                    log::debug!(
1068                        "Entity '{}' not found while resolving member '{}'; continuing lookup",
1069                        object,
1070                        member
1071                    );
1072                }
1073
1074                if let Some(id) = graph.find_resource_by_name(object) {
1075                    if let Some(resource) = graph.get_resource(&id) {
1076                        if member == "id" {
1077                            return Ok(serde_json::json!(resource.id().to_string()));
1078                        } else if member == "name" {
1079                            return Ok(serde_json::json!(resource.name()));
1080                        } else if member == "unit" {
1081                            return Ok(serde_json::json!(resource.unit()));
1082                        }
1083                        if let Some(val) = resource.get_attribute(member) {
1084                            if val.is_null() {
1085                                log::debug!(
1086                                    "Resource '{}' member '{}' present but NULL; returning Null",
1087                                    object,
1088                                    member
1089                                );
1090                            }
1091                            return Ok(val.clone());
1092                        }
1093                        log::debug!(
1094                            "Resource '{}' found but member '{}' missing; returning Null",
1095                            object,
1096                            member
1097                        );
1098                        return Ok(serde_json::Value::Null);
1099                    } else {
1100                        log::debug!(
1101                            "Resource lookup for '{}' returned id {} but resource missing; returning Null",
1102                            object, id
1103                        );
1104                    }
1105                } else {
1106                    log::debug!(
1107                        "Resource '{}' not found while resolving member '{}'; returning Null",
1108                        object,
1109                        member
1110                    );
1111                }
1112
1113                // Not found: return Null to indicate unknown member
1114                log::debug!(
1115                    "Member access '{}.{}' did not resolve to entity or resource; returning Null",
1116                    object,
1117                    member
1118                );
1119                Ok(serde_json::Value::Null)
1120            }
1121            Expression::Aggregation {
1122                function,
1123                collection,
1124                field,
1125                filter,
1126            } => {
1127                let v =
1128                    Expression::evaluate_aggregation(function, collection, field, filter, graph)?;
1129                Ok(v)
1130            }
1131            Expression::AggregationComprehension {
1132                function,
1133                variable,
1134                collection,
1135                window,
1136                predicate,
1137                projection,
1138                target_unit,
1139            } => {
1140                let v = Expression::evaluate_aggregation_comprehension(
1141                    function,
1142                    variable,
1143                    collection,
1144                    window,
1145                    predicate,
1146                    projection,
1147                    target_unit.as_deref(),
1148                    graph,
1149                )?;
1150                Ok(v)
1151            }
1152            Expression::Cast {
1153                operand,
1154                target_type,
1155            } => {
1156                let val = Self::get_runtime_value(operand, graph)?;
1157                let (value_dec, source_unit) = Self::parse_numeric_with_unit_value(&val)
1158                    .map_err(|e| format!("Invalid cast operand: {}", e))?
1159                    .ok_or_else(|| {
1160                        format!("Cannot cast non-numeric value {} to {}", val, target_type)
1161                    })?;
1162
1163                let registry = get_default_registry();
1164                let registry = registry
1165                    .read()
1166                    .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
1167                let target_unit = registry
1168                    .get_unit(target_type)
1169                    .map_err(|e| format!("Unknown target unit '{}': {}", target_type, e))?;
1170
1171                let converted_value = if let Some(from_unit_symbol) = source_unit {
1172                    let from_unit = registry
1173                        .get_unit(&from_unit_symbol)
1174                        .map_err(|e| format!("Unknown unit '{}': {}", from_unit_symbol, e))?;
1175                    if from_unit.dimension() != target_unit.dimension() {
1176                        return Err(format!(
1177                            "Cannot cast from '{}' ({:?}) to '{}' ({:?})",
1178                            from_unit_symbol,
1179                            from_unit.dimension(),
1180                            target_type,
1181                            target_unit.dimension()
1182                        ));
1183                    }
1184                    registry
1185                        .convert(value_dec, from_unit, target_unit)
1186                        .map_err(|e| format!("Unit conversion failed: {}", e))?
1187                } else {
1188                    value_dec
1189                };
1190
1191                Ok(serde_json::json!({
1192                    "__quantity_value": converted_value.to_string(),
1193                    "__quantity_unit": target_type
1194                }))
1195            }
1196            Expression::QuantityLiteral { value, unit } => Ok(
1197                serde_json::json!({"__quantity_value": value.to_string(), "__quantity_unit": unit}),
1198            ),
1199            Expression::TimeLiteral(timestamp) => Ok(serde_json::json!(timestamp)),
1200            Expression::IntervalLiteral { start, end } => {
1201                Ok(serde_json::json!({"__interval_start": start, "__interval_end": end}))
1202            }
1203            _ => Err(
1204                "Expected a runtime-resolvable expression (literal, member access, or aggregation)"
1205                    .to_string(),
1206            ),
1207        }
1208    }
1209}
1210
1211impl PolicyModality {
1212    pub fn to_severity(&self) -> Severity {
1213        match self {
1214            Self::Obligation => Severity::Error,
1215            Self::Prohibition => Severity::Error,
1216            Self::Permission => Severity::Info,
1217        }
1218    }
1219}
1220
1221impl EvaluationResult {
1222    pub fn has_errors(&self) -> bool {
1223        self.violations
1224            .iter()
1225            .any(|v| v.severity == Severity::Error)
1226    }
1227
1228    pub fn error_count(&self) -> usize {
1229        self.violations
1230            .iter()
1231            .filter(|v| v.severity == Severity::Error)
1232            .count()
1233    }
1234}