Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat(studio): add corpus ingest, store and decision-ledger commands
FABIOTESSc981ba74da65
diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lockindex 44ed02fe..48dff6e5 100644--- a/studio/src-tauri/Cargo.lock+++ b/studio/src-tauri/Cargo.lock@@ -47,6 +47,28 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "ashpd"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"+dependencies = [+ "async-fs",+ "async-net",+ "enumflags2",+ "futures-channel",+ "futures-util",+ "rand 0.9.5",+ "raw-window-handle",+ "serde",+ "serde_repr",+ "url",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "zbus",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -85,6 +107,17 @@ dependencies = ["slab",]+[[package]]+name = "async-fs"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"+dependencies = [+ "async-lock",+ "blocking",+ "futures-lite",+]+[[package]]name = "async-io"version = "2.6.0"@@ -114,6 +147,17 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-net"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"+dependencies = [+ "async-io",+ "blocking",+ "futures-lite",+]+[[package]]name = "async-process"version = "2.5.0"@@ -766,6 +810,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]+[[package]]name = "dlopen2"version = "0.8.2"@@ -804,6 +857,12 @@ dependencies = ["tendril",]+[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]name = "dpi"version = "0.1.2"@@ -2421,6 +2480,7 @@ name = "open-ontologies-studio"version = "0.1.0"dependencies = ["reqwest 0.12.28",+ "rfd","serde","serde_json","tauri",@@ -2779,7 +2839,7 @@ checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"dependencies = ["base64 0.22.1","indexmap 2.13.0",- "quick-xml",+ "quick-xml 0.38.4","serde","time",]@@ -2811,6 +2871,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"+[[package]]name = "potential_utf"version = "0.1.4"@@ -2928,6 +2994,15 @@ dependencies = ["memchr",]+[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]+[[package]]name = "quote"version = "1.0.45"@@ -2974,6 +3049,16 @@ dependencies = ["rand_core 0.6.4",]+[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha 0.9.0",+ "rand_core 0.9.5",+]+[[package]]name = "rand_chacha"version = "0.2.2"@@ -2994,6 +3079,16 @@ dependencies = ["rand_core 0.6.4",]+[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]+[[package]]name = "rand_core"version = "0.5.1"@@ -3012,6 +3107,15 @@ dependencies = ["getrandom 0.2.17",]+[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]+[[package]]name = "rand_hc"version = "0.2.0"@@ -3179,6 +3283,30 @@ dependencies = ["web-sys",]+[[package]]+name = "rfd"+version = "0.15.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed"+dependencies = [+ "ashpd",+ "block2",+ "dispatch2",+ "js-sys",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "pollster",+ "raw-window-handle",+ "urlencoding",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows-sys 0.59.0",+]+[[package]]name = "ring"version = "0.17.14"@@ -3335,6 +3463,12 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"+[[package]]name = "scopeguard"version = "1.2.0"@@ -4629,6 +4763,12 @@ dependencies = ["serde_derive",]+[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]name = "urlpattern"version = "0.3.0"@@ -4858,6 +4998,66 @@ dependencies = ["semver",]+[[package]]+name = "wayland-backend"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"+dependencies = [+ "cc",+ "downcast-rs",+ "rustix",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"+dependencies = [+ "bitflags 2.11.0",+ "rustix",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols"+version = "0.32.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"+dependencies = [+ "bitflags 2.11.0",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"+dependencies = [+ "proc-macro2",+ "quick-xml 0.41.0",+ "quote",+]++[[package]]+name = "wayland-sys"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"+dependencies = [+ "dlib",+ "log",+ "pkg-config",+]+[[package]]name = "web-sys"version = "0.3.91"@@ -5771,6 +5971,7 @@ dependencies = ["endi","enumflags2","serde",+ "url","winnow 0.7.15","zvariant_derive","zvariant_utils",diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.tomlindex d51760b7..c34409c7 100644--- a/studio/src-tauri/Cargo.toml+++ b/studio/src-tauri/Cargo.toml@@ -23,6 +23,7 @@ tauri-plugin-opener = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"reqwest = { version = "0.12", features = ["json"] }+rfd = "0.15"[dev-dependencies]tempfile = "3"diff --git a/studio/src-tauri/src/corpus.rs b/studio/src-tauri/src/corpus.rsnew file mode 100644index 00000000..971ae41c--- /dev/null+++ b/studio/src-tauri/src/corpus.rs@@ -0,0 +1,343 @@+//! Corpus ingestion: read a folder of documents, build the knowledge graph.+//!+//! Wraps `demo/corpus_pipeline.py` and streams its output to the UI as+//! `corpus-progress` events, so the five stages (read, extract, verify, load,+//! scan) appear live rather than as a spinner.+//!+//! The pipeline is deliberately a separate process: it talks to the same+//! engine over MCP that Studio does, so what the UI shows afterwards is the+//! real merged store, not a private copy.++use std::io::{BufRead, BufReader};+use std::path::PathBuf;+use std::process::{Command, Stdio};+use std::sync::{Arc, Mutex};+use tauri::{Emitter, Manager};++pub struct CorpusState {+ /// Arc so the flag can be cleared from the reader thread without holding+ /// a borrow of the AppHandle across statements.+ pub running: Arc<Mutex<bool>>,+}++/// Pick a Python interpreter that actually exists.+///+/// A Finder-launched app inherits a minimal PATH, and a bare "python3" then+/// resolves to the system interpreter rather than whichever one has the+/// pipeline's optional dependencies. Candidates are tried in order of+/// specificity so an explicit choice always wins.+fn resolve_python() -> String {+ if let Ok(explicit) = std::env::var("ONTO_PYTHON") {+ if !explicit.trim().is_empty() {+ return explicit;+ }+ }+ let root = repo_root();+ let candidates = [+ root.join(".venv/bin/python3"),+ root.join("venv/bin/python3"),+ PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("scratch/.venv/bin/python3"),+ ];+ for c in candidates {+ if c.exists() {+ return c.to_string_lossy().into_owned();+ }+ }+ "python3".into()+}++/// Single-quote a value for safe inclusion in a shell command.+fn shell_quote(value: &str) -> String {+ format!("'{}'", value.replace('\'', "'\\''"))+}++/// Repository root, derived from the crate location at compile time.+pub fn repo_root() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(|p| p.parent())+ .map(|p| p.to_path_buf())+ .unwrap_or_else(|| PathBuf::from("."))+}++/// Corpora offered in the UI. The third element is a document count and MUST+/// match what the corpus that populates `demo/corpus/dcat-us` actually+/// contains: it is not computed from disk here because that corpus does not+/// exist in this tree yet, only the pipeline that will read it does.+#[tauri::command]+pub fn corpus_presets() -> Vec<(String, String, usize)> {+ vec![(+ "dcat-us".to_string(),+ "DCAT-US 3.0 profile documents and the W3C DCAT conformance clause".to_string(),+ 6,+ )]+}++/// Run the pipeline over `folder`. When `live` is false the cached extraction+/// is reused, which makes the demo instant; when true it re-runs extraction+/// against the configured model endpoint.+#[tauri::command]+pub fn ingest_corpus(+ app: tauri::AppHandle,+ folder: String,+ live: bool,+) -> Result<(), String> {+ let running_flag = app.state::<CorpusState>().running.clone();+ {+ let mut running = running_flag.lock().map_err(|e| e.to_string())?;+ if *running {+ return Err("an ingestion is already running".into());+ }+ *running = true;+ }++ // Prefer the app's resource directory when `demo/` has actually been+ // bundled into it (today only the sidecar's `dist/` and its+ // `package.json` are, per `tauri.conf.json`); fall back to the+ // development checkout the same way `chat::resolve_sidecar_entry` does+ // for the agent sidecar. That keeps this consistent with the rest of the+ // crate rather than assuming the internal branch's directory layout, and+ // it starts working the moment `demo/` is added to `resources` without a+ // second code path to maintain.+ let root = app+ .path()+ .resource_dir()+ .ok()+ .filter(|dir| dir.join("demo").is_dir())+ .unwrap_or_else(repo_root);+ let script = root.join("demo").join("ontology_from_docs.py");+ if !script.exists() {+ *running_flag.lock().unwrap() = false;+ return Err(format!("pipeline not found at {}", script.display()));+ }++ // An app launched from Finder inherits a minimal PATH, so a bare "python3"+ // resolves to /usr/bin/python3 rather than whichever interpreter actually+ // has the pipeline's dependencies installed. Run through a LOGIN shell so+ // the user's real PATH applies, and let ONTO_PYTHON override outright.+ let python = resolve_python();+ let cached = if live { "" } else { "--cached" };+ let command = format!(+ "{} {} {} --corpus {}",+ shell_quote(&python),+ shell_quote(&script.to_string_lossy()),+ cached,+ shell_quote(&folder),+ );++ let mut child = Command::new("/bin/zsh")+ .arg("-lc")+ .arg(&command)+ .current_dir(&root)+ // Strip ANSI colour: the pane renders plain text.+ .env("NO_COLOR", "1")+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("failed to start pipeline: {e}"))?;++ let stdout = child.stdout.take().ok_or("no stdout")?;+ let stderr = child.stderr.take().ok_or("no stderr")?;++ // stderr MUST be drained. Leaving it piped and unread can block the child+ // once the pipe buffer fills, and it is where the actual error message+ // lives: without this the UI can only report "finished with errors".+ let err_handle = app.clone();+ std::thread::spawn(move || {+ for line in BufReader::new(stderr).lines().map_while(Result::ok) {+ let _ = err_handle.emit("corpus-progress", format!("stderr: {line}"));+ }+ });++ let handle = app.clone();+ let running_flag = running_flag.clone();+ let normalise_root = root.clone();+ std::thread::spawn(move || {+ for line in BufReader::new(stdout).lines().map_while(Result::ok) {+ let _ = handle.emit("corpus-progress", line);+ }+ let status = child.wait();+ let ok = status.map(|s| s.success()).unwrap_or(false);++ // Post-build normalisation, before anything loads the store.+ //+ // The pipeline REGENERATES _store.ttl on every build, which discards+ // anything appended to it. Access control is derived from the document+ // headers rather than produced by the extractor, so without this it+ // vanishes the moment the graph is rebuilt: the role switcher would+ // silently stop filtering, which is the worst possible failure because+ // it looks like it is working. Running it here ties the ACL triples to+ // the build that produced the store they annotate.+ if ok {+ for script in ["demo/acl_normalise.py", "demo/corpus_text.py"] {+ let path = normalise_root.join(script);+ if !path.exists() {+ continue;+ }+ let out = Command::new("/bin/zsh")+ .arg("-lc")+ .arg(format!(+ "{} {}",+ shell_quote(&resolve_python()),+ shell_quote(&path.to_string_lossy())+ ))+ .current_dir(&normalise_root)+ .output();+ match out {+ Ok(o) if o.status.success() => {+ if let Some(line) = String::from_utf8_lossy(&o.stdout).lines().next() {+ let _ = handle.emit("corpus-progress", line.to_string());+ }+ }+ Ok(o) => {+ let _ = handle.emit(+ "corpus-progress",+ format!("{script} failed: {}", String::from_utf8_lossy(&o.stderr)),+ );+ }+ Err(e) => {+ let _ = handle.emit("corpus-progress", format!("{script} failed: {e}"));+ }+ }+ }+ }++ let _ = handle.emit("corpus-done", ok);+ if let Ok(mut running) = running_flag.lock() {+ *running = false;+ }+ });++ Ok(())+}++/// The store the last build produced, for the frontend to feed through the+/// plan -> enforce -> apply cycle in ITS OWN MCP session. Lineage is+/// session-scoped in the engine, so events recorded by the pipeline's session+/// are invisible to the Studio; the trail the Lineage panel shows must be+/// created by the session that reads it.+#[tauri::command]+pub fn read_store() -> Result<String, String> {+ let path = repo_root().join("demo/derived/_store.ttl");+ std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))+}++/// The per-document VOCABULARIES the last build wrote. Alignment operates on+/// class declarations, so instance graphs always produce zero candidates;+/// the fragments are where the duplicate concepts live.+#[tauri::command]+pub fn list_graphs() -> Vec<String> {+ let dir = repo_root().join("demo/derived");+ // The full derived vocabulary first: aligning it against the curated+ // store is the richest source of duplicate-concept candidates.+ let full = dir.join("_ontology.ttl");+ let mut head: Vec<String> = if full.exists() {+ vec![full.to_string_lossy().into_owned()]+ } else {+ Vec::new()+ };+ let mut out: Vec<String> = std::fs::read_dir(&dir)+ .map(|entries| {+ entries+ .filter_map(Result::ok)+ .map(|e| e.path())+ .filter(|p| {+ p.file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.ends_with(".vocab.ttl"))+ })+ .filter_map(|p| p.to_str().map(String::from))+ .collect()+ })+ .unwrap_or_default();+ out.sort();+ head.extend(out);+ head+}++/// The build's decision ledger: every automated resolution (typing, renames,+/// inversions, spam drops, review referrals) as JSONL, newest last.+#[tauri::command]+pub fn read_decisions() -> String {+ std::fs::read_to_string(repo_root().join("demo/derived/_decisions.jsonl")).unwrap_or_default()+}++/// Revert a typing decision: put `from` back in place of `to` on one subject+/// in one document graph. The ledger gets a revert entry rather than a+/// deletion, because an audit trail that forgets is not an audit trail.+#[tauri::command]+pub fn revert_type(doc: String, subject: String, from: String, to: String) -> Result<(), String> {+ let path = repo_root().join(format!("demo/derived/{doc}.data.ttl"));+ let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;++ let mut out: Vec<String> = Vec::new();+ let mut in_block = false;+ let mut done = false;+ for line in text.lines() {+ let mut l = line.to_string();+ if let Some(rest) = l.strip_prefix(&format!(":{subject}")) {+ let boundary = rest.chars().next().map_or(true, |c| !c.is_alphanumeric() && c != '_');+ if boundary {+ in_block = true;+ }+ } else if l.starts_with(':') {+ in_block = false;+ }+ if in_block && !done {+ let pat = format!("a :{to}");+ if l.contains(&pat) {+ l = l.replacen(&pat, &format!("a :{from}"), 1);+ done = true;+ }+ }+ out.push(l);+ }+ if !done {+ return Err(format!("no `a :{to}` under :{subject} in {doc}"));+ }+ std::fs::write(&path, out.join("\n")).map_err(|e| e.to_string())?;++ let ledger = repo_root().join("demo/derived/_decisions.jsonl");+ let entry = format!(+ "{{\"kind\": \"reverted\", \"doc\": \"{doc}\", \"subject\": \"{subject}\", \"from\": \"{to}\", \"to\": \"{from}\", \"how\": \"human revert in the resolution panel\"}}\n"+ );+ use std::io::Write;+ if let Ok(mut fh) = std::fs::OpenOptions::new().create(true).append(true).open(&ledger) {+ let _ = fh.write_all(entry.as_bytes());+ }+ Ok(())+}++/// Saved ontologies in ~/.open-ontologies, for the Open control: a save+/// without a load is a dead end.+#[tauri::command]+pub fn list_saved() -> Vec<String> {+ let dir = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default())+ .join(".open-ontologies");+ let mut out: Vec<String> = std::fs::read_dir(&dir)+ .map(|entries| {+ entries+ .filter_map(Result::ok)+ .map(|e| e.path())+ .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("ttl"))+ .filter_map(|p| p.file_stem().and_then(|n| n.to_str()).map(String::from))+ .collect()+ })+ .unwrap_or_default();+ out.sort();+ out+}++/// Native file picker for opening an ontology: starts in the folder where+/// saves land, but the whole disk is reachable. Returns the absolute path.+/// Sync command: Tauri runs it on the main thread, which macOS dialogs need.+#[tauri::command]+pub fn pick_ontology_file() -> Option<String> {+ let start = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default())+ .join(".open-ontologies");+ rfd::FileDialog::new()+ .add_filter("RDF / OWL", &["ttl", "nt", "rdf", "owl", "trig"])+ .set_directory(&start)+ .pick_file()+ .and_then(|p| p.to_str().map(String::from))+}diff --git a/studio/src-tauri/src/lib.rs b/studio/src-tauri/src/lib.rsindex 42d75915..7afd259d 100644--- a/studio/src-tauri/src/lib.rs+++ b/studio/src-tauri/src/lib.rs@@ -1,8 +1,10 @@mod chat;+mod corpus;mod engine;mod mcp;use chat::ChatState;+use corpus::CorpusState;use engine::EngineState;use mcp::McpState;use std::sync::atomic::{AtomicBool, Ordering};@@ -29,6 +31,9 @@ pub fn run() {session_id: Mutex::new(None),client: reqwest::Client::new(),})+ .manage(CorpusState {+ running: Arc::new(Mutex::new(false)),+ }).setup(|app| {let handle = app.handle().clone();if let Err(e) = engine::spawn_engine(&handle) {@@ -54,7 +59,15 @@ pub fn run() {mcp::mcp_call,mcp::set_mcp_session,chat::send_chat_message,- chat::reset_chat+ chat::reset_chat,+ corpus::corpus_presets,+ corpus::ingest_corpus,+ corpus::read_store,+ corpus::list_graphs,+ corpus::read_decisions,+ corpus::revert_type,+ corpus::list_saved,+ corpus::pick_ontology_file]).build(tauri::generate_context!()).expect("error while building tauri application")