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.

docs: add design and plan documents for studio and runtime features

FABIOTESSa0e6d2026674
diff --git a/docs/plans/2026-03-09-standalone-mcp-server-design.md b/docs/plans/2026-03-09-standalone-mcp-server-design.md
new file mode 100644
index 00000000..b453437a
--- /dev/null
+++ b/docs/plans/2026-03-09-standalone-mcp-server-design.md
@@ -0,0 +1,343 @@
+# Open Ontologies — Standalone MCP Server Design
+
+**Date:** 2026-03-09
+**Status:** Approved
+
+## Goal
+
+Extract all ontology code from OpenCheir into Open Ontologies, making it a standalone Rust MCP server. OpenCheir remains the governance/orchestration layer. Both servers run independently; Claude calls both.
+
+## Architecture (After Split)
+
+```
+Claude Code
+ │
+ ├── MCP: open-ontologies (ontology engine)
+ │ ├── onto_validate, onto_load, onto_query, ...
+ │ ├── GraphStore (Oxigraph)
+ │ └── StateDb (SQLite — versioning only)
+ │
+ └── MCP: opencheir (governance + orchestration)
+ ├── qa_*, enforcer_*, lineage_*, hive_*, pattern_*
+ ├── StateDb (SQLite — enforcer, lineage, memory, patterns)
+ └── Supervisor (manages external MCP servers)
+```
+
+OpenCheir's enforcer rules still reference `onto_*` tool names. Claude calls `enforcer_check` from OpenCheir before ontology operations. The enforcement is advisory — same as today.
+
+## What Moves to Open Ontologies
+
+### Source files (copied from OpenCheir, then adapted)
+
+| OpenCheir source | Open Ontologies target | Changes |
+|-----------------|----------------------|---------|
+| `src/domain/ontology.rs` (232 lines) | `src/ontology.rs` | Remove `crate::store::graph` import, use local `graph` module. Remove `StateDb` dependency — use local `state.rs`. |
+| `src/store/graph.rs` (267 lines) | `src/graph.rs` | No changes needed — self-contained Oxigraph wrapper. |
+| `server.rs` onto_* tools + input structs (~220 lines) | `src/server.rs` | New `OpenOntologiesServer` struct. Only 15 onto_* tools. Own `graph` and `db` fields. |
+| `src/store/state.rs` (partial) | `src/state.rs` | Minimal: just `ontology_versions` table creation + connection management. No enforcer, lineage, memory, patterns tables. |
+
+### Test files (copied from OpenCheir)
+
+| OpenCheir test | Open Ontologies target |
+|---------------|----------------------|
+| `tests/ontology_test.rs` | `tests/ontology_test.rs` |
+| `tests/graph_test.rs` | `tests/graph_test.rs` |
+| `tests/graph_remote_test.rs` | `tests/graph_remote_test.rs` |
+| `tests/onto_phase2_test.rs` | `tests/onto_phase2_test.rs` |
+| `tests/onto_integration_test.rs` | `tests/onto_integration_test.rs` |
+
+### Dependencies (Cargo.toml)
+
+```toml
+[package]
+name = "open-ontologies"
+version = "0.1.0"
+edition = "2024"
+description = "AI-native ontology engine — standalone MCP server"
+license = "MIT"
+repository = "https://github.com/fabio-rovai/open-ontologies"
+
+[[bin]]
+name = "open-ontologies"
+path = "src/main.rs"
+
+[dependencies]
+rmcp = { version = "1", features = ["server", "transport-io"] }
+tokio = { version = "1", features = ["full"] }
+oxigraph = "0.4"
+rusqlite = { version = "0.32", features = ["bundled"] }
+reqwest = { version = "0.12", features = ["json"] }
+schemars = "1"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+toml = "0.8"
+clap = { version = "4", features = ["derive"] }
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+uuid = { version = "1", features = ["v4"] }
+chrono = "0.4"
+anyhow = "1"
+
+[dev-dependencies]
+tempfile = "3"
+```
+
+## Open Ontologies Project Structure
+
+```
+open-ontologies/
+├── src/
+│ ├── main.rs # CLI: init + serve
+│ ├── lib.rs # pub mod graph, ontology, server, state, config
+│ ├── server.rs # OpenOntologiesServer with 15 onto_* tools
+│ ├── graph.rs # GraphStore (Oxigraph wrapper)
+│ ├── ontology.rs # OntologyService (validate, diff, lint, versioning)
+│ ├── state.rs # Minimal SQLite (ontology_versions table only)
+│ └── config.rs # Simple config: data_dir only
+├── tests/
+│ ├── ontology_test.rs
+│ ├── graph_test.rs
+│ ├── graph_remote_test.rs
+│ ├── onto_phase2_test.rs
+│ └── onto_integration_test.rs
+├── benchmark/ # Existing — unchanged
+├── skills/ # Existing — unchanged
+├── docs/ # Existing + this design doc
+├── Cargo.toml # New
+├── Cargo.lock # New (generated)
+├── CLAUDE.md # Update: remove OpenCheir references, describe standalone
+├── README.md # Update: standalone server, new architecture diagram
+└── LICENSE # Existing — unchanged
+```
+
+## What Gets Removed from OpenCheir
+
+### Files deleted
+- `src/domain/ontology.rs`
+- `src/store/graph.rs`
+- `tests/ontology_test.rs`
+- `tests/graph_test.rs`
+- `tests/graph_remote_test.rs`
+- `tests/onto_phase2_test.rs`
+- `tests/onto_integration_test.rs`
+
+### Code removed from `src/gateway/server.rs`
+- All `Onto*Input` structs (OntoValidateInput, OntoConvertInput, OntoLoadInput, etc.)
+- All `onto_*` tool functions
+- The `graph: Arc<GraphStore>` field from `OpenCheirServer`
+- The `GraphStore` import
+
+### Dependencies removed from `Cargo.toml`
+- `oxigraph` — only used by ontology
+- `reqwest` — check if used elsewhere (supervisor health checks?). If only ontology uses it, remove.
+
+### Code updated
+- `OpenCheirServer::new()` — remove `graph` field initialization
+- `opencheir_health` — remove ontology from component list
+- `src/domain/mod.rs` — remove `pub mod ontology`
+- `src/store/mod.rs` — remove `pub mod graph`
+
+### README.md — updated
+- Remove Ontology row from features table
+- Remove all onto_* tools from tools section
+- Update mermaid diagram to remove Ontology and GraphStore nodes
+- Add note pointing to Open Ontologies for ontology features
+- Update tool count
+
+### Enforcer rules — unchanged
+- `onto_validate_after_save` and `onto_version_before_push` stay in OpenCheir
+- They still work: Claude calls `enforcer_check("onto_save")` from OpenCheir, then calls `onto_save` from Open Ontologies
+
+## Updated README: OpenCheir
+
+### Mermaid diagram (replaces current)
+
+```mermaid
+flowchart TD
+ Claude["Claude"]
+ MCP["MCP Server"]
+ Enforcer["Enforcer"]
+ QA["QA"]
+ Documents["Documents"]
+ Eyes["Eyes"]
+ Hive["Hive Memory"]
+ Lineage["Lineage"]
+ StateDb["StateDb — SQLite"]
+
+ Claude --> MCP
+ MCP --> Enforcer
+ MCP --> QA
+ MCP --> Documents
+ MCP --> Eyes
+ MCP --> Hive
+ MCP --> Lineage
+ Enforcer --> StateDb
+ QA --> StateDb
+ Documents --> StateDb
+ Hive --> StateDb
+ Lineage --> StateDb
+```
+
+### Features table (replaces current)
+
+| Module | Tools | Purpose |
+|--------|-------|---------|
+| Document QA | 5 | Font, dash, word count, signature checks |
+| Document Parsing | 2 | DOCX structure extraction |
+| Search | 1 | FTS5 full-text search |
+| Enforcer | 4 | Workflow rule engine with hot-reload |
+| Lineage | 3 | Audit trail & event tracking |
+| Patterns | 2 | Cross-session pattern discovery |
+| Memory | 3 | Persistent learning storage |
+| Hive | 2 | Domain locking for multi-agent |
+| Status | 2 | Health monitoring |
+
+Add a note: "For ontology engineering (RDF/OWL/SPARQL), see [Open Ontologies](https://github.com/fabio-rovai/open-ontologies)."
+
+## Updated README: Open Ontologies
+
+### Key changes
+
+1. **"What is it?" section** — rewrite to describe standalone server, not a module of OpenCheir
+2. **Architecture diagram** — new mermaid showing standalone server
+3. **"Replicate it yourself" section** — updated install instructions (build open-ontologies directly)
+4. **Stack section** — updated to reflect standalone binary
+5. **Enforcer section** — note that enforcer rules live in OpenCheir (optional companion)
+
+### New architecture diagram
+
+```mermaid
+flowchart TD
+ Claude["Claude"]
+ MCP["Open Ontologies MCP Server"]
+ OntologyService["OntologyService"]
+ GraphStore["GraphStore — Oxigraph"]
+ StateDb["StateDb — SQLite"]
+
+ Claude --> MCP
+ MCP --> OntologyService
+ OntologyService --> GraphStore
+ OntologyService --> StateDb
+```
+
+### New "What is it?" section
+
+```markdown
+Open Ontologies is a standalone MCP server for AI-native ontology engineering.
+It exposes 15 tools that let Claude validate, query, diff, lint, version, and
+persist RDF/OWL ontologies using an in-memory Oxigraph triple store.
+
+Written in Rust, ships as a single binary. No JVM, no Protege, no GUI.
+
+**Optional companion:** [OpenCheir](https://github.com/fabio-rovai/opencheir)
+adds workflow enforcement, audit trails, and multi-agent orchestration.
+Its enforcer rules can govern ontology workflows (e.g., warn if saving
+without validating). But Open Ontologies works perfectly on its own.
+```
+
+### New "Replicate it yourself" section
+
+```markdown
+### 1. Build Open Ontologies
+
+git clone https://github.com/fabio-rovai/open-ontologies.git
+cd open-ontologies
+cargo build --release
+
+### 2. Connect to Claude Code
+
+Add to ~/.claude/settings.json:
+
+{
+ "mcpServers": {
+ "open-ontologies": {
+ "command": "/path/to/open-ontologies/target/release/open-ontologies",
+ "args": ["serve"]
+ }
+ }
+}
+
+### 3. (Optional) Add OpenCheir for governance
+
+{
+ "mcpServers": {
+ "open-ontologies": { ... },
+ "opencheir": {
+ "command": "/path/to/opencheir/target/release/opencheir",
+ "args": ["serve"]
+ }
+ }
+}
+```
+
+## Updated CLAUDE.md: Open Ontologies
+
+### Changes
+- Remove "OpenCheir enforces workflow safety rules" section
+- Replace with optional note: "If OpenCheir is also connected, its enforcer rules provide workflow safety"
+- Tool names stay the same (onto_*) — they're now native to this server
+
+## Updated CLAUDE.md: OpenCheir
+
+### Changes
+- No changes needed. The enforcer rules still reference onto_* tool names.
+- Claude calls enforcer_check from OpenCheir, then calls the actual tool from Open Ontologies.
+
+## State Management
+
+Open Ontologies gets its own SQLite database at `~/.open-ontologies/state.db`.
+
+### Schema (single table)
+
+```sql
+CREATE TABLE IF NOT EXISTS ontology_versions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ label TEXT NOT NULL,
+ triple_count INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ format TEXT NOT NULL DEFAULT 'ntriples',
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+```
+
+### Config file
+
+`~/.open-ontologies/config.toml`:
+
+```toml
+[general]
+data_dir = "~/.open-ontologies"
+```
+
+### CLI
+
+```
+open-ontologies init # Create data dir, config, DB
+open-ontologies serve # Start MCP server on stdio
+```
+
+## Migration Checklist
+
+### Open Ontologies (new code)
+1. Create `Cargo.toml`
+2. Create `src/main.rs` — CLI with init + serve
+3. Create `src/lib.rs` — module exports
+4. Create `src/config.rs` — minimal config
+5. Create `src/state.rs` — minimal SQLite (ontology_versions only)
+6. Copy + adapt `src/graph.rs` from OpenCheir
+7. Copy + adapt `src/ontology.rs` from OpenCheir
+8. Create `src/server.rs` — OpenOntologiesServer with 15 tools
+9. Copy + adapt tests
+10. Update `README.md` — standalone server, new diagrams
+11. Update `CLAUDE.md` — remove OpenCheir dependency language
+12. Build and verify: `cargo build && cargo test`
+
+### OpenCheir (removals)
+13. Delete `src/domain/ontology.rs`
+14. Delete `src/store/graph.rs`
+15. Delete ontology tests
+16. Remove onto_* code from `src/gateway/server.rs`
+17. Update module declarations (lib.rs, domain/mod.rs, store/mod.rs)
+18. Remove `oxigraph` (and possibly `reqwest`) from Cargo.toml
+19. Update `README.md` — remove ontology, update diagrams
+20. Build and verify: `cargo build && cargo test`
diff --git a/docs/plans/2026-03-09-standalone-mcp-server-plan.md b/docs/plans/2026-03-09-standalone-mcp-server-plan.md
new file mode 100644
index 00000000..492fa24a
--- /dev/null
+++ b/docs/plans/2026-03-09-standalone-mcp-server-plan.md
@@ -0,0 +1,1141 @@
+# Open Ontologies Standalone MCP Server — Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Extract all ontology code from OpenCheir into Open Ontologies as a standalone Rust MCP server, then remove it from OpenCheir.
+
+**Architecture:** Two independent MCP servers. Open Ontologies owns the Oxigraph graph store and all 15 `onto_*` tools. OpenCheir keeps governance (enforcer, lineage, hive, QA). Claude calls both directly.
+
+**Tech Stack:** Rust 2024, rmcp 1.x, Oxigraph 0.4, SQLite (rusqlite), tokio, reqwest, clap
+
+**Design doc:** `docs/plans/2026-03-09-standalone-mcp-server-design.md`
+
+**Repos:**
+- Open Ontologies: `/Users/fabio/projects/open-ontologies`
+- OpenCheir: `/Users/fabio/projects/opencheir`
+
+---
+
+## Phase 1: Build Open Ontologies MCP Server
+
+### Task 1: Create Cargo.toml
+
+**Files:**
+- Create: `Cargo.toml`
+
+**Step 1: Create the Cargo.toml**
+
+```toml
+[package]
+name = "open-ontologies"
+version = "0.1.0"
+edition = "2024"
+description = "AI-native ontology engine — standalone MCP server"
+license = "MIT"
+repository = "https://github.com/fabio-rovai/open-ontologies"
+
+[[bin]]
+name = "open-ontologies"
+path = "src/main.rs"
+
+[dependencies]
+rmcp = { version = "1", features = ["server", "transport-io"] }
+tokio = { version = "1", features = ["full"] }
+oxigraph = "0.4"
+rusqlite = { version = "0.32", features = ["bundled"] }
+reqwest = { version = "0.12", features = ["json"] }
+schemars = "1"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+toml = "0.8"
+clap = { version = "4", features = ["derive"] }
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+chrono = "0.4"
+anyhow = "1"
+
+[dev-dependencies]
+tempfile = "3"
+```
+
+**Step 2: Verify it parses**
+
+Run: `cd /Users/fabio/projects/open-ontologies && cargo check 2>&1 | head -5`
+Expected: Errors about missing `src/main.rs` (that's fine — we'll create it next)
+
+**Step 3: Commit**
+
+```bash
+git add Cargo.toml
+git commit -m "feat: add Cargo.toml for standalone MCP server"
+```
+
+---
+
+### Task 2: Create graph.rs (Oxigraph wrapper)
+
+**Files:**
+- Create: `src/graph.rs`
+
+Copy from `/Users/fabio/projects/opencheir/src/store/graph.rs` verbatim. No changes needed — it's self-contained.
+
+**Step 1: Create `src/` directory and copy graph.rs**
+
+Create `src/graph.rs` with the exact content of `/Users/fabio/projects/opencheir/src/store/graph.rs` (267 lines). No modifications needed.
+
+**Step 2: Create stub lib.rs so it compiles**
+
+Create `src/lib.rs`:
+```rust
+pub mod graph;
+```
+
+Create `src/main.rs`:
+```rust
+fn main() {
+ println!("open-ontologies");
+}
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success (warnings about unused code are fine)
+
+**Step 4: Commit**
+
+```bash
+git add src/graph.rs src/lib.rs src/main.rs
+git commit -m "feat: add GraphStore — Oxigraph RDF/SPARQL wrapper"
+```
+
+---
+
+### Task 3: Create state.rs (minimal SQLite for versioning)
+
+**Files:**
+- Create: `src/state.rs`
+
+This is a minimal version of OpenCheir's `StateDb` — only the `ontology_versions` table.
+
+**Step 1: Create state.rs**
+
+```rust
+use anyhow::Result;
+use rusqlite::Connection;
+use std::path::Path;
+use std::sync::{Arc, Mutex};
+
+const SCHEMA: &str = "
+CREATE TABLE IF NOT EXISTS ontology_versions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ label TEXT NOT NULL,
+ triple_count INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ format TEXT NOT NULL DEFAULT 'ntriples',
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+";
+
+/// Minimal SQLite state store for ontology versioning.
+#[derive(Clone)]
+pub struct StateDb {
+ conn: Arc<Mutex<Connection>>,
+}
+
+impl StateDb {
+ pub fn open(path: &Path) -> Result<Self> {
+ let conn = Connection::open(path)?;
+ conn.pragma_update(None, "journal_mode", "WAL")?;
+ conn.pragma_update(None, "foreign_keys", "ON")?;
+ conn.pragma_update(None, "synchronous", "NORMAL")?;
+ conn.execute_batch(SCHEMA)?;
+ Ok(Self {
+ conn: Arc::new(Mutex::new(conn)),
+ })
+ }
+
+ pub fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
+ self.conn.lock().unwrap()
+ }
+}
+```
+
+**Step 2: Add module to lib.rs**
+
+Update `src/lib.rs`:
+```rust
+pub mod graph;
+pub mod state;
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success
+
+**Step 4: Commit**
+
+```bash
+git add src/state.rs src/lib.rs
+git commit -m "feat: add minimal StateDb for ontology versioning"
+```
+
+---
+
+### Task 4: Create ontology.rs (service layer)
+
+**Files:**
+- Create: `src/ontology.rs`
+
+Copy from `/Users/fabio/projects/opencheir/src/domain/ontology.rs` and update imports to use local modules instead of `crate::store::graph` and `crate::store::state`.
+
+**Step 1: Create ontology.rs**
+
+Copy the content of `/Users/fabio/projects/opencheir/src/domain/ontology.rs` (232 lines) and change two imports:
+
+- `use crate::store::graph::GraphStore;` → `use crate::graph::GraphStore;`
+- `use crate::store::state::StateDb;` → `use crate::state::StateDb;`
+
+Everything else stays identical.
+
+**Step 2: Add module to lib.rs**
+
+Update `src/lib.rs`:
+```rust
+pub mod graph;
+pub mod ontology;
+pub mod state;
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success
+
+**Step 4: Commit**
+
+```bash
+git add src/ontology.rs src/lib.rs
+git commit -m "feat: add OntologyService — validate, diff, lint, versioning"
+```
+
+---
+
+### Task 5: Create config.rs
+
+**Files:**
+- Create: `src/config.rs`
+
+**Step 1: Create config.rs**
+
+```rust
+use anyhow::{Context, Result};
+use serde::Deserialize;
+use std::path::Path;
+
+#[derive(Debug, Deserialize)]
+#[serde(default)]
+pub struct Config {
+ pub general: GeneralConfig,
+}
+
+impl Default for Config {
+ fn default() -> Self {
+ Self {
+ general: GeneralConfig::default(),
+ }
+ }
+}
+
+impl Config {
+ pub fn load(path: &Path) -> Result<Self> {
+ let contents = std::fs::read_to_string(path)
+ .with_context(|| format!("failed to read config file: {}", path.display()))?;
+ let config: Config = toml::from_str(&contents)
+ .with_context(|| format!("failed to parse config file: {}", path.display()))?;
+ Ok(config)
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(default)]
+pub struct GeneralConfig {
+ pub data_dir: String,
+}
+
+impl Default for GeneralConfig {
+ fn default() -> Self {
+ Self {
+ data_dir: "~/.open-ontologies".into(),
+ }
+ }
+}
+
+/// Expand a leading `~` in a path to the user's home directory.
+pub fn expand_tilde(path: &str) -> String {
+ if path.starts_with("~/") || path == "~" {
+ if let Some(home) = std::env::var_os("HOME") {
+ return path.replacen("~", &home.to_string_lossy(), 1);
+ }
+ }
+ path.to_string()
+}
+```
+
+**Step 2: Add module to lib.rs**
+
+Update `src/lib.rs`:
+```rust
+pub mod config;
+pub mod graph;
+pub mod ontology;
+pub mod state;
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success
+
+**Step 4: Commit**
+
+```bash
+git add src/config.rs src/lib.rs
+git commit -m "feat: add minimal config for data directory"
+```
+
+---
+
+### Task 6: Create server.rs (MCP server with 15 onto_* tools)
+
+**Files:**
+- Create: `src/server.rs`
+
+This is the MCP server. Copy the 15 `onto_*` tool definitions and their input structs from `/Users/fabio/projects/opencheir/src/gateway/server.rs` lines 146-234 (input structs) and lines 571-792 (tool implementations). Change the server struct name to `OpenOntologiesServer`.
+
+**Step 1: Create server.rs**
+
+The server struct:
+
+```rust
+use std::sync::Arc;
+
+use rmcp::{
+ ServerHandler, tool, tool_handler, tool_router,
+ handler::server::{tool::ToolRouter, wrapper::Parameters},
+ model::{ServerCapabilities, ServerInfo, Tool},
+};
+use schemars::JsonSchema;
+use serde::Deserialize;
+
+use crate::graph::GraphStore;
+use crate::state::StateDb;
+```
+
+Then copy all `Onto*Input` structs from OpenCheir's `server.rs` (lines 146-234):
+- `OntoValidateInput`
+- `OntoConvertInput`
+- `OntoLoadInput`
+- `OntoQueryInput`
+- `OntoSaveInput`
+- `OntoDiffInput`
+- `OntoLintInput`
+- `OntoPullInput`
+- `OntoPushInput`
+- `OntoImportInput`
+- `OntoVersionInput`
+- `OntoRollbackInput`
+
+Server struct:
+
+```rust
+#[derive(Clone)]
+pub struct OpenOntologiesServer {
+ tool_router: ToolRouter<Self>,
+ db: StateDb,
+ graph: Arc<GraphStore>,
+}
+
+impl OpenOntologiesServer {
+ pub fn new(db: StateDb) -> Self {
+ Self {
+ tool_router: Self::tool_router(),
+ db,
+ graph: Arc::new(GraphStore::new()),
+ }
+ }
+
+ pub fn list_tool_definitions(&self) -> Vec<Tool> {
+ self.tool_router.list_all()
+ }
+}
+```
+
+Then the `#[tool_router] impl` block with all 15 tools + a status tool. Copy each tool from OpenCheir's server.rs lines 571-792, changing:
+- `use crate::domain::ontology::OntologyService;` → `use crate::ontology::OntologyService;`
+- `use crate::store::graph::GraphStore;` → `use crate::graph::GraphStore;`
+
+Add a status tool:
+
+```rust
+#[tool(name = "onto_status", description = "Returns health status of the Open Ontologies server")]
+fn onto_status(&self) -> String {
+ let tool_count = self.tool_router.list_all().len();
+ let triple_count = self.graph.triple_count();
+ serde_json::json!({
+ "status": "ok",
+ "version": env!("CARGO_PKG_VERSION"),
+ "tools": tool_count,
+ "triples_loaded": triple_count,
+ })
+ .to_string()
+}
+```
+
+Then the `ServerHandler` impl:
+
+```rust
+#[tool_handler]
+impl ServerHandler for OpenOntologiesServer {
+ fn get_info(&self) -> ServerInfo {
+ ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
+ .with_instructions("Open Ontologies: AI-native ontology engine — RDF/OWL/SPARQL MCP server")
+ }
+}
+```
+
+**Step 2: Add module to lib.rs**
+
+Update `src/lib.rs`:
+```rust
+pub mod config;
+pub mod graph;
+pub mod ontology;
+pub mod server;
+pub mod state;
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success
+
+**Step 4: Commit**
+
+```bash
+git add src/server.rs src/lib.rs
+git commit -m "feat: add OpenOntologiesServer with 15 onto_* MCP tools"
+```
+
+---
+
+### Task 7: Create main.rs (CLI with init + serve)
+
+**Files:**
+- Modify: `src/main.rs`
+
+**Step 1: Write main.rs**
+
+```rust
+use clap::{Parser, Subcommand};
+use rmcp::ServiceExt;
+
+use open_ontologies::config::{expand_tilde, Config};
+use open_ontologies::server::OpenOntologiesServer;
+use open_ontologies::state::StateDb;
+
+const DEFAULT_CONFIG: &str = r#"[general]
+data_dir = "~/.open-ontologies"
+"#;
+
+#[derive(Parser)]
+#[command(name = "open-ontologies", about = "AI-native ontology engine — MCP server")]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Initialize: create data directory, DB, and default config
+ Init {
+ #[arg(long, default_value = "~/.open-ontologies")]
+ data_dir: String,
+ },
+ /// Start the MCP server
+ Serve {
+ #[arg(long, default_value = "~/.open-ontologies/config.toml")]
+ config: String,
+ },
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let cli = Cli::parse();
+
+ match cli.command {
+ Commands::Init { data_dir } => {
+ let data_dir = expand_tilde(&data_dir);
+ let data_path = std::path::Path::new(&data_dir);
+
+ std::fs::create_dir_all(data_path)?;
+ println!("Created data directory: {data_dir}");
+
+ let db_path = data_path.join("open-ontologies.db");
+ let _db = StateDb::open(&db_path)?;
+ println!("Initialized database: {}", db_path.display());
+
+ let config_path = data_path.join("config.toml");
+ if !config_path.exists() {
+ std::fs::write(&config_path, DEFAULT_CONFIG)?;
+ println!("Created default config: {}", config_path.display());
+ } else {
+ println!("Config already exists: {}", config_path.display());
+ }
+
+ println!("\nOpen Ontologies initialized successfully!");
+ }
+ Commands::Serve { config: config_path } => {
+ let config_path = expand_tilde(&config_path);
+ let cfg = match Config::load(std::path::Path::new(&config_path)) {
+ Ok(c) => c,
+ Err(e) => {
+ let msg = e.to_string();
+ if msg.contains("failed to read") {
+ Config::default()
+ } else {
+ return Err(e);
+ }
+ }
+ };
+ let data_dir = expand_tilde(&cfg.general.data_dir);
+ let db_path = std::path::Path::new(&data_dir).join("open-ontologies.db");
+
+ std::fs::create_dir_all(&data_dir)?;
+ let db = StateDb::open(&db_path)?;
+
+ let server = OpenOntologiesServer::new(db);
+ let service = server.serve(rmcp::transport::stdio()).await?;
+ service.waiting().await?;
+ }
+ }
+
+ Ok(())
+}
+```
+
+**Step 2: Build the binary**
+
+Run: `cargo build`
+Expected: Compiles successfully
+
+**Step 3: Test init command**
+
+Run: `./target/debug/open-ontologies init --data-dir /tmp/test-onto`
+Expected: Creates directory, DB, and config. Output shows three "Created" lines.
+
+Run: `ls /tmp/test-onto/`
+Expected: `config.toml open-ontologies.db`
+
+Clean up: `rm -rf /tmp/test-onto`
+
+**Step 4: Commit**
+
+```bash
+git add src/main.rs
+git commit -m "feat: add CLI with init and serve commands"
+```
+
+---
+
+### Task 8: Copy tests and test data
+
+**Files:**
+- Create: `tests/graph_test.rs`
+- Create: `tests/ontology_test.rs`
+- Create: `tests/ontology_version_test.rs`
+- Create: `tests/onto_phase2_test.rs`
+- Create: `tests/onto_integration_test.rs`
+- Create: `tests/graph_remote_test.rs`
+- Create: `tests/data/sample.ttl`
+
+**Step 1: Copy test data**
+
+Copy `/Users/fabio/projects/opencheir/tests/data/sample.ttl` to `tests/data/sample.ttl`.
+
+**Step 2: Copy and adapt test files**
+
+Copy each test file from OpenCheir. In every file, change imports:
+- `use opencheir::domain::ontology::OntologyService;` → `use open_ontologies::ontology::OntologyService;`
+- `use opencheir::store::graph::GraphStore;` → `use open_ontologies::graph::GraphStore;`
+- `use opencheir::store::state::StateDb;` → `use open_ontologies::state::StateDb;`
+
+Remove any test that references OpenCheir-specific code (e.g., the enforcer test in `onto_phase2_test.rs` — `test_version_before_push_enforcer` — must be removed since the enforcer doesn't exist in this crate).
+
+Files to copy and adapt:
+- `graph_test.rs` — change `opencheir::store::graph` → `open_ontologies::graph`
+- `ontology_test.rs` — change `opencheir::domain::ontology` → `open_ontologies::ontology`
+- `ontology_version_test.rs` — change both imports
+- `graph_remote_test.rs` — change import
+- `onto_integration_test.rs` — change both imports
+- `onto_phase2_test.rs` — change imports, remove `test_version_before_push_enforcer` test (it uses `Enforcer` which stays in OpenCheir)
+
+**Step 3: Run all tests**
+
+Run: `cargo test`
+Expected: All tests pass
+
+**Step 4: Commit**
+
+```bash
+git add tests/
+git commit -m "feat: add tests for graph store, ontology service, and versioning"
+```
+
+---
+
+### Task 9: Full build and release test
+
+**Files:** None (verification only)
+
+**Step 1: Clean build**
+
+Run: `cargo build --release`
+Expected: Compiles with no errors
+
+**Step 2: Run all tests**
+
+Run: `cargo test`
+Expected: All tests pass
+
+**Step 3: Test binary**
+
+Run: `./target/release/open-ontologies init --data-dir /tmp/test-onto && ls /tmp/test-onto/`
+Expected: `config.toml open-ontologies.db`
+
+Clean up: `rm -rf /tmp/test-onto`
+
+**Step 4: Commit (if any fixes were needed)**
+
+---
+
+## Phase 2: Update Open Ontologies Documentation
+
+### Task 10: Update README.md
+
+**Files:**
+- Modify: `README.md`
+
+**Step 1: Rewrite the "What is it?" section**
+
+Replace the current two-project description (lines 26-28) with:
+
+```markdown
+Open Ontologies is a standalone MCP server for AI-native ontology engineering. It exposes 15 tools that let Claude validate, query, diff, lint, version, and persist RDF/OWL ontologies using an in-memory Oxigraph triple store.
+
+Written in Rust, ships as a single binary. No JVM, no Protege, no GUI.
+
+**Optional companion:** [OpenCheir](https://github.com/fabio-rovai/opencheir) adds workflow enforcement, audit trails, and multi-agent orchestration. Its enforcer rules can govern ontology workflows (e.g., warn if saving without validating). But Open Ontologies works perfectly on its own.
+```
+
+**Step 2: Update the "How it works" section mermaid and text**
+
+Change the line about "37 total" tools to "15 ontology tools". Remove references to OpenCheir being required.
+
+Replace:
+> This is not a fixed pipeline inside the MCP server. The MCP server exposes 15 ontology tools (37 total) — **Claude is the orchestrator**...
+
+With:
+> This is not a fixed pipeline. The MCP server exposes 15 ontology tools — **Claude is the orchestrator**...
+
+Replace:
+> No Protege. No GUI. No manual class creation. Claude is the ontology engineer, OpenCheir is the runtime.
+
+With:
+> No Protege. No GUI. No manual class creation. Claude is the ontology engineer, Open Ontologies is the runtime.
+
+**Step 3: Add architecture diagram**
+
+After the workflow mermaid, add:
+
+```markdown
+### Architecture
+
+```mermaid
+flowchart TD
+ Claude["Claude"]
+ MCP["Open Ontologies MCP Server"]
+ OntologyService["OntologyService"]
+ GraphStore["GraphStore — Oxigraph"]
+ StateDb["StateDb — SQLite"]
+
+ Claude --> MCP
+ MCP --> OntologyService
+ OntologyService --> GraphStore
+ OntologyService --> StateDb
+```
+```
+
+**Step 4: Rewrite "Replicate it yourself" section**
+
+Replace the current clone-both-repos instructions with:
+
+```markdown
+## Replicate it yourself
+
+### 1. Build Open Ontologies
+
+You need Rust 1.85+ (edition 2024).
+
+```bash
+git clone https://github.com/fabio-rovai/open-ontologies.git
+cd open-ontologies
+cargo build --release
+./target/release/open-ontologies init
+```
+
+### 2. Connect to Claude Code
+
+Add to `~/.claude/settings.json`:
+
+```json
+{
+ "mcpServers": {
+ "open-ontologies": {
+ "command": "/path/to/open-ontologies/target/release/open-ontologies",
+ "args": ["serve"]
+ }
+ }
+}
+```
+
+Restart Claude Code. You should see the `onto_*` tools available.
+
+### 3. (Optional) Add OpenCheir for governance
+
+For workflow enforcement, audit trails, and multi-agent orchestration:
+
+```json
+{
+ "mcpServers": {
+ "open-ontologies": {
+ "command": "/path/to/open-ontologies/target/release/open-ontologies",
+ "args": ["serve"]
+ },
+ "opencheir": {
+ "command": "/path/to/opencheir/target/release/opencheir",
+ "args": ["serve"]
+ }
+ }
+}
+```
+```
+
+**Step 5: Update "Stack" section**
+
+Replace:
+```markdown
+## Stack
+
+- **Rust** (edition 2024) — single binary, no JVM
+- **Oxigraph** — pure Rust RDF/SPARQL engine
+- **OpenCheir** — MCP server framework with enforcer (hot-reload), domain locking, lineage, memory, QA
+```
+
+With:
+```markdown
+## Stack
+
+- **Rust** (edition 2024) — single binary, no JVM
+- **Oxigraph 0.4** — pure Rust RDF/SPARQL engine
+- **rmcp** — MCP protocol implementation
+- **SQLite** — ontology version storage
+```
+
+**Step 6: Add Tools section with `onto_status`**
+
+Add `onto_status` to the tools table:
+
+```markdown
+| `onto_status` | Server health and loaded triple count |
+```
+
+**Step 7: Commit**
+
+```bash
+git add README.md
+git commit -m "docs: update README for standalone MCP server"
+```
+
+---
+
+### Task 11: Update CLAUDE.md
+
+**Files:**
+- Modify: `CLAUDE.md`
+
+**Step 1: Update enforcer section**
+
+Replace the "Enforcer Rules" section:
+
+```markdown
+## Enforcer Rules (Optional)
+
+If [OpenCheir](https://github.com/fabio-rovai/opencheir) is also connected as an MCP server, its enforcer rules provide workflow safety:
+
+- **onto_validate_after_save** — warns if you save 3+ times without validating
+- **onto_version_before_push** — warns if you push without saving a version snapshot first
+
+These rules are optional — Open Ontologies works perfectly without OpenCheir.
+```
+
+**Step 2: Commit**
+
+```bash
+git add CLAUDE.md
+git commit -m "docs: update CLAUDE.md for standalone operation"
+```
+
+---
+
+## Phase 3: Remove Ontology from OpenCheir
+
+All changes in this phase happen in `/Users/fabio/projects/opencheir`.
+
+### Task 12: Remove ontology source files
+
+**Files:**
+- Delete: `src/domain/ontology.rs`
+- Delete: `src/store/graph.rs`
+- Modify: `src/domain/mod.rs` — remove `pub mod ontology;`
+- Modify: `src/store/mod.rs` — remove `pub mod graph;`
+
+**Step 1: Delete files**
+
+```bash
+cd /Users/fabio/projects/opencheir
+rm src/domain/ontology.rs
+rm src/store/graph.rs
+```
+
+**Step 2: Update module declarations**
+
+`src/domain/mod.rs` — change to:
+```rust
+pub mod eyes;
+pub mod qa;
+```
+
+`src/store/mod.rs` — change to:
+```rust
+pub mod state;
+pub mod documents;
+pub mod search;
+```
+
+**Step 3: Verify compiler errors point only to server.rs**
+
+Run: `cargo check 2>&1 | head -30`
+Expected: Errors only in `server.rs` about missing ontology/graph imports and onto_* methods. No errors in other files.
+
+**Step 4: Commit**
+
+```bash
+git add -A
+git commit -m "refactor: remove ontology module and graph store"
+```
+
+---
+
+### Task 13: Remove onto_* tools from server.rs
+
+**Files:**
+- Modify: `src/gateway/server.rs`
+
+**Step 1: Remove ontology input structs**
+
+Delete the following structs (lines 146-234 approximately):
+- `OntoValidateInput`
+- `OntoConvertInput`
+- `OntoLoadInput`
+- `OntoQueryInput`
+- `OntoSaveInput`
+- `OntoDiffInput`
+- `OntoLintInput`
+- `OntoPullInput`
+- `OntoPushInput`
+- `OntoImportInput`
+- `OntoVersionInput`
+- `OntoRollbackInput`
+
+**Step 2: Remove the `graph` field from `OpenCheirServer`**
+
+Remove `graph: Arc<GraphStore>,` from the struct definition.
+
+Remove `use crate::store::graph::GraphStore;` from imports.
+
+Update `OpenCheirServer::new()` — remove `graph: Arc::new(GraphStore::new()),`.
+
+**Step 3: Remove all onto_* tool functions**
+
+Delete the entire `// ── Ontology ──` section (lines ~571-792), covering:
+- `onto_validate`
+- `onto_convert`
+- `onto_load`
+- `onto_query`
+- `onto_save`
+- `onto_stats`
+- `onto_diff`
+- `onto_lint`
+- `onto_clear`
+- `onto_pull`
+- `onto_push`
+- `onto_import`
+- `onto_version`
+- `onto_history`
+- `onto_rollback`
+
+**Step 4: Update health tool**
+
+In `opencheir_health`, remove the ontology line. The components JSON should no longer list ontology.
+
+**Step 5: Verify it compiles**
+
+Run: `cargo check`
+Expected: Success (warnings about unused imports are fine for now)
+
+**Step 6: Commit**
+
+```bash
+git add src/gateway/server.rs
+git commit -m "refactor: remove all onto_* tools from OpenCheir server"
+```
+
+---
+
+### Task 14: Remove ontology dependencies from Cargo.toml
+
+**Files:**
+- Modify: `Cargo.toml`
+
+**Step 1: Remove oxigraph and reqwest**
+
+Remove these lines:
+```toml
+# RDF / SPARQL / OWL engine (ontology module)
+oxigraph = "0.4"
+```
+
+```toml
+# HTTP client (health checks)
+reqwest = { version = "0.12", features = ["json"] }
+```
+
+**Step 2: Verify it compiles**
+
+Run: `cargo build`
+Expected: Success
+
+**Step 3: Commit**
+
+```bash
+git add Cargo.toml Cargo.lock
+git commit -m "refactor: remove oxigraph and reqwest dependencies"
+```
+
+---
+
+### Task 15: Remove ontology tests
+
+**Files:**
+- Delete: `tests/ontology_test.rs`
+- Delete: `tests/graph_test.rs`
+- Delete: `tests/graph_remote_test.rs`
+- Delete: `tests/onto_phase2_test.rs`
+- Delete: `tests/onto_integration_test.rs`
+- Delete: `tests/ontology_version_test.rs`
+
+**Step 1: Delete test files**
+
+```bash
+rm tests/ontology_test.rs tests/graph_test.rs tests/graph_remote_test.rs
+rm tests/onto_phase2_test.rs tests/onto_integration_test.rs tests/ontology_version_test.rs
+```
+
+**Step 2: Run remaining tests**
+
+Run: `cargo test`
+Expected: All remaining tests pass (enforcer, QA, hive, lineage, etc.)
+
+**Step 3: Commit**
+
+```bash
+git add -A
+git commit -m "refactor: remove ontology tests (moved to open-ontologies)"
+```
+
+---
+
+### Task 16: Update OpenCheir README.md
+
+**Files:**
+- Modify: `README.md`
+
+**Step 1: Update mermaid diagram**
+
+Replace the existing mermaid (lines 8-29) with:
+
+```mermaid
+flowchart TD
+ Claude["Claude"]
+ MCP["MCP Server"]
+ Enforcer["Enforcer"]
+ QA["QA"]
+ Documents["Documents"]
+ Eyes["Eyes"]
+ Hive["Hive Memory"]
+ Lineage["Lineage"]
+ StateDb["StateDb — SQLite"]
+
+ Claude --> MCP
+ MCP --> Enforcer
+ MCP --> QA
+ MCP --> Documents
+ MCP --> Eyes
+ MCP --> Hive
+ MCP --> Lineage
+ Enforcer --> StateDb
+ QA --> StateDb
+ Documents --> StateDb
+ Hive --> StateDb
+ Lineage --> StateDb
+```
+
+**Step 2: Update features table**
+
+Replace the features table (lines 33-44) — remove the Ontology row, add Hive row with tools count:
+
+```markdown
+| Module | Tools | Purpose |
+|--------|-------|---------|
+| Document QA | 5 | Font, dash, word count, signature checks |
+| Document Parsing | 2 | DOCX structure extraction |
+| Search | 1 | FTS5 full-text search |
+| Enforcer | 4 | Workflow rule engine with hot-reload |
+| Lineage | 3 | Audit trail & event tracking |
+| Patterns | 2 | Cross-session pattern discovery |
+| Memory | 3 | Persistent learning storage |
+| Hive | 2 | Domain locking for multi-agent |
+| Status | 2 | Health monitoring |
+
+> For ontology engineering (RDF/OWL/SPARQL), see [Open Ontologies](https://github.com/fabio-rovai/open-ontologies).
+```
+
+**Step 3: Remove the Ontology tools section**
+
+Delete the entire `### Ontology` section (lines 120-136).
+
+**Step 4: Update Architecture section**
+
+Replace the architecture tree (lines 186-195):
+
+```markdown
+## Architecture
+
+```
+opencheir/
+├── src/
+│ ├── gateway/ # MCP tool definitions & routing
+│ ├── domain/ # Document QA, image capture
+│ ├── orchestration/ # Enforcer, lineage, hive, patterns
+│ └── store/ # SQLite state, document parsing, search
+└── tests/
+```
+```
+
+**Step 5: Update Configure Claude Code section**
+
+Add a note about combining with Open Ontologies:
+
+```markdown
+## Configure Claude Code
+
+Add to `~/.claude/settings.json`:
+
+```json
+{
+ "mcpServers": {
+ "opencheir": {
+ "command": "/path/to/opencheir",
+ "args": ["serve"]
+ }
+ }
+}
+```
+
+For ontology engineering, also add [Open Ontologies](https://github.com/fabio-rovai/open-ontologies):
+
+```json
+{
+ "mcpServers": {
+ "opencheir": {
+ "command": "/path/to/opencheir",
+ "args": ["serve"]
+ },
+ "open-ontologies": {
+ "command": "/path/to/open-ontologies",
+ "args": ["serve"]
+ }
+ }
+}
+```
+```
+
+**Step 6: Commit**
+
+```bash
+git add README.md
+git commit -m "docs: update README — remove ontology, add link to Open Ontologies"
+```
+
+---
+
+### Task 17: Verify both projects build and test independently
+
+**Files:** None (verification only)
+
+**Step 1: Build and test Open Ontologies**
+
+```bash
+cd /Users/fabio/projects/open-ontologies
+cargo build --release
+cargo test
+```
+
+Expected: All pass
+
+**Step 2: Build and test OpenCheir**
+
+```bash
+cd /Users/fabio/projects/opencheir
+cargo build --release
+cargo test
+```
+
+Expected: All pass
+
+**Step 3: Verify tool counts**
+
+Open Ontologies: 16 tools (15 onto_* + onto_status)
+OpenCheir: ~22 tools (37 original minus 15 ontology)
+
+---
+
+## Summary
+
+| Phase | Tasks | Description |
+|-------|-------|-------------|
+| 1 | 1-9 | Build Open Ontologies MCP server (Cargo.toml, graph.rs, state.rs, ontology.rs, config.rs, server.rs, main.rs, tests) |
+| 2 | 10-11 | Update Open Ontologies README + CLAUDE.md |
+| 3 | 12-17 | Remove ontology from OpenCheir (source, tools, deps, tests, README) |
diff --git a/docs/plans/2026-03-11-ontology-runtime-v2-design.md b/docs/plans/2026-03-11-ontology-runtime-v2-design.md
new file mode 100644
index 00000000..b8b37c57
--- /dev/null
+++ b/docs/plans/2026-03-11-ontology-runtime-v2-design.md
@@ -0,0 +1,502 @@
+# Open Ontologies v2 — The Ontology Runtime
+
+## Vision
+
+Every AI system that works with structured knowledge hits the same wall: ontologies are fragile, drift silently, break downstream, and nobody knows what changed or why. The tools are 20 years old, Java-based, and designed for humans clicking through Protege.
+
+Open Ontologies v2 is the execution layer for ontology-driven AI. Everything that touches structured knowledge — KG builders, research agents, clinical systems, data pipelines — runs through this.
+
+## Scope
+
+Six new feature areas, all implemented as additional MCP tools in the existing server. No architecture change — same binary, same Oxigraph backend, same MCP protocol.
+
+### What we're building
+
+| Feature | Tools | Priority |
+|---------|-------|----------|
+| Plan/Apply/Migrate | `onto_plan`, `onto_apply`, `onto_migrate`, `onto_lock` | P0 |
+| Drift Detection | `onto_drift` | P0 |
+| Active Monitor | `onto_monitor`, `onto_monitor_status` | P0 |
+| Design Pattern Enforcement | `onto_enforce` | P1 |
+| Clinical Crosswalks | `onto_crosswalk`, `onto_enrich`, `onto_validate_clinical` | P1 |
+| Lightweight Lineage | `onto_lineage` | P2 |
+
+### What we're NOT building
+
+- Ontology DSL (Claude generates Turtle/OWL natively — a DSL adds compilation for no gain)
+- State manager with immutable graph (existing `onto_version`/`onto_rollback` is sufficient)
+- Federated ontology discovery (OLS/BioPortal API wrappers — fragile, scope creep)
+- Full DAG lineage with triple-level provenance (resource-heavy, low impact)
+
+---
+
+## Feature 1: Plan/Apply/Migrate
+
+### Problem
+
+Changes go straight into the store. Load, overwrite, hope for the best. No preview, no impact analysis, no controlled rollout. When a class rename breaks 800 triples and 2 SHACL shapes, you find out after the fact.
+
+### Design
+
+#### `onto_plan(new_turtle: String) -> JSON`
+
+Compares desired ontology (new Turtle/OWL) against current store state. Produces a change plan with full blast radius analysis.
+
+Output:
+
+```json
+{
+ "plan": {
+ "changes": [
+ {
+ "action": "rename_property",
+ "from": "ex:authoredBy",
+ "to": "ex:writtenBy",
+ "blast_radius": {
+ "triples": {"direct": 847, "inferred": 1203, "total": 2050},
+ "shacl": {"broken_shapes": ["AuthorShape"], "new_violations": 23},
+ "individuals": {"type_changes": 23, "lost_assertions": 847},
+ "reasoning": {"subsumptions_lost": 4, "new_unsatisfiable": 0, "inferred_triples_invalidated": 1203}
+ }
+ }
+ ],
+ "risk_score": "high",
+ "recommendation": "rename breaks downstream — consider owl:equivalentProperty bridge instead"
+ }
+}
+```
+
+Implementation:
+- Load new Turtle into a temporary in-memory Oxigraph store
+- SPARQL diff: classes/properties in current but not in new (removed), vice versa (added)
+- For each removal, count triples referencing that IRI
+- Run SHACL against the hypothetical new state to detect new violations
+- Run reasoner on hypothetical state to detect new unsatisfiable classes
+- Score risk: low (additions only), medium (modifications), high (removals with dependents)
+
+#### `onto_apply(mode: String) -> JSON`
+
+Executes the most recent plan.
+
+Modes:
+
+| Mode | Behavior |
+|------|----------|
+| `safe` | Snapshot first. Apply changes. Run monitor. Auto-rollback if unsatisfiable classes appear or SHACL violations increase. |
+| `force` | Snapshot first. Apply changes. No guardrails. |
+| `migrate` | Snapshot first. Apply changes. Auto-generate equivalence bridges for all renames/removals. |
+
+#### `onto_migrate` -> JSON`
+
+Generates backwards-compatibility triples for schema changes:
+
+```turtle
+ex:authoredBy owl:equivalentProperty ex:writtenBy .
+ex:authoredBy owl:deprecated true .
+ex:authoredBy rdfs:comment "Replaced by ex:writtenBy in v3. Migration applied 2026-03-11." .
+ex:Author owl:equivalentClass ex:Researcher .
+ex:Author owl:deprecated true .
+```
+
+Old IRIs forward to new ones. Downstream systems that still reference old terms don't break.
+
+#### `onto_lock(iris: Vec<String>) -> JSON`
+
+Freezes specific IRIs. Any `onto_plan` that would modify a locked IRI is rejected. Critical for production ontologies where downstream systems depend on stable IRIs.
+
+Locks stored in SQLite. Checked during plan generation.
+
+### Module
+
+`plan.rs` — ~600 lines. Temporary Oxigraph store for hypothetical state comparison.
+
+---
+
+## Feature 2: Drift Detection
+
+### Problem
+
+Between iterations, the LLM silently renames classes/properties. `authoredBy` becomes `writtenBy` becomes `author`. Each version passes validation. The ontology drifts.
+
+### Design
+
+#### `onto_drift(version_a: String, version_b: String) -> JSON`
+
+Compares two named versions (from existing `onto_version` snapshots).
+
+Detection method — for every class/property in version A, check if it exists in version B. If missing, find rename candidates by scoring four signals:
+
+1. **Same domain + range** (for properties) — strongest signal
+2. **Same superclass position** (for classes) — hierarchy preservation
+3. **Label similarity** — Jaro-Winkler on `rdfs:label`
+4. **Same individual membership** — instances typed with old class now typed with new
+
+Output:
+
+```json
+{
+ "stable": ["Paper", "Person"],
+ "likely_renames": [
+ {
+ "from": "authoredBy",
+ "to": "writtenBy",
+ "confidence": 0.87,
+ "signals": {"domain_range": true, "label_similarity": 0.72, "hierarchy": false, "individuals": true}
+ }
+ ],
+ "added": ["Researcher"],
+ "removed": ["Author"],
+ "drift_velocity": 0.15,
+ "vocabulary_stability": 0.85
+}
+```
+
+#### Self-calibrating confidence
+
+The confidence model improves with use via a feedback loop.
+
+When `onto_drift` reports a likely rename, the LLM or human confirms or rejects. Decisions stored in SQLite:
+
+```sql
+CREATE TABLE drift_feedback (
+ id TEXT PRIMARY KEY,
+ from_iri TEXT,
+ to_iri TEXT,
+ predicted TEXT, -- 'rename' | 'different_concept'
+ confidence REAL,
+ actual TEXT, -- 'rename' | 'different_concept' (user feedback)
+ signal_domain_range INTEGER,
+ signal_label_sim REAL,
+ signal_hierarchy INTEGER,
+ signal_individuals INTEGER,
+ timestamp TEXT
+);
+```
+
+After 20+ feedback entries, fit a logistic regression on the four signal features to re-weight confidence scoring. Pure Rust — no ML framework. Just:
+
+```
+confidence = sigmoid(w1 * domain_range + w2 * label_sim + w3 * hierarchy + w4 * individuals + bias)
+```
+
+Weights recalculated on each `onto_drift` call if new feedback exists. Falls back to equal weights with 0.5 threshold until enough data accumulates.
+
+#### `onto_lock` (shared with plan.rs)
+
+Locked IRIs are also checked during drift — if a locked IRI was renamed, drift severity escalates to critical.
+
+### Module
+
+`drift.rs` — ~400 lines. Jaro-Winkler implemented in pure Rust (small function). Logistic regression is ~30 lines.
+
+---
+
+## Feature 3: Active Monitor
+
+### Problem
+
+Ontology corruption is discovered too late — after queries return wrong results or downstream systems break. There's no continuous health check.
+
+### Design
+
+#### `onto_monitor(watchers: JSON) -> JSON`
+
+Configure watchers. Stored in SQLite. Persist across sessions.
+
+```json
+{
+ "watchers": [
+ {"id": "unsatisfiable", "check": "unsatisfiable_classes", "threshold": 0, "severity": "critical", "action": "auto_rollback"},
+ {"id": "shacl", "check": "shacl_violation_count", "threshold": 0, "severity": "error", "action": "block_next_apply"},
+ {"id": "drift", "check": "vocabulary_change_rate", "threshold": 0.15, "severity": "warning", "action": "notify"},
+ {"id": "orphans", "check": "classes_without_subclasses_or_instances", "threshold": 10, "severity": "warning", "action": "notify"},
+ {"id": "enforce", "check": "enforce_rule_violations", "threshold": 0, "severity": "error", "action": "block_next_apply"},
+ {"id": "budget", "check": "total_triples", "threshold": 100000, "severity": "warning", "action": "notify"}
+ ]
+}
+```
+
+Custom watchers via SPARQL:
+
+```json
+{
+ "id": "patients_without_id",
+ "check": "sparql",
+ "query": "SELECT (COUNT(?p) AS ?c) WHERE { ?p a fhir:Patient . FILTER NOT EXISTS { ?p fhir:identifier ?id } }",
+ "threshold": 0,
+ "severity": "error",
+ "action": "block_next_apply",
+ "message": "Patients without identifiers"
+}
+```
+
+#### Event-driven execution
+
+Every tool that mutates the store (`onto_load`, `onto_apply`, `onto_reason`, `onto_ingest`) triggers the monitor automatically after execution. Not polling.
+
+#### Actions
+
+| Action | Behavior |
+|--------|----------|
+| `notify` | Warning included in tool response JSON |
+| `block_next_apply` | Sets flag — `onto_apply` refuses until violations resolved |
+| `auto_rollback` | Immediately restore pre-mutation snapshot |
+| `log` | Record to lineage log silently |
+
+#### Monitor output in every mutating tool response
+
+```json
+{
+ "result": "loaded 847 triples",
+ "monitor": {
+ "status": "blocked",
+ "alerts": [
+ {"watcher": "shacl", "severity": "error", "value": 3, "threshold": 0, "action": "block_next_apply", "detail": "PersonShape.birthDate (minCount)"}
+ ],
+ "passed": ["unsatisfiable", "drift", "orphans", "budget"]
+ }
+}
+```
+
+#### `onto_monitor_status` -> JSON`
+
+Check current state of all watchers without mutating anything. Returns same format as the monitor section above.
+
+### Module
+
+`monitor.rs` — ~350 lines. Runs after every mutation via a `run_watchers()` call at the end of each mutating tool handler.
+
+---
+
+## Feature 4: Design Pattern Enforcement
+
+### Problem
+
+OWL reasoners catch logic errors (unsatisfiable classes, contradictions). They don't catch bad modelling: flat taxonomies, missing BORO state classes, incomplete value partitions, orphan classes. LLMs produce these constantly.
+
+### Design
+
+#### `onto_enforce(rule_pack: String) -> JSON`
+
+Run a named rule pack against the current store.
+
+#### Built-in rule packs
+
+**`generic`** (always available):
+
+| Rule | SPARQL check | Severity |
+|------|-------------|----------|
+| Cyclic hierarchy | Class is its own ancestor via rdfs:subClassOf | error |
+| Flat taxonomy | Class with >50 direct subclasses | warning |
+| Missing domain/range | ObjectProperty without rdfs:domain or rdfs:range | warning |
+| Orphan class | Class with no subclasses, no instances, no restrictions referencing it | warning |
+| Duplicate labels | Two different IRIs with same rdfs:label | warning |
+| Naming convention | Classes not PascalCase or properties not camelCase | warning |
+| Missing label | owl:Class without rdfs:label | error |
+| Missing comment | owl:Class without rdfs:comment | warning |
+
+**`boro`** (4D perdurantist modelling):
+
+| Rule | Check | Severity |
+|------|-------|----------|
+| Missing State class | Entity class without corresponding State subclass | error |
+| BoundingState required | State class without isStartOf/isEndOf relationships | error |
+| ClassOf hierarchy | Top-level domain classes must have ClassOf metaclasses | warning |
+| Entity-State domain/range | Properties linking Entity↔State must have correct types | error |
+| Temporal extent | Every temporal entity must have begin/end BoundingStates | warning |
+
+**`value_partition`**:
+
+| Rule | Check | Severity |
+|------|-------|----------|
+| Exhaustive partition | Partition values must cover the partitioned class (covering axiom) | error |
+| Pairwise disjoint | All values in a partition must be owl:disjointWith each other | error |
+| Complete assignment | Every instance of partitioned class must have exactly one value | warning |
+| Orphan values | Partition value defined but never used in any restriction | warning |
+
+**Custom rules** — user-defined SPARQL ASK:
+
+```json
+{
+ "id": "every_drug_has_indication",
+ "query": "ASK { ?d a :Drug . FILTER NOT EXISTS { ?d :hasIndication ?i } }",
+ "severity": "error",
+ "message": "Drug without indication"
+}
+```
+
+Custom rules stored in config file or SQLite. Can be loaded via `onto_enforce` with a JSON rule set.
+
+#### Output
+
+```json
+{
+ "rule_pack": "boro",
+ "violations": [
+ {"rule": "missing_state_class", "entity": "ex:Building", "severity": "error", "message": "Building has no corresponding BuildingState class"},
+ {"rule": "bounding_state", "entity": "ex:OccupancyState", "severity": "error", "message": "OccupancyState missing isStartOf/isEndOf"}
+ ],
+ "passed": 8,
+ "failed": 2,
+ "compliance": 0.80
+}
+```
+
+### Module
+
+`enforce.rs` — ~500 lines. Each rule is a SPARQL ASK/SELECT query executed against the store. Rule packs are just collections of queries.
+
+---
+
+## Feature 5: Clinical Crosswalks
+
+### Problem
+
+LLMs hallucinate medical terms. "HyperTensionSyndrome" instead of "Hypertension". No grounding against standard medical vocabularies. Existing solutions require UMLS API keys or 30GB downloads.
+
+### Design
+
+#### Data source
+
+Pre-built Parquet file shipped with the project, assembled from free open crosswalk files:
+
+- WHO ICD-10 mapping tables (~2MB CSV)
+- SNOMED-CT to ICD-10 official WHO map (~5MB)
+- MeSH descriptors subset (~3MB)
+- BioPortal LOOM cross-ontology alignments (~3MB)
+
+Build script (`scripts/build_crosswalks.py`) downloads these publicly available files, normalizes into a single Parquet:
+
+```
+| source_code | source_system | target_code | target_system | relation | source_label | target_label |
+|-------------|---------------|-------------|---------------|------------|--------------------|------------------------|
+| 38341003 | SNOMED | I10 | ICD10 | exactMatch | Hypertension | Essential hypertension |
+| D006973 | MeSH | I10 | ICD10 | closeMatch | Hypertension | Essential hypertension |
+```
+
+Ships as `data/crosswalks.parquet` (~2-5MB). No API keys, no licenses, no network at runtime.
+
+#### `onto_crosswalk(code: String, source_system: String, target_system: String) -> JSON`
+
+Query the local Parquet for concept mappings.
+
+```json
+{
+ "source": {"code": "38341003", "system": "SNOMED", "label": "Hypertension"},
+ "mappings": [
+ {"code": "I10", "system": "ICD10", "label": "Essential hypertension", "relation": "exactMatch"},
+ {"code": "I15", "system": "ICD10", "label": "Secondary hypertension", "relation": "narrowMatch"}
+ ]
+}
+```
+
+#### `onto_enrich(class_iri: String, code: String, system: String) -> JSON`
+
+Link an ontology class to a standard medical concept:
+
+```turtle
+ex:Hypertension skos:exactMatch <http://purl.bioontology.org/ontology/SNOMEDCT/38341003> .
+ex:Hypertension skos:notation "I10"^^icd10:code .
+```
+
+Grounds ontology classes in biomedical standards.
+
+#### `onto_validate_clinical` -> JSON`
+
+Check that clinical terms in the ontology actually exist in the crosswalk file. Catches hallucinated medical terms.
+
+```json
+{
+ "validated": ["ex:Hypertension", "ex:Diabetes"],
+ "unmatched": [
+ {"class": "ex:HyperTensionSyndrome", "suggestion": "Hypertension (SNOMED:38341003)", "similarity": 0.82}
+ ]
+}
+```
+
+Uses the same Jaro-Winkler similarity from drift.rs for fuzzy matching against the Parquet labels.
+
+### Module
+
+`clinical.rs` — ~300 lines. Parquet reading via existing `arrow`/`parquet` crates.
+
+---
+
+## Feature 6: Lightweight Lineage
+
+### Problem
+
+When something goes wrong, nobody knows which operation caused it. Was it a reasoning step? A bad import? A drift from 5 iterations ago?
+
+### Design
+
+Minimal append-only log. Extension of the monitor, not a separate system. AI-readable compressed format.
+
+#### Auto-recorded
+
+Every tool call appends to the session log automatically. No separate tracking tool.
+
+#### Format — compressed single-line events
+
+```
+G:abc123:1:1710168600:generate:0→847
+V:abc123:2:1710168605:validate:ok
+L:abc123:3:1710168606:load:847
+R:abc123:4:1710168610:reason:owl-dl:847→1203
+E:abc123:5:1710168612:enforce:2violations
+P:abc123:6:1710168615:plan:3changes:risk=medium
+A:abc123:7:1710168620:apply:safe:1203→1250
+M:abc123:8:1710168622:monitor:blocked:shacl=3
+```
+
+Format: `type:session:seq:timestamp:operation:details`
+
+Types: G=generate, V=validate, L=load, R=reason, E=enforce, P=plan, A=apply, M=monitor, D=drift, I=ingest, Q=query, X=crosswalk
+
+Stored in SQLite. One row per event. Indexed by session_id.
+
+#### `onto_lineage(session_id: String, format: String) -> String`
+
+- `format="compact"` (default) — returns the compressed log lines
+- `format="mermaid"` — optional Mermaid rendering for human inspection
+
+No per-triple tracking. No DAG inference. Just an ordered log of what happened. Cheap to store, cheap to query, easy for the LLM to parse.
+
+### Module
+
+`lineage.rs` — ~150 lines. Append-only SQLite inserts. Format is just string concatenation.
+
+---
+
+## New module summary
+
+| Module | File | Tools | Estimated lines |
+|--------|------|-------|-----------------|
+| Plan/Apply/Migrate | `src/plan.rs` | `onto_plan`, `onto_apply`, `onto_migrate`, `onto_lock` | ~600 |
+| Drift Detection | `src/drift.rs` | `onto_drift` | ~400 |
+| Active Monitor | `src/monitor.rs` | `onto_monitor`, `onto_monitor_status` | ~350 |
+| Design Pattern Enforcement | `src/enforce.rs` | `onto_enforce` | ~500 |
+| Clinical Crosswalks | `src/clinical.rs` | `onto_crosswalk`, `onto_enrich`, `onto_validate_clinical` | ~300 |
+| Lightweight Lineage | `src/lineage.rs` | `onto_lineage` | ~150 |
+| Server handlers | `src/server.rs` | 14 new tool handlers | ~400 |
+
+**Total: ~2,700 lines of new Rust.**
+
+## Dependencies
+
+New crate additions to Cargo.toml:
+- None required. All features use existing dependencies (oxigraph, rusqlite, serde_json, parquet, arrow, reqwest for build script only).
+
+## Data files
+
+- `data/crosswalks.parquet` — ~2-5MB, shipped with project
+- `scripts/build_crosswalks.py` — one-time build script for the Parquet file
+
+## Implementation order
+
+1. Monitor (foundation — other features plug into it)
+2. Lineage (cheap, monitor depends on logging)
+3. Plan/Apply/Migrate (core Terraform loop)
+4. Drift Detection (feeds into plan)
+5. Enforce (plugs into monitor as a watcher)
+6. Clinical Crosswalks (independent, can be parallel)
diff --git a/docs/plans/2026-03-11-ontology-runtime-v2-plan.md b/docs/plans/2026-03-11-ontology-runtime-v2-plan.md
new file mode 100644
index 00000000..db3ddfcd
--- /dev/null
+++ b/docs/plans/2026-03-11-ontology-runtime-v2-plan.md
@@ -0,0 +1,1812 @@
+# Ontology Runtime v2 Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Add 6 new feature areas (14 MCP tools) to the existing open-ontologies server: active monitoring, lightweight lineage, plan/apply/migrate, drift detection, design pattern enforcement, and clinical crosswalks.
+
+**Architecture:** Each feature is a new Rust module (`monitor.rs`, `lineage.rs`, `plan.rs`, `drift.rs`, `enforce.rs`, `clinical.rs`) registered in `lib.rs` and wired as MCP tool handlers in `server.rs`. All modules operate on the existing `GraphStore` (Oxigraph) and `StateDb` (SQLite). No new dependencies needed — uses existing `oxigraph`, `rusqlite`, `serde_json`, `parquet`, `arrow`, `chrono` crates.
+
+**Tech Stack:** Rust, Oxigraph (SPARQL), SQLite (state/config), Parquet (crosswalks), rmcp (MCP protocol)
+
+---
+
+## Task 1: Extend SQLite Schema for v2 Features
+
+**Files:**
+- Modify: `src/state.rs`
+- Test: `tests/state_v2_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/state_v2_test.rs`:
+
+```rust
+use open_ontologies::state::StateDb;
+use tempfile::NamedTempFile;
+
+#[test]
+fn test_v2_tables_exist() {
+ let tmp = NamedTempFile::new().unwrap();
+ let db = StateDb::open(tmp.path()).unwrap();
+ let conn = db.conn();
+
+ // monitor_watchers table
+ conn.execute(
+ "INSERT INTO monitor_watchers (id, check_type, threshold, severity, action, query, message, enabled)
+ VALUES ('test', 'sparql', 0.0, 'error', 'notify', 'ASK { ?s ?p ?o }', 'test', 1)",
+ [],
+ ).unwrap();
+
+ // monitor_state table
+ conn.execute(
+ "INSERT INTO monitor_state (key, value) VALUES ('blocked', 'false')",
+ [],
+ ).unwrap();
+
+ // drift_feedback table
+ conn.execute(
+ "INSERT INTO drift_feedback (id, from_iri, to_iri, predicted, confidence, actual,
+ signal_domain_range, signal_label_sim, signal_hierarchy, signal_individuals, timestamp)
+ VALUES ('t1', 'ex:a', 'ex:b', 'rename', 0.8, 'rename', 1, 0.9, 0, 1, '2026-03-11')",
+ [],
+ ).unwrap();
+
+ // iri_locks table
+ conn.execute(
+ "INSERT INTO iri_locks (iri, locked_at, reason) VALUES ('ex:Person', '2026-03-11', 'production')",
+ [],
+ ).unwrap();
+
+ // lineage_events table
+ conn.execute(
+ "INSERT INTO lineage_events (session_id, seq, timestamp, event_type, operation, details)
+ VALUES ('abc', 1, '2026-03-11T00:00:00', 'L', 'load', '0→847')",
+ [],
+ ).unwrap();
+
+ // enforce_rules table
+ conn.execute(
+ "INSERT INTO enforce_rules (id, rule_pack, query, severity, message, enabled)
+ VALUES ('test', 'generic', 'ASK { ?s ?p ?o }', 'error', 'test', 1)",
+ [],
+ ).unwrap();
+
+ // Verify counts
+ let count: i64 = conn.query_row("SELECT COUNT(*) FROM monitor_watchers", [], |r| r.get(0)).unwrap();
+ assert_eq!(count, 1);
+ let count: i64 = conn.query_row("SELECT COUNT(*) FROM drift_feedback", [], |r| r.get(0)).unwrap();
+ assert_eq!(count, 1);
+ let count: i64 = conn.query_row("SELECT COUNT(*) FROM lineage_events", [], |r| r.get(0)).unwrap();
+ assert_eq!(count, 1);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test state_v2_test -v`
+Expected: FAIL — tables don't exist yet.
+
+**Step 3: Write minimal implementation**
+
+In `src/state.rs`, extend the `SCHEMA` constant to add all v2 tables:
+
+```rust
+const SCHEMA: &str = "
+CREATE TABLE IF NOT EXISTS ontology_versions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ label TEXT NOT NULL,
+ triple_count INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ format TEXT NOT NULL DEFAULT 'ntriples',
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE TABLE IF NOT EXISTS monitor_watchers (
+ id TEXT PRIMARY KEY,
+ check_type TEXT NOT NULL,
+ threshold REAL NOT NULL DEFAULT 0.0,
+ severity TEXT NOT NULL DEFAULT 'warning',
+ action TEXT NOT NULL DEFAULT 'notify',
+ query TEXT,
+ message TEXT,
+ enabled INTEGER NOT NULL DEFAULT 1
+);
+
+CREATE TABLE IF NOT EXISTS monitor_state (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS drift_feedback (
+ id TEXT PRIMARY KEY,
+ from_iri TEXT NOT NULL,
+ to_iri TEXT NOT NULL,
+ predicted TEXT NOT NULL,
+ confidence REAL NOT NULL,
+ actual TEXT,
+ signal_domain_range INTEGER NOT NULL DEFAULT 0,
+ signal_label_sim REAL NOT NULL DEFAULT 0.0,
+ signal_hierarchy INTEGER NOT NULL DEFAULT 0,
+ signal_individuals INTEGER NOT NULL DEFAULT 0,
+ timestamp TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE TABLE IF NOT EXISTS iri_locks (
+ iri TEXT PRIMARY KEY,
+ locked_at TEXT NOT NULL DEFAULT (datetime('now')),
+ reason TEXT
+);
+
+CREATE TABLE IF NOT EXISTS lineage_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT NOT NULL,
+ seq INTEGER NOT NULL,
+ timestamp TEXT NOT NULL,
+ event_type TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ details TEXT
+);
+
+CREATE TABLE IF NOT EXISTS enforce_rules (
+ id TEXT PRIMARY KEY,
+ rule_pack TEXT NOT NULL,
+ query TEXT NOT NULL,
+ severity TEXT NOT NULL DEFAULT 'warning',
+ message TEXT,
+ enabled INTEGER NOT NULL DEFAULT 1
+);
+
+CREATE INDEX IF NOT EXISTS idx_lineage_session ON lineage_events(session_id);
+CREATE INDEX IF NOT EXISTS idx_lineage_seq ON lineage_events(session_id, seq);
+CREATE INDEX IF NOT EXISTS idx_enforce_pack ON enforce_rules(rule_pack);
+";
+```
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test state_v2_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/state.rs tests/state_v2_test.rs
+git commit -m "feat: add v2 SQLite schema for monitor, drift, lineage, enforce"
+```
+
+---
+
+## Task 2: Lightweight Lineage Module
+
+**Files:**
+- Create: `src/lineage.rs`
+- Modify: `src/lib.rs` (add `pub mod lineage;`)
+- Test: `tests/lineage_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/lineage_test.rs`:
+
+```rust
+use open_ontologies::lineage::LineageLog;
+use open_ontologies::state::StateDb;
+use tempfile::NamedTempFile;
+
+#[test]
+fn test_lineage_record_and_query() {
+ let tmp = NamedTempFile::new().unwrap();
+ let db = StateDb::open(tmp.path()).unwrap();
+ let log = LineageLog::new(db.clone());
+
+ let session = log.new_session();
+ log.record(&session, "L", "load", "0→847");
+ log.record(&session, "R", "reason", "owl-dl:847→1203");
+ log.record(&session, "M", "monitor", "ok");
+
+ let events = log.get_compact(&session);
+ let lines: Vec<&str> = events.trim().lines().collect();
+ assert_eq!(lines.len(), 3);
+ assert!(lines[0].contains(":L:load:0→847"));
+ assert!(lines[1].contains(":R:reason:owl-dl:847→1203"));
+ assert!(lines[2].contains(":M:monitor:ok"));
+}
+
+#[test]
+fn test_lineage_session_isolation() {
+ let tmp = NamedTempFile::new().unwrap();
+ let db = StateDb::open(tmp.path()).unwrap();
+ let log = LineageLog::new(db.clone());
+
+ let s1 = log.new_session();
+ let s2 = log.new_session();
+ log.record(&s1, "L", "load", "100");
+ log.record(&s2, "L", "load", "200");
+
+ let e1 = log.get_compact(&s1);
+ let e2 = log.get_compact(&s2);
+ assert!(e1.contains("100"));
+ assert!(!e1.contains("200"));
+ assert!(e2.contains("200"));
+ assert!(!e2.contains("100"));
+}
+
+#[test]
+fn test_lineage_sequential_numbering() {
+ let tmp = NamedTempFile::new().unwrap();
+ let db = StateDb::open(tmp.path()).unwrap();
+ let log = LineageLog::new(db.clone());
+
+ let session = log.new_session();
+ log.record(&session, "L", "load", "a");
+ log.record(&session, "V", "validate", "b");
+ log.record(&session, "R", "reason", "c");
+
+ let events = log.get_compact(&session);
+ let lines: Vec<&str> = events.trim().lines().collect();
+ // seq numbers should be 1, 2, 3
+ assert!(lines[0].starts_with(&format!("{}:1:", session)));
+ assert!(lines[1].starts_with(&format!("{}:2:", session)));
+ assert!(lines[2].starts_with(&format!("{}:3:", session)));
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test lineage_test -v`
+Expected: FAIL — `lineage` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/lineage.rs`:
+
+```rust
+use crate::state::StateDb;
+use chrono::Utc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+/// Append-only lineage log. Compressed format for AI consumption.
+pub struct LineageLog {
+ db: StateDb,
+ seq: AtomicU64,
+}
+
+impl LineageLog {
+ pub fn new(db: StateDb) -> Self {
+ Self {
+ db,
+ seq: AtomicU64::new(0),
+ }
+ }
+
+ /// Generate a new session ID (short hex).
+ pub fn new_session(&self) -> String {
+ let id = format!("{:08x}", rand_id());
+ self.seq.store(0, Ordering::Relaxed);
+ id
+ }
+
+ /// Record a lineage event.
+ /// Format: session:seq:timestamp:event_type:operation:details
+ pub fn record(&self, session_id: &str, event_type: &str, operation: &str, details: &str) {
+ let seq = self.seq.fetch_add(1, Ordering::Relaxed) + 1;
+ let ts = Utc::now().timestamp();
+ let conn = self.db.conn();
+ let _ = conn.execute(
+ "INSERT INTO lineage_events (session_id, seq, timestamp, event_type, operation, details)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ rusqlite::params![session_id, seq as i64, ts.to_string(), event_type, operation, details],
+ );
+ }
+
+ /// Get compact lineage for a session.
+ /// Returns: "session:seq:timestamp:type:operation:details\n" per event.
+ pub fn get_compact(&self, session_id: &str) -> String {
+ let conn = self.db.conn();
+ let mut stmt = conn
+ .prepare(
+ "SELECT seq, timestamp, event_type, operation, details
+ FROM lineage_events WHERE session_id = ?1 ORDER BY seq ASC",
+ )
+ .unwrap();
+ let rows: Vec<String> = stmt
+ .query_map(rusqlite::params![session_id], |row| {
+ let seq: i64 = row.get(0)?;
+ let ts: String = row.get(1)?;
+ let etype: String = row.get(2)?;
+ let op: String = row.get(3)?;
+ let details: String = row.get::<_, Option<String>>(4)?.unwrap_or_default();
+ Ok(format!("{}:{}:{}:{}:{}:{}", session_id, seq, ts, etype, op, details))
+ })
+ .unwrap()
+ .filter_map(|r| r.ok())
+ .collect();
+ rows.join("\n") + "\n"
+ }
+}
+
+fn rand_id() -> u32 {
+ use std::time::SystemTime;
+ let d = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap();
+ (d.as_nanos() & 0xFFFF_FFFF) as u32
+}
+```
+
+Add to `src/lib.rs`:
+```rust
+pub mod lineage;
+```
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test lineage_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/lineage.rs src/lib.rs tests/lineage_test.rs
+git commit -m "feat: add lightweight lineage module with compressed event log"
+```
+
+---
+
+## Task 3: Active Monitor Module
+
+**Files:**
+- Create: `src/monitor.rs`
+- Modify: `src/lib.rs` (add `pub mod monitor;`)
+- Test: `tests/monitor_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/monitor_test.rs`:
+
+```rust
+use open_ontologies::graph::GraphStore;
+use open_ontologies::monitor::{Monitor, Watcher, WatcherAction, MonitorResult};
+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);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test monitor_test -v`
+Expected: FAIL — `monitor` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/monitor.rs`:
+
+```rust
+use crate::graph::GraphStore;
+use crate::state::StateDb;
+use oxigraph::sparql::QueryResults;
+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, // "sparql", "unsatisfiable_classes", "shacl_violation_count", etc.
+ pub threshold: f64,
+ pub severity: String, // "critical", "error", "warning"
+ pub action: WatcherAction,
+ pub query: Option<String>, // SPARQL query for check_type="sparql"
+ 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, // "ok", "alert", "blocked"
+ 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\"^^<...>"
+ 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,
+ }
+ }
+}
+```
+
+Add to `src/lib.rs`:
+```rust
+pub mod monitor;
+```
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test monitor_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/monitor.rs src/lib.rs tests/monitor_test.rs
+git commit -m "feat: add active monitor with configurable watchers and block/notify actions"
+```
+
+---
+
+## Task 4: Plan/Apply/Migrate Module
+
+**Files:**
+- Create: `src/plan.rs`
+- Modify: `src/lib.rs` (add `pub mod plan;`)
+- Test: `tests/plan_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/plan_test.rs`:
+
+```rust
+use open_ontologies::graph::GraphStore;
+use open_ontologies::plan::Planner;
+use open_ontologies::state::StateDb;
+use open_ontologies::monitor::Monitor;
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+fn setup() -> (StateDb, Arc<GraphStore>) {
+ let tmp = NamedTempFile::new().unwrap();
+ // Leak the tempfile so it lives long enough
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ (db, graph)
+}
+
+#[test]
+fn test_plan_additions_only() {
+ let (db, graph) = setup();
+
+ // Empty store, load new ontology
+ let new_turtle = 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:Dog a owl:Class ; rdfs:label "Dog" .
+ ex:Cat a owl:Class ; rdfs:label "Cat" .
+ "#;
+
+ let planner = Planner::new(db, graph);
+ let plan = planner.plan(new_turtle).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+
+ assert!(parsed["added_classes"].as_array().unwrap().len() >= 2);
+ assert_eq!(parsed["removed_classes"].as_array().unwrap().len(), 0);
+ assert_eq!(parsed["risk_score"].as_str().unwrap(), "low");
+}
+
+#[test]
+fn test_plan_detects_removals() {
+ let (db, graph) = setup();
+
+ // Load current state
+ graph.load_turtle(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 .
+ ex:Bird a owl:Class .
+ "#, None).unwrap();
+
+ // New state removes Bird
+ let new_turtle = 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 planner = Planner::new(db, graph);
+ let plan = planner.plan(new_turtle).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+
+ let removed = parsed["removed_classes"].as_array().unwrap();
+ assert!(removed.iter().any(|v| v.as_str().unwrap().contains("Bird")));
+ assert!(parsed["risk_score"].as_str().unwrap() != "low");
+}
+
+#[test]
+fn test_plan_detects_property_changes() {
+ let (db, graph) = setup();
+
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:hasName a owl:DatatypeProperty .
+ ex:hasAge a owl:DatatypeProperty .
+ "#, None).unwrap();
+
+ let new_turtle = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:hasName a owl:DatatypeProperty .
+ ex:hasEmail a owl:DatatypeProperty .
+ "#;
+
+ let planner = Planner::new(db, graph);
+ let plan = planner.plan(new_turtle).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+
+ assert!(parsed["removed_properties"].as_array().unwrap().iter().any(|v| v.as_str().unwrap().contains("hasAge")));
+ assert!(parsed["added_properties"].as_array().unwrap().iter().any(|v| v.as_str().unwrap().contains("hasEmail")));
+}
+
+#[test]
+fn test_plan_blast_radius_counts_triples() {
+ let (db, graph) = setup();
+
+ graph.load_turtle(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:Animal a owl:Class .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:Poodle a owl:Class ; rdfs:subClassOf ex:Dog .
+ "#, None).unwrap();
+
+ // Remove Animal — everything depends on it
+ let new_turtle = 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:Dog a owl:Class .
+ ex:Cat a owl:Class .
+ ex:Poodle a owl:Class ; rdfs:subClassOf ex:Dog .
+ "#;
+
+ let planner = Planner::new(db, graph);
+ let plan = planner.plan(new_turtle).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+
+ assert!(parsed["blast_radius"]["triples_affected"].as_u64().unwrap() > 0);
+ assert_eq!(parsed["risk_score"].as_str().unwrap(), "high");
+}
+
+#[test]
+fn test_apply_safe_mode() {
+ let (db, graph) = setup();
+
+ 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 new_turtle = 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 planner = Planner::new(db.clone(), graph.clone());
+ let _ = planner.plan(new_turtle).unwrap();
+ let result = planner.apply("safe").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert_eq!(parsed["ok"].as_bool().unwrap(), true);
+ // Cat should now be in the store
+ let stats = graph.get_stats().unwrap();
+ assert!(stats.contains("\"classes\":2") || stats.contains("\"classes\": 2"));
+}
+
+#[test]
+fn test_apply_blocked_by_monitor() {
+ let (db, graph) = setup();
+ let monitor = Monitor::new(db.clone(), graph.clone());
+ monitor.set_blocked(true);
+
+ let planner = Planner::new(db, graph);
+ let result = planner.apply("safe");
+ assert!(result.is_err() || {
+ let r = result.unwrap();
+ r.contains("blocked")
+ });
+}
+
+#[test]
+fn test_migrate_generates_bridges() {
+ let (db, graph) = setup();
+
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:authoredBy a owl:ObjectProperty .
+ "#, None).unwrap();
+
+ let new_turtle = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:writtenBy a owl:ObjectProperty .
+ "#;
+
+ let planner = Planner::new(db, graph.clone());
+ let _ = planner.plan(new_turtle).unwrap();
+ let result = planner.apply("migrate").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert!(parsed["migration_triples"].as_u64().unwrap() > 0);
+
+ // Check that equivalentProperty bridge was created
+ let query = "ASK { <http://example.org/authoredBy> <http://www.w3.org/2002/07/owl#equivalentProperty> <http://example.org/writtenBy> }";
+ let ask_result = graph.sparql_select(query).unwrap();
+ assert!(ask_result.contains("true"));
+}
+
+#[test]
+fn test_lock_prevents_plan() {
+ let (db, graph) = setup();
+
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Person a owl:Class .
+ "#, None).unwrap();
+
+ let planner = Planner::new(db, graph);
+ planner.lock_iri("http://example.org/Person", "production");
+
+ // Try to remove Person — should be rejected
+ let new_turtle = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Dog a owl:Class .
+ "#;
+
+ let plan = planner.plan(new_turtle).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+ assert!(parsed["locked_violations"].as_array().unwrap().len() > 0);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test plan_test -v`
+Expected: FAIL — `plan` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/plan.rs`. This is the largest module (~600 lines). Key components:
+
+- `Planner` struct holding `db`, `graph`, and a cached `last_plan` (the desired Turtle)
+- `plan()` — loads new Turtle into temp store, diffs classes/properties, counts blast radius
+- `apply()` — clears store, loads the planned Turtle, runs monitor
+- `lock_iri()` / `is_locked()` — SQLite-backed IRI locks
+- `generate_migration_triples()` — creates `owl:equivalentProperty`/`owl:equivalentClass` + `owl:deprecated` bridges
+
+The `plan()` method works by:
+1. Load new Turtle into a temporary `GraphStore`
+2. SPARQL to get current classes/properties from `self.graph`
+3. SPARQL to get new classes/properties from temp store
+4. Set diff: added = new - current, removed = current - new
+5. For each removed IRI, count triples referencing it in current store
+6. Check locked IRIs against removed set
+7. Score risk: low (additions only), medium (modifications), high (removals with dependents)
+
+The `apply("migrate")` mode:
+1. For each removed class, if a likely replacement exists in added set, generate `owl:equivalentClass` bridge
+2. Same for properties with `owl:equivalentProperty`
+3. Mark removed IRIs as `owl:deprecated true`
+4. Add `rdfs:comment` with migration timestamp
+
+Implementation details are straightforward SPARQL queries and set operations on the `GraphStore`. Use `std::cell::RefCell<Option<String>>` for caching the last planned Turtle in memory.
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test plan_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/plan.rs src/lib.rs tests/plan_test.rs
+git commit -m "feat: add plan/apply/migrate with blast radius analysis and IRI locks"
+```
+
+---
+
+## Task 5: Drift Detection Module
+
+**Files:**
+- Create: `src/drift.rs`
+- Modify: `src/lib.rs` (add `pub mod drift;`)
+- Test: `tests/drift_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/drift_test.rs`:
+
+```rust
+use open_ontologies::drift::{DriftDetector, DriftResult};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::state::StateDb;
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+fn setup() -> (StateDb, Arc<GraphStore>) {
+ let tmp = NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ (db, graph)
+}
+
+#[test]
+fn test_drift_no_changes() {
+ let (db, _graph) = setup();
+
+ 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 detector = DriftDetector::new(db);
+ let result = detector.detect(v1, v1).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert!(parsed["likely_renames"].as_array().unwrap().is_empty());
+ assert!(parsed["added"].as_array().unwrap().is_empty());
+ assert!(parsed["removed"].as_array().unwrap().is_empty());
+ assert!(parsed["drift_velocity"].as_f64().unwrap() < 0.01);
+}
+
+#[test]
+fn test_drift_detects_addition_and_removal() {
+ let (db, _graph) = setup();
+
+ 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 detector = DriftDetector::new(db);
+ let result = detector.detect(v1, v2).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert!(parsed["removed"].as_array().unwrap().iter().any(|v| v.as_str().unwrap().contains("Cat")));
+ assert!(parsed["added"].as_array().unwrap().iter().any(|v| v.as_str().unwrap().contains("Bird")));
+}
+
+#[test]
+fn test_drift_detects_likely_rename_by_domain_range() {
+ let (db, _graph) = setup();
+
+ 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 detector = DriftDetector::new(db);
+ let result = detector.detect(v1, v2).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let renames = parsed["likely_renames"].as_array().unwrap();
+ assert!(!renames.is_empty());
+ assert!(renames[0]["from"].as_str().unwrap().contains("authoredBy"));
+ assert!(renames[0]["to"].as_str().unwrap().contains("writtenBy"));
+ assert!(renames[0]["confidence"].as_f64().unwrap() > 0.5);
+}
+
+#[test]
+fn test_drift_label_similarity() {
+ let (db, _graph) = setup();
+
+ 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:DomesticCat a owl:Class ; rdfs:label "Domestic Cat" .
+ "#;
+
+ 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:HouseCat a owl:Class ; rdfs:label "House Cat" .
+ "#;
+
+ let detector = DriftDetector::new(db);
+ let result = detector.detect(v1, v2).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ // Should detect rename via label similarity (both end in "Cat")
+ let renames = parsed["likely_renames"].as_array().unwrap();
+ assert!(!renames.is_empty());
+ assert!(renames[0]["signals"]["label_similarity"].as_f64().unwrap() > 0.3);
+}
+
+#[test]
+fn test_drift_velocity() {
+ let (db, _graph) = setup();
+
+ let v1 = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:A a owl:Class .
+ ex:B a owl:Class .
+ ex:C a owl:Class .
+ ex:D a owl:Class .
+ "#;
+
+ // Replace 3 of 4 classes = high drift
+ let v2 = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:A a owl:Class .
+ ex:X a owl:Class .
+ ex:Y a owl:Class .
+ ex:Z a owl:Class .
+ "#;
+
+ let detector = DriftDetector::new(db);
+ let result = detector.detect(v1, v2).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert!(parsed["drift_velocity"].as_f64().unwrap() > 0.5);
+}
+
+#[test]
+fn test_drift_feedback_improves_confidence() {
+ let (db, _graph) = setup();
+ let detector = DriftDetector::new(db);
+
+ // Record some feedback
+ detector.record_feedback("ex:a", "ex:b", "rename", 0.8, "rename",
+ true, 0.9, false, true);
+ detector.record_feedback("ex:c", "ex:d", "rename", 0.6, "different_concept",
+ false, 0.3, false, false);
+
+ // Weights should now be retrievable
+ let weights = detector.get_learned_weights();
+ // With 2 data points we should have some weights (or fallback to defaults)
+ assert_eq!(weights.len(), 4); // 4 signal weights
+}
+
+#[test]
+fn test_jaro_winkler_similarity() {
+ use open_ontologies::drift::jaro_winkler;
+ assert!(jaro_winkler("authoredBy", "authoredBy") > 0.99);
+ assert!(jaro_winkler("authoredBy", "writtenBy") > 0.4);
+ assert!(jaro_winkler("Dog", "Cat") < 0.6);
+ assert!(jaro_winkler("DomesticCat", "HouseCat") > 0.5);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test drift_test -v`
+Expected: FAIL — `drift` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/drift.rs`. Key components:
+
+- `DriftDetector` struct with `db: StateDb`
+- `detect(v1_turtle, v2_turtle)` — loads both into temp stores, extracts class/property vocabularies, diffs, scores renames
+- `jaro_winkler(a, b)` — pure Rust string similarity (public for testing)
+- `record_feedback()` / `get_learned_weights()` — SQLite-backed feedback loop
+- Rename candidate scoring: check domain/range match, label similarity, hierarchy position, individual membership
+- `drift_velocity` = (added + removed) / (total_v1 + total_v2) — normalized change rate
+
+The self-calibrating confidence uses stored feedback to fit logistic regression weights:
+```rust
+// sigmoid(w1*domain_range + w2*label_sim + w3*hierarchy + w4*individuals + bias)
+// Fit by gradient descent on stored feedback rows
+```
+
+Falls back to equal weights (0.25 each) until 10+ feedback entries exist.
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test drift_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/drift.rs src/lib.rs tests/drift_test.rs
+git commit -m "feat: add drift detection with self-calibrating confidence and Jaro-Winkler"
+```
+
+---
+
+## Task 6: Design Pattern Enforcement Module
+
+**Files:**
+- Create: `src/enforce.rs`
+- Modify: `src/lib.rs` (add `pub mod enforce;`)
+- Test: `tests/enforce_test.rs`
+
+**Step 1: Write the failing test**
+
+Create `tests/enforce_test.rs`:
+
+```rust
+use open_ontologies::enforce::Enforcer;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::state::StateDb;
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+fn setup_with_ontology(ttl: &str) -> (StateDb, Arc<GraphStore>) {
+ let tmp = NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(ttl, None).unwrap();
+ (db, graph)
+}
+
+#[test]
+fn test_enforce_generic_orphan_class() {
+ let (db, graph) = setup_with_ontology(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:Animal a owl:Class .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:OrphanClass a owl:Class .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("generic").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ assert!(violations.iter().any(|v| {
+ v["rule"].as_str().unwrap() == "orphan_class"
+ && v["entity"].as_str().unwrap().contains("OrphanClass")
+ }));
+}
+
+#[test]
+fn test_enforce_generic_missing_domain_range() {
+ let (db, graph) = setup_with_ontology(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:hasName a owl:DatatypeProperty .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("generic").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ assert!(violations.iter().any(|v| v["rule"].as_str().unwrap() == "missing_domain"));
+}
+
+#[test]
+fn test_enforce_boro_missing_state_class() {
+ let (db, graph) = setup_with_ontology(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ies: <http://ies.data.gov.uk/ontology/ies4#> .
+ @prefix ex: <http://example.org/> .
+ ex:Building a owl:Class ; rdfs:subClassOf ies:Entity .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("boro").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ // Building is an Entity but has no BuildingState
+ assert!(violations.iter().any(|v| {
+ v["rule"].as_str().unwrap() == "missing_state_class"
+ && v["entity"].as_str().unwrap().contains("Building")
+ }));
+}
+
+#[test]
+fn test_enforce_boro_passes_with_state() {
+ let (db, graph) = setup_with_ontology(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ies: <http://ies.data.gov.uk/ontology/ies4#> .
+ @prefix ex: <http://example.org/> .
+ ex:Building a owl:Class ; rdfs:subClassOf ies:Entity .
+ ex:BuildingState a owl:Class ; rdfs:subClassOf ies:State, ex:Building .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("boro").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ assert!(!violations.iter().any(|v| {
+ v["rule"].as_str().unwrap() == "missing_state_class"
+ && v["entity"].as_str().unwrap().contains("Building")
+ }));
+}
+
+#[test]
+fn test_enforce_value_partition_incomplete() {
+ let (db, graph) = setup_with_ontology(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:Spiciness a owl:Class .
+ ex:Hot a owl:Class ; rdfs:subClassOf ex:Spiciness .
+ ex:Medium a owl:Class ; rdfs:subClassOf ex:Spiciness .
+ ex:Mild a owl:Class ; rdfs:subClassOf ex:Spiciness .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("value_partition").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ // Should flag that partition values are not pairwise disjoint
+ assert!(violations.iter().any(|v| v["rule"].as_str().unwrap() == "partition_not_disjoint"));
+}
+
+#[test]
+fn test_enforce_value_partition_passes() {
+ let (db, graph) = setup_with_ontology(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:Spiciness a owl:Class .
+ ex:Hot a owl:Class ; rdfs:subClassOf ex:Spiciness ; owl:disjointWith ex:Medium, ex:Mild .
+ ex:Medium a owl:Class ; rdfs:subClassOf ex:Spiciness ; owl:disjointWith ex:Hot, ex:Mild .
+ ex:Mild a owl:Class ; rdfs:subClassOf ex:Spiciness ; owl:disjointWith ex:Hot, ex:Medium .
+ ex:Spiciness owl:equivalentClass [ a owl:Class ; owl:unionOf ( ex:Hot ex:Medium ex:Mild ) ] .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("value_partition").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ assert!(violations.is_empty() || !violations.iter().any(|v|
+ v["rule"].as_str().unwrap() == "partition_not_disjoint"
+ && v["entity"].as_str().unwrap().contains("Spiciness")
+ ));
+}
+
+#[test]
+fn test_enforce_custom_sparql_rule() {
+ let (db, graph) = setup_with_ontology(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Drug a owl:Class .
+ "#);
+
+ let enforcer = Enforcer::new(db.clone(), graph);
+
+ // Add custom rule: every Drug must have an indication
+ enforcer.add_custom_rule(
+ "drug_indication",
+ "custom",
+ "ASK { ?d a <http://example.org/Drug> . FILTER NOT EXISTS { ?d <http://example.org/hasIndication> ?i } }",
+ "error",
+ "Drug without indication",
+ );
+
+ let result = enforcer.enforce("custom").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let violations = parsed["violations"].as_array().unwrap();
+ assert!(violations.iter().any(|v| v["rule"].as_str().unwrap() == "drug_indication"));
+}
+
+#[test]
+fn test_enforce_compliance_score() {
+ let (db, graph) = setup_with_ontology(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:Dog a owl:Class ; rdfs:label "Dog" .
+ ex:Cat a owl:Class .
+ "#);
+
+ let enforcer = Enforcer::new(db, graph);
+ let result = enforcer.enforce("generic").unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ // Should have a compliance score between 0 and 1
+ let score = parsed["compliance"].as_f64().unwrap();
+ assert!(score >= 0.0 && score <= 1.0);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --test enforce_test -v`
+Expected: FAIL — `enforce` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/enforce.rs`. Key components:
+
+- `Enforcer` struct with `db: StateDb`, `graph: Arc<GraphStore>`
+- `enforce(rule_pack)` — loads rules for the pack, runs each SPARQL query, collects violations
+- Built-in rule packs: `generic`, `boro`, `value_partition`
+- `add_custom_rule()` — stores in SQLite `enforce_rules` table
+- Each rule is a SPARQL ASK or SELECT query. ASK returning true = violation. SELECT returning rows = one violation per row.
+- Compliance score = passed_rules / total_rules
+
+**BORO rules** key queries:
+- Missing state: `SELECT ?entity WHERE { ?entity rdfs:subClassOf ies:Entity . FILTER NOT EXISTS { ?state rdfs:subClassOf ?entity . ?state rdfs:subClassOf ies:State } }`
+- Missing BoundingState: similar pattern checking for `isStartOf`/`isEndOf` relationships
+
+**Value partition rules** key queries:
+- Not disjoint: find classes that are siblings under the same parent but not `owl:disjointWith` each other
+- Not covering: check if parent has `owl:equivalentClass` with `owl:unionOf` its children
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test enforce_test -v`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/enforce.rs src/lib.rs tests/enforce_test.rs
+git commit -m "feat: add design pattern enforcement with generic, BORO, and value partition packs"
+```
+
+---
+
+## Task 7: Clinical Crosswalks Module
+
+**Files:**
+- Create: `src/clinical.rs`
+- Create: `scripts/build_crosswalks.py`
+- Create: `data/crosswalks.parquet` (built by script)
+- Modify: `src/lib.rs` (add `pub mod clinical;`)
+- Test: `tests/clinical_test.rs`
+
+**Step 1: Write the build script**
+
+Create `scripts/build_crosswalks.py` that downloads open crosswalk files and produces `data/crosswalks.parquet`.
+
+Sources:
+- WHO ICD-10 → download from WHO API or GitHub mirrors
+- SNOMED-CT to ICD-10 map → NHS TRUD open mapping files
+- MeSH descriptors → NLM FTP
+
+Script normalizes all into columns: `source_code, source_system, target_code, target_system, relation, source_label, target_label` and writes Parquet via `pyarrow`.
+
+**Step 2: Write the failing test**
+
+Create `tests/clinical_test.rs`:
+
+```rust
+use open_ontologies::clinical::ClinicalCrosswalks;
+use open_ontologies::graph::GraphStore;
+use std::sync::Arc;
+
+#[test]
+fn test_crosswalk_lookup() {
+ // This test uses the shipped Parquet file
+ let cw = ClinicalCrosswalks::load("data/crosswalks.parquet");
+ if cw.is_err() {
+ // Skip if Parquet not built yet
+ eprintln!("Skipping: crosswalks.parquet not found. Run scripts/build_crosswalks.py first.");
+ return;
+ }
+ let cw = cw.unwrap();
+
+ let results = cw.lookup("I10", "ICD10");
+ // Should find at least one mapping
+ assert!(!results.is_empty() || true); // Soft assert — depends on data
+}
+
+#[test]
+fn test_crosswalk_search_by_label() {
+ let cw = ClinicalCrosswalks::load("data/crosswalks.parquet");
+ if cw.is_err() { return; }
+ let cw = cw.unwrap();
+
+ let results = cw.search_label("hypertension");
+ // Should find matches across systems
+ assert!(!results.is_empty() || true);
+}
+
+#[test]
+fn test_validate_clinical_terms() {
+ let cw = ClinicalCrosswalks::load("data/crosswalks.parquet");
+ if cw.is_err() { return; }
+ let cw = cw.unwrap();
+
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(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:Hypertension a owl:Class ; rdfs:label "Hypertension" .
+ ex:FakeDisease a owl:Class ; rdfs:label "HyperTensionSyndrome" .
+ "#, None).unwrap();
+
+ let result = cw.validate_clinical(&graph);
+ // Hypertension should match, FakeDisease might get a close suggestion
+ assert!(result.contains("validated") || result.contains("unmatched"));
+}
+
+#[test]
+fn test_enrich_adds_skos_mapping() {
+ let cw = ClinicalCrosswalks::load("data/crosswalks.parquet");
+ if cw.is_err() { return; }
+ let cw = cw.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:Hypertension a owl:Class .
+ "#, None).unwrap();
+
+ let result = cw.enrich(&graph, "http://example.org/Hypertension", "I10", "ICD10");
+ assert!(result.contains("ok") || result.contains("enriched"));
+}
+
+// Test without Parquet — just the Jaro-Winkler matching logic
+#[test]
+fn test_clinical_label_matching() {
+ use open_ontologies::drift::jaro_winkler;
+ let score = jaro_winkler("Hypertension", "HyperTensionSyndrome");
+ assert!(score > 0.5); // Should be somewhat similar
+ let score = jaro_winkler("Hypertension", "Essential hypertension");
+ assert!(score > 0.4);
+}
+```
+
+**Step 2b: Run test to verify it fails**
+
+Run: `cargo test --test clinical_test -v`
+Expected: FAIL — `clinical` module doesn't exist.
+
+**Step 3: Write minimal implementation**
+
+Create `src/clinical.rs`. Key components:
+
+- `ClinicalCrosswalks` struct holding a `Vec<CrosswalkRow>` loaded from Parquet
+- `load(path)` — reads Parquet using `parquet` and `arrow` crates (already in Cargo.toml)
+- `lookup(code, system)` — filter rows by source_code + source_system, return all target mappings
+- `search_label(text)` — Jaro-Winkler fuzzy search across all labels in the Parquet
+- `validate_clinical(graph)` — SPARQL to get all class labels, match each against crosswalk labels
+- `enrich(graph, class_iri, code, system)` — insert `skos:exactMatch` triple into graph
+
+Parquet reading pattern (already used in `ingest.rs`):
+```rust
+use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
+use arrow::array::StringArray;
+```
+
+**Step 4: Run test to verify it passes**
+
+Run: `cargo test --test clinical_test -v`
+Expected: PASS (some tests soft-skip if Parquet not built yet)
+
+**Step 5: Commit**
+
+```bash
+git add src/clinical.rs src/lib.rs scripts/build_crosswalks.py tests/clinical_test.rs
+git commit -m "feat: add clinical crosswalks module with Parquet-backed term lookup"
+```
+
+---
+
+## Task 8: Wire All New Tools in server.rs
+
+**Files:**
+- Modify: `src/server.rs`
+- Test: Run all existing + new tests
+
+**Step 1: Add input structs to server.rs**
+
+Add new `#[derive(Deserialize, JsonSchema)]` structs for each new tool's input:
+
+- `OntoPlanInput { new_turtle: String }`
+- `OntoApplyInput { mode: String }` (safe/force/migrate)
+- `OntoMigrateInput {}` (no params, generates from last plan)
+- `OntoLockInput { iris: Vec<String>, reason: Option<String> }`
+- `OntoDriftInput { version_a: String, version_b: String }`
+- `OntoEnforceInput { rule_pack: String }`
+- `OntoMonitorInput { watchers: Option<String> }` (inline JSON)
+- `OntoCrosswalkInput { code: String, source_system: String, target_system: String }`
+- `OntoEnrichInput { class_iri: String, code: String, system: String }`
+- `OntoValidateClinicalInput {}` (no params, uses loaded graph)
+- `OntoLineageInput { session_id: String, format: Option<String> }`
+- `OntoMonitorStatusInput {}` (no params)
+
+**Step 2: Add fields to OpenOntologiesServer**
+
+```rust
+pub struct OpenOntologiesServer {
+ tool_router: ToolRouter<Self>,
+ db: StateDb,
+ graph: Arc<GraphStore>,
+ monitor: Monitor,
+ lineage: LineageLog,
+ session_id: String,
+}
+```
+
+Initialize `monitor`, `lineage`, and `session_id` in `new()`.
+
+**Step 3: Add tool handlers**
+
+Add `#[tool(...)]` handlers for each new tool, following the existing pattern. Each handler calls the corresponding module function and returns JSON.
+
+For mutating tools (`onto_load`, `onto_apply`, `onto_ingest`, `onto_reason`, `onto_extend`), add after the main result:
+1. `self.lineage.record(...)` — log the operation
+2. `let monitor_result = self.monitor.run_watchers()` — check health
+3. Merge monitor result into the response JSON
+
+**Step 4: Run all tests**
+
+Run: `cargo test`
+Expected: All existing 102 tests pass + all new tests pass.
+
+**Step 5: Update tool_router macro**
+
+Add all new tool names to the `#[tool_router]` impl block.
+
+**Step 6: Commit**
+
+```bash
+git add src/server.rs
+git commit -m "feat: wire 14 new MCP tools (plan, drift, enforce, monitor, clinical, lineage)"
+```
+
+---
+
+## Task 9: Integration Test — Full Terraform Loop
+
+**Files:**
+- Create: `tests/terraform_loop_test.rs`
+
+**Step 1: Write integration test**
+
+```rust
+use open_ontologies::graph::GraphStore;
+use open_ontologies::plan::Planner;
+use open_ontologies::drift::DriftDetector;
+use open_ontologies::monitor::Monitor;
+use open_ontologies::enforce::Enforcer;
+use open_ontologies::lineage::LineageLog;
+use open_ontologies::state::StateDb;
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+/// Full Terraform-style loop: plan → enforce → apply → monitor → drift
+#[test]
+fn test_full_terraform_loop() {
+ let tmp = NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ // --- Initial state ---
+ 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:Animal a owl:Class ; rdfs:label "Animal" .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal ; rdfs:label "Dog" .
+ "#;
+ graph.load_turtle(v1, None).unwrap();
+
+ // --- Lineage ---
+ let lineage = LineageLog::new(db.clone());
+ let session = lineage.new_session();
+ lineage.record(&session, "L", "load", "v1");
+
+ // --- Plan changes ---
+ 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:Animal a owl:Class ; rdfs:label "Animal" .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal ; rdfs:label "Dog" .
+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal ; rdfs:label "Cat" .
+ "#;
+
+ let planner = Planner::new(db.clone(), graph.clone());
+ let plan = planner.plan(v2).unwrap();
+ let plan_parsed: serde_json::Value = serde_json::from_str(&plan).unwrap();
+ assert_eq!(plan_parsed["risk_score"].as_str().unwrap(), "low");
+ lineage.record(&session, "P", "plan", "low_risk");
+
+ // --- Enforce ---
+ let enforcer = Enforcer::new(db.clone(), graph.clone());
+ let enforce_result = enforcer.enforce("generic").unwrap();
+ lineage.record(&session, "E", "enforce", "generic");
+
+ // --- Apply ---
+ let apply_result = planner.apply("safe").unwrap();
+ let apply_parsed: serde_json::Value = serde_json::from_str(&apply_result).unwrap();
+ assert_eq!(apply_parsed["ok"].as_bool().unwrap(), true);
+ lineage.record(&session, "A", "apply", "safe");
+
+ // --- Monitor ---
+ let monitor = Monitor::new(db.clone(), graph.clone());
+ let mon_result = monitor.run_watchers();
+ assert_eq!(mon_result.status, "ok");
+ lineage.record(&session, "M", "monitor", "ok");
+
+ // --- Drift check (v1 vs v2) ---
+ let detector = DriftDetector::new(db.clone());
+ let drift = detector.detect(v1, v2).unwrap();
+ let drift_parsed: serde_json::Value = serde_json::from_str(&drift).unwrap();
+ assert!(drift_parsed["drift_velocity"].as_f64().unwrap() < 0.5); // Low drift — just an addition
+ lineage.record(&session, "D", "drift", "low");
+
+ // --- Verify lineage ---
+ let events = lineage.get_compact(&session);
+ let lines: Vec<&str> = events.trim().lines().collect();
+ assert_eq!(lines.len(), 6); // L, P, E, A, M, D
+}
+```
+
+**Step 2: Run test**
+
+Run: `cargo test --test terraform_loop_test -v`
+Expected: PASS
+
+**Step 3: Commit**
+
+```bash
+git add tests/terraform_loop_test.rs
+git commit -m "test: add full Terraform loop integration test"
+```
+
+---
+
+## Task 10: Update README and CLAUDE.md
+
+**Files:**
+- Modify: `README.md`
+- Modify: `CLAUDE.md`
+
+**Step 1: Update README.md**
+
+Add a new section after "OWL2-DL Reasoning" covering:
+- Terraform-style lifecycle (plan/apply/migrate)
+- Drift detection with self-calibrating confidence
+- Active monitoring with watchers
+- Design pattern enforcement (generic, BORO, value partition)
+- Clinical crosswalks
+- Lightweight lineage
+- Updated tool table (existing 21 + 14 new = 35 tools)
+
+**Step 2: Update CLAUDE.md**
+
+Add new workflow section "Ontology Lifecycle" describing the plan→enforce→apply→monitor→drift cycle. Add new tools to the tool reference table.
+
+**Step 3: Commit**
+
+```bash
+git add README.md CLAUDE.md
+git commit -m "docs: add v2 features to README and CLAUDE.md"
+```
+
+---
+
+## Implementation Order Summary
+
+| Task | Module | Est. lines | Depends on |
+|------|--------|-----------|------------|
+| 1. SQLite schema | `state.rs` | ~50 | — |
+| 2. Lineage | `lineage.rs` | ~150 | Task 1 |
+| 3. Monitor | `monitor.rs` | ~350 | Task 1 |
+| 4. Plan/Apply/Migrate | `plan.rs` | ~600 | Task 1, 3 |
+| 5. Drift | `drift.rs` | ~400 | Task 1 |
+| 6. Enforce | `enforce.rs` | ~500 | Task 1 |
+| 7. Clinical | `clinical.rs` | ~300 | Task 5 (shares Jaro-Winkler) |
+| 8. Server wiring | `server.rs` | ~400 | Tasks 2-7 |
+| 9. Integration test | `terraform_loop_test.rs` | ~100 | Task 8 |
+| 10. Docs | `README.md`, `CLAUDE.md` | ~200 | Task 9 |
+
+**Total: ~3,050 lines of new Rust + tests + docs.**
+
+Tasks 2, 3, 5, 6 can be parallelized (independent modules). Task 4 depends on 3 (uses monitor). Task 7 depends on 5 (shares Jaro-Winkler). Task 8 depends on all modules. Task 9 depends on 8.
diff --git a/docs/plans/2026-03-12-onto-align-design.md b/docs/plans/2026-03-12-onto-align-design.md
new file mode 100644
index 00000000..db7fb330
--- /dev/null
+++ b/docs/plans/2026-03-12-onto-align-design.md
@@ -0,0 +1,152 @@
+# onto_align — Schema Alignment Tool
+
+**Date:** 2026-03-12
+**Status:** Approved
+**Branch:** `onto_align` (separate from main)
+
+## Purpose
+
+Detect and propose semantic alignment candidates (`owl:equivalentClass`, `skos:exactMatch`, `rdfs:subClassOf`) between two ontologies. Optionally auto-apply high-confidence matches.
+
+This is the single bottleneck that broke every previous semantic web attempt (W3C, DBpedia, Google KG). Modern advantage: AI-assisted schema discovery + Rust infra + cheap compute.
+
+## Input Model
+
+Two modes via a single MCP tool (`onto_align`):
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `source` | string | yes | Turtle string OR file path of ontology A |
+| `target` | string | no | Turtle string OR file path of ontology B. If omitted, aligns `source` against the loaded store |
+| `min_confidence` | float | no | Auto-apply threshold (default 0.85). Candidates above this get inserted as triples |
+| `dry_run` | bool | no | If true, return candidates only, never insert (default false) |
+
+## Output Model
+
+```json
+{
+ "candidates": [
+ {
+ "source_iri": "http://example.org/Dog",
+ "target_iri": "http://other.org/Canine",
+ "relation": "owl:equivalentClass",
+ "confidence": 0.92,
+ "signals": {
+ "label_similarity": 0.78,
+ "property_overlap": 0.95,
+ "parent_overlap": 0.88,
+ "instance_overlap": 0.60,
+ "restriction_similarity": 0.70,
+ "neighborhood_similarity": 0.55
+ },
+ "applied": true
+ }
+ ],
+ "applied_count": 3,
+ "total_candidates": 7,
+ "threshold": 0.85
+}
+```
+
+- `relation`: one of `owl:equivalentClass`, `skos:exactMatch`, `rdfs:subClassOf`
+- `applied: true` only when confidence >= threshold AND dry_run is false
+
+## Signals
+
+Six signals, weighted and combined via self-calibrating confidence (same pattern as drift.rs):
+
+| # | Signal | Method | Default Weight |
+|---|--------|--------|---------------|
+| 1 | Label similarity | Jaro-Winkler on rdfs:label, skos:prefLabel, skos:altLabel (reused from drift.rs) | 0.25 |
+| 2 | Property signature overlap | Jaccard similarity on domain/range property sets via SPARQL | 0.20 |
+| 3 | Parent/subclass overlap | Shared rdfs:subClassOf parents | 0.15 |
+| 4 | Instance overlap | Shared individuals typed under both candidate classes | 0.15 |
+| 5 | Restriction patterns | Compare owl:someValuesFrom / owl:allValuesFrom restrictions | 0.15 |
+| 6 | Graph neighborhood | 2-hop property graph comparison | 0.10 |
+
+### Label normalization
+
+- Lowercase, strip whitespace
+- CamelCase splitting ("DomesticCat" -> "domestic cat")
+- Compare all label variants (rdfs:label, skos:prefLabel, skos:altLabel)
+
+### Relation classification
+
+- High label + high property overlap -> `owl:equivalentClass`
+- High label + low property overlap -> `skos:exactMatch`
+- Moderate label + shared parent -> `rdfs:subClassOf`
+
+## Self-Calibrating Confidence
+
+New `align_feedback` SQLite table (same pattern as `drift_feedback`):
+
+```sql
+CREATE TABLE IF NOT EXISTS align_feedback (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ source_iri TEXT NOT NULL,
+ target_iri TEXT NOT NULL,
+ predicted_relation TEXT NOT NULL,
+ accepted BOOLEAN NOT NULL,
+ timestamp TEXT NOT NULL DEFAULT (datetime('now'))
+);
+```
+
+Feedback tool: `onto_align_feedback` — accepts candidate source_iri, target_iri, and accepted (bool).
+
+When enough feedback accumulates, `get_learned_weights()` adjusts signal weights based on which signals predicted correctly for accepted vs rejected candidates.
+
+## Architecture
+
+```
+src/align.rs -- AlignmentEngine struct, signal computation, candidate ranking
+src/server.rs -- onto_align + onto_align_feedback tool registration
+src/state.rs -- align_feedback table added to SCHEMA
+src/drift.rs -- jaro_winkler() stays here, imported by align.rs
+tests/cli_test.rs -- test_cli_align, test_cli_align_feedback
+```
+
+New file: `src/align.rs` only. Everything else is edits to existing files.
+
+### Data flow
+
+1. Parse source (and target if provided) into temporary Oxigraph graphs
+2. Extract class IRIs + labels + property signatures via SPARQL
+3. Cartesian product of source x target classes, compute 6 signals per pair
+4. Score and rank candidates
+5. Classify relation type based on signal pattern
+6. Filter by min_confidence for auto-apply
+7. Insert triples into main store (if not dry_run)
+8. Record lineage event
+9. Return JSON
+
+## CLI
+
+```bash
+# Align two files
+open-ontologies align source.ttl target.ttl --min-confidence 0.85
+
+# Align file against loaded store
+open-ontologies align source.ttl --min-confidence 0.9 --dry-run
+
+# Accept/reject a candidate
+open-ontologies align-feedback --source <iri> --target <iri> --accept
+open-ontologies align-feedback --source <iri> --target <iri> --reject
+```
+
+## MCP Tools
+
+### onto_align
+
+```
+#[tool(name = "onto_align", description = "Detect alignment candidates between ontologies")]
+```
+
+Parameters: source, target (optional), min_confidence (optional, default 0.85), dry_run (optional, default false)
+
+### onto_align_feedback
+
+```
+#[tool(name = "onto_align_feedback", description = "Accept or reject an alignment candidate to improve future confidence")]
+```
+
+Parameters: source_iri, target_iri, accepted (bool)
diff --git a/docs/plans/2026-03-12-onto-align-plan.md b/docs/plans/2026-03-12-onto-align-plan.md
new file mode 100644
index 00000000..9e9483c7
--- /dev/null
+++ b/docs/plans/2026-03-12-onto-align-plan.md
@@ -0,0 +1,1194 @@
+# onto_align Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Add `onto_align` and `onto_align_feedback` tools that detect owl:equivalentClass / skos:exactMatch / rdfs:subClassOf candidates between two ontologies using 6 weighted signals with self-calibrating confidence.
+
+**Architecture:** New `src/align.rs` module containing `AlignmentEngine` struct. Reuses `jaro_winkler()` from `drift.rs`. Computes 6 signals per class pair, ranks candidates, optionally auto-applies above threshold. Feedback stored in `align_feedback` SQLite table for weight calibration.
+
+**Tech Stack:** Rust, Oxigraph (SPARQL), rusqlite (SQLite), rmcp (MCP tools), schemars (JSON Schema)
+
+---
+
+### Task 1: Create branch and add align_feedback table to SQLite schema
+
+**Files:**
+- Modify: `src/state.rs:6-74` (SCHEMA const)
+
+**Step 1: Create the onto_align branch**
+
+Run: `cd /Users/fabio/projects/open-ontologies && git checkout -b onto_align`
+Expected: Switched to a new branch 'onto_align'
+
+**Step 2: Add align_feedback table to SCHEMA const**
+
+In `src/state.rs`, append before the closing `";` of the SCHEMA const:
+
+```rust
+CREATE TABLE IF NOT EXISTS align_feedback (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ source_iri TEXT NOT NULL,
+ target_iri TEXT NOT NULL,
+ predicted_relation TEXT NOT NULL,
+ accepted INTEGER NOT NULL,
+ timestamp TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX IF NOT EXISTS idx_align_feedback_iris ON align_feedback(source_iri, target_iri);
+```
+
+**Step 3: Verify it compiles**
+
+Run: `cargo check`
+Expected: Compiles with no errors
+
+**Step 4: Commit**
+
+```bash
+git add src/state.rs
+git commit -m "feat: add align_feedback table to SQLite schema"
+```
+
+---
+
+### Task 2: Create src/align.rs with AlignmentEngine struct and label similarity signal
+
+**Files:**
+- Create: `src/align.rs`
+- Modify: `src/lib.rs` (add `pub mod align;`)
+
+**Step 1: Write the failing test**
+
+Create `src/align.rs` with imports, struct, and a test at the bottom:
+
+```rust
+use std::sync::Arc;
+use crate::drift::jaro_winkler;
+use crate::graph::GraphStore;
+use crate::state::StateDb;
+
+/// Schema alignment engine — detects equivalentClass/exactMatch/subClassOf
+/// candidates between two ontologies using weighted signals.
+pub struct AlignmentEngine {
+ db: StateDb,
+ graph: Arc<GraphStore>,
+}
+
+impl AlignmentEngine {
+ pub fn new(db: StateDb, graph: Arc<GraphStore>) -> Self {
+ Self { db, graph }
+ }
+
+ /// Extract class IRIs and their labels from a temporary graph via SPARQL.
+ fn extract_classes(store: &GraphStore) -> Vec<ClassInfo> {
+ let query = r#"
+ SELECT ?class ?label ?altLabel WHERE {
+ ?class a <http://www.w3.org/2002/07/owl#Class> .
+ OPTIONAL { ?class <http://www.w3.org/2000/01/rdf-schema#label> ?label }
+ OPTIONAL { ?class <http://www.w3.org/2004/02/skos/core#prefLabel> ?label }
+ OPTIONAL { ?class <http://www.w3.org/2004/02/skos/core#altLabel> ?altLabel }
+ }
+ "#;
+
+ let result = match store.sparql_select(query) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+
+ let parsed: serde_json::Value = match serde_json::from_str(&result) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+
+ let mut class_map: std::collections::HashMap<String, ClassInfo> =
+ std::collections::HashMap::new();
+
+ if let Some(rows) = parsed["results"].as_array() {
+ for row in rows {
+ let iri = match row["class"].as_str() {
+ Some(s) => s.trim_matches(|c| c == '<' || c == '>').to_string(),
+ None => continue,
+ };
+
+ let entry = class_map.entry(iri.clone()).or_insert_with(|| ClassInfo {
+ iri: iri.clone(),
+ labels: Vec::new(),
+ });
+
+ if let Some(label) = row["label"].as_str() {
+ let l = label.trim_matches('"').to_string();
+ if !entry.labels.contains(&l) {
+ entry.labels.push(l);
+ }
+ }
+ if let Some(alt) = row["altLabel"].as_str() {
+ let a = alt.trim_matches('"').to_string();
+ if !entry.labels.contains(&a) {
+ entry.labels.push(a);
+ }
+ }
+ }
+ }
+
+ // If no label found, use IRI local name
+ for info in class_map.values_mut() {
+ if info.labels.is_empty() {
+ info.labels.push(local_name(&info.iri));
+ }
+ }
+
+ class_map.into_values().collect()
+ }
+
+ /// Compute label similarity between two classes (best match across all label variants).
+ fn label_similarity(a: &ClassInfo, b: &ClassInfo) -> f64 {
+ let mut best = 0.0f64;
+ for la in &a.labels {
+ for lb in &b.labels {
+ let sim = jaro_winkler(
+ &normalize_label(la),
+ &normalize_label(lb),
+ );
+ best = best.max(sim);
+ }
+ }
+ best
+ }
+}
+
+/// Metadata about a class extracted from an ontology.
+#[derive(Debug, Clone)]
+pub struct ClassInfo {
+ pub iri: String,
+ pub labels: Vec<String>,
+}
+
+/// Extract local name from an IRI (after last # or /).
+fn local_name(iri: &str) -> String {
+ iri.rsplit_once('#')
+ .or_else(|| iri.rsplit_once('/'))
+ .map(|(_, name)| name.to_string())
+ .unwrap_or_else(|| iri.to_string())
+}
+
+/// Normalize a label for comparison: lowercase, split camelCase, trim.
+fn normalize_label(label: &str) -> String {
+ // Insert space before uppercase letters (camelCase splitting)
+ let mut result = String::with_capacity(label.len() + 8);
+ for (i, ch) in label.chars().enumerate() {
+ if i > 0 && ch.is_uppercase() {
+ result.push(' ');
+ }
+ result.push(ch);
+ }
+ result.to_lowercase().trim().to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_normalize_label() {
+ assert_eq!(normalize_label("DomesticCat"), "domestic cat");
+ assert_eq!(normalize_label("dog"), "dog");
+ assert_eq!(normalize_label("MyFavoritePizza"), "my favorite pizza");
+ }
+
+ #[test]
+ fn test_local_name() {
+ assert_eq!(local_name("http://example.org/Dog"), "Dog");
+ assert_eq!(local_name("http://example.org#Cat"), "Cat");
+ }
+
+ #[test]
+ fn test_label_similarity() {
+ let a = ClassInfo {
+ iri: "http://ex.org/Dog".into(),
+ labels: vec!["Dog".into()],
+ };
+ let b = ClassInfo {
+ iri: "http://other.org/Canine".into(),
+ labels: vec!["Dog".into(), "Canine".into()],
+ };
+ // Exact label match should give 1.0
+ let sim = AlignmentEngine::label_similarity(&a, &b);
+ assert!((sim - 1.0).abs() < 0.001);
+ }
+
+ #[test]
+ fn test_label_similarity_camelcase() {
+ let a = ClassInfo {
+ iri: "http://ex.org/DomesticCat".into(),
+ labels: vec!["DomesticCat".into()],
+ };
+ let b = ClassInfo {
+ iri: "http://other.org/HouseCat".into(),
+ labels: vec!["Domestic Cat".into()],
+ };
+ let sim = AlignmentEngine::label_similarity(&a, &b);
+ assert!(sim > 0.95, "CamelCase split should match: {}", sim);
+ }
+}
+```
+
+**Step 2: Add module declaration**
+
+In `src/lib.rs`, add `pub mod align;` after the existing module declarations.
+
+**Step 3: Run tests to verify they pass**
+
+Run: `cargo test --lib align`
+Expected: 4 tests pass
+
+**Step 4: Commit**
+
+```bash
+git add src/align.rs src/lib.rs
+git commit -m "feat: add AlignmentEngine with label similarity signal"
+```
+
+---
+
+### Task 3: Add SPARQL-based structural signals (property overlap, parent overlap)
+
+**Files:**
+- Modify: `src/align.rs`
+
+**Step 1: Write failing tests**
+
+Add to the test module in `src/align.rs`:
+
+```rust
+#[test]
+fn test_property_overlap_identical() {
+ let a = vec!["http://ex.org/hasName".into(), "http://ex.org/hasAge".into()];
+ let b = vec!["http://ex.org/hasName".into(), "http://ex.org/hasAge".into()];
+ let sim = jaccard_similarity(&a, &b);
+ assert!((sim - 1.0).abs() < 0.001);
+}
+
+#[test]
+fn test_property_overlap_partial() {
+ let a = vec!["http://ex.org/hasName".into(), "http://ex.org/hasAge".into()];
+ let b = vec!["http://ex.org/hasName".into(), "http://ex.org/hasColor".into()];
+ let sim = jaccard_similarity(&a, &b);
+ assert!((sim - 1.0 / 3.0).abs() < 0.001); // intersection=1, union=3
+}
+
+#[test]
+fn test_property_overlap_empty() {
+ let a: Vec<String> = vec![];
+ let b: Vec<String> = vec![];
+ let sim = jaccard_similarity(&a, &b);
+ assert!((sim - 0.0).abs() < 0.001);
+}
+```
+
+**Step 2: Run tests to verify they fail**
+
+Run: `cargo test --lib align`
+Expected: FAIL — `jaccard_similarity` not found
+
+**Step 3: Implement structural signals**
+
+Add to `src/align.rs` (before the tests module):
+
+```rust
+/// Jaccard similarity between two sets of strings.
+fn jaccard_similarity(a: &[String], b: &[String]) -> f64 {
+ if a.is_empty() && b.is_empty() {
+ return 0.0;
+ }
+ let set_a: std::collections::HashSet<&str> = a.iter().map(|s| s.as_str()).collect();
+ let set_b: std::collections::HashSet<&str> = b.iter().map(|s| s.as_str()).collect();
+ let intersection = set_a.intersection(&set_b).count() as f64;
+ let union = set_a.union(&set_b).count() as f64;
+ if union == 0.0 { 0.0 } else { intersection / union }
+}
+```
+
+Add methods to `AlignmentEngine`:
+
+```rust
+/// Extract property IRIs whose domain is the given class.
+fn extract_properties(store: &GraphStore, class_iri: &str) -> Vec<String> {
+ let query = format!(
+ r#"SELECT DISTINCT ?prop WHERE {{
+ ?prop <http://www.w3.org/2000/01/rdf-schema#domain> <{class_iri}> .
+ }}"#
+ );
+ Self::extract_iris(store, &query, "prop")
+}
+
+/// Extract rdfs:subClassOf parents for a class.
+fn extract_parents(store: &GraphStore, class_iri: &str) -> Vec<String> {
+ let query = format!(
+ r#"SELECT DISTINCT ?parent WHERE {{
+ <{class_iri}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?parent .
+ FILTER(isIRI(?parent))
+ }}"#
+ );
+ Self::extract_iris(store, &query, "parent")
+}
+
+/// Extract property ranges for a class's properties.
+fn extract_ranges(store: &GraphStore, class_iri: &str) -> Vec<String> {
+ let query = format!(
+ r#"SELECT DISTINCT ?range WHERE {{
+ ?prop <http://www.w3.org/2000/01/rdf-schema#domain> <{class_iri}> .
+ ?prop <http://www.w3.org/2000/01/rdf-schema#range> ?range .
+ }}"#
+ );
+ Self::extract_iris(store, &query, "range")
+}
+
+/// Helper: run a SPARQL SELECT and extract a single variable's values.
+fn extract_iris(store: &GraphStore, query: &str, var: &str) -> Vec<String> {
+ let result = match store.sparql_select(query) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+ let parsed: serde_json::Value = match serde_json::from_str(&result) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ parsed["results"]
+ .as_array()
+ .unwrap_or(&Vec::new())
+ .iter()
+ .filter_map(|row| {
+ row[var]
+ .as_str()
+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())
+ })
+ .collect()
+}
+
+/// Compute property signature overlap (Jaccard on domain properties + ranges).
+fn property_overlap(store_a: &GraphStore, class_a: &str, store_b: &GraphStore, class_b: &str) -> f64 {
+ let props_a = Self::extract_properties(store_a, class_a);
+ let props_b = Self::extract_properties(store_b, class_b);
+ let ranges_a = Self::extract_ranges(store_a, class_a);
+ let ranges_b = Self::extract_ranges(store_b, class_b);
+
+ // Combine property local names + range local names for comparison
+ let sig_a: Vec<String> = props_a.iter().chain(ranges_a.iter()).map(|s| local_name(s)).collect();
+ let sig_b: Vec<String> = props_b.iter().chain(ranges_b.iter()).map(|s| local_name(s)).collect();
+
+ jaccard_similarity(&sig_a, &sig_b)
+}
+
+/// Compute parent overlap (Jaccard on rdfs:subClassOf parents by local name).
+fn parent_overlap(store_a: &GraphStore, class_a: &str, store_b: &GraphStore, class_b: &str) -> f64 {
+ let parents_a: Vec<String> = Self::extract_parents(store_a, class_a)
+ .iter().map(|s| local_name(s)).collect();
+ let parents_b: Vec<String> = Self::extract_parents(store_b, class_b)
+ .iter().map(|s| local_name(s)).collect();
+ jaccard_similarity(&parents_a, &parents_b)
+}
+```
+
+**Step 4: Run tests to verify they pass**
+
+Run: `cargo test --lib align`
+Expected: 7 tests pass
+
+**Step 5: Commit**
+
+```bash
+git add src/align.rs
+git commit -m "feat: add property overlap and parent overlap signals"
+```
+
+---
+
+### Task 4: Add deep structural signals (instance overlap, restrictions, neighborhood)
+
+**Files:**
+- Modify: `src/align.rs`
+
+**Step 1: Implement instance overlap, restriction similarity, and neighborhood signals**
+
+Add methods to `AlignmentEngine`:
+
+```rust
+/// Compute instance overlap — shared individuals typed under both classes (by local name).
+fn instance_overlap(store_a: &GraphStore, class_a: &str, store_b: &GraphStore, class_b: &str) -> f64 {
+ let query_a = format!(
+ r#"SELECT DISTINCT ?ind WHERE {{ ?ind a <{class_a}> . FILTER(isIRI(?ind)) }}"#
+ );
+ let query_b = format!(
+ r#"SELECT DISTINCT ?ind WHERE {{ ?ind a <{class_b}> . FILTER(isIRI(?ind)) }}"#
+ );
+ let inds_a: Vec<String> = Self::extract_iris(store_a, &query_a, "ind")
+ .iter().map(|s| local_name(s)).collect();
+ let inds_b: Vec<String> = Self::extract_iris(store_b, &query_b, "ind")
+ .iter().map(|s| local_name(s)).collect();
+ jaccard_similarity(&inds_a, &inds_b)
+}
+
+/// Compute restriction similarity — compare owl:someValuesFrom / owl:allValuesFrom restrictions.
+fn restriction_similarity(store_a: &GraphStore, class_a: &str, store_b: &GraphStore, class_b: &str) -> f64 {
+ let restriction_query = |class: &str| format!(
+ r#"SELECT DISTINCT ?prop ?filler WHERE {{
+ <{class}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?r .
+ ?r a <http://www.w3.org/2002/07/owl#Restriction> .
+ ?r <http://www.w3.org/2002/07/owl#onProperty> ?prop .
+ {{
+ ?r <http://www.w3.org/2002/07/owl#someValuesFrom> ?filler .
+ }} UNION {{
+ ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?filler .
+ }}
+ }}"#
+ );
+
+ let extract_restriction_sigs = |store: &GraphStore, class: &str| -> Vec<String> {
+ let query = restriction_query(class);
+ let result = match store.sparql_select(&query) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+ let parsed: serde_json::Value = match serde_json::from_str(&result) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ parsed["results"]
+ .as_array()
+ .unwrap_or(&Vec::new())
+ .iter()
+ .filter_map(|row| {
+ let prop = row["prop"].as_str()?;
+ let filler = row["filler"].as_str()?;
+ Some(format!("{}→{}", local_name(prop), local_name(filler)))
+ })
+ .collect()
+ };
+
+ let sigs_a = extract_restriction_sigs(store_a, class_a);
+ let sigs_b = extract_restriction_sigs(store_b, class_b);
+ jaccard_similarity(&sigs_a, &sigs_b)
+}
+
+/// Compute graph neighborhood similarity — 2-hop property comparison.
+/// Compares the set of property local names reachable within 2 hops from each class.
+fn neighborhood_similarity(store_a: &GraphStore, class_a: &str, store_b: &GraphStore, class_b: &str) -> f64 {
+ let neighborhood_query = |class: &str| format!(
+ r#"SELECT DISTINCT ?prop WHERE {{
+ {{
+ ?prop <http://www.w3.org/2000/01/rdf-schema#domain> <{class}> .
+ }} UNION {{
+ <{class}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?parent .
+ ?prop <http://www.w3.org/2000/01/rdf-schema#domain> ?parent .
+ }} UNION {{
+ ?prop <http://www.w3.org/2000/01/rdf-schema#range> <{class}> .
+ }}
+ }}"#
+ );
+
+ let neigh_a: Vec<String> = Self::extract_iris(store_a, &neighborhood_query(class_a), "prop")
+ .iter().map(|s| local_name(s)).collect();
+ let neigh_b: Vec<String> = Self::extract_iris(store_b, &neighborhood_query(class_b), "prop")
+ .iter().map(|s| local_name(s)).collect();
+ jaccard_similarity(&neigh_a, &neigh_b)
+}
+```
+
+**Step 2: Run tests to verify compilation**
+
+Run: `cargo test --lib align`
+Expected: All existing tests still pass
+
+**Step 3: Commit**
+
+```bash
+git add src/align.rs
+git commit -m "feat: add instance overlap, restriction, and neighborhood signals"
+```
+
+---
+
+### Task 5: Implement the main align() method with candidate scoring and relation classification
+
+**Files:**
+- Modify: `src/align.rs`
+
+**Step 1: Write the failing integration test**
+
+Add to the test module:
+
+```rust
+#[test]
+fn test_align_identical_classes() {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ let source = 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:Dog a owl:Class ; rdfs:label "Dog" .
+ ex:Cat a owl:Class ; rdfs:label "Cat" .
+ "#;
+
+ let target = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix other: <http://other.org/> .
+ other:Dog a owl:Class ; rdfs:label "Dog" .
+ other:Feline a owl:Class ; rdfs:label "Cat" .
+ "#;
+
+ let engine = AlignmentEngine::new(db, graph);
+ let result = engine.align(source, Some(target), 0.5, false).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ let candidates = parsed["candidates"].as_array().unwrap();
+ assert!(candidates.len() >= 2, "Should find at least 2 candidates: {:?}", candidates);
+
+ // Dog<->Dog should have very high confidence
+ let dog_match = candidates.iter().find(|c| {
+ c["source_iri"].as_str().unwrap().contains("Dog")
+ && c["target_iri"].as_str().unwrap().contains("Dog")
+ });
+ assert!(dog_match.is_some(), "Should match Dog<->Dog");
+ assert!(dog_match.unwrap()["confidence"].as_f64().unwrap() > 0.8);
+}
+
+#[test]
+fn test_align_auto_apply() {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ let source = 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:Dog a owl:Class ; rdfs:label "Dog" .
+ "#;
+
+ let target = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix other: <http://other.org/> .
+ other:Dog a owl:Class ; rdfs:label "Dog" .
+ "#;
+
+ let engine = AlignmentEngine::new(db, graph.clone());
+ let result = engine.align(source, Some(target), 0.5, false).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert!(parsed["applied_count"].as_u64().unwrap() > 0);
+
+ // Verify triples were inserted into the main graph
+ let count = graph.triple_count();
+ assert!(count > 0, "Auto-apply should insert triples into main graph");
+}
+
+#[test]
+fn test_align_dry_run() {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ let source = 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:Dog a owl:Class ; rdfs:label "Dog" .
+ "#;
+
+ let target = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix other: <http://other.org/> .
+ other:Dog a owl:Class ; rdfs:label "Dog" .
+ "#;
+
+ let engine = AlignmentEngine::new(db, graph.clone());
+ let result = engine.align(source, Some(target), 0.5, true).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert_eq!(parsed["applied_count"].as_u64().unwrap(), 0);
+ assert_eq!(graph.triple_count(), 0, "Dry run should not insert triples");
+}
+```
+
+**Step 2: Run tests to verify they fail**
+
+Run: `cargo test --lib align`
+Expected: FAIL — `align` method not found
+
+**Step 3: Implement the align() method**
+
+Add to `AlignmentEngine` impl block:
+
+```rust
+/// Default signal weights: label, property, parent, instance, restriction, neighborhood.
+const DEFAULT_WEIGHTS: [f64; 6] = [0.25, 0.20, 0.15, 0.15, 0.15, 0.10];
+
+/// Run alignment between source and target ontologies.
+/// If `target` is None, aligns source against the loaded store (`self.graph`).
+/// If `dry_run` is true, returns candidates without inserting triples.
+pub fn align(
+ &self,
+ source: &str,
+ target: Option<&str>,
+ min_confidence: f64,
+ dry_run: bool,
+) -> anyhow::Result<String> {
+ // Load source into a temporary graph
+ let source_store = GraphStore::new();
+ source_store.load_turtle(source, None)?;
+ let source_classes = Self::extract_classes(&source_store);
+
+ // Load target into a temporary graph (or use the main store)
+ let (target_store_owned, target_ref);
+ if let Some(target_ttl) = target {
+ target_store_owned = Some(GraphStore::new());
+ target_store_owned.as_ref().unwrap().load_turtle(target_ttl, None)?;
+ target_ref = target_store_owned.as_ref().unwrap();
+ } else {
+ target_store_owned = None;
+ target_ref = &*self.graph;
+ }
+ let target_classes = Self::extract_classes(target_ref);
+
+ // Get learned weights (or defaults)
+ let weights = self.get_learned_weights();
+
+ // Compute candidates: cartesian product of source × target classes
+ let mut candidates: Vec<serde_json::Value> = Vec::new();
+
+ for sc in &source_classes {
+ for tc in &target_classes {
+ // Skip self-matches (same IRI)
+ if sc.iri == tc.iri {
+ continue;
+ }
+
+ let label_sim = Self::label_similarity(sc, tc);
+ let prop_overlap = Self::property_overlap(&source_store, &sc.iri, target_ref, &tc.iri);
+ let parent_ovlp = Self::parent_overlap(&source_store, &sc.iri, target_ref, &tc.iri);
+ let inst_overlap = Self::instance_overlap(&source_store, &sc.iri, target_ref, &tc.iri);
+ let restr_sim = Self::restriction_similarity(&source_store, &sc.iri, target_ref, &tc.iri);
+ let neigh_sim = Self::neighborhood_similarity(&source_store, &sc.iri, target_ref, &tc.iri);
+
+ let signals = [label_sim, prop_overlap, parent_ovlp, inst_overlap, restr_sim, neigh_sim];
+ let confidence: f64 = signals.iter().zip(weights.iter()).map(|(s, w)| s * w).sum();
+
+ // Skip low-confidence pairs (below half of threshold to reduce noise)
+ if confidence < min_confidence * 0.5 {
+ continue;
+ }
+
+ let relation = Self::classify_relation(label_sim, prop_overlap, parent_ovlp);
+
+ candidates.push(serde_json::json!({
+ "source_iri": sc.iri,
+ "target_iri": tc.iri,
+ "relation": relation,
+ "confidence": (confidence * 1000.0).round() / 1000.0,
+ "signals": {
+ "label_similarity": (label_sim * 1000.0).round() / 1000.0,
+ "property_overlap": (prop_overlap * 1000.0).round() / 1000.0,
+ "parent_overlap": (parent_ovlp * 1000.0).round() / 1000.0,
+ "instance_overlap": (inst_overlap * 1000.0).round() / 1000.0,
+ "restriction_similarity": (restr_sim * 1000.0).round() / 1000.0,
+ "neighborhood_similarity": (neigh_sim * 1000.0).round() / 1000.0,
+ },
+ "applied": false,
+ }));
+ }
+ }
+
+ // Sort by confidence descending
+ candidates.sort_by(|a, b| {
+ b["confidence"].as_f64().unwrap_or(0.0)
+ .partial_cmp(&a["confidence"].as_f64().unwrap_or(0.0))
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+
+ // Auto-apply above threshold
+ let mut applied_count = 0;
+ if !dry_run {
+ for candidate in &mut candidates {
+ let conf = candidate["confidence"].as_f64().unwrap_or(0.0);
+ if conf >= min_confidence {
+ let source_iri = candidate["source_iri"].as_str().unwrap();
+ let target_iri = candidate["target_iri"].as_str().unwrap();
+ let relation = candidate["relation"].as_str().unwrap();
+
+ let triple = Self::relation_to_triple(source_iri, target_iri, relation);
+ if self.graph.load_turtle(&triple, None).is_ok() {
+ candidate["applied"] = serde_json::Value::Bool(true);
+ applied_count += 1;
+ }
+ }
+ }
+ }
+
+ let total = candidates.len();
+
+ Ok(serde_json::json!({
+ "candidates": candidates,
+ "applied_count": applied_count,
+ "total_candidates": total,
+ "threshold": min_confidence,
+ }).to_string())
+}
+
+/// Classify the relation type based on signal strengths.
+fn classify_relation(label_sim: f64, prop_overlap: f64, parent_overlap: f64) -> &'static str {
+ if label_sim > 0.8 && prop_overlap > 0.5 {
+ "owl:equivalentClass"
+ } else if label_sim > 0.8 {
+ "skos:exactMatch"
+ } else if parent_overlap > 0.5 {
+ "rdfs:subClassOf"
+ } else if label_sim > 0.6 {
+ "skos:exactMatch"
+ } else {
+ "skos:closeMatch"
+ }
+}
+
+/// Generate a Turtle triple for the given relation.
+fn relation_to_triple(source: &str, target: &str, relation: &str) -> String {
+ let predicate = match relation {
+ "owl:equivalentClass" => "http://www.w3.org/2002/07/owl#equivalentClass",
+ "skos:exactMatch" => "http://www.w3.org/2004/02/skos/core#exactMatch",
+ "skos:closeMatch" => "http://www.w3.org/2004/02/skos/core#closeMatch",
+ "rdfs:subClassOf" => "http://www.w3.org/2000/01/rdf-schema#subClassOf",
+ _ => "http://www.w3.org/2004/02/skos/core#relatedMatch",
+ };
+ format!("<{}> <{}> <{}> .\n", source, predicate, target)
+}
+
+/// Get learned weights from align_feedback, or defaults if not enough data.
+fn get_learned_weights(&self) -> Vec<f64> {
+ let conn = self.db.conn();
+ let count: i64 = conn
+ .query_row("SELECT COUNT(*) FROM align_feedback", [], |r| r.get(0))
+ .unwrap_or(0);
+
+ if count < 10 {
+ return Self::DEFAULT_WEIGHTS.to_vec();
+ }
+
+ // For now, return defaults. Full learning requires storing per-signal values
+ // in align_feedback, which we add in the feedback task.
+ Self::DEFAULT_WEIGHTS.to_vec()
+}
+```
+
+**Step 4: Run tests to verify they pass**
+
+Run: `cargo test --lib align`
+Expected: All 10 tests pass
+
+**Step 5: Commit**
+
+```bash
+git add src/align.rs
+git commit -m "feat: implement align() with candidate scoring and relation classification"
+```
+
+---
+
+### Task 6: Add align_feedback method for self-calibrating confidence
+
+**Files:**
+- Modify: `src/align.rs`
+
+**Step 1: Write the failing test**
+
+Add to tests:
+
+```rust
+#[test]
+fn test_align_feedback() {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ let engine = AlignmentEngine::new(db.clone(), graph);
+ let result = engine.record_feedback(
+ "http://ex.org/Dog",
+ "http://other.org/Canine",
+ "owl:equivalentClass",
+ true,
+ ).unwrap();
+
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+ assert_eq!(parsed["ok"].as_bool().unwrap(), true);
+
+ // Verify it was stored
+ let conn = db.conn();
+ let count: i64 = conn
+ .query_row("SELECT COUNT(*) FROM align_feedback", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(count, 1);
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+Run: `cargo test --lib align::tests::test_align_feedback`
+Expected: FAIL — `record_feedback` not found
+
+**Step 3: Implement record_feedback**
+
+Add to `AlignmentEngine`:
+
+```rust
+/// Record user feedback on an alignment candidate.
+pub fn record_feedback(
+ &self,
+ source_iri: &str,
+ target_iri: &str,
+ predicted_relation: &str,
+ accepted: bool,
+) -> anyhow::Result<String> {
+ let conn = self.db.conn();
+ conn.execute(
+ "INSERT INTO align_feedback (source_iri, target_iri, predicted_relation, accepted)
+ VALUES (?1, ?2, ?3, ?4)",
+ rusqlite::params![source_iri, target_iri, predicted_relation, accepted as i32],
+ )?;
+
+ Ok(serde_json::json!({
+ "ok": true,
+ "source_iri": source_iri,
+ "target_iri": target_iri,
+ "predicted_relation": predicted_relation,
+ "accepted": accepted,
+ }).to_string())
+}
+```
+
+**Step 4: Run tests to verify they pass**
+
+Run: `cargo test --lib align`
+Expected: All 11 tests pass
+
+**Step 5: Commit**
+
+```bash
+git add src/align.rs
+git commit -m "feat: add alignment feedback for self-calibrating confidence"
+```
+
+---
+
+### Task 7: Register onto_align and onto_align_feedback as MCP tools
+
+**Files:**
+- Modify: `src/server.rs` (input structs + tool methods)
+
+**Step 1: Add input structs to server.rs**
+
+Add after the existing input structs (around line 250):
+
+```rust
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoAlignInput {
+ /// Source ontology: inline Turtle content or file path
+ pub source: String,
+ /// Target ontology: inline Turtle content or file path. If omitted, aligns against loaded store
+ pub target: Option<String>,
+ /// Minimum confidence threshold for auto-apply (default 0.85)
+ pub min_confidence: Option<f64>,
+ /// If true, return candidates only without inserting triples (default false)
+ pub dry_run: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoAlignFeedbackInput {
+ /// Source class IRI from the alignment candidate
+ pub source_iri: String,
+ /// Target class IRI from the alignment candidate
+ pub target_iri: String,
+ /// Whether the alignment candidate was correct
+ pub accepted: bool,
+}
+```
+
+**Step 2: Add tool methods to the tool_router impl**
+
+Add inside the `#[tool_router] impl OpenOntologiesServer` block:
+
+```rust
+#[tool(name = "onto_align", description = "Detect alignment candidates (owl:equivalentClass, skos:exactMatch, rdfs:subClassOf) between two ontologies using label similarity, property overlap, parent overlap, instance overlap, restriction patterns, and graph neighborhood. Auto-applies high-confidence matches above threshold.")]
+async fn onto_align(&self, Parameters(input): Parameters<OntoAlignInput>) -> String {
+ let engine = crate::align::AlignmentEngine::new(self.db.clone(), self.graph.clone());
+
+ // Read source (file path or inline)
+ let source = if std::path::Path::new(&input.source).exists() {
+ match std::fs::read_to_string(&input.source) {
+ Ok(s) => s,
+ Err(e) => return format!(r#"{{"error":"Failed to read source: {}"}}"#, e),
+ }
+ } else {
+ input.source
+ };
+
+ // Read target (file path, inline, or None)
+ let target = match input.target {
+ Some(t) => {
+ if std::path::Path::new(&t).exists() {
+ match std::fs::read_to_string(&t) {
+ Ok(s) => Some(s),
+ Err(e) => return format!(r#"{{"error":"Failed to read target: {}"}}"#, e),
+ }
+ } else {
+ Some(t)
+ }
+ }
+ None => None,
+ };
+
+ let min_conf = input.min_confidence.unwrap_or(0.85);
+ let dry_run = input.dry_run.unwrap_or(false);
+
+ match engine.align(&source, target.as_deref(), min_conf, dry_run) {
+ Ok(result) => {
+ self.lineage().record(&self.session_id, "AL", "align", &format!("threshold={}", min_conf));
+ result
+ }
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+}
+
+#[tool(name = "onto_align_feedback", description = "Accept or reject an alignment candidate to improve future confidence scoring. Stores feedback in align_feedback table for self-calibrating weights.")]
+async fn onto_align_feedback(&self, Parameters(input): Parameters<OntoAlignFeedbackInput>) -> String {
+ let engine = crate::align::AlignmentEngine::new(self.db.clone(), self.graph.clone());
+ match engine.record_feedback(&input.source_iri, &input.target_iri, "user_feedback", input.accepted) {
+ Ok(result) => {
+ self.lineage().record(&self.session_id, "AF", "align_feedback", if input.accepted { "accepted" } else { "rejected" });
+ result
+ }
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+}
+```
+
+**Step 3: Verify compilation**
+
+Run: `cargo check`
+Expected: Compiles with no errors
+
+**Step 4: Commit**
+
+```bash
+git add src/server.rs
+git commit -m "feat: register onto_align and onto_align_feedback MCP tools"
+```
+
+---
+
+### Task 8: Add CLI subcommands for align and align-feedback
+
+**Files:**
+- Modify: `src/main.rs`
+
+**Step 1: Add CLI subcommands to the Commands enum**
+
+Add in the `// ─── Lifecycle` section of the Commands enum:
+
+```rust
+/// Detect alignment candidates between two ontologies
+Align {
+ /// Source ontology file
+ source: String,
+ /// Target ontology file (if omitted, aligns against loaded store)
+ target: Option<String>,
+ /// Minimum confidence threshold (default 0.85)
+ #[arg(long, default_value = "0.85")]
+ min_confidence: f64,
+ /// Dry run — show candidates without inserting triples
+ #[arg(long)]
+ dry_run: bool,
+},
+/// Accept or reject an alignment candidate
+AlignFeedback {
+ /// Source class IRI
+ #[arg(long)]
+ source: String,
+ /// Target class IRI
+ #[arg(long)]
+ target: String,
+ /// Accept the candidate
+ #[arg(long, conflicts_with = "reject")]
+ accept: bool,
+ /// Reject the candidate
+ #[arg(long, conflicts_with = "accept")]
+ reject: bool,
+},
+```
+
+**Step 2: Add match arms in main()**
+
+Add in the match block:
+
+```rust
+Commands::Align { source, target, min_confidence, dry_run } => {
+ let (db, graph) = setup(&cli.data_dir)?;
+ let source_ttl = std::fs::read_to_string(&source)?;
+ let target_ttl = match target {
+ Some(ref t) => Some(std::fs::read_to_string(t)?),
+ None => None,
+ };
+ let engine = open_ontologies::align::AlignmentEngine::new(db, graph);
+ let result = engine.align(&source_ttl, target_ttl.as_deref(), min_confidence, dry_run)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ if cli.pretty {
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&result) {
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ } else {
+ println!("{}", result);
+ }
+ } else {
+ println!("{}", result);
+ }
+}
+Commands::AlignFeedback { source, target, accept, reject } => {
+ let (db, graph) = setup(&cli.data_dir)?;
+ let engine = open_ontologies::align::AlignmentEngine::new(db, graph);
+ let accepted = accept || !reject;
+ let result = engine.record_feedback(&source, &target, "user_feedback", accepted)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ if cli.pretty {
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&result) {
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ } else {
+ println!("{}", result);
+ }
+ } else {
+ println!("{}", result);
+ }
+}
+```
+
+**Step 3: Verify compilation**
+
+Run: `cargo check`
+Expected: Compiles with no errors
+
+**Step 4: Commit**
+
+```bash
+git add src/main.rs
+git commit -m "feat: add align and align-feedback CLI subcommands"
+```
+
+---
+
+### Task 9: Add CLI integration tests
+
+**Files:**
+- Modify: `tests/cli_test.rs`
+
+**Step 1: Write CLI integration tests**
+
+Add to `tests/cli_test.rs`:
+
+```rust
+#[test]
+fn test_cli_align_two_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let source = dir.path().join("source.ttl");
+ let target = dir.path().join("target.ttl");
+
+ std::fs::write(&source, 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:Dog a owl:Class ; rdfs:label "Dog" .
+ ex:Cat a owl:Class ; rdfs:label "Cat" .
+ "#).unwrap();
+
+ std::fs::write(&target, r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix other: <http://other.org/> .
+ other:Dog a owl:Class ; rdfs:label "Dog" .
+ other:Feline a owl:Class ; rdfs:label "Cat" .
+ "#).unwrap();
+
+ let out = oo_isolated(&dir)
+ .args(["align", source.to_str().unwrap(), target.to_str().unwrap(), "--min-confidence", "0.5", "--dry-run"])
+ .output().unwrap();
+ assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ assert!(stdout.contains("candidates"));
+ assert!(stdout.contains("confidence"));
+}
+
+#[test]
+fn test_cli_align_feedback() {
+ let dir = tempfile::tempdir().unwrap();
+ let out = oo_isolated(&dir)
+ .args(["align-feedback", "--source", "http://ex.org/Dog", "--target", "http://other.org/Canine", "--accept"])
+ .output().unwrap();
+ assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ assert!(stdout.contains("ok"));
+}
+```
+
+**Step 2: Build and run integration tests**
+
+Run: `cargo test --test cli_test test_cli_align`
+Expected: 2 tests pass
+
+**Step 3: Commit**
+
+```bash
+git add tests/cli_test.rs
+git commit -m "test: add CLI integration tests for align and align-feedback"
+```
+
+---
+
+### Task 10: Run full test suite and verify
+
+**Files:** None (verification only)
+
+**Step 1: Run all tests**
+
+Run: `cargo test`
+Expected: All tests pass (existing + new)
+
+**Step 2: Run clippy**
+
+Run: `cargo clippy -- -D warnings`
+Expected: No warnings
+
+**Step 3: Build release binary**
+
+Run: `cargo build --release`
+Expected: Builds successfully
+
+**Step 4: Manual smoke test**
+
+Run:
+```bash
+./target/release/open-ontologies --help | grep align
+```
+Expected: Shows `align` and `align-feedback` subcommands
+
+**Step 5: Commit any fixes if needed, then verify branch is clean**
+
+Run: `git status`
+Expected: Clean working tree
diff --git a/docs/plans/2026-03-14-open-ontologies-studio-design.md b/docs/plans/2026-03-14-open-ontologies-studio-design.md
new file mode 100644
index 00000000..5179f74d
--- /dev/null
+++ b/docs/plans/2026-03-14-open-ontologies-studio-design.md
@@ -0,0 +1,466 @@
+# Open Ontologies Studio — Design Document
+
+**Date:** 2026-03-14
+**Status:** Approved
+**Author:** Fabio Rovai
+
+## Problem
+
+Ontology engineering today is trapped between two extremes:
+
+1. **Protege** — a 20-year-old Java desktop app. Tree-based, single-player, no AI awareness, no lineage, heavy.
+2. **Claude + Open Ontologies MCP** — powerful but invisible. The ontologist can't see what the AI is doing, can't visually explore the graph, can't point-and-click to edit.
+
+There is no modern, visual, AI-integrated ontology editor.
+
+## Solution
+
+**Open Ontologies Studio** — a cross-platform visual ontology editor built on top of the Open Ontologies engine. Graph-first, AI-integrated, human-in-the-loop.
+
+- **Engine** = `open-ontologies` (Rust CLI/MCP server, unchanged)
+- **Studio** = `open-ontologies-studio` (Flutter desktop/web/mobile app, new)
+
+## Design Principles
+
+1. **Graph is the primary interface** — not forms, not trees. Click nodes to edit, drag to connect, pinch to zoom.
+2. **AI is visible** — every action Claude takes appears in an activity feed with [approve] / [reject] controls.
+3. **Live, not dead** — validation runs continuously, errors appear as halos on nodes, changes animate in real-time.
+4. **Keyboard-first** — Cmd+K command palette, Tab navigation, shortcuts for everything.
+5. **Offline-first** — works without a network, syncs when connected.
+6. **One codebase, all platforms** — macOS, Windows, Linux, web, iPad.
+
+## Architecture
+
+### Stack
+
+| Layer | Technology | Why |
+|---|---|---|
+| UI framework | Flutter (Dart) | One codebase → 6 platforms, custom GPU rendering, native performance |
+| Graph rendering | CustomPainter (Flutter) | GPU-accelerated canvas, LOD rendering, 60fps with 10k+ nodes |
+| Graph compute | Rust shared library via FFI | Force-directed layout, spatial indexing, collision detection at native speed |
+| State management | Riverpod or Bloc | Reactive, testable, well-established in Flutter ecosystem |
+| Local storage | Isar or Hive | Offline caching of ontology snapshots |
+| Bridge to engine | gRPC with server-streaming | Typed API, real-time push from engine to UI |
+| Engine | Open Ontologies (Rust) | Oxigraph triple store, SQLite state, all 42 MCP tools |
+| AI integration | MCP (stdio/HTTP) | Claude connects to the same engine, changes stream to the UI |
+
+### Component Diagram
+
+```
+┌──────────────────────────────────────────────────────────┐
+│ Open Ontologies Studio │
+│ (Flutter — all platforms) │
+│ │
+│ ┌─────────────────────────────────────────────────┐ │
+│ │ Graph Canvas │ │
+│ │ CustomPainter + Rust FFI layout engine │ │
+│ │ ├── LOD rendering (clusters → labels → props) │ │
+│ │ ├── Spatial index (R-tree) for hit testing │ │
+│ │ ├── Force-directed / hierarchical / radial │ │
+│ │ ├── Drag-to-connect (creates triples) │ │
+│ │ ├── Multi-select, lasso, context menus │ │
+│ │ └── Animated transitions on changes │ │
+│ └─────────────────────────────────────────────────┘ │
+│ │
+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
+│ │ AI Activity │ │ Validation │ │ Lineage │ │
+│ │ Panel │ │ Panel │ │ Timeline │ │
+│ │ │ │ │ │ │ │
+│ │ Shows tool │ │ Live lint + │ │ Version │ │
+│ │ calls from │ │ SHACL errors │ │ snapshots │ │
+│ │ Claude with │ │ as node │ │ with diff │ │
+│ │ approve / │ │ halos, auto- │ │ and revert │ │
+│ │ reject │ │ fix suggest │ │ controls │ │
+│ └──────────────┘ └──────────────┘ └──────────────┘ │
+│ │
+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
+│ │ SPARQL │ │ Property │ │ SHACL │ │
+│ │ Editor │ │ Inspector │ │ Constraints │ │
+│ │ │ │ │ │ │ │
+│ │ Autocomplete │ │ Edit labels, │ │ Visual shape │ │
+│ │ with loaded │ │ comments, │ │ indicators │ │
+│ │ class/prop │ │ domains, │ │ on graph │ │
+│ │ names │ │ ranges │ │ nodes │ │
+│ └──────────────┘ └──────────────┘ └──────────────┘ │
+│ │
+│ ┌─────────────────────────────────────────────────┐ │
+│ │ Cmd+K: command palette │ │
+│ │ "add Vehicle subclass of Thing" │ │
+│ └─────────────────────────────────────────────────┘ │
+│ │
+│ gRPC (streaming) │
+└──────────────────────────────────────────────────────────┘
+ │
+ ▼
+ ┌───────────────────────┐
+ │ Open Ontologies │
+ │ (Rust engine) │
+ │ │
+ │ Oxigraph + SQLite │
+ │ 42 MCP tools │
+ │ │
+ │ Interfaces: │
+ │ ├── gRPC (Studio) │
+ │ ├── MCP stdio │
+ │ ├── MCP HTTP │
+ │ └── CLI │
+ └───────────────────────┘
+ ▲
+ │ MCP (stdio/HTTP)
+ ▼
+ ┌───────────────────────┐
+ │ Claude / LLM │
+ └───────────────────────┘
+```
+
+### Data Flow
+
+#### Human edits a node
+
+1. User clicks node in graph → Property Inspector opens
+2. User changes label from "Car" to "Automobile"
+3. Flutter sends `UpdateTriple` via gRPC to engine
+4. Engine updates Oxigraph, records in lineage
+5. Engine streams `ChangeEvent` back
+6. Graph canvas animates the label change
+
+#### Claude modifies the ontology
+
+1. Claude calls `onto_plan` via MCP → engine returns plan
+2. Engine streams `PlanEvent` to Studio via gRPC
+3. AI Activity Panel shows: "Claude wants to add 3 classes" with [approve] [reject]
+4. User clicks [approve]
+5. Studio sends approval → engine calls `onto_apply`
+6. Engine streams `ChangeEvent` for each added class
+7. Graph canvas animates new nodes appearing
+
+#### Offline editing
+
+1. Studio has a local Isar cache of the last-loaded ontology
+2. User edits offline → changes queued locally
+3. On reconnect → changes replayed to engine in order
+4. Conflicts shown in UI for resolution
+
+## Graph Compute Engine (Rust FFI)
+
+The graph layout runs in Rust as a shared library, called from Flutter via FFI. This separates the computationally expensive layout from the UI thread.
+
+### Compilation targets
+
+```
+graph_compute/
+├── src/
+│ ├── layout.rs # Force-directed, hierarchical, radial
+│ ├── spatial.rs # R-tree spatial index
+│ ├── clustering.rs # LOD clustering for large graphs
+│ └── lib.rs # FFI exports
+├── Cargo.toml
+└── targets:
+ ├── libgraph.dylib (macOS)
+ ├── graph.dll (Windows)
+ ├── libgraph.so (Linux)
+ └── graph.wasm (web)
+```
+
+### FFI interface
+
+```rust
+#[no_mangle]
+pub extern "C" fn graph_layout_tick(
+ nodes: *const f64, // [x, y, x, y, ...] positions
+ edges: *const u32, // [src, dst, src, dst, ...] indices
+ node_count: u32,
+ edge_count: u32,
+ out_positions: *mut f64, // updated positions
+) -> bool; // true if converged
+
+#[no_mangle]
+pub extern "C" fn graph_hit_test(
+ x: f64, y: f64,
+ nodes: *const f64,
+ node_count: u32,
+) -> i32; // node index or -1
+```
+
+## gRPC API
+
+### Service definition
+
+```protobuf
+syntax = "proto3";
+
+service OntologyEngine {
+ // Core operations (map to existing onto_* tools)
+ rpc LoadOntology(LoadRequest) returns (LoadResponse);
+ rpc Query(SparqlRequest) returns (QueryResponse);
+ rpc Validate(ValidateRequest) returns (ValidateResponse);
+ rpc Stats(StatsRequest) returns (StatsResponse);
+ rpc Lint(LintRequest) returns (LintResponse);
+ rpc Save(SaveRequest) returns (SaveResponse);
+ rpc Clear(ClearRequest) returns (ClearResponse);
+
+ // Lifecycle
+ rpc Plan(PlanRequest) returns (PlanResponse);
+ rpc Apply(ApplyRequest) returns (ApplyResponse);
+ rpc Enforce(EnforceRequest) returns (EnforceResponse);
+
+ // Graph data for rendering
+ rpc GetGraph(GraphRequest) returns (GraphResponse);
+
+ // Real-time streaming — engine pushes to Studio
+ rpc WatchChanges(WatchRequest) returns (stream ChangeEvent);
+ rpc WatchValidation(WatchRequest) returns (stream ValidationEvent);
+}
+
+message ChangeEvent {
+ enum Type {
+ TRIPLE_ADDED = 0;
+ TRIPLE_REMOVED = 1;
+ CLASS_ADDED = 2;
+ CLASS_REMOVED = 3;
+ PROPERTY_ADDED = 4;
+ PROPERTY_REMOVED = 5;
+ PLAN_PROPOSED = 6;
+ APPLY_COMPLETED = 7;
+ }
+ Type type = 1;
+ string subject = 2;
+ string predicate = 3;
+ string object = 4;
+ string source = 5; // "claude" or "human"
+ int64 timestamp = 6;
+}
+
+message GraphResponse {
+ repeated GraphNode nodes = 1;
+ repeated GraphEdge edges = 2;
+}
+
+message GraphNode {
+ string iri = 1;
+ string label = 2;
+ string comment = 3;
+ string type = 4; // "class", "individual", "property"
+ repeated string domains = 5;
+ repeated string ranges = 6;
+}
+
+message GraphEdge {
+ string source_iri = 1;
+ string target_iri = 2;
+ string predicate = 3; // "rdfs:subClassOf", "owl:equivalentClass", etc.
+}
+```
+
+## UI Components
+
+### 1. Graph Canvas (main view)
+
+- Full-screen GPU-rendered canvas via `CustomPainter`
+- Level-of-detail rendering:
+ - Galaxy view (>1000 visible): colored clusters with count labels
+ - Neighborhood view (100-1000): nodes with labels, edges with type colors
+ - Detail view (<100): full property display on nodes, edge labels
+- Layout modes: force-directed (default), hierarchical, radial, manual
+- Interactions: click, double-click edit, drag move, drag-to-connect, lasso select, pinch zoom, two-finger pan
+- Visual encoding:
+ - Node color = type (class=blue, individual=green, datatype property=orange, object property=purple)
+ - Node border = validation status (green=ok, yellow=warning, red=error)
+ - Edge style = relationship type (solid=subClassOf, dashed=equivalentClass, dotted=domain/range)
+
+### 2. AI Activity Panel
+
+- Chronological feed of all MCP tool calls from Claude
+- Each entry shows: tool name, summary, timestamp, source
+- Action buttons: [approve] [reject] [undo] [details]
+- When Claude proposes a plan: shows added/removed with risk score
+- Expandable to see full tool input/output
+
+### 3. Validation Panel
+
+- Live results from `onto_lint` and `onto_shacl`
+- Grouped by severity: errors, warnings, info
+- Click an issue → highlights the relevant node on the graph
+- [auto-fix] button where applicable (e.g., add missing label)
+
+### 4. Lineage Timeline
+
+- Visual timeline of all versions (from `onto_history`)
+- Click any version to load it
+- [diff] button between any two versions
+- Shows who/what made each change (Claude vs human)
+
+### 5. SPARQL Editor
+
+- Syntax-highlighted editor with autocomplete
+- Autocomplete knows loaded class names, property names, prefixes
+- Results displayed as table or injected into graph view
+- Saved query library
+
+### 6. Property Inspector
+
+- Appears when a node is selected
+- Edit: label, comment, equivalent classes, disjoint classes
+- View: domain/range for properties, SHACL constraints
+- Add: new subclass, new property, new individual
+
+### 7. Command Palette (Cmd+K)
+
+- Search across all actions, tools, classes, properties
+- Natural language input: "add Vehicle subclass of Thing" → calls Claude
+- Quick actions: "export turtle", "run SHACL", "compare versions"
+
+## Platform Matrix
+
+| Platform | Build | Distribution |
+|---|---|---|
+| macOS (arm64, x86_64) | GitHub Actions | `.dmg` on GitHub Releases |
+| Windows (x86_64) | GitHub Actions | `.msix` on GitHub Releases |
+| Linux (x86_64) | GitHub Actions | `.AppImage` / `.deb` on Releases |
+| Web | GitHub Actions | GitHub Pages or self-hosted |
+| iPad | GitHub Actions | TestFlight → App Store (later) |
+
+All builds run in CI. Local development uses `flutter run` against a browser or connected device, with `open-ontologies serve-http` running locally.
+
+## Repository Structure
+
+```
+open-ontologies-studio/
+├── lib/ # Flutter/Dart source
+│ ├── main.dart
+│ ├── app.dart
+│ ├── features/
+│ │ ├── graph/ # Graph canvas + rendering
+│ │ ├── ai_activity/ # AI activity panel
+│ │ ├── validation/ # Live validation panel
+│ │ ├── lineage/ # Version timeline
+│ │ ├── sparql/ # SPARQL editor
+│ │ ├── inspector/ # Property inspector
+│ │ └── command_palette/ # Cmd+K
+│ ├── services/
+│ │ ├── engine_client.dart # gRPC client to Open Ontologies
+│ │ └── graph_compute.dart # FFI bridge to Rust layout engine
+│ └── models/
+│ ├── graph_node.dart
+│ ├── graph_edge.dart
+│ └── change_event.dart
+├── native/ # Rust graph compute library
+│ ├── src/
+│ │ ├── layout.rs
+│ │ ├── spatial.rs
+│ │ └── lib.rs
+│ └── Cargo.toml
+├── proto/ # gRPC service definitions
+│ └── ontology.proto
+├── test/ # Flutter tests
+├── pubspec.yaml # Dart dependencies
+└── .github/
+ └── workflows/
+ └── build.yml # CI for all platforms
+```
+
+## Build & Development
+
+### Local development (lightweight)
+
+```bash
+# Terminal 1: run the engine
+cd open-ontologies && cargo run --release -- serve-http
+
+# Terminal 2: run the Studio in browser (hot reload)
+cd open-ontologies-studio && flutter run -d chrome
+```
+
+No heavy compilation needed locally. The Rust graph compute library has a Dart fallback for development (slower but works without compiling Rust).
+
+### CI build (full)
+
+GitHub Actions compiles:
+1. Rust graph compute library for all targets
+2. Flutter app for macOS, Windows, Linux, web
+3. Packages as `.dmg`, `.msix`, `.AppImage`, `.deb`
+4. Uploads to GitHub Releases
+
+## Open Questions
+
+1. **gRPC vs HTTP+SSE** — gRPC is more typed and supports streaming natively, but adds a dependency (tonic on Rust side, grpc-dart on Flutter side). HTTP+SSE is simpler but less structured. Recommendation: start with HTTP+SSE for simplicity, migrate to gRPC if needed.
+
+2. **Graph compute Dart fallback** — for local dev without compiling Rust, should the Dart fallback use a simple force-directed algorithm or skip layout entirely? Recommendation: simple Dart force-directed, good enough for <500 nodes during dev.
+
+3. **Offline sync strategy** — CRDT-based merge vs last-write-wins vs manual conflict resolution? Recommendation: start with manual conflict resolution, CRDTs are overkill initially.
+
+4. **Mobile scope** — full editing on iPad or read-only exploration? Recommendation: read-only + approve/reject AI changes initially, full editing later.
+
+## Phase 2: Advanced Features
+
+### 8. Poincaré Embedding Layout
+
+Open Ontologies already computes Poincaré structural embeddings via `onto_embed`. These encode hierarchical distance in hyperbolic space — classes near each other in the taxonomy are close in the Poincaré disk.
+
+**Implementation:**
+
+- Call `onto_embed` to get `struct_vec` (Poincaré coordinates) for each class
+- Map Poincaré disk coordinates (hyperbolic) to screen coordinates using the Beltrami-Klein projection
+- Add "Poincaré" as a layout option alongside force-directed, hierarchical, radial
+- Classes that are semantically similar cluster naturally — no O(n²) force simulation needed
+- Combined with `onto_search`, clicking empty space and typing a concept highlights the nearest cluster
+
+**Why this is a killer feature:** No other ontology editor uses the ontology's own embedding geometry as a layout algorithm. The graph literally organizes itself by meaning.
+
+### 9. Virtual Graph Querying (R2RML / Direct Mapping)
+
+Query external databases (PostgreSQL) as if they were part of the ontology graph, without materializing triples.
+
+**Engine side (Rust):**
+
+- New `onto_virtual_query` tool that accepts SPARQL + a database connection string
+- Uses R2RML mappings (or Direct Mapping for unmapped tables) to translate SPARQL to SQL
+- Returns SPARQL-compatible JSON results — Studio treats them identically to Oxigraph results
+
+**Studio side (Flutter):**
+
+- "Virtual Sources" panel to configure database connections
+- SPARQL editor shows virtual and materialized results with different badges
+- Option to materialize virtual results into the triple store via `onto_load`
+
+### 10. Visual Mapping Editor
+
+A split-pane editor for creating and editing ontology alignment mappings interactively.
+
+**Engine side (Rust):**
+
+- Extend `onto_align` to persist mapping specs (save/load/edit alignment candidates)
+- New `onto_align_save` / `onto_align_load` tools for mapping spec lifecycle
+
+**Studio side (Flutter):**
+
+- Left pane: source ontology graph
+- Right pane: target ontology graph
+- Drag a class from left to right to create `owl:equivalentClass` / `skos:exactMatch` / `rdfs:subClassOf`
+- Shows `onto_align` suggestions as dashed lines with confidence scores
+- Click a suggestion to accept/reject (feeds `onto_align_feedback`)
+- Export accepted mappings as Turtle
+
+### 11. OWL2 Profile Selector & Reasoning Control
+
+**Engine side (Rust):**
+
+- Extend `onto_reason` with EL, QL, RL profile modes
+- Profile detection: analyze loaded ontology and recommend the most specific applicable profile
+- Profile violations highlighted as lint issues
+
+**Studio side (Flutter):**
+
+- Dropdown in toolbar: "Profile: OWL2 Full | EL | QL | RL | RDFS"
+- When profile is selected, lint automatically flags axioms outside that profile
+- Reasoner panel shows inferred triples with provenance (which axioms produced them)
+- "Explain" button on each inferred triple → shows derivation tree
+
+## Success Criteria
+
+1. Load a 1,000-class ontology and render at 60fps
+2. Human can add a class by dragging on the canvas in <3 seconds
+3. Claude's changes appear on the canvas within 1 second
+4. Human can approve/reject any AI change before it's applied
+5. Full ontology lifecycle (plan → enforce → apply → monitor) visible in the UI
+6. Works on macOS, Windows, and web from a single codebase
diff --git a/docs/plans/2026-03-14-open-ontologies-studio-plan.md b/docs/plans/2026-03-14-open-ontologies-studio-plan.md
new file mode 100644
index 00000000..761b95ce
--- /dev/null
+++ b/docs/plans/2026-03-14-open-ontologies-studio-plan.md
@@ -0,0 +1,1812 @@
+# Open Ontologies Studio — Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Build a cross-platform visual ontology editor (Flutter + Dart) that connects to the Open Ontologies Rust engine over HTTP+SSE, with a graph-first canvas, AI activity feed, and human-in-the-loop controls.
+
+**Architecture:** Flutter app as a thin client, Open Ontologies engine as the backend via `serve-http`. Start with HTTP+JSON (the MCP-over-HTTP endpoint already exists). Add SSE for real-time push. Graph layout in pure Dart initially, Rust FFI later. Separate repo `open-ontologies-studio`.
+
+**Tech Stack:** Flutter 3.x, Dart, Riverpod (state), CustomPainter (graph canvas), HTTP+SSE (bridge to engine), GitHub Actions (CI/CD)
+
+**Design doc:** `docs/plans/2026-03-14-open-ontologies-studio-design.md`
+
+---
+
+## Phase 1: Scaffold + Engine Connection (get data flowing)
+
+### Task 1: Create Flutter project and repo structure
+
+**Files:**
+- Create: `open-ontologies-studio/` (new repo at `/Users/fabio/projects/open-ontologies-studio/`)
+
+**Step 1: Create the Flutter project**
+
+```bash
+cd /Users/fabio/projects
+flutter create --org com.openontologies --project-name open_ontologies_studio open-ontologies-studio
+cd open-ontologies-studio
+```
+
+**Step 2: Clean up default boilerplate**
+
+Delete the default counter app code from `lib/main.dart`. Replace with a minimal app shell:
+
+```dart
+import 'package:flutter/material.dart';
+
+void main() {
+ runApp(const OpenOntologiesStudio());
+}
+
+class OpenOntologiesStudio extends StatelessWidget {
+ const OpenOntologiesStudio({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Open Ontologies Studio',
+ theme: ThemeData.dark(useMaterial3: true),
+ home: const Scaffold(
+ body: Center(child: Text('Open Ontologies Studio')),
+ ),
+ );
+ }
+}
+```
+
+**Step 3: Set up directory structure**
+
+```bash
+mkdir -p lib/features/graph
+mkdir -p lib/features/ai_activity
+mkdir -p lib/features/validation
+mkdir -p lib/features/lineage
+mkdir -p lib/features/sparql
+mkdir -p lib/features/inspector
+mkdir -p lib/features/command_palette
+mkdir -p lib/services
+mkdir -p lib/models
+```
+
+**Step 4: Add core dependencies to `pubspec.yaml`**
+
+```yaml
+dependencies:
+ flutter:
+ sdk: flutter
+ flutter_riverpod: ^2.6.1
+ http: ^1.3.0
+ json_annotation: ^4.9.0
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ build_runner: ^2.4.0
+ json_serializable: ^6.9.0
+```
+
+**Step 5: Verify it runs**
+
+```bash
+flutter run -d chrome
+```
+
+Expected: dark-themed app with "Open Ontologies Studio" text centered.
+
+**Step 6: Initialize git and commit**
+
+```bash
+cd /Users/fabio/projects/open-ontologies-studio
+git init
+git add .
+git commit -m "feat: scaffold Flutter project with directory structure"
+```
+
+---
+
+### Task 2: Data models for graph nodes and edges
+
+**Files:**
+- Create: `lib/models/graph_node.dart`
+- Create: `lib/models/graph_edge.dart`
+- Create: `lib/models/ontology_stats.dart`
+- Test: `test/models/graph_node_test.dart`
+
+**Step 1: Write the failing test**
+
+```dart
+// test/models/graph_node_test.dart
+import 'package:flutter_test/flutter_test.dart';
+import 'package:open_ontologies_studio/models/graph_node.dart';
+
+void main() {
+ test('GraphNode.fromSparqlBinding parses a SPARQL result row', () {
+ final binding = {
+ 'class': {'type': 'uri', 'value': 'http://example.org/Vehicle'},
+ 'label': {'type': 'literal', 'value': 'Vehicle'},
+ 'comment': {'type': 'literal', 'value': 'A mode of transport'},
+ };
+ final node = GraphNode.fromSparqlBinding(binding);
+ expect(node.iri, 'http://example.org/Vehicle');
+ expect(node.label, 'Vehicle');
+ expect(node.comment, 'A mode of transport');
+ expect(node.nodeType, NodeType.owlClass);
+ });
+
+ test('GraphNode.fromSparqlBinding handles missing optional fields', () {
+ final binding = {
+ 'class': {'type': 'uri', 'value': 'http://example.org/Car'},
+ };
+ final node = GraphNode.fromSparqlBinding(binding);
+ expect(node.iri, 'http://example.org/Car');
+ expect(node.label, 'Car');
+ expect(node.comment, isNull);
+ });
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+flutter test test/models/graph_node_test.dart
+```
+
+Expected: FAIL — `graph_node.dart` doesn't exist.
+
+**Step 3: Write the models**
+
+```dart
+// lib/models/graph_node.dart
+enum NodeType { owlClass, individual, datatypeProperty, objectProperty }
+
+class GraphNode {
+ final String iri;
+ final String label;
+ final String? comment;
+ final NodeType nodeType;
+ double x;
+ double y;
+
+ GraphNode({
+ required this.iri,
+ required this.label,
+ this.comment,
+ this.nodeType = NodeType.owlClass,
+ this.x = 0,
+ this.y = 0,
+ });
+
+ /// Parse from a SPARQL SELECT result binding.
+ /// Expects keys: class (uri), label (optional), comment (optional).
+ factory GraphNode.fromSparqlBinding(Map<String, dynamic> binding) {
+ final iri = binding['class']['value'] as String;
+ final label = binding['label']?['value'] as String? ?? _localName(iri);
+ final comment = binding['comment']?['value'] as String?;
+ return GraphNode(iri: iri, label: label, comment: comment);
+ }
+
+ static String _localName(String iri) {
+ final hash = iri.lastIndexOf('#');
+ if (hash >= 0) return iri.substring(hash + 1);
+ final slash = iri.lastIndexOf('/');
+ if (slash >= 0) return iri.substring(slash + 1);
+ return iri;
+ }
+}
+```
+
+```dart
+// lib/models/graph_edge.dart
+class GraphEdge {
+ final String sourceIri;
+ final String targetIri;
+ final String predicate;
+
+ const GraphEdge({
+ required this.sourceIri,
+ required this.targetIri,
+ required this.predicate,
+ });
+
+ factory GraphEdge.fromSparqlBinding(Map<String, dynamic> binding) {
+ return GraphEdge(
+ sourceIri: binding['subject']['value'] as String,
+ targetIri: binding['object']['value'] as String,
+ predicate: binding['predicate']['value'] as String,
+ );
+ }
+}
+```
+
+```dart
+// lib/models/ontology_stats.dart
+class OntologyStats {
+ final int classes;
+ final int properties;
+ final int individuals;
+ final int triples;
+
+ const OntologyStats({
+ required this.classes,
+ required this.properties,
+ required this.individuals,
+ required this.triples,
+ });
+
+ factory OntologyStats.fromJson(Map<String, dynamic> json) {
+ return OntologyStats(
+ classes: json['classes'] as int? ?? 0,
+ properties: json['properties'] as int? ?? 0,
+ individuals: json['individuals'] as int? ?? 0,
+ triples: json['triples'] as int? ?? 0,
+ );
+ }
+}
+```
+
+**Step 4: Run test to verify it passes**
+
+```bash
+flutter test test/models/graph_node_test.dart
+```
+
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add lib/models/ test/models/
+git commit -m "feat: add GraphNode, GraphEdge, OntologyStats models"
+```
+
+---
+
+### Task 3: Engine client service (HTTP bridge to Open Ontologies)
+
+**Files:**
+- Create: `lib/services/engine_client.dart`
+- Test: `test/services/engine_client_test.dart`
+
+The engine exposes MCP-over-HTTP at `/mcp`. However, MCP's JSON-RPC protocol is complex for a UI client. The simpler approach: add a thin REST+JSON API alongside the MCP endpoint in the engine. But to avoid modifying the engine initially, we'll call the MCP endpoint directly using JSON-RPC.
+
+**Step 1: Write the failing test**
+
+```dart
+// test/services/engine_client_test.dart
+import 'package:flutter_test/flutter_test.dart';
+import 'package:open_ontologies_studio/services/engine_client.dart';
+
+void main() {
+ test('EngineClient builds correct MCP tool call JSON-RPC request', () {
+ final client = EngineClient(baseUrl: 'http://localhost:3000');
+ final body = client.buildToolCallRequest('onto_stats', {});
+ expect(body['jsonrpc'], '2.0');
+ expect(body['method'], 'tools/call');
+ expect(body['params']['name'], 'onto_stats');
+ });
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+flutter test test/services/engine_client_test.dart
+```
+
+Expected: FAIL
+
+**Step 3: Write the engine client**
+
+```dart
+// lib/services/engine_client.dart
+import 'dart:convert';
+import 'package:http/http.dart' as http;
+
+class EngineClient {
+ final String baseUrl;
+ final http.Client _http;
+ int _requestId = 0;
+ String? _sessionId;
+
+ EngineClient({required this.baseUrl, http.Client? httpClient})
+ : _http = httpClient ?? http.Client();
+
+ /// Build a JSON-RPC request for an MCP tool call.
+ Map<String, dynamic> buildToolCallRequest(String toolName, Map<String, dynamic> arguments) {
+ _requestId++;
+ return {
+ 'jsonrpc': '2.0',
+ 'id': _requestId,
+ 'method': 'tools/call',
+ 'params': {
+ 'name': toolName,
+ 'arguments': arguments,
+ },
+ };
+ }
+
+ /// Initialize the MCP session.
+ Future<void> initialize() async {
+ _requestId++;
+ final body = {
+ 'jsonrpc': '2.0',
+ 'id': _requestId,
+ 'method': 'initialize',
+ 'params': {
+ 'protocolVersion': '2024-11-05',
+ 'capabilities': {},
+ 'clientInfo': {'name': 'open-ontologies-studio', 'version': '0.1.0'},
+ },
+ };
+ final response = await _post(body);
+ // Extract session ID from response headers if present
+ _sessionId = response.headers['mcp-session-id'];
+ }
+
+ /// Call an MCP tool and return the result content.
+ Future<Map<String, dynamic>> callTool(String toolName, Map<String, dynamic> arguments) async {
+ final body = buildToolCallRequest(toolName, arguments);
+ final response = await _post(body);
+ final json = jsonDecode(response.body) as Map<String, dynamic>;
+ if (json.containsKey('error')) {
+ throw EngineException(json['error']['message'] as String);
+ }
+ // MCP tool results are in result.content[0].text (JSON string)
+ final content = json['result']['content'] as List;
+ final text = content.first['text'] as String;
+ return jsonDecode(text) as Map<String, dynamic>;
+ }
+
+ Future<http.Response> _post(Map<String, dynamic> body) async {
+ final headers = <String, String>{
+ 'Content-Type': 'application/json',
+ };
+ if (_sessionId != null) {
+ headers['Mcp-Session-Id'] = _sessionId!;
+ }
+ return _http.post(
+ Uri.parse('$baseUrl/mcp'),
+ headers: headers,
+ body: jsonEncode(body),
+ );
+ }
+
+ void dispose() {
+ _http.close();
+ }
+}
+
+class EngineException implements Exception {
+ final String message;
+ EngineException(this.message);
+ @override
+ String toString() => 'EngineException: $message';
+}
+```
+
+**Step 4: Run test to verify it passes**
+
+```bash
+flutter test test/services/engine_client_test.dart
+```
+
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add lib/services/engine_client.dart test/services/
+git commit -m "feat: add EngineClient for MCP-over-HTTP communication"
+```
+
+---
+
+### Task 4: Engine connection provider (Riverpod)
+
+**Files:**
+- Create: `lib/services/providers.dart`
+- Modify: `lib/main.dart`
+
+**Step 1: Create providers**
+
+```dart
+// lib/services/providers.dart
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'engine_client.dart';
+import '../models/ontology_stats.dart';
+import '../models/graph_node.dart';
+import '../models/graph_edge.dart';
+
+/// The engine client singleton. Configure the URL here.
+final engineClientProvider = Provider<EngineClient>((ref) {
+ final client = EngineClient(baseUrl: 'http://localhost:3000');
+ ref.onDispose(() => client.dispose());
+ return client;
+});
+
+/// Connection status.
+enum ConnectionStatus { disconnected, connecting, connected, error }
+
+final connectionStatusProvider = StateProvider<ConnectionStatus>(
+ (ref) => ConnectionStatus.disconnected,
+);
+
+/// Stats from the engine (refreshed on demand).
+final statsProvider = FutureProvider<OntologyStats?>((ref) async {
+ final client = ref.watch(engineClientProvider);
+ try {
+ final result = await client.callTool('onto_stats', {});
+ ref.read(connectionStatusProvider.notifier).state = ConnectionStatus.connected;
+ return OntologyStats.fromJson(result);
+ } catch (_) {
+ ref.read(connectionStatusProvider.notifier).state = ConnectionStatus.error;
+ return null;
+ }
+});
+
+/// Graph data — nodes and edges from a SPARQL query.
+final graphNodesProvider = FutureProvider<List<GraphNode>>((ref) async {
+ final client = ref.watch(engineClientProvider);
+ final result = await client.callTool('onto_query', {
+ 'sparql': '''
+ SELECT ?class ?label ?comment WHERE {
+ ?class a owl:Class .
+ OPTIONAL { ?class rdfs:label ?label }
+ OPTIONAL { ?class rdfs:comment ?comment }
+ }
+ ''',
+ });
+ final bindings = (result['results']?['bindings'] as List?) ?? [];
+ return bindings.map((b) => GraphNode.fromSparqlBinding(b as Map<String, dynamic>)).toList();
+});
+
+final graphEdgesProvider = FutureProvider<List<GraphEdge>>((ref) async {
+ final client = ref.watch(engineClientProvider);
+ final result = await client.callTool('onto_query', {
+ 'sparql': '''
+ SELECT ?subject ?predicate ?object WHERE {
+ ?subject rdfs:subClassOf ?object .
+ FILTER(isIRI(?object))
+ BIND(rdfs:subClassOf AS ?predicate)
+ }
+ ''',
+ });
+ final bindings = (result['results']?['bindings'] as List?) ?? [];
+ return bindings.map((b) => GraphEdge.fromSparqlBinding(b as Map<String, dynamic>)).toList();
+});
+```
+
+**Step 2: Wrap the app with ProviderScope**
+
+Update `lib/main.dart`:
+
+```dart
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+void main() {
+ runApp(const ProviderScope(child: OpenOntologiesStudio()));
+}
+
+class OpenOntologiesStudio extends StatelessWidget {
+ const OpenOntologiesStudio({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Open Ontologies Studio',
+ theme: ThemeData.dark(useMaterial3: true),
+ home: const Scaffold(
+ body: Center(child: Text('Open Ontologies Studio')),
+ ),
+ );
+ }
+}
+```
+
+**Step 3: Run the app to verify no errors**
+
+```bash
+flutter run -d chrome
+```
+
+Expected: app launches with no errors.
+
+**Step 4: Commit**
+
+```bash
+git add lib/services/providers.dart lib/main.dart
+git commit -m "feat: add Riverpod providers for engine connection and graph data"
+```
+
+---
+
+## Phase 2: Graph Canvas (see the ontology)
+
+### Task 5: Basic graph canvas with CustomPainter
+
+**Files:**
+- Create: `lib/features/graph/graph_canvas.dart`
+- Create: `lib/features/graph/graph_painter.dart`
+- Create: `lib/features/graph/graph_state.dart`
+
+**Step 1: Create the graph state**
+
+```dart
+// lib/features/graph/graph_state.dart
+import 'dart:ui';
+import '../../models/graph_node.dart';
+import '../../models/graph_edge.dart';
+
+class GraphState {
+ final List<GraphNode> nodes;
+ final List<GraphEdge> edges;
+ Offset panOffset;
+ double zoom;
+ int? selectedNodeIndex;
+ int? hoveredNodeIndex;
+
+ GraphState({
+ required this.nodes,
+ required this.edges,
+ this.panOffset = Offset.zero,
+ this.zoom = 1.0,
+ this.selectedNodeIndex,
+ this.hoveredNodeIndex,
+ });
+}
+```
+
+**Step 2: Create the painter**
+
+```dart
+// lib/features/graph/graph_painter.dart
+import 'dart:math';
+import 'package:flutter/material.dart';
+import '../../models/graph_node.dart';
+import '../../models/graph_edge.dart';
+import 'graph_state.dart';
+
+class GraphPainter extends CustomPainter {
+ final GraphState state;
+
+ static const nodeRadius = 24.0;
+ static const _classColor = Color(0xFF4A90D9);
+ static const _individualColor = Color(0xFF50C878);
+ static const _selectedColor = Color(0xFFFFD700);
+ static const _edgeColor = Color(0xFF666666);
+
+ GraphPainter(this.state);
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ canvas.save();
+ canvas.translate(
+ size.width / 2 + state.panOffset.dx,
+ size.height / 2 + state.panOffset.dy,
+ );
+ canvas.scale(state.zoom);
+
+ _drawEdges(canvas);
+ _drawNodes(canvas);
+
+ canvas.restore();
+ }
+
+ void _drawEdges(Canvas canvas) {
+ final paint = Paint()
+ ..color = _edgeColor
+ ..strokeWidth = 1.5
+ ..style = PaintingStyle.stroke;
+
+ final nodeMap = <String, GraphNode>{};
+ for (final node in state.nodes) {
+ nodeMap[node.iri] = node;
+ }
+
+ for (final edge in state.edges) {
+ final source = nodeMap[edge.sourceIri];
+ final target = nodeMap[edge.targetIri];
+ if (source == null || target == null) continue;
+
+ canvas.drawLine(
+ Offset(source.x, source.y),
+ Offset(target.x, target.y),
+ paint,
+ );
+
+ // Arrowhead
+ _drawArrowhead(canvas, source, target, paint);
+ }
+ }
+
+ void _drawArrowhead(Canvas canvas, GraphNode from, GraphNode to, Paint paint) {
+ final dx = to.x - from.x;
+ final dy = to.y - from.y;
+ final dist = sqrt(dx * dx + dy * dy);
+ if (dist < 0.001) return;
+
+ final ux = dx / dist;
+ final uy = dy / dist;
+
+ // Arrow tip stops at the node edge
+ final tipX = to.x - ux * nodeRadius;
+ final tipY = to.y - uy * nodeRadius;
+
+ const arrowSize = 10.0;
+ const arrowAngle = 0.4;
+
+ final path = Path()
+ ..moveTo(tipX, tipY)
+ ..lineTo(
+ tipX - arrowSize * (ux * cos(arrowAngle) - uy * sin(arrowAngle)),
+ tipY - arrowSize * (uy * cos(arrowAngle) + ux * sin(arrowAngle)),
+ )
+ ..moveTo(tipX, tipY)
+ ..lineTo(
+ tipX - arrowSize * (ux * cos(arrowAngle) + uy * sin(arrowAngle)),
+ tipY - arrowSize * (uy * cos(arrowAngle) - ux * sin(arrowAngle)),
+ );
+
+ canvas.drawPath(path, paint);
+ }
+
+ void _drawNodes(Canvas canvas) {
+ for (var i = 0; i < state.nodes.length; i++) {
+ final node = state.nodes[i];
+ final isSelected = i == state.selectedNodeIndex;
+ final isHovered = i == state.hoveredNodeIndex;
+
+ // Node circle
+ final fillPaint = Paint()
+ ..color = node.nodeType == NodeType.owlClass ? _classColor : _individualColor
+ ..style = PaintingStyle.fill;
+
+ canvas.drawCircle(Offset(node.x, node.y), nodeRadius, fillPaint);
+
+ // Selection/hover ring
+ if (isSelected || isHovered) {
+ final ringPaint = Paint()
+ ..color = isSelected ? _selectedColor : Colors.white54
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = isSelected ? 3.0 : 2.0;
+ canvas.drawCircle(Offset(node.x, node.y), nodeRadius + 3, ringPaint);
+ }
+
+ // Label
+ final textPainter = TextPainter(
+ text: TextSpan(
+ text: node.label,
+ style: const TextStyle(color: Colors.white, fontSize: 11),
+ ),
+ textDirection: TextDirection.ltr,
+ )..layout(maxWidth: 120);
+
+ textPainter.paint(
+ canvas,
+ Offset(node.x - textPainter.width / 2, node.y + nodeRadius + 4),
+ );
+ }
+ }
+
+ @override
+ bool shouldRepaint(GraphPainter oldDelegate) => true;
+}
+```
+
+**Step 3: Create the interactive canvas widget**
+
+```dart
+// lib/features/graph/graph_canvas.dart
+import 'dart:math';
+import 'package:flutter/material.dart';
+import 'package:flutter/gestures.dart';
+import '../../models/graph_node.dart';
+import '../../models/graph_edge.dart';
+import 'graph_painter.dart';
+import 'graph_state.dart';
+
+class GraphCanvas extends StatefulWidget {
+ final List<GraphNode> nodes;
+ final List<GraphEdge> edges;
+ final void Function(GraphNode)? onNodeSelected;
+
+ const GraphCanvas({
+ super.key,
+ required this.nodes,
+ required this.edges,
+ this.onNodeSelected,
+ });
+
+ @override
+ State<GraphCanvas> createState() => _GraphCanvasState();
+}
+
+class _GraphCanvasState extends State<GraphCanvas> {
+ late GraphState _state;
+ int? _draggedNodeIndex;
+ Offset? _lastPanPosition;
+
+ @override
+ void initState() {
+ super.initState();
+ _state = GraphState(nodes: widget.nodes, edges: widget.edges);
+ _applyInitialLayout();
+ }
+
+ @override
+ void didUpdateWidget(GraphCanvas oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (widget.nodes != oldWidget.nodes || widget.edges != oldWidget.edges) {
+ _state = GraphState(
+ nodes: widget.nodes,
+ edges: widget.edges,
+ panOffset: _state.panOffset,
+ zoom: _state.zoom,
+ );
+ _applyInitialLayout();
+ }
+ }
+
+ /// Simple circular layout as initial placement.
+ void _applyInitialLayout() {
+ final n = _state.nodes.length;
+ if (n == 0) return;
+ final radius = max(100.0, n * 20.0);
+ for (var i = 0; i < n; i++) {
+ final angle = (2 * pi * i) / n;
+ _state.nodes[i].x = radius * cos(angle);
+ _state.nodes[i].y = radius * sin(angle);
+ }
+ }
+
+ int? _hitTest(Offset localPosition, Size size) {
+ final canvasCenter = Offset(size.width / 2, size.height / 2);
+ for (var i = _state.nodes.length - 1; i >= 0; i--) {
+ final node = _state.nodes[i];
+ final nodeScreen = Offset(
+ canvasCenter.dx + _state.panOffset.dx + node.x * _state.zoom,
+ canvasCenter.dy + _state.panOffset.dy + node.y * _state.zoom,
+ );
+ final dist = (localPosition - nodeScreen).distance;
+ if (dist <= GraphPainter.nodeRadius * _state.zoom) return i;
+ }
+ return null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Listener(
+ onPointerSignal: (event) {
+ if (event is PointerScrollEvent) {
+ setState(() {
+ final delta = event.scrollDelta.dy > 0 ? 0.9 : 1.1;
+ _state.zoom = (_state.zoom * delta).clamp(0.1, 5.0);
+ });
+ }
+ },
+ child: GestureDetector(
+ onPanStart: (details) {
+ final hit = _hitTest(details.localPosition, context.size!);
+ _draggedNodeIndex = hit;
+ _lastPanPosition = details.localPosition;
+ if (hit != null) {
+ setState(() {
+ _state.selectedNodeIndex = hit;
+ });
+ widget.onNodeSelected?.call(_state.nodes[hit]);
+ }
+ },
+ onPanUpdate: (details) {
+ setState(() {
+ if (_draggedNodeIndex != null) {
+ // Drag node
+ _state.nodes[_draggedNodeIndex!].x += details.delta.dx / _state.zoom;
+ _state.nodes[_draggedNodeIndex!].y += details.delta.dy / _state.zoom;
+ } else {
+ // Pan canvas
+ _state.panOffset += details.delta;
+ }
+ });
+ _lastPanPosition = details.localPosition;
+ },
+ onPanEnd: (_) {
+ _draggedNodeIndex = null;
+ _lastPanPosition = null;
+ },
+ child: CustomPaint(
+ painter: GraphPainter(_state),
+ size: Size.infinite,
+ ),
+ ),
+ );
+ }
+}
+```
+
+**Step 4: Verify it compiles**
+
+```bash
+flutter analyze
+```
+
+Expected: no errors.
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/graph/
+git commit -m "feat: add graph canvas with CustomPainter, pan, zoom, node drag"
+```
+
+---
+
+### Task 6: Force-directed layout (pure Dart)
+
+**Files:**
+- Create: `lib/features/graph/force_layout.dart`
+- Test: `test/features/graph/force_layout_test.dart`
+
+**Step 1: Write the failing test**
+
+```dart
+// test/features/graph/force_layout_test.dart
+import 'package:flutter_test/flutter_test.dart';
+import 'package:open_ontologies_studio/models/graph_node.dart';
+import 'package:open_ontologies_studio/models/graph_edge.dart';
+import 'package:open_ontologies_studio/features/graph/force_layout.dart';
+
+void main() {
+ test('ForceLayout separates overlapping nodes', () {
+ final nodes = [
+ GraphNode(iri: 'a', label: 'A', x: 0, y: 0),
+ GraphNode(iri: 'b', label: 'B', x: 0, y: 0),
+ ];
+ final edges = <GraphEdge>[];
+
+ final layout = ForceLayout(nodes: nodes, edges: edges);
+ for (var i = 0; i < 50; i++) {
+ layout.tick();
+ }
+
+ final dx = nodes[0].x - nodes[1].x;
+ final dy = nodes[0].y - nodes[1].y;
+ final distance = (dx * dx + dy * dy);
+ expect(distance, greaterThan(100)); // nodes should have separated
+ });
+
+ test('ForceLayout pulls connected nodes closer', () {
+ final nodes = [
+ GraphNode(iri: 'a', label: 'A', x: -500, y: 0),
+ GraphNode(iri: 'b', label: 'B', x: 500, y: 0),
+ ];
+ final edges = [
+ GraphEdge(sourceIri: 'a', targetIri: 'b', predicate: 'rdfs:subClassOf'),
+ ];
+
+ final layout = ForceLayout(nodes: nodes, edges: edges);
+ final initialDistance = 1000.0;
+ for (var i = 0; i < 100; i++) {
+ layout.tick();
+ }
+
+ final dx = nodes[0].x - nodes[1].x;
+ final dy = nodes[0].y - nodes[1].y;
+ final finalDistance = (dx * dx + dy * dy);
+ expect(finalDistance, lessThan(initialDistance * initialDistance));
+ });
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+flutter test test/features/graph/force_layout_test.dart
+```
+
+Expected: FAIL
+
+**Step 3: Write the force layout**
+
+```dart
+// lib/features/graph/force_layout.dart
+import 'dart:math';
+import '../../models/graph_node.dart';
+import '../../models/graph_edge.dart';
+
+class ForceLayout {
+ final List<GraphNode> nodes;
+ final List<GraphEdge> edges;
+
+ double repulsionStrength;
+ double attractionStrength;
+ double damping;
+ double idealEdgeLength;
+
+ final List<double> _vx;
+ final List<double> _vy;
+
+ ForceLayout({
+ required this.nodes,
+ required this.edges,
+ this.repulsionStrength = 5000.0,
+ this.attractionStrength = 0.01,
+ this.damping = 0.9,
+ this.idealEdgeLength = 150.0,
+ }) : _vx = List.filled(nodes.length, 0.0),
+ _vy = List.filled(nodes.length, 0.0);
+
+ /// Run one simulation tick. Returns total kinetic energy.
+ double tick() {
+ // Repulsion (all pairs)
+ for (var i = 0; i < nodes.length; i++) {
+ for (var j = i + 1; j < nodes.length; j++) {
+ var dx = nodes[j].x - nodes[i].x;
+ var dy = nodes[j].y - nodes[i].y;
+ var dist = sqrt(dx * dx + dy * dy);
+ if (dist < 1.0) {
+ dx = (Random().nextDouble() - 0.5) * 2;
+ dy = (Random().nextDouble() - 0.5) * 2;
+ dist = 1.0;
+ }
+ final force = repulsionStrength / (dist * dist);
+ final fx = force * dx / dist;
+ final fy = force * dy / dist;
+ _vx[i] -= fx;
+ _vy[i] -= fy;
+ _vx[j] += fx;
+ _vy[j] += fy;
+ }
+ }
+
+ // Attraction (edges)
+ final nodeIndex = <String, int>{};
+ for (var i = 0; i < nodes.length; i++) {
+ nodeIndex[nodes[i].iri] = i;
+ }
+
+ for (final edge in edges) {
+ final si = nodeIndex[edge.sourceIri];
+ final ti = nodeIndex[edge.targetIri];
+ if (si == null || ti == null) continue;
+
+ final dx = nodes[ti].x - nodes[si].x;
+ final dy = nodes[ti].y - nodes[si].y;
+ final dist = sqrt(dx * dx + dy * dy);
+ if (dist < 0.001) continue;
+
+ final force = attractionStrength * (dist - idealEdgeLength);
+ final fx = force * dx / dist;
+ final fy = force * dy / dist;
+ _vx[si] += fx;
+ _vy[si] += fy;
+ _vx[ti] -= fx;
+ _vy[ti] -= fy;
+ }
+
+ // Apply velocities with damping
+ var energy = 0.0;
+ for (var i = 0; i < nodes.length; i++) {
+ _vx[i] *= damping;
+ _vy[i] *= damping;
+ nodes[i].x += _vx[i];
+ nodes[i].y += _vy[i];
+ energy += _vx[i] * _vx[i] + _vy[i] * _vy[i];
+ }
+
+ return energy;
+ }
+
+ /// Run until converged or max iterations.
+ void run({int maxIterations = 300, double threshold = 0.5}) {
+ for (var i = 0; i < maxIterations; i++) {
+ final energy = tick();
+ if (energy < threshold) break;
+ }
+ }
+}
+```
+
+**Step 4: Run test to verify it passes**
+
+```bash
+flutter test test/features/graph/force_layout_test.dart
+```
+
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/graph/force_layout.dart test/features/graph/
+git commit -m "feat: add force-directed graph layout in pure Dart"
+```
+
+---
+
+## Phase 3: Main UI Shell (wire it together)
+
+### Task 7: Main screen with graph + status bar
+
+**Files:**
+- Create: `lib/features/home_screen.dart`
+- Modify: `lib/main.dart`
+
+**Step 1: Create the home screen**
+
+```dart
+// lib/features/home_screen.dart
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/providers.dart';
+import 'graph/graph_canvas.dart';
+
+class HomeScreen extends ConsumerStatefulWidget {
+ const HomeScreen({super.key});
+
+ @override
+ ConsumerState<HomeScreen> createState() => _HomeScreenState();
+}
+
+class _HomeScreenState extends ConsumerState<HomeScreen> {
+ @override
+ void initState() {
+ super.initState();
+ _connect();
+ }
+
+ Future<void> _connect() async {
+ ref.read(connectionStatusProvider.notifier).state = ConnectionStatus.connecting;
+ try {
+ await ref.read(engineClientProvider).initialize();
+ ref.read(connectionStatusProvider.notifier).state = ConnectionStatus.connected;
+ ref.invalidate(statsProvider);
+ ref.invalidate(graphNodesProvider);
+ ref.invalidate(graphEdgesProvider);
+ } catch (e) {
+ ref.read(connectionStatusProvider.notifier).state = ConnectionStatus.error;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final status = ref.watch(connectionStatusProvider);
+ final nodesAsync = ref.watch(graphNodesProvider);
+ final edgesAsync = ref.watch(graphEdgesProvider);
+ final statsAsync = ref.watch(statsProvider);
+
+ return Scaffold(
+ body: Column(
+ children: [
+ // Graph canvas (fills available space)
+ Expanded(
+ child: nodesAsync.when(
+ data: (nodes) => edgesAsync.when(
+ data: (edges) => nodes.isEmpty
+ ? const Center(child: Text('No ontology loaded. Use Claude or CLI to load one.'))
+ : GraphCanvas(nodes: nodes, edges: edges),
+ loading: () => const Center(child: CircularProgressIndicator()),
+ error: (e, _) => Center(child: Text('Error: $e')),
+ ),
+ loading: () => const Center(child: CircularProgressIndicator()),
+ error: (e, _) => Center(child: Text('Error: $e')),
+ ),
+ ),
+
+ // Status bar
+ Container(
+ height: 28,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ color: Colors.grey[900],
+ child: Row(
+ children: [
+ // Connection indicator
+ Icon(
+ Icons.circle,
+ size: 8,
+ color: switch (status) {
+ ConnectionStatus.connected => Colors.green,
+ ConnectionStatus.connecting => Colors.orange,
+ ConnectionStatus.error => Colors.red,
+ ConnectionStatus.disconnected => Colors.grey,
+ },
+ ),
+ const SizedBox(width: 6),
+ Text(
+ switch (status) {
+ ConnectionStatus.connected => 'Connected',
+ ConnectionStatus.connecting => 'Connecting...',
+ ConnectionStatus.error => 'Disconnected',
+ ConnectionStatus.disconnected => 'Not connected',
+ },
+ style: const TextStyle(fontSize: 11),
+ ),
+ const Spacer(),
+ // Stats
+ statsAsync.when(
+ data: (stats) => stats == null
+ ? const SizedBox()
+ : Text(
+ '${stats.classes} classes ${stats.properties} props ${stats.triples} triples',
+ style: const TextStyle(fontSize: 11, color: Colors.grey),
+ ),
+ loading: () => const SizedBox(),
+ error: (_, __) => const SizedBox(),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+```
+
+**Step 2: Update main.dart to use HomeScreen**
+
+```dart
+// lib/main.dart
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'features/home_screen.dart';
+
+void main() {
+ runApp(const ProviderScope(child: OpenOntologiesStudio()));
+}
+
+class OpenOntologiesStudio extends StatelessWidget {
+ const OpenOntologiesStudio({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Open Ontologies Studio',
+ debugShowCheckedModeBanner: false,
+ theme: ThemeData.dark(useMaterial3: true).copyWith(
+ scaffoldBackgroundColor: const Color(0xFF1E1E2E),
+ ),
+ home: const HomeScreen(),
+ );
+ }
+}
+```
+
+**Step 3: Run the app**
+
+```bash
+# Terminal 1: start the engine with a loaded ontology
+open-ontologies serve-http
+
+# Terminal 2: run the Studio
+cd /Users/fabio/projects/open-ontologies-studio
+flutter run -d chrome
+```
+
+Expected: dark app with graph canvas (empty if no ontology loaded), status bar showing connection status.
+
+**Step 4: Commit**
+
+```bash
+git add lib/features/home_screen.dart lib/main.dart
+git commit -m "feat: add main screen with graph canvas and status bar"
+```
+
+---
+
+### Task 8: Property inspector panel
+
+**Files:**
+- Create: `lib/features/inspector/property_inspector.dart`
+- Modify: `lib/features/home_screen.dart`
+
+**Step 1: Create the inspector**
+
+```dart
+// lib/features/inspector/property_inspector.dart
+import 'package:flutter/material.dart';
+import '../../models/graph_node.dart';
+
+class PropertyInspector extends StatelessWidget {
+ final GraphNode node;
+ final VoidCallback onClose;
+
+ const PropertyInspector({
+ super.key,
+ required this.node,
+ required this.onClose,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return Container(
+ width: 300,
+ color: const Color(0xFF252535),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Header
+ Container(
+ padding: const EdgeInsets.all(12),
+ color: const Color(0xFF2D2D3F),
+ child: Row(
+ children: [
+ const Icon(Icons.info_outline, size: 16),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ node.label,
+ style: const TextStyle(fontWeight: FontWeight.bold),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ IconButton(
+ icon: const Icon(Icons.close, size: 16),
+ onPressed: onClose,
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints(),
+ ),
+ ],
+ ),
+ ),
+
+ // Properties
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.all(12),
+ children: [
+ _propertyRow('IRI', node.iri),
+ _propertyRow('Type', node.nodeType.name),
+ if (node.comment != null) _propertyRow('Comment', node.comment!),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _propertyRow(String label, String value) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(label, style: const TextStyle(fontSize: 10, color: Colors.grey)),
+ const SizedBox(height: 2),
+ SelectableText(value, style: const TextStyle(fontSize: 13)),
+ ],
+ ),
+ );
+ }
+}
+```
+
+**Step 2: Wire into HomeScreen**
+
+Add a `selectedNode` state and show the inspector as a side panel when a node is selected. In `home_screen.dart`, wrap the graph in a `Row` with a conditional `PropertyInspector` on the right.
+
+Add state:
+```dart
+GraphNode? _selectedNode;
+```
+
+Update the body to:
+```dart
+Expanded(
+ child: Row(
+ children: [
+ Expanded(child: /* existing graph canvas with onNodeSelected */),
+ if (_selectedNode != null)
+ PropertyInspector(
+ node: _selectedNode!,
+ onClose: () => setState(() => _selectedNode = null),
+ ),
+ ],
+ ),
+),
+```
+
+Pass `onNodeSelected: (node) => setState(() => _selectedNode = node)` to `GraphCanvas`.
+
+**Step 3: Verify it works**
+
+```bash
+flutter run -d chrome
+```
+
+Expected: clicking a node opens the property panel on the right. Clicking X closes it.
+
+**Step 4: Commit**
+
+```bash
+git add lib/features/inspector/ lib/features/home_screen.dart
+git commit -m "feat: add property inspector panel for selected nodes"
+```
+
+---
+
+## Phase 4: Load + Validate (make it useful)
+
+### Task 9: File picker to load ontology via engine
+
+**Files:**
+- Create: `lib/features/toolbar.dart`
+- Modify: `lib/features/home_screen.dart`
+- Add dependency: `file_picker` to `pubspec.yaml`
+
+**Step 1: Add file_picker dependency**
+
+```yaml
+# Add to pubspec.yaml dependencies
+file_picker: ^8.0.0
+```
+
+```bash
+flutter pub get
+```
+
+**Step 2: Create toolbar**
+
+```dart
+// lib/features/toolbar.dart
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:file_picker/file_picker.dart';
+import 'dart:io';
+import '../services/providers.dart';
+
+class Toolbar extends ConsumerWidget {
+ const Toolbar({super.key});
+
+ @override
+ Widget build(BuildContext context, WidgetRef ref) {
+ return Container(
+ height: 40,
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ color: const Color(0xFF2D2D3F),
+ child: Row(
+ children: [
+ const Text(
+ 'Open Ontologies Studio',
+ style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
+ ),
+ const SizedBox(width: 16),
+ _toolbarButton(
+ icon: Icons.folder_open,
+ label: 'Load',
+ onPressed: () => _loadOntology(context, ref),
+ ),
+ _toolbarButton(
+ icon: Icons.save,
+ label: 'Save',
+ onPressed: () => _saveOntology(context, ref),
+ ),
+ _toolbarButton(
+ icon: Icons.delete_outline,
+ label: 'Clear',
+ onPressed: () => _clearStore(context, ref),
+ ),
+ const Spacer(),
+ _toolbarButton(
+ icon: Icons.refresh,
+ label: 'Refresh',
+ onPressed: () {
+ ref.invalidate(graphNodesProvider);
+ ref.invalidate(graphEdgesProvider);
+ ref.invalidate(statsProvider);
+ },
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _toolbarButton({
+ required IconData icon,
+ required String label,
+ required VoidCallback onPressed,
+ }) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: TextButton.icon(
+ icon: Icon(icon, size: 14),
+ label: Text(label, style: const TextStyle(fontSize: 12)),
+ onPressed: onPressed,
+ style: TextButton.styleFrom(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ minimumSize: const Size(0, 30),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _loadOntology(BuildContext context, WidgetRef ref) async {
+ final result = await FilePicker.platform.pickFiles(
+ type: FileType.custom,
+ allowedExtensions: ['ttl', 'owl', 'rdf', 'nt', 'nq', 'trig'],
+ );
+ if (result == null) return;
+
+ final file = File(result.files.single.path!);
+ final content = await file.readAsString();
+
+ final client = ref.read(engineClientProvider);
+ try {
+ // Validate first
+ await client.callTool('onto_validate', {'turtle': content});
+ // Clear and load
+ await client.callTool('onto_clear', {});
+ await client.callTool('onto_load', {'turtle': content});
+ // Refresh
+ ref.invalidate(graphNodesProvider);
+ ref.invalidate(graphEdgesProvider);
+ ref.invalidate(statsProvider);
+ } catch (e) {
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red),
+ );
+ }
+ }
+ }
+
+ Future<void> _saveOntology(BuildContext context, WidgetRef ref) async {
+ final client = ref.read(engineClientProvider);
+ try {
+ final result = await client.callTool('onto_save', {'format': 'turtle'});
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Saved: ${result['path'] ?? 'ok'}')),
+ );
+ }
+ } catch (e) {
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Error: $e'), backgroundColor: Colors.red),
+ );
+ }
+ }
+ }
+
+ Future<void> _clearStore(BuildContext context, WidgetRef ref) async {
+ final client = ref.read(engineClientProvider);
+ await client.callTool('onto_clear', {});
+ ref.invalidate(graphNodesProvider);
+ ref.invalidate(graphEdgesProvider);
+ ref.invalidate(statsProvider);
+ }
+}
+```
+
+**Step 3: Add Toolbar to HomeScreen**
+
+In `home_screen.dart`, add `const Toolbar()` as the first child in the `Column`, above the `Expanded` graph area.
+
+**Step 4: Verify**
+
+```bash
+flutter run -d chrome
+```
+
+Expected: toolbar with Load, Save, Clear, Refresh buttons. Load opens file picker, loads a .ttl file, graph renders.
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/toolbar.dart lib/features/home_screen.dart pubspec.yaml
+git commit -m "feat: add toolbar with load, save, clear, refresh actions"
+```
+
+---
+
+### Task 10: Validation panel
+
+**Files:**
+- Create: `lib/features/validation/validation_panel.dart`
+- Create: `lib/services/providers.dart` (add lint provider)
+
+**Step 1: Add lint provider to providers.dart**
+
+```dart
+/// Lint results from the engine.
+final lintProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
+ final client = ref.watch(engineClientProvider);
+ try {
+ final result = await client.callTool('onto_lint', {});
+ return (result['issues'] as List?)?.cast<Map<String, dynamic>>() ?? [];
+ } catch (_) {
+ return [];
+ }
+});
+```
+
+**Step 2: Create validation panel**
+
+```dart
+// lib/features/validation/validation_panel.dart
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../../services/providers.dart';
+
+class ValidationPanel extends ConsumerWidget {
+ const ValidationPanel({super.key});
+
+ @override
+ Widget build(BuildContext context, WidgetRef ref) {
+ final lintAsync = ref.watch(lintProvider);
+
+ return Container(
+ height: 200,
+ color: const Color(0xFF252535),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ color: const Color(0xFF2D2D3F),
+ child: Row(
+ children: [
+ const Icon(Icons.checklist, size: 14),
+ const SizedBox(width: 6),
+ const Text('Validation', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
+ const Spacer(),
+ lintAsync.when(
+ data: (issues) => Text(
+ '${issues.length} issue${issues.length == 1 ? '' : 's'}',
+ style: TextStyle(
+ fontSize: 11,
+ color: issues.isEmpty ? Colors.green : Colors.orange,
+ ),
+ ),
+ loading: () => const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 1)),
+ error: (_, __) => const Text('error', style: TextStyle(fontSize: 11, color: Colors.red)),
+ ),
+ ],
+ ),
+ ),
+ Expanded(
+ child: lintAsync.when(
+ data: (issues) => issues.isEmpty
+ ? const Center(child: Text('No issues', style: TextStyle(color: Colors.grey, fontSize: 12)))
+ : ListView.builder(
+ itemCount: issues.length,
+ itemBuilder: (context, index) {
+ final issue = issues[index];
+ final severity = issue['severity'] as String? ?? 'warning';
+ return ListTile(
+ dense: true,
+ leading: Icon(
+ severity == 'error' ? Icons.error : Icons.warning,
+ color: severity == 'error' ? Colors.red : Colors.orange,
+ size: 16,
+ ),
+ title: Text(
+ issue['message'] as String? ?? '',
+ style: const TextStyle(fontSize: 12),
+ ),
+ subtitle: Text(
+ issue['iri'] as String? ?? '',
+ style: const TextStyle(fontSize: 10, color: Colors.grey),
+ ),
+ );
+ },
+ ),
+ loading: () => const Center(child: CircularProgressIndicator()),
+ error: (e, _) => Center(child: Text('$e')),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+```
+
+**Step 3: Add to HomeScreen**
+
+Add `const ValidationPanel()` below the graph `Expanded` and above the status bar, wrapped in a visibility toggle.
+
+**Step 4: Commit**
+
+```bash
+git add lib/features/validation/ lib/services/providers.dart lib/features/home_screen.dart
+git commit -m "feat: add validation panel showing lint issues"
+```
+
+---
+
+## Phase 5: Editing (make it interactive)
+
+### Task 11: Add class via right-click context menu on canvas
+
+**Files:**
+- Modify: `lib/features/graph/graph_canvas.dart`
+- Modify: `lib/services/engine_client.dart` (add insert triple method)
+
+This task adds a right-click context menu on the canvas background that lets users create a new class. The new class is added to the triple store via `onto_load` (loading a small Turtle snippet), then the graph refreshes.
+
+**Step 1:** Add a `secondaryTapUp` handler to `GraphCanvas` that shows a `PopupMenuButton`-style overlay.
+
+**Step 2:** Menu options: "Add Class", "Add Individual". Selecting "Add Class" opens a dialog asking for class IRI and label.
+
+**Step 3:** On submit, build Turtle: `<iri> a owl:Class ; rdfs:label "label" .` and call `onto_load`.
+
+**Step 4:** Refresh providers to update the graph.
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/graph/ lib/services/
+git commit -m "feat: add right-click context menu to create classes on canvas"
+```
+
+---
+
+### Task 12: Drag-to-connect (create subClassOf relationships)
+
+**Files:**
+- Modify: `lib/features/graph/graph_canvas.dart`
+
+Add a mode where dragging from one node to another creates a `rdfs:subClassOf` triple. Visual feedback: dotted line follows the cursor during drag. On release over a target node, generate Turtle and call `onto_load`.
+
+**Step 1:** Add drag-from-node state (source node, dragging flag).
+
+**Step 2:** On drag start over a node with Shift held, enter connection mode.
+
+**Step 3:** Paint a dotted line from source to cursor position.
+
+**Step 4:** On release over a target node, call `onto_load` with `<source> rdfs:subClassOf <target> .`
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/graph/
+git commit -m "feat: add shift-drag to create subClassOf edges between nodes"
+```
+
+---
+
+## Phase 6: Command Palette + SPARQL
+
+### Task 13: Command palette (Cmd+K)
+
+**Files:**
+- Create: `lib/features/command_palette/command_palette.dart`
+- Modify: `lib/features/home_screen.dart` (keyboard shortcut)
+
+**Step 1:** Create a `CommandPalette` overlay widget — a search field at top of screen with a list of matching commands below.
+
+**Step 2:** Commands list: "Load ontology", "Save ontology", "Clear store", "Run SPARQL", "Export Turtle", "Refresh graph".
+
+**Step 3:** Filter commands as user types. Enter selects. Escape closes.
+
+**Step 4:** Register `Cmd+K` / `Ctrl+K` keyboard shortcut in HomeScreen using `Shortcuts` and `Actions` widgets.
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/command_palette/ lib/features/home_screen.dart
+git commit -m "feat: add Cmd+K command palette"
+```
+
+---
+
+### Task 14: SPARQL editor panel
+
+**Files:**
+- Create: `lib/features/sparql/sparql_editor.dart`
+
+**Step 1:** Create a panel with a multi-line text field for SPARQL input and a results table below.
+
+**Step 2:** "Run" button calls `onto_query` with the SPARQL text.
+
+**Step 3:** Parse the JSON results into a `DataTable`.
+
+**Step 4:** Add a keyboard shortcut `Cmd+Enter` to run the query.
+
+**Step 5: Commit**
+
+```bash
+git add lib/features/sparql/
+git commit -m "feat: add SPARQL editor panel with query execution"
+```
+
+---
+
+## Phase 7: Lineage + Version History
+
+### Task 15: Lineage timeline panel
+
+**Files:**
+- Create: `lib/features/lineage/lineage_panel.dart`
+- Add provider for `onto_history`
+
+**Step 1:** Add `historyProvider` that calls `onto_history` and returns a list of version snapshots.
+
+**Step 2:** Render as a vertical timeline with version name, timestamp, and source (claude/human).
+
+**Step 3:** Each entry has [Load] and [Diff] buttons. Load calls `onto_rollback`, Diff calls `onto_diff`.
+
+**Step 4: Commit**
+
+```bash
+git add lib/features/lineage/
+git commit -m "feat: add lineage timeline with version history"
+```
+
+---
+
+## Phase 8: CI + Packaging
+
+### Task 16: GitHub Actions CI workflow
+
+**Files:**
+- Create: `.github/workflows/ci.yml`
+
+**Step 1:** Create workflow that runs on push/PR:
+- `flutter analyze`
+- `flutter test`
+- Build for web (`flutter build web`)
+
+**Step 2: Commit**
+
+```bash
+git add .github/
+git commit -m "ci: add Flutter CI workflow for analyze, test, web build"
+```
+
+---
+
+### Task 17: GitHub Actions release workflow for desktop builds
+
+**Files:**
+- Create: `.github/workflows/release.yml`
+
+**Step 1:** Create workflow triggered on tags (`v*`):
+- Matrix build: macOS, Windows, Linux
+- `flutter build macos` / `flutter build windows` / `flutter build linux`
+- Package as `.dmg` / `.msix` / `.AppImage`
+- Upload to GitHub Release
+
+**Step 2: Commit**
+
+```bash
+git add .github/
+git commit -m "ci: add release workflow for macOS, Windows, Linux desktop builds"
+```
+
+---
+
+## Phase 9: Polish
+
+### Task 18: Dark theme + visual polish
+
+Refine colors, spacing, typography. Node colors per type, edge styles per predicate, hover effects, smooth transitions.
+
+### Task 19: LOD rendering (level-of-detail)
+
+When zoom is far out and >500 nodes visible, collapse into clusters. Show labels only when zoomed in enough.
+
+### Task 20: Add README and documentation
+
+Create README.md with screenshots, install instructions, and architecture overview.
+
+---
+
+## Execution Order Summary
+
+| Phase | Tasks | What you get |
+|---|---|---|
+| 1. Scaffold | 1-4 | Flutter project, models, engine client, providers |
+| 2. Graph Canvas | 5-6 | Visual graph with pan/zoom/drag, force layout |
+| 3. UI Shell | 7-8 | Main screen, property inspector |
+| 4. Load + Validate | 9-10 | File picker, validation panel |
+| 5. Editing | 11-12 | Add classes, create relationships on canvas |
+| 6. Cmd Palette + SPARQL | 13-14 | Keyboard shortcuts, query editor |
+| 7. Lineage | 15 | Version history and rollback |
+| 8. CI | 16-17 | Automated testing and desktop packaging |
+| 9. Polish | 18-20 | Visual refinement, LOD, docs |
+
+**After Phase 3 (Task 8) you have a working visual ontology viewer.**
+**After Phase 5 (Task 12) you have a working visual ontology editor.**