Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat: full BC+ semantics + 12 new primitives + README rewrite (#52)
Fabio Rovai4f91c1d17b34
diff --git a/README.md b/README.mdindex b4439c03..02528b19 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@----Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **43 tools** that let Claude build, validate, query, diff, lint, version, reason over, align, and persist RDF/OWL ontologies using an in-memory Oxigraph triple store — with Terraform-style lifecycle management, a marketplace of 32 standard ontologies, clinical crosswalks, semantic embeddings, and a full lineage audit trail.+Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **70+ tools** that let Claude build, validate, query, diff, lint, version, reason over, align, plan, certify, and govern RDF/OWL ontologies using an in-memory Oxigraph triple store — with a full three-layer Dynamics → Causal → Planner architecture, a marketplace of 32 standard ontologies, clinical crosswalks, semantic embeddings, and a full lineage audit trail.The **Studio** wraps the engine in a visual desktop environment: virtualized ontology tree with hierarchy lines, breadcrumb navigation, and connection explorer; AI chat panel with `/build` (IES-level deep) and `/sketch` (quick prototype) commands; Protégé-style property inspector; and lineage viewer.@@ -39,16 +39,43 @@ No JVM. No Protégé.----## What's New in v0.2+## What's New in v0.4–v0.6 (three-layer architecture + 13 new primitives)-Four PRs landed in the May 2026 release, all built on the **MCP-native** convention: the server provides validation and scaffolding primitives, the connected LLM (Claude over MCP) does the intelligence. No internal LLM clients, no API keys, no provider abstractions — the protocol already provides the model.+The May 2026 megapush lands the full **Dynamics → Causal → Planner** stack plus 13 new primitives driven by the May 2026 KR/UAI/ICAPS/ISWC/K-CAP/SEMANTiCS/AAAI survey. Every piece holds the **MCP-native** convention: the server provides validation and scaffolding, the connected LLM (Claude over MCP) does the intelligence. No internal LLM clients, no API keys, no provider abstractions.-- **KGCL drift output (#19)** — `onto_drift` can now emit results in the [Knowledge Graph Change Language](https://github.com/INCATools/kgcl) (CNL or structured JSON-LD) alongside the existing JSON. Instant OBO/BioPortal interop; "Terraform plan" output becomes machine-replayable.-- **Borderline-candidate review for `onto_align` (#20)** — two-threshold bucketing (`auto_applied` / `borderline` / dropped) replaces the single `min_confidence` cliff. Borderline pairs carry rich `context` (labels, parents) so Claude can judge them in-conversation and record verdicts via the existing `onto_align_feedback` loop. MCP-native form of the LogMap-LLM "LLM-as-oracle" pattern (top-2 OAEI 2025 Bio-ML).-- **`onto_shacl_check` (#21)** — structural dry-run for proposed SHACL shapes against the loaded ontology. Catches missing `sh:targetClass`, `sh:path`, `sh:class`, and unrecognised `sh:datatype` references before applying. The validation primitive Claude needs to iterate on LLM-authored SHACL.-- **Oxigraph 0.5.8 migration (#22)** — `Store::query` ported to the non-deprecated `SparqlEvaluator` builder API. Unlocks **RDFC 1.0 canonicalisation** (W3C Recommendation, 21 May 2024) built-in, plus RDF 1.2 / SPARQL 1.2 / JSON-LD 1.1 / GeoSPARQL features available on demand.+### Three-layer architecture (v0.4 → v0.5 → v0.6)-Zero new external dependencies across all four PRs. Full test suite (~290 tests) green; `cargo clippy --lib --tests -- -D warnings` clean.+| Layer | Issue | What it ships | Anchor research |+|---|---|---|---|+| **Dynamics** | [#43](https://github.com/fabio-rovai/open-ontologies/issues/43) | `ActionSchema` (BC+) + 4 MCP tools: `onto_action_register` / `_applicable` / `_apply` / `_list`. Full BC+ semantics — concurrent atomic ticks, static causal laws (invariants), default-value laws, ramification via OWL-RL closure, non-deterministic outcomes with reproducible seed. | Babb & Lee arXiv 2506.18044 |+| **Causal** | [#44](https://github.com/fabio-rovai/open-ontologies/issues/44) | `onto_certify_action` with optional PyWhy/DoWhy backdoor identification (opt-in via `causal-pywhy` feature). Structural-proxy default + do-calculus opt-in + graceful fallback. | CIVeX arXiv:2605.09168; DoWhy v0.13 |+| **Planner** | [#45](https://github.com/fabio-rovai/open-ontologies/issues/45) | `onto_plan_compile_pddl` + `onto_plan_classical` (Fast Downward subprocess) + `onto_plan_validate` (sandbox-simulate). Per LLM-Modulo, solver stays client-side; server compiles + validates. | Kambhampati arXiv 2402.01817 |++### 13 new primitives from May 2026 conferences++- **`onto_owl_shacl_coevolve_check`** (#33, K-CAP 2025) — SHACL validation against the OWL-RL closure, not the raw ABox.+- **`onto_segment_retrieve`** (#34, GrOWL-RAG SEMANTiCS 2025) — TBox-slice retrieval for ontology-grounded RAG.+- **`onto_extract_scaffold`** + **`onto_extract_validate`** (#28, OntoGPT SPIRES) — schema-guided structured extraction, MCP-native.+- **`onto_cq_run`** (#29) + **`onto_verify_cq`** (#39, Lippolis ISWC 2025) — competency-question runner with VSPO pitfall hints + LLM-judgement loop.+- **`onto_classify_el`** (#30) — OWL-EL classification (transitive subsumption table, trivial pairs excluded).+- **`onto_eval_alignment`** (#31) — OAEI-style P/R/F1 over reference + computed alignments.+- **`onto_shape_combinatorics`** (#36, K-CAP 2025 Kastor) — property-combination lattice for shape induction.+- **`borderline_partition`** + **`borderline_record_verdict`** (#37, NORA NeurIPS 2025) — generalised borderline-pair review loop.+- **`onto_align_fuzzy`** (#38, FLORA ISWC 2025 Best Paper) — embedding-free fuzzy-logic adjudication; demotes HNSW to a candidate generator per the strategic alignment pivot.+- **`onto_policy_register`** + **`onto_policy_list`** + **`onto_policy_check`** (#40, ARGOS ISWC 2025 WOP) — authorisation gate that composes with CIVeX (CIVeX = causal risk; ARGOS = authorisation).+- **`eval_rag`** (#41, mmRAG ISWC 2025) — Hit@k / MRR / exact-match-at-1 scoring for retriever pipelines.++Also: **`graph_projection_lossy_check`** (#35, IJCAI 2025) lands as the auditor that pairs with `onto_segment_retrieve`.++### Validating end-to-end++```bash+cargo run --example three_layer_pipeline+```++Walks Dynamics register → PDDL compile → Fast-Downward-shaped sas_plan parse → orchestrator-side IRI bind → sandbox validate → CIVeX certify → apply with OWL-RL ramification → final state inspection. Every layer through its public API, no external dependencies (Python, DoWhy, Fast Downward) required.++Zero new external Rust dependencies; everything optional gates behind Cargo features. Full test suite (160+ tests) green on default build; `cargo clippy --lib --tests --examples -- -D warnings` clean across both default and `causal-pywhy` configurations.---@@ -646,7 +673,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T## Tools-43 tools organized by function — available as MCP tools (prefixed `onto_`) and CLI subcommands:+70+ tools organized by function — available as MCP tools (prefixed `onto_`) and CLI subcommands:| Category | Tools | Purpose || --- | --- | --- |@@ -655,15 +682,26 @@ The same tool, applied to any ontology, produces the same kind of improvement. T| **Cache** | `cache_status` `cache_list` `cache_remove` `unload` `recompile` | On-disk N-Triples compile cache, idle-TTL eviction, per-name management ([details](docs/cache-and-registry.md)) || **Marketplace** | `marketplace` | Browse and install 32 standard W3C/ISO/industry ontologies || **Remote** | `pull` `push` `import` | Fetch/push ontologies, resolve owl:imports |-| **Schema** | `import-schema` | PostgreSQL → OWL conversion |-| **Data** | `map` `ingest` `shacl` `reason` `extend` | Structured data → RDF pipeline |+| **Schema** | `import-schema` `sql-ingest` | Postgres + DuckDB → OWL + SQL → RDF ingest |+| **Data** | `map` `ingest` `shacl` `shacl_check` `reason` `extend` | Structured data → RDF pipeline || **Versioning** | `version` `history` `rollback` | Named snapshots and rollback || **Lifecycle** | `plan` `apply` `lock` `drift` `enforce` `monitor` `monitor-clear` `lineage` | Terraform-style change management with webhook alerts and [OpenCheir](https://github.com/fabio-rovai/opencheir) governance integration |-| **Alignment** | `align` `align-feedback` | Cross-ontology class matching with self-calibrating confidence |-| **Clinical** | `crosswalk` `enrich` `validate-clinical` | ICD-10 / SNOMED / MeSH crosswalks (93-row sample ships in `data/crosswalks.parquet`; run `python scripts/build_crosswalks.py` to rebuild or extend) |-| **Feedback** | `lint-feedback` `enforce-feedback` | Self-calibrating suppression |+| **Alignment** | `align` `align_feedback` `align_fuzzy` | Cross-ontology class matching with self-calibrating weights + FLORA fuzzy adjudication |+| **HNSW** | `hnsw_build` | Persisted HNSW indices (cosine + Poincaré) over class embeddings |+| **Clinical** | `crosswalk` `enrich` `validate_clinical` | ICD-10 / SNOMED / MeSH crosswalks (93-row sample ships in `data/crosswalks.parquet`; run `python scripts/build_crosswalks.py` to rebuild or extend) |+| **Feedback** | `lint_feedback` `enforce_feedback` | Self-calibrating suppression || **Embeddings** | `embed` `search` `similarity` | Dual-space semantic search (text + Poincaré structural) |-| **Reasoning** | `reason` `dl_explain` `dl_check` | Native OWL2-DL SHOIQ tableaux reasoner |+| **Reasoning** | `reason` `dl_explain` `dl_check` `classify_el` | Native OWL2-DL SHOIQ tableaux + OWL-EL classification |+| **Dynamics (#43)** | `action_register` `action_applicable` `action_apply` `action_list` `action_apply_concurrent` `invariant_register` `invariant_list` `invariant_remove` `invariant_check` `default_register` `default_apply` | BC+ action schemas + concurrent atomic ticks + static causal laws + default values |+| **Causal (#44)** | `certify_action` | CIVeX-style four-verdict causal certificate (EXECUTE / REJECT / EXPERIMENT / ABSTAIN); optional `causal-pywhy` feature enables DoWhy backdoor identification |+| **Planner (#45)** | `plan_compile_pddl` `plan_classical` `plan_validate` | Per LLM-Modulo: compile + validate live on the server; solver (Fast Downward) is a client-side subprocess |+| **Governance (#40)** | `policy_register` `policy_list` `policy_check` | ARGOS-style authorisation rules; composes with `certify_action` |+| **RAG** | `segment_retrieve` `graph_projection_lossy_check` | TBox-slice retrieval + projection-loss auditor |+| **Extraction (#28)** | `extract_scaffold` `extract_validate` | Schema-guided structured-extraction prompt + validator (MCP-native SPIRES) |+| **CQs** | `cq_run` `verify_cq` `cq_verdicts_list` | Competency-question runner with VSPO pitfall hints + LLM-judgement loop |+| **Shape induction** | `shape_combinatorics` | Property-combination lattice for SHACL-shape induction |+| **Borderline loop** | `borderline_partition` `borderline_record_verdict` | Generalised two-threshold borderline pattern for any candidate set |+| **Evaluation** | `eval_alignment` `eval_rag` | OAEI P/R/F1 + mmRAG Hit@k / MRR scoring |---diff --git a/src/align_fuzzy.rs b/src/align_fuzzy.rsnew file mode 100644index 00000000..62e73974--- /dev/null+++ b/src/align_fuzzy.rs@@ -0,0 +1,162 @@+//! FLORA-style fuzzy-logic alignment adjudication (#38, ISWC 2025 Best+//! Paper).+//!+//! FLORA (Fuzzy Logic Over Relational Alignments) is embedding-free: it+//! adjudicates candidate alignment pairs using fuzzy-logic rules over+//! structural signals (label-token-Jaccard, parent overlap, sibling+//! overlap, datatype-property overlap), then aggregates via a configurable+//! t-norm.+//!+//! ## Per the strategic pivot recorded in project memory+//!+//! HNSW (currently the alignment engine's main matcher) is **demoted to a+//! candidate generator**. FLORA-style fuzzy adjudication becomes the+//! final-decision layer for borderline pairs. The ISWC 2025 Best Paper+//! result: embedding-free fuzzy alignment matches or beats embedding-based+//! pipelines on OAEI benchmarks while being interpretable.++use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]+pub struct FuzzySignals {+ /// Token Jaccard over labels in `[0, 1]`.+ pub label_jaccard: f64,+ /// Fraction of parents shared in `[0, 1]`.+ pub parent_overlap: f64,+ /// Fraction of siblings shared in `[0, 1]`.+ pub sibling_overlap: f64,+ /// Fraction of datatype properties shared in `[0, 1]`.+ pub datatype_overlap: f64,+}++#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum TNorm {+ /// `min(a, b)` — Zadeh / Gödel.+ #[default]+ Min,+ /// `a * b` — product / probabilistic.+ Product,+ /// `max(0, a + b - 1)` — Łukasiewicz.+ Lukasiewicz,+}++#[derive(Clone, Debug, Serialize)]+pub struct FuzzyDecision {+ pub fuzzy_score: f64,+ pub verdict: String,+ pub rule_trace: Vec<String>,+}++/// Adjudicate a candidate pair using fuzzy logic over the supplied signals.+/// Returns a score in `[0, 1]` and one of `"accept"` / `"reject"` /+/// `"borderline"` based on thresholds.+pub fn adjudicate(+ signals: &FuzzySignals,+ tnorm: TNorm,+ low_threshold: f64,+ high_threshold: f64,+) -> FuzzyDecision {+ let mut trace: Vec<String> = Vec::new();++ // Rule 1: high label similarity AND high parent overlap → strong accept.+ let rule1 = combine(signals.label_jaccard, signals.parent_overlap, tnorm);+ trace.push(format!(+ "R1 (label ∧ parent, {:?}): label={:.3} parent={:.3} = {:.3}",+ tnorm, signals.label_jaccard, signals.parent_overlap, rule1+ ));++ // Rule 2: structural support (parent + sibling + datatype) for borderline labels.+ let mid = (signals.parent_overlap + signals.sibling_overlap + signals.datatype_overlap) / 3.0;+ let rule2 = combine(signals.label_jaccard, mid, tnorm);+ trace.push(format!(+ "R2 (label ∧ mean-structural, {:?}): label={:.3} mean-struct={:.3} = {:.3}",+ tnorm, signals.label_jaccard, mid, rule2+ ));++ // Final score: maximum activation (Mamdani-style aggregation).+ let fuzzy_score = rule1.max(rule2);+ trace.push(format!("aggregate (max of rules): {:.3}", fuzzy_score));++ let verdict = if fuzzy_score >= high_threshold {+ "accept"+ } else if fuzzy_score >= low_threshold {+ "borderline"+ } else {+ "reject"+ }+ .to_string();+ trace.push(format!(+ "verdict: {} (thresholds: low={:.3}, high={:.3})",+ verdict, low_threshold, high_threshold+ ));++ FuzzyDecision { fuzzy_score, verdict, rule_trace: trace }+}++fn combine(a: f64, b: f64, t: TNorm) -> f64 {+ match t {+ TNorm::Min => a.min(b),+ TNorm::Product => a * b,+ TNorm::Lukasiewicz => (a + b - 1.0).max(0.0),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn s(l: f64, p: f64, sb: f64, d: f64) -> FuzzySignals {+ FuzzySignals {+ label_jaccard: l,+ parent_overlap: p,+ sibling_overlap: sb,+ datatype_overlap: d,+ }+ }++ #[test]+ fn high_label_and_parent_accepts_under_min_tnorm() {+ let d = adjudicate(&s(0.95, 0.9, 0.4, 0.3), TNorm::Min, 0.4, 0.85);+ assert_eq!(d.verdict, "accept");+ assert!(d.fuzzy_score >= 0.9);+ }++ #[test]+ fn moderate_label_borderline() {+ let d = adjudicate(&s(0.6, 0.5, 0.3, 0.2), TNorm::Min, 0.4, 0.85);+ assert_eq!(d.verdict, "borderline");+ }++ #[test]+ fn low_label_rejects_even_with_structural_support() {+ let d = adjudicate(&s(0.1, 0.95, 0.95, 0.95), TNorm::Min, 0.4, 0.85);+ assert_eq!(d.verdict, "reject");+ }++ #[test]+ fn product_tnorm_is_stricter_than_min() {+ let signals = s(0.8, 0.8, 0.4, 0.3);+ let d_min = adjudicate(&signals, TNorm::Min, 0.4, 0.85);+ let d_prod = adjudicate(&signals, TNorm::Product, 0.4, 0.85);+ assert!(d_min.fuzzy_score >= d_prod.fuzzy_score);+ }++ #[test]+ fn lukasiewicz_strictest_of_the_three() {+ let signals = s(0.5, 0.5, 0.5, 0.5);+ let d_min = adjudicate(&signals, TNorm::Min, 0.0, 1.0);+ let d_prod = adjudicate(&signals, TNorm::Product, 0.0, 1.0);+ let d_luka = adjudicate(&signals, TNorm::Lukasiewicz, 0.0, 1.0);+ assert!(d_luka.fuzzy_score <= d_prod.fuzzy_score);+ assert!(d_prod.fuzzy_score <= d_min.fuzzy_score);+ }++ #[test]+ fn rule_trace_records_each_rule_score_and_verdict() {+ let d = adjudicate(&s(0.7, 0.7, 0.7, 0.7), TNorm::Min, 0.4, 0.85);+ assert!(d.rule_trace.iter().any(|s| s.contains("R1")));+ assert!(d.rule_trace.iter().any(|s| s.contains("R2")));+ assert!(d.rule_trace.iter().any(|s| s.contains("verdict")));+ }+}diff --git a/src/borderline_loop.rs b/src/borderline_loop.rsnew file mode 100644index 00000000..fc4f16db--- /dev/null+++ b/src/borderline_loop.rs@@ -0,0 +1,227 @@+//! Generalised iterative borderline-pair review loop (#37, NORA NeurIPS+//! 2025).+//!+//! Generalises the borderline-pair pattern from `onto_align` (#16) to any+//! candidate set: given a list of `(item, score)` candidates plus two+//! thresholds, partition into `auto_accept` (above high), `borderline`+//! (between low and high), `auto_reject` (below low), and emit a summary+//! prompt instructing the orchestrator to judge the borderline bucket.+//!+//! The judgement persists via `record_verdict`, and `apply_verdicts`+//! merges accepted-borderline items back into the auto-accept set.++use crate::state::StateDb;+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct Candidate {+ pub id: String,+ pub score: f64,+ /// Free-form context for the LLM's judgement (e.g. labels, parents).+ #[serde(default)]+ pub context: serde_json::Value,+}++#[derive(Clone, Debug, Serialize)]+pub struct PartitionReport {+ pub auto_accept: Vec<Candidate>,+ pub borderline: Vec<Candidate>,+ pub auto_reject: Vec<Candidate>,+ pub summary_for_review: String,+}++/// Partition `candidates` by two thresholds. Items with `score >= high`+/// land in `auto_accept`; `[low, high)` in `borderline`; `< low` in+/// `auto_reject`.+pub fn partition(candidates: Vec<Candidate>, low: f64, high: f64) -> PartitionReport {+ let (mut auto_a, mut bord, mut auto_r) = (Vec::new(), Vec::new(), Vec::new());+ for c in candidates {+ if c.score >= high {+ auto_a.push(c);+ } else if c.score >= low {+ bord.push(c);+ } else {+ auto_r.push(c);+ }+ }+ let summary = format!(+ "Review {} borderline candidate(s) in range [{:.3}, {:.3}). For each, call \+ `borderline_record_verdict` with verdict `\"accept\"` or `\"reject\"`. \+ {} auto-accepted, {} auto-rejected.",+ bord.len(),+ low,+ high,+ auto_a.len(),+ auto_r.len()+ );+ PartitionReport {+ auto_accept: auto_a,+ borderline: bord,+ auto_reject: auto_r,+ summary_for_review: summary,+ }+}++// ─── Verdict persistence ────────────────────────────────────────────────────++const ENSURE_TABLE: &str = "+CREATE TABLE IF NOT EXISTS borderline_verdicts (+ candidate_id TEXT NOT NULL,+ namespace TEXT NOT NULL DEFAULT 'default',+ verdict TEXT NOT NULL CHECK (verdict IN ('accept', 'reject')),+ rationale TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ PRIMARY KEY (candidate_id, namespace, created_at)+)";++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct BorderlineVerdict {+ pub candidate_id: String,+ /// Logical namespace ("default" if unspecified). Lets a single server+ /// host multiple independent borderline loops without collision.+ #[serde(default = "default_namespace")]+ pub namespace: String,+ /// Either "accept" or "reject".+ pub verdict: String,+ #[serde(default)]+ pub rationale: Option<String>,+}++fn default_namespace() -> String {+ "default".to_string()+}++fn ensure(db: &StateDb) -> anyhow::Result<()> {+ db.conn().execute(ENSURE_TABLE, [])?;+ Ok(())+}++pub fn record_verdict(db: &StateDb, v: &BorderlineVerdict) -> anyhow::Result<()> {+ if !matches!(v.verdict.as_str(), "accept" | "reject") {+ anyhow::bail!("invalid verdict `{}`: must be accept/reject", v.verdict);+ }+ ensure(db)?;+ db.conn().execute(+ "INSERT INTO borderline_verdicts (candidate_id, namespace, verdict, rationale) VALUES (?1, ?2, ?3, ?4)",+ rusqlite::params![v.candidate_id, v.namespace, v.verdict, v.rationale],+ )?;+ Ok(())+}++/// Return the most-recent verdict for a candidate id in the given namespace,+/// or `None` if no verdict has been recorded.+pub fn latest_verdict(db: &StateDb, namespace: &str, candidate_id: &str) -> anyhow::Result<Option<BorderlineVerdict>> {+ ensure(db)?;+ let conn = db.conn();+ let row: Option<(String, Option<String>)> = conn+ .query_row(+ "SELECT verdict, rationale FROM borderline_verdicts \+ WHERE candidate_id = ?1 AND namespace = ?2 ORDER BY created_at DESC LIMIT 1",+ rusqlite::params![candidate_id, namespace],+ |r| Ok((r.get(0)?, r.get(1)?)),+ )+ .ok();+ Ok(row.map(|(verdict, rationale)| BorderlineVerdict {+ candidate_id: candidate_id.to_string(),+ namespace: namespace.to_string(),+ verdict,+ rationale,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::Path;++ fn fresh_db() -> StateDb {+ StateDb::open(Path::new(":memory:")).unwrap()+ }++ fn cand(id: &str, score: f64) -> Candidate {+ Candidate { id: id.to_string(), score, context: serde_json::Value::Null }+ }++ #[test]+ fn partition_splits_by_two_thresholds() {+ let cs = vec![cand("a", 0.95), cand("b", 0.7), cand("c", 0.2)];+ let r = partition(cs, 0.4, 0.85);+ assert_eq!(r.auto_accept.len(), 1);+ assert_eq!(r.auto_accept[0].id, "a");+ assert_eq!(r.borderline.len(), 1);+ assert_eq!(r.borderline[0].id, "b");+ assert_eq!(r.auto_reject.len(), 1);+ assert_eq!(r.auto_reject[0].id, "c");+ }++ #[test]+ fn summary_text_reflects_counts() {+ let cs = vec![cand("a", 0.9), cand("b", 0.6), cand("c", 0.6), cand("d", 0.1)];+ let r = partition(cs, 0.5, 0.85);+ assert!(r.summary_for_review.contains("2 borderline"));+ assert!(r.summary_for_review.contains("1 auto-accepted"));+ assert!(r.summary_for_review.contains("1 auto-rejected"));+ }++ #[test]+ fn record_verdict_round_trip() {+ let db = fresh_db();+ record_verdict(+ &db,+ &BorderlineVerdict {+ candidate_id: "pair_42".to_string(),+ namespace: "alignment".to_string(),+ verdict: "accept".to_string(),+ rationale: Some("labels matched after stemming".to_string()),+ },+ )+ .unwrap();+ let v = latest_verdict(&db, "alignment", "pair_42").unwrap().unwrap();+ assert_eq!(v.verdict, "accept");+ }++ #[test]+ fn record_verdict_rejects_invalid_label() {+ let db = fresh_db();+ let err = record_verdict(+ &db,+ &BorderlineVerdict {+ candidate_id: "x".to_string(),+ namespace: "default".to_string(),+ verdict: "maybe".to_string(),+ rationale: None,+ },+ )+ .expect_err("should reject");+ assert!(format!("{}", err).contains("invalid verdict"));+ }++ #[test]+ fn namespaces_isolate_verdicts() {+ let db = fresh_db();+ record_verdict(+ &db,+ &BorderlineVerdict {+ candidate_id: "x".to_string(),+ namespace: "ns_a".to_string(),+ verdict: "accept".to_string(),+ rationale: None,+ },+ )+ .unwrap();+ record_verdict(+ &db,+ &BorderlineVerdict {+ candidate_id: "x".to_string(),+ namespace: "ns_b".to_string(),+ verdict: "reject".to_string(),+ rationale: None,+ },+ )+ .unwrap();+ let va = latest_verdict(&db, "ns_a", "x").unwrap().unwrap();+ let vb = latest_verdict(&db, "ns_b", "x").unwrap().unwrap();+ assert_eq!(va.verdict, "accept");+ assert_eq!(vb.verdict, "reject");+ }+}diff --git a/src/classify_el.rs b/src/classify_el.rsnew file mode 100644index 00000000..24ccf969--- /dev/null+++ b/src/classify_el.rs@@ -0,0 +1,140 @@+//! OWL-EL classification primitive (#30, ELK-style).+//!+//! OWL 2 EL is the polynomial-time profile suitable for ontologies with+//! large class hierarchies but limited expressivity. ELK (Kazakov et al.,+//! 2011) is the canonical EL reasoner.+//!+//! ## Scope+//!+//! This primitive runs the existing OWL-RL reasoner on the loaded graph+//! (which is sufficient for the EL fragment: subClassOf transitivity,+//! property hierarchies, existential restrictions via owl-rl-ext) and+//! emits the **full classification table** — every materialised+//! `?sub rdfs:subClassOf ?super` pair, sorted, deduplicated.+//!+//! For deep OWL-DL (SHOIQ), use `onto_dl_check` / `onto_dl_explain` which+//! delegate to the tableaux reasoner.++use crate::graph::GraphStore;+use crate::reason::Reasoner;+use serde::Serialize;+use std::sync::Arc;++#[derive(Clone, Debug, Serialize)]+pub struct ClassificationReport {+ pub profile: String,+ pub class_count: usize,+ pub subsumption_count: usize,+ /// `[sub, super]` pairs. Sorted by sub then super for stable output.+ pub subsumptions: Vec<(String, String)>,+}++/// Classify the loaded ontology in the OWL-EL fragment. Runs OWL-RL+/// materialisation in a sandbox so the original graph is not mutated.+pub fn classify(graph: &Arc<GraphStore>) -> anyhow::Result<ClassificationReport> {+ let sandbox = Arc::new(GraphStore::new());+ let triples = graph.all_triples()?;+ if !triples.is_empty() {+ let mut nt = String::with_capacity(triples.len() * 64);+ for (s, p, o) in &triples {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ sandbox.load_turtle(&nt, None)?;+ }+ let _ = Reasoner::run(&sandbox, "owl-rl-ext", true)?;++ let q = "SELECT ?sub ?sup WHERE { ?sub <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?sup } LIMIT 100000";+ let js = sandbox.sparql_select(q)?;+ let v: serde_json::Value = serde_json::from_str(&js)?;+ let rows = v["results"].as_array().cloned().unwrap_or_default();++ let mut subs: Vec<(String, String)> = rows+ .iter()+ .filter_map(|r| {+ let s = r["sub"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();+ let o = r["sup"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();+ // Skip trivial X ⊑ X and X ⊑ owl:Thing.+ if s == o || o == "http://www.w3.org/2002/07/owl#Thing" {+ return None;+ }+ Some((s, o))+ })+ .collect();+ subs.sort();+ subs.dedup();++ // Count distinct class IRIs participating in any subsumption.+ let mut classes: std::collections::BTreeSet<&String> = std::collections::BTreeSet::new();+ for (s, o) in &subs {+ classes.insert(s);+ classes.insert(o);+ }++ Ok(ClassificationReport {+ profile: "owl-rl-ext".to_string(),+ class_count: classes.len(),+ subsumption_count: subs.len(),+ subsumptions: subs,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn classify_emits_transitive_closure_of_subclassof() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:A a owl:Class .+ ex:B a owl:Class ; rdfs:subClassOf ex:A .+ ex:C a owl:Class ; rdfs:subClassOf ex:B .+ "#,+ None,+ )+ .unwrap();+ let r = classify(&g).unwrap();+ // Transitive: C ⊑ A must be derived.+ let has_c_a = r.subsumptions.iter().any(|(s, o)| {+ s == "http://ex.org/C" && o == "http://ex.org/A"+ });+ assert!(has_c_a, "transitive subsumption not derived; got: {:?}", r.subsumptions);+ assert!(r.subsumption_count >= 3);+ }++ #[test]+ fn classify_excludes_trivial_self_subsumptions() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://ex.org/> . ex:A a owl:Class .",+ None,+ )+ .unwrap();+ let r = classify(&g).unwrap();+ for (s, o) in &r.subsumptions {+ assert_ne!(s, o, "self-subsumption emitted");+ }+ }++ #[test]+ fn classify_does_not_mutate_original() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix ex: <http://ex.org/> . ex:A a owl:Class . ex:B a owl:Class ; rdfs:subClassOf ex:A .",+ None,+ )+ .unwrap();+ let pre = g.triple_count();+ let _ = classify(&g).unwrap();+ assert_eq!(pre, g.triple_count());+ }+}diff --git a/src/coevolve.rs b/src/coevolve.rsnew file mode 100644index 00000000..0e019795--- /dev/null+++ b/src/coevolve.rs@@ -0,0 +1,151 @@+//! Combined OWL+SHACL co-evolution validator (#33, K-CAP 2025).+//!+//! The K-CAP 2025 paper "Co-evolving OWL ontologies and SHACL shapes" shows+//! that validating SHACL against ABox data alone misses constraints that+//! become satisfiable only after OWL inference (`rdfs:subClassOf` transitive+//! closure, `owl:sameAs`, domain/range propagation). The co-evolve check+//! materialises OWL entailments first, then runs SHACL against the closure.+//!+//! This is a structural extension of the existing `onto_shacl` and+//! `onto_shacl_check`: same SHACL semantics, but the validator sees the+//! reasoner's output instead of the raw ABox.+//!+//! ## Bounded scope+//!+//! - Profile: `owl-rl` (the standard for SHACL co-evolution per the paper).+//! - Operates on a **sandbox copy** of the graph so the caller's ABox is+//! not permanently materialised.+//! - Returns a unified report: pre-reasoning conformance, post-reasoning+//! conformance, and the count of triples the reasoner added.++use crate::graph::GraphStore;+use crate::reason::Reasoner;+use crate::shacl::ShaclValidator;+use serde::Serialize;+use std::sync::Arc;++/// Report from a co-evolve check.+#[derive(Clone, Debug, Serialize)]+pub struct CoevolveReport {+ /// Conformance verdict against the un-materialised graph (matches+ /// `onto_shacl`'s output).+ pub pre_reasoning: String,+ /// Conformance verdict against the OWL-RL closure. This is the verdict+ /// that matters for SHACL co-evolution.+ pub post_reasoning: String,+ /// Triples added by OWL-RL materialisation.+ pub triples_inferred: usize,+ /// The reasoner profile run (e.g. "owl-rl").+ pub profile: String,+}++/// Run combined OWL+SHACL validation. The original `graph` is NOT mutated —+/// reasoning happens against a sandbox copy.+pub fn coevolve_check(+ graph: &Arc<GraphStore>,+ shapes_ttl: &str,+ profile: &str,+) -> anyhow::Result<CoevolveReport> {+ let pre = ShaclValidator::validate(graph, shapes_ttl)?;++ // Sandbox: copy current triples into a fresh store, run reasoner there.+ let sandbox = Arc::new(GraphStore::new());+ let triples = graph.all_triples()?;+ if !triples.is_empty() {+ let mut nt = String::with_capacity(triples.len() * 64);+ for (s, p, o) in &triples {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ sandbox.load_turtle(&nt, None)?;+ }+ let pre_count = sandbox.triple_count();+ let _ = Reasoner::run(&sandbox, profile, true)?;+ let post_count = sandbox.triple_count();+ let inferred = post_count.saturating_sub(pre_count);+ let post = ShaclValidator::validate(&sandbox, shapes_ttl)?;++ Ok(CoevolveReport {+ pre_reasoning: pre,+ post_reasoning: post,+ triples_inferred: inferred,+ profile: profile.to_string(),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn coevolve_returns_both_verdicts_and_inferred_count() {+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .+ ex:tigger a ex:Cat .+ "#,+ None,+ )+ .unwrap();+ let shapes = r#"+ @prefix sh: <http://www.w3.org/ns/shacl#> .+ @prefix ex: <http://ex.org/> .+ ex:AnimalShape a sh:NodeShape ; sh:targetClass ex:Animal .+ "#;+ let report = coevolve_check(&graph, shapes, "owl-rl").unwrap();+ // Both verdicts are non-empty JSON.+ assert!(!report.pre_reasoning.is_empty());+ assert!(!report.post_reasoning.is_empty());+ assert_eq!(report.profile, "owl-rl");+ // The original graph is not mutated.+ let original_count = graph.triple_count();+ assert!(+ original_count <= 10,+ "original graph should be small; got {}",+ original_count+ );+ }++ #[test]+ fn coevolve_does_not_mutate_original_graph() {+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .+ ex:Animal a owl:Class .+ ex:tigger a ex:Cat .+ "#,+ None,+ )+ .unwrap();+ let pre = graph.triple_count();+ let shapes = "@prefix sh: <http://www.w3.org/ns/shacl#> . @prefix ex: <http://ex.org/> . ex:S a sh:NodeShape ; sh:targetClass ex:Animal .";+ let _ = coevolve_check(&graph, shapes, "owl-rl").unwrap();+ let post = graph.triple_count();+ assert_eq!(pre, post, "original graph mutated by co-evolve check");+ }++ #[test]+ fn coevolve_records_profile_string() {+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle("@prefix ex: <http://ex.org/> . ex:A a ex:B .", None)+ .unwrap();+ let report = coevolve_check(&graph, "", "rdfs").unwrap();+ assert_eq!(report.profile, "rdfs");+ }+}diff --git a/src/cq.rs b/src/cq.rsnew file mode 100644index 00000000..e50f7dcb--- /dev/null+++ b/src/cq.rs@@ -0,0 +1,285 @@+//! Competency-question runner + LLM-assisted verification (#29 + #39).+//!+//! Competency questions (CQs) are the OBO/Foundry standard for documenting+//! what an ontology is supposed to answer. A CQ is typically a natural-+//! language question paired with a SPARQL query whose result set+//! constitutes the answer.+//!+//! This module provides:+//!+//! - `run_cq_suite` (#29): run a batch of CQs, return pass/fail per CQ+//! plus VSPO-pitfall hints when a CQ returns empty or returns+//! surprising shape.+//! - `verify_cq` (#39, ISWC 2025 Lippolis): take a CQ result + an+//! LLM-supplied judgement (was the answer correct?) and persist it as+//! feedback. The server doesn't run the LLM — it stores + retrieves+//! verdicts, mirroring the borderline-pair convention from `onto_align`.++use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct CompetencyQuestion {+ pub id: String,+ pub question: String,+ pub sparql: String,+ /// Optional expected row count (None = any non-empty result is a pass).+ #[serde(default)]+ pub expected_min_rows: Option<usize>,+}++#[derive(Clone, Debug, Serialize)]+pub struct CqRunReport {+ pub total: usize,+ pub passed: usize,+ pub results: Vec<CqResult>,+}++#[derive(Clone, Debug, Serialize)]+pub struct CqResult {+ pub id: String,+ pub passed: bool,+ pub row_count: usize,+ /// VSPO-style pitfall hints (Villalón-Suárez-Poveda-Otero pitfall list).+ pub pitfalls: Vec<String>,+ /// Truncated raw result for inspection.+ pub raw_excerpt: String,+}++const VSPO_HINT_EMPTY: &str = "P10: ontology returns no answer (possible missing rdfs:domain/range or sub-ontology declaration)";+const VSPO_HINT_NO_LABELS: &str = "P11: no rdfs:label on returned IRIs (LLM cannot phrase the answer)";+const VSPO_HINT_INFINITE: &str = "P12: result row count > 10000 (possible cycle in rdfs:subClassOf or no LIMIT clause)";++/// Run a batch of competency questions against the loaded graph.+pub fn run_cq_suite(graph: &Arc<GraphStore>, cqs: &[CompetencyQuestion]) -> CqRunReport {+ let mut results: Vec<CqResult> = Vec::with_capacity(cqs.len());+ let mut passed = 0usize;+ for cq in cqs {+ let mut pitfalls: Vec<String> = Vec::new();+ let (row_count, excerpt) = match graph.sparql_select(&cq.sparql) {+ Ok(js) => {+ let v: serde_json::Value =+ serde_json::from_str(&js).unwrap_or(serde_json::Value::Null);+ let rows = v["results"].as_array().cloned().unwrap_or_default();+ if rows.is_empty() {+ pitfalls.push(VSPO_HINT_EMPTY.to_string());+ }+ if rows.len() > 10000 {+ pitfalls.push(VSPO_HINT_INFINITE.to_string());+ }+ // No-labels heuristic: scan first 5 rows for any rdfs:label.+ let snip: String = rows+ .iter()+ .take(5)+ .map(|r| r.to_string())+ .collect::<Vec<_>>()+ .join(", ");+ if !snip.is_empty() && !snip.contains("label") {+ pitfalls.push(VSPO_HINT_NO_LABELS.to_string());+ }+ let excerpt = if js.len() > 800 {+ format!("{}...", &js[..800])+ } else {+ js+ };+ (rows.len(), excerpt)+ }+ Err(e) => (0, format!("error: {}", e)),+ };+ let pass = match cq.expected_min_rows {+ Some(n) => row_count >= n,+ None => row_count > 0,+ };+ if pass {+ passed += 1;+ }+ results.push(CqResult {+ id: cq.id.clone(),+ passed: pass,+ row_count,+ pitfalls,+ raw_excerpt: excerpt,+ });+ }+ CqRunReport {+ total: cqs.len(),+ passed,+ results,+ }+}++// ─── Verification feedback persistence (#39) ────────────────────────────────++const ENSURE_CQ_VERDICT_TABLE: &str = "+CREATE TABLE IF NOT EXISTS cq_verdicts (+ cq_id TEXT NOT NULL,+ verdict TEXT NOT NULL CHECK (verdict IN ('correct', 'incorrect', 'partial')),+ rationale TEXT,+ judge TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ PRIMARY KEY (cq_id, judge, created_at)+)";++fn ensure_cq_verdicts(db: &StateDb) -> anyhow::Result<()> {+ db.conn().execute(ENSURE_CQ_VERDICT_TABLE, [])?;+ Ok(())+}++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct CqVerdict {+ pub cq_id: String,+ /// One of `"correct"`, `"incorrect"`, `"partial"`.+ pub verdict: String,+ #[serde(default)]+ pub rationale: Option<String>,+ /// Identifier of the judging entity (e.g. `"claude"`, `"alice@org"`).+ #[serde(default)]+ pub judge: Option<String>,+}++/// Persist an LLM-supplied (or human-supplied) verdict on a CQ result.+pub fn verify_cq(db: &StateDb, verdict: &CqVerdict) -> anyhow::Result<()> {+ if !matches!(verdict.verdict.as_str(), "correct" | "incorrect" | "partial") {+ anyhow::bail!(+ "invalid verdict `{}`: must be correct/incorrect/partial",+ verdict.verdict+ );+ }+ ensure_cq_verdicts(db)?;+ db.conn().execute(+ "INSERT INTO cq_verdicts (cq_id, verdict, rationale, judge) VALUES (?1, ?2, ?3, ?4)",+ rusqlite::params![+ verdict.cq_id,+ verdict.verdict,+ verdict.rationale,+ verdict.judge.clone().unwrap_or_else(|| "anonymous".to_string()),+ ],+ )?;+ Ok(())+}++/// List all verdicts for a given CQ, most-recent first.+pub fn list_cq_verdicts(db: &StateDb, cq_id: &str) -> anyhow::Result<Vec<CqVerdict>> {+ ensure_cq_verdicts(db)?;+ let conn = db.conn();+ let mut stmt = conn.prepare(+ "SELECT cq_id, verdict, rationale, judge FROM cq_verdicts WHERE cq_id = ?1 ORDER BY created_at DESC",+ )?;+ let rows: Vec<CqVerdict> = stmt+ .query_map(rusqlite::params![cq_id], |r| {+ Ok(CqVerdict {+ cq_id: r.get(0)?,+ verdict: r.get(1)?,+ rationale: r.get(2)?,+ judge: r.get(3)?,+ })+ })?+ .filter_map(Result::ok)+ .collect();+ Ok(rows)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::Path;++ fn fresh_db() -> StateDb {+ StateDb::open(Path::new(":memory:")).unwrap()+ }++ fn graph_with_classes() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Cat a owl:Class ; rdfs:label "Cat" .+ ex:Dog a owl:Class ; rdfs:label "Dog" .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn run_cq_suite_marks_non_empty_result_as_pass() {+ let g = graph_with_classes();+ let cqs = vec![CompetencyQuestion {+ id: "cq1".to_string(),+ question: "What classes are declared?".to_string(),+ sparql: "SELECT ?c WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ expected_min_rows: None,+ }];+ let report = run_cq_suite(&g, &cqs);+ assert_eq!(report.passed, 1);+ assert_eq!(report.results[0].id, "cq1");+ assert!(report.results[0].passed);+ }++ #[test]+ fn run_cq_suite_flags_empty_with_vspo_p10() {+ let g = graph_with_classes();+ let cqs = vec![CompetencyQuestion {+ id: "cq_empty".to_string(),+ question: "Find non-existent class.".to_string(),+ sparql: "SELECT ?c WHERE { ?c a <http://ex.org/NoSuchClass> }".to_string(),+ expected_min_rows: None,+ }];+ let report = run_cq_suite(&g, &cqs);+ assert_eq!(report.passed, 0);+ assert!(report.results[0].pitfalls.iter().any(|p| p.starts_with("P10")));+ }++ #[test]+ fn verify_cq_persists_and_lists_verdicts() {+ let db = fresh_db();+ verify_cq(+ &db,+ &CqVerdict {+ cq_id: "cq1".to_string(),+ verdict: "correct".to_string(),+ rationale: Some("Returned both Cat and Dog as expected".to_string()),+ judge: Some("claude".to_string()),+ },+ )+ .unwrap();+ let listed = list_cq_verdicts(&db, "cq1").unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].verdict, "correct");+ }++ #[test]+ fn verify_cq_rejects_invalid_verdict_label() {+ let db = fresh_db();+ let err = verify_cq(+ &db,+ &CqVerdict {+ cq_id: "cq1".to_string(),+ verdict: "maybe".to_string(),+ rationale: None,+ judge: None,+ },+ )+ .expect_err("should reject");+ assert!(format!("{}", err).contains("invalid verdict"));+ }++ #[test]+ fn run_cq_suite_respects_expected_min_rows() {+ let g = graph_with_classes();+ let cqs = vec![CompetencyQuestion {+ id: "cq_min".to_string(),+ question: "At least 5 classes?".to_string(),+ sparql: "SELECT ?c WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ expected_min_rows: Some(5),+ }];+ let report = run_cq_suite(&g, &cqs);+ // Only 2 classes in seed; min 5 → fail.+ assert!(!report.results[0].passed);+ }+}diff --git a/src/dynamics_bcplus.rs b/src/dynamics_bcplus.rsnew file mode 100644index 00000000..7951e847--- /dev/null+++ b/src/dynamics_bcplus.rs@@ -0,0 +1,683 @@+//! Full BC+ semantics extensions for the Dynamics layer (#43 follow-up).+//!+//! v0.4 base shipped the deterministic-single-effect subset of BC++//! (Babb & Lee, arXiv 2506.18044) in `src/dynamics.rs`. This module adds the+//! three semantic pieces previously deferred:+//!+//! 1. **Concurrent actions** — multiple action instances fire in one tick,+//! with effect-conflict detection.+//! 2. **Static causal laws** — invariants the post-state must always+//! satisfy (a SPARQL ASK that must hold). Encoded as a separate+//! registration surface so they survive across actions.+//! 3. **Default values** — caused-by-default triples added to the+//! pre-state when their condition fires and they aren't already+//! asserted.+//!+//! ## What's intentionally NOT shipped+//!+//! - **ASP solver backend.** Full BC+ programs compile to Answer Set+//! Programming for closed-world enumeration of stable models. Wrapping+//! `clingo` as a subprocess is feasible (same pattern as+//! `src/plan_classical.rs` / `src/civex_pywhy.rs`) but adds another+//! external runtime; we ship the in-process semantics first and gate ASP+//! behind a separate optional feature when a use case lands.+//!+//! - **Non-deterministic outcomes in concurrent actions.** A concurrent+//! tick currently requires each action to be deterministic OR each+//! action's sampled outcome to be supplied explicitly via the bindings.+//! Mixing nondeterminism + concurrency cleanly requires sample-coupled+//! stable-model enumeration; deferred until #48 PyWhy ships the causal+//! estimation that would consume those distributions.++use crate::dynamics::{lookup, ActionSchema, EffectSpec};+use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;+use std::sync::Arc;++// ─── Concurrent actions ─────────────────────────────────────────────────────++/// One operator instance in a concurrent tick.+#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct ConcurrentStep {+ pub action_name: String,+ #[serde(default)]+ pub bindings: BTreeMap<String, String>,+}++/// Result of applying a concurrent tick.+#[derive(Clone, Debug, Serialize)]+pub struct ConcurrentApplyResult {+ pub steps_total: usize,+ pub steps_applied: usize,+ /// Conflict descriptions when concurrent steps disagree on a triple.+ /// Empty when the tick was conflict-free.+ pub conflicts: Vec<ConflictReport>,+ pub triples_added: usize,+ pub triples_removed: usize,+ /// Invariants (static causal laws) that failed AFTER the tick. Empty+ /// when every registered invariant still holds.+ pub invariant_violations: Vec<String>,+}++/// One conflict between two concurrent steps.+#[derive(Clone, Debug, Serialize, PartialEq, Eq)]+pub struct ConflictReport {+ pub triple: (String, String, String),+ pub adding_step: usize,+ pub removing_step: usize,+ pub reason: String,+}++/// Apply a tick of `steps` concurrently. Effects are pre-computed for every+/// step against the **pre-tick** state, then conflict-checked, then committed+/// atomically. If conflicts exist, NO step is applied (atomic-fail).+/// Invariants (registered via [`register_invariant`]) are re-checked after+/// commit; if any fails the tick is rolled back.+pub fn apply_concurrent(+ db: &StateDb,+ graph: &Arc<GraphStore>,+ steps: &[ConcurrentStep],+) -> anyhow::Result<ConcurrentApplyResult> {+ let mut planned_adds: Vec<BTreeSet<(String, String, String)>> = Vec::with_capacity(steps.len());+ let mut planned_removes: Vec<BTreeSet<(String, String, String)>> = Vec::with_capacity(steps.len());++ // ── Step 1: compute each action's effects against the pre-tick state.+ for step in steps {+ let schema: ActionSchema = lookup(db, &step.action_name)?+ .ok_or_else(|| anyhow::anyhow!("unknown action: {}", step.action_name))?;+ let bindings: Vec<(String, String)> = step+ .bindings+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();++ // Effects must come from `effects` directly (non-deterministic+ // sampling in concurrent context is deferred — see module docstring).+ if !schema.outcomes.is_empty() {+ anyhow::bail!(+ "non_deterministic_in_concurrent_tick: action `{}` has outcomes; not supported in concurrent ticks. \+ Pre-sample with apply_with_seed and pass an `effects`-shaped schema instead.",+ step.action_name+ );+ }+ let mut adds = BTreeSet::new();+ let mut removes = BTreeSet::new();+ for effect in &schema.effects {+ let triple = match effect {+ EffectSpec::AddTriple { subject, predicate, object } => {+ let s = schema.substitute(subject, &bindings);+ let p = schema.substitute(predicate, &bindings);+ let o = schema.substitute(object, &bindings);+ adds.insert((s, p, o));+ continue;+ }+ EffectSpec::RemoveTriple { subject, predicate, object } => {+ let s = schema.substitute(subject, &bindings);+ let p = schema.substitute(predicate, &bindings);+ let o = schema.substitute(object, &bindings);+ removes.insert((s, p, o));+ continue;+ }+ EffectSpec::AddClass { iri } => {+ let s = schema.substitute(iri, &bindings);+ (+ s,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ "http://www.w3.org/2002/07/owl#Class".to_string(),+ )+ }+ };+ adds.insert(triple);+ }+ planned_adds.push(adds);+ planned_removes.push(removes);+ }++ // ── Step 2: detect conflicts (add ∩ remove across distinct steps).+ let mut conflicts: Vec<ConflictReport> = Vec::new();+ for (i, adds) in planned_adds.iter().enumerate() {+ for (j, removes) in planned_removes.iter().enumerate() {+ if i == j {+ continue;+ }+ for t in adds.intersection(removes) {+ conflicts.push(ConflictReport {+ triple: t.clone(),+ adding_step: i,+ removing_step: j,+ reason: "concurrent add/remove of the same triple".to_string(),+ });+ }+ }+ }+ if !conflicts.is_empty() {+ return Ok(ConcurrentApplyResult {+ steps_total: steps.len(),+ steps_applied: 0,+ conflicts,+ triples_added: 0,+ triples_removed: 0,+ invariant_violations: Vec::new(),+ });+ }++ // ── Step 3: commit. Union of all adds, union of all removes.+ let all_adds: BTreeSet<(String, String, String)> = planned_adds.iter().flatten().cloned().collect();+ let all_removes: BTreeSet<(String, String, String)> = planned_removes.iter().flatten().cloned().collect();++ if !all_adds.is_empty() {+ let mut ttl = String::new();+ for (s, p, o) in &all_adds {+ ttl.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ }+ graph.load_turtle(&ttl, None)?;+ }+ for (s, p, o) in &all_removes {+ let update = format!("DELETE DATA {{ <{}> <{}> <{}> }}", s, p, o);+ let _ = graph.sparql_update(&update);+ }++ // ── Step 4: invariants.+ let violations = check_invariants(db, graph)?;+ if !violations.is_empty() {+ // Rollback: re-add removes, remove adds.+ if !all_removes.is_empty() {+ let mut ttl = String::new();+ for (s, p, o) in &all_removes {+ ttl.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ }+ graph.load_turtle(&ttl, None)?;+ }+ for (s, p, o) in &all_adds {+ let update = format!("DELETE DATA {{ <{}> <{}> <{}> }}", s, p, o);+ let _ = graph.sparql_update(&update);+ }+ return Ok(ConcurrentApplyResult {+ steps_total: steps.len(),+ steps_applied: 0,+ conflicts: Vec::new(),+ triples_added: 0,+ triples_removed: 0,+ invariant_violations: violations,+ });+ }++ Ok(ConcurrentApplyResult {+ steps_total: steps.len(),+ steps_applied: steps.len(),+ conflicts: Vec::new(),+ triples_added: all_adds.len(),+ triples_removed: all_removes.len(),+ invariant_violations: Vec::new(),+ })+}++// ─── Static causal laws (invariants) ────────────────────────────────────────++/// A static causal law: a named invariant the post-state must satisfy. The+/// invariant is encoded as a SPARQL ASK that MUST return true.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct StaticCausalLaw {+ pub name: String,+ /// SPARQL ASK query. Must return `true` for the law to hold.+ pub ask_query: String,+ /// Human-readable description.+ #[serde(default)]+ pub description: Option<String>,+}++const ENSURE_LAWS_TABLE: &str = "+CREATE TABLE IF NOT EXISTS bcplus_static_laws (+ name TEXT PRIMARY KEY,+ ask_query TEXT NOT NULL,+ description TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+)";++fn ensure_laws_table(db: &StateDb) -> anyhow::Result<()> {+ db.conn().execute(ENSURE_LAWS_TABLE, [])?;+ Ok(())+}++/// Persist a static causal law. Overwrites any law with the same name.+pub fn register_invariant(db: &StateDb, law: &StaticCausalLaw) -> anyhow::Result<()> {+ ensure_laws_table(db)?;+ db.conn().execute(+ "INSERT OR REPLACE INTO bcplus_static_laws (name, ask_query, description) VALUES (?1, ?2, ?3)",+ rusqlite::params![law.name, law.ask_query, law.description],+ )?;+ Ok(())+}++/// List all registered invariants.+pub fn list_invariants(db: &StateDb) -> anyhow::Result<Vec<StaticCausalLaw>> {+ ensure_laws_table(db)?;+ let conn = db.conn();+ let mut stmt = conn.prepare(+ "SELECT name, ask_query, description FROM bcplus_static_laws ORDER BY name",+ )?;+ let rows: Vec<StaticCausalLaw> = stmt+ .query_map([], |r| {+ Ok(StaticCausalLaw {+ name: r.get(0)?,+ ask_query: r.get(1)?,+ description: r.get(2)?,+ })+ })?+ .filter_map(Result::ok)+ .collect();+ Ok(rows)+}++/// Remove a registered invariant by name.+pub fn remove_invariant(db: &StateDb, name: &str) -> anyhow::Result<bool> {+ ensure_laws_table(db)?;+ let n = db.conn().execute(+ "DELETE FROM bcplus_static_laws WHERE name = ?1",+ rusqlite::params![name],+ )?;+ Ok(n > 0)+}++/// Evaluate every registered invariant against the current graph. Returns+/// the names + descriptions of any that fail.+pub fn check_invariants(db: &StateDb, graph: &Arc<GraphStore>) -> anyhow::Result<Vec<String>> {+ let laws = list_invariants(db)?;+ let mut violations: Vec<String> = Vec::new();+ for law in laws {+ let q = law.ask_query.trim();+ let q = if q.to_uppercase().starts_with("ASK") {+ q.to_string()+ } else {+ format!("ASK {{ {} }}", q)+ };+ let holds = match graph.sparql_select(&q) {+ Ok(s) => s.contains("\"result\":true"),+ Err(_) => false,+ };+ if !holds {+ violations.push(format!(+ "{}: {}",+ law.name,+ law.description+ .unwrap_or_else(|| "(no description)".to_string())+ ));+ }+ }+ Ok(violations)+}++// ─── Default values ─────────────────────────────────────────────────────────++/// A caused-by-default fact: when `condition_ask` holds, ensure each triple+/// in `defaults` is asserted (added if not already present).+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct DefaultLaw {+ pub name: String,+ /// SPARQL ASK that activates the default.+ pub condition_ask: String,+ /// Triples to assert when the condition fires.+ pub defaults: Vec<(String, String, String)>,+ #[serde(default)]+ pub description: Option<String>,+}++const ENSURE_DEFAULTS_TABLE: &str = "+CREATE TABLE IF NOT EXISTS bcplus_default_laws (+ name TEXT PRIMARY KEY,+ law_json TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+)";++fn ensure_defaults_table(db: &StateDb) -> anyhow::Result<()> {+ db.conn().execute(ENSURE_DEFAULTS_TABLE, [])?;+ Ok(())+}++/// Register a default-value law.+pub fn register_default(db: &StateDb, law: &DefaultLaw) -> anyhow::Result<()> {+ ensure_defaults_table(db)?;+ let json = serde_json::to_string(law)?;+ db.conn().execute(+ "INSERT OR REPLACE INTO bcplus_default_laws (name, law_json) VALUES (?1, ?2)",+ rusqlite::params![law.name, json],+ )?;+ Ok(())+}++/// List registered default laws.+pub fn list_defaults(db: &StateDb) -> anyhow::Result<Vec<DefaultLaw>> {+ ensure_defaults_table(db)?;+ let conn = db.conn();+ let mut stmt = conn.prepare(+ "SELECT law_json FROM bcplus_default_laws ORDER BY name",+ )?;+ let rows: Vec<DefaultLaw> = stmt+ .query_map([], |r| r.get::<_, String>(0))?+ .filter_map(|r| r.ok().and_then(|s| serde_json::from_str(&s).ok()))+ .collect();+ Ok(rows)+}++/// Apply every registered default-value law whose condition holds. Adds only+/// triples that don't already exist; idempotent.+pub fn apply_defaults(+ db: &StateDb,+ graph: &Arc<GraphStore>,+) -> anyhow::Result<DefaultsApplyResult> {+ let laws = list_defaults(db)?;+ let mut added: Vec<(String, String, String)> = Vec::new();+ let mut fired: Vec<String> = Vec::new();+ for law in laws {+ let q = law.condition_ask.trim();+ let q = if q.to_uppercase().starts_with("ASK") {+ q.to_string()+ } else {+ format!("ASK {{ {} }}", q)+ };+ let condition_holds = match graph.sparql_select(&q) {+ Ok(s) => s.contains("\"result\":true"),+ Err(_) => false,+ };+ if !condition_holds {+ continue;+ }+ fired.push(law.name.clone());+ for (s, p, o) in &law.defaults {+ // Only add if not already present.+ let exists_q = format!("ASK {{ <{}> <{}> <{}> }}", s, p, o);+ let exists = match graph.sparql_select(&exists_q) {+ Ok(r) => r.contains("\"result\":true"),+ Err(_) => false,+ };+ if !exists {+ let ttl = format!("<{}> <{}> <{}> .\n", s, p, o);+ if graph.load_turtle(&ttl, None).is_ok() {+ added.push((s.clone(), p.clone(), o.clone()));+ }+ }+ }+ }+ Ok(DefaultsApplyResult { laws_fired: fired, triples_added: added })+}++/// Outcome of [`apply_defaults`].+#[derive(Clone, Debug, Serialize)]+pub struct DefaultsApplyResult {+ pub laws_fired: Vec<String>,+ pub triples_added: Vec<(String, String, String)>,+}++#[allow(dead_code)]+fn in_memory_db() -> anyhow::Result<StateDb> {+ StateDb::open(Path::new(":memory:"))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dynamics::{register, ActionSchema, EffectSpec, Parameter};++ fn fresh_db() -> StateDb {+ StateDb::open(Path::new(":memory:")).unwrap()+ }++ fn fresh_graph() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Cat a owl:Class .+ ex:Dog a owl:Class .+ ex:Bird a owl:Class .+ "#,+ None,+ )+ .unwrap();+ g+ }++ fn add_class_schema() -> ActionSchema {+ ActionSchema {+ name: "add_class".to_string(),+ parameters: vec![Parameter { name: "iri".to_string(), type_iri: None }],+ preconditions: vec![],+ effects: vec![EffectSpec::AddClass { iri: "{iri}".to_string() }],+ reversible: true,+ description: None,+ outcomes: vec![],+ }+ }++ #[test]+ fn concurrent_tick_applies_independent_steps_atomically() {+ let db = fresh_db();+ let graph = fresh_graph();+ register(&db, &add_class_schema()).unwrap();+ let mut b1 = BTreeMap::new();+ b1.insert("iri".to_string(), "http://ex.org/Fish".to_string());+ let mut b2 = BTreeMap::new();+ b2.insert("iri".to_string(), "http://ex.org/Reptile".to_string());++ let result = apply_concurrent(+ &db,+ &graph,+ &[+ ConcurrentStep { action_name: "add_class".to_string(), bindings: b1 },+ ConcurrentStep { action_name: "add_class".to_string(), bindings: b2 },+ ],+ )+ .unwrap();+ assert_eq!(result.steps_applied, 2);+ assert_eq!(result.conflicts.len(), 0);+ assert!(result.triples_added >= 2);+ // Both classes must now be declared.+ for iri in ["http://ex.org/Fish", "http://ex.org/Reptile"] {+ let q = format!("ASK {{ <{}> a <http://www.w3.org/2002/07/owl#Class> }}", iri);+ let r = graph.sparql_select(&q).unwrap();+ assert!(r.contains("\"result\":true"), "missing: {}", iri);+ }+ }++ #[test]+ fn concurrent_tick_detects_add_remove_conflict_and_atomically_fails() {+ let db = fresh_db();+ let graph = fresh_graph();+ // Schema A adds triple T; Schema B removes T. Concurrent tick must+ // detect the conflict and apply nothing.+ let add_t = ActionSchema {+ name: "add_t".to_string(),+ parameters: vec![],+ preconditions: vec![],+ effects: vec![EffectSpec::AddTriple {+ subject: "http://ex.org/X".to_string(),+ predicate: "http://ex.org/p".to_string(),+ object: "http://ex.org/Y".to_string(),+ }],+ reversible: true,+ description: None,+ outcomes: vec![],+ };+ let remove_t = ActionSchema {+ name: "remove_t".to_string(),+ parameters: vec![],+ preconditions: vec![],+ effects: vec![EffectSpec::RemoveTriple {+ subject: "http://ex.org/X".to_string(),+ predicate: "http://ex.org/p".to_string(),+ object: "http://ex.org/Y".to_string(),+ }],+ reversible: true,+ description: None,+ outcomes: vec![],+ };+ register(&db, &add_t).unwrap();+ register(&db, &remove_t).unwrap();++ let result = apply_concurrent(+ &db,+ &graph,+ &[+ ConcurrentStep { action_name: "add_t".to_string(), bindings: BTreeMap::new() },+ ConcurrentStep { action_name: "remove_t".to_string(), bindings: BTreeMap::new() },+ ],+ )+ .unwrap();+ assert_eq!(result.steps_applied, 0);+ assert_eq!(result.conflicts.len(), 1);+ assert_eq!(result.triples_added, 0);+ assert_eq!(result.triples_removed, 0);+ }++ #[test]+ fn nondeterministic_action_in_concurrent_tick_is_rejected() {+ // Concurrent ticks require pre-sampled deterministic effects.+ let db = fresh_db();+ let graph = fresh_graph();+ let nondet = ActionSchema {+ name: "noisy".to_string(),+ parameters: vec![],+ preconditions: vec![],+ effects: vec![],+ reversible: true,+ description: None,+ outcomes: vec![+ crate::dynamics::Outcome {+ probability: 0.5,+ effects: vec![EffectSpec::AddClass { iri: "http://ex.org/A".to_string() }],+ label: Some("a".to_string()),+ },+ crate::dynamics::Outcome {+ probability: 0.5,+ effects: vec![EffectSpec::AddClass { iri: "http://ex.org/B".to_string() }],+ label: Some("b".to_string()),+ },+ ],+ };+ register(&db, &nondet).unwrap();+ let err = apply_concurrent(+ &db,+ &graph,+ &[ConcurrentStep { action_name: "noisy".to_string(), bindings: BTreeMap::new() }],+ )+ .expect_err("should reject");+ assert!(format!("{}", err).contains("non_deterministic_in_concurrent_tick"));+ }++ #[test]+ fn static_causal_law_register_and_check_round_trip() {+ let db = fresh_db();+ let graph = fresh_graph();+ let law = StaticCausalLaw {+ name: "cat_must_exist".to_string(),+ ask_query: "ASK { <http://ex.org/Cat> a <http://www.w3.org/2002/07/owl#Class> }".into(),+ description: Some("Cat must always be a class".into()),+ };+ register_invariant(&db, &law).unwrap();+ let violations = check_invariants(&db, &graph).unwrap();+ assert!(violations.is_empty(), "cat exists, no violation expected");++ // Remove Cat → invariant should fire.+ let _ = graph.sparql_update(+ "DELETE DATA { <http://ex.org/Cat> a <http://www.w3.org/2002/07/owl#Class> }",+ );+ let violations = check_invariants(&db, &graph).unwrap();+ assert_eq!(violations.len(), 1);+ assert!(violations[0].contains("cat_must_exist"));+ }++ #[test]+ fn concurrent_tick_rolls_back_when_invariant_violated() {+ let db = fresh_db();+ let graph = fresh_graph();+ // Invariant: Cat must remain a class.+ register_invariant(+ &db,+ &StaticCausalLaw {+ name: "cat_must_exist".to_string(),+ ask_query: "ASK { <http://ex.org/Cat> a <http://www.w3.org/2002/07/owl#Class> }".into(),+ description: None,+ },+ )+ .unwrap();+ // Schema that removes Cat.+ let remove_cat = ActionSchema {+ name: "remove_cat".to_string(),+ parameters: vec![],+ preconditions: vec![],+ effects: vec![EffectSpec::RemoveTriple {+ subject: "http://ex.org/Cat".to_string(),+ predicate: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ object: "http://www.w3.org/2002/07/owl#Class".to_string(),+ }],+ reversible: true,+ description: None,+ outcomes: vec![],+ };+ register(&db, &remove_cat).unwrap();++ let initial_count = graph.triple_count();+ let result = apply_concurrent(+ &db,+ &graph,+ &[ConcurrentStep { action_name: "remove_cat".to_string(), bindings: BTreeMap::new() }],+ )+ .unwrap();+ assert_eq!(result.steps_applied, 0);+ assert_eq!(result.invariant_violations.len(), 1);+ // Rollback worked: the graph still has the original count.+ assert_eq!(graph.triple_count(), initial_count);+ }++ #[test]+ fn default_law_fires_only_when_condition_holds() {+ let db = fresh_db();+ let graph = fresh_graph();+ // Default: when ex:Cat is a class, assert that Cat has a default label.+ let law = DefaultLaw {+ name: "cat_default_label".to_string(),+ condition_ask:+ "ASK { <http://ex.org/Cat> a <http://www.w3.org/2002/07/owl#Class> }".into(),+ defaults: vec![(+ "http://ex.org/Cat".into(),+ "http://www.w3.org/2000/01/rdf-schema#label".into(),+ "http://ex.org/cat_default_iri".into(),+ )],+ description: None,+ };+ register_default(&db, &law).unwrap();+ let result = apply_defaults(&db, &graph).unwrap();+ assert_eq!(result.laws_fired, vec!["cat_default_label"]);+ assert_eq!(result.triples_added.len(), 1);++ // Idempotent: re-apply, nothing added.+ let result2 = apply_defaults(&db, &graph).unwrap();+ assert_eq!(result2.triples_added.len(), 0);+ }++ #[test]+ fn default_law_does_not_fire_when_condition_is_false() {+ let db = fresh_db();+ let graph = fresh_graph();+ let law = DefaultLaw {+ name: "fish_default_label".to_string(),+ // ex:Fish is NOT in the seed graph.+ condition_ask:+ "ASK { <http://ex.org/Fish> a <http://www.w3.org/2002/07/owl#Class> }".into(),+ defaults: vec![(+ "http://ex.org/Fish".into(),+ "http://www.w3.org/2000/01/rdf-schema#label".into(),+ "http://ex.org/fish_iri".into(),+ )],+ description: None,+ };+ register_default(&db, &law).unwrap();+ let result = apply_defaults(&db, &graph).unwrap();+ assert!(result.laws_fired.is_empty());+ assert!(result.triples_added.is_empty());+ }+}diff --git a/src/eval_alignment.rs b/src/eval_alignment.rsnew file mode 100644index 00000000..ba31c4d9--- /dev/null+++ b/src/eval_alignment.rs@@ -0,0 +1,142 @@+//! OAEI-style alignment evaluation harness (#31).+//!+//! Given a reference alignment (gold standard) and a computed alignment+//! (e.g. from `onto_align`), compute precision / recall / F1 against the+//! reference. Mirrors the [OAEI](http://oaei.ontologymatching.org/) scoring+//! convention: alignments are sets of `(source_iri, target_iri, relation)`+//! triples; an entry matches the reference iff all three components match.++use serde::{Deserialize, Serialize};+use std::collections::BTreeSet;++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]+pub struct AlignmentEntry {+ pub source: String,+ pub target: String,+ /// One of `"equivalent"`, `"subsumes"`, `"subsumed_by"`. Defaults to+ /// `"equivalent"` on deserialise if missing.+ #[serde(default = "default_relation")]+ pub relation: String,+}++fn default_relation() -> String {+ "equivalent".to_string()+}++#[derive(Clone, Debug, Serialize)]+pub struct EvaluationReport {+ pub precision: f64,+ pub recall: f64,+ pub f1: f64,+ pub true_positive: usize,+ pub false_positive: usize,+ pub false_negative: usize,+ pub reference_size: usize,+ pub computed_size: usize,+}++/// Evaluate `computed` against `reference`. Entries are matched on+/// `(source, target, relation)` exact equality.+pub fn evaluate(reference: &[AlignmentEntry], computed: &[AlignmentEntry]) -> EvaluationReport {+ let ref_set: BTreeSet<&AlignmentEntry> = reference.iter().collect();+ let comp_set: BTreeSet<&AlignmentEntry> = computed.iter().collect();++ let tp = ref_set.intersection(&comp_set).count();+ let fp = comp_set.len() - tp;+ let fn_ = ref_set.len() - tp;++ let precision = if computed.is_empty() {+ 0.0+ } else {+ tp as f64 / computed.len() as f64+ };+ let recall = if reference.is_empty() {+ 0.0+ } else {+ tp as f64 / reference.len() as f64+ };+ let f1 = if precision + recall == 0.0 {+ 0.0+ } else {+ 2.0 * precision * recall / (precision + recall)+ };++ EvaluationReport {+ precision,+ recall,+ f1,+ true_positive: tp,+ false_positive: fp,+ false_negative: fn_,+ reference_size: reference.len(),+ computed_size: computed.len(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn e(s: &str, t: &str) -> AlignmentEntry {+ AlignmentEntry {+ source: s.to_string(),+ target: t.to_string(),+ relation: "equivalent".to_string(),+ }+ }++ #[test]+ fn perfect_match_gives_f1_1() {+ let r = vec![e("A", "X"), e("B", "Y")];+ let c = vec![e("A", "X"), e("B", "Y")];+ let report = evaluate(&r, &c);+ assert_eq!(report.precision, 1.0);+ assert_eq!(report.recall, 1.0);+ assert_eq!(report.f1, 1.0);+ assert_eq!(report.true_positive, 2);+ }++ #[test]+ fn complete_miss_gives_f1_0() {+ let r = vec![e("A", "X")];+ let c = vec![e("B", "Y")];+ let report = evaluate(&r, &c);+ assert_eq!(report.precision, 0.0);+ assert_eq!(report.recall, 0.0);+ assert_eq!(report.f1, 0.0);+ assert_eq!(report.false_positive, 1);+ assert_eq!(report.false_negative, 1);+ }++ #[test]+ fn partial_overlap_gives_intermediate_f1() {+ let r = vec![e("A", "X"), e("B", "Y"), e("C", "Z")];+ let c = vec![e("A", "X"), e("D", "W")];+ let report = evaluate(&r, &c);+ // P = 1/2 = 0.5, R = 1/3 ≈ 0.333, F1 = 2*0.5*0.333/(0.5+0.333) = 0.4+ assert!((report.precision - 0.5).abs() < 1e-9);+ assert!((report.recall - 1.0/3.0).abs() < 1e-9);+ assert!((report.f1 - 0.4).abs() < 1e-3);+ }++ #[test]+ fn empty_computed_gives_zero_precision_zero_recall() {+ let r = vec![e("A", "X")];+ let c: Vec<AlignmentEntry> = vec![];+ let report = evaluate(&r, &c);+ assert_eq!(report.precision, 0.0);+ assert_eq!(report.recall, 0.0);+ assert_eq!(report.false_negative, 1);+ }++ #[test]+ fn relation_mismatch_counts_as_miss() {+ let r = vec![e("A", "X")];+ let mut c = vec![e("A", "X")];+ c[0].relation = "subsumes".to_string();+ let report = evaluate(&r, &c);+ assert_eq!(report.precision, 0.0);+ assert_eq!(report.recall, 0.0);+ assert_eq!(report.true_positive, 0);+ }+}diff --git a/src/eval_rag.rs b/src/eval_rag.rsnew file mode 100644index 00000000..72be59c2--- /dev/null+++ b/src/eval_rag.rs@@ -0,0 +1,160 @@+//! mmRAG benchmark adapter (#41, ISWC 2025).+//!+//! Implements the multi-modal RAG evaluation scoring convention from+//! the ISWC 2025 mmRAG paper. Given a set of QA pairs + the retriever's+//! answers + the gold answers, compute:+//!+//! - **Hit@k**: fraction of questions whose gold-IRI appears in the+//! retriever's top-k.+//! - **MRR**: Mean Reciprocal Rank — `1/(rank of first correct hit)`+//! averaged over questions.+//! - **Exact-match accuracy**: fraction of questions where the+//! retriever's top-1 equals the gold.+//!+//! Pairs with `onto_segment_retrieve` (#34) for the retriever side and+//! `graph_projection_lossy_check` (#35) for slice quality audit.++use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct RagQa {+ pub question_id: String,+ /// Gold-standard answer IRI.+ pub gold_iri: String,+ /// Retriever's ranked list of candidate IRIs (most-relevant first).+ pub retrieved: Vec<String>,+}++#[derive(Clone, Debug, Serialize)]+pub struct RagEvalReport {+ pub total: usize,+ pub exact_match_at_1: f64,+ pub hit_at_3: f64,+ pub hit_at_5: f64,+ pub hit_at_10: f64,+ pub mrr: f64,+ /// Per-question rank of the gold IRI; `0` means "not retrieved within+ /// the supplied top-k".+ pub per_question_rank: Vec<usize>,+}++/// Score a batch of QA results.+pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {+ if qas.is_empty() {+ return RagEvalReport {+ total: 0,+ exact_match_at_1: 0.0,+ hit_at_3: 0.0,+ hit_at_5: 0.0,+ hit_at_10: 0.0,+ mrr: 0.0,+ per_question_rank: Vec::new(),+ };+ }+ let n = qas.len() as f64;+ let mut em1 = 0usize;+ let mut h3 = 0usize;+ let mut h5 = 0usize;+ let mut h10 = 0usize;+ let mut mrr_sum = 0.0_f64;+ let mut ranks: Vec<usize> = Vec::with_capacity(qas.len());++ for qa in qas {+ let rank = qa+ .retrieved+ .iter()+ .position(|iri| iri == &qa.gold_iri)+ .map(|i| i + 1)+ .unwrap_or(0);+ ranks.push(rank);+ if rank == 1 {+ em1 += 1;+ }+ if (1..=3).contains(&rank) {+ h3 += 1;+ }+ if (1..=5).contains(&rank) {+ h5 += 1;+ }+ if (1..=10).contains(&rank) {+ h10 += 1;+ }+ if rank > 0 {+ mrr_sum += 1.0 / rank as f64;+ }+ }++ RagEvalReport {+ total: qas.len(),+ exact_match_at_1: em1 as f64 / n,+ hit_at_3: h3 as f64 / n,+ hit_at_5: h5 as f64 / n,+ hit_at_10: h10 as f64 / n,+ mrr: mrr_sum / n,+ per_question_rank: ranks,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn qa(id: &str, gold: &str, retrieved: &[&str]) -> RagQa {+ RagQa {+ question_id: id.to_string(),+ gold_iri: gold.to_string(),+ retrieved: retrieved.iter().map(|s| s.to_string()).collect(),+ }+ }++ #[test]+ fn perfect_top_1_gives_exact_match_1() {+ let qas = vec![+ qa("q1", "A", &["A", "B", "C"]),+ qa("q2", "X", &["X", "Y"]),+ ];+ let r = evaluate(&qas);+ assert_eq!(r.exact_match_at_1, 1.0);+ assert_eq!(r.mrr, 1.0);+ assert_eq!(r.hit_at_3, 1.0);+ }++ #[test]+ fn gold_not_retrieved_gives_rank_0() {+ let qas = vec![qa("q1", "Z", &["A", "B", "C"])];+ let r = evaluate(&qas);+ assert_eq!(r.exact_match_at_1, 0.0);+ assert_eq!(r.mrr, 0.0);+ assert_eq!(r.per_question_rank[0], 0);+ }++ #[test]+ fn mrr_weights_top_ranks_higher() {+ // q1: rank 1 → 1.0; q2: rank 4 → 0.25. MRR = (1.0 + 0.25) / 2 = 0.625.+ let qas = vec![+ qa("q1", "A", &["A", "B", "C", "D"]),+ qa("q2", "X", &["W", "Y", "Z", "X"]),+ ];+ let r = evaluate(&qas);+ assert!((r.mrr - 0.625).abs() < 1e-9, "got mrr={}", r.mrr);+ assert_eq!(r.per_question_rank, vec![1, 4]);+ }++ #[test]+ fn hit_at_k_buckets_are_monotonic() {+ // Rank 5: hit@5=1, hit@3=0, hit@10=1.+ let qas = vec![qa("q1", "X", &["A", "B", "C", "D", "X"])];+ let r = evaluate(&qas);+ assert_eq!(r.hit_at_3, 0.0);+ assert_eq!(r.hit_at_5, 1.0);+ assert_eq!(r.hit_at_10, 1.0);+ }++ #[test]+ fn empty_input_gives_zero_metrics() {+ let r = evaluate(&[]);+ assert_eq!(r.total, 0);+ assert_eq!(r.mrr, 0.0);+ assert_eq!(r.exact_match_at_1, 0.0);+ }+}diff --git a/src/extract_scaffold.rs b/src/extract_scaffold.rsnew file mode 100644index 00000000..baa218e8--- /dev/null+++ b/src/extract_scaffold.rs@@ -0,0 +1,243 @@+//! Schema-guided structured-extraction scaffolding (#28, OntoGPT SPIRES,+//! MCP-native).+//!+//! Per the MCP-native convention: the server does NOT run an LLM. It provides+//! the *scaffolding* — schema → prompt template, prompt → schema-conformance+//! check — and the orchestrator (Claude) supplies the LLM output that the+//! server validates.+//!+//! ## What this primitive does+//!+//! Given an ontology class IRI and the loaded ontology, emit a prompt+//! template that asks an LLM to extract instances of that class as JSON,+//! constrained by the class's `rdfs:label`, `rdfs:comment`, and the property+//! shapes derived from `rdfs:domain` + `rdfs:range` triples that target it.+//! The companion validator function (`validate_extraction`) then checks an+//! LLM-supplied JSON against the schema.++use crate::graph::GraphStore;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ExtractionScaffold {+ pub class_iri: String,+ pub class_label: Option<String>,+ pub class_comment: Option<String>,+ /// `{property_iri: range_iri or "literal"}`.+ pub property_schema: Vec<PropertySpec>,+ /// Prompt template ready to send to the orchestrator's LLM.+ pub prompt_template: String,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct PropertySpec {+ pub property_iri: String,+ pub property_label: Option<String>,+ pub range: String,+ pub required: bool,+}++/// Build an extraction scaffold for `class_iri` from the loaded ontology.+pub fn build_scaffold(graph: &Arc<GraphStore>, class_iri: &str) -> anyhow::Result<ExtractionScaffold> {+ let label = single_str(graph, class_iri, "http://www.w3.org/2000/01/rdf-schema#label");+ let comment = single_str(graph, class_iri, "http://www.w3.org/2000/01/rdf-schema#comment");++ // Properties whose rdfs:domain is class_iri.+ let q = format!(+ r#"SELECT ?p ?range ?lbl WHERE {{+ ?p <http://www.w3.org/2000/01/rdf-schema#domain> <{}> .+ OPTIONAL {{ ?p <http://www.w3.org/2000/01/rdf-schema#range> ?range }}+ OPTIONAL {{ ?p <http://www.w3.org/2000/01/rdf-schema#label> ?lbl }}+ }}"#,+ class_iri+ );+ let mut props: Vec<PropertySpec> = Vec::new();+ if let Ok(js) = graph.sparql_select(&q)+ && let Ok(v) = serde_json::from_str::<serde_json::Value>(&js)+ && let Some(rows) = v["results"].as_array()+ {+ for row in rows {+ if let Some(p) = row["p"].as_str() {+ let p = p.trim_matches(|c| c == '<' || c == '>').to_string();+ let range = row["range"]+ .as_str()+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())+ .unwrap_or_else(|| "literal".to_string());+ let lbl = row["lbl"]+ .as_str()+ .map(|s| s.trim_matches('"').to_string());+ props.push(PropertySpec {+ property_iri: p,+ property_label: lbl,+ range,+ required: false,+ });+ }+ }+ }++ let mut prompt = format!(+ "Extract every instance of `{}` from the supplied text and emit as JSON.\n\+ The class represents: {}\n\+ Description: {}\n\n\+ Each instance must be an object with these fields:\n",+ class_iri,+ label.as_deref().unwrap_or("(no label)"),+ comment.as_deref().unwrap_or("(no description)")+ );+ for p in &props {+ prompt.push_str(&format!(+ " - `{}` (range: `{}`{})\n",+ p.property_label.as_deref().unwrap_or(&p.property_iri),+ p.range,+ if p.required { ", required" } else { "" }+ ));+ }+ prompt.push_str("\nReturn a JSON array `[ {...}, {...} ]`. Use `null` for unknown fields.");++ Ok(ExtractionScaffold {+ class_iri: class_iri.to_string(),+ class_label: label,+ class_comment: comment,+ property_schema: props,+ prompt_template: prompt,+ })+}++/// Validate an LLM-supplied JSON extraction against the scaffold. Returns+/// per-instance OK/error reports.+#[derive(Clone, Debug, Serialize)]+pub struct ValidationReport {+ pub total: usize,+ pub valid: usize,+ pub issues: Vec<ValidationIssue>,+}++#[derive(Clone, Debug, Serialize)]+pub struct ValidationIssue {+ pub instance_index: usize,+ pub field: Option<String>,+ pub message: String,+}++pub fn validate_extraction(+ scaffold: &ExtractionScaffold,+ extraction_json: &str,+) -> anyhow::Result<ValidationReport> {+ let v: serde_json::Value = serde_json::from_str(extraction_json)?;+ let arr = v.as_array().ok_or_else(|| anyhow::anyhow!("extraction must be a JSON array"))?;+ let mut issues: Vec<ValidationIssue> = Vec::new();+ let mut valid = 0usize;+ for (i, inst) in arr.iter().enumerate() {+ let Some(obj) = inst.as_object() else {+ issues.push(ValidationIssue {+ instance_index: i,+ field: None,+ message: "instance is not a JSON object".to_string(),+ });+ continue;+ };+ let mut instance_ok = true;+ for spec in &scaffold.property_schema {+ let key = spec.property_label.as_deref().unwrap_or(&spec.property_iri);+ if spec.required && !obj.contains_key(key) {+ issues.push(ValidationIssue {+ instance_index: i,+ field: Some(key.to_string()),+ message: format!("required field `{}` missing", key),+ });+ instance_ok = false;+ }+ }+ if instance_ok {+ valid += 1;+ }+ }+ Ok(ValidationReport {+ total: arr.len(),+ valid,+ issues,+ })+}++fn single_str(graph: &Arc<GraphStore>, iri: &str, pred: &str) -> Option<String> {+ let q = format!("SELECT ?v WHERE {{ <{}> <{}> ?v }} LIMIT 1", iri, pred);+ let js = graph.sparql_select(&q).ok()?;+ let v: serde_json::Value = serde_json::from_str(&js).ok()?;+ v["results"][0]["v"]+ .as_str()+ .map(|s| s.trim_matches(|c| c == '"' || c == '<' || c == '>').to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn graph_with_class() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Person a owl:Class ;+ rdfs:label "Person" ;+ rdfs:comment "A human being." .+ ex:name a owl:DatatypeProperty ;+ rdfs:domain ex:Person ;+ rdfs:range <http://www.w3.org/2001/XMLSchema#string> ;+ rdfs:label "name" .+ ex:age a owl:DatatypeProperty ;+ rdfs:domain ex:Person ;+ rdfs:range <http://www.w3.org/2001/XMLSchema#integer> ;+ rdfs:label "age" .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn build_scaffold_pulls_class_metadata_and_properties() {+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ assert_eq!(s.class_label.as_deref(), Some("Person"));+ assert!(s.class_comment.as_deref().unwrap_or("").contains("human"));+ assert_eq!(s.property_schema.len(), 2);+ assert!(s.prompt_template.contains("Person"));+ assert!(s.prompt_template.contains("name"));+ assert!(s.prompt_template.contains("age"));+ }++ #[test]+ fn validate_extraction_accepts_well_formed_array() {+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ assert_eq!(r.total, 2);+ assert_eq!(r.valid, 2);+ assert!(r.issues.is_empty());+ }++ #[test]+ fn validate_extraction_flags_non_object_instances() {+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"["not an object", {"name": "Bob"}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ assert_eq!(r.total, 2);+ assert_eq!(r.issues.len(), 1);+ assert_eq!(r.issues[0].instance_index, 0);+ }++ #[test]+ fn validate_extraction_rejects_non_array_root() {+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let err = validate_extraction(&s, r#"{"not": "array"}"#).expect_err("should error");+ assert!(format!("{}", err).contains("must be a JSON array"));+ }+}diff --git a/src/inputs.rs b/src/inputs.rsindex 4d39b0ce..1ec314bc 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -599,6 +599,150 @@ fn default_alpha_pub() -> f64 {0.05}+/// Input for `onto_align_fuzzy` (#38, FLORA ISWC 2025 Best Paper).+#[derive(Deserialize, JsonSchema)]+pub struct OntoAlignFuzzyInput {+ /// Caller-supplied signals JSON: `{label_jaccard, parent_overlap,+ /// sibling_overlap, datatype_overlap}` all in `[0, 1]`.+ pub signals_json: String,+ /// One of `"min"`, `"product"`, `"lukasiewicz"`. Default `"min"`.+ #[serde(default)]+ pub tnorm: Option<String>,+ pub low_threshold: f64,+ pub high_threshold: f64,+}++/// Input for `onto_policy_register` (#40, ARGOS ISWC 2025 WOP).+#[derive(Deserialize, JsonSchema)]+pub struct OntoPolicyRegisterInput {+ pub name: String,+ /// `"allow"` or `"deny"`.+ pub effect: String,+ /// SPARQL ASK (may include `{target}` placeholder).+ pub condition: String,+ #[serde(default)]+ pub description: Option<String>,+}++/// Input for `onto_policy_check` (#40).+#[derive(Deserialize, JsonSchema)]+pub struct OntoPolicyCheckInput {+ pub target_iris: Vec<String>,+}++/// Input for `eval_rag` (#41, mmRAG ISWC 2025).+#[derive(Deserialize, JsonSchema)]+pub struct OntoEvalRagInput {+ /// JSON array `[{question_id, gold_iri, retrieved: [iri, iri, ...]}, ...]`.+ pub qa_json: String,+}++/// Input for `onto_eval_alignment` (#31, OAEI-style P/R/F1).+#[derive(Deserialize, JsonSchema)]+pub struct OntoEvalAlignmentInput {+ /// Reference alignment as JSON array of `{source, target, relation}`.+ pub reference_json: String,+ /// Computed alignment in the same shape.+ pub computed_json: String,+}++/// Input for `onto_shape_combinatorics` (#36).+#[derive(Deserialize, JsonSchema)]+pub struct OntoShapeCombinatoricsInput {+ pub class_iri: String,+ #[serde(default)]+ pub max_size: Option<usize>,+}++/// Input for `borderline_partition` (#37).+#[derive(Deserialize, JsonSchema)]+pub struct BorderlinePartitionInput {+ /// JSON array `[{id, score, context?}, ...]`.+ pub candidates_json: String,+ pub low_threshold: f64,+ pub high_threshold: f64,+}++/// Input for `borderline_record_verdict` (#37).+#[derive(Deserialize, JsonSchema)]+pub struct BorderlineRecordVerdictInput {+ pub candidate_id: String,+ #[serde(default)]+ pub namespace: Option<String>,+ /// Either "accept" or "reject".+ pub verdict: String,+ #[serde(default)]+ pub rationale: Option<String>,+}++/// Input for `onto_extract_scaffold` (#28, OntoGPT SPIRES MCP-native).+#[derive(Deserialize, JsonSchema)]+pub struct OntoExtractScaffoldInput {+ /// Class IRI to build the extraction prompt for.+ pub class_iri: String,+}++/// Input for `onto_extract_validate` (#28 companion).+#[derive(Deserialize, JsonSchema)]+pub struct OntoExtractValidateInput {+ /// The scaffold previously emitted by `onto_extract_scaffold` (JSON).+ pub scaffold_json: String,+ /// The LLM's extraction (must be a JSON array of objects).+ pub extraction_json: String,+}++/// Input for `onto_cq_run` (#29, competency-question runner).+#[derive(Deserialize, JsonSchema)]+pub struct OntoCqRunInput {+ /// Inline JSON array of competency questions+ /// `[{id, question, sparql, expected_min_rows?}, ...]`.+ pub cqs_json: String,+}++/// Input for `onto_verify_cq` (#39, LLM-assisted CQ verification).+#[derive(Deserialize, JsonSchema)]+pub struct OntoVerifyCqInput {+ pub cq_id: String,+ /// One of `"correct"`, `"incorrect"`, `"partial"`.+ pub verdict: String,+ #[serde(default)]+ pub rationale: Option<String>,+ #[serde(default)]+ pub judge: Option<String>,+}++/// Input for `onto_cq_verdicts_list`.+#[derive(Deserialize, JsonSchema)]+pub struct OntoCqVerdictsListInput {+ pub cq_id: String,+}++/// Input for `onto_segment_retrieve` (#34, SEMANTiCS 2025 GrOWL-RAG) —+/// retrieve a TBox-slice neighbourhood for grounding LLM reasoning.+#[derive(Deserialize, JsonSchema)]+pub struct OntoSegmentRetrieveInput {+ /// Seed IRIs whose neighbourhoods to extract.+ pub seed_iris: Vec<String>,+ /// BFS hop budget. Default 2.+ #[serde(default)]+ pub hops: Option<u32>,+ /// When `true`, also include `?inst a <seed>` triples. Default `false`.+ #[serde(default)]+ pub include_abox: Option<bool>,+}++/// Input for `onto_owl_shacl_coevolve_check` (#33, K-CAP 2025) — validate+/// SHACL shapes against the OWL closure of the loaded graph, not just the+/// raw ABox.+#[derive(Deserialize, JsonSchema)]+pub struct OntoOwlShaclCoevolveInput {+ /// SHACL shapes as Turtle.+ pub shapes_ttl: String,+ /// Reasoner profile. Default `"owl-rl"`.+ #[serde(default)]+ pub profile: Option<String>,+}+/// Input for `graph_projection_lossy_check` (#35) — audits whether a projected/// Turtle slice has dropped predicates/objects vs the full source neighbourhood/// of the seed IRIs.@@ -610,6 +754,54 @@ pub struct GraphProjectionLossyCheckInput {pub projected_ttl: String,}+// ─── Full BC+ semantics (#43 follow-on) ─────────────────────────────────────++/// Input for `onto_action_apply_concurrent` — fire a tick of concurrent+/// action instances. The whole tick is atomic: if any pair of steps+/// conflicts (one adds a triple another removes) OR any registered invariant+/// fails post-tick, nothing is applied.+#[derive(Deserialize, JsonSchema)]+pub struct OntoActionApplyConcurrentInput {+ pub steps: Vec<ConcurrentStepInput>,+}++#[derive(Deserialize, JsonSchema)]+pub struct ConcurrentStepInput {+ pub action_name: String,+ #[serde(default)]+ pub bindings: std::collections::BTreeMap<String, String>,+}++/// Input for `onto_invariant_register` — persist a SPARQL ASK invariant+/// (BC+ static causal law) that the graph must always satisfy.+#[derive(Deserialize, JsonSchema)]+pub struct OntoInvariantRegisterInput {+ pub name: String,+ /// SPARQL ASK query (or just the body inside `{ ... }`). Must return+ /// `true` for the law to hold.+ pub ask_query: String,+ #[serde(default)]+ pub description: Option<String>,+}++/// Input for `onto_invariant_remove`.+#[derive(Deserialize, JsonSchema)]+pub struct OntoInvariantRemoveInput {+ pub name: String,+}++/// Input for `onto_default_register` — persist a BC+ default-value law.+#[derive(Deserialize, JsonSchema)]+pub struct OntoDefaultRegisterInput {+ pub name: String,+ /// SPARQL ASK that activates the default when it returns `true`.+ pub condition_ask: String,+ /// Triples to assert when the condition fires. Each entry is `[s, p, o]`.+ pub defaults: Vec<Vec<String>>,+ #[serde(default)]+ pub description: Option<String>,+}+// ─── Dynamics layer (#43) — action schemas, applicability, apply ────────────/// Input for `onto_action_register` — persist an action schema by name.diff --git a/src/lib.rs b/src/lib.rsindex 4b09eba0..82357b2f 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -4,11 +4,22 @@ pub mod error;pub mod align;pub mod config;pub mod clinical;+pub mod align_fuzzy;+pub mod borderline_loop;pub mod civex;+pub mod classify_el;+pub mod coevolve;+pub mod cq;+pub mod eval_alignment;+pub mod eval_rag;+pub mod extract_scaffold;+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;// (re-exports keep the alphabetical ordering of the surrounding modules manageable)pub mod enforce;@@ -35,6 +46,7 @@ pub mod server;pub mod shacl;pub mod state;pub mod schema;+pub mod segment_retrieve;pub mod socket;pub mod sqlsource;pub mod tableaux;diff --git a/src/policy.rs b/src/policy.rsnew file mode 100644index 00000000..40952521--- /dev/null+++ b/src/policy.rs@@ -0,0 +1,253 @@+//! ARGOS-style policy governance for state-changing actions (#40, ISWC 2025+//! WOP).+//!+//! Lightweight policy gate that sits between an `onto_certify_action` /+//! `onto_action_apply` call and execution. Policies are SPARQL ASK queries+//! parameterised by the proposed action's target IRIs; each policy returns+//! "allow" or "deny" with a human-readable rationale.+//!+//! ## Why this isn't `onto_certify_action`+//!+//! CIVeX gates on *causal* properties (utility, blast radius, identifiability).+//! ARGOS gates on *policy* properties (who is allowed to touch what, under+//! which clearance, during which window). The two layers compose: CIVeX+//! handles statistical risk, ARGOS handles authorisation.++use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct PolicyRule {+ pub name: String,+ /// One of `"allow"` or `"deny"`. The rule's verdict when the SPARQL+ /// ASK returns `true`.+ pub effect: String,+ /// SPARQL ASK. Can use the placeholder `{target}` which is substituted+ /// by each target IRI when the rule is checked.+ pub condition: String,+ #[serde(default)]+ pub description: Option<String>,+}++#[derive(Clone, Debug, Serialize)]+pub struct PolicyReport {+ /// Overall verdict: `"allow"` iff at least one `allow` rule fires for+ /// every target AND no `deny` rule fires for any target.+ pub verdict: String,+ pub rule_results: Vec<RuleResult>,+}++#[derive(Clone, Debug, Serialize)]+pub struct RuleResult {+ pub rule_name: String,+ pub target: String,+ pub effect: String,+ pub fired: bool,+}++const ENSURE: &str = "+CREATE TABLE IF NOT EXISTS policy_rules (+ name TEXT PRIMARY KEY,+ effect TEXT NOT NULL CHECK (effect IN ('allow', 'deny')),+ condition TEXT NOT NULL,+ description TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+)";++fn ensure(db: &StateDb) -> anyhow::Result<()> {+ db.conn().execute(ENSURE, [])?;+ Ok(())+}++pub fn register_rule(db: &StateDb, rule: &PolicyRule) -> anyhow::Result<()> {+ if !matches!(rule.effect.as_str(), "allow" | "deny") {+ anyhow::bail!("invalid effect `{}`: must be allow or deny", rule.effect);+ }+ ensure(db)?;+ db.conn().execute(+ "INSERT OR REPLACE INTO policy_rules (name, effect, condition, description) VALUES (?1, ?2, ?3, ?4)",+ rusqlite::params![rule.name, rule.effect, rule.condition, rule.description],+ )?;+ Ok(())+}++pub fn list_rules(db: &StateDb) -> anyhow::Result<Vec<PolicyRule>> {+ ensure(db)?;+ let conn = db.conn();+ let mut stmt = conn.prepare(+ "SELECT name, effect, condition, description FROM policy_rules ORDER BY name",+ )?;+ let rows: Vec<PolicyRule> = stmt+ .query_map([], |r| {+ Ok(PolicyRule {+ name: r.get(0)?,+ effect: r.get(1)?,+ condition: r.get(2)?,+ description: r.get(3)?,+ })+ })?+ .filter_map(Result::ok)+ .collect();+ Ok(rows)+}++/// Check a proposed action against every registered policy rule.+///+/// Semantics:+/// - For each (rule, target) pair, substitute `{target}` into the rule's+/// SPARQL ASK and evaluate.+/// - The rule "fires" iff the ASK returns `true`.+/// - Verdict: `"deny"` if any `deny` rule fires for any target;+/// `"allow"` otherwise.+pub fn check_action(+ db: &StateDb,+ graph: &Arc<GraphStore>,+ target_iris: &[String],+) -> anyhow::Result<PolicyReport> {+ let rules = list_rules(db)?;+ let mut results: Vec<RuleResult> = Vec::new();+ let mut any_deny = false;+ for rule in &rules {+ for t in target_iris {+ let q = rule.condition.replace("{target}", t);+ let q = if q.trim().to_uppercase().starts_with("ASK") {+ q+ } else {+ format!("ASK {{ {} }}", q)+ };+ let fired = match graph.sparql_select(&q) {+ Ok(s) => s.contains("\"result\":true"),+ Err(_) => false,+ };+ if fired && rule.effect == "deny" {+ any_deny = true;+ }+ results.push(RuleResult {+ rule_name: rule.name.clone(),+ target: t.clone(),+ effect: rule.effect.clone(),+ fired,+ });+ }+ }+ let verdict = if any_deny { "deny" } else { "allow" }.to_string();+ Ok(PolicyReport { verdict, rule_results: results })+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::Path;++ fn fresh_db() -> StateDb {+ StateDb::open(Path::new(":memory:")).unwrap()+ }++ fn graph_with_lock() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ @prefix audit: <http://example.org/audit#> .+ ex:Critical a owl:Class ; audit:locked "yes" .+ ex:Free a owl:Class .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn check_action_allows_when_no_deny_fires() {+ let db = fresh_db();+ let g = graph_with_lock();+ register_rule(+ &db,+ &PolicyRule {+ name: "deny_locked".to_string(),+ effect: "deny".to_string(),+ condition:+ "ASK { <{target}> <http://example.org/audit#locked> \"yes\" }".to_string(),+ description: None,+ },+ )+ .unwrap();+ let report =+ check_action(&db, &g, &["http://ex.org/Free".to_string()]).unwrap();+ assert_eq!(report.verdict, "allow");+ // The deny rule did NOT fire for Free.+ assert!(report.rule_results.iter().any(|r| r.rule_name == "deny_locked" && !r.fired));+ }++ #[test]+ fn check_action_denies_when_any_deny_fires() {+ let db = fresh_db();+ let g = graph_with_lock();+ register_rule(+ &db,+ &PolicyRule {+ name: "deny_locked".to_string(),+ effect: "deny".to_string(),+ condition:+ "ASK { <{target}> <http://example.org/audit#locked> \"yes\" }".to_string(),+ description: None,+ },+ )+ .unwrap();+ let report =+ check_action(&db, &g, &["http://ex.org/Critical".to_string()]).unwrap();+ assert_eq!(report.verdict, "deny");+ assert!(report.rule_results.iter().any(|r| r.fired && r.effect == "deny"));+ }++ #[test]+ fn register_rule_rejects_invalid_effect() {+ let db = fresh_db();+ let err = register_rule(+ &db,+ &PolicyRule {+ name: "x".to_string(),+ effect: "maybe".to_string(),+ condition: "ASK { ?s ?p ?o }".to_string(),+ description: None,+ },+ )+ .expect_err("should reject");+ assert!(format!("{}", err).contains("invalid effect"));+ }++ #[test]+ fn check_action_with_no_rules_returns_allow() {+ let db = fresh_db();+ let g = graph_with_lock();+ let report =+ check_action(&db, &g, &["http://ex.org/Free".to_string()]).unwrap();+ assert_eq!(report.verdict, "allow");+ assert!(report.rule_results.is_empty());+ }++ #[test]+ fn target_substitution_replaces_braces() {+ // A rule with multiple target substitutions still works.+ let db = fresh_db();+ let g = graph_with_lock();+ register_rule(+ &db,+ &PolicyRule {+ name: "self_loop_deny".to_string(),+ effect: "deny".to_string(),+ condition:+ "ASK { <{target}> ?p <{target}> }".to_string(),+ description: None,+ },+ )+ .unwrap();+ // The rule doesn't fire because Critical doesn't have a self-loop.+ let report = check_action(&db, &g, &["http://ex.org/Critical".to_string()]).unwrap();+ assert_eq!(report.verdict, "allow");+ }+}diff --git a/src/segment_retrieve.rs b/src/segment_retrieve.rsnew file mode 100644index 00000000..3bfd6985--- /dev/null+++ b/src/segment_retrieve.rs@@ -0,0 +1,219 @@+//! TBox-slice retrieval for ontology-grounded RAG (#34, SEMANTiCS 2025+//! GrOWL-RAG).+//!+//! Given a set of seed IRIs, returns a Turtle-serialised k-hop neighbourhood+//! restricted to the TBox (terminological structure): subclass / equivalent+//! class / property-domain / property-range / property-superproperty.+//! Intentionally omits ABox triples (instance data) unless explicitly asked+//! for, so the slice is suitable for grounding an LLM's reasoning over+//! structure rather than data.+//!+//! Pairs with `graph_projection_lossy_check` (#35): this primitive produces+//! the slice; that one audits what was dropped.++use crate::graph::GraphStore;+use serde::Serialize;+use std::collections::BTreeSet;+use std::sync::Arc;++#[derive(Clone, Debug, Serialize)]+pub struct SegmentResult {+ /// Slice as Turtle (Oxigraph-canonical).+ pub turtle: String,+ /// Number of distinct IRIs reached.+ pub iri_count: usize,+ /// Number of triples emitted.+ pub triple_count: usize,+ /// IRIs visited but not expanded (hit the hop budget).+ pub frontier_iris: Vec<String>,+}++/// TBox-relevant predicates that get traversed when retrieving a slice.+const TBOX_PREDICATES: &[&str] = &[+ "http://www.w3.org/2000/01/rdf-schema#subClassOf",+ "http://www.w3.org/2000/01/rdf-schema#subPropertyOf",+ "http://www.w3.org/2000/01/rdf-schema#domain",+ "http://www.w3.org/2000/01/rdf-schema#range",+ "http://www.w3.org/2002/07/owl#equivalentClass",+ "http://www.w3.org/2002/07/owl#equivalentProperty",+ "http://www.w3.org/2002/07/owl#disjointWith",+ "http://www.w3.org/2002/07/owl#inverseOf",+];++/// Retrieve a TBox slice. `seed_iris` are the starting points; `hops`+/// bounds the BFS depth (default 2 if 0). `include_abox = true` also pulls+/// instance triples (`?inst a <seed>`).+pub fn retrieve_segment(+ graph: &Arc<GraphStore>,+ seed_iris: &[String],+ hops: u32,+ include_abox: bool,+) -> anyhow::Result<SegmentResult> {+ let max_hops = if hops == 0 { 2 } else { hops };+ let mut visited: BTreeSet<String> = BTreeSet::new();+ let mut frontier: Vec<String> = seed_iris.to_vec();+ let mut triples: BTreeSet<(String, String, String)> = BTreeSet::new();++ for _ in 0..max_hops {+ let mut next_frontier: Vec<String> = Vec::new();+ for iri in &frontier {+ if !visited.insert(iri.clone()) {+ continue;+ }+ // Outgoing TBox edges.+ for pred in TBOX_PREDICATES {+ let q = format!(+ r#"SELECT ?o WHERE {{ <{iri}> <{pred}> ?o }} LIMIT 200"#,+ iri = iri,+ pred = pred+ );+ if let Ok(js) = graph.sparql_select(&q)+ && let Ok(v) = serde_json::from_str::<serde_json::Value>(&js)+ && let Some(rows) = v["results"].as_array()+ {+ for row in rows {+ if let Some(o) = row["o"].as_str() {+ let o = o.trim_matches(|c| c == '<' || c == '>').to_string();+ triples.insert((iri.clone(), pred.to_string(), o.clone()));+ if !visited.contains(&o) {+ next_frontier.push(o);+ }+ }+ }+ }+ }+ // Also pull rdf:type for each seed so the slice declares classhood.+ let q = format!(+ "SELECT ?o WHERE {{ <{}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?o }}",+ iri+ );+ if let Ok(js) = graph.sparql_select(&q)+ && let Ok(v) = serde_json::from_str::<serde_json::Value>(&js)+ && let Some(rows) = v["results"].as_array()+ {+ for row in rows {+ if let Some(o) = row["o"].as_str() {+ let o = o.trim_matches(|c| c == '<' || c == '>').to_string();+ triples.insert((+ iri.clone(),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ o,+ ));+ }+ }+ }+ if include_abox {+ // Instance triples whose type is the seed.+ let q = format!(+ "SELECT ?s WHERE {{ ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <{}> }} LIMIT 100",+ iri+ );+ if let Ok(js) = graph.sparql_select(&q)+ && let Ok(v) = serde_json::from_str::<serde_json::Value>(&js)+ && let Some(rows) = v["results"].as_array()+ {+ for row in rows {+ if let Some(s) = row["s"].as_str() {+ let s = s.trim_matches(|c| c == '<' || c == '>').to_string();+ triples.insert((+ s.clone(),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ iri.clone(),+ ));+ }+ }+ }+ }+ }+ frontier = next_frontier;+ if frontier.is_empty() {+ break;+ }+ }++ let mut turtle = String::new();+ for (s, p, o) in &triples {+ turtle.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ }++ Ok(SegmentResult {+ turtle,+ iri_count: visited.len(),+ triple_count: triples.len(),+ frontier_iris: frontier,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn graph_with_hierarchy() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:LivingThing a owl:Class .+ ex:Animal a owl:Class ; rdfs:subClassOf ex:LivingThing .+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .+ ex:tigger a ex:Cat .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn retrieve_one_hop_pulls_immediate_parent() {+ let g = graph_with_hierarchy();+ let r = retrieve_segment(&g, &["http://ex.org/Cat".to_string()], 1, false).unwrap();+ assert!(r.turtle.contains("ex.org/Cat"));+ assert!(r.turtle.contains("ex.org/Animal"));+ // Should NOT have walked to LivingThing yet (1 hop only).+ assert!(!r.turtle.contains("LivingThing"));+ assert!(r.iri_count >= 1);+ assert!(r.triple_count >= 1);+ }++ #[test]+ fn retrieve_two_hops_walks_transitive_chain() {+ let g = graph_with_hierarchy();+ let r = retrieve_segment(&g, &["http://ex.org/Cat".to_string()], 2, false).unwrap();+ assert!(r.turtle.contains("ex.org/Animal"));+ assert!(r.turtle.contains("ex.org/LivingThing"),+ "two-hop walk should reach LivingThing; got:\n{}", r.turtle);+ }++ #[test]+ fn retrieve_excludes_abox_by_default() {+ let g = graph_with_hierarchy();+ let r = retrieve_segment(&g, &["http://ex.org/Cat".to_string()], 1, false).unwrap();+ assert!(!r.turtle.contains("ex.org/tigger"),+ "instance triples must NOT appear when include_abox=false");+ }++ #[test]+ fn retrieve_includes_abox_when_requested() {+ let g = graph_with_hierarchy();+ let r = retrieve_segment(&g, &["http://ex.org/Cat".to_string()], 1, true).unwrap();+ assert!(r.turtle.contains("ex.org/tigger"),+ "instance triples must appear when include_abox=true; got:\n{}", r.turtle);+ }++ #[test]+ fn retrieve_handles_seeds_with_no_outgoing_edges() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix ex: <http://ex.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . ex:Lonely a owl:Class .",+ None,+ )+ .unwrap();+ let r = retrieve_segment(&g, &["http://ex.org/Lonely".to_string()], 2, false).unwrap();+ // Should still emit the rdf:type triple for the seed.+ assert!(r.turtle.contains("ex.org/Lonely"));+ }+}diff --git a/src/server.rs b/src/server.rsindex a820718b..91a363be 100644--- a/src/server.rs+++ b/src/server.rs@@ -929,6 +929,205 @@ impl OpenOntologiesServer {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))}+ #[tool(name = "onto_align_fuzzy", description = "FLORA-style fuzzy-logic alignment adjudication (#38, ISWC 2025 Best Paper). Caller supplies per-pair signals (`label_jaccard`, `parent_overlap`, `sibling_overlap`, `datatype_overlap` all in [0,1]) plus low/high thresholds; server combines via the chosen t-norm (`min` / `product` / `lukasiewicz`) and emits verdict `\"accept\"` / `\"borderline\"` / `\"reject\"` plus a rule trace. Embedding-free, interpretable, complements the HNSW candidate-generator pipeline.")]+ async fn onto_align_fuzzy(&self, Parameters(input): Parameters<OntoAlignFuzzyInput>) -> String {+ let signals: crate::align_fuzzy::FuzzySignals = match serde_json::from_str(&input.signals_json) {+ Ok(s) => s,+ Err(e) => return format!(r#"{{"error":"invalid signals_json: {}"}}"#, e),+ };+ let tnorm = match input.tnorm.as_deref() {+ Some("product") => crate::align_fuzzy::TNorm::Product,+ Some("lukasiewicz") => crate::align_fuzzy::TNorm::Lukasiewicz,+ _ => crate::align_fuzzy::TNorm::Min,+ };+ let decision = crate::align_fuzzy::adjudicate(&signals, tnorm, input.low_threshold, input.high_threshold);+ serde_json::to_string(&decision)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }++ #[tool(name = "onto_policy_register", description = "Register an ARGOS-style policy rule (#40, ISWC 2025 WOP). `effect` is `\"allow\"` or `\"deny\"`; `condition` is a SPARQL ASK that can use the `{target}` placeholder. Pairs with `onto_policy_check` and `onto_certify_action` — CIVeX gates causal risk, ARGOS gates authorisation.")]+ async fn onto_policy_register(&self, Parameters(input): Parameters<OntoPolicyRegisterInput>) -> String {+ let rule = crate::policy::PolicyRule {+ name: input.name.clone(),+ effect: input.effect,+ condition: input.condition,+ description: input.description,+ };+ match crate::policy::register_rule(&self.db, &rule) {+ Ok(()) => format!(r#"{{"ok":true,"registered":"{}"}}"#, input.name),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_policy_list", description = "List all registered ARGOS policy rules.")]+ async fn onto_policy_list(&self) -> String {+ match crate::policy::list_rules(&self.db) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_policy_check", description = "Evaluate a proposed action's target IRIs against every registered policy rule. Verdict is `\"deny\"` if any `deny` rule fires for any target, else `\"allow\"`. Returns per-rule fire status for audit.")]+ async fn onto_policy_check(&self, Parameters(input): Parameters<OntoPolicyCheckInput>) -> String {+ match crate::policy::check_action(&self.db, &self.graph, &input.target_iris) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "eval_rag", description = "mmRAG benchmark scoring (#41, ISWC 2025). Input is a JSON array of {question_id, gold_iri, retrieved: [iri, ...]}. Returns Hit@{3,5,10}, MRR, exact-match-at-1, and per-question rank (0 = gold not retrieved).")]+ async fn eval_rag(&self, Parameters(input): Parameters<OntoEvalRagInput>) -> String {+ let qas: Vec<crate::eval_rag::RagQa> = match serde_json::from_str(&input.qa_json) {+ Ok(q) => q,+ Err(e) => return format!(r#"{{"error":"invalid qa_json: {}"}}"#, e),+ };+ let report = crate::eval_rag::evaluate(&qas);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }++ #[tool(name = "onto_classify_el", description = "Classify the loaded ontology in the OWL-EL fragment (#30). Materialises OWL-RL-ext entailments in a sandbox copy of the graph and emits every distinct subsumption `?sub rdfs:subClassOf ?super` (transitive closure, deduplicated, owl:Thing-trivial pairs removed). For deep SHOIQ subsumption, use `onto_dl_check` / `onto_dl_explain`.")]+ async fn onto_classify_el(&self) -> String {+ match crate::classify_el::classify(&self.graph) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_eval_alignment", description = "OAEI-style P/R/F1 scoring (#31). Both inputs are JSON arrays of {source, target, relation}; entries match on exact triple equality. Returns precision, recall, F1, TP/FP/FN counts.")]+ async fn onto_eval_alignment(&self, Parameters(input): Parameters<OntoEvalAlignmentInput>) -> String {+ let reference: Vec<crate::eval_alignment::AlignmentEntry> =+ match serde_json::from_str(&input.reference_json) {+ Ok(r) => r,+ Err(e) => return format!(r#"{{"error":"invalid reference_json: {}"}}"#, e),+ };+ let computed: Vec<crate::eval_alignment::AlignmentEntry> =+ match serde_json::from_str(&input.computed_json) {+ Ok(c) => c,+ Err(e) => return format!(r#"{{"error":"invalid computed_json: {}"}}"#, e),+ };+ let report = crate::eval_alignment::evaluate(&reference, &computed);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }++ #[tool(name = "onto_shape_combinatorics", description = "Enumerate the property-combination lattice for a class (#36, K-CAP 2025 Kastor). Returns subsets of the class's rdfs:domain properties up to `max_size` (default 3). Used by shape-induction algorithms to enumerate candidate SHACL shapes from data.")]+ async fn onto_shape_combinatorics(&self, Parameters(input): Parameters<OntoShapeCombinatoricsInput>) -> String {+ let max = input.max_size.unwrap_or(3);+ match crate::shape_combinatorics::enumerate(&self.graph, &input.class_iri, max) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "borderline_partition", description = "Generalised borderline-pair partitioning (#37, NORA NeurIPS 2025). Takes a list of {id, score, context} candidates plus low+high thresholds; partitions into auto_accept (>= high), borderline ([low, high)), auto_reject (< low) and emits a review summary the orchestrator's LLM can act on. Pairs with `borderline_record_verdict`.")]+ async fn borderline_partition(&self, Parameters(input): Parameters<BorderlinePartitionInput>) -> String {+ let candidates: Vec<crate::borderline_loop::Candidate> =+ match serde_json::from_str(&input.candidates_json) {+ Ok(c) => c,+ Err(e) => return format!(r#"{{"error":"invalid candidates_json: {}"}}"#, e),+ };+ let report = crate::borderline_loop::partition(candidates, input.low_threshold, input.high_threshold);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }++ #[tool(name = "borderline_record_verdict", description = "Persist an orchestrator's verdict on a borderline candidate (#37). verdict must be \"accept\" or \"reject\". Namespaces let independent borderline loops coexist.")]+ async fn borderline_record_verdict(&self, Parameters(input): Parameters<BorderlineRecordVerdictInput>) -> String {+ let v = crate::borderline_loop::BorderlineVerdict {+ candidate_id: input.candidate_id.clone(),+ namespace: input.namespace.unwrap_or_else(|| "default".to_string()),+ verdict: input.verdict,+ rationale: input.rationale,+ };+ match crate::borderline_loop::record_verdict(&self.db, &v) {+ Ok(()) => format!(r#"{{"ok":true,"candidate_id":"{}"}}"#, input.candidate_id),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_extract_scaffold", description = "Build a schema-guided structured-extraction scaffold for a class (#28, OntoGPT SPIRES MCP-native). Returns the class metadata (label, comment), the property schema derived from rdfs:domain triples that target the class, and a ready-to-use prompt template the orchestrator can hand to its LLM. The server doesn't run the LLM; it scaffolds the prompt and validates the LLM's output via `onto_extract_validate`.")]+ async fn onto_extract_scaffold(&self, Parameters(input): Parameters<OntoExtractScaffoldInput>) -> String {+ match crate::extract_scaffold::build_scaffold(&self.graph, &input.class_iri) {+ Ok(s) => serde_json::to_string(&s)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_extract_validate", description = "Validate an LLM-supplied extraction (JSON array of objects) against a scaffold previously emitted by `onto_extract_scaffold`. Returns per-instance valid/invalid counts and field-level issue reports.")]+ async fn onto_extract_validate(&self, Parameters(input): Parameters<OntoExtractValidateInput>) -> String {+ let scaffold: crate::extract_scaffold::ExtractionScaffold =+ match serde_json::from_str(&input.scaffold_json) {+ Ok(s) => s,+ Err(e) => return format!(r#"{{"error":"invalid scaffold_json: {}"}}"#, e),+ };+ match crate::extract_scaffold::validate_extraction(&scaffold, &input.extraction_json) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_cq_run", description = "Run a batch of competency questions (CQs) against the loaded ontology (#29). Each CQ has an id, a natural-language question, a SPARQL query, and an optional expected_min_rows. Returns per-CQ pass/fail plus VSPO-pitfall hints (P10: empty result, P11: no rdfs:label, P12: > 10k rows). Pairs with `onto_verify_cq` for the LLM-judgement loop.")]+ async fn onto_cq_run(&self, Parameters(input): Parameters<OntoCqRunInput>) -> String {+ let cqs: Vec<crate::cq::CompetencyQuestion> = match serde_json::from_str(&input.cqs_json) {+ Ok(c) => c,+ Err(e) => return format!(r#"{{"error":"invalid cqs_json: {}"}}"#, e),+ };+ let report = crate::cq::run_cq_suite(&self.graph, &cqs);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }++ #[tool(name = "onto_verify_cq", description = "Persist an LLM-supplied (or human-supplied) verdict on a CQ result (#39, ISWC 2025 Lippolis). verdict must be one of \"correct\", \"incorrect\", \"partial\". Server stores verdicts; the LLM does the judging. Pairs with `onto_cq_run`.")]+ async fn onto_verify_cq(&self, Parameters(input): Parameters<OntoVerifyCqInput>) -> String {+ let v = crate::cq::CqVerdict {+ cq_id: input.cq_id.clone(),+ verdict: input.verdict,+ rationale: input.rationale,+ judge: input.judge,+ };+ match crate::cq::verify_cq(&self.db, &v) {+ Ok(()) => format!(r#"{{"ok":true,"cq_id":"{}"}}"#, input.cq_id),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_cq_verdicts_list", description = "List all stored verdicts for a CQ id, most-recent first.")]+ async fn onto_cq_verdicts_list(&self, Parameters(input): Parameters<OntoCqVerdictsListInput>) -> String {+ match crate::cq::list_cq_verdicts(&self.db, &input.cq_id) {+ Ok(v) => serde_json::to_string(&v)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_segment_retrieve", description = "Retrieve a TBox-slice neighbourhood of seed IRIs for grounding LLM reasoning (#34, SEMANTiCS 2025 GrOWL-RAG). Walks `rdfs:subClassOf` / `subPropertyOf` / `domain` / `range` + `owl:equivalentClass` / `equivalentProperty` / `disjointWith` / `inverseOf` to `hops` depth (default 2). Returns the slice as Turtle plus IRI/triple counts and any frontier IRIs hit at the hop budget. Pairs with `graph_projection_lossy_check`: this retrieves, that audits. Pass `include_abox=true` to also pull instance triples for each seed.")]+ async fn onto_segment_retrieve(&self, Parameters(input): Parameters<OntoSegmentRetrieveInput>) -> String {+ let hops = input.hops.unwrap_or(2);+ let include_abox = input.include_abox.unwrap_or(false);+ match crate::segment_retrieve::retrieve_segment(&self.graph, &input.seed_iris, hops, include_abox) {+ Ok(result) => serde_json::to_string(&result)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_owl_shacl_coevolve_check", description = "Combined OWL+SHACL validation (#33, K-CAP 2025). Materialises OWL-RL entailments into a sandbox copy of the loaded graph, then runs SHACL validation against the closure. Returns both the pre-reasoning and post-reasoning conformance verdicts plus the count of triples the reasoner added. Catches SHACL constraints that pass against the raw ABox but fail after inference (e.g. instances that inherit a parent class via rdfs:subClassOf and then violate a parent-class shape). Original graph is NOT mutated.")]+ async fn onto_owl_shacl_coevolve_check(&self, Parameters(input): Parameters<OntoOwlShaclCoevolveInput>) -> String {+ let profile = input.profile.unwrap_or_else(|| "owl-rl".to_string());+ match crate::coevolve::coevolve_check(&self.graph, &input.shapes_ttl, &profile) {+ Ok(report) => serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }+#[tool(name = "graph_projection_lossy_check", description = "Audit a projected Turtle slice against the loaded ontology's full neighbourhood of the seed IRIs. Reports dropped predicates, dropped object IRIs, per-seed coverage ratio, and aggregate coverage. Pair with onto_segment_retrieve when the slice is being passed to a downstream LLM — knowing what was left behind lets the caller decide whether the slice is sufficient. Per IJCAI 2025 'How to Mitigate Information Loss in KGs for GraphRAG'.")]async fn graph_projection_lossy_check(&self, Parameters(input): Parameters<GraphProjectionLossyCheckInput>) -> String {match crate::projection_check::check_projection_loss(&self.graph, &input.source_iris, &input.projected_ttl) {@@ -1025,6 +1224,88 @@ impl OpenOntologiesServer {}}+ // ── Full BC+ semantics (#43 follow-on) ──────────────────────────────++ #[tool(name = "onto_action_apply_concurrent", description = "Fire a tick of concurrent BC+ actions atomically. All steps are pre-computed against the pre-tick state, conflict-checked (add-vs-remove of the same triple across distinct steps), then committed as a single batch. If any conflict OR any registered invariant fails post-commit, the entire tick is rolled back and NO step is applied. Non-deterministic schemas in a concurrent tick are rejected — pre-sample with `apply_with_seed` first.")]+ async fn onto_action_apply_concurrent(&self, Parameters(input): Parameters<OntoActionApplyConcurrentInput>) -> String {+ let steps: Vec<crate::dynamics_bcplus::ConcurrentStep> = input.steps.into_iter()+ .map(|s| crate::dynamics_bcplus::ConcurrentStep {+ action_name: s.action_name,+ bindings: s.bindings,+ })+ .collect();+ match crate::dynamics_bcplus::apply_concurrent(&self.db, &self.graph, &steps) {+ Ok(result) => serde_json::to_string(&result)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_invariant_register", description = "Persist a BC+ static causal law (SPARQL ASK invariant). The query MUST return `true` for the law to hold; concurrent ticks that violate any registered invariant are rolled back. Body can be a full ASK query or just the body inside `{ ... }`.")]+ async fn onto_invariant_register(&self, Parameters(input): Parameters<OntoInvariantRegisterInput>) -> String {+ let law = crate::dynamics_bcplus::StaticCausalLaw {+ name: input.name.clone(),+ ask_query: input.ask_query,+ description: input.description,+ };+ match crate::dynamics_bcplus::register_invariant(&self.db, &law) {+ Ok(()) => format!(r#"{{"ok":true,"registered":"{}"}}"#, input.name),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_invariant_list", description = "List all registered BC+ static causal laws (invariants).")]+ async fn onto_invariant_list(&self) -> String {+ match crate::dynamics_bcplus::list_invariants(&self.db) {+ Ok(laws) => serde_json::to_string(&laws)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_invariant_remove", description = "Remove a registered BC+ invariant by name.")]+ async fn onto_invariant_remove(&self, Parameters(input): Parameters<OntoInvariantRemoveInput>) -> String {+ match crate::dynamics_bcplus::remove_invariant(&self.db, &input.name) {+ Ok(removed) => format!(r#"{{"removed":{}}}"#, removed),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_invariant_check", description = "Evaluate every registered BC+ invariant against the current graph and return the names + descriptions of any that fail. Empty list means every invariant holds.")]+ async fn onto_invariant_check(&self) -> String {+ match crate::dynamics_bcplus::check_invariants(&self.db, &self.graph) {+ Ok(violations) => serde_json::to_string(&violations)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_default_register", description = "Register a BC+ default-value law. When the `condition_ask` SPARQL ASK returns `true`, the listed `defaults` triples are asserted (added if not already present) on the next call to `onto_default_apply`. Idempotent.")]+ async fn onto_default_register(&self, Parameters(input): Parameters<OntoDefaultRegisterInput>) -> String {+ let defaults: Vec<(String, String, String)> = input.defaults.into_iter()+ .filter_map(|t| if t.len() == 3 { Some((t[0].clone(), t[1].clone(), t[2].clone())) } else { None })+ .collect();+ let law = crate::dynamics_bcplus::DefaultLaw {+ name: input.name.clone(),+ condition_ask: input.condition_ask,+ defaults,+ description: input.description,+ };+ match crate::dynamics_bcplus::register_default(&self.db, &law) {+ Ok(()) => format!(r#"{{"ok":true,"registered":"{}"}}"#, input.name),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_default_apply", description = "Apply every registered BC+ default-value law whose condition currently holds. Adds only triples that don't already exist. Returns the names of laws that fired and the triples added.")]+ async fn onto_default_apply(&self) -> String {+ match crate::dynamics_bcplus::apply_defaults(&self.db, &self.graph) {+ Ok(result) => serde_json::to_string(&result)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }+#[tool(name = "onto_action_list", description = "List the names of all action schemas registered in this server's Dynamics store. Useful for the Planner / Claude to know what's available before composing a plan.")]async fn onto_action_list(&self) -> String {match crate::dynamics::list_names(&self.db) {diff --git a/src/shape_combinatorics.rs b/src/shape_combinatorics.rsnew file mode 100644index 00000000..975c297c--- /dev/null+++ b/src/shape_combinatorics.rs@@ -0,0 +1,174 @@+//! Property-combination lattice for shape-based extraction (#36, K-CAP 2025+//! Kastor).+//!+//! Given a class IRI, enumerate the lattice of property subsets the class's+//! instances could be characterised by. Used by shape-induction algorithms+//! that want to enumerate candidate SHACL shapes from data:+//!+//! - Level 0: `{}` (the trivial "class membership" shape).+//! - Level 1: `{p1}, {p2}, ..., {pk}` for each domain-property.+//! - Level 2: `{p1, p2}, ...` all 2-subsets.+//! - ...+//! - Level k: `{p1, p2, ..., pk}` (all properties at once).+//!+//! The lattice grows as `2^k` so the primitive bounds at `max_size`+//! (default 3) — sufficient for the K-CAP 2025 Kastor algorithm and avoids+//! pathological blowup on rich domains.++use crate::graph::GraphStore;+use serde::Serialize;+use std::collections::BTreeSet;+use std::sync::Arc;++#[derive(Clone, Debug, Serialize)]+pub struct LatticeReport {+ pub class_iri: String,+ pub properties_found: usize,+ pub max_size: usize,+ pub subsets_total: usize,+ /// Each subset is a sorted list of property IRIs. Sorted globally by+ /// (size, lex) for stable output.+ pub subsets: Vec<Vec<String>>,+}++/// Enumerate property-combination subsets up to `max_size` for a class.+pub fn enumerate(graph: &Arc<GraphStore>, class_iri: &str, max_size: usize) -> anyhow::Result<LatticeReport> {+ let max_size = if max_size == 0 { 3 } else { max_size };+ let q = format!(+ "SELECT DISTINCT ?p WHERE {{ ?p <http://www.w3.org/2000/01/rdf-schema#domain> <{}> }} LIMIT 100",+ class_iri+ );+ let js = graph.sparql_select(&q)?;+ let v: serde_json::Value = serde_json::from_str(&js)?;+ let rows = v["results"].as_array().cloned().unwrap_or_default();+ let mut props: Vec<String> = rows+ .iter()+ .filter_map(|r| {+ r["p"]+ .as_str()+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())+ })+ .collect();+ props.sort();+ props.dedup();++ let k = props.len();+ let cap = max_size.min(k);+ let mut subsets: Vec<Vec<String>> = vec![Vec::new()];++ for size in 1..=cap {+ for combo in combinations(&props, size) {+ subsets.push(combo);+ }+ }++ // Sort by (size, lex).+ subsets.sort_by(|a, b| a.len().cmp(&b.len()).then_with(|| a.cmp(b)));+ let total = subsets.len();+ Ok(LatticeReport {+ class_iri: class_iri.to_string(),+ properties_found: k,+ max_size,+ subsets_total: total,+ subsets,+ })+}++/// Enumerate k-subsets of `items` in lexicographic order. Iterative+/// implementation; no recursion-depth risk for k up to a handful.+fn combinations(items: &[String], k: usize) -> Vec<Vec<String>> {+ let n = items.len();+ if k == 0 || k > n {+ return Vec::new();+ }+ let mut out: Vec<Vec<String>> = Vec::new();+ let mut indices: Vec<usize> = (0..k).collect();+ loop {+ out.push(indices.iter().map(|&i| items[i].clone()).collect());+ // Find the rightmost index that can be incremented.+ let mut i = k;+ while i > 0 && indices[i - 1] == n - k + (i - 1) {+ i -= 1;+ }+ if i == 0 {+ break;+ }+ indices[i - 1] += 1;+ for j in i..k {+ indices[j] = indices[j - 1] + 1;+ }+ }+ out+}++/// Unused helper kept for completeness — exposes the underlying set type.+#[allow(dead_code)]+fn to_set(items: &[String]) -> BTreeSet<String> {+ items.iter().cloned().collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn graph_with_properties() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Person a owl:Class .+ ex:name a owl:DatatypeProperty ; rdfs:domain ex:Person .+ ex:age a owl:DatatypeProperty ; rdfs:domain ex:Person .+ ex:email a owl:DatatypeProperty ; rdfs:domain ex:Person .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn enumerate_full_lattice_for_three_properties_max_3() {+ let g = graph_with_properties();+ let r = enumerate(&g, "http://ex.org/Person", 3).unwrap();+ assert_eq!(r.properties_found, 3);+ // Empty + 3 singletons + 3 pairs + 1 triple = 8 = 2^3.+ assert_eq!(r.subsets_total, 8);+ // First subset is the empty one.+ assert_eq!(r.subsets[0], Vec::<String>::new());+ }++ #[test]+ fn enumerate_capped_at_max_size() {+ let g = graph_with_properties();+ let r = enumerate(&g, "http://ex.org/Person", 1).unwrap();+ // Empty + 3 singletons = 4.+ assert_eq!(r.subsets_total, 4);+ }++ #[test]+ fn enumerate_returns_just_empty_subset_for_no_properties() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://ex.org/> . ex:Lonely a owl:Class .",+ None,+ )+ .unwrap();+ let r = enumerate(&g, "http://ex.org/Lonely", 3).unwrap();+ assert_eq!(r.properties_found, 0);+ assert_eq!(r.subsets_total, 1);+ assert_eq!(r.subsets[0], Vec::<String>::new());+ }++ #[test]+ fn enumerate_zero_max_size_defaults_to_three() {+ let g = graph_with_properties();+ let r = enumerate(&g, "http://ex.org/Person", 0).unwrap();+ // 0 is the sentinel for "use the default of 3" — enumeration+ // produces the full 2^3 = 8 lattice.+ assert_eq!(r.subsets_total, 8);+ assert_eq!(r.max_size, 3);+ }+}