Skip to content

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

Add Windows native build support

Jioh Jung84572e4edfa2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b6341e1e..5a949ada 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -7,7 +7,10 @@ on:
jobs:
build:
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest]
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
CARGO_INCREMENTAL: 0
@@ -15,6 +18,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Free disk space
+ if: runner.os == 'Linux'
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /usr/local/share/powershell /usr/local/share/chromium /usr/local/share/edge
sudo apt-get clean
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fcd8e148..8c4868df 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -10,10 +10,16 @@ jobs:
include:
- os: ubuntu-22.04
target: x86_64-unknown-linux-musl
+ artifact_name: open-ontologies
- os: macos-latest
target: aarch64-apple-darwin
+ artifact_name: open-ontologies
- os: macos-14
target: x86_64-apple-darwin
+ artifact_name: open-ontologies
+ - os: windows-latest
+ target: x86_64-pc-windows-msvc
+ artifact_name: open-ontologies.exe
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
@@ -29,7 +35,7 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: open-ontologies-${{ matrix.target }}
- path: target/${{ matrix.target }}/release/open-ontologies
+ path: target/${{ matrix.target }}/release/${{ matrix.artifact_name }}
release:
needs: build
@@ -43,7 +49,11 @@ jobs:
for dir in open-ontologies-*/; do
target="${dir%/}"
target="${target#open-ontologies-}"
- mv "${dir}open-ontologies" "${dir}open-ontologies-${target}"
+ if [ -f "${dir}open-ontologies.exe" ]; then
+ mv "${dir}open-ontologies.exe" "${dir}open-ontologies-${target}.exe"
+ else
+ mv "${dir}open-ontologies" "${dir}open-ontologies-${target}"
+ fi
done
- name: Create release
uses: softprops/action-gh-release@v2
diff --git a/README.md b/README.md
index 48dadcd3..3dd4c546 100644
--- a/README.md
+++ b/README.md
@@ -114,6 +114,8 @@ cd open-ontologies && cargo build --release
./target/release/open-ontologies init
```
+For native Windows builds, see [docs/windows.md](docs/windows.md).
+
### Connect to your MCP client
<details>
diff --git a/docs/windows.md b/docs/windows.md
new file mode 100644
index 00000000..a97f5b0c
--- /dev/null
+++ b/docs/windows.md
@@ -0,0 +1,115 @@
+# Building on Windows
+
+This repository can be built on native Windows with the MSVC Rust toolchain. The steps below are the reference setup for building both the Rust engine and the Tauri Studio application without WSL.
+
+## Supported setup
+
+- Windows 10 or Windows 11, x64
+- Rust stable with the `x86_64-pc-windows-msvc` target
+- Visual Studio 2022 Build Tools
+- Windows 11 SDK `10.0.22621.0` or newer
+- LLVM for `libclang.dll`
+- Node.js 20+ with `npm.cmd`
+
+## Required Windows components
+
+Install Visual Studio 2022 Build Tools with these components:
+
+- `Microsoft.VisualStudio.Workload.VCTools`
+- `Microsoft.VisualStudio.Component.VC.Tools.x86.x64`
+- `Microsoft.VisualStudio.Component.Windows11SDK.22621`
+- `Microsoft.VisualStudio.Component.VC.CoreBuildTools`
+
+Install LLVM so that `libclang.dll` is available, for example under `C:\Program Files\LLVM\bin\libclang.dll`.
+
+## Why the environment matters
+
+The Rust build depends on two pieces of native Windows tooling:
+
+- MSVC and the Windows SDK, which provide `cl.exe`, `link.exe`, and system libraries such as `kernel32.lib`
+- LLVM, which provides `libclang.dll` for crates that use `bindgen`
+
+If those tools are installed but not active in the current shell, Cargo may fail with errors such as:
+
+- `link.exe not found`
+- `kernel32.lib` not found
+- `Unable to find libclang`
+
+## Build the Rust engine
+
+Open `cmd.exe` or PowerShell and run the build from a Visual Studio developer environment.
+
+```cmd
+call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
+set "LIBCLANG_PATH=C:\Program Files\LLVM\bin"
+%USERPROFILE%\.cargo\bin\cargo.exe build --release --bin open-ontologies
+```
+
+Expected output:
+
+- `target\release\open-ontologies.exe`
+
+## Build the Studio frontend
+
+Use the real Node.js installation, not the Windows app execution alias. On some systems `node.exe` may resolve to a packaged app path under `WindowsApps`, while `npm` is missing from `PATH`. If that happens, prepend `C:\Program Files\nodejs` to `PATH` before running `npm.cmd`.
+
+```cmd
+set "PATH=C:\Program Files\nodejs;%PATH%"
+cd studio
+npm.cmd install
+npm.cmd run build
+```
+
+The build step also runs `npm run prepare-engine`, which copies:
+
+- `target\release\open-ontologies.exe`
+
+to:
+
+- `studio\src-tauri\binaries\open-ontologies-x86_64-pc-windows-msvc.exe`
+
+## Build the full Tauri desktop app
+
+From the same shell, with MSVC and LLVM already configured:
+
+```cmd
+call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
+set "LIBCLANG_PATH=C:\Program Files\LLVM\bin"
+set "PATH=C:\Program Files\nodejs;%USERPROFILE%\.cargo\bin;%PATH%"
+cd studio
+npm.cmd run tauri build
+```
+
+Expected outputs:
+
+- `studio\src-tauri\target\release\open-ontologies-studio.exe`
+- `studio\src-tauri\target\release\bundle\msi\open-ontologies-studio_0.1.0_x64_en-US.msi`
+- `studio\src-tauri\target\release\bundle\nsis\open-ontologies-studio_0.1.0_x64-setup.exe`
+
+## Runtime notes
+
+- `serve-unix` is intentionally unavailable on Windows. Use `serve` or `serve-http` instead.
+- `~` path expansion uses `%USERPROFILE%` on Windows.
+- The Studio backend no longer depends on `sh`, `lsof`, or Homebrew-specific paths when running on Windows.
+
+## Troubleshooting
+
+### `link.exe` or `kernel32.lib` not found
+
+The Visual Studio Build Tools installation is incomplete, or `vcvars64.bat` was not called in the current shell.
+
+### `Unable to find libclang`
+
+LLVM is not installed, or `LIBCLANG_PATH` does not point to the directory containing `libclang.dll`.
+
+### `npm` is not recognized
+
+Install Node.js from the standard Windows installer and ensure `C:\Program Files\nodejs` is on `PATH`. If a `WindowsApps` alias shadows Node, explicitly prepend the Node.js installation directory before running `npm.cmd`.
+
+### `prepare-engine` says the engine binary does not exist
+
+Build the engine first with:
+
+```cmd
+%USERPROFILE%\.cargo\bin\cargo.exe build --release --bin open-ontologies
+```
diff --git a/src/config.rs b/src/config.rs
index 4490d415..74ada7f7 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -21,7 +21,6 @@ pub struct Config {
pub logging: LoggingConfig,
}
-
impl Config {
pub fn load(path: &Path) -> Result<Self> {
let contents = std::fs::read_to_string(path)
@@ -76,7 +75,11 @@ pub fn resolve_ontology_dirs(cfg: &[String]) -> Vec<std::path::PathBuf> {
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
- _ => cfg.iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
+ _ => cfg
+ .iter()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect(),
};
let mut seen = std::collections::HashSet::new();
let mut out = Vec::with_capacity(raw.len());
@@ -251,10 +254,12 @@ pub struct ToolsConfig {
/// Expand a leading `~` in a path to the user's home directory.
pub fn expand_tilde(path: &str) -> String {
- if (path.starts_with("~/") || path == "~")
- && let Some(home) = std::env::var_os("HOME") {
+ if path.starts_with("~/") || path == "~" {
+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
+ if let Some(home) = home {
return path.replacen("~", &home.to_string_lossy(), 1);
}
+ }
path.to_string()
}
@@ -269,7 +274,11 @@ pub struct WebhookConfig {
pub request_timeout_secs: u64,
}
impl Default for WebhookConfig {
- fn default() -> Self { Self { request_timeout_secs: 10 } }
+ fn default() -> Self {
+ Self {
+ request_timeout_secs: 10,
+ }
+ }
}
/// `[http]` — Streamable HTTP transport (`serve-http`).
@@ -320,7 +329,12 @@ pub struct MonitorConfig {
pub interval_secs: u64,
}
impl Default for MonitorConfig {
- fn default() -> Self { Self { enabled: false, interval_secs: 30 } }
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ interval_secs: 30,
+ }
+ }
}
/// `[reasoner]` — RDFS / OWL-RL fixpoint and DL tableaux limits.
@@ -340,7 +354,11 @@ pub struct ReasonerConfig {
}
impl Default for ReasonerConfig {
fn default() -> Self {
- Self { tableaux_max_depth: 100, tableaux_max_nodes: 10_000, max_iterations: 64 }
+ Self {
+ tableaux_max_depth: 100,
+ tableaux_max_nodes: 10_000,
+ max_iterations: 64,
+ }
}
}
@@ -357,7 +375,12 @@ pub struct FeedbackConfig {
pub downgrade_threshold: i64,
}
impl Default for FeedbackConfig {
- fn default() -> Self { Self { suppress_threshold: 3, downgrade_threshold: 2 } }
+ fn default() -> Self {
+ Self {
+ suppress_threshold: 3,
+ downgrade_threshold: 2,
+ }
+ }
}
/// `[imports]` — `owl:imports` resolution policy.
@@ -379,7 +402,11 @@ pub struct ImportsConfig {
}
impl Default for ImportsConfig {
fn default() -> Self {
- Self { max_depth: 3, request_timeout_secs: 30, follow_remote: true }
+ Self {
+ max_depth: 3,
+ request_timeout_secs: 30,
+ follow_remote: true,
+ }
}
}
@@ -392,7 +419,11 @@ pub struct RepoConfig {
pub default_list_limit: usize,
}
impl Default for RepoConfig {
- fn default() -> Self { Self { default_list_limit: 1000 } }
+ fn default() -> Self {
+ Self {
+ default_list_limit: 1000,
+ }
+ }
}
/// `[socket]` — Unix domain socket adapter for Tardygrada fact grounding.
@@ -425,7 +456,11 @@ pub struct LoggingConfig {
}
impl Default for LoggingConfig {
fn default() -> Self {
- Self { level: "info".into(), format: "compact".into(), file: None }
+ Self {
+ level: "info".into(),
+ format: "compact".into(),
+ file: None,
+ }
}
}
@@ -448,8 +483,7 @@ pub fn resolve_imports_timeout_secs(cfg: &ImportsConfig) -> u64 {
/// Resolve the monitor sweep interval. Precedence:
/// `OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS` > config > default.
pub fn resolve_monitor_interval_secs(cfg: &MonitorConfig) -> u64 {
- parse_env_u64("OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS")
- .unwrap_or(cfg.interval_secs)
+ parse_env_u64("OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS").unwrap_or(cfg.interval_secs)
}
/// Resolve the HTTP bind host. Precedence:
@@ -677,7 +711,9 @@ mod tests {
}
}
- let webhook = WebhookConfig { request_timeout_secs: 7 };
+ let webhook = WebhookConfig {
+ request_timeout_secs: 7,
+ };
assert_eq!(resolve_webhook_timeout_secs(&webhook), 7);
let imports = ImportsConfig {
@@ -687,7 +723,10 @@ mod tests {
};
assert_eq!(resolve_imports_timeout_secs(&imports), 42);
- let monitor = MonitorConfig { enabled: true, interval_secs: 11 };
+ let monitor = MonitorConfig {
+ enabled: true,
+ interval_secs: 11,
+ };
assert_eq!(resolve_monitor_interval_secs(&monitor), 11);
}
diff --git a/src/lib.rs b/src/lib.rs
index 3adaf941..7668a484 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,67 +1,71 @@
-pub mod batch;
-pub mod cache;
-pub mod error;
pub mod align;
-pub mod config;
-pub mod clinical;
pub mod align_fuzzy;
+pub mod batch;
pub mod borderline_loop;
+pub mod cache;
pub mod civex;
+#[cfg(feature = "causal-pywhy")]
+pub mod civex_pywhy;
pub mod classify_el;
+pub mod clinical;
pub mod coevolve;
+pub mod config;
pub mod cq;
+pub mod drift;
+pub mod dynamics;
+pub mod dynamics_bcplus;
+pub mod error;
pub mod eval_alignment;
pub mod eval_rag;
-pub mod flora_pipeline;
pub mod extract_scaffold;
+pub mod flora_pipeline;
pub mod policy;
-pub mod shape_combinatorics;
-#[cfg(feature = "causal-pywhy")]
-pub mod civex_pywhy;
-pub mod drift;
-pub mod dynamics;
-pub mod dynamics_bcplus;
pub mod projection_check;
+pub mod shape_combinatorics;
// (re-exports keep the alphabetical ordering of the surrounding modules manageable)
+#[cfg(feature = "embeddings")]
+pub mod embed;
+#[cfg(feature = "embeddings")]
+pub mod embed_remote;
pub mod enforce;
-pub mod kgcl;
pub mod feedback;
pub mod graph;
+#[cfg(feature = "embeddings")]
+pub mod hnsw_index;
pub mod ingest;
pub mod inputs;
+pub mod kgcl;
pub mod lineage;
+pub mod mapping;
+pub mod marketplace;
pub mod monitor;
+pub mod ontology;
pub mod plan;
pub mod plan_classical;
pub mod plan_pddl;
pub mod plan_validate;
-pub mod webhook;
-pub mod mapping;
-pub mod marketplace;
-pub mod ontology;
+#[cfg(feature = "embeddings")]
+pub mod poincare;
pub mod reason;
pub mod registry;
pub mod repo;
pub mod runtime;
-pub mod server;
-pub mod shacl;
-pub mod state;
pub mod schema;
pub mod segment_retrieve;
+pub mod server;
+pub mod shacl;
+#[cfg(unix)]
+pub mod socket;
+#[cfg(windows)]
+#[path = "socket_windows.rs"]
pub mod socket;
pub mod sql_sync;
pub mod sqlsource;
+pub mod state;
+#[cfg(feature = "embeddings")]
+pub mod structembed;
pub mod tableaux;
pub mod toolfilter;
#[cfg(feature = "embeddings")]
-pub mod poincare;
-#[cfg(feature = "embeddings")]
pub mod vecstore;
-#[cfg(feature = "embeddings")]
-pub mod hnsw_index;
-#[cfg(feature = "embeddings")]
-pub mod embed;
-#[cfg(feature = "embeddings")]
-pub mod embed_remote;
-#[cfg(feature = "embeddings")]
-pub mod structembed;
+pub mod webhook;
diff --git a/src/main.rs b/src/main.rs
index 4869ceed..1f0047cf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,7 +2,7 @@ use clap::{Parser, Subcommand};
use rmcp::ServiceExt;
use std::sync::Arc;
-use open_ontologies::config::{expand_tilde, Config};
+use open_ontologies::config::{Config, expand_tilde};
use open_ontologies::graph::GraphStore;
use open_ontologies::server::OpenOntologiesServer;
use open_ontologies::state::StateDb;
@@ -134,7 +134,10 @@ data_dir = "~/.open-ontologies"
"#;
#[derive(Parser)]
-#[command(name = "open-ontologies", about = "Terraform for Knowledge Graphs — AI-native ontology engine")]
+#[command(
+ name = "open-ontologies",
+ about = "Terraform for Knowledge Graphs — AI-native ontology engine"
+)]
struct Cli {
#[command(subcommand)]
command: Commands,
@@ -235,6 +238,7 @@ enum Commands {
},
/// Start unix socket server for Tardygrada fact grounding
+ #[cfg(unix)]
ServeUnix {
#[arg(long, default_value = "~/.open-ontologies/config.toml")]
config: String,
@@ -247,6 +251,16 @@ enum Commands {
#[arg(long = "file", num_args = 1..)]
files: Vec<String>,
},
+ /// Unix socket transport is not available on Windows.
+ #[cfg(windows)]
+ ServeUnix {
+ #[arg(long, default_value = "~/.open-ontologies/config.toml")]
+ config: String,
+ #[arg(long)]
+ socket: Option<String>,
+ #[arg(long = "file", num_args = 1..)]
+ files: Vec<String>,
+ },
// ─── Batch ────────────────────────────────────────────────────
/// Run a batch of commands from a file or stdin (one per line, or JSON array)
@@ -277,10 +291,7 @@ enum Commands {
/// Run SPARQL query (or stdin with -)
Query { query: String },
/// Compare two ontology files
- Diff {
- old_path: String,
- new_path: String,
- },
+ Diff { old_path: String, new_path: String },
/// Lint: check for missing labels, domains, ranges
Lint { input: String },
/// Convert between RDF formats
@@ -388,10 +399,7 @@ enum Commands {
reason: Option<String>,
},
/// Detect drift between two ontology versions
- Drift {
- file_a: String,
- file_b: String,
- },
+ Drift { file_a: String, file_b: String },
/// Run design pattern enforcement
Enforce {
#[arg(default_value = "generic")]
@@ -569,27 +577,23 @@ fn build_cache_config(
/// (when set) takes precedence over `level`. Idempotent: re-invocations are
/// harmless because `try_init` returns `Err` after the first install.
fn init_tracing(cfg: &open_ontologies::config::LoggingConfig) {
- use tracing_subscriber::{fmt, EnvFilter};
+ use tracing_subscriber::{EnvFilter, fmt};
let level = open_ontologies::config::resolve_logging_level(cfg);
- let env_filter = EnvFilter::try_new(&level)
- .unwrap_or_else(|_| EnvFilter::new("info"));
+ let env_filter = EnvFilter::try_new(&level).unwrap_or_else(|_| EnvFilter::new("info"));
// Output target: file when configured, else stderr (tracing default).
- let writer_file = cfg
- .file
- .as_deref()
- .and_then(|p| {
- let path = open_ontologies::config::expand_tilde(p);
- if let Some(parent) = std::path::Path::new(&path).parent() {
- let _ = std::fs::create_dir_all(parent);
- }
- std::fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(&path)
- .ok()
- });
+ let writer_file = cfg.file.as_deref().and_then(|p| {
+ let path = open_ontologies::config::expand_tilde(p);
+ if let Some(parent) = std::path::Path::new(&path).parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&path)
+ .ok()
+ });
let format = cfg.format.trim().to_lowercase();
// Build and install. Use `try_init` so calling this from multiple
@@ -643,11 +647,19 @@ fn build_tool_filter(
}
if let Some(spec) = cli_allow {
let (list, groups) = parse_csv(spec);
- return Ok(ToolFilter { mode: Mode::Allow, list, groups });
+ return Ok(ToolFilter {
+ mode: Mode::Allow,
+ list,
+ groups,
+ });
}
if let Some(spec) = cli_deny {
let (list, groups) = parse_csv(spec);
- return Ok(ToolFilter { mode: Mode::Deny, list, groups });
+ return Ok(ToolFilter {
+ mode: Mode::Deny,
+ list,
+ groups,
+ });
}
// Fall back to config file.
let mode = if cfg.tools.mode.is_empty() {
@@ -667,7 +679,12 @@ async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
match cli.command {
- Commands::Init { data_dir, model_url: _model_url, tokenizer_url: _tokenizer_url, model_name: _model_name } => {
+ Commands::Init {
+ data_dir,
+ model_url: _model_url,
+ tokenizer_url: _tokenizer_url,
+ model_name: _model_name,
+ } => {
let data_dir = expand_tilde(&data_dir);
let data_path = std::path::Path::new(&data_dir);
@@ -723,13 +740,16 @@ async fn main() -> anyhow::Result<()> {
} else {
std::fs::create_dir_all(&models_dir)?;
- let onnx_url = _model_url.as_deref()
+ let onnx_url = _model_url
+ .as_deref()
.or(cfg.model_url.as_deref())
.unwrap_or(open_ontologies::embed::BGE_SMALL_ONNX_URL);
- let tok_url = _tokenizer_url.as_deref()
+ let tok_url = _tokenizer_url
+ .as_deref()
.or(cfg.tokenizer_url.as_deref())
.unwrap_or(open_ontologies::embed::BGE_SMALL_TOKENIZER_URL);
- let onnx_filename = _model_name.as_deref()
+ let onnx_filename = _model_name
+ .as_deref()
.or(cfg.model_name.as_deref())
.unwrap_or("bge-small-en-v1.5.onnx");
@@ -738,10 +758,7 @@ async fn main() -> anyhow::Result<()> {
if !model_path.exists() {
println!("Downloading embedding model from {}...", onnx_url);
- open_ontologies::embed::download_model_file(
- onnx_url,
- &model_path,
- ).await?;
+ open_ontologies::embed::download_model_file(onnx_url, &model_path).await?;
println!(" Model saved: {}", model_path.display());
} else {
println!("Embedding model already exists: {}", model_path.display());
@@ -749,10 +766,8 @@ async fn main() -> anyhow::Result<()> {
if !tokenizer_path.exists() {
println!("Downloading tokenizer from {}...", tok_url);
- open_ontologies::embed::download_model_file(
- tok_url,
- &tokenizer_path,
- ).await?;
+ open_ontologies::embed::download_model_file(tok_url, &tokenizer_path)
+ .await?;
println!(" Tokenizer saved: {}", tokenizer_path.display());
} else {
println!("Tokenizer already exists: {}", tokenizer_path.display());
@@ -762,7 +777,16 @@ async fn main() -> anyhow::Result<()> {
println!("\nOpen Ontologies initialized successfully!");
}
- Commands::Serve { config: config_path, governance_webhook, watch, watch_interval, tools_allow, tools_deny, idle_ttl_secs, auto_refresh } => {
+ Commands::Serve {
+ config: config_path,
+ governance_webhook,
+ watch,
+ watch_interval,
+ tools_allow,
+ tools_deny,
+ idle_ttl_secs,
+ auto_refresh,
+ } => {
let config_path = expand_tilde(&config_path);
let cfg = match Config::load(std::path::Path::new(&config_path)) {
Ok(c) => c,
@@ -793,8 +817,9 @@ async fn main() -> anyhow::Result<()> {
// `[monitor] enabled`. CLI `--watch-interval` > env > `[monitor]
// interval_secs` > default 30.
let monitor_enabled = watch || cfg.monitor.enabled;
- let monitor_interval = watch_interval
- .unwrap_or_else(|| open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor));
+ let monitor_interval = watch_interval.unwrap_or_else(|| {
+ open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor)
+ });
let _watch_handle = if monitor_enabled {
let watch_db = StateDb::open(&db_path)?;
@@ -808,11 +833,16 @@ async fn main() -> anyhow::Result<()> {
};
let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
- let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
- let ontology_dirs = open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
+ let tool_filter =
+ build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
+ let ontology_dirs =
+ open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
for d in &ontology_dirs {
if !d.exists() {
- eprintln!("warning: ontology_dirs entry does not exist: {}", d.display());
+ eprintln!(
+ "warning: ontology_dirs entry does not exist: {}",
+ d.display()
+ );
}
}
let server = OpenOntologiesServer::new_with_repo_options(
@@ -828,7 +858,19 @@ async fn main() -> anyhow::Result<()> {
let service = server.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
}
- Commands::ServeHttp { config: config_path, host, port, token, governance_webhook, watch, watch_interval, tools_allow, tools_deny, idle_ttl_secs, auto_refresh } => {
+ Commands::ServeHttp {
+ config: config_path,
+ host,
+ port,
+ token,
+ governance_webhook,
+ watch,
+ watch_interval,
+ tools_allow,
+ tools_deny,
+ idle_ttl_secs,
+ auto_refresh,
+ } => {
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService,
session::local::LocalSessionManager,
@@ -852,14 +894,15 @@ async fn main() -> anyhow::Result<()> {
// Resolve effective host / port / token / stateful_mode honouring
// CLI > env > config > default precedence.
- let host = host.unwrap_or_else(|| open_ontologies::config::resolve_http_host(&cfg.http));
- let port = port.unwrap_or_else(|| open_ontologies::config::resolve_http_port(&cfg.http));
+ let host =
+ host.unwrap_or_else(|| open_ontologies::config::resolve_http_host(&cfg.http));
+ let port =
+ port.unwrap_or_else(|| open_ontologies::config::resolve_http_port(&cfg.http));
// Clap reads `OPEN_ONTOLOGIES_TOKEN` into `token` automatically
// (because of `env = "OPEN_ONTOLOGIES_TOKEN"`), so a non-`None`
// value already encompasses CLI + env. Fall back to config when
// neither is set.
- let token = token
- .or_else(|| open_ontologies::config::resolve_http_token(&cfg.http));
+ let token = token.or_else(|| open_ontologies::config::resolve_http_token(&cfg.http));
let data_dir = expand_tilde(&cfg.general.data_dir);
let db_path_owned = std::path::Path::new(&data_dir).join("open-ontologies.db");
@@ -873,8 +916,9 @@ async fn main() -> anyhow::Result<()> {
let shared_db = StateDb::open(&db_path_owned)?;
let monitor_enabled = watch || cfg.monitor.enabled;
- let monitor_interval = watch_interval
- .unwrap_or_else(|| open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor));
+ let monitor_interval = watch_interval.unwrap_or_else(|| {
+ open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor)
+ });
let _watch_handle = if monitor_enabled {
let watch_db = StateDb::open(&db_path_owned)?;
@@ -898,11 +942,16 @@ async fn main() -> anyhow::Result<()> {
let gw_for_service = governance_webhook.clone();
let embed_config = cfg.embeddings.clone();
let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
- let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
- let ontology_dirs = open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
+ let tool_filter =
+ build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
+ let ontology_dirs =
+ open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
for d in &ontology_dirs {
if !d.exists() {
- eprintln!("warning: ontology_dirs entry does not exist: {}", d.display());
+ eprintln!(
+ "warning: ontology_dirs entry does not exist: {}",
+ d.display()
+ );
}
}
// Spawn a single evictor backed by a registry over the shared graph.
@@ -920,32 +969,30 @@ async fn main() -> anyhow::Result<()> {
let cache_for_service = cache_config.clone();
let filter_for_service = tool_filter.clone();
let dirs_for_service = ontology_dirs.clone();
- let service: StreamableHttpService<_, LocalSessionManager> =
- StreamableHttpService::new(
- move || {
- let db = StateDb::open(&db_path_owned)
- .map_err(std::io::Error::other)?;
- Ok(OpenOntologiesServer::new_with_repo_options(
- db,
- shared_graph_for_service.clone(),
- gw_for_service.clone(),
- embed_config.clone(),
- cache_for_service.clone(),
- filter_for_service.clone(),
- dirs_for_service.clone(),
- ))
- },
- Default::default(),
- http_config,
- );
+ let service: StreamableHttpService<_, LocalSessionManager> = StreamableHttpService::new(
+ move || {
+ let db = StateDb::open(&db_path_owned).map_err(std::io::Error::other)?;
+ Ok(OpenOntologiesServer::new_with_repo_options(
+ db,
+ shared_graph_for_service.clone(),
+ gw_for_service.clone(),
+ embed_config.clone(),
+ cache_for_service.clone(),
+ filter_for_service.clone(),
+ dirs_for_service.clone(),
+ ))
+ },
+ Default::default(),
+ http_config,
+ );
// Simple REST API — no MCP sessions, direct access to shared graph
- let sg_stats = shared_graph.clone();
- let sg_query = shared_graph.clone();
+ let sg_stats = shared_graph.clone();
+ let sg_query = shared_graph.clone();
let sg_update = shared_graph.clone();
- let sg_load = shared_graph.clone();
- let sg_save = shared_graph.clone();
- let sg_load_turtle = shared_graph.clone();
+ let sg_load = shared_graph.clone();
+ let sg_save = shared_graph.clone();
+ let sg_load_turtle = shared_graph.clone();
let api = axum::Router::new()
.route("/stats", axum::routing::get(move || {
let g = sg_stats.clone();
@@ -1049,20 +1096,25 @@ async fn main() -> anyhow::Result<()> {
.nest_service("/mcp", service);
let router = if let Some(ref token) = token {
let expected = format!("Bearer {}", token);
- router.layer(axum::middleware::from_fn(move |req: axum::extract::Request, next: axum::middleware::Next| {
- let expected = expected.clone();
- async move {
- let auth = req.headers().get("authorization").and_then(|v| v.to_str().ok());
- if auth == Some(&expected) {
- next.run(req).await
- } else {
- axum::http::Response::builder()
- .status(401)
- .body(axum::body::Body::from("Unauthorized"))
- .unwrap()
+ router.layer(axum::middleware::from_fn(
+ move |req: axum::extract::Request, next: axum::middleware::Next| {
+ let expected = expected.clone();
+ async move {
+ let auth = req
+ .headers()
+ .get("authorization")
+ .and_then(|v| v.to_str().ok());
+ if auth == Some(&expected) {
+ next.run(req).await
+ } else {
+ axum::http::Response::builder()
+ .status(401)
+ .body(axum::body::Body::from("Unauthorized"))
+ .unwrap()
+ }
}
- }
- }))
+ },
+ ))
} else {
router
};
@@ -1079,7 +1131,12 @@ async fn main() -> anyhow::Result<()> {
.await?;
}
- Commands::ServeUnix { config: config_path, socket, files } => {
+ #[cfg(unix)]
+ Commands::ServeUnix {
+ config: config_path,
+ socket,
+ files,
+ } => {
let config_path = expand_tilde(&config_path);
let cfg = match Config::load(std::path::Path::new(&config_path)) {
Ok(c) => c,
@@ -1121,6 +1178,13 @@ async fn main() -> anyhow::Result<()> {
eprintln!("Graph has {} triples total", graph.triple_count());
open_ontologies::socket::serve(&socket_path, graph).await?;
}
+ #[cfg(windows)]
+ Commands::ServeUnix { .. } => {
+ eprintln!(
+ "serve-unix is not available on Windows. Use `serve` or `serve-http` instead."
+ );
+ std::process::exit(1);
+ }
// ─── Batch ──────────────────────────────────────────────────
Commands::Batch { input, bail } => {
@@ -1147,7 +1211,10 @@ async fn main() -> anyhow::Result<()> {
GraphStore::validate_file(&input)
};
match result {
- Ok(count) => output_json(&serde_json::json!({"ok": true, "triples": count}), cli.pretty),
+ Ok(count) => output_json(
+ &serde_json::json!({"ok": true, "triples": count}),
+ cli.pretty,
+ ),
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1157,7 +1224,10 @@ async fn main() -> anyhow::Result<()> {
Commands::Load { path } => {
let (_db, graph) = setup(&cli.data_dir)?;
match graph.load_file(&path) {
- Ok(count) => output_json(&serde_json::json!({"ok": true, "triples_loaded": count, "path": path}), cli.pretty),
+ Ok(count) => output_json(
+ &serde_json::json!({"ok": true, "triples_loaded": count, "path": path}),
+ cli.pretty,
+ ),
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1167,7 +1237,10 @@ async fn main() -> anyhow::Result<()> {
Commands::Save { path, format } => {
let (_db, graph) = setup(&cli.data_dir)?;
match graph.save_file(&path, &format) {
- Ok(_) => output_json(&serde_json::json!({"ok": true, "path": path, "format": format}), cli.pretty),
+ Ok(_) => output_json(
+ &serde_json::json!({"ok": true, "path": path, "format": format}),
+ cli.pretty,
+ ),
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1177,7 +1250,10 @@ async fn main() -> anyhow::Result<()> {
Commands::Clear => {
let (_db, graph) = setup(&cli.data_dir)?;
match graph.clear() {
- Ok(_) => output_json(&serde_json::json!({"ok": true, "message": "Store cleared"}), cli.pretty),
+ Ok(_) => output_json(
+ &serde_json::json!({"ok": true, "message": "Store cleared"}),
+ cli.pretty,
+ ),
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1186,7 +1262,9 @@ async fn main() -> anyhow::Result<()> {
}
Commands::Stats => {
let (_db, graph) = setup(&cli.data_dir)?;
- let stats_json = graph.get_stats().unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let stats_json = graph
+ .get_stats()
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&stats_json, cli.pretty);
}
Commands::Query { query } => {
@@ -1198,14 +1276,17 @@ async fn main() -> anyhow::Result<()> {
} else {
query
};
- let result = graph.sparql_select(&query_str).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = graph
+ .sparql_select(&query_str)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
Commands::Diff { old_path, new_path } => {
use open_ontologies::ontology::OntologyService;
let old = std::fs::read_to_string(&old_path)?;
let new = std::fs::read_to_string(&new_path)?;
- let result = OntologyService::diff(&old, &new).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = OntologyService::diff(&old, &new)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
Commands::Lint { input } => {
@@ -1218,28 +1299,30 @@ async fn main() -> anyhow::Result<()> {
} else {
std::fs::read_to_string(&input)?
};
- let result = OntologyService::lint_with_feedback(&content, Some(&db)).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = OntologyService::lint_with_feedback(&content, Some(&db))
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
Commands::Convert { path, to, output } => {
let store = GraphStore::new();
match store.load_file(&path) {
- Ok(_) => {
- match store.serialize(&to) {
- Ok(content) => {
- if let Some(out_path) = output {
- std::fs::write(&out_path, &content)?;
- output_json(&serde_json::json!({"ok": true, "path": out_path, "format": to}), cli.pretty);
- } else {
- println!("{}", content);
- }
- }
- Err(e) => {
- output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
- std::process::exit(1);
+ Ok(_) => match store.serialize(&to) {
+ Ok(content) => {
+ if let Some(out_path) = output {
+ std::fs::write(&out_path, &content)?;
+ output_json(
+ &serde_json::json!({"ok": true, "path": out_path, "format": to}),
+ cli.pretty,
+ );
+ } else {
+ println!("{}", content);
}
}
- }
+ Err(e) => {
+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
+ std::process::exit(1);
+ }
+ },
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1248,11 +1331,14 @@ async fn main() -> anyhow::Result<()> {
}
Commands::Status => {
let (_db, graph) = setup(&cli.data_dir)?;
- output_json(&serde_json::json!({
- "status": "ok",
- "version": env!("CARGO_PKG_VERSION"),
- "triples_loaded": graph.triple_count(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "status": "ok",
+ "version": env!("CARGO_PKG_VERSION"),
+ "triples_loaded": graph.triple_count(),
+ }),
+ cli.pretty,
+ );
}
// ─── Remote ─────────────────────────────────────────────────
@@ -1261,19 +1347,25 @@ async fn main() -> anyhow::Result<()> {
match action.as_str() {
"list" => {
let entries = marketplace::list(domain.as_deref());
- let items: Vec<serde_json::Value> = entries.iter().map(|e| {
- serde_json::json!({
- "id": e.id,
- "name": e.name,
- "description": e.description,
- "domain": e.domain,
- "format": marketplace::format_name(e.format),
+ let items: Vec<serde_json::Value> = entries
+ .iter()
+ .map(|e| {
+ serde_json::json!({
+ "id": e.id,
+ "name": e.name,
+ "description": e.description,
+ "domain": e.domain,
+ "format": marketplace::format_name(e.format),
+ })
})
- }).collect();
- output_json(&serde_json::json!({
- "count": items.len(),
- "ontologies": items,
- }), cli.pretty);
+ .collect();
+ output_json(
+ &serde_json::json!({
+ "count": items.len(),
+ "ontologies": items,
+ }),
+ cli.pretty,
+ );
}
"install" => {
let id = id.as_deref().unwrap_or_else(|| {
@@ -1283,7 +1375,10 @@ async fn main() -> anyhow::Result<()> {
let entry = match marketplace::find(id) {
Some(e) => e,
None => {
- eprintln!("Unknown ontology ID: '{}'. Run 'marketplace list' to see available IDs.", id);
+ eprintln!(
+ "Unknown ontology ID: '{}'. Run 'marketplace list' to see available IDs.",
+ id
+ );
std::process::exit(1);
}
};
@@ -1292,16 +1387,22 @@ async fn main() -> anyhow::Result<()> {
match graph.load_content_with_base(&content, entry.format, Some(entry.url)) {
Ok(count) => {
let stats = graph.get_stats().unwrap_or_default();
- output_json(&serde_json::json!({
- "ok": true,
- "installed": entry.id,
- "name": entry.name,
- "triples_loaded": count,
- "stats": serde_json::from_str::<serde_json::Value>(&stats).unwrap_or_default(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "installed": entry.id,
+ "name": entry.name,
+ "triples_loaded": count,
+ "stats": serde_json::from_str::<serde_json::Value>(&stats).unwrap_or_default(),
+ }),
+ cli.pretty,
+ );
}
Err(e) => {
- output_json(&serde_json::json!({"error": format!("Parse error: {}", e)}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": format!("Parse error: {}", e)}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
@@ -1315,24 +1416,37 @@ async fn main() -> anyhow::Result<()> {
Commands::Pull { url, sparql, query } => {
let (_db, graph) = setup(&cli.data_dir)?;
let content = if sparql {
- let q = query.as_deref().unwrap_or("CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }");
+ let q = query
+ .as_deref()
+ .unwrap_or("CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }");
GraphStore::fetch_sparql(&url, q).await?
} else {
GraphStore::fetch_url(&url).await?
};
match graph.load_turtle(&content, None) {
- Ok(count) => output_json(&serde_json::json!({"ok": true, "triples_loaded": count, "source": url}), cli.pretty),
+ Ok(count) => output_json(
+ &serde_json::json!({"ok": true, "triples_loaded": count, "source": url}),
+ cli.pretty,
+ ),
Err(e) => {
- output_json(&serde_json::json!({"error": format!("Parse error: {}", e)}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": format!("Parse error: {}", e)}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
}
- Commands::Push { endpoint, graph: graph_name } => {
+ Commands::Push {
+ endpoint,
+ graph: graph_name,
+ } => {
let (_db, graph) = setup(&cli.data_dir)?;
let content = graph.serialize("ntriples")?;
match GraphStore::push_sparql(&endpoint, &content).await {
- Ok(msg) => output_json(&serde_json::json!({"ok": true, "message": msg}), cli.pretty),
+ Ok(msg) => {
+ output_json(&serde_json::json!({"ok": true, "message": msg}), cli.pretty)
+ }
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1345,23 +1459,27 @@ async fn main() -> anyhow::Result<()> {
let mut imported = Vec::new();
let mut to_import: Vec<String> = Vec::new();
- let query = "SELECT ?import WHERE { ?onto <http://www.w3.org/2002/07/owl#imports> ?import }";
+ let query =
+ "SELECT ?import WHERE { ?onto <http://www.w3.org/2002/07/owl#imports> ?import }";
if let Ok(result) = graph.sparql_select(query)
&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&result)
- && let Some(results) = parsed["results"].as_array() {
- for row in results {
- if let Some(uri) = row["import"].as_str() {
- let uri = uri.trim_matches(|c| c == '<' || c == '>');
- to_import.push(uri.to_string());
- }
- }
+ && let Some(results) = parsed["results"].as_array()
+ {
+ for row in results {
+ if let Some(uri) = row["import"].as_str() {
+ let uri = uri.trim_matches(|c| c == '<' || c == '>');
+ to_import.push(uri.to_string());
}
+ }
+ }
let mut depth = 0;
while !to_import.is_empty() && depth < max_depth {
let batch = std::mem::take(&mut to_import);
for url in batch {
- if imported.contains(&url) { continue; }
+ if imported.contains(&url) {
+ continue;
+ }
match GraphStore::fetch_url(&url).await {
Ok(content) => {
if let Ok(count) = graph.load_turtle(&content, None) {
@@ -1375,7 +1493,10 @@ async fn main() -> anyhow::Result<()> {
depth += 1;
}
- output_json(&serde_json::json!({"ok": true, "imported": imported.len(), "urls": imported}), cli.pretty);
+ output_json(
+ &serde_json::json!({"ok": true, "imported": imported.len(), "urls": imported}),
+ cli.pretty,
+ );
}
// ─── Versioning ────────────────────────────────────────────
@@ -1402,7 +1523,11 @@ async fn main() -> anyhow::Result<()> {
}
// ─── Data pipeline ──────────────────────────────────────────
- Commands::Map { data_path, format: _format, save } => {
+ Commands::Map {
+ data_path,
+ format: _format,
+ save,
+ } => {
use open_ontologies::ingest::DataIngester;
use open_ontologies::mapping::MappingConfig;
let (_db, graph) = setup(&cli.data_dir)?;
@@ -1416,12 +1541,19 @@ async fn main() -> anyhow::Result<()> {
let classes = graph.sparql_select(classes_query).unwrap_or_default();
let props = graph.sparql_select(props_query).unwrap_or_default();
- let mapping = MappingConfig::from_headers(&headers, "http://example.org/data/", "http://example.org/data/Thing");
+ let mapping = MappingConfig::from_headers(
+ &headers,
+ "http://example.org/data/",
+ "http://example.org/data/Thing",
+ );
let mapping_json = serde_json::to_string_pretty(&mapping).unwrap_or_default();
if let Some(save_path) = save {
std::fs::write(&save_path, &mapping_json)?;
- output_json(&serde_json::json!({"ok": true, "saved": save_path}), cli.pretty);
+ output_json(
+ &serde_json::json!({"ok": true, "saved": save_path}),
+ cli.pretty,
+ );
} else {
let extract_iris = |json: &str, var: &str| -> Vec<String> {
serde_json::from_str::<serde_json::Value>(json)
@@ -1429,18 +1561,30 @@ async fn main() -> anyhow::Result<()> {
.and_then(|v| v["results"].as_array().cloned())
.unwrap_or_default()
.iter()
- .filter_map(|r| r[var].as_str().map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string()))
+ .filter_map(|r| {
+ r[var]
+ .as_str()
+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())
+ })
.collect()
};
- output_json(&serde_json::json!({
- "data_fields": headers,
- "ontology_classes": extract_iris(&classes, "c"),
- "ontology_properties": extract_iris(&props, "p"),
- "suggested_mapping": serde_json::from_str::<serde_json::Value>(&mapping_json).unwrap_or_default(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "data_fields": headers,
+ "ontology_classes": extract_iris(&classes, "c"),
+ "ontology_properties": extract_iris(&props, "p"),
+ "suggested_mapping": serde_json::from_str::<serde_json::Value>(&mapping_json).unwrap_or_default(),
+ }),
+ cli.pretty,
+ );
}
}
- Commands::Ingest { path, format: _format, mapping, base_iri } => {
+ Commands::Ingest {
+ path,
+ format: _format,
+ mapping,
+ base_iri,
+ } => {
use open_ontologies::ingest::DataIngester;
use open_ontologies::mapping::MappingConfig;
let (_db, graph) = setup(&cli.data_dir)?;
@@ -1449,7 +1593,10 @@ async fn main() -> anyhow::Result<()> {
let rows = DataIngester::parse_file(&path)?;
if rows.is_empty() {
- output_json(&serde_json::json!({"ok": true, "triples_loaded": 0, "warnings": ["No data rows found"]}), cli.pretty);
+ output_json(
+ &serde_json::json!({"ok": true, "triples_loaded": 0, "warnings": ["No data rows found"]}),
+ cli.pretty,
+ );
} else {
let mapping_config = if let Some(ref mapping_path) = mapping {
let content = std::fs::read_to_string(mapping_path)?;
@@ -1461,7 +1608,10 @@ async fn main() -> anyhow::Result<()> {
let ntriples = mapping_config.rows_to_ntriples(&rows);
match graph.load_ntriples(&ntriples) {
- Ok(count) => output_json(&serde_json::json!({"ok": true, "triples_loaded": count, "rows": rows.len()}), cli.pretty),
+ Ok(count) => output_json(
+ &serde_json::json!({"ok": true, "triples_loaded": count, "rows": rows.len()}),
+ cli.pretty,
+ ),
Err(e) => {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
@@ -1484,11 +1634,17 @@ async fn main() -> anyhow::Result<()> {
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
- Commands::Extend { data_path, format: _format, mapping, shapes, profile } => {
+ Commands::Extend {
+ data_path,
+ format: _format,
+ mapping,
+ shapes,
+ profile,
+ } => {
use open_ontologies::ingest::DataIngester;
use open_ontologies::mapping::MappingConfig;
- use open_ontologies::shacl::ShaclValidator;
use open_ontologies::reason::Reasoner;
+ use open_ontologies::shacl::ShaclValidator;
let (_db, graph) = setup(&cli.data_dir)?;
let base_iri = "http://example.org/data/";
@@ -1509,23 +1665,30 @@ async fn main() -> anyhow::Result<()> {
// 2. SHACL (optional)
let shacl_result = if let Some(ref shapes_path) = shapes {
let shapes_content = std::fs::read_to_string(shapes_path)?;
- Some(ShaclValidator::validate(&graph, &shapes_content)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)))
+ Some(
+ ShaclValidator::validate(&graph, &shapes_content)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)),
+ )
} else {
None
};
// 3. Reason (optional)
- let reason_result = profile.as_ref().map(|prof| Reasoner::run(&graph, prof, true)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)));
-
- output_json(&serde_json::json!({
- "ok": true,
- "triples_loaded": triples_loaded,
- "rows": rows.len(),
- "shacl": shacl_result.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok()),
- "reason": reason_result.and_then(|r| serde_json::from_str::<serde_json::Value>(&r).ok()),
- }), cli.pretty);
+ let reason_result = profile.as_ref().map(|prof| {
+ Reasoner::run(&graph, prof, true)
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
+ });
+
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "triples_loaded": triples_loaded,
+ "rows": rows.len(),
+ "shacl": shacl_result.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok()),
+ "reason": reason_result.and_then(|r| serde_json::from_str::<serde_json::Value>(&r).ok()),
+ }),
+ cli.pretty,
+ );
}
// ─── Lifecycle ──────────────────────────────────────────────
@@ -1533,14 +1696,16 @@ async fn main() -> anyhow::Result<()> {
let (db, graph) = setup(&cli.data_dir)?;
let turtle = std::fs::read_to_string(&file)?;
let planner = open_ontologies::plan::Planner::new(db, graph);
- let result = planner.plan(&turtle)
+ let result = planner
+ .plan(&turtle)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
Commands::Apply { mode } => {
let (db, graph) = setup(&cli.data_dir)?;
let planner = open_ontologies::plan::Planner::new(db, graph);
- let result = planner.apply(&mode)
+ let result = planner
+ .apply(&mode)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
@@ -1551,25 +1716,30 @@ async fn main() -> anyhow::Result<()> {
for iri in &iris {
planner.lock_iri(iri, reason_str);
}
- output_json(&serde_json::json!({
- "ok": true,
- "locked": iris,
- "reason": reason_str,
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "locked": iris,
+ "reason": reason_str,
+ }),
+ cli.pretty,
+ );
}
Commands::Drift { file_a, file_b } => {
let (db, _graph) = setup(&cli.data_dir)?;
let v1 = std::fs::read_to_string(&file_a)?;
let v2 = std::fs::read_to_string(&file_b)?;
let detector = open_ontologies::drift::DriftDetector::new(db);
- let result = detector.detect(&v1, &v2)
+ let result = detector
+ .detect(&v1, &v2)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
Commands::Enforce { pack } => {
let (db, graph) = setup(&cli.data_dir)?;
let enforcer = open_ontologies::enforce::Enforcer::new(db.clone(), graph);
- let result = enforcer.enforce_with_feedback(&pack, Some(&db))
+ let result = enforcer
+ .enforce_with_feedback(&pack, Some(&db))
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
@@ -1585,17 +1755,23 @@ async fn main() -> anyhow::Result<()> {
let (db, graph) = setup(&cli.data_dir)?;
let monitor = open_ontologies::monitor::Monitor::new(db, graph);
monitor.clear_blocked();
- output_json(&serde_json::json!({"ok": true, "message": "Monitor block cleared"}), cli.pretty);
+ output_json(
+ &serde_json::json!({"ok": true, "message": "Monitor block cleared"}),
+ cli.pretty,
+ );
}
Commands::Lineage { session } => {
let (db, _graph) = setup(&cli.data_dir)?;
let lineage = open_ontologies::lineage::LineageLog::new(db);
let session_id = session.unwrap_or_else(|| "current".to_string());
let events = lineage.get_compact(&session_id);
- output_json(&serde_json::json!({
- "session_id": session_id,
- "events": events.trim(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "session_id": session_id,
+ "events": events.trim(),
+ }),
+ cli.pretty,
+ );
}
// ─── Clinical ──────────────────────────────────────────────
@@ -1603,25 +1779,35 @@ async fn main() -> anyhow::Result<()> {
match open_ontologies::clinical::ClinicalCrosswalks::load("data/crosswalks.parquet") {
Ok(cw) => {
let results = cw.lookup(&code, &system);
- output_json(&serde_json::json!({
- "code": code,
- "system": system,
- "mappings": results.iter().map(|r| serde_json::json!({
- "target_code": r.target_code,
- "target_system": r.target_system,
- "relation": r.relation,
- "source_label": r.source_label,
- "target_label": r.target_label,
- })).collect::<Vec<_>>(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "code": code,
+ "system": system,
+ "mappings": results.iter().map(|r| serde_json::json!({
+ "target_code": r.target_code,
+ "target_system": r.target_system,
+ "relation": r.relation,
+ "source_label": r.source_label,
+ "target_label": r.target_label,
+ })).collect::<Vec<_>>(),
+ }),
+ cli.pretty,
+ );
}
Err(e) => {
- output_json(&serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
}
- Commands::Enrich { class_iri, code, system } => {
+ Commands::Enrich {
+ class_iri,
+ code,
+ system,
+ } => {
let (_db, graph) = setup(&cli.data_dir)?;
match open_ontologies::clinical::ClinicalCrosswalks::load("data/crosswalks.parquet") {
Ok(cw) => {
@@ -1629,7 +1815,10 @@ async fn main() -> anyhow::Result<()> {
output_result(&result, cli.pretty);
}
Err(e) => {
- output_json(&serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
@@ -1639,7 +1828,10 @@ async fn main() -> anyhow::Result<()> {
match open_ontologies::clinical::ClinicalCrosswalks::load("data/crosswalks.parquet") {
Ok(cw) => output_result(&cw.validate_clinical(&graph), cli.pretty),
Err(e) => {
- output_json(&serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": format!("Crosswalks not loaded: {}", e)}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
@@ -1647,7 +1839,10 @@ async fn main() -> anyhow::Result<()> {
// ─── Schema import ─────────────────────────────────────────
#[allow(unreachable_code, unused_variables)]
- Commands::ImportSchema { connection, base_iri } => {
+ Commands::ImportSchema {
+ connection,
+ base_iri,
+ } => {
let (_db, graph) = setup(&cli.data_dir)?;
let driver = match open_ontologies::sqlsource::detect_driver(&connection) {
Ok(d) => d,
@@ -1661,11 +1856,17 @@ async fn main() -> anyhow::Result<()> {
open_ontologies::sqlsource::SqlDriver::Postgres => {
#[cfg(feature = "postgres")]
{
- open_ontologies::schema::SchemaIntrospector::introspect_postgres(&connection).await?
+ open_ontologies::schema::SchemaIntrospector::introspect_postgres(
+ &connection,
+ )
+ .await?
}
#[cfg(not(feature = "postgres"))]
{
- output_json(&serde_json::json!({"error": "import-schema for postgres requires the 'postgres' feature (compile with --features postgres)"}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": "import-schema for postgres requires the 'postgres' feature (compile with --features postgres)"}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
@@ -1680,28 +1881,41 @@ async fn main() -> anyhow::Result<()> {
}
#[cfg(not(feature = "duckdb"))]
{
- output_json(&serde_json::json!({"error": "import-schema for duckdb requires the 'duckdb' feature (compile with --features duckdb)"}), cli.pretty);
+ output_json(
+ &serde_json::json!({"error": "import-schema for duckdb requires the 'duckdb' feature (compile with --features duckdb)"}),
+ cli.pretty,
+ );
std::process::exit(1);
}
}
};
- let turtle = open_ontologies::schema::SchemaIntrospector::generate_turtle(&tables, &base_iri);
+ let turtle =
+ open_ontologies::schema::SchemaIntrospector::generate_turtle(&tables, &base_iri);
// Validate + load
GraphStore::validate_turtle(&turtle)?;
let count = graph.load_turtle(&turtle, Some(&base_iri))?;
- output_json(&serde_json::json!({
- "ok": true,
- "driver": driver.as_str(),
- "tables": tables.len(),
- "classes": tables.len(),
- "triples": count,
- "base_iri": base_iri,
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "tables": tables.len(),
+ "classes": tables.len(),
+ "triples": count,
+ "base_iri": base_iri,
+ }),
+ cli.pretty,
+ );
}
- Commands::SqlIngest { connection, sql, mapping, inline_mapping, base_iri } => {
+ Commands::SqlIngest {
+ connection,
+ sql,
+ mapping,
+ inline_mapping,
+ base_iri,
+ } => {
use open_ontologies::ingest::DataIngester;
use open_ontologies::mapping::MappingConfig;
@@ -1728,13 +1942,16 @@ async fn main() -> anyhow::Result<()> {
let rows = open_ontologies::sqlsource::query_rows(&connection, &sql).await?;
if rows.is_empty() {
- output_json(&serde_json::json!({
- "ok": true,
- "driver": driver.as_str(),
- "triples_loaded": 0,
- "rows_processed": 0,
- "warnings": ["Query returned no rows"],
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": 0,
+ "rows_processed": 0,
+ "warnings": ["Query returned no rows"],
+ }),
+ cli.pretty,
+ );
return Ok(());
}
@@ -1753,15 +1970,23 @@ async fn main() -> anyhow::Result<()> {
let ntriples = mapping_cfg.rows_to_ntriples(&rows);
let count = graph.load_ntriples(&ntriples)?;
- output_json(&serde_json::json!({
- "ok": true,
- "driver": driver.as_str(),
- "triples_loaded": count,
- "rows_processed": rows.len(),
- "mapping_fields": mapping_cfg.mappings.len(),
- }), cli.pretty);
+ output_json(
+ &serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": count,
+ "rows_processed": rows.len(),
+ "mapping_fields": mapping_cfg.mappings.len(),
+ }),
+ cli.pretty,
+ );
}
- Commands::Align { source, target, min_confidence, dry_run } => {
+ 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 {
@@ -1769,30 +1994,51 @@ async fn main() -> anyhow::Result<()> {
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)
+ let result = engine
+ .align(&source_ttl, target_ttl.as_deref(), min_confidence, dry_run)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
- Commands::AlignFeedback { source, target, accept, reject } => {
+ 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, None)
+ let result = engine
+ .record_feedback(&source, &target, "user_feedback", accepted, None)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
- Commands::LintFeedback { rule_id, entity, accept, dismiss } => {
+ Commands::LintFeedback {
+ rule_id,
+ entity,
+ accept,
+ dismiss,
+ } => {
let (db, _graph) = setup(&cli.data_dir)?;
let accepted = accept || !dismiss;
- let result = open_ontologies::feedback::record_tool_feedback(&db, "lint", &rule_id, &entity, accepted)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = open_ontologies::feedback::record_tool_feedback(
+ &db, "lint", &rule_id, &entity, accepted,
+ )
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
- Commands::EnforceFeedback { rule_id, entity, accept, dismiss } => {
+ Commands::EnforceFeedback {
+ rule_id,
+ entity,
+ accept,
+ dismiss,
+ } => {
let (db, _graph) = setup(&cli.data_dir)?;
let accepted = accept || !dismiss;
- let result = open_ontologies::feedback::record_tool_feedback(&db, "enforce", &rule_id, &entity, accepted)
- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
+ let result = open_ontologies::feedback::record_tool_feedback(
+ &db, "enforce", &rule_id, &entity, accepted,
+ )
+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result(&result, cli.pretty);
}
}
diff --git a/src/socket_windows.rs b/src/socket_windows.rs
new file mode 100644
index 00000000..73b0264e
--- /dev/null
+++ b/src/socket_windows.rs
@@ -0,0 +1,10 @@
+use std::sync::Arc;
+
+use crate::graph::GraphStore;
+
+/// Windows stub for the Unix domain socket adapter.
+pub async fn serve(_socket_path: &str, _graph: Arc<GraphStore>) -> anyhow::Result<()> {
+ anyhow::bail!(
+ "serve-unix is not available on Windows yet. Use `serve` or `serve-http` instead."
+ );
+}
diff --git a/studio/WINDOWS.md b/studio/WINDOWS.md
new file mode 100644
index 00000000..c117cd11
--- /dev/null
+++ b/studio/WINDOWS.md
@@ -0,0 +1,7 @@
+# Windows Notes
+
+See the full Windows build guide in [`../docs/windows.md`](../docs/windows.md).
+
+- Local `tauri dev` looks for the engine in `..\target\debug\open-ontologies.exe` or `..\target\release\open-ontologies.exe`, so a macOS-specific sidecar setup is not required on Windows.
+- The Tauri backend does not shell out through `sh`, `lsof`, or Homebrew-specific paths when running on Windows.
+- Packaged builds use `npm run prepare-engine` to copy `open-ontologies.exe` into `src-tauri/binaries/open-ontologies-x86_64-pc-windows-msvc.exe`.
diff --git a/studio/package.json b/studio/package.json
index be870484..9e0177f0 100644
--- a/studio/package.json
+++ b/studio/package.json
@@ -5,9 +5,10 @@
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "build": "tsc && vite build && npm run prepare-engine",
"preview": "vite preview",
- "tauri": "tauri"
+ "tauri": "tauri",
+ "prepare-engine": "node ./scripts/prepare-engine.mjs"
},
"dependencies": {
"@tailwindcss/vite": "^4.2.1",
diff --git a/studio/scripts/prepare-engine.mjs b/studio/scripts/prepare-engine.mjs
new file mode 100644
index 00000000..f23396e2
--- /dev/null
+++ b/studio/scripts/prepare-engine.mjs
@@ -0,0 +1,33 @@
+import fs from "node:fs";
+import path from "node:path";
+
+const studioRoot = path.resolve(import.meta.dirname, "..");
+const workspaceRoot = path.resolve(studioRoot, "..");
+const ext = process.platform === "win32" ? ".exe" : "";
+
+const targetTripleByPlatform = {
+ win32: "x86_64-pc-windows-msvc",
+ darwin: process.arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin",
+ linux: "x86_64-unknown-linux-gnu",
+};
+
+const targetTriple = targetTripleByPlatform[process.platform];
+if (!targetTriple) {
+ console.warn(`Skipping engine bundle prep: unsupported platform ${process.platform}`);
+ process.exit(0);
+}
+
+const source = path.join(workspaceRoot, "target", "release", `open-ontologies${ext}`);
+const binariesDir = path.join(studioRoot, "src-tauri", "binaries");
+const destination = path.join(binariesDir, `open-ontologies-${targetTriple}${ext}`);
+
+if (!fs.existsSync(source)) {
+ console.warn(
+ `Skipping engine bundle prep: ${source} does not exist. Build the engine first with cargo build --release.`,
+ );
+ process.exit(0);
+}
+
+fs.mkdirSync(binariesDir, { recursive: true });
+fs.copyFileSync(source, destination);
+console.log(`Prepared bundled engine binary: ${destination}`);
diff --git a/studio/src-tauri/src/chat.rs b/studio/src-tauri/src/chat.rs
index 8cc3bb35..d1047395 100644
--- a/studio/src-tauri/src/chat.rs
+++ b/studio/src-tauri/src/chat.rs
@@ -1,22 +1,72 @@
+use std::io::BufRead;
use std::io::Write;
+use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
-use std::io::BufRead;
use tauri::{Emitter, Manager};
pub struct ChatState {
pub process: Mutex<Option<Child>>,
}
+fn resolve_node_binary() -> PathBuf {
+ #[cfg(target_os = "windows")]
+ {
+ let candidates = [
+ PathBuf::from(r"C:\Program Files\nodejs\node.exe"),
+ PathBuf::from(r"C:\Program Files (x86)\nodejs\node.exe"),
+ ];
+ if let Some(path) = candidates.into_iter().find(|path| path.exists()) {
+ return path;
+ }
+ PathBuf::from("node")
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let candidates = [
+ PathBuf::from("/opt/homebrew/bin/node"),
+ PathBuf::from("/usr/local/bin/node"),
+ PathBuf::from("/usr/bin/node"),
+ ];
+ if let Some(path) = candidates.into_iter().find(|path| path.exists()) {
+ return path;
+ }
+ PathBuf::from("node")
+ }
+}
+
+fn augmented_path() -> String {
+ let mut parts: Vec<String> = Vec::new();
+ #[cfg(target_os = "windows")]
+ {
+ parts.push(r"C:\Program Files\nodejs".to_string());
+ if let Some(home) = std::env::var_os("USERPROFILE") {
+ parts.push(format!(r"{}\.\cargo\bin", home.to_string_lossy()));
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ parts.push("/opt/homebrew/bin".to_string());
+ parts.push("/usr/local/bin".to_string());
+ parts.push("/usr/bin".to_string());
+ }
+ if let Ok(existing) = std::env::var("PATH") {
+ parts.push(existing);
+ }
+ let separator = if cfg!(target_os = "windows") { ";" } else { ":" };
+ parts.join(separator)
+}
+
pub fn spawn_agent_sidecar(app: &tauri::AppHandle) -> Result<(), String> {
let sidecar_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("sidecars/agent");
+ let node = resolve_node_binary();
- let mut child = Command::new("node")
+ let mut child = Command::new(&node)
.arg(sidecar_dir.join("dist/index.js"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
- .env("PATH", format!("/opt/homebrew/bin:/usr/local/bin:/usr/bin:{}", std::env::var("PATH").unwrap_or_default()))
+ .env("PATH", augmented_path())
.spawn()
.map_err(|e| format!("Failed to spawn agent sidecar: {e}"))?;
@@ -49,7 +99,11 @@ pub fn spawn_agent_sidecar(app: &tauri::AppHandle) -> Result<(), String> {
}
#[tauri::command]
-pub fn send_chat_message(message: String, mode: String, state: tauri::State<ChatState>) -> Result<(), String> {
+pub fn send_chat_message(
+ message: String,
+ mode: String,
+ state: tauri::State<ChatState>,
+) -> Result<(), String> {
let mut guard = state.process.lock().map_err(|e| format!("Lock error: {e}"))?;
let child = guard.as_mut().ok_or("Agent sidecar not running")?;
let stdin = child.stdin.as_mut().ok_or("No stdin")?;
diff --git a/studio/src-tauri/src/engine.rs b/studio/src-tauri/src/engine.rs
index d7593cf3..1f29c1be 100644
--- a/studio/src-tauri/src/engine.rs
+++ b/studio/src-tauri/src/engine.rs
@@ -1,4 +1,5 @@
use std::io::BufRead;
+use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
@@ -9,25 +10,117 @@ pub struct EngineState {
pub child: Mutex<Option<Child>>,
}
+fn engine_binary_names() -> &'static [&'static str] {
+ #[cfg(target_os = "windows")]
+ {
+ &["open-ontologies-x86_64-pc-windows-msvc.exe", "open-ontologies.exe"]
+ }
+ #[cfg(target_os = "macos")]
+ {
+ &[
+ "open-ontologies-aarch64-apple-darwin",
+ "open-ontologies-x86_64-apple-darwin",
+ "open-ontologies",
+ ]
+ }
+ #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
+ {
+ &[
+ "open-ontologies-x86_64-unknown-linux-gnu",
+ "open-ontologies-x86_64-unknown-linux-musl",
+ "open-ontologies",
+ ]
+ }
+}
+
+fn find_existing_binary(dir: &Path) -> Option<PathBuf> {
+ engine_binary_names()
+ .iter()
+ .map(|name| dir.join(name))
+ .find(|path| path.exists())
+}
+
+fn resolve_engine_binary() -> Result<PathBuf, String> {
+ let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ let bundled_dir = manifest_dir.join("binaries");
+ if let Some(path) = find_existing_binary(&bundled_dir) {
+ return Ok(path);
+ }
+
+ let workspace_root = manifest_dir
+ .parent()
+ .and_then(|p| p.parent())
+ .ok_or("Cannot resolve workspace root from Tauri manifest directory")?;
+ for profile in ["release", "debug"] {
+ let candidate_dir = workspace_root.join("target").join(profile);
+ if let Some(path) = find_existing_binary(&candidate_dir) {
+ return Ok(path);
+ }
+ }
+
+ Err(format!(
+ "No open-ontologies binary found. Checked {} and workspace target/{{release,debug}}.",
+ bundled_dir.display()
+ ))
+}
+
+fn stale_pids_on_port(port: u16) -> Vec<u32> {
+ #[cfg(target_os = "windows")]
+ {
+ let output = Command::new("netstat")
+ .args(["-ano", "-p", "tcp"])
+ .output();
+ let Ok(output) = output else {
+ return Vec::new();
+ };
+ let needle = format!(":{}", port);
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter(|line| line.contains("LISTENING") && line.contains(&needle))
+ .filter_map(|line| line.split_whitespace().last())
+ .filter_map(|pid| pid.parse::<u32>().ok())
+ .collect()
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let output = Command::new("lsof")
+ .args(["-ti", &format!("tcp:{}", port)])
+ .output();
+ let Ok(output) = output else {
+ return Vec::new();
+ };
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| line.trim().parse::<u32>().ok())
+ .collect()
+ }
+}
+
+fn kill_process(pid: u32) {
+ #[cfg(target_os = "windows")]
+ let _ = Command::new("taskkill")
+ .args(["/F", "/PID", &pid.to_string()])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+
+ #[cfg(not(target_os = "windows"))]
+ let _ = Command::new("kill")
+ .args(["-9", &pid.to_string()])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+}
+
+fn clear_stale_port(port: u16) {
+ for pid in stale_pids_on_port(port) {
+ kill_process(pid);
+ }
+}
+
pub fn spawn_engine(app: &tauri::AppHandle) -> Result<(), String> {
- let binaries_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("binaries");
-
- // Find the engine binary (e.g. open-ontologies-aarch64-apple-darwin)
- let binary = std::fs::read_dir(&binaries_dir)
- .map_err(|e| format!("Cannot list binaries dir {}: {e}", binaries_dir.display()))?
- .filter_map(|e| e.ok())
- .find(|e| {
- let name = e.file_name();
- let s = name.to_string_lossy();
- s.starts_with("open-ontologies") && !s.ends_with(".d")
- })
- .map(|e| e.path())
- .ok_or_else(|| "No open-ontologies binary found in binaries/".to_string())?;
-
- // Kill any stale process on port 8080 (e.g. from a previous hot-reload cycle)
- let _ = Command::new("sh")
- .args(["-c", "lsof -ti:8080 | xargs kill -9 2>/dev/null; true"])
- .output();
+ let binary = resolve_engine_binary()?;
+ clear_stale_port(8080);
std::thread::sleep(std::time::Duration::from_millis(300));
eprintln!("[engine] spawning {}", binary.display());
@@ -46,7 +139,8 @@ pub fn spawn_engine(app: &tauri::AppHandle) -> Result<(), String> {
for line in reader.lines() {
if let Ok(line) = line {
eprintln!("[engine] {}", line);
- if line.contains("listening") || line.contains("Listening") || line.contains("8080") {
+ if line.contains("listening") || line.contains("Listening") || line.contains("8080")
+ {
let _ = app_handle.emit("engine-ready", true);
}
}
@@ -57,7 +151,6 @@ pub fn spawn_engine(app: &tauri::AppHandle) -> Result<(), String> {
let state = app.state::<EngineState>();
*state.child.lock().map_err(|e| format!("Lock error: {e}"))? = Some(child);
- // Emit ready after 2s as fallback
let app_handle2 = app.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(2));