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(python): SHACL validation, the extra that was declared but never wired
FABIOTESS26a7572c9479
diff --git a/python/README.md b/python/README.mdindex b7f0a7e7..24919ad2 100644--- a/python/README.md+++ b/python/README.md@@ -99,6 +99,7 @@ Register it with any MCP client (e.g. Claude):| `onto_diff` | Triple-level diff between two ontologies || `onto_kgcl_diff` | KGCL change records between two versions (governance / change logs) || `onto_lint` | Missing labels, domains, ranges |+| `onto_shacl` | SHACL conformance: violations with focus node, path, value, severity and constraint (needs the `[shacl]` extra) |## Relationship to the Rust enginediff --git a/python/pyproject.toml b/python/pyproject.tomlindex bb22ad07..c6daad93 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "open-ontologies-lite"-version = "0.2.0"+version = "0.3.0"description = "Lightweight Python bridge to the Oxigraph RDF/OWL engine, MCP server included. No Rust toolchain, no compilation."readme = "README.md"requires-python = ">=3.10"diff --git a/python/src/open_ontologies_lite/__init__.py b/python/src/open_ontologies_lite/__init__.pyindex 9b23b689..e247eedb 100644--- a/python/src/open_ontologies_lite/__init__.py+++ b/python/src/open_ontologies_lite/__init__.py@@ -5,7 +5,7 @@ Oxigraph RDF/OWL engine. No Rust toolchain, no compilation, prebuilt wheels onlyfrom .engine import OntologyEngine, ValidationResult, resolve_formatfrom .kgcl import ChangeSet, kgcl_diff-__version__ = "0.2.0"+__version__ = "0.3.0"__all__ = ["OntologyEngine","ValidationResult",diff --git a/python/src/open_ontologies_lite/engine.py b/python/src/open_ontologies_lite/engine.pyindex 6cc55fc0..6a09a98c 100644--- a/python/src/open_ontologies_lite/engine.py+++ b/python/src/open_ontologies_lite/engine.py@@ -139,6 +139,11 @@ class OntologyEngine:_dump(self.store, str(p), rdf_format)return str(p)+ def dump(self, fmt: str = "turtle") -> str:+ """Serialize the loaded store to a string (needed to hand it to pySHACL)."""+ out = _dump(self.store, None, resolve_format(fmt))+ return out.decode("utf-8") if isinstance(out, (bytes, bytearray)) else str(out)+@staticmethoddef convert(data: str, from_fmt: str, to_fmt: str) -> str:tmp = ox.Store()diff --git a/python/src/open_ontologies_lite/server.py b/python/src/open_ontologies_lite/server.pyindex 653c94fb..6aabf5cf 100644--- a/python/src/open_ontologies_lite/server.py+++ b/python/src/open_ontologies_lite/server.py@@ -100,6 +100,26 @@ def onto_kgcl_diff(data_a: str, data_b: str, format: str = "turtle") -> dict:return {"changes": cs.changes, "counts": cs.counts(), "kgcl": cs.to_kgcl()}+def onto_shacl(+ shapes: str, shapes_format: str = "turtle", inference: str | None = None+) -> dict:+ """Validate the loaded graph against SHACL shapes.++ Returns conformance plus each violation's focus node, path, offending value,+ message, severity and the constraint component that produced it. `inference`+ ("rdfs", "owlrl", "both") is off by default, because materialising+ entailments changes what counts as a violation.++ Needs the optional extra: pip install "open-ontologies-lite[shacl]"+ """+ from .shacl import shacl_validate++ return shacl_validate(+ _engine.dump(), shapes, shapes_format=shapes_format, inference=inference+ )++def main() -> None:import argparsediff --git a/python/src/open_ontologies_lite/shacl.py b/python/src/open_ontologies_lite/shacl.pynew file mode 100644index 00000000..17cb9450--- /dev/null+++ b/python/src/open_ontologies_lite/shacl.py@@ -0,0 +1,90 @@+"""SHACL validation over the loaded graph.++Conformance is the question SHACL answers: is this data shaped the way the+model says it must be. The package owns the validation call and the report+parsing; deciding what to do about a violation is the orchestrator's job, as+everywhere else here.++Requires the optional extra: pip install "open-ontologies-lite[shacl]"++Reference: pySHACL, https://github.com/RDFLib/pySHACL+"""++from __future__ import annotations++SH = "http://www.w3.org/ns/shacl#"+++def _require_pyshacl():+ try:+ import pyshacl # noqa: F401++ return pyshacl+ except ImportError as exc: # pragma: no cover - exercised by the extra being absent+ raise ImportError(+ "SHACL validation needs the optional extra: "+ 'pip install "open-ontologies-lite[shacl]"'+ ) from exc+++def _local(term: str) -> str:+ """Strip a SHACL namespace prefix so severities read as Violation/Warning/Info."""+ return term[len(SH) :] if term.startswith(SH) else term+++def shacl_validate(+ data: str,+ shapes: str,+ *,+ data_format: str = "turtle",+ shapes_format: str = "turtle",+ inference: str | None = None,+) -> dict:+ """Validate `data` against `shapes` and return a structured report.++ `inference` is passed through to pySHACL ("rdfs", "owlrl", "both" or None).+ Inference is off by default: materialising entailments changes what counts+ as a violation, and that should be an explicit choice rather than a silent+ default.+ """+ pyshacl = _require_pyshacl()+ import rdflib++ conforms, results_graph, results_text = pyshacl.validate(+ data,+ shacl_graph=shapes,+ data_graph_format=data_format,+ shacl_graph_format=shapes_format,+ inference=inference,+ advanced=True,+ )++ sh = rdflib.Namespace(SH)+ violations: list[dict] = []+ for result in results_graph.subjects(rdflib.RDF.type, sh.ValidationResult):+ get = lambda p: results_graph.value(result, p) # noqa: E731+ severity = get(sh.resultSeverity)+ violations.append(+ {+ "focus_node": str(get(sh.focusNode) or ""),+ "path": str(get(sh.resultPath) or ""),+ "value": str(get(sh.value) or ""),+ "message": str(get(sh.resultMessage) or ""),+ "severity": _local(str(severity)) if severity else "Violation",+ "source_shape": str(get(sh.sourceShape) or ""),+ "constraint": _local(str(get(sh.sourceConstraintComponent) or "")),+ }+ )++ violations.sort(key=lambda v: (v["focus_node"], v["path"], v["constraint"]))+ by_severity: dict[str, int] = {}+ for v in violations:+ by_severity[v["severity"]] = by_severity.get(v["severity"], 0) + 1++ return {+ "conforms": bool(conforms),+ "count": len(violations),+ "by_severity": by_severity,+ "violations": violations,+ "text": results_text,+ }diff --git a/python/tests/test_shacl.py b/python/tests/test_shacl.pynew file mode 100644index 00000000..44817e61--- /dev/null+++ b/python/tests/test_shacl.py@@ -0,0 +1,65 @@+import pytest++from open_ontologies_lite import OntologyEngine++pytest.importorskip("pyshacl", reason="needs the [shacl] extra")++from open_ontologies_lite.shacl import shacl_validate # noqa: E402++SHAPES = """+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+@prefix ex: <http://example.org/> .++ex:PersonShape a sh:NodeShape ;+ sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:datatype xsd:string ;+ sh:message "A Person needs exactly one string name." ] .+"""++CONFORMING = """+@prefix ex: <http://example.org/> .+ex:ada a ex:Person ; ex:name "Ada" .+"""++VIOLATING = """+@prefix ex: <http://example.org/> .+ex:ada a ex:Person .+"""+++def test_conforming_data_reports_no_violations():+ report = shacl_validate(CONFORMING, SHAPES)+ assert report["conforms"] is True+ assert report["count"] == 0+ assert report["violations"] == []+++def test_violation_is_reported_with_focus_node_and_message():+ report = shacl_validate(VIOLATING, SHAPES)+ assert report["conforms"] is False+ assert report["count"] == 1+ v = report["violations"][0]+ assert v["focus_node"] == "http://example.org/ada"+ assert v["path"] == "http://example.org/name"+ assert "name" in v["message"]+ assert v["severity"] == "Violation"+ assert v["constraint"] == "MinCountConstraintComponent"+ assert report["by_severity"] == {"Violation": 1}+++def test_validates_the_loaded_store_via_dump():+ """The path the MCP tool actually takes: store -> dump -> pySHACL."""+ eng = OntologyEngine()+ eng.load(VIOLATING)+ report = shacl_validate(eng.dump(), SHAPES)+ assert report["conforms"] is False+ assert report["violations"][0]["focus_node"] == "http://example.org/ada"+++def test_dump_roundtrips_through_the_store():+ eng = OntologyEngine()+ eng.load(CONFORMING)+ dumped = eng.dump()+ again = OntologyEngine()+ assert again.load(dumped) == 2