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.

refactor: project-wide improvements — docs, structure, DX, and hardening

FABIOTESSd9ae6a4211a5
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 00000000..9c905349
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,10 @@
+target/
+.git/
+.worktrees/
+benchmark/
+docs/
+tests/
+*.md
+!README.md
+.github/
+skills/
diff --git a/.gitignore b/.gitignore
index 0335f6ae..a6378cd2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
/target
.worktrees/
data/
+# Ignore generated OWL files in root, but keep benchmark references
+/*.owl
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 00000000..673ba7fa
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,80 @@
+# Changelog
+
+All notable changes to Open Ontologies are documented here.
+
+## [0.1.9] - 2026-03-13
+
+### Added
+- Embedding similarity as alignment signal #7 (`onto_align` now uses text+structural embeddings when available)
+- `onto_embed`, `onto_search`, `onto_similarity` MCP tools for semantic search
+- End-to-end embedding pipeline test
+- Embedding tools in architecture diagram and workflow documentation
+
+### Fixed
+- Feature gating for `tool_router` macro, clippy warnings, and tokenizer download
+- Linux binary now built on ubuntu-22.04 for wider glibc compatibility
+
+## [0.1.8] - 2026-03-12
+
+### Added
+- Poincare structural embedding trainer (Riemannian SGD for hierarchy layout)
+- ONNX text embedder with tract (bge-small-en-v1.5, downloaded on init)
+- Dual-space vector store with cosine + Poincare search and SQLite persistence
+- Poincare ball geometry module (distance, exp_map, Riemannian SGD)
+
+### Fixed
+- Release binary naming now includes target triple
+- Replaced deprecated macos-13 runner with macos-14
+
+## [0.1.6] - 2026-03-11
+
+### Added
+- Glama server metadata and author verification
+
+### Fixed
+- Docker runtime libs and removed init from Dockerfile
+
+## [0.1.5] - 2026-03-11
+
+### Fixed
+- Added build-essential and clang to Docker builder for oxrocksdb-sys compilation
+
+## [0.1.4] - 2026-03-11
+
+### Fixed
+- Installed OpenSSL and libpq dev headers in Docker builder stage
+
+## [0.1.3] - 2026-03-10
+
+### Fixed
+- Use latest Rust image in Dockerfile (dependencies need Rust 1.88+)
+
+## [0.1.2] - 2026-03-10
+
+### Fixed
+- Free disk space in Docker workflow and optimize build
+- Bumped server.json to v0.1.1
+
+## [0.1.1] - 2026-03-09
+
+### Added
+- MCP Registry server.json, Docker publish workflow, and OCI label
+- Streamable HTTP transport (`serve-http` command)
+- MCP prompts (build_ontology, validate_ontology, compare_ontologies, ingest_data, explore_ontology)
+- Dockerfile for containerized deployment
+- OntoAxiom benchmark showdown (tool-augmented vs bare LLMs)
+- Claude Code plugin package and ClawHub skill wrapper
+- Bare Claude and hybrid benchmarks for three-way comparison
+- Self-calibrating feedback for lint and enforce (dismiss 3x to suppress)
+- Ontology alignment (`onto_align`, `onto_align_feedback`) with 6 weighted signals
+- Terraform-style lifecycle: plan, apply, lock, drift, enforce, monitor, lineage
+- Data pipeline: ingest, map, SHACL validate, reason, extend
+- Clinical crosswalks (ICD-10, SNOMED, MeSH)
+- OWL2-DL SHOIQ tableaux reasoner with parallel classification
+- Design pattern enforcement (generic, BORO, value_partition)
+- Version snapshots and rollback
+- Core ontology tools: validate, load, save, query, stats, diff, lint, convert, clear, pull, push, import
+
+### Fixed
+- Clippy `io_other_error` warning breaking CI
+- MCP benchmark scoring (camelCase normalization, pair order)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..be622b25
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,91 @@
+# Contributing to Open Ontologies
+
+Thanks for your interest in contributing! This document explains how to get started.
+
+## Getting Started
+
+1. Fork the repository
+2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/open-ontologies.git`
+3. Create a feature branch: `git checkout -b feature/your-feature`
+4. Make your changes
+5. Run checks: `cargo build && cargo test && cargo clippy -- -D warnings`
+6. Push and open a PR
+
+## Development Setup
+
+**Requirements:**
+- Rust 1.85+ (edition 2024)
+- For PostgreSQL schema import: `libpq-dev`
+- For embeddings: models are downloaded automatically via `open-ontologies init`
+
+**Build:**
+```bash
+cargo build --release
+```
+
+**Test:**
+```bash
+cargo test
+```
+
+**Lint:**
+```bash
+cargo clippy -- -D warnings
+```
+
+**Audit:**
+```bash
+cargo install cargo-audit
+cargo audit
+```
+
+## Architecture
+
+The codebase is organized into domain modules under `src/`:
+
+| Module | Purpose |
+|--------|---------|
+| `server.rs` | MCP server + tool/prompt implementations |
+| `graph.rs` | Oxigraph triple store wrapper |
+| `ontology.rs` | Core RDF operations (validate, load, diff, lint) |
+| `tableaux.rs` | OWL2-DL SHOIQ tableaux reasoner |
+| `align.rs` | Cross-ontology alignment |
+| `reason.rs` | RDFS/OWL-RL inference |
+| `ingest.rs` | Data format parsing (CSV, JSON, etc.) |
+| `drift.rs` | Version comparison & rename detection |
+| `enforce.rs` | Design pattern checking |
+| `plan.rs` | Terraform-style planning |
+| `shacl.rs` | SHACL shape validation |
+| `monitor.rs` | Lifecycle monitoring |
+| `clinical.rs` | ICD-10/SNOMED/MeSH crosswalks |
+| `feedback.rs` | Self-calibrating feedback |
+| `poincare.rs` | Hyperbolic geometry (embeddings feature) |
+| `vecstore.rs` | Dual-space vector store (embeddings feature) |
+
+## Pull Requests
+
+- Keep PRs focused on a single change
+- Include tests for new functionality
+- Run `cargo clippy -- -D warnings` before submitting
+- Update CHANGELOG.md for user-facing changes
+- CI must pass (build, test, clippy, audit)
+
+## Code Style
+
+- Follow standard Rust conventions (rustfmt defaults)
+- Use `anyhow::Result` for fallible operations
+- All MCP tools use the `onto_` prefix
+- Feature-gate optional dependencies with `#[cfg(feature = "...")]`
+- Integration tests go in `tests/`, not inline
+
+## Reporting Issues
+
+Open an issue on GitHub with:
+- What you expected to happen
+- What actually happened
+- Steps to reproduce
+- Relevant error output
+
+## License
+
+By contributing, you agree that your contributions will be licensed under the MIT License.
diff --git a/Cargo.lock b/Cargo.lock
index 97224e08..e1617e0b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2345,7 +2345,7 @@ dependencies = [
[[package]]
name = "open-ontologies"
-version = "0.1.0"
+version = "0.1.9"
dependencies = [
"anyhow",
"arrow",
@@ -2368,6 +2368,7 @@ dependencies = [
"serde_yaml",
"sqlx",
"tempfile",
+ "thiserror",
"tokenizers",
"tokio",
"tokio-util",
diff --git a/Cargo.toml b/Cargo.toml
index 7f157731..6456a5cb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "open-ontologies"
-version = "0.1.0"
+version = "0.1.9"
edition = "2024"
description = "AI-native ontology engine — standalone MCP server"
license = "MIT"
@@ -22,11 +22,12 @@ schemars = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
-clap = { version = "4", features = ["derive"] }
+clap = { version = "4", features = ["derive", "env"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
chrono = "0.4"
anyhow = "1"
+thiserror = "2"
rayon = "1.10"
csv = "1"
quick-xml = { version = "0.37", features = ["serialize"] }
diff --git a/Dockerfile b/Dockerfile
index 46c45edc..561e77d7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -9,14 +9,22 @@ WORKDIR /build
COPY . .
RUN cargo build --release && strip target/release/open-ontologies
-FROM debian:bookworm-slim
+FROM gcr.io/distroless/cc-debian12
LABEL io.modelcontextprotocol.server.name="io.github.fabio-rovai/open-ontologies"
-RUN apt-get update && apt-get install -y --no-install-recommends \
- ca-certificates libssl3 libpq5 && rm -rf /var/lib/apt/lists/*
-
COPY --from=builder /build/target/release/open-ontologies /usr/local/bin/open-ontologies
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libpq.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libssl.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libcrypto.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libgssapi_krb5.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libldap.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libkrb5.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libk5crypto.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libcom_err.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libkrb5support.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/liblber.so* /usr/lib/x86_64-linux-gnu/
+COPY --from=builder /usr/lib/x86_64-linux-gnu/libsasl2.so* /usr/lib/x86_64-linux-gnu/
ENTRYPOINT ["open-ontologies"]
CMD ["serve"]
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000..a75441f6
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,66 @@
+.PHONY: build test lint audit bench bench-pizza bench-ontoaxiom bench-mushroom bench-vision bench-reasoner docker clean
+
+# ─── Development ─────────────────────────────────────────────────────────────
+
+build:
+ cargo build --release
+
+test:
+ cargo test
+
+lint:
+ cargo clippy -- -D warnings
+
+audit:
+ cargo audit
+
+check: lint test audit
+
+# ─── Benchmarks ──────────────────────────────────────────────────────────────
+
+bench: bench-pizza bench-ontoaxiom bench-mushroom bench-reasoner
+ @echo "All benchmarks complete."
+
+bench-pizza:
+ @echo "=== Pizza Ontology Benchmark ==="
+ cd benchmark && python3 pizza_benchmark.py 2>/dev/null || echo "Requires Python 3 + rdflib"
+
+bench-ontoaxiom:
+ @echo "=== OntoAxiom Benchmark ==="
+ cd benchmark/ontoaxiom && python3 run_benchmark.py 2>/dev/null || echo "Requires Python 3 + dependencies"
+
+bench-mushroom:
+ @echo "=== Mushroom Classification Benchmark ==="
+ cd benchmark/mushroom && python3 mushroom_benchmark.py 2>/dev/null || echo "Requires Python 3 + dependencies"
+
+bench-vision:
+ @echo "=== Vision Pipeline Benchmark ==="
+ cd benchmark/vision && python3 vision_benchmark.py 2>/dev/null || echo "Requires Python 3 + dependencies"
+
+bench-reasoner:
+ @echo "=== Reasoner Comparison (HermiT vs Open Ontologies) ==="
+ cd benchmark/reasoner && python3 compare_reasoners.py 2>/dev/null || echo "Requires Python 3 + Java for HermiT"
+
+# ─── Docker ──────────────────────────────────────────────────────────────────
+
+docker:
+ docker build -t open-ontologies:latest .
+
+docker-run:
+ docker run -i open-ontologies:latest serve
+
+# ─── Release ─────────────────────────────────────────────────────────────────
+
+init:
+ cargo run --release -- init
+
+serve:
+ cargo run --release -- serve
+
+serve-http:
+ cargo run --release -- serve-http
+
+# ─── Cleanup ─────────────────────────────────────────────────────────────────
+
+clean:
+ cargo clean
diff --git a/README.md b/README.md
index 0a706b5c..3171804e 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
[![CI](https://github.com/fabio-rovai/open-ontologies/actions/workflows/ci.yml/badge.svg)](https://github.com/fabio-rovai/open-ontologies/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
-[![MCP Badge](https://lobehub.com/badge/mcp/fabio-rovai-open-ontologies)](https://lobehub.com/mcp/fabio-rovai-open-ontologies)
+[![Open MCP](https://img.shields.io/badge/Open_MCP-open--ontologies-blue)](https://openmcp.org/servers/open-ontologies)
[![PitchHut](https://img.shields.io/badge/PitchHut-open--ontologies-orange)](https://www.pitchhut.com/project/open-ontologies-mcp)
[![ClawHub Skill](https://img.shields.io/badge/ClawHub-open--ontologies-7c3aed)](https://clawhub.ai/fabio-rovai/open-ontologies)
@@ -131,74 +131,9 @@ Validate it, load it, and show me the stats.
Claude generates Turtle, then automatically calls `onto_validate` → `onto_load` → `onto_stats` → `onto_lint` → `onto_query`, fixing errors along the way.
-### Demo: Database → Ontology in 3 commands
-
-```bash
-# Import a PostgreSQL schema as OWL
-open-ontologies import-schema postgres://demo:demo@localhost/shop
-
-# Classify with native OWL2-DL reasoner
-open-ontologies reason --profile owl-dl
-
-# Query the result
-open-ontologies query "SELECT ?c ?label WHERE { ?c a owl:Class . ?c rdfs:label ?label }"
-```
-
## Why This Exists
-You can ask Claude to generate an ontology in a single prompt — and it will. But single-shot generation has real problems:
-
-| Problem | What goes wrong |
-| ------- | --------------- |
-| No validation | Invalid Turtle — wrong prefixes, unclosed brackets, bad URIs |
-| No verification | No way to check counts or structure without SPARQL |
-| No iteration | Can't diff versions, lint for missing labels, or run competency questions |
-| No persistence | Ontology lives only in chat context — no versioning, no rollback |
-| No scale | Context window holds ~2,000 triples; real ontologies need a triple store |
-| No integration | Can't push to SPARQL endpoints or resolve owl:imports chains |
-
-Open Ontologies solves all of these. It's a proper RDF/SPARQL engine (Oxigraph) exposed as MCP tools that Claude calls automatically.
-
-| Layer | Tool | What it does |
-| ----- | ---- | ------------ |
-| Generation | Claude / GPT / LLaMA | Generates OWL/RDF from natural language |
-| **Validation** | **Open Ontologies** | **Validates, classifies, enforces, monitors** |
-| Storage | SPARQL endpoint / triplestore | Persists the production ontology |
-| Consumption | Your app / API / pipeline | Queries the knowledge graph |
-
-## How It Works
-
-You provide domain requirements in natural language. Claude generates Turtle/OWL, then **dynamically decides** which MCP tools to call based on what each tool returns — validating, fixing, re-loading, querying, iterating until the ontology is correct.
-
-```mermaid
-flowchart TD
- You["You — 'Build me a Pizza ontology'"]
- Claude["Claude generates Turtle"]
- Validate["onto_validate"]
- Fix["Claude fixes errors"]
- Load["onto_load"]
- Stats["onto_stats"]
- Lint["onto_lint"]
- Query["onto_query — SPARQL"]
- Save["onto_save"]
- Version["onto_version"]
-
- You --> Claude
- Claude --> Validate
- Validate -->|"syntax errors"| Fix
- Fix --> Validate
- Validate -->|"ok"| Load
- Load --> Stats
- Stats -->|"wrong counts"| Claude
- Stats -->|"ok"| Lint
- Lint -->|"issues"| Fix
- Lint -->|"clean"| Query
- Query -->|"gaps found"| Claude
- Query -->|"all correct"| Version
- Version --> Save
-```
-
-This is not a fixed pipeline. Claude is the orchestrator — it decides what to call next based on results.
+Single-shot LLM ontology generation has real problems: no validation, no verification, no iteration, no persistence, no scale, no integration. Open Ontologies solves all of these with a proper RDF/SPARQL engine (Oxigraph) exposed as MCP tools that Claude calls automatically.
## Tools
@@ -214,331 +149,17 @@ This is not a fixed pipeline. Claude is the orchestrator — it decides what to
| **Lifecycle** | `plan`, `apply`, `lock`, `drift`, `enforce`, `monitor`, `monitor-clear`, `lineage` | Terraform-style change management |
| **Alignment** | `align`, `align-feedback` | Cross-ontology class matching with self-calibrating confidence |
| **Clinical** | `crosswalk`, `enrich`, `validate-clinical` | ICD-10 / SNOMED / MeSH crosswalks |
-| **Feedback** | `lint-feedback`, `enforce-feedback` | Self-calibrating suppression — teach lint/enforce to stop repeating dismissed warnings |
-| **Embeddings** | `embed`, `search`, `similarity` | Dual-space semantic search (text + Poincaré structural) |
-| **Reasoning** | `reason` (rdfs, owl-rl, owl-rl-ext, owl-dl), `dl_explain`, `dl_check` | Native SHOIQ tableaux reasoner |
+| **Feedback** | `lint-feedback`, `enforce-feedback` | Self-calibrating suppression |
+| **Embeddings** | `embed`, `search`, `similarity` | Dual-space semantic search (text + Poincare structural) |
+| **Reasoning** | `reason`, `dl_explain`, `dl_check` | Native OWL2-DL SHOIQ tableaux reasoner |
All tools are available both as MCP tools (prefixed `onto_`) and as CLI subcommands.
-```bash
-open-ontologies <command> [args] [--pretty] [--data-dir ~/.open-ontologies]
-```
-
-## Data Pipeline
-
-Take any structured data — CSV, JSON, Parquet, XLSX, XML, YAML — and terraform it into a validated, reasoned knowledge graph.
-
-```mermaid
-flowchart LR
- Data["CSV / JSON / XLSX / ..."]
- Map["onto_map — generate mapping"]
- Ingest["onto_ingest — parse to RDF"]
- Validate["onto_shacl — check constraints"]
- Reason["onto_reason — infer new facts"]
- Query["onto_query — ask questions"]
-
- Data --> Map
- Map --> Ingest
- Ingest --> Validate
- Validate -->|violations| Map
- Validate -->|ok| Reason
- Reason --> Query
-```
-
-| Manual process | Open Ontologies equivalent |
-| -------------- | ------------------------- |
-| Domain expert defines classes by hand | `import-schema` or Claude generates OWL |
-| Analyst maps spreadsheet columns to ontology | `map` auto-generates mapping config |
-| Data engineer writes ETL to RDF | `ingest` parses CSV/JSON/Parquet/XLSX → RDF |
-| Ontologist validates data constraints | `shacl` checks cardinality, datatypes, classes |
-| Reasoner classifies instances (Protege + HermiT) | `reason` runs native OWL2-DL classification |
-| Quality reviewer checks consistency | `enforce` + `lint` + `monitor` |
-
-### Supported formats
-
-| Format | Extension |
-| ------ | --------- |
-| CSV | `.csv` |
-| JSON | `.json` |
-| NDJSON | `.ndjson` |
-| XML | `.xml` |
-| YAML | `.yaml` |
-| Excel | `.xlsx` |
-| Parquet | `.parquet` |
-
-### Mapping config
-
-The mapping bridges tabular data and RDF:
-
-```json
-{
- "base_iri": "http://www.co-ode.org/ontologies/pizza/pizza.owl#",
- "id_field": "name",
- "class": "http://www.co-ode.org/ontologies/pizza/pizza.owl#NamedPizza",
- "mappings": [
- { "field": "base", "predicate": "pizza:hasBase", "lookup": true },
- { "field": "topping1", "predicate": "pizza:hasTopping", "lookup": true },
- { "field": "price", "predicate": "pizza:hasPrice", "datatype": "xsd:decimal" }
- ]
-}
-```
-
-- **`lookup: true`** — IRI reference (links to another entity)
-- **`datatype`** — typed literal (decimal, integer, date)
-- **Neither** — plain string literal
-
-## Ontology Lifecycle
-
-Production ontologies change over time. Open Ontologies provides Terraform-style lifecycle management.
-
-```mermaid
-flowchart LR
- Plan["onto_plan"]
- Enforce["onto_enforce"]
- Apply["onto_apply"]
- Monitor["onto_monitor"]
- Drift["onto_drift"]
-
- Plan -->|"risk score"| Enforce
- Enforce -->|"compliance"| Apply
- Apply -->|"safe / migrate"| Monitor
- Monitor -->|"watchers"| Drift
- Drift -->|"velocity"| Plan
-```
-
-**Plan** — Diffs current vs proposed ontology. Reports added/removed classes, blast radius, risk score (`low`/`medium`/`high`). Locked IRIs (`onto_lock`) prevent accidental removal.
-
-**Enforce** — Design pattern checks. Built-in packs: `generic` (orphan classes, missing labels), `boro` (IES4/BORO compliance), `value_partition` (disjointness). Custom SPARQL rules supported.
-
-**Apply** — Two modes: `safe` (clear + reload) or `migrate` (add owl:equivalentClass/Property bridges for consumers).
-
-**Monitor** — SPARQL watchers with threshold alerts. Actions: `notify`, `block_next_apply`, `auto_rollback`, `log`.
-
-**Drift** — Compares versions, detects renames via Jaro-Winkler similarity, computes drift velocity. Self-calibrating confidence via SQLite feedback loop.
-
-**Lineage** — Append-only audit trail of all lifecycle operations.
-
-**Feedback** — Lint and enforce learn from your decisions. Dismiss a warning 3 times and it's suppressed; accept it once and it sticks. Same self-calibrating pattern used by `align` and `drift`.
-
-### Semantic Embeddings (Poincaré Vector Store)
-
-Open Ontologies includes a built-in dual-space vector store for semantic search and alignment:
-
-- **Text embeddings** via ONNX model (bge-small-en-v1.5) — captures label/definition similarity
-- **Structural embeddings** via Poincaré ball — captures hierarchy position (root classes near center, leaves near boundary)
-- **Product search** — combines both spaces for best results
-
-```text
-onto_load → onto_embed → onto_search "domestic animal"
-```
-
-The embedding model (~33MB) is downloaded on `open-ontologies init`. All inference runs locally via tract (pure Rust ONNX runtime) — no API keys or external services needed.
-
-| Tool | Purpose |
-| ---- | ------- |
-| `onto_embed` | Generate embeddings for all classes in the loaded ontology |
-| `onto_search` | Semantic search by natural language query |
-| `onto_similarity` | Compare two IRIs by embedding similarity |
-
-### Schema Alignment
-
-Detect `owl:equivalentClass`, `skos:exactMatch`, `rdfs:subClassOf` candidates between two ontologies using 7 weighted signals:
-
-| Signal | Weight | What it measures |
-| ------ | ------ | ---------------- |
-| Label similarity | 0.20 | Jaro-Winkler on normalized labels (camelCase split, lowercased) |
-| Property overlap | 0.15 | Jaccard on domain property + range signatures |
-| Parent overlap | 0.12 | Jaccard on rdfs:subClassOf parent local names |
-| Instance overlap | 0.12 | Jaccard on shared individuals by local name |
-| Restriction similarity | 0.12 | Jaccard on OWL restriction signatures (property→filler) |
-| Neighborhood similarity | 0.09 | Jaccard on 2-hop property neighborhood |
-| Embedding similarity | 0.20 | Cosine similarity on text embeddings (requires `onto_embed`) |
-
-When compiled without the `embeddings` feature, alignment uses the first 6 signals with the original weights (0.25, 0.20, 0.15, 0.15, 0.15, 0.10). Candidates above the confidence threshold are auto-applied to the main graph. Use `onto_align_feedback` to accept/reject candidates — feedback is stored in SQLite and used to self-calibrate signal weights over time.
-
-```bash
-# Compare two ontology files (dry run)
-open-ontologies align source.ttl target.ttl --min-confidence 0.7 --dry-run
-
-# Accept a candidate
-open-ontologies align-feedback --source http://ex.org/Dog --target http://other.org/Canine --accept
-```
-
-### Clinical Crosswalks
-
-For healthcare ontologies, three tools bridge clinical coding systems:
-
-- `onto_crosswalk` — Look up mappings between ICD-10 (diagnoses), SNOMED CT (clinical terms), and MeSH (medical literature) from a Parquet-backed crosswalk file
-- `onto_enrich` — Insert `skos:exactMatch` triples linking ontology classes to clinical codes
-- `onto_validate_clinical` — Check that class labels align with standard clinical terminology
-
-## OWL2-DL Reasoning
-
-Native Rust SHOIQ tableaux reasoner — no JVM required.
-
-| DL Feature | Symbol | OWL Construct |
-| ---------- | ------ | ------------- |
-| Atomic negation | ¬A | complementOf |
-| Conjunction | C ⊓ D | intersectionOf |
-| Disjunction | C ⊔ D | unionOf |
-| Existential | ∃R.C | someValuesFrom |
-| Universal | ∀R.C | allValuesFrom |
-| Min cardinality | ≥n R.C | minQualifiedCardinality |
-| Max cardinality | ≤n R.C | maxQualifiedCardinality |
-| Role hierarchy | R ⊑ S | subPropertyOf |
-| Transitive roles | Trans(R) | TransitiveProperty |
-| Inverse roles | R⁻ | inverseOf |
-| Symmetric roles | Sym(R) | SymmetricProperty |
-| Functional | Fun(R) | FunctionalProperty |
-| ABox reasoning | a:C | NamedIndividual |
-
-**Agent-based parallel classification:**
-
-1. **Satisfiability Agent** — Tests each class in parallel using rayon
-2. **Subsumption Agent** — Pairwise subsumption tests, pruned by told-subsumer closure
-3. **Explanation Agent** — Traces clash derivations for unsatisfiable classes
-4. **ABox Agent** — Individual consistency and type inference
-
-| Reasoner | Language | JVM | Parallel | SHOIQ |
-| -------- | -------- | --- | -------- | ----- |
-| **Open Ontologies** | Rust | No | Yes (rayon) | Yes |
-| HermiT | Java | Yes | No | Yes |
-| Pellet | Java | Yes | No | Yes |
-
-## Benchmarks
-
-### Ontology Generation
-
-#### Pizza Ontology — Manchester Tutorial
-
-The [Manchester Pizza Tutorial](https://www.michaeldebellis.com/post/new-protege-pizza-tutorial) is the most widely used OWL teaching material. Students build a Pizza ontology in Protege over ~4 hours.
-
-**Input:** One sentence — "Build a Pizza ontology following the Manchester tutorial specification."
-
-| Metric | Reference (Protege) | AI-Generated | Coverage |
-| ------ | ------------------- | ------------ | -------- |
-| Classes | 99 | 95 | **96%** |
-| Properties | 8 | 8 | **100%** |
-| Toppings | 49 | 49 | **100%** |
-| Named Pizzas | 24 | 24 | **100%** |
-| Time | ~4 hours | ~5 minutes | |
-
-The 4 missing classes are teaching artifacts (e.g., `UnclosedPizza`) that exist only to demonstrate OWL syntax variants. Files: [`benchmark/`](benchmark/)
-
-#### IES4 Building Domain — BORO/4D
-
-The [IES4 standard](https://github.com/dstl/IES4) is the UK government's Information Exchange Standard for defence/intelligence. Built on BORO methodology and 4D perdurantist modeling.
-
-**Input:** Three context documents — BORO/4D methodology, structural requirements, and a domain brief with 9 competency questions.
-
-| Metric | Value |
-| ------ | ----- |
-| Compliance checks | **86/86 passed (100%)** |
-| Triples | 318 |
-| Classes | 36 |
-| Properties | 12 |
-| Generation | One pass — valid Turtle directly |
-
-Files: [`benchmark/`](benchmark/)
-
-### Ontology Extension — Pizza Menu Mapping
-
-Given the Manchester Pizza OWL (expert-crafted reference) and a 13-row restaurant CSV, map the data into the ontology.
-
-| Metric | Value |
-| ------ | ----- |
-| Topping coverage vs reference | **94%** (62/66 matched) |
-| IRI accuracy (naive) | 5% |
-| IRI accuracy (Claude-refined) | **94–100%** |
-| Vegetarian classification | **92%** (100% with refined mapping) |
-
-The 4 mismatches are naming convention gaps (e.g., "Anchovy" vs `AnchoviesTopping`). Files: [`benchmark/`](benchmark/)
-
-### Mushroom Classification — OWL Reasoning vs Expert Labels
-
-**Dataset:** UCI Mushroom Dataset — 8,124 specimens classified by mycology experts.
-
-| Metric | Value |
-| ------ | ----- |
-| Accuracy | **98.33%** |
-| Recall (poisonous) | **100%** — zero toxic mushrooms missed |
-| False positives | 136 (1.67%) — conservative by design |
-| False negatives | **0** |
-| Classification rules | 6 OWL axioms |
-
-The reasoner is conservative — it flags safe mushrooms as suspicious before ever classifying a toxic one as edible. Files: [`benchmark/mushroom/`](benchmark/mushroom/)
-
-### Vision Benchmark — Image to Knowledge Graph
-
-**Dataset:** 10 real photographs with manually annotated ground truth. RDF pipeline data extracted directly from TTL files; triple counts from `onto_validate`.
-
-| Metric | Manual | Pure Claude | RDF Pipeline |
-| ------ | ------ | ----------- | ------------ |
-| Object Recall | 100% | 89% | **95%** |
-| Category Recall | 100% | 79% | 32% |
-| Total RDF Triples | 0 | 0 | **2,540** |
-| skos:altLabel Synonyms | 0 | 0 | **612** |
-| SPARQL Queryable | No | No | **Yes** |
-| Confidence Scores | No | No | **Yes** |
-| Effort per image | ~2 min | ~8 sec | ~8 sec |
-
-Category recall is lower because TTL files use fine-grained categories ("animal body part", "vehicle part") while ground truth uses broad labels ("animal", "vehicle"). The value is in queryability — you can't ask "find all images containing animals near water" with flat text labels.
-
-The benchmark runs the full MCP pipeline: `onto_clear` → `onto_validate` (×10) → `onto_load` (×10) → `onto_stats` → `onto_lint` (×10) → `onto_query` (×6) via the real MCP server using the official MCP Python SDK over JSON-RPC 2.0 stdio. Files: [`benchmark/vision/`](benchmark/vision/)
-
-### OntoAxiom Benchmark — Three Approaches to Axiom Identification
-
-[OntoAxiom](https://arxiv.org/abs/2512.05594) tests LLM axiom identification across 9 ontologies and 3,042 ground truth axioms. We test three approaches:
-
-| Approach | Input | F1 | vs o1 |
-| -------- | ----- | -- | ----- |
-| o1 (paper's best) | Name lists only | 0.197 | — |
-| **Bare Claude Opus** | **Name lists only** | **0.431** | **+119%** |
-| **MCP extraction** | **Full OWL files** | **0.717** | **+264%** |
-
-MCP extraction per axiom type:
-
-| Axiom Type | MCP Extraction | o1 (paper) | Improvement |
-| ---------- | -------------- | ---------- | ----------- |
-| subClassOf | **0.835** | 0.359 | +133% |
-| disjointWith | **0.976** | 0.095 | +927% |
-| domain | **0.662** | 0.038 | +1642% |
-| range | **0.565** | 0.030 | +1783% |
-| subPropertyOf | **0.617** | 0.106 | +482% |
-| **OVERALL** | **0.717** | **0.197** | **+264%** |
-
-13 individual results scored PERFECT (F1 = 1.000). Full writeup: [`benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md`](benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md)
-
-### Reasoning Performance — HermiT vs Open Ontologies
-
-Java 25, HermiT 1.4.3.456, OWL API 4.5.29.
-
-**Pizza Ontology (4,179 triples)**
-
-| Tool | Time | Result |
-| ---- | ---- | ------ |
-| HermiT | 213ms | 312 subsumptions |
-| Open Ontologies (OWL-RL) | 43ms | Load + rule-based inference |
-| Open Ontologies (OWL-DL) | 19ms | Consistency check, SHOIQ tableaux |
-
-**LUBM Scaling (load + reason cycle)**
-
-| Axioms | Open Ontologies | HermiT | Speedup |
-| ------ | --------------- | ------- | ------- |
-| 1,000 | 15ms | 112ms | **7.5x** |
-| 5,000 | 14ms | 410ms | **29x** |
-| 10,000 | 14ms | 1,200ms | **86x** |
-| 50,000 | 15ms | 24,490ms | **1,633x** |
-
-OO's time stays flat — OWL-RL is SPARQL-based rule application, not tableaux expansion. HermiT's tableaux algorithm grows super-linearly with ontology size. Both produce correct results; different reasoning strategies for different use cases.
-
-Scripts and results: [`benchmark/reasoner/`](benchmark/reasoner/)
-
## Architecture
```mermaid
flowchart TD
- Claude["🤖 Claude / LLM"]
+ Claude["Claude / LLM"]
MCP["Open Ontologies MCP Server"]
subgraph Core["Core Engine"]
@@ -559,17 +180,29 @@ flowchart TD
Tools --> Core
```
+## Documentation
+
+| Topic | Link |
+| ----- | ---- |
+| Data Pipeline | [docs/data-pipeline.md](docs/data-pipeline.md) |
+| Ontology Lifecycle | [docs/lifecycle.md](docs/lifecycle.md) |
+| Schema Alignment | [docs/alignment.md](docs/alignment.md) |
+| OWL2-DL Reasoning | [docs/reasoning.md](docs/reasoning.md) |
+| Semantic Embeddings | [docs/embeddings.md](docs/embeddings.md) |
+| Clinical Crosswalks | [docs/clinical.md](docs/clinical.md) |
+| Benchmarks | [docs/benchmarks.md](docs/benchmarks.md) |
+| Contributing | [CONTRIBUTING.md](CONTRIBUTING.md) |
+| Changelog | [CHANGELOG.md](CHANGELOG.md) |
+
## Stack
- **Rust** (edition 2024) — single binary, no JVM
- **Oxigraph 0.4** — pure Rust RDF/SPARQL engine
- **rmcp** — MCP protocol implementation
-- **SQLite** (rusqlite) — state, versions, lineage, monitor, enforcer rules, drift feedback, embeddings
+- **SQLite** (rusqlite) — state, versions, lineage, feedback, embeddings
- **Apache Arrow/Parquet** — clinical crosswalk file format
-- **tract-onnx** — pure Rust ONNX runtime for text embeddings (optional, `embeddings` feature)
-- **tokenizers** — HuggingFace tokenizer for bge-small-en-v1.5 (optional, `embeddings` feature)
-
-**Optional companion:** [OpenCheir](https://github.com/fabio-rovai/opencheir) adds workflow enforcement, audit trails, and multi-agent orchestration.
+- **tract-onnx** — pure Rust ONNX runtime for text embeddings (optional)
+- **tokenizers** — HuggingFace tokenizer (optional)
## License
diff --git a/docs/alignment.md b/docs/alignment.md
new file mode 100644
index 00000000..3fb48e9e
--- /dev/null
+++ b/docs/alignment.md
@@ -0,0 +1,27 @@
+# Schema Alignment
+
+Detect `owl:equivalentClass`, `skos:exactMatch`, `rdfs:subClassOf` candidates between two ontologies using 7 weighted signals:
+
+| Signal | Weight | What it measures |
+| ------ | ------ | ---------------- |
+| Label similarity | 0.20 | Jaro-Winkler on normalized labels (camelCase split, lowercased) |
+| Property overlap | 0.15 | Jaccard on domain property + range signatures |
+| Parent overlap | 0.12 | Jaccard on rdfs:subClassOf parent local names |
+| Instance overlap | 0.12 | Jaccard on shared individuals by local name |
+| Restriction similarity | 0.12 | Jaccard on OWL restriction signatures (property->filler) |
+| Neighborhood similarity | 0.09 | Jaccard on 2-hop property neighborhood |
+| Embedding similarity | 0.20 | Cosine similarity on text embeddings (requires `onto_embed`) |
+
+When compiled without the `embeddings` feature, alignment uses the first 6 signals with the original weights (0.25, 0.20, 0.15, 0.15, 0.15, 0.10).
+
+Candidates above the confidence threshold are auto-applied to the main graph. Use `onto_align_feedback` to accept/reject candidates — feedback is stored in SQLite and used to self-calibrate signal weights over time.
+
+## CLI Usage
+
+```bash
+# Compare two ontology files (dry run)
+open-ontologies align source.ttl target.ttl --min-confidence 0.7 --dry-run
+
+# Accept a candidate
+open-ontologies align-feedback --source http://ex.org/Dog --target http://other.org/Canine --accept
+```
diff --git a/docs/benchmarks.md b/docs/benchmarks.md
new file mode 100644
index 00000000..e22c3f0e
--- /dev/null
+++ b/docs/benchmarks.md
@@ -0,0 +1,105 @@
+# Benchmarks
+
+## Ontology Generation
+
+### Pizza Ontology — Manchester Tutorial
+
+The [Manchester Pizza Tutorial](https://www.michaeldebellis.com/post/new-protege-pizza-tutorial) is the most widely used OWL teaching material. Students build a Pizza ontology in Protege over ~4 hours.
+
+**Input:** One sentence — "Build a Pizza ontology following the Manchester tutorial specification."
+
+| Metric | Reference (Protege) | AI-Generated | Coverage |
+| ------ | ------------------- | ------------ | -------- |
+| Classes | 99 | 95 | **96%** |
+| Properties | 8 | 8 | **100%** |
+| Toppings | 49 | 49 | **100%** |
+| Named Pizzas | 24 | 24 | **100%** |
+| Time | ~4 hours | ~5 minutes | |
+
+The 4 missing classes are teaching artifacts (e.g., `UnclosedPizza`) that exist only to demonstrate OWL syntax variants. Files: [`benchmark/`](../benchmark/)
+
+### IES4 Building Domain — BORO/4D
+
+The [IES4 standard](https://github.com/dstl/IES4) is the UK government's Information Exchange Standard for defence/intelligence.
+
+| Metric | Value |
+| ------ | ----- |
+| Compliance checks | **86/86 passed (100%)** |
+| Triples | 318 |
+| Classes | 36 |
+| Properties | 12 |
+| Generation | One pass — valid Turtle directly |
+
+## Ontology Extension — Pizza Menu Mapping
+
+Given the Manchester Pizza OWL and a 13-row restaurant CSV, map the data into the ontology.
+
+| Metric | Value |
+| ------ | ----- |
+| Topping coverage vs reference | **94%** (62/66 matched) |
+| IRI accuracy (Claude-refined) | **94-100%** |
+| Vegetarian classification | **92%** (100% with refined mapping) |
+
+## Mushroom Classification — OWL Reasoning vs Expert Labels
+
+**Dataset:** UCI Mushroom Dataset — 8,124 specimens classified by mycology experts.
+
+| Metric | Value |
+| ------ | ----- |
+| Accuracy | **98.33%** |
+| Recall (poisonous) | **100%** — zero toxic mushrooms missed |
+| False positives | 136 (1.67%) — conservative by design |
+| False negatives | **0** |
+| Classification rules | 6 OWL axioms |
+
+## Vision Benchmark — Image to Knowledge Graph
+
+**Dataset:** 10 real photographs with manually annotated ground truth.
+
+| Metric | Manual | Pure Claude | RDF Pipeline |
+| ------ | ------ | ----------- | ------------ |
+| Object Recall | 100% | 89% | **95%** |
+| Total RDF Triples | 0 | 0 | **2,540** |
+| SPARQL Queryable | No | No | **Yes** |
+
+## OntoAxiom Benchmark — Three Approaches
+
+[OntoAxiom](https://arxiv.org/abs/2512.05594) tests LLM axiom identification across 9 ontologies and 3,042 ground truth axioms.
+
+| Approach | F1 | vs o1 |
+| -------- | -- | ----- |
+| o1 (paper's best) | 0.197 | — |
+| **Bare Claude Opus** | **0.431** | **+119%** |
+| **MCP extraction** | **0.717** | **+264%** |
+
+Full writeup: [`benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md`](../benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md)
+
+## Reasoning Performance — HermiT vs Open Ontologies
+
+**Pizza Ontology (4,179 triples)**
+
+| Tool | Time | Result |
+| ---- | ---- | ------ |
+| HermiT | 213ms | 312 subsumptions |
+| Open Ontologies (OWL-RL) | 43ms | Load + rule-based inference |
+| Open Ontologies (OWL-DL) | 19ms | Consistency check, SHOIQ tableaux |
+
+**LUBM Scaling (load + reason cycle)**
+
+| Axioms | Open Ontologies | HermiT | Speedup |
+| ------ | --------------- | ------- | ------- |
+| 1,000 | 15ms | 112ms | **7.5x** |
+| 5,000 | 14ms | 410ms | **29x** |
+| 10,000 | 14ms | 1,200ms | **86x** |
+| 50,000 | 15ms | 24,490ms | **1,633x** |
+
+Scripts and results: [`benchmark/reasoner/`](../benchmark/reasoner/)
+
+## Running Benchmarks
+
+```bash
+make bench # Run all benchmarks
+make bench-pizza # Just Pizza
+make bench-ontoaxiom # Just OntoAxiom
+make bench-reasoner # Just reasoner comparison
+```
diff --git a/docs/clinical.md b/docs/clinical.md
new file mode 100644
index 00000000..10093dc7
--- /dev/null
+++ b/docs/clinical.md
@@ -0,0 +1,30 @@
+# Clinical Crosswalks
+
+For healthcare ontologies, three tools bridge clinical coding systems:
+
+- `onto_crosswalk` — Look up mappings between ICD-10 (diagnoses), SNOMED CT (clinical terms), and MeSH (medical literature) from a Parquet-backed crosswalk file
+- `onto_enrich` — Insert `skos:exactMatch` triples linking ontology classes to clinical codes
+- `onto_validate_clinical` — Check that class labels align with standard clinical terminology
+
+## Setup
+
+Build the crosswalk data file:
+
+```bash
+python3 scripts/build_crosswalks.py
+```
+
+This creates `data/crosswalks.parquet` from public terminology sources.
+
+## Usage
+
+```bash
+# Look up a code
+open-ontologies crosswalk I10 --system ICD10
+
+# Enrich a class with a mapping
+open-ontologies enrich http://example.org/Hypertension I10 --system ICD10
+
+# Validate all labels against clinical terms
+open-ontologies validate-clinical
+```
diff --git a/docs/data-pipeline.md b/docs/data-pipeline.md
new file mode 100644
index 00000000..da60a3ba
--- /dev/null
+++ b/docs/data-pipeline.md
@@ -0,0 +1,75 @@
+# Data Pipeline
+
+Take any structured data — CSV, JSON, Parquet, XLSX, XML, YAML — and terraform it into a validated, reasoned knowledge graph.
+
+```mermaid
+flowchart LR
+ Data["CSV / JSON / XLSX / ..."]
+ Map["onto_map — generate mapping"]
+ Ingest["onto_ingest — parse to RDF"]
+ Validate["onto_shacl — check constraints"]
+ Reason["onto_reason — infer new facts"]
+ Query["onto_query — ask questions"]
+
+ Data --> Map
+ Map --> Ingest
+ Ingest --> Validate
+ Validate -->|violations| Map
+ Validate -->|ok| Reason
+ Reason --> Query
+```
+
+| Manual process | Open Ontologies equivalent |
+| -------------- | ------------------------- |
+| Domain expert defines classes by hand | `import-schema` or Claude generates OWL |
+| Analyst maps spreadsheet columns to ontology | `map` auto-generates mapping config |
+| Data engineer writes ETL to RDF | `ingest` parses CSV/JSON/Parquet/XLSX → RDF |
+| Ontologist validates data constraints | `shacl` checks cardinality, datatypes, classes |
+| Reasoner classifies instances (Protege + HermiT) | `reason` runs native OWL2-DL classification |
+| Quality reviewer checks consistency | `enforce` + `lint` + `monitor` |
+
+## Supported Formats
+
+| Format | Extension |
+| ------ | --------- |
+| CSV | `.csv` |
+| JSON | `.json` |
+| NDJSON | `.ndjson` |
+| XML | `.xml` |
+| YAML | `.yaml` |
+| Excel | `.xlsx` |
+| Parquet | `.parquet` |
+
+## Mapping Config
+
+The mapping bridges tabular data and RDF:
+
+```json
+{
+ "base_iri": "http://www.co-ode.org/ontologies/pizza/pizza.owl#",
+ "id_field": "name",
+ "class": "http://www.co-ode.org/ontologies/pizza/pizza.owl#NamedPizza",
+ "mappings": [
+ { "field": "base", "predicate": "pizza:hasBase", "lookup": true },
+ { "field": "topping1", "predicate": "pizza:hasTopping", "lookup": true },
+ { "field": "price", "predicate": "pizza:hasPrice", "datatype": "xsd:decimal" }
+ ]
+}
+```
+
+- **`lookup: true`** — IRI reference (links to another entity)
+- **`datatype`** — typed literal (decimal, integer, date)
+- **Neither** — plain string literal
+
+## Demo: Database to Ontology in 3 Commands
+
+```bash
+# Import a PostgreSQL schema as OWL
+open-ontologies import-schema postgres://demo:demo@localhost/shop
+
+# Classify with native OWL2-DL reasoner
+open-ontologies reason --profile owl-dl
+
+# Query the result
+open-ontologies query "SELECT ?c ?label WHERE { ?c a owl:Class . ?c rdfs:label ?label }"
+```
diff --git a/docs/embeddings.md b/docs/embeddings.md
new file mode 100644
index 00000000..a265f938
--- /dev/null
+++ b/docs/embeddings.md
@@ -0,0 +1,29 @@
+# Semantic Embeddings (Poincare Vector Store)
+
+Open Ontologies includes a built-in dual-space vector store for semantic search and alignment:
+
+- **Text embeddings** via ONNX model (bge-small-en-v1.5) — captures label/definition similarity
+- **Structural embeddings** via Poincare ball — captures hierarchy position (root classes near center, leaves near boundary)
+- **Product search** — combines both spaces for best results
+
+```text
+onto_load → onto_embed → onto_search "domestic animal"
+```
+
+The embedding model (~33MB) is downloaded on `open-ontologies init`. All inference runs locally via tract (pure Rust ONNX runtime) — no API keys or external services needed.
+
+## Tools
+
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_embed` | Generate embeddings for all classes in the loaded ontology |
+| `onto_search` | Semantic search by natural language query |
+| `onto_similarity` | Compare two IRIs by embedding similarity |
+
+## Search Modes
+
+| Mode | What it uses |
+| ---- | ------------ |
+| `text` | Cosine similarity on text embeddings only |
+| `structure` | Poincare distance on structural embeddings only |
+| `product` | Weighted combination of both (default, alpha=0.5) |
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
new file mode 100644
index 00000000..de0f421c
--- /dev/null
+++ b/docs/lifecycle.md
@@ -0,0 +1,46 @@
+# Ontology Lifecycle
+
+Production ontologies change over time. Open Ontologies provides Terraform-style lifecycle management.
+
+```mermaid
+flowchart LR
+ Plan["onto_plan"]
+ Enforce["onto_enforce"]
+ Apply["onto_apply"]
+ Monitor["onto_monitor"]
+ Drift["onto_drift"]
+
+ Plan -->|"risk score"| Enforce
+ Enforce -->|"compliance"| Apply
+ Apply -->|"safe / migrate"| Monitor
+ Monitor -->|"watchers"| Drift
+ Drift -->|"velocity"| Plan
+```
+
+## Plan
+
+Diffs current vs proposed ontology. Reports added/removed classes, blast radius, risk score (`low`/`medium`/`high`). Locked IRIs (`onto_lock`) prevent accidental removal.
+
+## Enforce
+
+Design pattern checks. Built-in packs: `generic` (orphan classes, missing labels), `boro` (IES4/BORO compliance), `value_partition` (disjointness). Custom SPARQL rules supported.
+
+## Apply
+
+Two modes: `safe` (clear + reload) or `migrate` (add owl:equivalentClass/Property bridges for consumers).
+
+## Monitor
+
+SPARQL watchers with threshold alerts. Actions: `notify`, `block_next_apply`, `auto_rollback`, `log`.
+
+## Drift
+
+Compares versions, detects renames via Jaro-Winkler similarity, computes drift velocity. Self-calibrating confidence via SQLite feedback loop.
+
+## Lineage
+
+Append-only audit trail of all lifecycle operations.
+
+## Feedback
+
+Lint and enforce learn from your decisions. Dismiss a warning 3 times and it's suppressed; accept it once and it sticks. Same self-calibrating pattern used by `align` and `drift`.
diff --git a/docs/reasoning.md b/docs/reasoning.md
new file mode 100644
index 00000000..28e65845
--- /dev/null
+++ b/docs/reasoning.md
@@ -0,0 +1,49 @@
+# OWL2-DL Reasoning
+
+Native Rust SHOIQ tableaux reasoner — no JVM required.
+
+| DL Feature | Symbol | OWL Construct |
+| ---------- | ------ | ------------- |
+| Atomic negation | not A | complementOf |
+| Conjunction | C and D | intersectionOf |
+| Disjunction | C or D | unionOf |
+| Existential | exists R.C | someValuesFrom |
+| Universal | forall R.C | allValuesFrom |
+| Min cardinality | >=n R.C | minQualifiedCardinality |
+| Max cardinality | <=n R.C | maxQualifiedCardinality |
+| Role hierarchy | R subprop S | subPropertyOf |
+| Transitive roles | Trans(R) | TransitiveProperty |
+| Inverse roles | R inverse | inverseOf |
+| Symmetric roles | Sym(R) | SymmetricProperty |
+| Functional | Fun(R) | FunctionalProperty |
+| ABox reasoning | a:C | NamedIndividual |
+
+## Agent-Based Parallel Classification
+
+1. **Satisfiability Agent** — Tests each class in parallel using rayon
+2. **Subsumption Agent** — Pairwise subsumption tests, pruned by told-subsumer closure
+3. **Explanation Agent** — Traces clash derivations for unsatisfiable classes
+4. **ABox Agent** — Individual consistency and type inference
+
+| Reasoner | Language | JVM | Parallel | SHOIQ |
+| -------- | -------- | --- | -------- | ----- |
+| **Open Ontologies** | Rust | No | Yes (rayon) | Yes |
+| HermiT | Java | Yes | No | Yes |
+| Pellet | Java | Yes | No | Yes |
+
+## Reasoning Profiles
+
+| Profile | What it does |
+| ------- | ------------ |
+| `rdfs` | Subclass closure, domain/range inference |
+| `owl-rl` | + transitive/symmetric/inverse, sameAs, equivalentClass |
+| `owl-rl-ext` | + someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf |
+| `owl-dl` | Full SHOIQ tableaux: satisfiability, classification, ABox reasoning |
+
+## Tools
+
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_reason` | Run inference with selected profile |
+| `onto_dl_explain` | Explain why a class is unsatisfiable (clash trace) |
+| `onto_dl_check` | Check if one class is subsumed by another |
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 00000000..717d01c9
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,39 @@
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum OntologyError {
+ #[error("parse error: {0}")]
+ Parse(String),
+
+ #[error("validation error: {0}")]
+ Validation(String),
+
+ #[error("SPARQL error: {0}")]
+ Sparql(String),
+
+ #[error("store error: {0}")]
+ Store(String),
+
+ #[error("IO error: {0}")]
+ Io(#[from] std::io::Error),
+
+ #[error("serialization error: {0}")]
+ Serialization(String),
+
+ #[error("not found: {0}")]
+ NotFound(String),
+
+ #[error("alignment error: {0}")]
+ Alignment(String),
+
+ #[error("reasoning error: {0}")]
+ Reasoning(String),
+
+ #[error("configuration error: {0}")]
+ Config(String),
+
+ #[error("feature not enabled: {0}")]
+ FeatureDisabled(String),
+}
+
+pub type Result<T> = std::result::Result<T, OntologyError>;
diff --git a/src/inputs.rs b/src/inputs.rs
new file mode 100644
index 00000000..2d6400c8
--- /dev/null
+++ b/src/inputs.rs
@@ -0,0 +1,342 @@
+use schemars::JsonSchema;
+use serde::Deserialize;
+
+// ─── MCP tool input structs ─────────────────────────────────────────────────
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoValidateInput {
+ /// Path to an RDF file OR inline Turtle content
+ pub input: String,
+ /// If true, treat input as inline content rather than a file path
+ pub inline: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoConvertInput {
+ /// Path to source RDF file
+ pub path: String,
+ /// Target format: turtle, ntriples, rdfxml, nquads, trig
+ pub to: String,
+ /// Optional output file path (if omitted, returns content)
+ pub output: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoLoadInput {
+ /// Path to RDF file to load into the in-memory store
+ pub path: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoQueryInput {
+ /// SPARQL query string
+ pub query: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoSaveInput {
+ /// Output file path
+ pub path: String,
+ /// Format: turtle, ntriples, rdfxml, nquads, trig
+ pub format: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoDiffInput {
+ /// Path to the old/original ontology file
+ pub old_path: String,
+ /// Path to the new/modified ontology file
+ pub new_path: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoLintInput {
+ /// Path to RDF file to lint, OR inline Turtle content
+ pub input: String,
+ /// If true, treat input as inline content
+ pub inline: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoPullInput {
+ /// Remote URL or SPARQL endpoint to fetch ontology from
+ pub url: String,
+ /// If true, treat url as a SPARQL endpoint and run a CONSTRUCT query
+ pub sparql: Option<bool>,
+ /// Optional SPARQL CONSTRUCT query (required if sparql=true)
+ pub query: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoPushInput {
+ /// Remote SPARQL endpoint URL
+ pub endpoint: String,
+ /// Optional named graph IRI
+ pub graph: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoImportInput {
+ /// Resolve and load all owl:imports from the currently loaded ontology
+ pub max_depth: Option<usize>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoVersionInput {
+ /// Version label (e.g. "v1.0", "draft-2026-03-09")
+ pub label: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoRollbackInput {
+ /// Version label to restore
+ pub label: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoIngestInput {
+ /// Path to the data file (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet)
+ pub path: String,
+ /// Data format (auto-detected from extension if omitted): csv, json, ndjson, xml, yaml, xlsx, parquet
+ pub format: Option<String>,
+ /// Mapping config as JSON string or path to mapping JSON file
+ pub mapping: Option<String>,
+ /// If true, treat mapping as inline JSON (default: false = file path)
+ pub inline_mapping: Option<bool>,
+ /// Base IRI for generated instances (default: http://example.org/data/)
+ pub base_iri: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoMapInput {
+ /// Path to sample data file to generate mapping for
+ pub data_path: String,
+ /// Data format (auto-detected if omitted)
+ pub format: Option<String>,
+ /// Optional path to save the generated mapping config
+ pub save_path: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoShaclInput {
+ /// Path to SHACL shapes file OR inline SHACL Turtle content
+ pub shapes: String,
+ /// If true, treat shapes as inline Turtle content
+ pub inline: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoReasonInput {
+ /// Reasoning profile: rdfs (default), owl-rl
+ pub profile: Option<String>,
+ /// If true (default), add inferred triples to the store. If false, dry-run only.
+ pub materialize: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoDlExplainInput {
+ /// IRI of the class to explain unsatisfiability for
+ pub class_iri: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoDlCheckInput {
+ /// IRI of the sub-class (the more specific class)
+ pub sub_class: String,
+ /// IRI of the super-class (the more general class)
+ pub super_class: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoExtendInput {
+ /// Path to the data file
+ pub data_path: String,
+ /// Data format (auto-detected if omitted)
+ pub format: Option<String>,
+ /// Mapping config (inline JSON or file path)
+ pub mapping: Option<String>,
+ /// If true, treat mapping as inline JSON
+ pub inline_mapping: Option<bool>,
+ /// Base IRI for generated instances
+ pub base_iri: Option<String>,
+ /// Path to SHACL shapes file or inline Turtle
+ pub shapes: Option<String>,
+ /// If true, treat shapes as inline Turtle
+ pub inline_shapes: Option<bool>,
+ /// Reasoning profile (rdfs, owl-rl). Omit to skip reasoning.
+ pub reason_profile: Option<String>,
+ /// If true (default), stop pipeline on SHACL violations
+ pub stop_on_violations: Option<bool>,
+}
+
+// ─── v2 input structs ───────────────────────────────────────────────────────
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoPlanInput {
+ /// New ontology as inline Turtle content
+ pub new_turtle: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoApplyInput {
+ /// Apply mode: "safe" (default), "force" (ignores monitor), "migrate" (adds bridges)
+ pub mode: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoLockInput {
+ /// IRIs to lock (prevent removal)
+ pub iris: Vec<String>,
+ /// Reason for locking
+ pub reason: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoDriftInput {
+ /// First version as inline Turtle
+ pub version_a: String,
+ /// Second version as inline Turtle
+ pub version_b: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoEnforceInput {
+ /// Rule pack to enforce: "generic", "boro", "value_partition", or custom pack name
+ pub rule_pack: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoMonitorInput {
+ /// Inline JSON array of watchers to add, or omit to just run existing watchers
+ pub watchers: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoCrosswalkInput {
+ /// Clinical code to look up (e.g. "I10")
+ pub code: String,
+ /// Source system (e.g. "ICD10", "SNOMED", "MeSH")
+ pub source_system: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoEnrichInput {
+ /// IRI of the ontology class to enrich
+ pub class_iri: String,
+ /// Clinical code to map to
+ pub code: String,
+ /// Code system (e.g. "ICD10")
+ pub system: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoLineageInput {
+ /// Session ID to query (omit for current session)
+ pub session_id: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoImportSchemaInput {
+ /// Database connection string (e.g. postgres://user:pass@host/db)
+ pub connection: String,
+ /// Base IRI for generated classes (default: http://example.org/db/)
+ pub base_iri: Option<String>,
+}
+
+#[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,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoLintFeedbackInput {
+ /// The lint rule ID (e.g. "missing_label", "missing_comment", "missing_domain", "missing_range")
+ pub rule_id: String,
+ /// The entity IRI that triggered the lint issue
+ pub entity: String,
+ /// true = this is a real issue, false = dismiss/ignore
+ pub accepted: bool,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoEnforceFeedbackInput {
+ /// The enforce rule ID (e.g. "orphan_class", "missing_domain", "missing_range", "missing_label", or custom rule ID)
+ pub rule_id: String,
+ /// The entity IRI that triggered the violation
+ pub entity: String,
+ /// true = this is a real violation, false = dismiss/override
+ pub accepted: bool,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoEmbedInput {
+ /// Structural embedding dimension. Default: 32
+ pub struct_dim: Option<usize>,
+ /// Structural training epochs. Default: 100
+ pub struct_epochs: Option<usize>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoSearchInput {
+ /// Natural language query
+ pub query: String,
+ /// Number of results. Default: 10
+ pub top_k: Option<usize>,
+ /// Search mode: "text", "structure", or "product". Default: "product"
+ pub mode: Option<String>,
+ /// Weight for text vs structure in product mode (0.0-1.0). Default: 0.5
+ pub alpha: Option<f32>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoSimilarityInput {
+ /// First IRI
+ pub iri_a: String,
+ /// Second IRI
+ pub iri_b: String,
+}
+
+// ─── Prompt input structs ───────────────────────────────────────────────────
+
+#[derive(Deserialize, JsonSchema)]
+pub struct BuildOntologyInput {
+ /// Description of the domain to model (e.g. "A pizza ontology with toppings, bases, and named pizzas")
+ pub domain: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct ValidateOntologyInput {
+ /// Path to the ontology file to validate
+ pub path: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct CompareOntologiesInput {
+ /// Path to the old/original ontology file
+ pub old_path: String,
+ /// Path to the new/modified ontology file
+ pub new_path: String,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct IngestDataInput {
+ /// Path to the data file (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet)
+ pub data_path: String,
+}
diff --git a/src/lib.rs b/src/lib.rs
index 41ee1072..6c7f6ac9 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod error;
pub mod align;
pub mod config;
pub mod clinical;
@@ -6,6 +7,7 @@ pub mod enforce;
pub mod feedback;
pub mod graph;
pub mod ingest;
+pub mod inputs;
pub mod lineage;
pub mod monitor;
pub mod plan;
diff --git a/src/main.rs b/src/main.rs
index ec1333f9..33e11a25 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -48,6 +48,9 @@ enum Commands {
/// Port to bind to
#[arg(long, default_value = "8080")]
port: u16,
+ /// Optional bearer token for authentication
+ #[arg(long, env = "OPEN_ONTOLOGIES_TOKEN")]
+ token: Option<String>,
},
// ─── Core ontology ────────────────────────────────────────────
@@ -294,6 +297,20 @@ fn output_json(value: &serde_json::Value, pretty: bool) {
}
}
+/// Print a JSON string result, with optional pretty-printing.
+/// Handles the common pattern of domain functions returning String results.
+fn output_result(result: &str, pretty: bool) {
+ if 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);
+ }
+}
+
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
@@ -374,7 +391,7 @@ async fn main() -> anyhow::Result<()> {
let service = server.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
}
- Commands::ServeHttp { config: config_path, host, port } => {
+ Commands::ServeHttp { config: config_path, host, port, token } => {
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService,
session::local::LocalSessionManager,
@@ -417,9 +434,31 @@ async fn main() -> anyhow::Result<()> {
);
let router = axum::Router::new().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()
+ }
+ }
+ }))
+ } else {
+ router
+ };
let addr = format!("{host}:{port}");
let listener = tokio::net::TcpListener::bind(&addr).await?;
eprintln!("Open Ontologies MCP server listening on http://{addr}/mcp");
+ if token.is_some() {
+ eprintln!(" Authentication: bearer token required");
+ }
axum::serve(listener, router)
.with_graceful_shutdown(async move { ct.cancelled_owned().await })
@@ -476,15 +515,7 @@ 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));
- if cli.pretty {
- if let Ok(v) = serde_json::from_str::<serde_json::Value>(&stats_json) {
- println!("{}", serde_json::to_string_pretty(&v).unwrap());
- } else {
- println!("{}", stats_json);
- }
- } else {
- println!("{}", stats_json);
- }
+ output_result(&stats_json, cli.pretty);
}
Commands::Query { query } => {
let (_db, graph) = setup(&cli.data_dir)?;
@@ -496,30 +527,14 @@ async fn main() -> anyhow::Result<()> {
query
};
let result = graph.sparql_select(&query_str).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);
- }
+ 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));
- 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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Lint { input } => {
use open_ontologies::ontology::OntologyService;
@@ -532,15 +547,7 @@ async fn main() -> anyhow::Result<()> {
std::fs::read_to_string(&input)?
};
let result = OntologyService::lint_with_feedback(&content, Some(&db)).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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Convert { path, to, output } => {
let store = GraphStore::new();
@@ -740,30 +747,14 @@ async fn main() -> anyhow::Result<()> {
let shapes_content = std::fs::read_to_string(&shapes)?;
let result = ShaclValidator::validate(&graph, &shapes_content)
.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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Reason { profile } => {
use open_ontologies::reason::Reasoner;
let (_db, graph) = setup(&cli.data_dir)?;
let result = Reasoner::run(&graph, &profile, true)
.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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Extend { data_path, format: _format, mapping, shapes, profile } => {
use open_ontologies::ingest::DataIngester;
@@ -816,30 +807,14 @@ async fn main() -> anyhow::Result<()> {
let planner = open_ontologies::plan::Planner::new(db, graph);
let result = planner.plan(&turtle)
.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);
- }
+ 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)
.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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Lock { iris, reason } => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -861,30 +836,14 @@ async fn main() -> anyhow::Result<()> {
let detector = open_ontologies::drift::DriftDetector::new(db);
let result = detector.detect(&v1, &v2)
.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);
- }
+ 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))
.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);
- }
+ output_result(&result, cli.pretty);
}
Commands::Monitor => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -892,15 +851,7 @@ async fn main() -> anyhow::Result<()> {
let result = monitor.run_watchers();
let json = serde_json::to_string(&result)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- if cli.pretty {
- if let Ok(v) = serde_json::from_str::<serde_json::Value>(&json) {
- println!("{}", serde_json::to_string_pretty(&v).unwrap());
- } else {
- println!("{}", json);
- }
- } else {
- println!("{}", json);
- }
+ output_result(&json, cli.pretty);
}
Commands::MonitorClear => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -1000,15 +951,7 @@ async fn main() -> anyhow::Result<()> {
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);
- }
+ output_result(&result, cli.pretty);
}
Commands::AlignFeedback { source, target, accept, reject } => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -1016,45 +959,21 @@ async fn main() -> anyhow::Result<()> {
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);
- }
+ output_result(&result, cli.pretty);
}
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));
- 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);
- }
+ output_result(&result, cli.pretty);
}
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));
- 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);
- }
+ output_result(&result, cli.pretty);
}
}
diff --git a/src/poincare.rs b/src/poincare.rs
index b9713aa7..21a6b0a2 100644
--- a/src/poincare.rs
+++ b/src/poincare.rs
@@ -88,3 +88,45 @@ pub fn l2_normalize(v: &[f32]) -> Vec<f32> {
}
v.iter().map(|x| x / norm).collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn distance_triangle_inequality() {
+ let a = vec![0.1, 0.2];
+ let b = vec![0.3, -0.1];
+ let c = vec![-0.2, 0.4];
+ let d_ab = poincare_distance(&a, &b);
+ let d_bc = poincare_distance(&b, &c);
+ let d_ac = poincare_distance(&a, &c);
+ assert!(d_ac <= d_ab + d_bc + 1e-5, "Triangle inequality violated");
+ }
+
+ #[test]
+ fn mobius_add_identity() {
+ let origin = vec![0.0, 0.0, 0.0];
+ let p = vec![0.3, 0.4, 0.0];
+ let result = mobius_add(&origin, &p);
+ for (a, b) in result.iter().zip(p.iter()) {
+ assert!((a - b).abs() < 1e-5, "Origin should be identity for Mobius addition");
+ }
+ }
+
+ #[test]
+ fn conformal_factor_at_origin() {
+ let origin = vec![0.0, 0.0];
+ let lambda = conformal_factor(&origin);
+ assert!((lambda - 2.0).abs() < 1e-5, "Conformal factor at origin should be 2.0, got {}", lambda);
+ }
+
+ #[test]
+ fn conformal_factor_increases_near_boundary() {
+ let near_center = vec![0.1, 0.0];
+ let near_edge = vec![0.9, 0.0];
+ let lc = conformal_factor(&near_center);
+ let le = conformal_factor(&near_edge);
+ assert!(le > lc, "Conformal factor should increase near boundary");
+ }
+}
diff --git a/src/server.rs b/src/server.rs
index 4e4b47ca..13843281 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -11,324 +11,10 @@ use rmcp::{
},
service::RequestContext,
};
-use schemars::JsonSchema;
-use serde::Deserialize;
-
use crate::graph::GraphStore;
+use crate::inputs::*;
use crate::state::StateDb;
-// ─── MCP tool input structs ─────────────────────────────────────────────────
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoValidateInput {
- /// Path to an RDF file OR inline Turtle content
- pub input: String,
- /// If true, treat input as inline content rather than a file path
- pub inline: Option<bool>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoConvertInput {
- /// Path to source RDF file
- pub path: String,
- /// Target format: turtle, ntriples, rdfxml, nquads, trig
- pub to: String,
- /// Optional output file path (if omitted, returns content)
- pub output: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoLoadInput {
- /// Path to RDF file to load into the in-memory store
- pub path: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoQueryInput {
- /// SPARQL query string
- pub query: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoSaveInput {
- /// Output file path
- pub path: String,
- /// Format: turtle, ntriples, rdfxml, nquads, trig
- pub format: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoDiffInput {
- /// Path to the old/original ontology file
- pub old_path: String,
- /// Path to the new/modified ontology file
- pub new_path: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoLintInput {
- /// Path to RDF file to lint, OR inline Turtle content
- pub input: String,
- /// If true, treat input as inline content
- pub inline: Option<bool>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoPullInput {
- /// Remote URL or SPARQL endpoint to fetch ontology from
- pub url: String,
- /// If true, treat url as a SPARQL endpoint and run a CONSTRUCT query
- pub sparql: Option<bool>,
- /// Optional SPARQL CONSTRUCT query (required if sparql=true)
- pub query: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoPushInput {
- /// Remote SPARQL endpoint URL
- pub endpoint: String,
- /// Optional named graph IRI
- pub graph: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoImportInput {
- /// Resolve and load all owl:imports from the currently loaded ontology
- pub max_depth: Option<usize>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoVersionInput {
- /// Version label (e.g. "v1.0", "draft-2026-03-09")
- pub label: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoRollbackInput {
- /// Version label to restore
- pub label: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoIngestInput {
- /// Path to the data file (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet)
- pub path: String,
- /// Data format (auto-detected from extension if omitted): csv, json, ndjson, xml, yaml, xlsx, parquet
- pub format: Option<String>,
- /// Mapping config as JSON string or path to mapping JSON file
- pub mapping: Option<String>,
- /// If true, treat mapping as inline JSON (default: false = file path)
- pub inline_mapping: Option<bool>,
- /// Base IRI for generated instances (default: http://example.org/data/)
- pub base_iri: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoMapInput {
- /// Path to sample data file to generate mapping for
- pub data_path: String,
- /// Data format (auto-detected if omitted)
- pub format: Option<String>,
- /// Optional path to save the generated mapping config
- pub save_path: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoShaclInput {
- /// Path to SHACL shapes file OR inline SHACL Turtle content
- pub shapes: String,
- /// If true, treat shapes as inline Turtle content
- pub inline: Option<bool>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoReasonInput {
- /// Reasoning profile: rdfs (default), owl-rl
- pub profile: Option<String>,
- /// If true (default), add inferred triples to the store. If false, dry-run only.
- pub materialize: Option<bool>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoDlExplainInput {
- /// IRI of the class to explain unsatisfiability for
- pub class_iri: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoDlCheckInput {
- /// IRI of the sub-class (the more specific class)
- pub sub_class: String,
- /// IRI of the super-class (the more general class)
- pub super_class: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoExtendInput {
- /// Path to the data file
- pub data_path: String,
- /// Data format (auto-detected if omitted)
- pub format: Option<String>,
- /// Mapping config (inline JSON or file path)
- pub mapping: Option<String>,
- /// If true, treat mapping as inline JSON
- pub inline_mapping: Option<bool>,
- /// Base IRI for generated instances
- pub base_iri: Option<String>,
- /// Path to SHACL shapes file or inline Turtle
- pub shapes: Option<String>,
- /// If true, treat shapes as inline Turtle
- pub inline_shapes: Option<bool>,
- /// Reasoning profile (rdfs, owl-rl). Omit to skip reasoning.
- pub reason_profile: Option<String>,
- /// If true (default), stop pipeline on SHACL violations
- pub stop_on_violations: Option<bool>,
-}
-
-// ─── v2 input structs ───────────────────────────────────────────────────────
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoPlanInput {
- /// New ontology as inline Turtle content
- pub new_turtle: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoApplyInput {
- /// Apply mode: "safe" (default), "force" (ignores monitor), "migrate" (adds bridges)
- pub mode: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoLockInput {
- /// IRIs to lock (prevent removal)
- pub iris: Vec<String>,
- /// Reason for locking
- pub reason: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoDriftInput {
- /// First version as inline Turtle
- pub version_a: String,
- /// Second version as inline Turtle
- pub version_b: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoEnforceInput {
- /// Rule pack to enforce: "generic", "boro", "value_partition", or custom pack name
- pub rule_pack: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoMonitorInput {
- /// Inline JSON array of watchers to add, or omit to just run existing watchers
- pub watchers: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoCrosswalkInput {
- /// Clinical code to look up (e.g. "I10")
- pub code: String,
- /// Source system (e.g. "ICD10", "SNOMED", "MeSH")
- pub source_system: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoEnrichInput {
- /// IRI of the ontology class to enrich
- pub class_iri: String,
- /// Clinical code to map to
- pub code: String,
- /// Code system (e.g. "ICD10")
- pub system: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoLineageInput {
- /// Session ID to query (omit for current session)
- pub session_id: Option<String>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoImportSchemaInput {
- /// Database connection string (e.g. postgres://user:pass@host/db)
- pub connection: String,
- /// Base IRI for generated classes (default: http://example.org/db/)
- pub base_iri: Option<String>,
-}
-
-#[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,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoLintFeedbackInput {
- /// The lint rule ID (e.g. "missing_label", "missing_comment", "missing_domain", "missing_range")
- pub rule_id: String,
- /// The entity IRI that triggered the lint issue
- pub entity: String,
- /// true = this is a real issue, false = dismiss/ignore
- pub accepted: bool,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoEnforceFeedbackInput {
- /// The enforce rule ID (e.g. "orphan_class", "missing_domain", "missing_range", "missing_label", or custom rule ID)
- pub rule_id: String,
- /// The entity IRI that triggered the violation
- pub entity: String,
- /// true = this is a real violation, false = dismiss/override
- pub accepted: bool,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoEmbedInput {
- /// Structural embedding dimension. Default: 32
- pub struct_dim: Option<usize>,
- /// Structural training epochs. Default: 100
- pub struct_epochs: Option<usize>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoSearchInput {
- /// Natural language query
- pub query: String,
- /// Number of results. Default: 10
- pub top_k: Option<usize>,
- /// Search mode: "text", "structure", or "product". Default: "product"
- pub mode: Option<String>,
- /// Weight for text vs structure in product mode (0.0-1.0). Default: 0.5
- pub alpha: Option<f32>,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct OntoSimilarityInput {
- /// First IRI
- pub iri_a: String,
- /// Second IRI
- pub iri_b: String,
-}
-
// ─── OpenOntologiesServer ───────────────────────────────────────────────────
/// MCP server that exposes all Open Ontologies tools to Claude via stdin/stdout.
@@ -1435,34 +1121,6 @@ impl OpenOntologiesServer {
}
}
-// ─── Prompt input structs ───────────────────────────────────────────────────
-
-#[derive(Deserialize, JsonSchema)]
-pub struct BuildOntologyInput {
- /// Description of the domain to model (e.g. "A pizza ontology with toppings, bases, and named pizzas")
- pub domain: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct ValidateOntologyInput {
- /// Path to the ontology file to validate
- pub path: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct CompareOntologiesInput {
- /// Path to the old/original ontology file
- pub old_path: String,
- /// Path to the new/modified ontology file
- pub new_path: String,
-}
-
-#[derive(Deserialize, JsonSchema)]
-pub struct IngestDataInput {
- /// Path to the data file (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet)
- pub data_path: String,
-}
-
// ─── ServerHandler ──────────────────────────────────────────────────────────
#[tool_handler]
diff --git a/tests/poincare_stability_test.rs b/tests/poincare_stability_test.rs
new file mode 100644
index 00000000..842f9049
--- /dev/null
+++ b/tests/poincare_stability_test.rs
@@ -0,0 +1,148 @@
+//! Numerical stability tests for Poincaré ball geometry.
+//! Tests edge cases: zero vectors, near-boundary points, identical points,
+//! very high dimensions, and NaN/infinity propagation.
+
+#[cfg(feature = "embeddings")]
+mod stability {
+ use open_ontologies::poincare::*;
+
+ #[test]
+ fn distance_identical_points_is_zero() {
+ let p = vec![0.3, 0.4, 0.0];
+ let d = poincare_distance(&p, &p);
+ assert!(d.abs() < 1e-4, "Distance to self should be ~0, got {}", d);
+ }
+
+ #[test]
+ fn distance_zero_vectors() {
+ let zero = vec![0.0, 0.0, 0.0];
+ let d = poincare_distance(&zero, &zero);
+ assert!(d.is_finite(), "Distance between zero vectors should be finite, got {}", d);
+ assert!(d.abs() < 1e-4, "Distance between zero vectors should be ~0, got {}", d);
+ }
+
+ #[test]
+ fn distance_near_boundary() {
+ // Points very close to the boundary of the unit ball (norm ≈ 0.999)
+ let scale = 0.999 / (3.0f32).sqrt();
+ let a = vec![scale, scale, scale];
+ let b = vec![-scale, -scale, -scale];
+ let d = poincare_distance(&a, &b);
+ assert!(d.is_finite(), "Distance near boundary should be finite, got {}", d);
+ assert!(d > 0.0, "Distance between distinct near-boundary points should be positive");
+ }
+
+ #[test]
+ fn distance_one_at_origin() {
+ let origin = vec![0.0, 0.0, 0.0];
+ let p = vec![0.5, 0.0, 0.0];
+ let d = poincare_distance(&origin, &p);
+ assert!(d.is_finite(), "Distance from origin should be finite");
+ assert!(d > 0.0, "Distance from origin to non-origin point should be positive");
+ }
+
+ #[test]
+ fn distance_symmetry() {
+ let a = vec![0.1, 0.2, 0.3];
+ let b = vec![0.4, -0.1, 0.2];
+ let d_ab = poincare_distance(&a, &b);
+ let d_ba = poincare_distance(&b, &a);
+ assert!((d_ab - d_ba).abs() < 1e-6, "Distance should be symmetric: {} vs {}", d_ab, d_ba);
+ }
+
+ #[test]
+ fn exp_map_zero_tangent_returns_base() {
+ let base = vec![0.3, 0.4, 0.0];
+ let zero_v = vec![0.0, 0.0, 0.0];
+ let result = exp_map(&base, &zero_v);
+ for (a, b) in result.iter().zip(base.iter()) {
+ assert!((a - b).abs() < 1e-5, "exp_map with zero tangent should return base point");
+ }
+ }
+
+ #[test]
+ fn exp_map_stays_in_ball() {
+ // Large tangent vector — result must still be inside the unit ball
+ let base = vec![0.5, 0.5, 0.0];
+ let large_v = vec![100.0, 100.0, 100.0];
+ let result = exp_map(&base, &large_v);
+ let norm: f32 = result.iter().map(|x| x * x).sum::<f32>().sqrt();
+ assert!(norm < 1.0, "exp_map result must stay inside unit ball, got norm {}", norm);
+ assert!(result.iter().all(|x| x.is_finite()), "exp_map result must be finite");
+ }
+
+ #[test]
+ fn project_to_ball_clamps_outside_points() {
+ let outside = vec![2.0, 0.0, 0.0];
+ let projected = project_to_ball(&outside, 1e-5);
+ let norm: f32 = projected.iter().map(|x| x * x).sum::<f32>().sqrt();
+ assert!(norm < 1.0, "Projected point must be inside ball, got norm {}", norm);
+ }
+
+ #[test]
+ fn project_to_ball_preserves_interior_points() {
+ let inside = vec![0.3, 0.4, 0.0];
+ let projected = project_to_ball(&inside, 1e-5);
+ for (a, b) in projected.iter().zip(inside.iter()) {
+ assert!((a - b).abs() < 1e-6, "Interior point should not change");
+ }
+ }
+
+ #[test]
+ fn rsgd_step_stays_in_ball() {
+ let point = vec![0.8, 0.0, 0.0]; // near boundary
+ let grad = vec![1.0, 1.0, 1.0];
+ let result = rsgd_step(&point, &grad, 0.1);
+ let norm: f32 = result.iter().map(|x| x * x).sum::<f32>().sqrt();
+ assert!(norm < 1.0, "RSGD step must stay in ball, got norm {}", norm);
+ assert!(result.iter().all(|x| x.is_finite()), "RSGD result must be finite");
+ }
+
+ #[test]
+ fn cosine_similarity_zero_vector() {
+ let zero = vec![0.0, 0.0, 0.0];
+ let p = vec![1.0, 0.0, 0.0];
+ let sim = cosine_similarity(&zero, &p);
+ assert!(sim.is_finite(), "Cosine with zero vector should be finite");
+ assert!(sim.abs() < 1e-5, "Cosine with zero vector should be 0, got {}", sim);
+ }
+
+ #[test]
+ fn cosine_similarity_identical_is_one() {
+ let p = vec![0.3, 0.4, 0.5];
+ let sim = cosine_similarity(&p, &p);
+ assert!((sim - 1.0).abs() < 1e-5, "Cosine of identical vectors should be 1, got {}", sim);
+ }
+
+ #[test]
+ fn cosine_similarity_opposite_is_negative_one() {
+ let a = vec![1.0, 0.0, 0.0];
+ let b = vec![-1.0, 0.0, 0.0];
+ let sim = cosine_similarity(&a, &b);
+ assert!((sim + 1.0).abs() < 1e-5, "Cosine of opposite vectors should be -1, got {}", sim);
+ }
+
+ #[test]
+ fn l2_normalize_zero_vector() {
+ let zero = vec![0.0, 0.0, 0.0];
+ let result = l2_normalize(&zero);
+ assert!(result.iter().all(|x| x.is_finite()), "Normalizing zero should not produce NaN/Inf");
+ }
+
+ #[test]
+ fn l2_normalize_produces_unit_vector() {
+ let v = vec![3.0, 4.0, 0.0];
+ let result = l2_normalize(&v);
+ let norm: f32 = result.iter().map(|x| x * x).sum::<f32>().sqrt();
+ assert!((norm - 1.0).abs() < 1e-5, "Normalized vector should have unit length, got {}", norm);
+ }
+
+ #[test]
+ fn high_dimensional_distance_is_finite() {
+ let dim = 512;
+ let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.001) % 0.5).collect();
+ let b: Vec<f32> = (0..dim).map(|i| ((i + 1) as f32 * 0.001) % 0.5).collect();
+ let d = poincare_distance(&a, &b);
+ assert!(d.is_finite(), "High-dimensional distance should be finite, got {}", d);
+ }
+}