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: add active monitor with configurable watchers and block/notify actions
FABIOTESS6b89b14d7cab
diff --git a/src/lib.rs b/src/lib.rsindex 5e6b72b8..87ec1d3f 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -2,6 +2,7 @@ pub mod config;pub mod graph;pub mod ingest;pub mod lineage;+pub mod monitor;pub mod mapping;pub mod ontology;pub mod reason;diff --git a/src/monitor.rs b/src/monitor.rsnew file mode 100644index 00000000..e1601a44--- /dev/null+++ b/src/monitor.rs@@ -0,0 +1,197 @@+use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum WatcherAction {+ #[serde(rename = "notify")]+ Notify,+ #[serde(rename = "block_next_apply")]+ BlockNextApply,+ #[serde(rename = "auto_rollback")]+ AutoRollback,+ #[serde(rename = "log")]+ Log,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Watcher {+ pub id: String,+ pub check_type: String,+ pub threshold: f64,+ pub severity: String,+ pub action: WatcherAction,+ pub query: Option<String>,+ pub message: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct Alert {+ pub watcher: String,+ pub severity: String,+ pub value: f64,+ pub threshold: f64,+ pub action: String,+ pub detail: String,+}++#[derive(Debug, Clone, Serialize)]+pub struct MonitorResult {+ pub status: String,+ pub alerts: Vec<Alert>,+ pub passed: Vec<String>,+}++pub struct Monitor {+ db: StateDb,+ graph: Arc<GraphStore>,+}++impl Monitor {+ pub fn new(db: StateDb, graph: Arc<GraphStore>) -> Self {+ Self { db, graph }+ }++ pub fn add_watcher(&self, watcher: Watcher) {+ let conn = self.db.conn();+ let action_str = serde_json::to_string(&watcher.action).unwrap_or_default();+ let action_str = action_str.trim_matches('"');+ let _ = conn.execute(+ "INSERT OR REPLACE INTO monitor_watchers (id, check_type, threshold, severity, action, query, message, enabled)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 1)",+ rusqlite::params![+ watcher.id, watcher.check_type, watcher.threshold,+ watcher.severity, action_str, watcher.query, watcher.message,+ ],+ );+ }++ pub fn run_watchers(&self) -> MonitorResult {+ let watchers = self.load_watchers();+ let mut alerts = Vec::new();+ let mut passed = Vec::new();+ let mut blocked = false;++ for w in &watchers {+ let value = self.evaluate_watcher(w);+ if value > w.threshold {+ let action_str = serde_json::to_string(&w.action).unwrap_or_default();+ let action_str = action_str.trim_matches('"').to_string();+ if matches!(w.action, WatcherAction::BlockNextApply) {+ blocked = true;+ self.set_blocked(true);+ }+ alerts.push(Alert {+ watcher: w.id.clone(),+ severity: w.severity.clone(),+ value,+ threshold: w.threshold,+ action: action_str,+ detail: w.message.clone().unwrap_or_default(),+ });+ } else {+ passed.push(w.id.clone());+ }+ }++ let status = if blocked {+ "blocked".to_string()+ } else if !alerts.is_empty() {+ "alert".to_string()+ } else {+ "ok".to_string()+ };++ MonitorResult { status, alerts, passed }+ }++ pub fn is_blocked(&self) -> bool {+ let conn = self.db.conn();+ let result: Option<String> = conn+ .query_row(+ "SELECT value FROM monitor_state WHERE key = 'blocked'",+ [],+ |r| r.get(0),+ )+ .ok();+ result.as_deref() == Some("true")+ }++ pub fn set_blocked(&self, blocked: bool) {+ let conn = self.db.conn();+ let _ = conn.execute(+ "INSERT OR REPLACE INTO monitor_state (key, value) VALUES ('blocked', ?1)",+ rusqlite::params![if blocked { "true" } else { "false" }],+ );+ }++ pub fn clear_blocked(&self) {+ self.set_blocked(false);+ }++ fn load_watchers(&self) -> Vec<Watcher> {+ let conn = self.db.conn();+ let mut stmt = conn+ .prepare("SELECT id, check_type, threshold, severity, action, query, message FROM monitor_watchers WHERE enabled = 1")+ .unwrap();+ stmt.query_map([], |row| {+ let action_str: String = row.get(4)?;+ let action = match action_str.as_str() {+ "block_next_apply" => WatcherAction::BlockNextApply,+ "auto_rollback" => WatcherAction::AutoRollback,+ "log" => WatcherAction::Log,+ _ => WatcherAction::Notify,+ };+ Ok(Watcher {+ id: row.get(0)?,+ check_type: row.get(1)?,+ threshold: row.get(2)?,+ severity: row.get(3)?,+ action,+ query: row.get(5)?,+ message: row.get(6)?,+ })+ })+ .unwrap()+ .filter_map(|r| r.ok())+ .collect()+ }++ fn evaluate_watcher(&self, watcher: &Watcher) -> f64 {+ match watcher.check_type.as_str() {+ "sparql" => self.eval_sparql_watcher(watcher),+ _ => 0.0,+ }+ }++ fn eval_sparql_watcher(&self, watcher: &Watcher) -> f64 {+ let query = match &watcher.query {+ Some(q) => q,+ None => return 0.0,+ };+ // Expect a SELECT query returning a ?count binding+ match self.graph.sparql_select(query) {+ Ok(json) => {+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json) {+ if let Some(results) = parsed["results"].as_array() {+ if let Some(first) = results.first() {+ if let Some(count_str) = first["count"].as_str() {+ // Oxigraph returns literal like "\"1\"^^<http://...>"+ let cleaned = count_str+ .trim_matches('"')+ .split("^^")+ .next()+ .unwrap_or("0")+ .trim_matches('"');+ return cleaned.parse().unwrap_or(0.0);+ }+ }+ }+ }+ 0.0+ }+ Err(_) => 0.0,+ }+ }+}diff --git a/tests/monitor_test.rs b/tests/monitor_test.rsnew file mode 100644index 00000000..7dde69ef--- /dev/null+++ b/tests/monitor_test.rs@@ -0,0 +1,108 @@+use open_ontologies::graph::GraphStore;+use open_ontologies::monitor::{Monitor, Watcher, WatcherAction};+use open_ontologies::state::StateDb;+use std::sync::Arc;+use tempfile::NamedTempFile;++#[test]+fn test_monitor_no_watchers_passes() {+ let tmp = NamedTempFile::new().unwrap();+ let db = StateDb::open(tmp.path()).unwrap();+ let graph = Arc::new(GraphStore::new());+ let monitor = Monitor::new(db, graph);++ let result = monitor.run_watchers();+ assert_eq!(result.status, "ok");+ assert!(result.alerts.is_empty());+}++#[test]+fn test_monitor_sparql_watcher_triggers() {+ let tmp = NamedTempFile::new().unwrap();+ let db = StateDb::open(tmp.path()).unwrap();+ let graph = Arc::new(GraphStore::new());++ // Load some data without labels+ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ "#, None).unwrap();++ let monitor = Monitor::new(db.clone(), graph);++ // Add a watcher that checks for classes without labels+ monitor.add_watcher(Watcher {+ id: "no_labels".into(),+ check_type: "sparql".into(),+ threshold: 0.0,+ severity: "error".into(),+ action: WatcherAction::Notify,+ query: Some("SELECT (COUNT(?c) AS ?count) WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> . FILTER NOT EXISTS { ?c <http://www.w3.org/2000/01/rdf-schema#label> ?l } }".into()),+ message: Some("Classes without labels".into()),+ });++ let result = monitor.run_watchers();+ assert_eq!(result.status, "alert");+ assert_eq!(result.alerts.len(), 1);+ assert_eq!(result.alerts[0].watcher, "no_labels");+}++#[test]+fn test_monitor_block_flag() {+ let tmp = NamedTempFile::new().unwrap();+ let db = StateDb::open(tmp.path()).unwrap();+ let graph = Arc::new(GraphStore::new());++ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ "#, None).unwrap();++ let monitor = Monitor::new(db.clone(), graph);++ monitor.add_watcher(Watcher {+ id: "no_labels".into(),+ check_type: "sparql".into(),+ threshold: 0.0,+ severity: "error".into(),+ action: WatcherAction::BlockNextApply,+ query: Some("SELECT (COUNT(?c) AS ?count) WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> . FILTER NOT EXISTS { ?c <http://www.w3.org/2000/01/rdf-schema#label> ?l } }".into()),+ message: Some("Classes without labels".into()),+ });++ let result = monitor.run_watchers();+ assert_eq!(result.status, "blocked");+ assert!(monitor.is_blocked());+}++#[test]+fn test_monitor_watcher_below_threshold_passes() {+ let tmp = NamedTempFile::new().unwrap();+ let db = StateDb::open(tmp.path()).unwrap();+ let graph = Arc::new(GraphStore::new());++ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Dog a owl:Class .+ "#, None).unwrap();++ let monitor = Monitor::new(db.clone(), graph);++ monitor.add_watcher(Watcher {+ id: "class_count".into(),+ check_type: "sparql".into(),+ threshold: 10.0, // threshold is 10, only 1 class loaded+ severity: "warning".into(),+ action: WatcherAction::Notify,+ query: Some("SELECT (COUNT(?c) AS ?count) WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> }".into()),+ message: Some("Too many classes".into()),+ });++ let result = monitor.run_watchers();+ assert_eq!(result.status, "ok");+ assert!(result.alerts.is_empty());+ assert_eq!(result.passed.len(), 1);+}