Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

Add webhook actions to monitor watchers

FABIOTESSb3029fce71c1
diff --git a/CLAUDE.md b/CLAUDE.md
index 735011a1..5c51cfe5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -76,7 +76,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_lock` | To protect production IRIs from removal |
| `onto_drift` | To compare two versions — rename detection, drift velocity, self-calibrating confidence |
| `onto_enforce` | After loading — design pattern checks: `generic`, `boro`, `value_partition`, or custom rules |
-| `onto_monitor` | After apply — run SPARQL watchers with threshold alerts |
+| `onto_monitor` | After apply — run SPARQL watchers with threshold alerts. Watchers with `webhook_url` POST alerts to external systems (Slack, PagerDuty, etc.) |
| `onto_monitor_clear` | To clear blocked state after resolving monitor alerts |
| `onto_crosswalk` | To look up clinical terminology mappings (ICD-10 ↔ SNOMED ↔ MeSH) |
| `onto_enrich` | To add skos:exactMatch triples linking classes to clinical codes |
diff --git a/README.md b/README.md
index 15ec3b12..71e4580f 100644
--- a/README.md
+++ b/README.md
@@ -304,7 +304,7 @@ Full benchmark writeup: [docs/benchmarks.md](docs/benchmarks.md)
| **Schema** | `import-schema` | PostgreSQL → OWL conversion |
| **Data** | `map` `ingest` `shacl` `reason` `extend` | Structured data → RDF pipeline |
| **Versioning** | `version` `history` `rollback` | Named snapshots and rollback |
-| **Lifecycle** | `plan` `apply` `lock` `drift` `enforce` `monitor` `monitor-clear` `lineage` | Terraform-style change management |
+| **Lifecycle** | `plan` `apply` `lock` `drift` `enforce` `monitor` `monitor-clear` `lineage` | Terraform-style change management with webhook alerts |
| **Alignment** | `align` `align-feedback` | Cross-ontology class matching with self-calibrating confidence |
| **Clinical** | `crosswalk` `enrich` `validate-clinical` | ICD-10 / SNOMED / MeSH crosswalks |
| **Feedback** | `lint-feedback` `enforce-feedback` | Self-calibrating suppression |
diff --git a/docs/plans/2026-03-16-webhook-actions-design.md b/docs/plans/2026-03-16-webhook-actions-design.md
new file mode 100644
index 00000000..93f7bf26
--- /dev/null
+++ b/docs/plans/2026-03-16-webhook-actions-design.md
@@ -0,0 +1,57 @@
+# Webhook Actions for Monitor Watchers
+
+## Summary
+
+Extend the existing monitor watcher system to fire HTTP webhooks when alerts trigger. No new tools -- the existing `onto_monitor` accepts watcher JSON with two new optional fields: `webhook_url` and `webhook_headers`.
+
+## Motivation
+
+The monitor system already evaluates SPARQL conditions and produces alerts, but the Notify action is a no-op. Adding webhook delivery turns the platform from passive (alerts returned to caller) to active (alerts pushed to external systems -- Slack, PagerDuty, custom APIs).
+
+## Changes
+
+### 1. Watcher struct (monitor.rs)
+
+Add two optional fields:
+- `webhook_url: Option<String>` -- POST target URL
+- `webhook_headers: Option<String>` -- JSON object of extra headers (e.g. `{"Authorization": "Bearer ..."}`)
+
+### 2. SQLite schema (state.rs)
+
+Add columns to `monitor_watchers`:
+```sql
+ALTER TABLE monitor_watchers ADD COLUMN webhook_url TEXT;
+ALTER TABLE monitor_watchers ADD COLUMN webhook_headers TEXT;
+```
+
+Use IF NOT EXISTS pattern for safe migration.
+
+### 3. Webhook delivery (monitor.rs)
+
+After `run_watchers()` collects alerts, for each alert whose watcher has a `webhook_url`:
+- Build JSON payload with alert fields + timestamp
+- POST to webhook_url with Content-Type: application/json
+- Include any custom headers from webhook_headers
+- 10 second timeout, fire-and-forget (tokio::spawn)
+- Log delivery result to lineage
+
+### 4. Payload format
+
+```json
+{
+ "source": "open-ontologies",
+ "watcher_id": "unlabeled-classes",
+ "severity": "warning",
+ "value": 12,
+ "threshold": 5,
+ "message": "12 classes without labels",
+ "timestamp": "2026-03-16T12:00:00Z"
+}
+```
+
+### What this does NOT include
+
+- No retries or dead-letter queue (YAGNI)
+- No new tools (onto_monitor already handles watcher management)
+- No webhook registration UI
+- No payload templating
diff --git a/src/monitor.rs b/src/monitor.rs
index 545b3964..96bf24b3 100644
--- a/src/monitor.rs
+++ b/src/monitor.rs
@@ -2,6 +2,7 @@ use crate::graph::GraphStore;
use crate::state::StateDb;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
+use std::time::Duration;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WatcherAction {
@@ -24,6 +25,10 @@ pub struct Watcher {
pub action: WatcherAction,
pub query: Option<String>,
pub message: Option<String>,
+ #[serde(default)]
+ pub webhook_url: Option<String>,
+ #[serde(default)]
+ pub webhook_headers: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -58,11 +63,12 @@ impl Monitor {
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)",
+ "INSERT OR REPLACE INTO monitor_watchers (id, check_type, threshold, severity, action, query, message, webhook_url, webhook_headers, enabled)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1)",
rusqlite::params![
watcher.id, watcher.check_type, watcher.threshold,
watcher.severity, action_str, watcher.query, watcher.message,
+ watcher.webhook_url, watcher.webhook_headers,
],
);
}
@@ -82,6 +88,25 @@ impl Monitor {
blocked = true;
self.set_blocked(true);
}
+ // Fire webhook for Notify actions
+ if matches!(w.action, WatcherAction::Notify) {
+ if let Some(ref url) = w.webhook_url {
+ let url = url.clone();
+ let headers = w.webhook_headers.clone();
+ let payload = serde_json::json!({
+ "source": "open-ontologies",
+ "watcher_id": w.id,
+ "severity": w.severity,
+ "value": value,
+ "threshold": w.threshold,
+ "message": w.message.clone().unwrap_or_default(),
+ "timestamp": chrono::Utc::now().to_rfc3339(),
+ });
+ tokio::spawn(async move {
+ let _ = deliver_webhook(&url, headers.as_deref(), &payload).await;
+ });
+ }
+ }
alerts.push(Alert {
watcher: w.id.clone(),
severity: w.severity.clone(),
@@ -133,7 +158,7 @@ impl Monitor {
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")
+ .prepare("SELECT id, check_type, threshold, severity, action, query, message, webhook_url, webhook_headers FROM monitor_watchers WHERE enabled = 1")
.unwrap();
stmt.query_map([], |row| {
let action_str: String = row.get(4)?;
@@ -151,6 +176,8 @@ impl Monitor {
action,
query: row.get(5)?,
message: row.get(6)?,
+ webhook_url: row.get(7)?,
+ webhook_headers: row.get(8)?,
})
})
.unwrap()
@@ -192,3 +219,28 @@ impl Monitor {
}
}
}
+
+/// Fire-and-forget webhook delivery with 10s timeout.
+async fn deliver_webhook(
+ url: &str,
+ headers_json: Option<&str>,
+ payload: &serde_json::Value,
+) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(10))
+ .build()?;
+ let mut req = client.post(url).json(payload);
+ if let Some(hdr_json) = headers_json {
+ if let Ok(map) = serde_json::from_str::<std::collections::HashMap<String, String>>(hdr_json) {
+ for (k, v) in map {
+ req = req.header(&k, &v);
+ }
+ }
+ }
+ let resp = req.send().await?;
+ let status = resp.status();
+ if !status.is_success() {
+ eprintln!("Webhook to {} returned {}", url, status);
+ }
+ Ok(())
+}
diff --git a/src/server.rs b/src/server.rs
index 79e84a31..dc737d80 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -636,7 +636,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_monitor", description = "Run active monitoring watchers. Optionally add new watchers via inline JSON. Returns ok/alert/blocked status with details.")]
+ #[tool(name = "onto_monitor", description = "Run active monitoring watchers. Optionally add new watchers via inline JSON. Watchers with action=notify and a webhook_url will POST alerts to the URL. Returns ok/alert/blocked status with details.")]
async fn onto_monitor(&self, Parameters(input): Parameters<OntoMonitorInput>) -> String {
let monitor = self.monitor();
diff --git a/src/state.rs b/src/state.rs
index 85e9a031..cc89ca10 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -21,6 +21,8 @@ CREATE TABLE IF NOT EXISTS monitor_watchers (
action TEXT NOT NULL DEFAULT 'notify',
query TEXT,
message TEXT,
+ webhook_url TEXT,
+ webhook_headers TEXT,
enabled INTEGER NOT NULL DEFAULT 1
);
@@ -116,6 +118,11 @@ impl StateDb {
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.execute_batch(SCHEMA)?;
+ // Safe migration: add webhook columns if upgrading from older schema
+ let _ = conn.execute_batch(
+ "ALTER TABLE monitor_watchers ADD COLUMN webhook_url TEXT;
+ ALTER TABLE monitor_watchers ADD COLUMN webhook_headers TEXT;"
+ );
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
diff --git a/studio/src-tauri/sidecars/agent/index.ts b/studio/src-tauri/sidecars/agent/index.ts
index 7b9dab9a..19e3d77f 100644
--- a/studio/src-tauri/sidecars/agent/index.ts
+++ b/studio/src-tauri/sidecars/agent/index.ts
@@ -52,7 +52,7 @@ Lifecycle (Terraform-style):
- onto_lock: Protect production IRIs from removal
- onto_drift: Compare versions — rename detection, drift velocity
- onto_enforce: Check design pattern compliance (generic, boro, value_partition)
-- onto_monitor: Run SPARQL watchers with threshold alerts
+- onto_monitor: Run SPARQL watchers with threshold alerts (supports webhook_url for push notifications)
- onto_monitor_clear: Clear blocked state after resolving monitor alerts
- onto_lineage: View the session lineage trail