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(drift): emit KGCL change-language output for onto_drift (#19)
Fabio Rovai964ce23698b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d556ae8..606aefee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **KGCL output format for `onto_drift`** (#17). The drift detector can now emit results in the [Knowledge Graph Change Language](https://github.com/INCATools/kgcl) (Mungall et al., Database 2025, doi:10.1093/database/baae133) alongside the existing JSON. Two new format options on the MCP tool: `format = "kgcl"` produces line-oriented CNL (`create node <iri>`, `obsolete node <iri>`, `obsolete node <iri> with replacement <iri>`) consumed by ROBOT and BioPortal; `format = "kgcl_json"` produces structured JSON-LD. High-confidence likely_renames (above `rename_threshold`, default 0.7) collapse into a `NodeObsoletion` with `has_direct_replacement` instead of plain add+remove pairs. New module `src/kgcl.rs` with 8 unit tests plus `tests/kgcl_drift_test.rs` integration suite.- **DuckDB SQL data backbone**. New optional `duckdb` Cargo feature (and `sql` umbrella combining `postgres` + `duckdb`) wires DuckDB in alongside PostgreSQL as a *data integration* backbone — not as a SPARQL parser. DuckDB's extensions (`httpfs`, `parquet`, `csv`, `json`, `postgres_scanner`, `iceberg`, `delta`, …) let one SQL query federate over remote files, object stores, and other databases; rows then flow into the existing mapping/SHACL/reason pipeline.- **New MCP tool `onto_sql_ingest`** — runs a SQL `SELECT` against PostgreSQL or DuckDB and ingests result rows into the triple store using the same `MappingConfig` shape as `onto_ingest`. Connection-string scheme is auto-detected (`postgres://`, `postgresql://`, `duckdb://`, `:memory:`, or a `*.duckdb` / `*.ddb` file path).- **New CLI command `sql-ingest`** mirroring the MCP tool, with `--mapping`, `--inline-mapping`, `--base-iri`, and `-` (stdin) for the SQL.diff --git a/src/drift.rs b/src/drift.rsindex 26409038..ed51f0a3 100644--- a/src/drift.rs+++ b/src/drift.rs@@ -76,6 +76,20 @@ impl DriftDetector {Ok(result.to_string())}+ /// Detect drift and convert to a KGCL change report (high-level semantic format).+ /// `rename_threshold` controls when a likely_rename becomes an obsoletion-with-replacement+ /// (default 0.7 is a reasonable starting point).+ pub fn detect_kgcl(+ &self,+ v1_turtle: &str,+ v2_turtle: &str,+ rename_threshold: f64,+ ) -> anyhow::Result<crate::kgcl::KgclReport> {+ let json_str = self.detect(v1_turtle, v2_turtle)?;+ let json: serde_json::Value = serde_json::from_str(&json_str)?;+ Ok(crate::kgcl::drift_to_kgcl(&json, rename_threshold))+ }+/// Record feedback for a rename prediction.#[allow(clippy::too_many_arguments)]pub fn record_feedback(diff --git a/src/inputs.rs b/src/inputs.rsindex 325a7800..1a29a6f9 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -279,6 +279,16 @@ pub struct OntoDriftInput {pub version_a: String,/// Second version as inline Turtlepub version_b: String,+ /// Output format. One of: "json" (default, existing schema with added/removed/likely_renames),+ /// "kgcl" (KGCL Controlled Natural Language, one change per line),+ /// "kgcl_json" (KGCL changes as structured JSON-LD).+ #[serde(default)]+ pub format: Option<String>,+ /// Confidence threshold above which a likely_rename is emitted as a KGCL+ /// obsoletion-with-replacement instead of a plain add+remove pair. Default 0.7.+ /// Only consulted when `format` is "kgcl" or "kgcl_json".+ #[serde(default)]+ pub rename_threshold: Option<f64>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/kgcl.rs b/src/kgcl.rsnew file mode 100644index 00000000..af75e2d1--- /dev/null+++ b/src/kgcl.rs@@ -0,0 +1,365 @@+//! KGCL (Knowledge Graph Change Language) serialization for drift reports.+//!+//! Spec: <https://github.com/INCATools/kgcl>+//! Paper: Mungall et al., Database (Oxford) 2025, doi:10.1093/database/baae133+//!+//! Maps `DriftDetector::detect` output to KGCL change records. Two surface forms:+//! - **CNL** (Controlled Natural Language) — line-oriented, consumed by ROBOT and BioPortal+//! - **JSON-LD-style structured** — for machine consumers / replay tooling++use serde::{Deserialize, Serialize};++/// A single KGCL change. We model only the subset the drift detector can produce.+/// Other KGCL types (NodeMove, NewSynonym, EdgeChange, etc.) are out of scope here —+/// the drift detector compares class/property vocabularies, not edges or annotations.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(tag = "type")]+pub enum KgclChange {+ /// Creation of a new node (class or property). KGCL: `NodeCreation`.+ NodeCreation {+ id: String,+ about_node: String,+ /// "class" or "property" — informational, not part of core KGCL.+ node_kind: String,+ },+ /// Deprecation of a node, optionally pointing to a replacement.+ /// KGCL: `NodeObsoletion` (with optional `has_direct_replacement`).+ NodeObsoletion {+ id: String,+ about_node: String,+ node_kind: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ has_direct_replacement: Option<String>,+ /// Confidence carried from drift detector when this change came from a likely-rename.+ /// Stored in the KGCL `change_description` slot when serialised; surfaced as a field for tooling.+ #[serde(skip_serializing_if = "Option::is_none")]+ confidence: Option<f64>,+ },+}++impl KgclChange {+ /// Render this change as KGCL CNL (Controlled Natural Language).+ ///+ /// Grammar (from KGCL paper §4):+ /// - `create <kind> <iri>`+ /// - `obsolete <kind> <iri>`+ /// - `obsolete <kind> <iri> with replacement <iri>`+ pub fn to_cnl(&self) -> String {+ match self {+ KgclChange::NodeCreation { about_node, node_kind, .. } => {+ format!("create {} <{}>", node_kind, about_node)+ }+ KgclChange::NodeObsoletion {+ about_node,+ node_kind,+ has_direct_replacement: Some(repl),+ ..+ } => {+ format!(+ "obsolete {} <{}> with replacement <{}>",+ node_kind, about_node, repl+ )+ }+ KgclChange::NodeObsoletion {+ about_node,+ node_kind,+ has_direct_replacement: None,+ ..+ } => {+ format!("obsolete {} <{}>", node_kind, about_node)+ }+ }+ }+}++/// A bundle of KGCL changes representing a drift between two ontology versions.+#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct KgclReport {+ pub changes: Vec<KgclChange>,+}++impl KgclReport {+ /// CNL representation, one change per line.+ pub fn to_cnl(&self) -> String {+ self.changes+ .iter()+ .map(|c| c.to_cnl())+ .collect::<Vec<_>>()+ .join("\n")+ }++ /// Structured JSON representation (for machine consumers).+ pub fn to_json(&self) -> serde_json::Value {+ serde_json::json!({+ "@context": "http://w3id.org/kgcl/",+ "changes": self.changes,+ })+ }+}++/// Convert a drift report (the JSON `DriftDetector::detect` returns) into KGCL changes.+///+/// `rename_confidence_threshold`: likely_renames with confidence ≥ threshold are emitted as+/// `NodeObsoletion(old) with replacement(new)` + `NodeCreation(new)`, and the involved IRIs are+/// removed from the plain added/removed lists to avoid double-counting. Renames below threshold+/// fall through to plain Creation/Obsoletion pairs.+pub fn drift_to_kgcl(+ drift_json: &serde_json::Value,+ rename_confidence_threshold: f64,+) -> KgclReport {+ let mut changes = Vec::new();+ let mut next_id = 1u32;+ let mut next_id_fn = move || {+ let id = format!("kgcl_change_{:04}", next_id);+ next_id += 1;+ id+ };++ let added: Vec<String> = drift_json["added"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ })+ .unwrap_or_default();+ let removed: Vec<String> = drift_json["removed"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ })+ .unwrap_or_default();++ // Pull confident renames first, deduplicating against added/removed.+ let mut consumed_added = std::collections::HashSet::new();+ let mut consumed_removed = std::collections::HashSet::new();++ if let Some(renames) = drift_json["likely_renames"].as_array() {+ for r in renames {+ let confidence = r["confidence"].as_f64().unwrap_or(0.0);+ if confidence < rename_confidence_threshold {+ continue;+ }+ let from = match r["from"].as_str() {+ Some(s) => s.to_string(),+ None => continue,+ };+ let to = match r["to"].as_str() {+ Some(s) => s.to_string(),+ None => continue,+ };+ // First confident rename for this (from, to) wins — sorted by confidence desc upstream.+ if consumed_removed.contains(&from) || consumed_added.contains(&to) {+ continue;+ }+ consumed_removed.insert(from.clone());+ consumed_added.insert(to.clone());++ changes.push(KgclChange::NodeObsoletion {+ id: next_id_fn(),+ about_node: from,+ node_kind: "node".to_string(),+ has_direct_replacement: Some(to.clone()),+ confidence: Some(confidence),+ });+ changes.push(KgclChange::NodeCreation {+ id: next_id_fn(),+ about_node: to,+ node_kind: "node".to_string(),+ });+ }+ }++ for iri in &removed {+ if consumed_removed.contains(iri) {+ continue;+ }+ changes.push(KgclChange::NodeObsoletion {+ id: next_id_fn(),+ about_node: iri.clone(),+ node_kind: "node".to_string(),+ has_direct_replacement: None,+ confidence: None,+ });+ }++ for iri in &added {+ if consumed_added.contains(iri) {+ continue;+ }+ changes.push(KgclChange::NodeCreation {+ id: next_id_fn(),+ about_node: iri.clone(),+ node_kind: "node".to_string(),+ });+ }++ KgclReport { changes }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn cnl_creation() {+ let c = KgclChange::NodeCreation {+ id: "kgcl_change_0001".to_string(),+ about_node: "http://example.org/Cat".to_string(),+ node_kind: "class".to_string(),+ };+ assert_eq!(c.to_cnl(), "create class <http://example.org/Cat>");+ }++ #[test]+ fn cnl_obsoletion_no_replacement() {+ let c = KgclChange::NodeObsoletion {+ id: "kgcl_change_0001".to_string(),+ about_node: "http://example.org/Dog".to_string(),+ node_kind: "class".to_string(),+ has_direct_replacement: None,+ confidence: None,+ };+ assert_eq!(c.to_cnl(), "obsolete class <http://example.org/Dog>");+ }++ #[test]+ fn cnl_obsoletion_with_replacement() {+ let c = KgclChange::NodeObsoletion {+ id: "kgcl_change_0001".to_string(),+ about_node: "http://example.org/authoredBy".to_string(),+ node_kind: "property".to_string(),+ has_direct_replacement: Some("http://example.org/writtenBy".to_string()),+ confidence: Some(0.91),+ };+ assert_eq!(+ c.to_cnl(),+ "obsolete property <http://example.org/authoredBy> with replacement <http://example.org/writtenBy>"+ );+ }++ #[test]+ fn drift_to_kgcl_plain_add_remove() {+ let drift = json!({+ "added": ["http://example.org/Bird"],+ "removed": ["http://example.org/Cat"],+ "likely_renames": [],+ });+ let report = drift_to_kgcl(&drift, 0.7);+ assert_eq!(report.changes.len(), 2);+ // Order: obsoletions first, then creations.+ assert!(matches!(report.changes[0], KgclChange::NodeObsoletion { .. }));+ assert!(matches!(report.changes[1], KgclChange::NodeCreation { .. }));++ let cnl = report.to_cnl();+ assert!(cnl.contains("obsolete node <http://example.org/Cat>"));+ assert!(cnl.contains("create node <http://example.org/Bird>"));+ }++ #[test]+ fn drift_to_kgcl_high_confidence_rename_collapses() {+ let drift = json!({+ "added": ["http://example.org/writtenBy"],+ "removed": ["http://example.org/authoredBy"],+ "likely_renames": [{+ "from": "http://example.org/authoredBy",+ "to": "http://example.org/writtenBy",+ "confidence": 0.91,+ "predicted": "rename",+ "signals": {}+ }],+ });+ let report = drift_to_kgcl(&drift, 0.7);+ // Exactly one obsoletion-with-replacement + one creation; no duplicate plain entries.+ assert_eq!(report.changes.len(), 2);+ match &report.changes[0] {+ KgclChange::NodeObsoletion {+ about_node,+ has_direct_replacement: Some(repl),+ confidence: Some(c),+ ..+ } => {+ assert_eq!(about_node, "http://example.org/authoredBy");+ assert_eq!(repl, "http://example.org/writtenBy");+ assert!((c - 0.91).abs() < 1e-9);+ }+ other => panic!("expected NodeObsoletion with replacement, got {:?}", other),+ }+ match &report.changes[1] {+ KgclChange::NodeCreation { about_node, .. } => {+ assert_eq!(about_node, "http://example.org/writtenBy");+ }+ other => panic!("expected NodeCreation, got {:?}", other),+ }++ let cnl = report.to_cnl();+ assert!(cnl.contains(+ "obsolete node <http://example.org/authoredBy> with replacement <http://example.org/writtenBy>"+ ));+ }++ #[test]+ fn drift_to_kgcl_low_confidence_rename_does_not_collapse() {+ let drift = json!({+ "added": ["http://example.org/writtenBy"],+ "removed": ["http://example.org/authoredBy"],+ "likely_renames": [{+ "from": "http://example.org/authoredBy",+ "to": "http://example.org/writtenBy",+ "confidence": 0.35,+ "predicted": "rename",+ "signals": {}+ }],+ });+ let report = drift_to_kgcl(&drift, 0.7);+ // Below threshold — plain obsoletion + plain creation, no replacement link.+ assert_eq!(report.changes.len(), 2);+ match &report.changes[0] {+ KgclChange::NodeObsoletion {+ has_direct_replacement: None,+ confidence: None,+ ..+ } => {}+ other => panic!("expected plain NodeObsoletion, got {:?}", other),+ }+ }++ #[test]+ fn drift_to_kgcl_id_uniqueness() {+ let drift = json!({+ "added": ["http://example.org/A", "http://example.org/B"],+ "removed": ["http://example.org/X", "http://example.org/Y"],+ "likely_renames": [],+ });+ let report = drift_to_kgcl(&drift, 0.7);+ let mut ids: Vec<&str> = report+ .changes+ .iter()+ .map(|c| match c {+ KgclChange::NodeCreation { id, .. } => id.as_str(),+ KgclChange::NodeObsoletion { id, .. } => id.as_str(),+ })+ .collect();+ ids.sort();+ let count_before = ids.len();+ ids.dedup();+ assert_eq!(ids.len(), count_before, "IDs must be unique within a report");+ }++ #[test]+ fn report_to_json_has_context() {+ let report = KgclReport {+ changes: vec![KgclChange::NodeCreation {+ id: "kgcl_change_0001".to_string(),+ about_node: "http://example.org/Cat".to_string(),+ node_kind: "class".to_string(),+ }],+ };+ let j = report.to_json();+ assert_eq!(j["@context"].as_str().unwrap(), "http://w3id.org/kgcl/");+ assert!(j["changes"].is_array());+ }+}diff --git a/src/lib.rs b/src/lib.rsindex 139fa774..1894a6df 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -6,6 +6,7 @@ pub mod config;pub mod clinical;pub mod drift;pub mod enforce;+pub mod kgcl;pub mod feedback;pub mod graph;pub mod ingest;diff --git a/src/server.rs b/src/server.rsindex def7e039..70f3d803 100644--- a/src/server.rs+++ b/src/server.rs@@ -984,15 +984,35 @@ impl OpenOntologiesServer {}).to_string()}- #[tool(name = "onto_drift", description = "Detect drift between two ontology versions. Returns added/removed terms, likely renames with confidence scores, and drift velocity.")]+ #[tool(name = "onto_drift", description = "Detect drift between two ontology versions. Returns added/removed terms, likely renames with confidence scores, and drift velocity. `format` selects output: 'json' (default), 'kgcl' (KGCL CNL text), or 'kgcl_json' (KGCL structured JSON-LD).")]async fn onto_drift(&self, Parameters(input): Parameters<OntoDriftInput>) -> String {let detector = crate::drift::DriftDetector::new(self.db.clone());- match detector.detect(&input.version_a, &input.version_b) {- Ok(result) => {- self.lineage().record(&self.session_id, "D", "drift", "detected");- result- }- Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ let format = input.format.as_deref().unwrap_or("json");+ let threshold = input.rename_threshold.unwrap_or(0.7);+ match format {+ "kgcl" => match detector.detect_kgcl(&input.version_a, &input.version_b, threshold) {+ Ok(report) => {+ self.lineage()+ .record(&self.session_id, "D", "drift", "detected:kgcl");+ report.to_cnl()+ }+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ },+ "kgcl_json" => match detector.detect_kgcl(&input.version_a, &input.version_b, threshold) {+ Ok(report) => {+ self.lineage()+ .record(&self.session_id, "D", "drift", "detected:kgcl_json");+ report.to_json().to_string()+ }+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ },+ _ => match detector.detect(&input.version_a, &input.version_b) {+ Ok(result) => {+ self.lineage().record(&self.session_id, "D", "drift", "detected");+ result+ }+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ },}}diff --git a/tests/kgcl_drift_test.rs b/tests/kgcl_drift_test.rsnew file mode 100644index 00000000..df8cbbb4--- /dev/null+++ b/tests/kgcl_drift_test.rs@@ -0,0 +1,141 @@+use open_ontologies::drift::DriftDetector;+use open_ontologies::kgcl::KgclChange;+use open_ontologies::state::StateDb;+use tempfile::NamedTempFile;++fn setup() -> StateDb {+ let tmp = NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ StateDb::open(&path).unwrap()+}++#[test]+fn end_to_end_kgcl_addition_and_removal() {+ let db = setup();+ let detector = DriftDetector::new(db);++ let v1 = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ ex:Cat a owl:Class .+ "#;+ let v2 = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ ex:Bird a owl:Class .+ "#;++ let report = detector.detect_kgcl(v1, v2, 0.7).expect("detect_kgcl");++ // We expect Cat obsoleted, Bird created.+ let obsoleted: Vec<&str> = report+ .changes+ .iter()+ .filter_map(|c| match c {+ KgclChange::NodeObsoletion { about_node, .. } => Some(about_node.as_str()),+ _ => None,+ })+ .collect();+ let created: Vec<&str> = report+ .changes+ .iter()+ .filter_map(|c| match c {+ KgclChange::NodeCreation { about_node, .. } => Some(about_node.as_str()),+ _ => None,+ })+ .collect();++ assert!(+ obsoleted.iter().any(|s| s.contains("Cat")),+ "expected Cat in obsoletions; got {:?}",+ obsoleted+ );+ assert!(+ created.iter().any(|s| s.contains("Bird")),+ "expected Bird in creations; got {:?}",+ created+ );+}++#[test]+fn end_to_end_kgcl_high_confidence_rename_emits_replacement() {+ let db = setup();+ let detector = DriftDetector::new(db);++ // Same property, renamed — the existing drift test (test_drift_detects_likely_rename_by_domain_range)+ // produces a high-confidence rename here because domain+range match exactly.+ let v1 = 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/> .+ ex:authoredBy a owl:ObjectProperty ;+ rdfs:domain ex:Paper ;+ rdfs:range ex:Person .+ "#;+ let v2 = 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/> .+ ex:writtenBy a owl:ObjectProperty ;+ rdfs:domain ex:Paper ;+ rdfs:range ex:Person .+ "#;++ let report = detector.detect_kgcl(v1, v2, 0.5).expect("detect_kgcl");++ // Find the authoredBy obsoletion — must carry has_direct_replacement = writtenBy+ let obs = report.changes.iter().find_map(|c| match c {+ KgclChange::NodeObsoletion {+ about_node,+ has_direct_replacement,+ confidence,+ ..+ } if about_node.contains("authoredBy") => {+ Some((has_direct_replacement.clone(), *confidence))+ }+ _ => None,+ });+ let (replacement, confidence) =+ obs.expect("expected obsoletion of authoredBy to be present");+ let repl = replacement.expect("expected has_direct_replacement on a confident rename");+ assert!(+ repl.contains("writtenBy"),+ "replacement should point at writtenBy; got {}",+ repl+ );+ assert!(+ confidence.expect("confidence should be carried") > 0.5,+ "confidence should be above threshold"+ );++ // The CNL should contain the canonical "with replacement" phrasing.+ let cnl = report.to_cnl();+ assert!(+ cnl.contains("with replacement"),+ "expected 'with replacement' in CNL; got:\n{}",+ cnl+ );+}++#[test]+fn end_to_end_kgcl_no_changes_emits_empty_report() {+ let db = setup();+ let detector = DriftDetector::new(db);++ let v = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ ex:Cat a owl:Class .+ "#;++ let report = detector.detect_kgcl(v, v, 0.7).expect("detect_kgcl");+ assert!(+ report.changes.is_empty(),+ "no-change drift should produce empty KGCL report; got {:?}",+ report.changes+ );+}