Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat: onto_vocab_check — closed-world vocabulary check for generated data
Fabio Rovai82f0dcf82a90
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6c5e52eb..abada283 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **`onto_vocab_check` — closed-world vocabulary check for generated DATA graphs.** Verifies that every predicate and every `rdf:type` class used in a Turtle data graph is actually **declared** in the loaded ontology, flagging hallucinated/undeclared terms. This is the gate open-world SHACL structurally cannot provide: SHACL silently ignores predicates it has no shape for, so a graph full of invented terms (an LLM emitting `ies:hasDeparturePort` when the ontology only defines `ies:scheduledDeparturePort`) still reports `conforms=true`. Only IRIs whose namespace belongs to the ontology (plus any passed via `namespaces`) are policed — standard `rdf`/`rdfs`/`owl`/`xsd`/`sh` vocabulary and the caller's own instance-data IRIs are never flagged. Returns `{conforms, hallucinated_terms, checked_namespaces, predicates_checked, types_checked, ontology_terms}`. **Vacuous-pass guard:** when no ontology vocabulary is present (0 declared terms and no `namespaces`), the tool returns `conforms=false` with an explanatory `warning` rather than silently passing — a closed-world check with nothing to check against must never green-light. New module `src/vocab_check.rs` (SPARQL over Oxigraph, mirroring the term-existence logic of `onto_shacl_check`) with 3 unit tests (clean conforms / hallucinated predicate caught / instance + standard namespaces never flagged). Exposed as MCP tool `onto_vocab_check` (+ `OntoVocabCheckInput`), CLI subcommand `vocab-check`, and batch command `vocab_check`. Verified end-to-end against the real IES4 ontology (714 terms): it flags the non-ontology terms IES4's *own* published sample data uses — `movement.ttl` → `isScheduledDeparturePort`/`isScheduledArrivalPort`/`seatNumber`, `events.ttl` → `happensIn` — every one of which plain SHACL reports as conforming. Companion to `onto_shacl` (open-world data validation) and `onto_shacl_check` (checks proposed shapes); this checks generated data. Follows the MCP-native validation-primitive convention.- **Causal (v0.5): `certify_action` × PyWhy integration.** Wires the #48 PyWhy scaffold into the live `certify_action` path. New `ActionFrame.identification_mode` field (`Structural` | `DoCalculusBackdoor`, default `Structural` for back-compat) selects which identifiability proof to attempt. New helper `build_causal_dag(graph, target_iris)` extracts a causal DAG from the loaded RDF graph: nodes = target IRIs + their one-hop structural neighbours (same slice CIVeX already hashes); edges = `rdfs:subClassOf` / `rdfs:subPropertyOf` / `rdfs:domain` / `rdfs:range` triples among slice members (treated as cause → effect); plus a synthetic `__utility__` sink downstream of every node. When `DoCalculusBackdoor` is requested AND the `causal-pywhy` Cargo feature is enabled, the verifier calls `civex_pywhy::run_pywhy_backdoor` and on success stamps the certificate's `identification_proof` with DoWhy's adjustment estimand + tags assumptions with `"do_calculus_backdoor"`. On any failure path (Python unavailable / DoWhy unavailable / DoWhy runtime error / target unidentifiable) the verifier **silently falls back to the structural proxy** and records the reason in assumptions as `"do_calculus_unavailable:<kind>"`. When the feature is off, the marker is `"do_calculus_unavailable:feature_disabled"`. The certificate's `identification_proof` field is never empty regardless of branch taken. MCP tool `onto_certify_action` gains `identification_mode: Option<String>` accepting `"structural"` (default) or `"do_calculus_backdoor"`. Two new integration tests in `tests/civex_test.rs`: `structural_mode_records_structural_only_assumption` (back-compat) and `do_calculus_mode_falls_back_to_structural_when_feature_disabled` (verifies the fallback path doesn't crash and records the marker). All 9 civex integration tests pass in both default and `causal-pywhy` build configurations; clippy clean across `--lib --tests --examples` in both configs.- **Causal: PyWhy/DoWhy backdoor identification subprocess scaffold (#48).** Scaffolds the Causal flagship's substantive v0.5 work without pulling Python into the default build. New optional Cargo feature `causal-pywhy` (off by default) enables a `src/civex_pywhy.rs` module that wraps DoWhy v0.13 as a subprocess — same pattern as `src/plan_classical.rs` does for Fast Downward. The wrapper embeds a self-contained Python driver (`PYWHY_PYTHON_DRIVER`) that reads `{nodes, edges, treatment, outcome}` from stdin, builds a `networkx` DiGraph, runs DoWhy's `identify_effect` for backdoor adjustment, and emits `{identifiable, adjustment_set, estimand_expression}` to stdout. Per the May 2026 roadmap memo: **Pearl–Shpitser ID is not ported to Rust** — DoWhy is a 15-year-stable Python implementation, so we wrap it. Honest behaviour when Python or DoWhy is missing: structured errors with `kind = "python_unavailable"` / `"pywhy_unavailable"` / `"dowhy_runtime_failed"` that the caller (eventually `certify_action` in v0.5) dispatches on to fall back to the structural proxy. Binary resolution order: explicit `python_override` → `PYTHON_BIN` env var → `python3` on PATH. **NOT yet integrated into `certify_action`** — the structural proxy (`"structural_only"` assumption) remains the only identifier in shipped certificates; integration tracks as the v0.5 ship. 9 unit tests cover parser cases (identifiable, unidentifiable, both error kinds, invalid JSON), python resolver (override + default + env var), embedded-driver sanity check, and `python_unavailable` behaviour on missing binary. Zero additional Rust dependencies — the entire feature is embedded Python + subprocess plumbing.- **Dynamics: non-deterministic outcomes for ActionSchema (#49).** `ActionSchema` gains an additive `outcomes: Vec<Outcome>` field. Each `Outcome` carries a categorical `probability` in `[0, 1]`, its own `effects: Vec<EffectSpec>` list, and an optional human-readable `label` (e.g. `"success"` / `"degraded"` / `"failure"`). When `outcomes` is non-empty, `apply()` samples one outcome and executes its effects; the deterministic `effects` field is ignored. When empty (the default), the schema behaves exactly as before — full back-compat with v0.4 base. Probabilities are validated: the sum must equal `1.0 ± 1e-6` or `apply()` returns an error; negative probabilities are also rejected. Sampling uses an inline xorshift64 PRNG keyed by a seed — **zero new dependencies**, no `rand`/`fastrand` pulled in. New method `ActionSchema::apply_with_seed(graph, db, bindings, seed)` exposes the seed for reproducible sampling; the default `apply()` derives a seed from `SystemTime::now()`. `ApplyResult` gains `sampled_outcome: Option<usize>` and `sampled_outcome_label: Option<String>` so callers can see which branch fired. `onto_action_apply` gains an optional `seed: Option<u64>` parameter — pass it when you need reproducible runs (CIVeX certification, replay-from-audit-log, controlled experiments). Tests (4 new): `nondeterministic_apply_with_seed_is_reproducible`, `nondeterministic_apply_distribution_matches_probabilities` (1000-call smoke check that a 70/30 split lands within `[0.60, 0.80]`), `nondeterministic_apply_rejects_invalid_probability_sum`, `deterministic_schema_still_works_when_outcomes_is_empty` (back-compat).diff --git a/CLAUDE.md b/CLAUDE.mdindex 8dc7294f..6340da39 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -69,6 +69,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_sql_ingest` | To run a SQL `SELECT` against PostgreSQL or DuckDB and ingest the result rows into RDF (uses the same mapping format as `onto_ingest`). DuckDB acts as a federation backbone via its `httpfs`/`parquet`/`csv`/`postgres_scanner`/`iceberg` extensions. Connection strings: `postgres://…`, `duckdb:///path.duckdb`, `:memory:`, or `*.duckdb` file path. || `onto_map` | To generate a mapping config from data schema + loaded ontology for review || `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) |+| `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` || `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples || `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call || `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |diff --git a/README.md b/README.mdindex 83736074..896b34a5 100644--- a/README.md+++ b/README.md@@ -685,7 +685,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T| **Marketplace** | `marketplace` | Browse and install 32 standard W3C/ISO/industry ontologies || **Remote** | `pull` `push` `import` | Fetch/push ontologies, resolve owl:imports || **Schema** | `import-schema` `sql-ingest` | Postgres + DuckDB → OWL + SQL → RDF ingest |-| **Data** | `map` `ingest` `shacl` `shacl_check` `reason` `extend` | Structured data → RDF pipeline |+| **Data** | `map` `ingest` `shacl` `shacl_check` `vocab_check` `reason` `extend` | Structured data → RDF pipeline; `vocab_check` = closed-world check that generated data uses only ontology-declared terms (catches what open-world SHACL misses) || **Versioning** | `version` `history` `rollback` | Named snapshots and rollback || **Lifecycle** | `plan` `apply` `lock` `drift` `enforce` `monitor` `monitor-clear` `lineage` | Terraform-style change management with webhook alerts and [OpenCheir](https://github.com/fabio-rovai/opencheir) governance integration || **Alignment** | `align` `align_feedback` `align_fuzzy` `align_flora` | Cross-ontology class matching with self-calibrating weights + fuzzy-logic adjudication and end-to-end signal-driven pipeline |diff --git a/src/batch.rs b/src/batch.rsindex e60f8ec2..da2c63d9 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -79,6 +79,7 @@ impl BatchRunner {"lint" => self.exec_lint(&cmd.args),"reason" => self.exec_reason(&cmd.args),"shacl" => self.exec_shacl(&cmd.args),+ "vocab_check" => self.exec_vocab_check(&cmd.args),"diff" => self.exec_diff(&cmd.args),"convert" => self.exec_convert(&cmd.args),"enforce" => self.exec_enforce(&cmd.args),@@ -201,6 +202,21 @@ impl BatchRunner {}}+ fn exec_vocab_check(&self, args: &[String]) -> Value {+ let data_path = match args.first() {+ Some(p) => p,+ None => return json!({"error": "vocab_check requires a data file path"}),+ };+ match std::fs::read_to_string(data_path) {+ Ok(data) => {+ let result = crate::vocab_check::check_data_vocab(&self.graph, &data, &[])+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ serde_json::from_str(&result).unwrap_or(json!({"raw": result}))+ }+ Err(e) => json!({"error": e.to_string()}),+ }+ }+fn exec_diff(&self, args: &[String]) -> Value {use crate::ontology::OntologyService;if args.len() < 2 {diff --git a/src/inputs.rs b/src/inputs.rsindex 4574ff15..65270734 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -231,6 +231,20 @@ pub struct OntoShaclCheckInput {pub inline: Option<bool>,}+#[derive(Deserialize, JsonSchema)]+pub struct OntoVocabCheckInput {+ /// Path to a Turtle DATA file OR inline Turtle content to check against the+ /// currently loaded ontology. Every predicate and every `rdf:type` class used+ /// in the data, whose namespace belongs to the ontology, must be DECLARED in+ /// the ontology — otherwise it is reported as a hallucinated/undeclared term.+ pub data: String,+ /// If true, treat `data` as inline Turtle content (default false = file path).+ pub inline: Option<bool>,+ /// Optional extra namespaces to police, beyond the ontology's own namespaces+ /// (e.g. an imported vocabulary you also want closed-world-checked).+ pub namespaces: Option<Vec<String>>,+}+#[derive(Deserialize, JsonSchema)]pub struct OntoReasonInput {/// Reasoning profile: rdfs (default), owl-rldiff --git a/src/lib.rs b/src/lib.rsindex 6ee09426..b785a5f5 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -62,6 +62,7 @@ pub mod socket;pub mod socket;pub mod sql_sync;pub mod sqlsource;+pub mod vocab_check;pub mod state;#[cfg(feature = "embeddings")]pub mod structembed;diff --git a/src/main.rs b/src/main.rsindex 2b3e49ee..becfaf87 100644--- a/src/main.rs+++ b/src/main.rs@@ -377,6 +377,8 @@ enum Commands {},/// Validate against SHACL shapesShacl { shapes: String },+ /// Closed-world vocab check: flag data terms not declared in the loaded ontology+ VocabCheck { data: String },/// Run inference (rdfs, owl-rl, owl-rl-ext, owl-dl)Reason {#[arg(long, default_value = "rdfs")]@@ -1650,6 +1652,13 @@ async fn async_main() -> anyhow::Result<()> {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result(&result, cli.pretty);}+ Commands::VocabCheck { data } => {+ let (_db, graph) = setup(&cli.data_dir)?;+ let data_content = std::fs::read_to_string(&data)?;+ let result = open_ontologies::vocab_check::check_data_vocab(&graph, &data_content, &[])+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ output_result(&result, cli.pretty);+ }Commands::Reason { profile } => {use open_ontologies::reason::Reasoner;let (_db, graph) = setup(&cli.data_dir)?;diff --git a/src/server.rs b/src/server.rsindex 85c0142f..9bfd6257 100644--- a/src/server.rs+++ b/src/server.rs@@ -931,6 +931,20 @@ impl OpenOntologiesServer {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))}+ #[tool(name = "onto_vocab_check", description = "Closed-world vocabulary check on a Turtle DATA graph: verify that every predicate and every rdf:type class used in the data is actually DECLARED in the loaded ontology. Catches hallucinated/undeclared terms — e.g. an LLM emitting `ies:hasDeparturePort` when the ontology only defines `ies:scheduledDeparturePort`. This is the gate open-world SHACL structurally CANNOT provide: SHACL silently ignores predicates it has no shape for, so a graph full of invented terms still reports conforms=true. Only IRIs whose namespace belongs to the ontology (plus any passed in `namespaces`) are policed; standard rdf/rdfs/owl/xsd/sh vocabulary and your instance-data IRIs are never flagged. Returns {conforms, hallucinated_terms, checked_namespaces}. Companion to `onto_shacl` (open-world structural validation of data) and `onto_shacl_check` (checks proposed SHACL shapes); run this on generated data to catch fabricated vocabulary before it enters the store.")]+ async fn onto_vocab_check(&self, Parameters(input): Parameters<OntoVocabCheckInput>) -> String {+ let data = if input.inline.unwrap_or(false) {+ input.data.clone()+ } else {+ match std::fs::read_to_string(&input.data) {+ Ok(c) => c,+ Err(e) => return format!(r#"{{"error":"Cannot read data file: {}"}}"#, e),+ }+ };+ let extra = input.namespaces.clone().unwrap_or_default();+ crate::vocab_check::check_data_vocab(&self.graph, &data, &extra)+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))+ }#[tool(name = "onto_align_flora", description = "End-to-end FLORA alignment (#38). Takes the currently-loaded graph as source and a Turtle string for target, enumerates plausible class-pairs (pre-filtered by shared label tokens), extracts the four FLORA signals per pair (label Jaccard, parent overlap, sibling overlap, datatype overlap) from the structural neighbourhood, runs the 10-rule Mamdani inference engine, and returns only the accept-verdict pairs. Companion to `onto_align_fuzzy` (per-pair adjudication when you already have signals).")]async fn onto_align_flora(&self, Parameters(input): Parameters<OntoAlignFloraInput>) -> String {diff --git a/src/toolfilter.rs b/src/toolfilter.rsindex efb2eb8e..959c875c 100644--- a/src/toolfilter.rs+++ b/src/toolfilter.rs@@ -157,6 +157,7 @@ pub fn expand_group(name: &str) -> &'static [&'static str] {"onto_sql_ingest","onto_map","onto_shacl",+ "onto_vocab_check","onto_reason","onto_extend","onto_unload",diff --git a/src/vocab_check.rs b/src/vocab_check.rsnew file mode 100644index 00000000..bf75b27d--- /dev/null+++ b/src/vocab_check.rs@@ -0,0 +1,243 @@+//! Closed-world vocabulary check for generated DATA graphs (#vocab).+//!+//! The gap this fills: SHACL is **open-world**. It silently ignores any predicate+//! or class it has no shape for, so a data graph full of *invented* terms+//! (`ies:hasDeparturePort` where the ontology only defines+//! `ies:scheduledDeparturePort`) still reports `conforms = true`. For checking+//! LLM-generated RDF that is nearly useless — the model can hallucinate a+//! plausible-but-undeclared term and every open-world validator waves it through.+//!+//! `check_data_vocab` runs the complementary CLOSED-WORLD gate: every predicate+//! and every `rdf:type` object in the data whose namespace belongs to the ontology+//! must be *declared* in the ontology. Standard `rdf`/`rdfs`/`owl`/`xsd`/`sh`+//! vocabulary and the caller's own instance-data IRIs are never policed.+//!+//! This mirrors `shacl::check_shapes` (which checks that proposed SHACL references+//! real terms) but points the same idea at generated data instead of shapes.++use crate::graph::GraphStore;+use serde::Serialize;+use std::collections::BTreeSet;+use std::sync::Arc;++/// Namespaces that are always allowed and never flagged.+const STD_NS: &[&str] = &[+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#",+ "http://www.w3.org/2000/01/rdf-schema#",+ "http://www.w3.org/2002/07/owl#",+ "http://www.w3.org/2001/XMLSchema#",+ "http://www.w3.org/ns/shacl#",+ "http://www.w3.org/2004/02/skos/core#",+];++#[derive(Serialize)]+pub struct VocabReport {+ /// True iff an ontology was present AND no hallucinated terms were found.+ pub conforms: bool,+ /// Terms used in the data, in a policed namespace, but not declared in the ontology.+ pub hallucinated_terms: Vec<String>,+ /// The namespaces that were policed (ontology's own namespaces + any caller-supplied).+ pub checked_namespaces: Vec<String>,+ pub predicates_checked: usize,+ pub types_checked: usize,+ pub ontology_terms: usize,+ /// Set when the check could not be performed meaningfully (e.g. no ontology loaded).+ /// A closed-world check with no ontology must NEVER silently pass.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub warning: Option<String>,+}++/// Namespace of an IRI: everything up to and including the last `#` or `/`.+fn ns_of(iri: &str) -> String {+ match iri.rfind(['#', '/']) {+ Some(i) => iri[..=i].to_string(),+ None => iri.to_string(),+ }+}++/// Strip surrounding `<>` (oxigraph Display wraps NamedNodes in angle brackets).+fn strip_brackets(s: &str) -> &str {+ let s = s.trim();+ s.strip_prefix('<')+ .and_then(|s| s.strip_suffix('>'))+ .unwrap_or(s)+}++/// Run a SELECT and collect the IRI values of one variable (literals/blanks skipped).+fn select_iris(graph: &Arc<GraphStore>, query: &str, var: &str) -> anyhow::Result<Vec<String>> {+ let json_str = graph.sparql_select(query)?;+ let parsed: serde_json::Value = serde_json::from_str(&json_str)?;+ let mut out = Vec::new();+ if let Some(rows) = parsed["results"].as_array() {+ for row in rows {+ if let Some(v) = row.get(var).and_then(|v| v.as_str()) {+ let iri = strip_brackets(v);+ if iri.starts_with("http://") || iri.starts_with("https://") {+ out.push(iri.to_string());+ }+ }+ }+ }+ Ok(out)+}++const CLASS_OR_PROP_FILTER: &str = r#"FILTER(+ ?k = <http://www.w3.org/2002/07/owl#Class>+ || ?k = <http://www.w3.org/2000/01/rdf-schema#Class>+ || ?k = <http://www.w3.org/2002/07/owl#ObjectProperty>+ || ?k = <http://www.w3.org/2002/07/owl#DatatypeProperty>+ || ?k = <http://www.w3.org/2002/07/owl#AnnotationProperty>+ || ?k = <http://www.w3.org/2002/07/owl#FunctionalProperty>+ || ?k = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>+ || ?k = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>)"#;++const DEFINED_BY_AXIOM_FILTER: &str = r#"FILTER(+ ?p = <http://www.w3.org/2000/01/rdf-schema#domain>+ || ?p = <http://www.w3.org/2000/01/rdf-schema#range>+ || ?p = <http://www.w3.org/2000/01/rdf-schema#subClassOf>+ || ?p = <http://www.w3.org/2000/01/rdf-schema#subPropertyOf>)"#;++/// Closed-world vocabulary check of `data_ttl` against the loaded ontology `onto`.+/// `extra_ns` adds namespaces to police beyond the ontology's own.+/// Returns a JSON `VocabReport`.+pub fn check_data_vocab(+ onto: &Arc<GraphStore>,+ data_ttl: &str,+ extra_ns: &[String],+) -> anyhow::Result<String> {+ // 1. Parse the data into an isolated store (parse errors surface here).+ let data = Arc::new(GraphStore::new());+ data.load_turtle(data_ttl, None)+ .map_err(|e| anyhow::anyhow!("data failed to parse as Turtle: {e}"))?;++ // 2. The ontology's declared vocabulary (full IRIs): typed classes/properties+ // plus anything given a domain/range/subClassOf/subPropertyOf axiom.+ let mut onto_terms: BTreeSet<String> = BTreeSet::new();+ for t in select_iris(+ onto,+ &format!("SELECT DISTINCT ?t WHERE {{ ?t a ?k . {CLASS_OR_PROP_FILTER} }}"),+ "t",+ )? {+ onto_terms.insert(t);+ }+ for t in select_iris(+ onto,+ &format!("SELECT DISTINCT ?t WHERE {{ ?t ?p ?o . {DEFINED_BY_AXIOM_FILTER} }}"),+ "t",+ )? {+ onto_terms.insert(t);+ }++ // Guard: a closed-world check with no ontology vocabulary must never silently+ // pass — that is exactly the vacuous-conformance footgun this tool exists to kill.+ if onto_terms.is_empty() && extra_ns.is_empty() {+ let report = VocabReport {+ conforms: false,+ hallucinated_terms: Vec::new(),+ checked_namespaces: Vec::new(),+ predicates_checked: 0,+ types_checked: 0,+ ontology_terms: 0,+ warning: Some(+ "no ontology vocabulary found (0 declared terms) — load an ontology \+ first, or pass `namespaces` to police; nothing was checked"+ .to_string(),+ ),+ };+ return Ok(serde_json::to_string(&report)?);+ }++ // 3. Namespaces to police: the ontology's own, plus caller-supplied, minus standard.+ let mut checked: BTreeSet<String> = onto_terms.iter().map(|t| ns_of(t)).collect();+ checked.extend(extra_ns.iter().cloned());+ for std in STD_NS {+ checked.remove(*std);+ }++ // 4. Terms actually used in the data: every predicate + every asserted class.+ let preds = select_iris(&data, "SELECT DISTINCT ?p WHERE { ?s ?p ?o }", "p")?;+ let types = select_iris(&data, "SELECT DISTINCT ?c WHERE { ?s a ?c }", "c")?;++ // 5. Flag any policed-namespace term not declared in the ontology.+ let mut bad: BTreeSet<String> = BTreeSet::new();+ for iri in preds.iter().chain(types.iter()) {+ if checked.contains(&ns_of(iri)) && !onto_terms.contains(iri) {+ bad.insert(iri.clone());+ }+ }++ let report = VocabReport {+ conforms: bad.is_empty(),+ hallucinated_terms: bad.into_iter().collect(),+ checked_namespaces: checked.into_iter().collect(),+ predicates_checked: preds.len(),+ types_checked: types.len(),+ ontology_terms: onto_terms.len(),+ warning: None,+ };+ Ok(serde_json::to_string(&report)?)+}++#[cfg(test)]+mod tests {+ use super::*;++ const ONTO: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://example.org/onto#> .+ ex:Person a owl:Class .+ ex:Airport a owl:Class .+ ex:worksFor a owl:ObjectProperty ; rdfs:domain ex:Person .+ ex:scheduledDeparturePort a owl:ObjectProperty .+ "#;++ fn onto() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(ONTO, None).unwrap();+ g+ }++ #[test]+ fn clean_data_conforms() {+ let data = r#"+ @prefix ex: <http://example.org/onto#> .+ @prefix d: <http://data.example/> .+ d:Alice a ex:Person ; ex:worksFor d:Acme .+ "#;+ let out = check_data_vocab(&onto(), data, &[]).unwrap();+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert_eq!(v["conforms"], true, "clean data should conform: {out}");+ }++ #[test]+ fn hallucinated_predicate_is_caught() {+ // ex:hasDeparturePort is NOT declared; open-world SHACL would miss it.+ let data = r#"+ @prefix ex: <http://example.org/onto#> .+ @prefix d: <http://data.example/> .+ d:Flight a ex:Airport ; ex:hasDeparturePort d:LHR .+ "#;+ let out = check_data_vocab(&onto(), data, &[]).unwrap();+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert_eq!(v["conforms"], false, "should flag undeclared term: {out}");+ let bad = v["hallucinated_terms"].as_array().unwrap();+ assert!(+ bad.iter().any(|t| t.as_str().unwrap().ends_with("hasDeparturePort")),+ "hasDeparturePort should be flagged: {out}"+ );+ }++ #[test]+ fn instance_and_standard_ns_not_flagged() {+ // d: instances and rdf:type must never be flagged.+ let data = r#"+ @prefix ex: <http://example.org/onto#> .+ @prefix d: <http://data.example/> .+ d:Bob a ex:Person .+ "#;+ let out = check_data_vocab(&onto(), data, &[]).unwrap();+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert_eq!(v["conforms"], true, "instance IRIs must not be policed: {out}");+ }+}