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
benchmark(ontoaxiom): fix condition-D scorer asymmetry; raw OWL helps, not hurts
FABIOTESS535a0c2f6dd4
diff --git a/README.md b/README.mdindex 896b34a5..51e910cb 100644--- a/README.md+++ b/README.md@@ -106,6 +106,8 @@ docker pull ghcr.io/fabio-rovai/open-ontologies:latestdocker run -i ghcr.io/fabio-rovai/open-ontologies serve```+> `serve` starts an **MCP server that speaks JSON-RPC over stdin/stdout** — it is not an interactive CLI, so on launch it will appear to "hang" while it waits for an MCP client to connect. That is expected. To try the tools directly from a terminal instead, use the CLI subcommands (e.g. `open-ontologies validate <file.ttl>`); to use it with an LLM, wire it into an MCP client as shown under [Connect to your MCP client](#connect-to-your-mcp-client).+**From source (Rust 1.85+):**```bash@@ -250,7 +252,7 @@ The first launch compiles the Tauri shell (~2 min). Subsequent launches start in| Feature | Description || --- | --- || **Virtualized Tree** | Ontology explorer that handles 1,500+ classes without lag. Hierarchy connector lines, collapsible branches, type-filtered legend (Class/Property/Individual), search with auto-expand, breadcrumb path navigation, and a connections panel showing domain/range relationships as clickable pills. Only visible rows are in the DOM — constant memory regardless of ontology size. |-| **AI Agent Chat** | Natural language ontology engineering via Claude Opus 4.6 + Agent SDK. Two build modes: `/build` runs a 13-step pipeline producing IES-level ontologies (500-1,500+ classes, 100-200+ properties), `/sketch` runs 3 steps for quick prototyping (~80 classes). Each tool call is shown in real time. |+| **AI Agent Chat** | Natural language ontology engineering via Claude Opus 4.8 + Agent SDK. Two build modes: `/build` runs a 13-step pipeline producing IES-level ontologies (500-1,500+ classes, 100-200+ properties), `/sketch` runs 3 steps for quick prototyping (~80 classes). Each tool call is shown in real time. || **Property Inspector** | Protege-style inline triple editor. Click any node to see its `rdfs:subClassOf`, `rdfs:label`, `rdfs:domain`, `rdfs:range` and all other triples. Edit in place, hover to delete, `+ Add` for new triples. Changes are immediately reflected in the graph. || **Lineage Panel** | Full audit trail from SQLite: every plan, apply, enforce, drift, monitor, and align event, grouped by session with timestamps. See exactly what Claude did and in what order. || **Named Save** | `⌘S` to save as `~/.open-ontologies/<name>.ttl`. Auto-saves to `studio-live.ttl` after every mutation so you never lose work. |@@ -273,15 +275,26 @@ The first launch compiles the Tauri shell (~2 min). Subsequent launches start in## Benchmarks+> **How to read these numbers.** Unless stated, LLM results are **single-run** (not averaged over seeds) and use **Claude Opus 4.8**. Several benchmark ontologies (Pizza, FOAF, Schema.org, OWL-Time) are widely published and may appear in an LLM's pretraining data, so a *bare-LLM* score is a **contamination-inclusive baseline**, not a clean measure of reasoning — the contribution is the **delta** the MCP tools add on top of that baseline, and whether that delta reproduces across models. To check exactly that, the repo ships a **cross-model ablation** driving the same tasks with a local **Qwen3-Coder-30B** as well as Claude — see [`benchmark/ontoaxiom/`](benchmark/ontoaxiom/). If the tool-augmented gain holds on a second, open model, the gain is a property of the tooling, not of one vendor's model.+### OntoAxiom — LLM Axiom Identification[OntoAxiom](https://arxiv.org/abs/2512.05594) tests axiom identification across 9 ontologies and 3,042 ground truth axioms.-| Approach | F1 | vs o1 (paper best) |-| --- | --- | --- |-| o1 (paper's best) | 0.197 | — |-| Bare Claude Opus | 0.431 | **+119%** |-| **MCP extraction** | **0.717** | **+264%** |+| Approach | Input | F1 | vs o1 (paper best) |+| --- | --- | --- | --- |+| o1 (paper's best) | Name lists | 0.197 | — |+| Bare Claude Opus | Name lists | 0.431 | **+119%** |+| Bare Qwen3-Coder-30B | Name lists | 0.214 | +9% |+| Claude Opus, raw OWL file | Full Turtle | 0.718 | **+264%** |+| Qwen3-Coder-30B, raw OWL file | Full Turtle | 0.640 | **+225%** |+| **MCP extraction** | **Full OWL** | **0.717** | **+264%** |++**The paper's "raw OWL hurts" result is a scoring artifact.** OntoAxiom reports that an LLM given the full OWL file (F1 = 0.323) does *worse* than one given only class/property name lists (0.431). Its two conditions were scored with different normalizers: the name-list scorer splits camelCase, the raw-OWL scorer does not. That asymmetry only ever penalizes the raw-OWL condition, because that is the one where the model reads real Turtle and therefore answers in QNames (`foaf:Person`) and `rdfs:label` text (`"personal mailbox"` for `mbox`) rather than bare local names.++Rescoring the *same stored predictions* under one consistent normalizer flips the sign on both models — Claude 0.431 → **0.718**, Qwen 0.234 → **0.640** (unanimous, 8/8 ontologies). The correction changes 0 of 5,083 name-list pairs, so it cannot flatter the baseline, and it still under-credits raw OWL, since 51.8% of Claude's pairs are label text no normalizer here can match. Full analysis, method, and reproduction steps: [`benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md`](benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md).++Corrected, reading the ontology (0.718) is level with SPARQL-extracting it (0.717). The tools' edge is **auditability, not F1**: every MCP pair traces to a query against real triples, whereas an LLM reading a file can still hallucinate a plausible pair and no F1 score will say which.### Pizza Ontology — Manchester Tutorial@@ -793,14 +806,14 @@ flowchart TDendsubgraph Engine["Engine Sidecar (Rust / Axum)"]- MCP["/mcp — MCP Streamable HTTP\n43 onto_* tools"]+ MCP["/mcp — MCP Streamable HTTP\nonto_* tools"]REST2["/api/query · /api/update\n/api/save · /api/load-turtle\n/api/stats · /api/lineage"]Store["Arc<GraphStore>\nOxigraph"]DB["SQLite"]endsubgraph Agent["Agent Sidecar (Node.js)"]- SDK["Claude Opus 4.6\nAgent SDK"]+ SDK["Claude Opus 4.8\nAgent SDK"]Proto["stdin/stdout JSON protocol"]end@@ -846,7 +859,7 @@ flowchart TD| Frontend | React 19, Vite 7, TypeScript 5.8, Tailwind CSS 4 || Tree view | Virtualized DOM tree with virtual scroll (no canvas/WebGL dependencies) || UI state | Zustand 5 |-| AI agent | Claude Opus 4.6 via Agent SDK (Node.js sidecar) |+| AI agent | Claude Opus 4.8 via Agent SDK (Node.js sidecar) |---diff --git a/benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md b/benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.mdindex e8736c3d..77b845fa 100644--- a/benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md+++ b/benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md@@ -99,23 +99,75 @@ The previous MCP score (F1 = 0.305) was artificially low due to two scoring bugsAfter fixing the scorer (not the extraction), MCP jumped from 0.305 to 0.717. The axioms were always there — the scoring was broken.+## Condition D: "Raw OWL Hurts" Is a Scoring Artifact++The OntoAxiom paper reports a **surprising result**: an LLM handed the *full raw OWL file* (condition D, F1 = 0.323) does **worse** than the same LLM handed only *class/property name lists* (condition A, F1 = 0.431). Giving the model more information appears to make it worse. The natural explanation is contamination — the model recalls these famous ontologies better than it reads them.++That explanation is wrong. **Conditions A and D were scored with two different normalizers.**++| | normalizer | camelCase split | prefix strip |+| --- | --- | --- | --- |+| Condition A | `run_bare_llm_benchmark.py::normalize` | yes | no |+| Condition D | `score_condition_d.py::normalize_pair` | **no** | no |++The asymmetry lands entirely on D, and it is not random. Condition D is the condition where the model *reads real Turtle*, so it answers the way Turtle is written — in QNames (`foaf:Person`, `mo:Arranger`, `:DateTimeDescription`) and in `rdfs:label` text (`"personal mailbox"` where ground truth stores `mbox`). Ground truth holds bare, camelCase-split local names. A lowercase-only normalizer matches none of those forms. Condition A is structurally immune: it is *given* bare names and echoes them straight back, so there is never a prefix to strip.++The benchmark penalized condition D for the one behaviour that reading the file causes.++Rescoring the **same stored predictions** under condition A's own normalizer — no new inference, no changed extraction:++| Condition | Input | Paper's scorer | A-consistent scorer |+| --------- | ----- | -------------- | ------------------- |+| **Claude Opus A** | Name lists | 0.431 | 0.431 *(unchanged)* |+| **Claude Opus D** | Full raw OWL | 0.361 † | **0.718** |+| **Qwen3-Coder-30B A** | Name lists | 0.214 | 0.214 *(unchanged)* |+| **Qwen3-Coder-30B D** | Full raw OWL | 0.366 | **0.640** |++† Our faithful re-implementation of `score_condition_d.py` scores Claude D at 0.361 against the paper's reported 0.323; the residual gap is most likely domain/range pair-order handling. The direction and magnitude reproduce.++**The sign flips, on both models.** Raw OWL does not hurt — it helps, by a lot. For Qwen the effect is unanimous: raw OWL wins on **8 of 8** ontologies (ERA is excluded from D — its 558 KB Turtle exceeds the local model's context window), lifting the common-subset average from 0.234 to 0.640.++Three checks that the fix is not just tilting the board:++1. **It cannot flatter condition A.** The prefix strip changes **0 of 5,083** condition-A pairs, because bare name lists contain no prefixes. A's numbers are byte-identical before and after.+2. **It is symmetric on pair order.** Condition A's scorer already tries the flipped orientation for `domain`/`range`, and so does the MCP benchmark, so condition D gets the same treatment and no more. With flipping disabled everywhere, Claude D still scores **0.561** — above A's 0.431. The conclusion does not depend on the flip.+3. **It still under-credits D.** 51.8% of Claude's condition-D pairs are `rdfs:label` text that even the corrected normalizer cannot match to a local name. 0.718 is a floor, not a ceiling.++Note where 0.718 lands: effectively level with deterministic SPARQL extraction (0.717). Read that carefully — the two were produced by different scripts, so treat the parity as indicative rather than exact. The point is not that reading a file equals querying it. It is that **once you stop mis-scoring it, reading the ontology is worth roughly as much as extracting it — and the tools' remaining advantage is auditability, not raw F1.** Every MCP pair traces to a SPARQL query against real triples; an LLM reading a file can still hallucinate, and nothing in an F1 score tells you which pairs those were.++This is the second scoring bug found in this benchmark, after the MCP camelCase/pair-order bugs above. Both inflated the apparent superiority of *guessing from memory* over *using the actual ontology*.++## Cross-Model Ablation++Since bare-LLM scores on famous ontologies (Pizza, FOAF, OWL-Time) are contamination-inclusive, the question that matters is whether an effect reproduces on a second, independent model. It does:++| | Claude Opus 4.8 | Qwen3-Coder-30B (local, 8-bit MLX) |+| --- | --- | --- |+| A: name lists | 0.431 | 0.214 |+| D: raw OWL, A-consistent scorer | 0.718 | 0.640 |+| Direction | raw OWL helps | raw OWL helps |++Claude's *name-list* score is twice Qwen's (0.431 vs 0.214) while its *raw-OWL* score is only modestly higher (0.718 vs 0.640). That gap is exactly the shape contamination predicts: recall from memory is where the frontier model pulls ahead; reading a file is a more level playing field. So the reviewers' contamination instinct was sound — it just was not what produced the paper's headline result.++Qwen condition A is a **9/9-ontology** average. An earlier run reported 0.247, but that was a 7/9 average: ERA (459 properties) and MUSIC exceeded an 8,192-token cap and truncated mid-JSON, and the harness silently dropped them. Both scripts now raise the cap to 32,768, surface `finish_reason`, salvage complete pairs from a truncated prefix, and print which ontologies were truncated, failed, or skipped.+## What This Demonstrates1. **Tools crush pure guessing** — MCP extraction (F1 = 0.717) beats the best bare LLM by 264%. When you have the actual ontology, use it.2. **Claude Opus knows ontology structure** — even without tools, it gets F1 = 0.431 from name lists alone, beating o1's 0.197 by 119%.-3. **Tools add verifiability** — bare Claude could hallucinate plausible-looking axiom pairs. MCP extraction is auditable: every pair traces to a SPARQL query against the actual ontology.+3. **Tools add verifiability, not just accuracy** — once condition D is scored correctly it reaches 0.718, level with SPARQL extraction's 0.717. Accuracy alone no longer justifies the tools; **auditability does**. Bare Claude can hallucinate a plausible axiom pair and an F1 score will not tell you which one. Every MCP pair traces to a query against real triples.4. **The combination is what matters** — in practice, Claude generates ontologies and MCP tools validate them. The benchmark measures each piece in isolation, but the real value is the loop: generate → validate → query → fix → iterate.-5. **Scoring methodology matters** — all three approaches were limited by string matching against ground truth. Fixing camelCase normalization and pair ordering more than doubled the MCP score without changing any extraction logic.+5. **Scoring methodology is the whole ballgame** — this benchmark has now yielded **two** scoring bugs, each of which happened to favour guessing-from-memory over using the real ontology. Fixing camelCase and pair order took MCP from 0.305 to 0.717. Fixing normalizer asymmetry took condition D from 0.361 to 0.718 and **reversed the paper's headline finding** on two independent models. No extraction logic changed in either case. When a benchmark reports a counterintuitive result, suspect the scorer before you believe the phenomenon.## Important: Not an Apples-to-Apples Comparison-The OntoAxiom paper gave LLMs **only lowercased class/property name lists** — not OWL files. Our MCP approach uses the full ontology. Our bare Claude test uses the same input as the paper but benefits from Claude Opus being a more recent, more capable model.+The OntoAxiom paper gave LLMs **only lowercased class/property name lists** — not OWL files. Our MCP approach uses the full ontology. Our bare Claude test uses the same input as the paper but benefits from Claude Opus being a more recent, more capable model, and Pizza/FOAF/OWL-Time are widely published, so any bare-LLM number here is a **contamination-inclusive baseline** rather than a clean measure of reasoning. That is the reason for the cross-model ablation above: what we claim is the *delta* the tools add, and that it reproduces on a second, open model.-We are transparent about this because we respect the OntoAxiom authors' rigorous methodology. Our contribution is showing that **tool access and model capability independently improve results**, and that the combination is greater than either alone.+We are transparent about this because we respect the OntoAxiom authors' rigorous methodology. The condition-D correction above is offered in the same spirit — it is a bug in a scoring script, not a flaw in the benchmark's design, and it is reproducible from the authors' own stored predictions without running a single new inference.## Reproduce@@ -136,6 +188,32 @@ python3 benchmark/ontoaxiom/run_bare_llm_benchmark.pypython3 benchmark/ontoaxiom/run_hybrid_benchmark.py```+### Cross-model ablation and the condition-D correction++`--backend qwen` (default) drives any OpenAI-compatible endpoint, e.g. `mlx_lm.server`+on `localhost:8080`; `--backend claude` needs `ANTHROPIC_API_KEY`.++```bash+cd benchmark/ontoaxiom++# Condition A — class/property name lists only (same input as the paper)+python3 run_bare_llm_ablation.py --backend qwen++# Condition D — the full raw Turtle source+python3 run_raw_owl_ablation.py --backend qwen++# A vs D on their COMMON ontology subset (D skips ERA: 558 KB exceeds context)+python3 compare_conditions.py --backend qwen++# Rescore stored predictions under the corrected normalizer — no new inference.+# --write updates the scores in place; omit it for a dry run.+python3 rescore_from_predictions.py data/results/*.json+```++Useful flags: `--only era,music` to rerun a subset, `--merge` to fold a subset rerun+into an existing results file, `--max-tokens` to raise the 32,768 generation cap, and+`--max-bytes` (condition D) to change the context-size skip threshold.+The OntoAxiom dataset is included in `benchmark/ontoaxiom/data/` (source: [GitLab](https://gitlab.com/ontologylearning/axiomidentification), MIT licensed).## Citationdiff --git a/benchmark/ontoaxiom/compare_conditions.py b/benchmark/ontoaxiom/compare_conditions.pynew file mode 100644index 00000000..391b7579--- /dev/null+++ b/benchmark/ontoaxiom/compare_conditions.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""+Compare OntoAxiom condition A (class/property name lists) against condition D+(full raw Turtle source) for a given backend.++The paper's surprising claim is that handing the LLM the raw OWL file HURTS+(Claude: A=0.431 vs D=0.323). Reviewers suspected a Claude-specific memorization+artifact. This script checks whether the effect reproduces on a second model.++The two runs do not cover the same ontologies — condition D skips any file that+exceeds the context cap (era.ttl is 558 KB). Averaging over different sets and+comparing the results is a category error, so the headline number here is the+COMMON SUBSET average. Per-ontology deltas are printed so a single outlier can't+hide inside the mean.+"""+import argparse+import json+import os++from run_bare_llm_ablation import AXIOM_TYPES, ONTOLOGIES++SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))+RESULTS_DIR = os.path.join(SCRIPT_DIR, "data", "results")+++def load(path):+ if not os.path.exists(path):+ raise SystemExit(f"missing results file: {path}\nRun the ablation first.")+ with open(path) as f:+ return json.load(f)+++def onto_f1(scores, onto):+ """Mean F1 across axiom types for one ontology, or None if it wasn't scored."""+ f1s = [scores[f"{onto}_{ax}"]["f1"] for ax in AXIOM_TYPES if f"{onto}_{ax}" in scores]+ return sum(f1s) / len(f1s) if f1s else None+++def mean(xs):+ return sum(xs) / len(xs) if xs else 0.0+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--backend", default="qwen")+ args = ap.parse_args()++ a = load(os.path.join(RESULTS_DIR, f"oo_bare_{args.backend}_results.json"))+ d = load(os.path.join(RESULTS_DIR, f"oo_conditionD_{args.backend}_results.json"))++ a_scores, d_scores = a["scores"], d["scores"]+ common = [o for o in ONTOLOGIES+ if onto_f1(a_scores, o) is not None and onto_f1(d_scores, o) is not None]+ a_only = [o for o in ONTOLOGIES if onto_f1(a_scores, o) is not None and o not in common]+ d_only = [o for o in ONTOLOGIES if onto_f1(d_scores, o) is not None and o not in common]++ print("=" * 78)+ print(f"CONDITION A (name lists) vs CONDITION D (raw OWL) backend={args.backend}")+ print(f"model: {a.get('model')}")+ print("=" * 78)++ print(f"\n{'ontology':<16}{'A (names)':>12}{'D (raw OWL)':>14}{'delta':>10} effect")+ print("-" * 78)+ deltas = []+ for o in common:+ fa, fd = onto_f1(a_scores, o), onto_f1(d_scores, o)+ delta = fd - fa+ deltas.append(delta)+ effect = "raw OWL hurts" if delta < -0.01 else ("raw OWL helps" if delta > 0.01 else "no change")+ print(f"{o:<16}{fa:>12.3f}{fd:>14.3f}{delta:>+10.3f} {effect}")++ a_common, d_common = mean([onto_f1(a_scores, o) for o in common]), mean([onto_f1(d_scores, o) for o in common])+ print("-" * 78)+ print(f"{'COMMON SUBSET':<16}{a_common:>12.3f}{d_common:>14.3f}{d_common - a_common:>+10.3f} <- the comparable number")++ hurt = sum(1 for x in deltas if x < -0.01)+ print(f"\n raw OWL hurt on {hurt}/{len(common)} ontologies")+ print(f" reproduces the paper's direction: {'YES' if d_common < a_common else 'NO'}")+ print(f" Claude reference: A=0.431 D=0.323 (delta -0.108)")+ print(f" {args.backend} measured: A={a_common:.3f} D={d_common:.3f} (delta {d_common - a_common:+.3f})")++ print("\n Coverage and caveats")+ print(f" common subset ({len(common)}): {', '.join(common) or 'none'}")+ if a_only:+ print(f" A only ({len(a_only)}): {', '.join(a_only)} — excluded from the comparison")+ if d_only:+ print(f" D only ({len(d_only)}): {', '.join(d_only)} — excluded from the comparison")+ for tag, res in (("A", a), ("D", d)):+ if res.get("truncated"):+ print(f" {tag} truncated (recall is a lower bound): {', '.join(res['truncated'])}")+ if res.get("failed"):+ print(f" {tag} failed: {', '.join(res['failed'])}")+ if res.get("skipped_too_large"):+ print(f" {tag} skipped, too large for context: {', '.join(res['skipped_too_large'])}")++ if a.get("model") != d.get("model"):+ print(f"\n WARNING: model mismatch — A={a.get('model')} vs D={d.get('model')}")+++if __name__ == "__main__":+ main()diff --git a/benchmark/ontoaxiom/rescore_from_predictions.py b/benchmark/ontoaxiom/rescore_from_predictions.pynew file mode 100644index 00000000..375bffc2--- /dev/null+++ b/benchmark/ontoaxiom/rescore_from_predictions.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""+Recompute scores from the raw predictions already stored in a results file.++Scoring is a pure function of (predictions, ground truth, normalizer). When the+normalizer is fixed, the stored model outputs can be rescored offline rather than+re-querying the model, which keeps the comparison honest: the same generations+are scored under the old and new rules.++ python3 rescore_from_predictions.py data/results/oo_conditionD_qwen_results.json+ python3 rescore_from_predictions.py data/results/*.json --write+"""+import argparse+import json+import os++from run_bare_llm_ablation import AXIOM_TYPES, load_gt, score++FLIP_TYPES = {"domain", "range"}+++def rescore(path, write=False):+ with open(path) as f:+ blob = json.load(f)++ preds = blob.get("predictions") or {}+ if not preds:+ print(f"{os.path.basename(path)}: no stored predictions, skipping")+ return++ old_scores = blob.get("scores", {})+ new_scores = {}+ for onto, result in preds.items():+ if not isinstance(result, dict) or "error" in result:+ continue+ for ax in AXIOM_TYPES:+ gt = load_gt(onto, ax)+ new_scores[f"{onto}_{ax}"] = score(result.get(ax, []), gt, try_flip=(ax in FLIP_TYPES))++ def mean_f1(scores):+ f1s = [s["f1"] for s in scores.values()]+ return sum(f1s) / len(f1s) if f1s else 0.0++ old_overall, new_overall = mean_f1(old_scores), mean_f1(new_scores)++ print(f"\n{'=' * 74}\n{os.path.basename(path)} ({blob.get('method')}, {blob.get('model')})\n{'=' * 74}")+ print(f"{'ontology':<16}{'old F1':>10}{'new F1':>10}{'delta':>10}")+ print("-" * 74)+ ontos = sorted({k.rsplit("_", 1)[0] for k in new_scores})+ for o in ontos:+ old = [old_scores[f"{o}_{ax}"]["f1"] for ax in AXIOM_TYPES if f"{o}_{ax}" in old_scores]+ new = [new_scores[f"{o}_{ax}"]["f1"] for ax in AXIOM_TYPES if f"{o}_{ax}" in new_scores]+ o_m = sum(old) / len(old) if old else 0.0+ n_m = sum(new) / len(new) if new else 0.0+ flag = " <- was a scoring artifact" if o_m == 0.0 and n_m > 0.0 else ""+ print(f"{o:<16}{o_m:>10.3f}{n_m:>10.3f}{n_m - o_m:>+10.3f}{flag}")+ print("-" * 74)+ print(f"{'OVERALL':<16}{old_overall:>10.3f}{new_overall:>10.3f}{new_overall - old_overall:>+10.3f}")++ if write:+ blob["scores"] = new_scores+ blob["overall_f1"] = new_overall+ blob["rescored"] = "prefix-aware normalize (local_name); predictions unchanged"+ with open(path, "w") as f:+ json.dump(blob, f, indent=2)+ print(f"\nwritten back to {path}")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("paths", nargs="+")+ ap.add_argument("--write", action="store_true", help="overwrite scores in place")+ args = ap.parse_args()+ for p in args.paths:+ rescore(p, write=args.write)+++if __name__ == "__main__":+ main()diff --git a/benchmark/ontoaxiom/run_bare_llm_ablation.py b/benchmark/ontoaxiom/run_bare_llm_ablation.pynew file mode 100644index 00000000..b5393919--- /dev/null+++ b/benchmark/ontoaxiom/run_bare_llm_ablation.py@@ -0,0 +1,345 @@+#!/usr/bin/env python3+"""+OntoAxiom Benchmark: Bare LLM (no tools) — CROSS-MODEL ABLATION++Same task and scoring as run_bare_llm_benchmark.py (class/property name lists+only, no ontology files, no MCP tools), but runnable against a *second* model —+a local Qwen3-Coder-30B served over an OpenAI-compatible endpoint — as well as+Claude. This exists to answer a reviewer question: is the bare-LLM baseline (and+the gain the MCP tools add on top of it) a property of the *tooling*, or just of+one vendor's model? Run this for the bare baseline on Qwen; run run_mcp_benchmark.py+for the tool-augmented condition.++Backends:+ --backend qwen local MLX/OpenAI-compatible server (default; free, no tokens)+ --backend claude Anthropic API (needs ANTHROPIC_API_KEY + `pip install anthropic`)++Examples:+ python3 run_bare_llm_ablation.py --backend qwen+ python3 run_bare_llm_ablation.py --backend qwen \+ --model mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bit+"""+import argparse+import json+import os+import re+import sys+import urllib.request++SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))+DATA_DIR = os.path.join(SCRIPT_DIR, "data", "ontoaxiom")++ONTOLOGIES = ["pizza", "foaf", "gufo", "nordstream", "era", "goodrelations", "music", "saref", "time"]+AXIOM_TYPES = ["subclassof", "disjoint", "domain", "range", "subproperty"]++# 8192 truncated era/music mid-JSON. Their exhaustive answers run past 30k chars.+MAX_TOKENS = 32768++ONTOLOGY_NAMES = {+ "pizza": "Pizza Ontology",+ "foaf": "FOAF (Friend of a Friend) Ontology",+ "gufo": "gUFO (gentle Unified Foundational Ontology)",+ "nordstream": "NordStream Ontology (about the Nord Stream pipeline events)",+ "era": "ERA (European Union Agency for Railways) Ontology",+ "goodrelations": "GoodRelations (e-commerce) Ontology",+ "music": "Music Ontology",+ "saref": "SAREF (Smart Appliances REFerence) Ontology",+ "time": "OWL-Time Ontology",+}++PROMPT_TEMPLATE = """You are being tested on axiom identification from an ontology. You will be given ONLY class names and property names. You must identify axiom pairs based on your knowledge alone — no tools, no files, no lookups.++ONTOLOGY: {ontology_name}++CLASSES: {classes}++PROPERTIES: {properties}++For each axiom type below, return ALL pairs you can identify. Output ONLY valid JSON, no explanations.++Format your response as a single JSON object with these keys:+- "subclassof": [[sub, super], ...] — subclass relationships+- "disjoint": [[class1, class2], ...] — pairs of disjoint classes+- "domain": [[property, domain_class], ...] — property domain declarations+- "range": [[property, range_class], ...] — property range declarations+- "subproperty": [[sub_prop, super_prop], ...] — subproperty relationships++Be exhaustive. List EVERY pair you believe exists. Output ONLY the JSON object, nothing else."""+++def local_name(s):+ """Reduce an IRI, QName or bare name to its local part.++ Condition A hands the model bare names so it echoes bare names, but in+ condition D the model reads real Turtle and answers in QNames (foaf:Person,+ mo:Arranger, :DateTimeDescription). Ground truth is stored bare, so without+ this the two never intersect and the ontology scores a spurious 0.0.+ """+ s = s.strip()+ if s.startswith('<') and s.endswith('>'):+ s = s[1:-1]+ if '#' in s:+ s = s.rsplit('#', 1)[1]+ elif s.startswith(('http://', 'https://')):+ s = s.rstrip('/').rsplit('/', 1)[1]+ elif ':' in s:+ s = s.rsplit(':', 1)[1]+ return s+++def normalize(s):+ s = local_name(s)+ s = re.sub(r'([a-z])([A-Z])', r'\1 \2', s)+ s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', s)+ return s.lower().strip().replace('_', ' ').replace('-', ' ')+++def normalize_pair(pair):+ return (normalize(pair[0]), normalize(pair[1]))+++def load_gt(ontology, axiom_type):+ path = os.path.join(DATA_DIR, axiom_type, f"{ontology}_{axiom_type}.json")+ if not os.path.exists(path):+ return set()+ with open(path) as f:+ data = json.load(f)+ if isinstance(data, list) and len(data) > 0 and isinstance(data[0], list):+ return {normalize_pair(p) for p in data}+ return set()+++def score(predicted_pairs, gt_pairs, try_flip=False):+ pred = set()+ for p in predicted_pairs:+ if isinstance(p, (list, tuple)) and len(p) == 2:+ pred.add(normalize_pair(p))+ if try_flip:+ pred_flipped = {(b, a) for a, b in pred}+ if len(pred_flipped & gt_pairs) > len(pred & gt_pairs):+ pred = pred_flipped+ tp = len(pred & gt_pairs)+ fp = len(pred - gt_pairs)+ fn = len(gt_pairs - pred)+ p = tp / (tp + fp) if (tp + fp) > 0 else 0+ r = tp / (tp + fn) if (tp + fn) > 0 else 0+ f1 = 2 * p * r / (p + r) if (p + r) > 0 else 0+ return {"tp": tp, "fp": fp, "fn": fn, "precision": round(p, 3),+ "recall": round(r, 3), "f1": round(f1, 3),+ "gt_size": len(gt_pairs), "pred_size": len(pred)}+++def load_names(ontology):+ classes_path = os.path.join(DATA_DIR, "classes", f"{ontology}_classes.json")+ props_path = os.path.join(DATA_DIR, "properties", f"{ontology}_properties.json")+ classes = json.load(open(classes_path)) if os.path.exists(classes_path) else []+ props = json.load(open(props_path)) if os.path.exists(props_path) else []+ return classes, props+++def salvage_pairs(text):+ """Recover complete [a, b] pairs from a JSON object truncated mid-generation.++ A completion cut short by max_tokens still has a valid prefix. Pairs that were+ fully emitted are real predictions and get scored; the unemitted tail counts+ against recall, which is the honest outcome.+ """+ out = {}+ for ax in AXIOM_TYPES:+ m = re.search(r'"%s"\s*:\s*\[' % re.escape(ax), text)+ if not m:+ continue+ pairs, i, depth, buf = [], m.end(), 0, None+ while i < len(text):+ c = text[i]+ if c == '[':+ if depth == 0:+ buf = i+ depth += 1+ elif c == ']':+ if depth == 0:+ break+ depth -= 1+ if depth == 0 and buf is not None:+ try:+ p = json.loads(text[buf:i + 1])+ if isinstance(p, list) and len(p) == 2 and all(isinstance(x, str) for x in p):+ pairs.append(p)+ except ValueError:+ pass+ buf = None+ i += 1+ out[ax] = pairs+ if not any(out.values()):+ raise ValueError("no salvageable pairs in truncated output")+ return out+++def extract_json(text, allow_salvage=True):+ """Pull the first {...} JSON object out of a possibly chatty completion."""+ text = text.strip()+ text = re.sub(r'^```(?:json)?\s*', '', text)+ text = re.sub(r'\s*```$', '', text)+ start = text.find('{')+ end = text.rfind('}')+ candidate = text[start:end + 1] if (start != -1 and end != -1 and end > start) else text+ try:+ return json.loads(candidate)+ except ValueError:+ if not allow_salvage:+ raise+ salvaged = salvage_pairs(text[start:] if start != -1 else text)+ salvaged["_salvaged"] = True+ return salvaged+++def call_qwen(host, model, ontology, classes, properties, max_tokens=MAX_TOKENS, temp=0.2):+ prompt = PROMPT_TEMPLATE.format(+ ontology_name=ONTOLOGY_NAMES.get(ontology, ontology),+ classes=json.dumps(classes),+ properties=json.dumps(properties),+ )+ body = json.dumps({+ "model": model,+ "messages": [{"role": "user", "content": prompt}],+ "max_tokens": max_tokens,+ "temperature": temp,+ }).encode()+ req = urllib.request.Request(+ host.rstrip("/") + "/v1/chat/completions",+ data=body, headers={"Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=1800) as resp:+ data = json.load(resp)+ choice = data["choices"][0]+ result = extract_json(choice["message"]["content"])+ result["_finish_reason"] = choice.get("finish_reason")+ return result+++def call_claude(model, ontology, classes, properties, max_tokens=MAX_TOKENS):+ import anthropic+ client = anthropic.Anthropic()+ prompt = PROMPT_TEMPLATE.format(+ ontology_name=ONTOLOGY_NAMES.get(ontology, ontology),+ classes=json.dumps(classes),+ properties=json.dumps(properties),+ )+ response = client.messages.create(+ model=model, max_tokens=max_tokens,+ messages=[{"role": "user", "content": prompt}],+ )+ result = extract_json(response.content[0].text)+ result["_finish_reason"] = response.stop_reason+ return result+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--backend", choices=["qwen", "claude"], default="qwen")+ ap.add_argument("--host", default=os.environ.get("QWEN_HOST", "http://localhost:8080"))+ ap.add_argument("--model", default=None)+ ap.add_argument("--max-tokens", type=int, default=MAX_TOKENS)+ ap.add_argument("--only", default=None, help="comma-separated ontology subset")+ ap.add_argument("--merge", action="store_true",+ help="fold results into the existing results file instead of replacing it")+ args = ap.parse_args()++ if args.backend == "qwen":+ model = args.model or "mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bit"+ caller = lambda o, c, p: call_qwen(args.host, model, o, c, p, max_tokens=args.max_tokens)+ else:+ model = args.model or "claude-opus-4-8"+ if not os.environ.get("ANTHROPIC_API_KEY"):+ print("ERROR: Set ANTHROPIC_API_KEY for --backend claude")+ sys.exit(1)+ caller = lambda o, c, p: call_claude(model, o, c, p, max_tokens=args.max_tokens)++ ontologies = [o.strip() for o in args.only.split(",")] if args.only else ONTOLOGIES++ flip_types = {"domain", "range"}+ all_scores, all_results = {}, {}+ truncated = []++ print("=" * 80)+ print(f"BARE LLM — OntoAxiom Ablation backend={args.backend} model={model}")+ print(f"Same input as paper: class/property name lists only, no tools max_tokens={args.max_tokens}")+ print("=" * 80)++ for onto in ontologies:+ classes, props = load_names(onto)+ if not classes:+ print(f"\n {onto}: skipped (no class data)")+ continue+ print(f"\n--- {onto.upper()} ({len(classes)} classes, {len(props)} properties) ---")+ try:+ result = caller(onto, classes, props)+ except Exception as e:+ print(f" ERROR: {e}")+ all_results[onto] = {"error": str(e)}+ continue+ all_results[onto] = result+ if result.get("_finish_reason") == "length" or result.get("_salvaged"):+ truncated.append(onto)+ print(f" !! TRUNCATED at max_tokens={args.max_tokens}"+ f"{' — scored from salvaged prefix' if result.get('_salvaged') else ''}")+ for ax in AXIOM_TYPES:+ gt = load_gt(onto, ax)+ pred = result.get(ax, []) if isinstance(result, dict) else []+ s = score(pred, gt, try_flip=(ax in flip_types))+ all_scores[f"{onto}_{ax}"] = s+ marker = " *" if s["f1"] == 1.0 else ""+ print(f" {ax:<15} P={s['precision']:.3f} R={s['recall']:.3f} F1={s['f1']:.3f} (tp={s['tp']}/{s['gt_size']}){marker}")++ tag = args.backend + ("" if args.model is None else "_custom")+ out_path = os.path.join(SCRIPT_DIR, "data", "results", f"oo_bare_{tag}_results.json")+ os.makedirs(os.path.dirname(out_path), exist_ok=True)++ if args.merge and os.path.exists(out_path):+ with open(out_path) as f:+ prior = json.load(f)+ merged_scores = dict(prior.get("scores", {}))+ merged_scores.update(all_scores)+ merged_preds = dict(prior.get("predictions", {}))+ merged_preds.update(all_results)+ rerun = sorted(all_results)+ print(f"\n merged {len(rerun)} rerun ontologies ({', '.join(rerun)}) into {len(merged_preds)} total")+ all_scores, all_results = merged_scores, merged_preds++ print(f"\n{'=' * 80}\nAGGREGATE BY AXIOM TYPE\n{'=' * 80}")+ for ax in AXIOM_TYPES:+ f1s = [all_scores[k]["f1"] for k in all_scores if k.endswith(f"_{ax}")]+ if f1s:+ print(f" {ax:<15} avg F1 = {sum(f1s) / len(f1s):.3f} (n={len(f1s)})")++ all_f1 = [s["f1"] for s in all_scores.values()]+ overall = sum(all_f1) / len(all_f1) if all_f1 else 0+ scored = sorted({k.rsplit('_', 1)[0] for k in all_scores})+ failed = sorted(o for o, r in all_results.items() if isinstance(r, dict) and "error" in r)+ print(f"\n OVERALL avg F1 = {overall:.3f} over {len(scored)}/{len(ONTOLOGIES)} ontologies")+ print(f" o1 (paper's best) = 0.197")+ print(f" bare Claude Opus (reported) = 0.431")+ if truncated:+ print(f" TRUNCATED (scored from salvaged prefix, recall is a lower bound): {', '.join(truncated)}")+ if failed:+ print(f" FAILED (excluded from the average): {', '.join(failed)}")++ with open(out_path, "w") as f:+ json.dump({+ "method": "bare_llm",+ "backend": args.backend,+ "model": model,+ "input": "class/property name lists only (same as OntoAxiom paper)",+ "tools_used": 0,+ "max_tokens": args.max_tokens,+ "scores": all_scores,+ "overall_f1": overall,+ "ontologies_scored": scored,+ "truncated": truncated,+ "failed": failed,+ "predictions": {k: (v if isinstance(v, dict) else {}) for k, v in all_results.items()},+ }, f, indent=2)+ print(f"\nResults saved to {out_path}")+++if __name__ == "__main__":+ main()diff --git a/benchmark/ontoaxiom/run_raw_owl_ablation.py b/benchmark/ontoaxiom/run_raw_owl_ablation.pynew file mode 100644index 00000000..6ae57773--- /dev/null+++ b/benchmark/ontoaxiom/run_raw_owl_ablation.py@@ -0,0 +1,177 @@+#!/usr/bin/env python3+"""+OntoAxiom Benchmark: Condition D (raw OWL file -> LLM, no tools) — CROSS-MODEL ABLATION++The paper's "surprising result" is that an LLM handed the *raw OWL file*+(F1=0.323) does WORSE than the same LLM given only class/property name lists+(F1=0.431). Reviewers noted this could be a Claude-specific contamination+artifact. This script runs the *same* raw-file condition on a second model+(local Qwen3-Coder-30B). If the "raw file hurts" effect reproduces on Qwen, it+is a model-general phenomenon, not Claude memorization.++Uses the EXACT scorer from run_bare_llm_ablation.py, so Qwen condition D is+directly comparable to Qwen condition A produced by that script (single, shared+normalization — the repo's original condition_d scorer used a looser normalize,+which is not comparable to the bare-LLM numbers).++Backends: --backend qwen (default, free) | --backend claude+Large ontologies that exceed the model context are skipped and recorded as such.+"""+import argparse+import json+import os+import sys+import urllib.request++from run_bare_llm_ablation import (+ AXIOM_TYPES, MAX_TOKENS, ONTOLOGY_NAMES, load_gt, score, extract_json,+)++SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))+ONT_DIR = os.path.join(SCRIPT_DIR, "data", "ontoaxiom", "ontologies")++# Roughly cap by file size (bytes) to stay within a local model's context.+DEFAULT_MAX_BYTES = 160_000++PROMPT_TEMPLATE = """You are being tested on axiom identification. Below is the FULL source of an ontology in Turtle (RDF/OWL). Read it and extract the declared axiom pairs.++ONTOLOGY: {ontology_name}++--- BEGIN ONTOLOGY (Turtle) ---+{ttl}+--- END ONTOLOGY ---++Return ONLY a single JSON object with these keys (use the local names of classes/properties, not full IRIs):+- "subclassof": [[sub, super], ...]+- "disjoint": [[class1, class2], ...]+- "domain": [[property, domain_class], ...]+- "range": [[property, range_class], ...]+- "subproperty": [[sub_prop, super_prop], ...]++Output ONLY the JSON object, nothing else."""+++def call_qwen(host, model, ontology, ttl, max_tokens=MAX_TOKENS, temp=0.2):+ prompt = PROMPT_TEMPLATE.format(+ ontology_name=ONTOLOGY_NAMES.get(ontology, ontology), ttl=ttl)+ body = json.dumps({+ "model": model,+ "messages": [{"role": "user", "content": prompt}],+ "max_tokens": max_tokens, "temperature": temp,+ }).encode()+ req = urllib.request.Request(+ host.rstrip("/") + "/v1/chat/completions",+ data=body, headers={"Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=2400) as resp:+ data = json.load(resp)+ choice = data["choices"][0]+ result = extract_json(choice["message"]["content"])+ result["_finish_reason"] = choice.get("finish_reason")+ return result+++def call_claude(model, ontology, ttl, max_tokens=MAX_TOKENS):+ import anthropic+ client = anthropic.Anthropic()+ prompt = PROMPT_TEMPLATE.format(+ ontology_name=ONTOLOGY_NAMES.get(ontology, ontology), ttl=ttl)+ r = client.messages.create(model=model, max_tokens=max_tokens,+ messages=[{"role": "user", "content": prompt}])+ result = extract_json(r.content[0].text)+ result["_finish_reason"] = r.stop_reason+ return result+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--backend", choices=["qwen", "claude"], default="qwen")+ ap.add_argument("--host", default=os.environ.get("QWEN_HOST", "http://localhost:8080"))+ ap.add_argument("--model", default=None)+ ap.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES)+ ap.add_argument("--max-tokens", type=int, default=MAX_TOKENS)+ ap.add_argument("--only", default=None, help="comma-separated ontology subset")+ args = ap.parse_args()++ if args.backend == "qwen":+ model = args.model or "mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bit"+ caller = lambda o, ttl: call_qwen(args.host, model, o, ttl, max_tokens=args.max_tokens)+ else:+ model = args.model or "claude-opus-4-8"+ if not os.environ.get("ANTHROPIC_API_KEY"):+ print("ERROR: Set ANTHROPIC_API_KEY for --backend claude"); sys.exit(1)+ caller = lambda o, ttl: call_claude(model, o, ttl, max_tokens=args.max_tokens)++ ontologies = ["pizza", "foaf", "gufo", "nordstream", "era",+ "goodrelations", "music", "saref", "time"]+ if args.only:+ ontologies = [o.strip() for o in args.only.split(",")]++ flip_types = {"domain", "range"}+ all_scores, all_results, skipped, truncated = {}, {}, [], []++ print("=" * 80)+ print(f"CONDITION D (raw OWL -> LLM, no tools) backend={args.backend} model={model}")+ print(f"max_tokens={args.max_tokens} max_bytes={args.max_bytes}")+ print("=" * 80)++ for onto in ontologies:+ path = os.path.join(ONT_DIR, f"{onto}.ttl")+ if not os.path.exists(path):+ print(f"\n {onto}: skipped (no .ttl)"); continue+ size = os.path.getsize(path)+ if size > args.max_bytes:+ print(f"\n {onto}: SKIPPED ({size} bytes > {args.max_bytes} cap — exceeds model context)")+ skipped.append(onto); continue+ ttl = open(path).read()+ print(f"\n--- {onto.upper()} ({size} bytes) ---")+ try:+ result = caller(onto, ttl)+ except Exception as e:+ print(f" ERROR: {e}")+ all_results[onto] = {"error": str(e)}; continue+ all_results[onto] = result+ if result.get("_finish_reason") == "length" or result.get("_salvaged"):+ truncated.append(onto)+ print(f" !! TRUNCATED at max_tokens={args.max_tokens}"+ f"{' — scored from salvaged prefix' if result.get('_salvaged') else ''}")+ for ax in AXIOM_TYPES:+ gt = load_gt(onto, ax)+ pred = result.get(ax, []) if isinstance(result, dict) else []+ s = score(pred, gt, try_flip=(ax in flip_types))+ all_scores[f"{onto}_{ax}"] = s+ print(f" {ax:<15} P={s['precision']:.3f} R={s['recall']:.3f} F1={s['f1']:.3f} (tp={s['tp']}/{s['gt_size']})")++ print(f"\n{'=' * 80}\nAGGREGATE\n{'=' * 80}")+ all_f1 = [s["f1"] for s in all_scores.values()]+ overall = sum(all_f1) / len(all_f1) if all_f1 else 0+ scored = sorted({k.rsplit('_', 1)[0] for k in all_scores})+ failed = sorted(o for o, r in all_results.items() if isinstance(r, dict) and "error" in r)+ print(f" OVERALL avg F1 (condition D, {args.backend}) = {overall:.3f} over {len(scored)} ontologies")+ print(f" Claude condition A (name lists) = 0.431")+ print(f" Claude condition D (raw OWL) = 0.323 <- the 'surprising' number")+ if skipped:+ print(f" Skipped (too large for context): {', '.join(skipped)}")+ if truncated:+ print(f" TRUNCATED (salvaged prefix, recall is a lower bound): {', '.join(truncated)}")+ if failed:+ print(f" FAILED (excluded from the average): {', '.join(failed)}")+ print("\n NOTE: this average covers a different ontology set than condition A.")+ print(" Compare A vs D only on their common subset — see compare_conditions.py")++ tag = args.backend+ out_path = os.path.join(SCRIPT_DIR, "data", "results", f"oo_conditionD_{tag}_results.json")+ os.makedirs(os.path.dirname(out_path), exist_ok=True)+ with open(out_path, "w") as f:+ json.dump({"method": "raw_owl_no_tools", "backend": args.backend, "model": model,+ "input": "full Turtle source of the ontology",+ "max_tokens": args.max_tokens, "max_bytes": args.max_bytes,+ "scores": all_scores, "overall_f1": overall,+ "ontologies_scored": scored,+ "skipped_too_large": skipped, "truncated": truncated, "failed": failed,+ "predictions": {k: (v if isinstance(v, dict) else {}) for k, v in all_results.items()},+ }, f, indent=2)+ print(f"\nResults saved to {out_path}")+++if __name__ == "__main__":+ main()