Skip to main content

qualia_core_db/modalities/logic/shacl/
validate.rs

1//! Comprehensive graph-level SHACL validation.
2//!
3//! [`ShaclCompiler`](super::shacl_compiler) lowers a shape to `SlgOpcode`s for the
4//! firewall (LLM-rule gating). This module is the complementary **data validator**:
5//! it interprets the full [`ShaclConstraint`]
6//! vocabulary against a graph of [`NQuin`]s and produces a real
7//! [`ValidationReport`] — the path a "validate this data against this shape"
8//! request (e.g. the docs playground, ingestion-time conformance) actually takes.
9//!
10//! ## Values are hashes — string constraints need a resolver
11//!
12//! Quin object fields hold either an **inline-typed literal** (numeric/boolean,
13//! decodable here via `frame_layout()`) or the **`q_hash` of a lexical value**
14//! (IRIs and strings — one-way). Numeric/cardinality/value-type/structural
15//! constraints are therefore fully enforceable on the bare graph. String-shaped
16//! constraints (`sh:pattern`, `sh:minLength`/`maxLength`, `sh:languageIn`,
17//! `sh:uniqueLang`) need the original lexical form, so the caller supplies a
18//! `resolve: hash -> Option<String>`. When a value cannot be resolved, a
19//! string-shaped constraint reports a `Violation` (the value cannot be shown to
20//! conform) rather than silently passing — fail closed.
21//!
22//! Cold path: `ValidationReport` is `Vec`-backed (allocation is expected here, as
23//! in the existing `sparql_shacl` validator); the zero-heap invariant covers the
24//! hot path, not shape validation.
25
26use super::shacl_types::{
27    CompiledShape, NodeKindType, PropertyPath, ShaclConstraint, ShaclSeverity, ValidationReport,
28    ValidationResult,
29};
30use crate::frame_layout::{
31    object_tag, unpack_float_object, INLINE_TAG_BOOLEAN, INLINE_TAG_DECIMAL, INLINE_TAG_FLOAT,
32    INLINE_TAG_INTEGER, INLINE_VALUE_MASK, MSB_FLAG,
33};
34use crate::{q_hash, NQuin};
35
36/// A lexical-value resolver: maps a value hash back to its original string when
37/// available (used only by string-shaped constraints).
38pub type Resolver<'r> = &'r dyn Fn(u64) -> Option<String>;
39
40/// Decode an inline-typed object field to an `f64`, or `None` if the object is a
41/// pointer / IRI hash / un-typed (i.e. not a comparable number).
42pub fn object_as_f64(object: u64) -> Option<f64> {
43    if object & MSB_FLAG != 0 {
44        return None; // topological pointer, not a literal
45    }
46    match object_tag(object) {
47        INLINE_TAG_FLOAT => Some(unpack_float_object(object) as f64),
48        INLINE_TAG_INTEGER => {
49            let mut n = (object & INLINE_VALUE_MASK) as i64;
50            if n & (1i64 << 59) != 0 {
51                n |= !((1i64 << 60) - 1); // sign-extend 60-bit two's complement
52            }
53            Some(n as f64)
54        }
55        INLINE_TAG_DECIMAL => {
56            let mut raw = (object & INLINE_VALUE_MASK) as i64;
57            if raw & (1i64 << 59) != 0 {
58                raw |= !((1i64 << 60) - 1);
59            }
60            Some(raw as f64 / 1_000_000.0) // fixed-point ×10⁶
61        }
62        INLINE_TAG_BOOLEAN => Some(if object & 1 != 0 { 1.0 } else { 0.0 }),
63        _ => None,
64    }
65}
66
67/// The SHACL node kind of an object value (0=BlankNode, 1=IRI, 2=Literal).
68fn node_kind_of(object: u64) -> u8 {
69    if object & MSB_FLAG != 0 {
70        1 // did:q42 topological pointer — an IRI
71    } else if object_tag(object) != 0 {
72        2 // inline-typed literal
73    } else {
74        1 // plain IRI hash
75    }
76}
77
78/// Test an object against a `sh:NodeKind` requirement using the
79/// `node_kind_of` classification (0=blank, 1=IRI/`did:q42` pointer,
80/// 2=inline-typed literal).
81fn node_kind_matches(object: u64, want: NodeKindType) -> bool {
82    let k = node_kind_of(object); // 0=blank,1=iri,2=literal
83    match want {
84        NodeKindType::BlankNode => k == 0,
85        NodeKindType::Iri => k == 1,
86        NodeKindType::Literal => k == 2,
87        NodeKindType::BlankNodeOrIri => k == 0 || k == 1,
88        NodeKindType::BlankNodeOrLiteral => k == 0 || k == 2,
89        NodeKindType::IriOrLiteral => k == 1 || k == 2,
90    }
91}
92
93/// `sh:datatype` IRI → inline tag.
94fn datatype_tag(dt: &str) -> Option<u64> {
95    let h = q_hash(dt);
96    if h == q_hash("xsd:string") {
97        Some(0)
98    } else if h == q_hash("xsd:integer") {
99        Some(INLINE_TAG_INTEGER)
100    } else if h == q_hash("xsd:decimal") {
101        Some(INLINE_TAG_DECIMAL)
102    } else if h == q_hash("xsd:float") || h == q_hash("xsd:double") {
103        Some(INLINE_TAG_FLOAT)
104    } else if h == q_hash("xsd:boolean") {
105        Some(INLINE_TAG_BOOLEAN)
106    } else {
107        None
108    }
109}
110
111/// A readable label for a node: the resolved lexical value, else the decoded
112/// inline numeric/boolean value, else a hash tag.
113fn label(node: u64, resolve: Resolver) -> String {
114    if let Some(s) = resolve(node) {
115        return s;
116    }
117    if node & MSB_FLAG == 0 {
118        match object_tag(node) {
119            INLINE_TAG_BOOLEAN => return (node & 1 != 0).to_string(),
120            INLINE_TAG_FLOAT | INLINE_TAG_INTEGER | INLINE_TAG_DECIMAL => {
121                if let Some(n) = object_as_f64(node) {
122                    return if n.fract() == 0.0 && n.abs() < 1e15 {
123                        (n as i64).to_string()
124                    } else {
125                        n.to_string()
126                    };
127                }
128            }
129            _ => {}
130        }
131    }
132    format!("node:{node:016x}")
133}
134
135const RDF_TYPE_KEYS: [&str; 2] = ["rdf:type", "a"];
136
137/// Engine binding shapes + graph for a validation pass.
138pub struct ShaclEngine<'a> {
139    pub quins: &'a [NQuin],
140    /// Registry used to resolve `sh:node` / `and` / `or` / `not` / `xone` references
141    /// (referenced shapes are looked up by their `shape_class`).
142    pub shapes: &'a [CompiledShape],
143}
144
145impl<'a> ShaclEngine<'a> {
146    /// Bind the quin graph and compiled shapes for one validation pass —
147    /// borrows only, no allocation.
148    pub fn new(quins: &'a [NQuin], shapes: &'a [CompiledShape]) -> Self {
149        Self { quins, shapes }
150    }
151
152    /// Validate every shape against its target nodes.
153    pub fn validate(&self, resolve: Resolver) -> ValidationReport {
154        let mut results = Vec::new();
155        for shape in self.shapes {
156            for focus in self.target_nodes(shape) {
157                self.validate_focus(focus, shape, resolve, &mut results);
158            }
159        }
160        ValidationReport {
161            conforms: !results
162                .iter()
163                .any(|r| r.severity == ShaclSeverity::Violation),
164            results,
165        }
166    }
167
168    /// Validate a single focus node against one shape.
169    pub fn validate_focus(
170        &self,
171        focus: u64,
172        shape: &CompiledShape,
173        resolve: Resolver,
174        out: &mut Vec<ValidationResult>,
175    ) {
176        let path_set = !shape.property_path.is_empty();
177        let values: Vec<u64> = if path_set {
178            self.values_at(focus, &shape.property_path)
179        } else {
180            vec![focus]
181        };
182        let path = if path_set {
183            Some(shape.property_path.clone())
184        } else {
185            None
186        };
187        for c in &shape.constraints {
188            self.check(focus, &path, &values, c, shape.severity, resolve, out);
189        }
190    }
191
192    /// Objects of `(focus, <path>)`.
193    fn values_at(&self, focus: u64, path: &str) -> Vec<u64> {
194        let p = q_hash(path);
195        self.quins
196            .iter()
197            .filter(|q| q.subject == focus && q.predicate == p)
198            .map(|q| q.object)
199            .collect()
200    }
201
202    /// Whether `node` is an `rdf:type` instance of `class_hash`.
203    fn is_a(&self, node: u64, class_hash: u64) -> bool {
204        let type_keys = RDF_TYPE_KEYS.map(q_hash);
205        self.quins.iter().any(|q| {
206            q.subject == node && type_keys.contains(&q.predicate) && q.object == class_hash
207        })
208    }
209
210    /// Look up a referenced shape by its `shape_class` name.
211    fn shape_named(&self, name: &str) -> Option<&CompiledShape> {
212        let h = q_hash(name);
213        self.shapes.iter().find(|s| q_hash(&s.shape_class) == h)
214    }
215
216    /// `true` if `focus` conforms to the named shape (no Violations).
217    fn focus_conforms(&self, focus: u64, name: &str, resolve: Resolver) -> bool {
218        match self.shape_named(name) {
219            Some(s) => {
220                let mut tmp = Vec::new();
221                self.validate_focus(focus, s, resolve, &mut tmp);
222                !tmp.iter().any(|r| r.severity == ShaclSeverity::Violation)
223            }
224            // An unresolved shape reference cannot be shown to hold → fail closed.
225            None => false,
226        }
227    }
228
229    /// Evaluate one constraint against a focus node's `values`,
230    /// appending a `ValidationResult` per violation with the SHACL
231    /// component name. Non-numeric/missing values fail closed — a value
232    /// that can't be checked is a violation, not a skip.
233    #[allow(clippy::too_many_arguments)]
234    fn check(
235        &self,
236        focus: u64,
237        path: &Option<String>,
238        values: &[u64],
239        c: &ShaclConstraint,
240        severity: ShaclSeverity,
241        resolve: Resolver,
242        out: &mut Vec<ValidationResult>,
243    ) {
244        let mut violate = |component: &str, value: Option<u64>, msg: String| {
245            out.push(ValidationResult {
246                severity,
247                focus_node: label(focus, resolve),
248                result_path: path.clone(),
249                message: Some(msg),
250                source_constraint: None,
251                source_constraint_component: Some(component.to_string()),
252                value: value.map(|v| label(v, resolve)),
253            });
254        };
255
256        match c {
257            // ── value range (numeric) ──────────────────────────────────────────
258            ShaclConstraint::MinInclusive(m) => {
259                for &v in values {
260                    match object_as_f64(v) {
261                        Some(x) if x >= *m => {}
262                        _ => violate(
263                            "sh:MinInclusiveConstraintComponent",
264                            Some(v),
265                            format!("value < minInclusive {m} (or not numeric)"),
266                        ),
267                    }
268                }
269            }
270            ShaclConstraint::MaxInclusive(m) => {
271                for &v in values {
272                    match object_as_f64(v) {
273                        Some(x) if x <= *m => {}
274                        _ => violate(
275                            "sh:MaxInclusiveConstraintComponent",
276                            Some(v),
277                            format!("value > maxInclusive {m} (or not numeric)"),
278                        ),
279                    }
280                }
281            }
282            ShaclConstraint::MinExclusive(m) => {
283                for &v in values {
284                    match object_as_f64(v) {
285                        Some(x) if x > *m => {}
286                        _ => violate(
287                            "sh:MinExclusiveConstraintComponent",
288                            Some(v),
289                            format!("value <= minExclusive {m} (or not numeric)"),
290                        ),
291                    }
292                }
293            }
294            ShaclConstraint::MaxExclusive(m) => {
295                for &v in values {
296                    match object_as_f64(v) {
297                        Some(x) if x < *m => {}
298                        _ => violate(
299                            "sh:MaxExclusiveConstraintComponent",
300                            Some(v),
301                            format!("value >= maxExclusive {m} (or not numeric)"),
302                        ),
303                    }
304                }
305            }
306            ShaclConstraint::DatatypeRange {
307                min_inclusive,
308                max_inclusive,
309                min_exclusive,
310                max_exclusive,
311            } => {
312                for &v in values {
313                    let x = object_as_f64(v);
314                    let ok = match x {
315                        Some(x) => {
316                            min_inclusive.map_or(true, |b| x >= b)
317                                && max_inclusive.map_or(true, |b| x <= b)
318                                && min_exclusive.map_or(true, |b| x > b)
319                                && max_exclusive.map_or(true, |b| x < b)
320                        }
321                        None => false,
322                    };
323                    if !ok {
324                        violate(
325                            "sh:DatatypeRange",
326                            Some(v),
327                            "value outside datatype range".into(),
328                        );
329                    }
330                }
331            }
332
333            // ── cardinality ────────────────────────────────────────────────────
334            ShaclConstraint::MinCount(n) => {
335                if (values.len() as u32) < *n {
336                    violate(
337                        "sh:MinCountConstraintComponent",
338                        None,
339                        format!("{} value(s) < minCount {n}", values.len()),
340                    );
341                }
342            }
343            ShaclConstraint::MaxCount(n) => {
344                if (values.len() as u32) > *n {
345                    violate(
346                        "sh:MaxCountConstraintComponent",
347                        None,
348                        format!("{} value(s) > maxCount {n}", values.len()),
349                    );
350                }
351            }
352
353            // ── value type ─────────────────────────────────────────────────────
354            ShaclConstraint::Class(class) => {
355                let ch = q_hash(class);
356                for &v in values {
357                    if !self.is_a(v, ch) {
358                        violate(
359                            "sh:ClassConstraintComponent",
360                            Some(v),
361                            format!("value is not an instance of {class}"),
362                        );
363                    }
364                }
365            }
366            ShaclConstraint::DataType(dt) => {
367                if let Some(tag) = datatype_tag(dt) {
368                    for &v in values {
369                        let ok = if v & MSB_FLAG != 0 {
370                            false
371                        } else if tag == 0 {
372                            object_tag(v) == 0 // xsd:string == untyped hash
373                        } else {
374                            object_tag(v) == tag
375                        };
376                        if !ok {
377                            violate(
378                                "sh:DatatypeConstraintComponent",
379                                Some(v),
380                                format!("value is not a {dt}"),
381                            );
382                        }
383                    }
384                }
385            }
386            ShaclConstraint::NodeKind(kind_str) => {
387                let want = parse_node_kind(kind_str);
388                if let Some(want) = want {
389                    for &v in values {
390                        if !node_kind_matches(v, want) {
391                            violate(
392                                "sh:NodeKindConstraintComponent",
393                                Some(v),
394                                format!("value is not nodeKind {kind_str}"),
395                            );
396                        }
397                    }
398                }
399            }
400            ShaclConstraint::NodeKindStrict(kind) => {
401                for &v in values {
402                    if !node_kind_matches(v, *kind) {
403                        violate(
404                            "sh:NodeKindConstraintComponent",
405                            Some(v),
406                            format!("value is not nodeKind {kind:?}"),
407                        );
408                    }
409                }
410            }
411
412            // ── value (membership / exact) ───────────────────────────────────────
413            ShaclConstraint::In(allowed) => {
414                let set: Vec<u64> = allowed.iter().map(|s| q_hash(s)).collect();
415                for &v in values {
416                    if !set.contains(&v) {
417                        violate(
418                            "sh:InConstraintComponent",
419                            Some(v),
420                            "value not in the allowed set".into(),
421                        );
422                    }
423                }
424            }
425            ShaclConstraint::HasValue(expected) => {
426                let e = q_hash(expected);
427                if !values.contains(&e) {
428                    violate(
429                        "sh:HasValueConstraintComponent",
430                        None,
431                        format!("required value {expected} absent"),
432                    );
433                }
434            }
435
436            // ── string-shaped (need the resolver) ────────────────────────────────
437            ShaclConstraint::MinLength(n) => {
438                for &v in values {
439                    match resolve(v) {
440                        Some(s) if s.chars().count() as u32 >= *n => {}
441                        _ => violate(
442                            "sh:MinLengthConstraintComponent",
443                            Some(v),
444                            format!("length < minLength {n} (or unresolvable)"),
445                        ),
446                    }
447                }
448            }
449            ShaclConstraint::MaxLength(n) => {
450                for &v in values {
451                    match resolve(v) {
452                        Some(s) if s.chars().count() as u32 <= *n => {}
453                        _ => violate(
454                            "sh:MaxLengthConstraintComponent",
455                            Some(v),
456                            format!("length > maxLength {n} (or unresolvable)"),
457                        ),
458                    }
459                }
460            }
461            ShaclConstraint::Pattern(pat) => match regex::Regex::new(pat) {
462                Ok(re) => {
463                    for &v in values {
464                        match resolve(v) {
465                            Some(s) if re.is_match(&s) => {}
466                            _ => violate(
467                                "sh:PatternConstraintComponent",
468                                Some(v),
469                                format!("value does not match /{pat}/ (or unresolvable)"),
470                            ),
471                        }
472                    }
473                }
474                Err(_) => violate(
475                    "sh:PatternConstraintComponent",
476                    None,
477                    format!("invalid regex pattern /{pat}/"),
478                ),
479            },
480            ShaclConstraint::LanguageIn(langs) => {
481                for &v in values {
482                    let ok = resolve(v)
483                        .map(|s| langs.iter().any(|l| lang_tag_matches(&s, l)))
484                        .unwrap_or(false);
485                    if !ok {
486                        violate(
487                            "sh:LanguageInConstraintComponent",
488                            Some(v),
489                            "value language tag not in languageIn (or unresolvable)".into(),
490                        );
491                    }
492                }
493            }
494            ShaclConstraint::UniqueLang => {
495                let mut seen: Vec<String> = Vec::new();
496                for &v in values {
497                    if let Some(tag) = resolve(v).and_then(|s| lang_tag_of(&s)) {
498                        if seen.contains(&tag) {
499                            violate(
500                                "sh:UniqueLangConstraintComponent",
501                                Some(v),
502                                format!("duplicate language tag @{tag}"),
503                            );
504                        } else {
505                            seen.push(tag);
506                        }
507                    }
508                }
509            }
510
511            // ── property-pair comparison ─────────────────────────────────────────
512            ShaclConstraint::Equals(other) => {
513                let theirs = self.values_at(focus, other);
514                if !same_set(values, &theirs) {
515                    violate(
516                        "sh:EqualsConstraintComponent",
517                        None,
518                        format!("value set != values of {other}"),
519                    );
520                }
521            }
522            ShaclConstraint::LessThan(other) => {
523                self.compare_pair(
524                    focus,
525                    values,
526                    other,
527                    severity,
528                    path,
529                    resolve,
530                    out,
531                    "sh:LessThanConstraintComponent",
532                    |a, b| a < b,
533                );
534            }
535            ShaclConstraint::LessThanOrEquals(other) => {
536                self.compare_pair(
537                    focus,
538                    values,
539                    other,
540                    severity,
541                    path,
542                    resolve,
543                    out,
544                    "sh:LessThanOrEqualsConstraintComponent",
545                    |a, b| a <= b,
546                );
547            }
548            ShaclConstraint::GreaterThan(other) => {
549                self.compare_pair(
550                    focus,
551                    values,
552                    other,
553                    severity,
554                    path,
555                    resolve,
556                    out,
557                    "sh:GreaterThanConstraintComponent",
558                    |a, b| a > b,
559                );
560            }
561            ShaclConstraint::GreaterThanOrEquals(other) => {
562                self.compare_pair(
563                    focus,
564                    values,
565                    other,
566                    severity,
567                    path,
568                    resolve,
569                    out,
570                    "sh:GreaterThanOrEqualsConstraintComponent",
571                    |a, b| a >= b,
572                );
573            }
574
575            // ── shape-based / logical ────────────────────────────────────────────
576            ShaclConstraint::Node(shape) => {
577                for &v in values {
578                    if !self.focus_conforms(v, shape, resolve) {
579                        violate(
580                            "sh:NodeConstraintComponent",
581                            Some(v),
582                            format!("value does not conform to shape {shape}"),
583                        );
584                    }
585                }
586            }
587            ShaclConstraint::And(shapes) => {
588                for &v in values {
589                    if !shapes.iter().all(|s| self.focus_conforms(v, s, resolve)) {
590                        violate(
591                            "sh:AndConstraintComponent",
592                            Some(v),
593                            "value fails one or more sh:and shapes".into(),
594                        );
595                    }
596                }
597            }
598            ShaclConstraint::Or(shapes) => {
599                for &v in values {
600                    if !shapes.iter().any(|s| self.focus_conforms(v, s, resolve)) {
601                        violate(
602                            "sh:OrConstraintComponent",
603                            Some(v),
604                            "value conforms to none of the sh:or shapes".into(),
605                        );
606                    }
607                }
608            }
609            ShaclConstraint::Not(shape) => {
610                for &v in values {
611                    if self.focus_conforms(v, shape, resolve) {
612                        violate(
613                            "sh:NotConstraintComponent",
614                            Some(v),
615                            format!("value conforms to negated shape {shape}"),
616                        );
617                    }
618                }
619            }
620            ShaclConstraint::Xone(shapes) => {
621                for &v in values {
622                    let n = shapes
623                        .iter()
624                        .filter(|s| self.focus_conforms(v, s, resolve))
625                        .count();
626                    if n != 1 {
627                        violate(
628                            "sh:XoneConstraintComponent",
629                            Some(v),
630                            format!("value conforms to {n} sh:xone shapes (need exactly 1)"),
631                        );
632                    }
633                }
634            }
635            ShaclConstraint::Closed { ignored_properties } => {
636                let mut allowed: Vec<u64> = ignored_properties.iter().map(|s| q_hash(s)).collect();
637                if let Some(p) = path {
638                    allowed.push(q_hash(p));
639                }
640                let type_keys = RDF_TYPE_KEYS.map(q_hash);
641                for q in self.quins.iter().filter(|q| q.subject == focus) {
642                    if !allowed.contains(&q.predicate) && !type_keys.contains(&q.predicate) {
643                        violate(
644                            "sh:ClosedConstraintComponent",
645                            Some(q.object),
646                            format!("closed shape: unexpected predicate {:016x}", q.predicate),
647                        );
648                    }
649                }
650            }
651
652            // ── property-path wrapper / qualifier ────────────────────────────────
653            ShaclConstraint::PropertyPath {
654                path: pp,
655                constraint,
656            } => {
657                let pvals = self.values_for_path(focus, pp);
658                let pstr = property_path_label(pp);
659                self.check(
660                    focus,
661                    &Some(pstr),
662                    &pvals,
663                    constraint,
664                    severity,
665                    resolve,
666                    out,
667                );
668            }
669            ShaclConstraint::QualifierValue { path: pp, value } => {
670                let pvals = self.values_for_path(focus, pp);
671                if !pvals.contains(&q_hash(value)) {
672                    violate(
673                        "sh:QualifiedValueShapeConstraintComponent",
674                        None,
675                        format!("qualified value {value} absent at path"),
676                    );
677                }
678            }
679
680            // ── Qualia-native modality constraints ───────────────────────────────
681            // These two have a direct data semantics over the value quins'
682            // confidence/truth degree (frame_layout::truth_degree in metadata).
683            ShaclConstraint::EpistemicConstraint {
684                certainty_threshold,
685            } => {
686                self.check_truth_degree(
687                    focus,
688                    path,
689                    *certainty_threshold,
690                    severity,
691                    resolve,
692                    out,
693                    "q42:EpistemicConstraintComponent",
694                );
695            }
696            ShaclConstraint::ProbabilisticConstraint {
697                confidence_threshold,
698            } => {
699                self.check_truth_degree(
700                    focus,
701                    path,
702                    *confidence_threshold,
703                    severity,
704                    resolve,
705                    out,
706                    "q42:ProbabilisticConstraintComponent",
707                );
708            }
709            ShaclConstraint::EconVaRPositive => {
710                for &v in values {
711                    match object_as_f64(v) {
712                        Some(x) if x > 0.0 => {}
713                        Some(x) => violate(
714                            "q42:EconVaRPositiveConstraintComponent",
715                            Some(v),
716                            format!("Value-at-Risk {x} <= 0 (must be strictly positive)"),
717                        ),
718                        None => violate(
719                            "q42:EconVaRPositiveConstraintComponent",
720                            Some(v),
721                            "VaR observation is not numeric".into(),
722                        ),
723                    }
724                }
725            }
726            ShaclConstraint::EconPositivePrice => {
727                for &v in values {
728                    match object_as_f64(v) {
729                        Some(x) if x > 0.0 => {}
730                        Some(x) => violate(
731                            "q42:EconPositivePriceConstraintComponent",
732                            Some(v),
733                            format!("price {x} <= 0 (must be strictly positive)"),
734                        ),
735                        None => violate(
736                            "q42:EconPositivePriceConstraintComponent",
737                            Some(v),
738                            "price observation is not numeric".into(),
739                        ),
740                    }
741                }
742            }
743            ShaclConstraint::EconWelfareAboveFloor { min_welfare } => {
744                for &v in values {
745                    match object_as_f64(v) {
746                        Some(x) if x >= *min_welfare => {}
747                        Some(x) => violate(
748                            "q42:EconWelfareAboveFloorConstraintComponent",
749                            Some(v),
750                            format!("welfare index {x} < required floor {min_welfare}"),
751                        ),
752                        None => violate(
753                            "q42:EconWelfareAboveFloorConstraintComponent",
754                            Some(v),
755                            "welfare observation is not numeric".into(),
756                        ),
757                    }
758                }
759            }
760            ShaclConstraint::EconRiskBelowThreshold { max_risk } => {
761                for &v in values {
762                    match object_as_f64(v) {
763                        Some(x) if x <= *max_risk => {}
764                        Some(x) => violate(
765                            "q42:EconRiskBelowThresholdConstraintComponent",
766                            Some(v),
767                            format!("risk metric {x} > maximum allowed threshold {max_risk}"),
768                        ),
769                        None => violate(
770                            "q42:EconRiskBelowThresholdConstraintComponent",
771                            Some(v),
772                            "risk observation is not numeric".into(),
773                        ),
774                    }
775                }
776            }
777            ShaclConstraint::EconConvergedModel => {
778                for &v in values {
779                    let passed = match object_as_f64(v) {
780                        Some(x) => x > 0.0,
781                        None => resolve(v)
782                            .map(|s| s == "true" || s == "converged" || s == "1")
783                            .unwrap_or(false),
784                    };
785                    if !passed {
786                        violate(
787                            "q42:EconConvergedModelConstraintComponent",
788                            Some(v),
789                            "model did not report converged state".into(),
790                        );
791                    }
792                }
793            }
794            ShaclConstraint::ValuesConsentNonCoerced { max_imbalance } => {
795                // Coercion evidence: numeric imbalance ≥ threshold, or CoercedConsentFlag term.
796                let flag_hashes = [
797                    crate::q_hash("https://ns.webcivics.net/values/CoercedConsentFlag"),
798                    crate::q_hash("values:CoercedConsentFlag"),
799                    crate::q_hash("CoercedConsentFlag"),
800                ];
801                for &v in values {
802                    let coerced = if let Some(x) = object_as_f64(v) {
803                        crate::modalities::capacity::detect_duress(
804                            x as f32,
805                            false,
806                            *max_imbalance as f32,
807                        )
808                    } else {
809                        flag_hashes.contains(&v)
810                            || resolve(v)
811                                .map(|s| {
812                                    s.contains("CoercedConsentFlag")
813                                        || s.eq_ignore_ascii_case("coerced")
814                                        || s == "true"
815                                        || s == "1"
816                                })
817                                .unwrap_or(false)
818                    };
819                    if coerced {
820                        violate(
821                            "q42:ValuesConsentNonCoercedConstraintComponent",
822                            Some(v),
823                            format!(
824                                "consent appears coerced (imbalance/flag ≥ threshold {max_imbalance})"
825                            ),
826                        );
827                    }
828                }
829            }
830            ShaclConstraint::ValuesHarmBelowCeiling { max_harm } => {
831                for &v in values {
832                    match object_as_f64(v) {
833                        Some(x) if x < *max_harm => {}
834                        Some(x) => violate(
835                            "q42:ValuesHarmBelowCeilingConstraintComponent",
836                            Some(v),
837                            format!("harm metric {x} is not strictly below ceiling {max_harm}"),
838                        ),
839                        None => violate(
840                            "q42:ValuesHarmBelowCeilingConstraintComponent",
841                            Some(v),
842                            "harm observation is not numeric".into(),
843                        ),
844                    }
845                }
846            }
847            ShaclConstraint::FuzzyMinDegree { min_degree } => {
848                for &v in values {
849                    match object_as_f64(v) {
850                        Some(x) if x >= *min_degree => {}
851                        Some(x) => violate(
852                            "q42:FuzzyMinDegreeConstraintComponent",
853                            Some(v),
854                            format!("fuzzy degree {x} < required minimum {min_degree}"),
855                        ),
856                        None => violate(
857                            "q42:FuzzyMinDegreeConstraintComponent",
858                            Some(v),
859                            "fuzzy degree observation is not numeric".into(),
860                        ),
861                    }
862                }
863            }
864
865            // Modality constraints — graph-level admission (Civics / SHACL gate).
866            // Scan the bound quin graph; fail closed when required norms/claims are absent.
867            ShaclConstraint::DeonticPolicy { .. }
868            | ShaclConstraint::DeonticObligate
869            | ShaclConstraint::DeonticPermit
870            | ShaclConstraint::DeonticForbid => {
871                use crate::modalities::logic::deontic::{
872                    evaluate_deontic_contract, extract_deontic_opcode, DeonticStatus, OP_FORBID,
873                    OP_OBLIGATE, OP_PERMIT,
874                };
875                let want = match c {
876                    ShaclConstraint::DeonticObligate => Some(OP_OBLIGATE),
877                    ShaclConstraint::DeonticPermit => Some(OP_PERMIT),
878                    ShaclConstraint::DeonticForbid => Some(OP_FORBID),
879                    _ => None, // DeonticPolicy: any O/P/F
880                };
881                let mut buf = vec![
882                    crate::modalities::logic::deontic::DeonticVerdict::default();
883                    self.quins.len().max(1)
884                ];
885                let n = evaluate_deontic_contract(self.quins, 0, &mut buf).unwrap_or(0);
886                let ok = buf[..n].iter().any(|v| {
887                    if v.status != DeonticStatus::Active {
888                        return false;
889                    }
890                    let op = extract_deontic_opcode(v.norm.predicate);
891                    let op_ok = match want {
892                        Some(w) => op == w,
893                        None => op == OP_OBLIGATE || op == OP_PERMIT || op == OP_FORBID,
894                    };
895                    op_ok && (v.norm.subject == focus || values.contains(&v.norm.subject))
896                });
897                if !ok {
898                    let kind = match want {
899                        Some(OP_OBLIGATE) => "obligation",
900                        Some(OP_PERMIT) => "permission",
901                        Some(OP_FORBID) => "prohibition",
902                        None | Some(_) => "deontic policy",
903                    };
904                    violate(
905                        "q42:DeonticConstraintComponent",
906                        None,
907                        format!("no active {kind} norm for focus in graph"),
908                    );
909                }
910            }
911            ShaclConstraint::DeonticNotExpired { now_unix } => {
912                use crate::modalities::logic::deontic::{evaluate_deontic_contract, DeonticStatus};
913                let mut buf = vec![
914                    crate::modalities::logic::deontic::DeonticVerdict::default();
915                    self.quins.len().max(1)
916                ];
917                let n = evaluate_deontic_contract(self.quins, *now_unix, &mut buf).unwrap_or(0);
918                let expired = buf[..n].iter().any(|v| {
919                    v.status == DeonticStatus::Expired
920                        && (v.norm.subject == focus || values.contains(&v.norm.subject))
921                });
922                if expired {
923                    violate(
924                        "q42:DeonticNotExpiredConstraintComponent",
925                        None,
926                        format!("deontic norm expired at now_unix={now_unix}"),
927                    );
928                }
929            }
930            ShaclConstraint::EpistemicKnowledge { .. }
931            | ShaclConstraint::EpistemicBelief { .. }
932            | ShaclConstraint::CommonKnowledge => {
933                use crate::modalities::epistemic::{
934                    evaluate_epistemic_frame, EpistemicStatus, EpistemicVerdict, OP_BELIEVES,
935                    OP_COMMON_KNOWLEDGE, OP_KNOWS,
936                };
937                let (want_op, min_c) = match c {
938                    ShaclConstraint::EpistemicKnowledge { min_certainty } => {
939                        (Some(OP_KNOWS), *min_certainty)
940                    }
941                    ShaclConstraint::EpistemicBelief { min_certainty } => {
942                        (Some(OP_BELIEVES), *min_certainty)
943                    }
944                    ShaclConstraint::CommonKnowledge => (Some(OP_COMMON_KNOWLEDGE), 255u8),
945                    _ => (None, 0u8),
946                };
947                let empty = EpistemicVerdict {
948                    claim: NQuin::default(),
949                    status: EpistemicStatus::Skipped,
950                    certainty: 0,
951                };
952                let mut buf = vec![empty; self.quins.len().max(1)];
953                let n = evaluate_epistemic_frame(self.quins, focus, 0, &mut buf).unwrap_or(0);
954                let ok = buf[..n].iter().any(|v| {
955                    if v.certainty < min_c {
956                        return false;
957                    }
958                    if !matches!(
959                        v.status,
960                        EpistemicStatus::Active | EpistemicStatus::Uncertain
961                    ) {
962                        return false;
963                    }
964                    if v.status == EpistemicStatus::Uncertain && want_op == Some(OP_KNOWS) {
965                        return false;
966                    }
967                    let op = (v.claim.predicate & 0xFF) as u8;
968                    match want_op {
969                        Some(w) => op == w,
970                        None => op == OP_KNOWS || op == OP_BELIEVES || op == OP_COMMON_KNOWLEDGE,
971                    }
972                });
973                if !ok {
974                    violate(
975                        "q42:EpistemicConstraintComponent",
976                        None,
977                        format!("no qualifying epistemic claim for focus (minCertainty={min_c})"),
978                    );
979                }
980            }
981            ShaclConstraint::ParaconsistentConstraint { isolation_context } => {
982                use crate::modalities::paraconsistent::route_paraconsistent;
983                let mut consistent = vec![NQuin::default(); self.quins.len().max(1)];
984                let mut isolated = vec![NQuin::default(); self.quins.len().max(1)];
985                let (_c_n, i_n) = route_paraconsistent(self.quins, &mut consistent, &mut isolated)
986                    .unwrap_or((0, 0));
987                if isolation_context.is_empty() {
988                    // Admission rule: graph must not introduce isolations involving focus.
989                    let hit = isolated[..i_n].iter().any(|q| {
990                        q.subject == focus
991                            || values.contains(&q.subject)
992                            || values.contains(&q.object)
993                    });
994                    if hit {
995                        violate(
996                            "q42:ParaconsistentConstraintComponent",
997                            None,
998                            "contradiction isolated for focus (paraconsistent admission failed)"
999                                .into(),
1000                        );
1001                    }
1002                } else {
1003                    let want = q_hash(isolation_context);
1004                    let ok = isolated[..i_n].iter().any(|q| q.context == want);
1005                    if !ok {
1006                        violate(
1007                            "q42:ParaconsistentConstraintComponent",
1008                            None,
1009                            format!("expected isolation context {isolation_context} not present"),
1010                        );
1011                    }
1012                }
1013            }
1014            ShaclConstraint::LtlConstraint { formula } => {
1015                use crate::modalities::temporal_ltl::{evaluate_ltl_trace, LtlFormula};
1016                let f = formula.trim();
1017                if f.is_empty() {
1018                    violate(
1019                        "q42:TemporalLtlConstraintComponent",
1020                        None,
1021                        "ltl formula is empty".into(),
1022                    );
1023                } else {
1024                    // Compact forms: "G:<u64>", "F:<u64>", "X:<u64>", "U:<ante>:<cons>"
1025                    let parsed = if let Some(rest) = f.strip_prefix("G:") {
1026                        rest.parse::<u64>().ok().map(LtlFormula::Globally)
1027                    } else if let Some(rest) = f.strip_prefix("F:") {
1028                        rest.parse::<u64>().ok().map(LtlFormula::Finally)
1029                    } else if let Some(rest) = f.strip_prefix("X:") {
1030                        rest.parse::<u64>().ok().map(LtlFormula::Next)
1031                    } else if let Some(rest) = f.strip_prefix("U:") {
1032                        let mut parts = rest.splitn(2, ':');
1033                        match (parts.next(), parts.next()) {
1034                            (Some(a), Some(b)) => match (a.parse::<u64>(), b.parse::<u64>()) {
1035                                (Ok(ante), Ok(consequent)) => {
1036                                    Some(LtlFormula::Until { ante, consequent })
1037                                }
1038                                _ => None,
1039                            },
1040                            _ => None,
1041                        }
1042                    } else {
1043                        None
1044                    };
1045                    match parsed {
1046                        Some(ltl) => {
1047                            if !evaluate_ltl_trace(self.quins, &ltl) {
1048                                violate(
1049                                    "q42:TemporalLtlConstraintComponent",
1050                                    None,
1051                                    format!("LTL formula not satisfied on graph trace: {f}"),
1052                                );
1053                            }
1054                        }
1055                        None => violate(
1056                            "q42:TemporalLtlConstraintComponent",
1057                            None,
1058                            format!(
1059                                "unsupported LTL formula encoding '{f}' (use G:|F:|X:|U: property hashes)"
1060                            ),
1061                        ),
1062                    }
1063                }
1064            }
1065            // Remaining modality computations still route via VM opcodes for now.
1066            ShaclConstraint::CalculusConstraint { .. }
1067            | ShaclConstraint::GraphConstraint { .. }
1068            | ShaclConstraint::ArgumentationConstraint { .. }
1069            | ShaclConstraint::DialecticalConstraint { .. }
1070            | ShaclConstraint::AspConstraint { .. }
1071            | ShaclConstraint::DiffusionConstraint { .. }
1072            | ShaclConstraint::LinearLogicConstraint { .. }
1073            | ShaclConstraint::ControlFeedbackConstraint { .. }
1074            | ShaclConstraint::IntervalArithmeticConstraint { .. } => {
1075                violate(
1076                    "q42:UnsupportedConstraintComponent",
1077                    None,
1078                    "unsupported modality constraint component in data validator (use VM path or extend validate.rs)"
1079                        .into(),
1080                );
1081            }
1082        }
1083    }
1084
1085    /// Values reachable from `focus` along a `PropertyPath` expression.
1086    fn values_for_path(&self, focus: u64, path: &PropertyPath) -> Vec<u64> {
1087        match path {
1088            PropertyPath::Predicate(p) => self.values_at(focus, p),
1089            PropertyPath::Inverse(inner) => {
1090                if let PropertyPath::Predicate(p) = inner.as_ref() {
1091                    let ph = q_hash(p);
1092                    self.quins
1093                        .iter()
1094                        .filter(|q| q.object == focus && q.predicate == ph)
1095                        .map(|q| q.subject)
1096                        .collect()
1097                } else {
1098                    Vec::new()
1099                }
1100            }
1101            PropertyPath::Sequence(steps) => {
1102                let mut frontier = vec![focus];
1103                for step in steps {
1104                    let mut next = Vec::new();
1105                    for f in frontier {
1106                        next.extend(self.values_for_path(f, step));
1107                    }
1108                    frontier = next;
1109                }
1110                frontier
1111            }
1112            PropertyPath::Alternative(alts) => {
1113                let mut out = Vec::new();
1114                for a in alts {
1115                    out.extend(self.values_for_path(focus, a));
1116                }
1117                out
1118            }
1119            PropertyPath::ZeroOrMore(inner) => {
1120                let mut seen = vec![focus];
1121                let mut frontier = vec![focus];
1122                while let Some(f) = frontier.pop() {
1123                    for v in self.values_for_path(f, inner) {
1124                        if !seen.contains(&v) {
1125                            seen.push(v);
1126                            frontier.push(v);
1127                        }
1128                    }
1129                }
1130                seen
1131            }
1132            PropertyPath::OneOrMore(inner) => {
1133                let mut seen = Vec::new();
1134                let mut frontier = self.values_for_path(focus, inner);
1135                while let Some(f) = frontier.pop() {
1136                    if !seen.contains(&f) {
1137                        seen.push(f);
1138                        frontier.extend(self.values_for_path(f, inner));
1139                    }
1140                }
1141                seen
1142            }
1143            PropertyPath::ZeroOrOne(inner) => {
1144                let mut out = vec![focus];
1145                out.extend(self.values_for_path(focus, inner));
1146                out
1147            }
1148        }
1149    }
1150
1151    /// Cross-property comparison (`sh:lessThan`/`equals`/…): every
1152    /// (value, other-property-value) pair must satisfy `cmp` as `f64`;
1153    /// pairs that can't be decoded to numbers are violations.
1154    #[allow(clippy::too_many_arguments)]
1155    fn compare_pair(
1156        &self,
1157        focus: u64,
1158        values: &[u64],
1159        other: &str,
1160        severity: ShaclSeverity,
1161        path: &Option<String>,
1162        resolve: Resolver,
1163        out: &mut Vec<ValidationResult>,
1164        component: &str,
1165        cmp: fn(f64, f64) -> bool,
1166    ) {
1167        let theirs = self.values_at(focus, other);
1168        for &a in values {
1169            for &b in &theirs {
1170                let ok = match (object_as_f64(a), object_as_f64(b)) {
1171                    (Some(x), Some(y)) => cmp(x, y),
1172                    _ => false,
1173                };
1174                if !ok {
1175                    out.push(ValidationResult {
1176                        severity,
1177                        focus_node: label(focus, resolve),
1178                        result_path: path.clone(),
1179                        message: Some(format!("comparison vs {other} failed")),
1180                        source_constraint: None,
1181                        source_constraint_component: Some(component.to_string()),
1182                        value: Some(label(a, resolve)),
1183                    });
1184                }
1185            }
1186        }
1187    }
1188
1189    /// `q42`-extension check: every quin on `focus` (optionally filtered
1190    /// to `path`) must carry `truth_degree` ≥ `threshold` in its metadata;
1191    /// under-threshold quins emit a violation per quin.
1192    #[allow(clippy::too_many_arguments)]
1193    fn check_truth_degree(
1194        &self,
1195        focus: u64,
1196        path: &Option<String>,
1197        threshold: f32,
1198        severity: ShaclSeverity,
1199        resolve: Resolver,
1200        out: &mut Vec<ValidationResult>,
1201        component: &str,
1202    ) {
1203        let p = path.as_ref().map(|s| q_hash(s));
1204        for q in self.quins.iter().filter(|q| q.subject == focus) {
1205            if let Some(ph) = p {
1206                if q.predicate != ph {
1207                    continue;
1208                }
1209            }
1210            if crate::frame_layout::truth_degree(q.metadata) < threshold {
1211                out.push(ValidationResult {
1212                    severity,
1213                    focus_node: label(focus, resolve),
1214                    result_path: path.clone(),
1215                    message: Some(format!("truth/confidence below {threshold}")),
1216                    source_constraint: None,
1217                    source_constraint_component: Some(component.to_string()),
1218                    value: Some(label(q.object, resolve)),
1219                });
1220            }
1221        }
1222    }
1223
1224    /// Target nodes for a shape (class-based: `shape_class` is treated as the
1225    /// `sh:targetClass`; falls back to "every subject" when no instances exist so
1226    /// node shapes still validate explicitly-supplied focus nodes).
1227    fn target_nodes(&self, shape: &CompiledShape) -> Vec<u64> {
1228        let class = q_hash(&shape.shape_class);
1229        let type_keys = RDF_TYPE_KEYS.map(q_hash);
1230        let mut nodes: Vec<u64> = self
1231            .quins
1232            .iter()
1233            .filter(|q| type_keys.contains(&q.predicate) && q.object == class)
1234            .map(|q| q.subject)
1235            .collect();
1236        nodes.sort_unstable();
1237        nodes.dedup();
1238        nodes
1239    }
1240}
1241
1242/// Parse a `sh:nodeKind` lexical value into `NodeKindType` — accepts
1243/// with or without the `sh:` prefix; `None` for unrecognized kinds.
1244fn parse_node_kind(s: &str) -> Option<NodeKindType> {
1245    match s.trim_start_matches("sh:") {
1246        "BlankNode" => Some(NodeKindType::BlankNode),
1247        "IRI" => Some(NodeKindType::Iri),
1248        "Literal" => Some(NodeKindType::Literal),
1249        "BlankNodeOrIRI" => Some(NodeKindType::BlankNodeOrIri),
1250        "BlankNodeOrLiteral" => Some(NodeKindType::BlankNodeOrLiteral),
1251        "IRIOrLiteral" => Some(NodeKindType::IriOrLiteral),
1252        _ => None,
1253    }
1254}
1255
1256/// Render a `PropertyPath` back to SHACL surface syntax (`^` inverse,
1257/// `/` sequence, `|` alternative, `*`/`+`/`?` cardinality) for report
1258/// `result_path` labels.
1259fn property_path_label(p: &PropertyPath) -> String {
1260    match p {
1261        PropertyPath::Predicate(s) => s.clone(),
1262        PropertyPath::Inverse(i) => format!("^{}", property_path_label(i)),
1263        PropertyPath::Sequence(s) => s
1264            .iter()
1265            .map(property_path_label)
1266            .collect::<Vec<_>>()
1267            .join("/"),
1268        PropertyPath::Alternative(s) => s
1269            .iter()
1270            .map(property_path_label)
1271            .collect::<Vec<_>>()
1272            .join("|"),
1273        PropertyPath::ZeroOrMore(i) => format!("{}*", property_path_label(i)),
1274        PropertyPath::OneOrMore(i) => format!("{}+", property_path_label(i)),
1275        PropertyPath::ZeroOrOne(i) => format!("{}?", property_path_label(i)),
1276    }
1277}
1278
1279/// Order-insensitive set equality over two `u64` slices (duplicates
1280/// ignored). O(n·m) — inputs are property-value counts, small in
1281/// practice.
1282fn same_set(a: &[u64], b: &[u64]) -> bool {
1283    a.iter().all(|x| b.contains(x)) && b.iter().all(|x| a.contains(x))
1284}
1285
1286/// Extract the `@lang` tag of a lexical value (e.g. `"hello"@en` → `en`).
1287fn lang_tag_of(s: &str) -> Option<String> {
1288    s.rsplit_once('@')
1289        .map(|(_, tag)| tag.trim_matches('"').to_ascii_lowercase())
1290}
1291
1292/// Whether a value's language tag matches `want` (BCP-47 prefix match, e.g.
1293/// `en` matches `en-US`).
1294fn lang_tag_matches(value: &str, want: &str) -> bool {
1295    match lang_tag_of(value) {
1296        Some(tag) => {
1297            let want = want.to_ascii_lowercase();
1298            tag == want || tag.starts_with(&format!("{want}-"))
1299        }
1300        None => false,
1301    }
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306    use super::*;
1307    use crate::frame_layout::{pack_float_object, INLINE_TAG_INTEGER};
1308
1309    fn iri(s: &str) -> u64 {
1310        q_hash(s)
1311    }
1312    fn int_obj(n: i64) -> u64 {
1313        INLINE_TAG_INTEGER | ((n as u64) & INLINE_VALUE_MASK)
1314    }
1315    fn quin(s: u64, p: u64, o: u64) -> NQuin {
1316        NQuin {
1317            subject: s,
1318            predicate: p,
1319            object: o,
1320            context: 0,
1321            metadata: 0,
1322            parity: 0,
1323        }
1324    }
1325    fn type_quin(node: u64, class: &str) -> NQuin {
1326        quin(node, q_hash("rdf:type"), q_hash(class))
1327    }
1328    fn no_resolve() -> impl Fn(u64) -> Option<String> {
1329        |_| None
1330    }
1331
1332    fn shape(class: &str, path: &str, cs: Vec<ShaclConstraint>) -> CompiledShape {
1333        let mut s = CompiledShape::new(class.to_string(), cs, ShaclSeverity::Violation);
1334        s.property_path = path.to_string();
1335        s
1336    }
1337
1338    #[test]
1339    fn min_inclusive_passes_and_fails_on_real_numbers() {
1340        let alice = iri("ex:Alice");
1341        let bob = iri("ex:Bob");
1342        let quins = vec![
1343            type_quin(alice, "ex:Adult"),
1344            quin(alice, q_hash("ex:age"), int_obj(30)),
1345            type_quin(bob, "ex:Adult"),
1346            quin(bob, q_hash("ex:age"), int_obj(12)),
1347        ];
1348        let shapes = vec![shape(
1349            "ex:Adult",
1350            "ex:age",
1351            vec![ShaclConstraint::MinInclusive(18.0)],
1352        )];
1353        let eng = ShaclEngine::new(&quins, &shapes);
1354        let rep = eng.validate(&no_resolve());
1355        assert!(!rep.conforms, "bob (age 12) must violate minInclusive 18");
1356        assert_eq!(rep.results.len(), 1);
1357        assert_eq!(
1358            rep.results[0].source_constraint_component.as_deref(),
1359            Some("sh:MinInclusiveConstraintComponent")
1360        );
1361    }
1362
1363    #[test]
1364    fn min_max_count_use_property_value_count() {
1365        let n = iri("ex:N");
1366        let quins = vec![
1367            type_quin(n, "ex:Thing"),
1368            quin(n, q_hash("ex:p"), iri("ex:v1")),
1369            quin(n, q_hash("ex:p"), iri("ex:v2")),
1370        ];
1371        let too_few = vec![shape(
1372            "ex:Thing",
1373            "ex:p",
1374            vec![ShaclConstraint::MinCount(3)],
1375        )];
1376        assert!(
1377            !ShaclEngine::new(&quins, &too_few)
1378                .validate(&no_resolve())
1379                .conforms
1380        );
1381        let too_many = vec![shape(
1382            "ex:Thing",
1383            "ex:p",
1384            vec![ShaclConstraint::MaxCount(1)],
1385        )];
1386        assert!(
1387            !ShaclEngine::new(&quins, &too_many)
1388                .validate(&no_resolve())
1389                .conforms
1390        );
1391        let ok = vec![shape(
1392            "ex:Thing",
1393            "ex:p",
1394            vec![ShaclConstraint::MinCount(2), ShaclConstraint::MaxCount(2)],
1395        )];
1396        assert!(
1397            ShaclEngine::new(&quins, &ok)
1398                .validate(&no_resolve())
1399                .conforms
1400        );
1401    }
1402
1403    #[test]
1404    fn class_constraint_checks_rdf_type() {
1405        let n = iri("ex:N");
1406        let dog = iri("ex:Rex");
1407        let quins = vec![
1408            type_quin(n, "ex:Owner"),
1409            quin(n, q_hash("ex:pet"), dog),
1410            type_quin(dog, "ex:Cat"),
1411        ];
1412        let shapes = vec![shape(
1413            "ex:Owner",
1414            "ex:pet",
1415            vec![ShaclConstraint::Class("ex:Dog".into())],
1416        )];
1417        assert!(
1418            !ShaclEngine::new(&quins, &shapes)
1419                .validate(&no_resolve())
1420                .conforms
1421        );
1422    }
1423
1424    #[test]
1425    fn in_and_has_value() {
1426        let n = iri("ex:N");
1427        let quins = vec![
1428            type_quin(n, "ex:T"),
1429            quin(n, q_hash("ex:status"), iri("ex:active")),
1430        ];
1431        let in_ok = vec![shape(
1432            "ex:T",
1433            "ex:status",
1434            vec![ShaclConstraint::In(vec![
1435                "ex:active".into(),
1436                "ex:inactive".into(),
1437            ])],
1438        )];
1439        assert!(
1440            ShaclEngine::new(&quins, &in_ok)
1441                .validate(&no_resolve())
1442                .conforms
1443        );
1444        let in_bad = vec![shape(
1445            "ex:T",
1446            "ex:status",
1447            vec![ShaclConstraint::In(vec!["ex:archived".into()])],
1448        )];
1449        assert!(
1450            !ShaclEngine::new(&quins, &in_bad)
1451                .validate(&no_resolve())
1452                .conforms
1453        );
1454        let hv = vec![shape(
1455            "ex:T",
1456            "ex:status",
1457            vec![ShaclConstraint::HasValue("ex:active".into())],
1458        )];
1459        assert!(
1460            ShaclEngine::new(&quins, &hv)
1461                .validate(&no_resolve())
1462                .conforms
1463        );
1464    }
1465
1466    #[test]
1467    fn pattern_uses_real_regex_with_resolver() {
1468        let n = iri("ex:N");
1469        let email = iri("alice@example.org"); // value hash; resolver supplies the string
1470        let quins = vec![type_quin(n, "ex:User"), quin(n, q_hash("ex:email"), email)];
1471        let shapes = vec![shape(
1472            "ex:User",
1473            "ex:email",
1474            vec![ShaclConstraint::Pattern(r"^[^@]+@[^@]+\.[a-z]+$".into())],
1475        )];
1476        let resolve = |h: u64| {
1477            if h == email {
1478                Some("alice@example.org".to_string())
1479            } else {
1480                None
1481            }
1482        };
1483        assert!(
1484            ShaclEngine::new(&quins, &shapes)
1485                .validate(&resolve)
1486                .conforms
1487        );
1488        // A non-matching string fails.
1489        let resolve_bad = |h: u64| {
1490            if h == email {
1491                Some("not-an-email".to_string())
1492            } else {
1493                None
1494            }
1495        };
1496        assert!(
1497            !ShaclEngine::new(&quins, &shapes)
1498                .validate(&resolve_bad)
1499                .conforms
1500        );
1501        // Unresolvable → fail closed.
1502        assert!(
1503            !ShaclEngine::new(&quins, &shapes)
1504                .validate(&no_resolve())
1505                .conforms
1506        );
1507    }
1508
1509    #[test]
1510    fn min_length_with_resolver() {
1511        let n = iri("ex:N");
1512        let v = iri("ex:val");
1513        let quins = vec![type_quin(n, "ex:T"), quin(n, q_hash("ex:name"), v)];
1514        let shapes = vec![shape(
1515            "ex:T",
1516            "ex:name",
1517            vec![ShaclConstraint::MinLength(5)],
1518        )];
1519        let ok = |h: u64| {
1520            if h == v {
1521                Some("Timothy".to_string())
1522            } else {
1523                None
1524            }
1525        };
1526        assert!(ShaclEngine::new(&quins, &shapes).validate(&ok).conforms);
1527        let bad = |h: u64| {
1528            if h == v {
1529                Some("Tim".to_string())
1530            } else {
1531                None
1532            }
1533        };
1534        assert!(!ShaclEngine::new(&quins, &shapes).validate(&bad).conforms);
1535    }
1536
1537    #[test]
1538    fn logical_or_and_not_xone() {
1539        let n = iri("ex:N");
1540        let quins = vec![
1541            type_quin(n, "ex:Doc"),
1542            quin(n, q_hash("ex:title"), iri("t")),
1543        ];
1544        // Sub-shape: requires ex:title present (minCount 1).
1545        let has_title = shape(
1546            "ex:HasTitle",
1547            "ex:title",
1548            vec![ShaclConstraint::MinCount(1)],
1549        );
1550        let has_author = shape(
1551            "ex:HasAuthor",
1552            "ex:author",
1553            vec![ShaclConstraint::MinCount(1)],
1554        );
1555        // Node shape on the focus: Or(HasTitle, HasAuthor) → passes (has title).
1556        let mut or_shape = CompiledShape::new(
1557            "ex:Doc".into(),
1558            vec![ShaclConstraint::Or(vec![
1559                "ex:HasTitle".into(),
1560                "ex:HasAuthor".into(),
1561            ])],
1562            ShaclSeverity::Violation,
1563        );
1564        or_shape.property_path = String::new(); // node shape (focus itself)
1565        let shapes = vec![or_shape, has_title.clone(), has_author.clone()];
1566        assert!(
1567            ShaclEngine::new(&quins, &shapes)
1568                .validate(&no_resolve())
1569                .conforms
1570        );
1571
1572        // Not(HasAuthor) → passes (no author). Not(HasTitle) → fails.
1573        let mut not_author = CompiledShape::new(
1574            "ex:Doc".into(),
1575            vec![ShaclConstraint::Not("ex:HasAuthor".into())],
1576            ShaclSeverity::Violation,
1577        );
1578        not_author.property_path = String::new();
1579        let shapes2 = vec![not_author, has_title.clone(), has_author.clone()];
1580        assert!(
1581            ShaclEngine::new(&quins, &shapes2)
1582                .validate(&no_resolve())
1583                .conforms
1584        );
1585
1586        let mut not_title = CompiledShape::new(
1587            "ex:Doc".into(),
1588            vec![ShaclConstraint::Not("ex:HasTitle".into())],
1589            ShaclSeverity::Violation,
1590        );
1591        not_title.property_path = String::new();
1592        let shapes3 = vec![not_title, has_title, has_author];
1593        assert!(
1594            !ShaclEngine::new(&quins, &shapes3)
1595                .validate(&no_resolve())
1596                .conforms
1597        );
1598    }
1599
1600    #[test]
1601    fn closed_shape_rejects_extra_predicates() {
1602        let n = iri("ex:N");
1603        let quins = vec![
1604            type_quin(n, "ex:Strict"),
1605            quin(n, q_hash("ex:allowed"), iri("v1")),
1606            quin(n, q_hash("ex:sneaky"), iri("v2")),
1607        ];
1608        let mut s = CompiledShape::new(
1609            "ex:Strict".into(),
1610            vec![ShaclConstraint::Closed {
1611                ignored_properties: vec!["ex:allowed".into()],
1612            }],
1613            ShaclSeverity::Violation,
1614        );
1615        s.property_path = String::new();
1616        let shapes = vec![s];
1617        let rep = ShaclEngine::new(&quins, &shapes).validate(&no_resolve());
1618        assert!(!rep.conforms, "ex:sneaky is not in the allowed/ignored set");
1619    }
1620
1621    #[test]
1622    fn property_pair_less_than() {
1623        let n = iri("ex:N");
1624        let quins = vec![
1625            type_quin(n, "ex:Event"),
1626            quin(n, q_hash("ex:start"), int_obj(5)),
1627            quin(n, q_hash("ex:end"), int_obj(10)),
1628        ];
1629        let ok = vec![shape(
1630            "ex:Event",
1631            "ex:start",
1632            vec![ShaclConstraint::LessThan("ex:end".into())],
1633        )];
1634        assert!(
1635            ShaclEngine::new(&quins, &ok)
1636                .validate(&no_resolve())
1637                .conforms
1638        );
1639        // Reverse: end < start should fail.
1640        let bad = vec![shape(
1641            "ex:Event",
1642            "ex:end",
1643            vec![ShaclConstraint::LessThan("ex:start".into())],
1644        )];
1645        assert!(
1646            !ShaclEngine::new(&quins, &bad)
1647                .validate(&no_resolve())
1648                .conforms
1649        );
1650    }
1651
1652    #[test]
1653    fn object_as_f64_decodes_inline_types() {
1654        assert_eq!(object_as_f64(int_obj(42)), Some(42.0));
1655        assert_eq!(object_as_f64(int_obj(-7)), Some(-7.0));
1656        assert_eq!(object_as_f64(pack_float_object(3.5)), Some(3.5));
1657        assert_eq!(object_as_f64(q_hash("ex:iri")), None); // IRI hash is not numeric
1658    }
1659}