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
merge: a second reasoner in Python, model certificates, and one decision record instead of two
FABIOTESS393421b09651
diff --cc CHANGELOG.mdindex 72fc5cc6,824c0676..7346692d--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -5,71 -5,64 +5,129 @@@ All notable changes to Open Ontologies## [Unreleased]### Added+- **The refutation checker has a producer.** `lean/OOCert/Refute.lean` has+ checked refutations since it landed and nothing in `src/` could write one: a+ checker with no producer, which is the same shape of defect as a gate that+ cannot fail. `reason --certificate DIR` (and `onto_reason` with+ `certificate_dir`) now looks for a contradiction in the closure the fixpoint+ reached and writes `refutation.tsv` beside `asserted.tsv` and+ `derivations.tsv`, in the `oo-refute/1` format, with the minimal derivation+ prefix that reached the clash. `lake exe oo-refute check` accepts it and+ `oo-refute guard` refuses the derivation certificate over the same graph,+ which is what `OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`+ says to do.+- **Ten of the seventeen OWL 2 RL rules that conclude `false` are detected, and+ exactly one is certifiable.** `cax-dw`, `cls-com`, `cls-nothing2`,+ `cls-maxc1`, `eq-diff1`, `prp-irp`, `prp-asyp`, `prp-pdw`, `prp-npa1` and+ `prp-npa2` are looked for after the fixpoint. Only `cax-dw` gets a refutation+ file, because `OOCert.RefuteConditions` carries a semantic condition for that+ rule alone and `oo-refute` refuses a refutation naming any other with exit 2.+ The other nine report `clash_found_by_this_engine` and write nothing, and the+ seven not looked for at all (`cax-adc`, `prp-adp`, `eq-diff2`, `eq-diff3`,+ `cls-maxqc1`, `cls-maxqc2`, `dt-not-type`) are listed in the response with the+ reason, so a clean run is never read as a consistency result.+- **The two verdicts are kept apart by a test.** `clash_found_by_this_engine` is+ the engine's word and `unsatisfiable_under_disjointness` is what `oo-refute`+ prints for an ACCEPTED refutation.+ `tests/lean_refutation_producer_test.rs::the_engine_never_states_the_checkers_verdict`+ walks every string in the response and fails if the engine ever states the+ checker's verdict or names its soundness theorem, on the pattern+ `a_user_rule_never_earns_the_absolute_verdict` set for the Horn layer.+ `a_consistent_ontology_is_not_refuted` is the test that matters most: no+ refutation is produced for a consistent ontology and a hand-written one over+ it is rejected.+- **The limit is stated and computed, not papered over.** `cax-dw` needs an+ INDIVIDUAL in two disjoint classes, so a TBox unsatisfiable with no individual+ asserted is invisible to the rule-based route.+ `the_tbox_only_case_is_invisible_here_and_the_tableau_sees_it` runs one+ ontology through both paths: `owl-rl` finds nothing and `owl-dl` reports the+ unsatisfiable class. No refutation is emitted from the tableau, and the+ obstruction is written down: `oo-refute/1` can express one contradiction,+ `cax-dw`, over triples the forward-chaining prefix can reach, and a clash+ reached through `∃`/`∀` expansion or a cardinality bound has no form in it.+ Widening that is a change to `lean/`.+- **The trusted computing base of the certificate layer is written down and+ property-tested.** `docs/trusted-computing-base.md` enumerates, as twenty-nine+ checkable properties, everything `lean/` assumes about the Rust: that+ `asserted.tsv` is the graph the engine reasoned over with nothing dropped and+ nothing added, that every emitted step is a step the engine took, that the+ interner round-trips, that the rule table the certificate is checked against+ is the table that was evaluated, and that no term can carry the field or+ record separator of a format that has no escaping layer of its own.+ `tests/certificate_boundary_proptest.rs` property-tests them with generators+ built to forge a derivation step: literals holding tabs, newlines, carriage+ returns, quotes and backslashes, a literal spelled exactly like an IRI, a+ literal spelled exactly like a whole extra TSV line, combining characters+ against their precomposed form, percent-encoded separators inside IRIs, the+ empty graph. `proptest` is a DEV-dependency; the shipped binary's dependency+ surface is unchanged. Three Kani harnesses in `src/reason.rs` (`make verify`)+ prove the serialisation properties over every byte pattern at a fixed term+ length rather than over a sample; the bound is stated on each harness, along+ with the two formulations that made CBMC measure the wrong function. A fourth,+ over `parse_pat`, does NOT terminate (no verdict at 14 minutes and 9.5GB,+ because `anyhow`'s error formatting is flattened whether or not the refusal+ paths are reachable); it is excluded from `make verify`, carries its+ measurements, and the property is sampled instead. The first property-test run+ found the `rdfs7` defect below, and measuring its reach found the `cls-avf`+ one.+ - **The SAT/SMT family, and the asymmetry that makes it worth building.** A+ refutation cannot be replayed in core Lean, so decision 0005 rules a prover's+ verdict an oracle opinion for ever. A MODEL is the opposite: a finite object,+ decidable to check, and `lean/Fol/` holds a verified evaluator for it. So the+ SATISFIABILITY direction is CERTIFIED while the refutation direction stays an+ oracle, and the two never share a word.++ `fol --format smtlib|ladr` are a third and fourth printer over the same+ `FolProblem` the TPTP and CLIF printers walk, never a second translation;+ every run also writes `problem.tsv`, the format `oo-folmodel` reads, with a+ digest the Lean recomputes. `fol-model` (also `onto_fol_model` and batch+ `fol-model`) drives the whole loop: export, run Z3 or Mace4, read the+ structure back, hand it to the verified checker, and report five fields that+ are never collapsed — `solver_verdict`, `encoding`, `checker_exit`, `verdict`+ and `owl_reading`. Only `model_checked` rests on a theorem+ (`Fol.satisfiable_of_check`), and it requires `checker_exit: 0`. An exhausted+ BOUNDED search is `no_model_up_to_size_k` and is not unsatisfiability:+ `∀x∃y (r(x,y) ∧ x≠y)` is unsat at carrier 1 and sat at carrier 2.+ `unsatisfiable_oracle` may come only from a run with no cardinality+ constraint. With a goal, a checked countermodel carries+ `not_entailed_under_unproved_translation` — `Fol.not_entails_of_check`, the+ sentence no prover can produce, weakened by the two things this layer does+ not prove.++ A solver answering `sat` whose model the checker REJECTS is a STOP_THE_LINE+ disagreement with its own block, counted in the summary and exiting non-zero,+ the way `tools/shacl_differential.py` treats a FALSE_CLEAN. It is never+ `rejected` as though the ontology were at fault and never `model_checked`.++ Mace4 is here because the dead toolchain has a live half: Prover9's+ refutations are uncheckable, and Mace4 is a finite model finder whose output+ is exactly what this layer certifies. Its symbols are MANGLED, because LADR+ reads a name beginning with `u`, `v`, `w`, `x`, `y` or `z` as a VARIABLE —+ measured on LADR 2009-11A, `p0(w0). -p0(k0).` is echoed as `p0(x).` and the+ run reports `exit (exhausted)` with no error at all.++ ### Fixed+ - **An assertion on a punned entity was dropped from the first-order export+ SILENTLY, and the report said the axiom set was not weakened.** OWL 2 DL lets+ one IRI be a class and an individual at once; `OwlLean/Syntax.lean` does not,+ so the assertion is correctly outside the fragment — but+ `count_out_of_fragment` knew six named OWL constructs and nothing about+ punning, so `exports_a_weaker_axiom_set` was `false` over an export that was+ weaker than the graph. Found by the new model-certificate pipeline, which+ returned machine-checked countermodels for five of the nine triples the+ OWL-RL reasoner derives on+ `case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl`, where+ `bf:Hanging` is an `owl:Class` that also carries `bf:hasSeverity+ bf:HighSeverity`. Now counted as `assertion on a punned entity` with its+ reason; the reading itself is unchanged.+ - **A stop-the-line disagreement did not fail a `batch` run.** `src/batch.rs`+ decided the exit code from the presence of an `"error"` key, and a+ stop-the-line is not an error: the command ran and answered. Batch is the+ mode every tool in `tools/` uses, so in the one place the gate has to bite it+ did not. It now also reads the `stop_the_line` count, keyed on the field+ rather than on the command name.++ ### Added- **First-order export, over the translation a machine-checked adequacy theoremis about.** `fol --out DIR --format tptp|clif` (also `onto_fol_export` andbatch `fol`) writes the loaded ontology as TPTP FOF or as ISO/IEC 24707diff --cc README.mdindex cf69af04,98f91e46..7c1336c7--- a/README.md+++ b/README.md@@@ -29,46 -27,72 +29,47 @@@<strong>English</strong> · <a href="README.zh-CN.md">简体中文</a></p>-<p align="center">- <a href="#quick-start-mcp--cli">Quick Start</a> ·- <a href="#studio-desktop-app">Studio</a> ·- <a href="#benchmarks">Benchmarks</a> ·- <a href="#ies-support">IES</a> ·- <a href="#tools">Tools</a> ·- <a href="#extending-open-ontologies">Extending</a> ·- <a href="#architecture">Architecture</a> ·- <a href="#documentation">Docs</a>-</p>-------Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **109 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, alongside a three-layer Dynamics → Causal → Planner architecture, a marketplace of 33 standard ontologies, clinical crosswalks, semantic embeddings, and a lineage audit trail. A default build advertises all 109 tools. Eight of them need an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`. The published binaries and the GHCR image are built with the default feature set, so they do not carry those eight. Build from source with `cargo build --release --features embeddings,plugins,sql` to get them.--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.--No JVM. No Protégé.-----## What's New (three-layer architecture + 13 new primitives)--The full **Dynamics → Causal → Planner** stack plus 13 new primitives. 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.--### Three-layer architecture--| Layer | What it ships |-|---|---|-| **Dynamics** | `ActionSchema` + 4 MCP tools: `onto_action_register` / `_applicable` / `_apply` / `_list`. Concurrent atomic ticks, static causal laws (invariants), default-value laws, ramification via OWL-RL closure, non-deterministic outcomes with reproducible seed. |-| **Causal** | `onto_certify_action` with optional PyWhy backdoor identification (opt-in via `causal-pywhy` feature). Structural-proxy default + do-calculus opt-in + graceful fallback. |-| **Planner** | `onto_plan_compile_pddl` + `onto_plan_classical` (Fast Downward subprocess) + `onto_plan_validate` (sandbox-simulate). Solver stays client-side; server compiles + validates. |--### 13 new primitives+Ask a reasoner why it reached a conclusion and it will usually tell you to trust it.-- **`onto_owl_shacl_coevolve_check`** + **`onto_owl_shacl_coevolve_incremental`**, SHACL validation against the OWL-RL closure, with dependency-graph routing so only shapes touching changed IRIs revalidate.-- **`onto_segment_retrieve`**, TBox-slice retrieval for ontology-grounded RAG.-- **`onto_extract_scaffold`** + **`onto_extract_validate`**, schema-guided structured extraction with typed datatype validation + conformance scoring.-- **`onto_cq_run`** + **`onto_verify_cq`** + **`onto_cq_verdicts_list`**, competency-question runner with pitfall hints + LLM-judgement loop.-- **`onto_classify_el`**, OWL-EL classification (transitive subsumption table, trivial pairs excluded).-- **`onto_eval_alignment`**, P/R/F1 over reference + computed alignment sets.-- **`onto_shape_combinatorics`** + **`onto_shape_induce`**, property-combination lattice + data-driven SHACL shape induction with support × confidence ranking.-- **`borderline_partition`** + **`borderline_record_verdict`**, generalised two-threshold review loop for any candidate set.-- **`onto_align_fuzzy`**, embedding-free fuzzy-logic adjudication with 10-rule Mamdani inference; HNSW is demoted to a candidate generator.-- **`onto_align_flora`**, end-to-end alignment pipeline pairing the signal extractor to the fuzzy adjudicator.-- **`onto_policy_register`** + **`onto_policy_list`** + **`onto_policy_check`**, authorisation gate that composes with `onto_certify_action` (Causal = risk; policy = authorisation).-- **`eval_rag`** + **`eval_rag_mmrag`**, Hit@k / MRR / faithfulness / token-Jaccard / ROUGE-1 scoring for retriever pipelines, with a dataset adapter.-- **`graph_projection_lossy_check`**, the auditor that pairs with `onto_segment_retrieve`.+This one hands you the working. An inference comes back with a derivation certificate. A+satisfiable ontology comes back with a model. An inconsistent one comes back with a refutation.+Each is replayed by a small checker written in Lean 4, in core Lean with no Mathlib, whose+theorems say the conclusion holds in **every** model of what you asserted.-### Validating end-to-end+You do not have to trust this engine. You can check what it did.```bash-cargo run --example three_layer_pipeline+open-ontologies reason --profile owl-rl --certificate ./cert+cd lean && lake exe oo-cert ../cert/asserted.tsv ../cert/derivations.tsv+# {"ok":true,"verdict":"entailed","theorem":"OOCert.certificate_sound"}```-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.+## What is actually proved-Zero new external Rust dependencies; everything optional gates behind Cargo features. The default build compiles and runs 930 tests, out of 1,061 in the repository; the remaining 131 are gated behind optional Cargo features; `cargo clippy --lib --tests --examples -- -D warnings` clean across both default and `causal-pywhy` configurations.+| You ask | You get back | Checked against |+| --- | --- | --- |+| Reason over OWL | A derivation certificate | `OOCert.certificate_sound` |+| Reason with rules you wrote | A certificate, and a different verdict word | `OOCert.horn_certificate_sound` |+| Is this satisfiable | A finite model | `Dl.satisfiable_of_checkModel` |++| Is a solver's model real | The model, replayed | `Fol.satisfiable_of_check` |+| Is this inconsistent | A refutation | `OOCert.refutation_sound` |+| Does this data fit the shapes | A validation report | `Shacl.validate_spec` |----+The discipline matters more than the machinery, and it runs through all of it.-## Quick Start (MCP / CLI)+A rule **you** supplied is an assumption the certificate carries, never a fact it establishes, so+it earns `entailed_under_supplied_rules` and never `entailed`. A model a solver hands back can be+checked and becomes a certificate; a refutation cannot be replayed in core Lean and stays an+oracle opinion. The two never share a word. Where something is measured rather than proved, the+documentation says measured, and [what the proofs assume about the Rust](docs/trusted-computing-base.md)+is written down rather than left implied.-### Install+The reasoning behind each of those rules is in [docs/decisions/](docs/decisions/), one file per+rule, each naming the failure it exists to prevent.-**Pre-built binaries:**+## Install```bash# macOS (Apple Silicon)@@@ -109,20 -182,929 +110,24 @@@ Add to `~/.claude/settings.json` for Cl}```-</details>--<details>-<summary><strong>Docker</strong></summary>--```json-{- "mcpServers": {- "open-ontologies": {- "command": "docker",- "args": ["run", "-i", "--rm", "ghcr.io/fabio-rovai/open-ontologies", "serve"]- }- }-}-```--</details>--<details>-<summary><strong>Obsidian</strong></summary>--The [Open Ontologies plugin for Obsidian](https://github.com/fabio-rovai/obsidian-open-ontologies) runs this engine as a managed sidecar inside Obsidian: ontology tree, SPARQL console, validation panel, validate-on-save for Turtle files, and a vault-to-RDF mapper so your notes become a graph the reasoners can work on. It also exposes the engine over MCP on a stable authenticated loopback port, so Claude Code or Claude Desktop can query the reasoned vault graph. Desktop only; the plugin auto-downloads the pinned engine release, or point it at an existing binary.--See [docs/obsidian.md](docs/obsidian.md) for the settings reference and the agent-access model.--</details>--<details>-<summary><strong>HTTP transport (<code>serve-http</code>)</strong></summary>--For clients that speak MCP over HTTP rather than stdio:--```bash-open-ontologies serve-http --host 127.0.0.1 --port 8080-```--| Route | Auth | Purpose |-|---|---|---|-| `/mcp` | bearer, if a token is configured | MCP Streamable HTTP: the `onto_*` tools |-| `/api/stats`, `/api/lineage` | bearer, if a token is configured | read-only introspection |-| `/api/query` | bearer, if a token is configured | SPARQL SELECT |-| `/api/update`, `/api/load`, `/api/load-turtle`, `/api/save` | bearer, if a token is configured | **mutating**: SPARQL UPDATE, and `/load` / `/save` read and write files on the server at a path taken from the request body |-| `/health` | never | liveness probe |--> **The HTTP surface is not read-only.** When no token is configured the bearer-> layer is not installed at all, so every route above, including the ones that-> write to the server's filesystem, is reachable by anyone who can open the-> port. Set a token, or bind to a loopback address, whenever the port is-> reachable by anything other than the local process.--`/health` returns `{"status":"ok","version":"<crate version>"}` and is-deliberately outside the bearer layer, so an orchestrator can probe the process-without holding API credentials. It reports nothing about loaded state, use-`/api/stats` for that.--</details>--### Build your first ontology--```text-Build me a Pizza ontology following the Manchester University tutorial.-Include all 49 toppings, 24 named pizzas, spiciness value partition,-and defined classes (VegetarianPizza, MeatyPizza, SpicyPizza).-Validate it, load it, and show me the stats.-```--Claude generates Turtle, then runs the full pipeline automatically:--`onto_validate` → `onto_load` → `onto_stats` → `onto_reason` → `onto_stats` → `onto_lint` → `onto_enforce` → `onto_query` → `onto_save` → `onto_version`--Every build includes OWL reasoning (materializes inferred triples), design pattern enforcement, and automatic versioning.-------## Studio (Desktop App)--The Studio is a native desktop application that wraps the same engine in a visual environment with no browser and no server to manage. It runs entirely on your machine: the engine sidecar handles RDF/OWL operations while the UI renders the graph in real time.--Think of it as **Protege meets an AI copilot**. Type "build ontology about cats" and watch a 1,400-class ontology appear in the tree: classes, properties, individuals and axioms built automatically across 13 pipeline steps. Click any node to inspect its triples, trace connections via clickable pills, and follow every change through the lineage panel.--### Why virtualized tree (not 3D graph)--Prior to v0.1.12, the Studio used a D3.js horizontal tree and a 3D force-directed graph (Three.js / WebGL). Both worked for small ontologies (~100 classes) but became unusable at IES-level depth: the D3 tree couldn't handle 500+ nodes without layout thrashing, and the 3D graph froze the WebKit webview above 1,000 nodes.--The v2 deep builder changed the equation: a single `/build` command now produces 1,400+ classes. We replaced both views with a virtualized DOM tree: only visible rows exist in the DOM (constant memory regardless of ontology size), with hierarchy connector lines, type-filtered legend, search, breadcrumb navigation, and a connections panel. This handles the full IES Common (511 classes) and deep-built ontologies (1,400+ classes) without lag.--### How it works--The Studio launches three processes that communicate locally:--1. **Tauri 2 shell**, native window (macOS/Linux/Windows) with a WebKit webview-2. **Engine sidecar**: the same Rust binary, running as an HTTP MCP server on `localhost:8137`, configurable with `OPEN_ONTOLOGIES_STUDIO_PORT`-3. **Agent sidecar**: a Node.js process that connects a model to the engine over MCP. The Anthropic path calls the raw `@anthropic-ai/sdk` Messages API, not the Claude Agent SDK.--When you type in the chat panel, your message goes to the Agent sidecar, which sends it to whichever provider is configured. The model decides which `onto_*` tools to call: the engine executes them, and the UI refreshes the graph. The whole loop, from prompt to visual update, takes seconds.--### Install and run--**Prerequisites:** Rust + Cargo · Node.js 18+--```bash-# 1. Build the engine binary (from repo root)-cargo build --release--# 2. Install JS dependencies-cd studio && npm install--# 3. Run-PATH=/opt/homebrew/bin:~/.cargo/bin:$PATH npm run tauri dev-```--The first launch compiles the Tauri shell (~2 min). Subsequent launches start in seconds.--### Features--| 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 through a provider chosen at runtime. The Anthropic path defaults to `claude-opus-5` on the raw `@anthropic-ai/sdk`, and `ONTO_LLM_MODEL` overrides it. Two build modes: `/build` runs an 11-step pipeline producing IES-level ontologies, `/sketch` runs 5 steps for quick prototyping. 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. |--### Keyboard shortcuts--| Shortcut | Action |-| --- | --- |-| `⌘J` | Toggle AI chat panel |-| `⌘I` | Toggle property inspector |-| `⌘S` | Save ontology |-| `F` | Fit graph to viewport (tree view) |-| `R` | Reset zoom (tree view) |-| `Esc` | Deselect node |-| `Shift+click` | Collapse/expand branch (tree view) |-| `Scroll` | Zoom in/out |-| `Click + drag` | Pan |-------## Research Questions--The benchmarks below are not a feature tour. Each one exists to answer a specific question, and the answers include the unflattering ones.--| # | Question | Where it is measured | Answer as measured |-| --- | --- | --- | --- |-| **RQ1** | Does structured tool access give an LLM a materially different mode of access to an ontology than handing it the raw OWL file, or than giving it nothing but class and property names? | [OntoAxiom](#ontoaxiom--llm-axiom-identification), 3 conditions, 2 models | **Partly.** Both beat name lists decisively. Tool extraction and raw-file reading are at **parity** with each other: raw OWL wins the macro average, extraction wins the micro. The tools' remaining advantage is that every pair traces to a query against real triples. |-| **RQ2** | When two evaluation conditions disagree, how much of the gap is the method and how much is the scorer? | [OntoAxiom](#ontoaxiom--llm-axiom-identification), legacy vs unified evaluator | **Enough to invert the finding.** Three scorer asymmetries, all pointing one way, produced a reported result whose sign reverses under a shared evaluator, on both models and under both averages. |-| **RQ3** | In ontology alignment, which carries the result: how the similarity signals are weighted, or the constraint that the matching be 1-to-1? | [OAEI Anatomy](#oaei-ontology-alignment--anatomy-track), 5 weight configurations vs stable-matching ablation | **The constraint, overwhelmingly.** Removing stable matching as the only variable drops F1 from 0.829 to 0.728; the five-weight-configuration spread is 0.0033, and even that overstates it (the zero-structural-signal branch bypasses the weights entirely). |-| **RQ4** | How far does an alignment system get on a biomedical track with **no** domain background knowledge (no UMLS, no BioPortal, no LLM oracle)? | [OAEI Anatomy](#oaei-ontology-alignment--anatomy-track) and [Conference](#oaei-ontology-alignment--conference-track), full 2025 field | **Not far enough.** 9th of 13 on Anatomy, level with the lightweight lexical matcher and +0.063 F1 over a string-equality baseline. Below every system and both baselines on Conference. Precision is competitive; recall is the failure. |-| **RQ5** | Does a closed-world vocabulary check catch generated terms that open-world SHACL validation silently accepts? | [`onto-correctness-bench`](case-studies/onto-correctness-bench/): 3 vocabularies, 418 fabricated terms, 300 graphs | **Yes, completely.** SHACL returned `conforms=true` on **300/300** graphs containing a fabricated term. The closed-world gate flagged **300/300**, with zero false positives on clean graphs. Open-world semantics treat an undeclared predicate as merely unknown, so SHACL is structurally unable to see it. |-| **RQ6** | Can the SHACL-SPARQL governance rules an ontology ships actually be executed as written at national scale, or does the reference store force a workaround? | [`investment-fund-ontology`](case-studies/investment-fund-ontology/): 1.29M-triple US fund universe, 4 layer-3 rules, rdflib 7.6.0 A/B | **Store-specific.** rdflib finishes the anti-join (0.1s) and nested aggregate (0.8s) but times out (>300s) on both multi-way self-joins: exactly the cross-source reconciliation rules the ontology exists for. This repo's Oxigraph engine runs load + all four rules, unmodified, in 2.1s, reproducing the reference pipeline's published counts (73 / 0 / 214 / 2,148) exactly. The shapes also forced two validator fixes here: `sh:inversePath` support and `sh:severity` reporting. |--| **RQ7** | When the graph is register-scale (276k triples) rather than fund-universe-scale (1.29M), does the reference store still force the set-based workaround, and do the rule counts survive entity resolution? | [`insurance-register-ontology`](case-studies/insurance-register-ontology/): 276,683-triple EEA insurance register, 6 layer-3 rules, rdflib 7.6.0 A/B | **The workaround becomes speed, not survival.** At this scale rdflib completes all six rules (133.2s total, 97s of it in one double anti-join) against 2s to 9s for the Oxigraph engine; nothing times out. Counts match the reference pipeline exactly on R1-R4 (643 / 4 / 118 / 42). R5 falls from 227 to 20 and R6 rises from 283 to 291 because the graph runs the same rule text after entity resolution, which absorbs the legitimate branch shares and attributes 8 more zombie passports via the LEI join; both differences were verified set-based. The shapes forced two more validator fixes: `sh:pattern` and `sh:hasValue`. |-| **RQ8** | When a published standard ships a validator but no RDF binding, does a green SHACL result mean the data is valid, or that nothing was checked? | [`dcat-us-binding`](case-studies/dcat-us-binding/): DCAT-US 3.0, the US federal metadata profile, 115 published examples from its live repository, pySHACL vs this engine | **It means nothing was checked, and the distinction is invisible without reporting reach.** The corpus as published expands to **76 triples, 1 predicate, 0 DCAT**, so the shapes GSA deleted select **0 focus nodes** and return `conforms=True`. Generating a JSON-LD context from the same JSON Schema that already carries the RDF terms (231 of 270 properties) lifts the corpus to **1,510 triples and 228 DCAT statements**, and the *same deleted shapes*, unchanged, then select **228 focus nodes and report 287 violations**. This is why `onto_shacl` reports `focus_nodes` next to the verdict. The run also found two defects here, both since fixed. `sh:class` and `sh:nodeKind` written directly under `sh:property` were not evaluated at all, which made 287 of pySHACL's 316 findings invisible on that run; both are evaluated now, pinned by `tests/shacl_class_constraint_test.rs`. Where the two appear as members of an `sh:or` list, which is how most of these shapes write them: the disjunction is still recorded in `skipped_constraints` and the verdict is null rather than a pass. `sh:datatype` also rejected `"1024"^^xsd:nonNegativeInteger` against `sh:datatype xsd:nonNegativeInteger`; the store does not preserve that datatype IRI, so the constraint is now recorded as unevaluated instead of answered wrongly. The case-study table has not been re-measured since the fixes. |--RQ2 and RQ4 are the ones worth reading if you are deciding whether to trust this repo. Both are negative results about work done here.--## 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.--All conditions below are scored by a **single evaluator** (`benchmark/ontoaxiom/score_all_conditions.py`) with one shared normalizer, and both averages are reported, because the original scripts disagreed on all of that. `macro` = mean of per-(ontology, axiom) F1; `micro` = F1 over pooled TP/FP/FN.--| Approach | Input | macro F1 | micro F1 |-| --- | --- | --- | --- |-| o1 (paper's best) | Name lists |: | 0.197 |-| Bare Claude Opus | Name lists | 0.451 | 0.397 |-| Bare Qwen3-Coder-30B | Name lists | 0.223 | 0.176 |-| Claude Opus, raw OWL file | Full Turtle | **0.768** | 0.686 |-| Qwen3-Coder-30B, raw OWL file | Full Turtle | 0.673 | 0.667 |-| **MCP extraction** | **Full OWL** | 0.713 | **0.717** |--**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). Those two numbers came from scripts that disagreed on three axes: the name-list scorer splits camelCase and the raw-OWL scorer only lowercases; the first reports a **macro** mean and the second a **micro** F1; and they flip pair order on different axiom types. Every one of those differences 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. **0.431 and 0.323 were never the same statistic.**--Rescoring the *same stored predictions* under one evaluator flips the sign on both models and under both averages: Claude 0.451 → **0.768** macro (0.397 → 0.686 micro), Qwen 0.246 → **0.673** macro, winning 33/43 and 33/38 cells respectively. `score_condition_d.py --legacy` reproduces the broken 0.323 exactly, so the bug is demonstrated rather than asserted. The correction moves 0 of 5,083 name-list pairs, so it cannot flatter the baseline, and it still under-credits raw OWL: 51.8% of Claude's pairs are label text no normalizer here can match. Full analysis and reproduction: [`benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md`](benchmark/ontoaxiom/ONTOAXIOM_SHOWDOWN.md).--Corrected, reading the ontology and SPARQL-extracting it are **at parity**, raw OWL wins macro (0.768 vs 0.713), extraction wins micro (0.717 vs 0.686). So 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--One sentence input: *"Build a Pizza ontology following the Manchester tutorial specification."*--| Metric | Reference (Protégé, ~4 hours) | AI-Generated (~5 min) | Coverage |-| --- | --- | --- | --- |-| Classes | 99 | 95 | **96%** |-| Properties | 8 | 8 | **100%** |-| Toppings | 49 | 49 | **100%** |-| Named Pizzas | 24 | 24 | **100%** |--### `/sketch` vs `/build`, Two Build Modes--The Studio provides two build commands for different use cases. Both take the same input, *"build ontology about cats"*, but produce very different results:--| Metric | `/sketch` (3 steps, ~2 min) | `/build` (13 steps, ~15 min) | IES Common (reference) |-| --- | ---: | ---: | ---: |-| Classes | 95 | **1,433** | 511 |-| Object properties | 15 | **218** | 162 |-| Datatype properties | 5 | **101** | 44 |-| Individuals | 3 | **358** | 1 |-| Disjoints | 6 | **60+** |: |-| Max hierarchy depth | 5 | **11** | 8 |-| Build time | ~2 min | ~15 min |: (hand-built) |--**`/sketch`** runs 3 steps: classes + properties in one Turtle block, axioms + individuals, then save. Good for quick domain exploration or demo prototyping. Produces a complete ontology with hierarchy, properties, and individuals, but at a fraction of the depth.--**`/build`** runs a 13-step pipeline within a single persistent Claude session: foundation classes → per-branch deepening (4 passes) → gap filling → object properties (2 batches) → datatype properties → disjoints → individuals → reason → save. Each step focuses on one aspect of the ontology, staying within output token limits while building on the previous step's context. The result exceeds IES Common on every metric.--`/sketch` is comparable to the Pizza benchmark (95 classes, 8 properties). `/build` produces IES-level ontologies, deep enough for production use.--### Mushroom Classification, OWL Reasoning vs Expert Labels--**Dataset:** UCI Mushroom Dataset, 8,124 specimens classified by mycology experts.--| Metric | Result |-| --- | --- |-| Accuracy | **98.33%** |-| Recall (poisonous) | **100%**: zero toxic mushrooms missed |-| False negatives | **0** |-| Classification rules | 6 OWL axioms |--### Ontology Marketplace, 33 Standard Ontologies--The 29 general-purpose marketplace ontologies (the four IES entries are covered separately under [IES Support](#ies-support)) fetched, `owl:imports` resolved, loaded, and reasoned over with both RDFS and OWL-RL profiles. Regenerate with `python3 benchmark/marketplace_benchmark.py`:--| Ontology | Classes | Properties | Triples | + RDFS | + OWL-RL | Fetch | RDFS | OWL-RL |-| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |-| OWL 2 | 29 | 0 | 537 | +230 | +230 | 276ms | 1ms | 1ms |-| RDF Schema | 4 | 0 | 87 | +35 | +35 | 268ms | 0ms | 0ms |-| RDF Concepts | 13 | 0 | 127 | +31 | +31 | 175ms | 0ms | 0ms |-| BFO (ISO 21838) | 35 | 2 | 1,221 | +186 | +186 | 254ms | 2ms | 1ms |-| DOLCE/DUL | 79 | 118 | 1,917 | +666 | +692 | 181ms | 7ms | 8ms |-| Schema.org | 1,032 | 1,674 | 17,949 | +4,082 | **+14,236** | 679ms | 56ms | 136ms |-| FOAF | 15 | 62 | 631 | +4 | +31 | 656ms | 1ms | 1ms |-| SKOS | 5 | 28 | 252 | +55 | +55 | 81ms | 1ms | 1ms |-| Dublin Core Elements | 0 | 15 | 107 | +0 | +0 | 315ms | 1ms | 0ms |-| Dublin Core Terms | 23 | 70 | 700 | +256 | +261 | 129ms | 2ms | 2ms |-| DCAT | 49 | 110 | 2,841 | +223 | +254 | 356ms | 7ms | 8ms |-| VoID | 7 | 27 | 216 | +0 | +0 | 333ms | 0ms | 0ms |-| DOAP | 22 | 45 | 741 | +0 | +0 | 352ms | 1ms | 1ms |-| PROV-O | 31 | 59 | 1,146 | +202 | +203 | 204ms | 3ms | 2ms |-| OWL-Time | 29 | 58 | 1,296 | +165 | +165 | 206ms | 3ms | 2ms |-| W3C Organization | 17 | 38 | 748 | +9 | +21 | 259ms | 2ms | 2ms |-| SSN | 23 | 38 | 1,815 | +84 | +84 | 262ms | 2ms | 2ms |-| SOSA | 17 | 23 | 396 | +0 | +0 | 323ms | 1ms | 1ms |-| GeoSPARQL | 15 | 54 | 796 | +4 | +12 | 227ms | 1ms | 1ms |-| LOCN | 3 | 15 | 206 | +0 | +0 | 363ms | 1ms | 1ms |-| SHACL | 48 | 101 | 1,128 | +268 | +268 | 277ms | 2ms | 2ms |-| vCard | 64 | 84 | 882 | +0 | +46 | 316ms | 1ms | 1ms |-| ODRL | 31 | 58 | 2,157 | +73 | +76 | 212ms | 3ms | 3ms |-| Creative Commons | 21 | 13 | 115 | +0 | +49 | 564ms | 1ms | 1ms |-| SIOC | 17 | 86 | 615 | +0 | +2 | 364ms | 1ms | 1ms |-| ADMS | 8 | 16 | 151 | +0 | +0 | 377ms | 1ms | 1ms |-| GoodRelations | 43 | 102 | 1,834 | +15 | +42 | 303ms | 3ms | 4ms |-| FIBO (metadata) | 0 | 0 | 48 | +0 | +0 | 505ms | 4ms | 4ms |-| QUDT | 99 | 196 | 2,434 | +1,574 | +1,581 | 2,100ms | 50ms | 49ms |-| **Total** | **1,779** | **3,092** | **43,093** | **+8,162** | **+18,560** |: |: |: |--29/29 ontologies loaded, imports resolved, and reasoned. RDFS adds 18% more triples. OWL-RL adds **43%**, transitive/symmetric/inverse properties and equivalentClass expansion discover significantly more implicit knowledge. Schema.org jumps from +4,082 (RDFS) to +14,236 (OWL-RL) inferred triples in 136ms.--Class and property counts are structural, not declaration-only: a term counts if it is typed (`owl:Class`, `rdfs:Class`, `owl:ObjectProperty`, `owl:DatatypeProperty`, `rdf:Property`) **or** used as one (`rdfs:subClassOf`/`subPropertyOf`/`domain`/`range` position). Vocabularies that never issue OWL type declarations, such as Schema.org, are therefore counted rather than reported as empty. Terms in the `rdf:`, `rdfs:` and `owl:` namespaces are excluded so a vocabulary is not credited with the meta-vocabulary it is written in. That exclusion is why OWL 2, RDF Schema and RDF Concepts report **0 properties**: every property they define is, by definition, in an excluded namespace. FIBO's marketplace entry is the metadata module only (48 triples), which declares no terms of its own.--### Compiled Claim Verification (research benchmark, not an exposed tool)--This is a benchmark of the `claimcheck` library module in `src/claimcheck.rs`. No-MCP tool in `src/server.rs` and no CLI subcommand in `src/main.rs` calls it, so it-cannot be reached from the server, the `open-ontologies` binary, or the Docker-image. Its only caller in this repository is the Rust test-`tests/claimcheck_pizza_bench.rs`, which runs after the offline compile step-described below.--The module compiles an ontology **once** (inferred hierarchy plus disjointness,-including pairs derived by sound propagation rules) into per-class token bitsets,-then answers the question "is this set of triples consistent with the ontology?"-with **no reasoning at query time**: two 64-bit ANDs per class pair, with the-witness axiom extracted for the explanation.--Same ontology (canonical `pizza.owl`), same task, same machine, verdicts-cross-checked against HermiT 1.4.3.456:--| Per-claim consistency check | median | p95 | throughput |-| --- | --- | --- | --- |-| HermiT (warm JVM, ontology pre-loaded) | 4,936 µs |: | ~200/s |-| **open-ontologies compiled check** | **0.3 µs** | **0.4 µs** | **3.1M/s (11.2M/s batched)** |--Measured on Apple M3 Max over a rotation of four claims against the compiled-Pizza ontology, so it reports warm-cache per-claim cost rather than the cost of-a varied claim stream. No run artefact is committed. Reproduce by generating-the compiled input from `benchmark/reasoner` with `java -cp ".:lib/*"-CompileOntology /tmp/pizza_real.owl /tmp/pizza_compiled.json`, then running-`cargo test --release --test claimcheck_pizza_bench -- --nocapture`. The test-skips and passes when that input is absent, so a green test run is not-evidence that the number was measured.--Correctness before speed:--- **0 unsound rejections against HermiT** across 78,884 exhaustively-audited- class pairs (13 ontologies) and 793 structurally adversarial claims. The- compiled surface is sound but incomplete, so this measures soundness rather- than full agreement: 23 of the 78,884 pairs are left undecided and routed to- the residual tier. No run artefact is committed, and the ORE 2015 corpus and- reasoner jars are gitignored. Reproduce with `bash- benchmark/reasoner/setup_jars.sh`, then `python- benchmark/layer3-prototype/verify_join_soundness.py <ore2015-dir> 250`.-- **Sound by construction**: a `Rejected` verdict is backed by a derivable- contradiction and names the witnessing axiom. 100% contradiction recall on- both fully-audited ontologies.-- **Explicit incompleteness envelope**: anything the compiled surface cannot- decide returns `Undetermined` and routes to a reasoner-backed residual tier-, it is never guessed.-- Closed-world vocabulary checks catch hallucinated classes/properties that- open-world OWL semantics structurally cannot flag.--Offline compile: one classification pass (about 120 ms for Pizza) via any complete-OWL reasoner. The Rust check needs no JVM, but the compile step that produces its-input does. To run the benchmark from a clean checkout:--```bash-cd benchmark/reasoner-./setup_jars.sh # the jars are gitignored, so fetch them first-javac -cp "lib/*" CompileOntology.java-java -cp ".:lib/*" CompileOntology <pizza.owl> /tmp/pizza_compiled.json-cd ../..-cargo test --release --test claimcheck_pizza_bench -- --nocapture-```--The test reads `/tmp/pizza_compiled.json` and skips when that file is absent, which-is why `cargo test` on CI never exercises it. Its assertions use the-`http://www.co-ode.org/ontologies/pizza/pizza.owl#` namespace, so the ontology-passed to `CompileOntology` must carry those IRIs. The copy at-`benchmark/reference/pizza-reference.owl` is namespaced under-`https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#`-and fails the assertions.--Verification harness for the parity and soundness sweeps:-[benchmark/layer3-prototype/](benchmark/layer3-prototype/).--Design, measurements and envelope: [docs/layer3-compiled-reasoning.md](docs/layer3-compiled-reasoning.md).-Full benchmark methodology: [docs/benchmarks.md](docs/benchmarks.md)--### OAEI Ontology Alignment, Anatomy Track--[OAEI](https://oaei.ontologymatching.org/) is the standard benchmark for ontology alignment systems. The Anatomy track aligns the mouse anatomy ontology (2,744 classes) to the human anatomy fragment of the NCI Thesaurus (3,304 classes) against 1,516 reference mappings.--The comparison below is the **complete** OAEI 2025 Anatomy field, reproduced from Table 9 of the official results paper ([Vol-4144, om2025-oaei-paper0](https://ceur-ws.org/Vol-4144/om2025-oaei-paper0.pdf)), including both baselines. Open Ontologies is inserted at its measured rank. Nothing is filtered.--| System | Precision | Recall | F1 |-| --- | ---: | ---: | ---: |-| Matcha | 0.951 | 0.931 | **0.941** |-| Agent-OM | 0.959 | 0.883 | **0.920** |-| ALIN | 0.942 | 0.884 | **0.912** |-| LogMapLLM | 0.964 | 0.842 | **0.899** |-| LogMap-Bio | 0.885 | 0.911 | **0.898** |-| MDMapper | 0.899 | 0.879 | **0.889** |-| LogMap | 0.917 | 0.848 | **0.881** |-| LogMapKG | 0.917 | 0.848 | **0.881** |-| **Open Ontologies** | **0.960** | **0.730** | **0.829** |-| DRAL-OA | 0.830 | 0.827 | **0.828** |-| LogMapLt | 0.962 | 0.728 | **0.828** |-| *StringEquiv (baseline)* | 0.997 | 0.622 | **0.766** |-| LSMatch | 0.952 | 0.634 | **0.761** |--**Read this honestly.** Open Ontologies ranks **9th of 13** on F1. Its precision (0.960) is third in the field, but its recall (0.730) is second-from-bottom among non-baseline systems, and the resulting F1 sits **level with LogMapLt**, the deliberately lightweight lexical matcher, and 0.112 below the leader. The `StringEquiv` baseline reaches 0.766 by normalised string equality alone, so the margin this system earns over pure string matching is **+0.063 F1**. That is the number to beat, and it is not yet a competitive result.--The gap is recall, and its cause is identifiable: this system carries **no domain background knowledge**. Anatomy is a track where UMLS and BioPortal lookups are what separate the 0.88+ band from the rest, and every system above Open Ontologies in the table either uses biomedical background knowledge, an LLM oracle, or both. Alignment here was run from a build with `--features embeddings`, giving 7 weighted signals (label similarity, property/parent/instance/restriction/neighbourhood overlap, embedding similarity), stable 1-to-1 matching, and a label penalty when no structural evidence is available. A default build drops the embedding signal and runs on the first 6.--The defensible finding from this track is therefore **not** the headline F1. It is the ablation: stable 1-to-1 matching is what makes the difference, and the signal weights are nearly irrelevant once it is applied.--| Configuration | Precision | Recall | F1 |-| --- | ---: | ---: | ---: |-| With stable matching | 0.960 | 0.730 | 0.829 |-| Without stable matching | 0.102 | 0.846 | 0.182 |--Removing stable matching produces 12,557 candidates against a 1,516-mapping reference. See issues [#8](https://github.com/fabio-rovai/open-ontologies/issues/8), [#9](https://github.com/fabio-rovai/open-ontologies/issues/9), [#10](https://github.com/fabio-rovai/open-ontologies/issues/10); background-knowledge integration is the open work.--### OAEI Ontology Alignment, Conference Track--15 of the 21 conference-track pairs, micro-averaged:--| System | Precision | Recall | F1 |-| --- | ---: | ---: | ---: |-| ALIN | 0.62 | 0.68 | **0.65** |-| LogMap | 0.76 | 0.56 | **0.64** |-| Matcha | 0.77 | 0.53 | **0.63** |-| Agent-OM | 0.64 | 0.59 | **0.61** |-| MDMapper | 0.69 | 0.50 | **0.58** |-| *edna (baseline)* | 0.74 | 0.45 | **0.56** |-| LogMapLt | 0.68 | 0.47 | **0.56** |-| LSMatch | 0.83 | 0.41 | **0.55** |-| *StringEquiv (baseline)* | 0.76 | 0.41 | **0.53** |-| **Open Ontologies** | **0.693** | **0.320** | **0.438** |--**Not comparable like-for-like, and worse than it looks.** The OAEI rows are Table 10 of the 2025 results paper, evaluated over all 21 pairs against the `rar2` reference at each system's F1-optimal threshold. The Open Ontologies row covers 15 pairs at a fixed confidence threshold. With that caveat stated, the result is unambiguous: **below every participating system and below both baselines**. Best pairs are `ekaw-iasted` (0.588) and `ekaw-sigkdd` (0.533); worst is `edas-sigkdd` (0.211). Conference is a track where the same recall failure that costs Anatomy its rank costs more, because there is no lexical redundancy to fall back on.-------## IES Support--[IES (Information Exchange Standard)](https://github.com/IES-Org) is the UK National Digital Twin Programme's core ontology framework. It uses a 4D extensionalist (BORO) approach for modelling entities, events, states, and relationships. Open Ontologies supports the **full IES stack**, all three layers, SHACL shapes, and example datasets from the IES-Org GitHub repositories.--### The IES Layers--The marketplace includes all three tiers of the IES framework:--```text-onto_marketplace install ies-top # ToLO — BORO foundations (~22 classes)-onto_marketplace install ies-core # Core — persons, states, events (~131 classes)-onto_marketplace install ies # Common — full ontology (511 classes, 206 properties)-```--### Benchmark--| Metric | IES Common |-| --- | --- |-| Classes | 513 counted structurally, 511 declared with `rdfs:Class` |-| Object properties | 162 |-| Datatype properties | 44 |-| Total properties | 206 |-| Triples loaded | 4,039 |-| + RDFS inferred | **+3,094 (+77%)** |-| RDFS reasoning | 63ms |-| Lint issues | 0 warnings or errors, 19 info-level missing-domain notices |--Measured against the vendored copy at-[case-studies/foundry-owl-crosswalk/vendor/ies-common.ttl](case-studies/foundry-owl-crosswalk/vendor/ies-common.ttl).-Reproduce with `open-ontologies batch` over the lines `clear`, `load-case-studies/foundry-owl-crosswalk/vendor/ies-common.ttl`, `stats`, `reason---profile rdfs`. The class count differs by rule: `onto_stats` counts a term-that is typed as a class or used in a class position, which gives 513, while-the count of explicit `rdfs:Class` declarations is 511. The IES presets are not-part of `benchmark/marketplace_benchmark.py`, so-`benchmark/marketplace_results.json` does not contain this row. Fetch time is-omitted because it measured a network round trip rather than the engine.--IES is the second-largest ontology in the marketplace by class count (after Schema.org). RDFS reasoning produces the richest inference gain of any non-general ontology, State, ClassOfEntity, and Event subclasses all generating deep transitive chains.--### Example Data--Load IES example datasets directly from the official repositories:--```text-onto_pull https://raw.githubusercontent.com/IES-Org/ont-ies/main/docs/examples/sample-data/event-participation.ttl-onto_pull https://raw.githubusercontent.com/IES-Org/ont-ies/main/docs/examples/sample-data/hospital.ttl-onto_pull https://raw.githubusercontent.com/telicent-oss/ies-examples/main/additional_examples/ship_movement.ttl-```--### SHACL Validation--```text-onto_pull https://raw.githubusercontent.com/IES-Org/ont-ies/main/docs/specification/ies-common.shacl-onto_shacl-```--### Data Mapping: EPC → IES--The repo includes a sample of real UK Energy Performance Certificates ([benchmark/epc/epc-sample.csv](benchmark/epc/epc-sample.csv)) with a mapping config that transforms tabular EPC data into IES-shaped RDF:--```text-onto_load benchmark/generated/ies-building-extension.ttl-onto_ingest benchmark/epc/epc-sample.csv --mapping benchmark/epc/epc-ies-mapping.json-onto_reason --profile rdfs-```--This mirrors NDTP's actual pipeline: CSV → IES RDF → validate → reason → query.+Restart, and the `onto_*` tools are available. Cursor, Windsurf, Zed and VS Code are in+[docs/quickstart.md](docs/quickstart.md).-### IES Building Extension, Comparison with NDTP/IRIS+## What is in the box- **111 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify- and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises all 111 tools.-The repo includes an [IES Building Extension](benchmark/generated/ies-building-extension.ttl) built from the UK EPC data schema and building science fundamentals, using IES 4D patterns. It was built independently, without reference to any existing implementation, then compared against the NDTP/IRIS production building ontology used in government data pipelines.--| Metric | NDTP/IRIS (hand-built) | Open Ontologies (AI-built) |-| --- | ---: | ---: |-| **Schema** | | |-| Classes | 244 | 525 |-| Properties | 34 | 104 |-| Triples (raw) | 1,346 | 3,229 |-| Lint issues | 2 | 0 |-| **Reasoning** | | |-| RDFS inferred | 621 | 662 |-| Triples after RDFS | 1,967 | 3,891 |-| Max hierarchy depth | 7 | 10 |-| Avg hierarchy depth | 2.89 | 2.02 |-| **EPC Coverage** | | |-| EPC columns covered | 18/36 (50%) | 36/36 (100%) |-| **4D Pattern** | | |-| Complete triads (Entity+State+ClassOf) | 14 | 129 |-| Enumerated individuals | 2 | 214 |--Built blind from the 105-column EPC schema, SAP methodology, and BORO 4D extensionalism, zero reference to the IRIS implementation. The two ontologies make different trade-offs: IRIS is more tightly curated with higher average hierarchy depth (2.89 vs 2.02), reflecting deliberate grouping by domain experts. Open Ontologies covers more of the EPC data schema and applies the BORO 4D pattern more systematically across the domain.--#### How the hierarchy emerges from building science--The ontology's depth (max 10 levels) is not hand-tuned, it follows the natural classification that building scientists use. The EPC data schema describes heating systems as flat text fields (`"Condensing gas boiler with radiators"`), but the underlying domain has layered structure:--```mermaid-graph TD- HS[Heating System] --> CH[Central Heating]- HS --> NC[Non-Central / Room Heating]-- CH --> WET[Wet Central Heating<br/><i>hydronic distribution</i>]- CH --> WA[Warm Air Central Heating<br/><i>ducted air</i>]- CH --> EC[Electric Central Heating<br/><i>storage / underfloor</i>]-- WET --> BB[Boiler-Based]- WET --> HP[Heat Pump]- WET --> DH[Community / District]-- BB --> CB[Combustion Boiler]- BB --> CHP[Micro-CHP]-- CB --> GAS["Gas boiler"]- CB --> OIL["Oil boiler"]- CB --> LPG["LPG boiler"]- CB --> COND["Condensing boiler"]- CB --> COMBI["Combi boiler"]- CB --> BACK["Back boiler"]-- HP --> ASHP["Air source"]- HP --> GSHP["Ground source"]- HP --> WSHP["Water source"]-- EC --> STOR["Storage heaters"]- EC --> PNL["Panel heaters"]- EC --> UF["Underfloor electric"]-- NC --> FIX[Fixed Room Heater]- NC --> PORT[Portable Heater]-- FIX --> GROOM["Gas room heater"]- FIX --> EROOM["Electric room heater"]- FIX --> SFROOM["Solid fuel room heater"]-- style HS fill:#1a1a2e,color:#fff- style CH fill:#16213e,color:#fff- style NC fill:#16213e,color:#fff- style WET fill:#0f3460,color:#fff- style WA fill:#0f3460,color:#fff- style EC fill:#0f3460,color:#fff- style BB fill:#533483,color:#fff- style HP fill:#533483,color:#fff- style DH fill:#533483,color:#fff- style CB fill:#e94560,color:#fff- style CHP fill:#e94560,color:#fff-```--The same pattern applies to the building fabric, heat transfer physics dictates the grouping:--```mermaid-graph TD- TE[Building Thermal Envelope] --> OP[Opaque Elements<br/><i>conduction-dominated</i>]- TE --> TR[Transparent Elements<br/><i>radiation + conduction</i>]-- OP --> WALL[Walls]- OP --> ROOF[Roofs]- OP --> FLOOR[Floors]-- TR --> WIN[Windows]- TR --> DOOR[Doors]-- WALL --> MAS[Masonry Walls<br/><i>thermal mass</i>]- WALL --> FRM[Framed Walls<br/><i>stud bridges</i>]-- MAS --> CAV["Cavity wall"]- MAS --> SOL["Solid brick"]- MAS --> SND["Sandstone"]- MAS --> GRN["Granite"]- MAS --> COB["Cob"]-- FRM --> TF["Timber frame"]- FRM --> SYS["System-built"]- FRM --> PH["Park home"]-- ROOF --> PIT[Pitched Roof]- ROOF --> FLT[Flat Roof]-- PIT --> COLD["Cold roof<br/><i>insulation at ceiling</i>"]- PIT --> WARM["Warm roof<br/><i>insulation at rafter</i>"]- PIT --> THATCH["Thatched"]-- WIN --> SGL["Single glazed"]- WIN --> DBL["Double glazed"]- WIN --> TPL["Triple glazed"]- WIN --> SEC["Secondary glazing"]-- style TE fill:#1a1a2e,color:#fff- style OP fill:#16213e,color:#fff- style TR fill:#16213e,color:#fff- style WALL fill:#0f3460,color:#fff- style ROOF fill:#0f3460,color:#fff- style FLOOR fill:#0f3460,color:#fff- style WIN fill:#0f3460,color:#fff- style DOOR fill:#0f3460,color:#fff- style MAS fill:#533483,color:#fff- style FRM fill:#533483,color:#fff- style PIT fill:#533483,color:#fff- style FLT fill:#533483,color:#fff-```--Each level in the tree is a real building science distinction, central vs room heating, hydronic vs warm air, combustion vs electric, masonry vs framed, cavity vs solid. An independent building scientist, given the same EPC data values, produces these same intermediate groupings ([verified by clean-room reproduction](docs/ies-ecosystem.md)). RDFS reasoning traverses these chains transitively, which is why a 10-level hierarchy generates 662 inferred triples from 3,229 raw.--### EPC Column Coverage Benchmark--Both ontologies tested against 36 key EPC data columns, can each ontology receive and represent the data from that column?--| Metric | NDTP/IRIS | Open Ontologies |-| --- | ---: | ---: |-| EPC columns covered | 18/36 (50%) | 36/36 (100%) |-| Triples | 1,346 | 3,229 |--Queries derived from published DESNZ/ONS EPC statistical reports, not from either ontology's class structure. Full benchmark: [benchmark/epc/](benchmark/epc/)--Use `onto_align` to map it to other domain ontologies:--```text-onto_load benchmark/generated/ies-building-extension.ttl-onto_align <other-ontology.ttl>-```--### Hierarchy Enforcement, Automated Inference Improvement--The `hierarchy` enforce pack detects flat spots in any ontology and suggests intermediate grouping classes. This is the same process used to deepen the building extension, now codified as a repeatable tool:--```text-onto_load my-ontology.ttl-onto_enforce --pack hierarchy-# → flags classes with >5 direct children-# → reports max depth, avg depth, hierarchy density-```++**112 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify++and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises all 112 tools.+Eight need an optional Cargo feature and return an error without it: four need `embeddings`, two+need `plugins`, two need `postgres` or `duckdb`. The published binaries and the GHCR image are+built with the default feature set, so they do not carry those eight.-Tested on IES Common (511 classes), the tool found 24 flat spots. A clean-room agent, with no prior context, proposed 38 intermediate grouping classes based solely on the domain meaning of the flagged children:++The Python package `open-ontologies-lite` now reasons as well, in pure Python with no Rust++toolchain, and its certificates are checked by the same Lean binaries. It is a second engine, and++being untrusted costs nothing: the warrant was never in the engine.+-```mermaid-graph LR- subgraph Before["IES Common — before"]- EP1[EventParticipant] --> P1["Prosecutor"]- EP1 --> P2["Observer"]- EP1 --> P3["Driver"]- EP1 --> P4["Supplier"]- EP1 --> P5["WeaponLocation"]- EP1 --> P6["...52 direct children"]- end-- subgraph After["IES Common — after hierarchy enforce"]- EP2[EventParticipant] --> R[RoleInEvent]- EP2 --> L[LocationInEvent]- EP2 --> A[AssetInEvent]- R --> LR2[LegalRole]- R --> IR[InvestigativeRole]- R --> CR[CommercialRole]- LR2 --> Q1["Prosecutor"]- LR2 --> Q2["Signatory"]- IR --> Q3["Observer"]- IR --> Q4["Investigator"]- CR --> Q5["Supplier"]- CR --> Q6["Negotiator"]- L --> Q7["WeaponLocation"]- L --> Q8["TargetLocation"]- A --> Q9["VehicleUsed"]- end-- style EP1 fill:#e94560,color:#fff- style EP2 fill:#1a1a2e,color:#fff- style R fill:#16213e,color:#fff- style L fill:#16213e,color:#fff- style A fill:#16213e,color:#fff- style LR2 fill:#0f3460,color:#fff- style IR fill:#0f3460,color:#fff- style CR fill:#0f3460,color:#fff-```--| Metric | Before | After | Change |-| --- | ---: | ---: | ---: |-| Classes | 511 | 549 | +38 |-| RDFS inferred | 3,094 | 3,422 | **+328 (+10.6%)** |--The 3,094 baseline is reproducible from the vendored ontology. The 549-class-extended version is not committed, so the 3,422 figure and the delta cannot be-rechecked from this repository. Commit the extended Turtle file, or state the-before figure alone.--The same tool, applied to any ontology, produces the same kind of improvement. The intermediate classes emerge from domain knowledge, not from reference to any other implementation.--### Further Reading--| Topic | Link |-| --- | --- |-| IES Ecosystem Demo | [docs/ies-ecosystem.md](docs/ies-ecosystem.md) |-| SPARQL Examples | [docs/ies-examples.md](docs/ies-examples.md) |-| Building Alignment | [docs/ies-alignment.md](docs/ies-alignment.md) |-------## Tools--109 tools organized by function, available as MCP tools (prefixed `onto_`) and CLI subcommands. A default build advertises all 109. Eight require an optional Cargo feature at call time: `embed`, `search`, `similarity` and `hnsw_build` need `embeddings`; `plugin_list` and `plugin_call` need `plugins`; `import-schema` and `sql-ingest` need `postgres` or `duckdb`.--| Category | Tools | Purpose |-| --- | --- | --- |-| **Core** | `validate` `load` `save` `clear` `stats` `query` `diff` `lint` `convert` `status` | RDF/OWL validation, querying, and management |-| **Repository** | `repo_list` `repo_load` | Browse and load ontologies from configured `[general] ontology_dirs` directories |-| **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 33 curated W3C/ISO/industry ontologies + open [community packs](community/README.md) |-| **Plugins** | `plugin_list` `plugin_call` | Discover and invoke sandboxed community WASM plugins (`--features plugins`, [details](docs/plugins.md)) |-| **Remote** | `pull` `push` `import` | Fetch/push ontologies, resolve owl:imports |-| **Schema** | `import-schema` `sql-ingest` | Postgres + DuckDB → OWL + SQL → RDF ingest (`--features sql`, [details](docs/data-pipeline.md)) |-| **Data** | `map` `ingest` `shacl` `shacl_check` `vocab_check` `reason` `extend` | Structured data → RDF pipeline; `vocab_check` = closed-world check that generated data uses only ontology-declared terms (catches what open-world SHACL misses) |-| **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` `align_fuzzy` `align_flora` | Cross-ontology class matching with self-calibrating weights + fuzzy-logic adjudication and end-to-end signal-driven pipeline. Without `--features embeddings` these run on 6 signals instead of 7 and cannot match across languages ([details](docs/alignment.md)) |-| **HNSW** | `hnsw_build` | Persisted HNSW indices (cosine + Poincaré) over class embeddings (`--features 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 (`--features embeddings`, [details](docs/embeddings.md)) |-| **Reasoning** | `reason` `dl_explain` `dl_check` `classify_el` | Native SHIQ tableaux, no nominals, plus OWL-EL classification |-| **Dynamics** | `action_register` `action_applicable` `action_apply` `action_list` `action_apply_concurrent` `invariant_register` `invariant_list` `invariant_remove` `invariant_check` `default_register` `default_apply` | Action schemas + concurrent atomic ticks + static causal laws + default values |-| **Causal** | `certify_action` | Four-verdict causal certificate (EXECUTE / REJECT / EXPERIMENT / ABSTAIN); optional `causal-pywhy` feature enables backdoor identification |-| **Planner** | `plan_compile_pddl` `plan_classical` `plan_validate` | Compile + validate on the server; solver (Fast Downward) is a client-side subprocess |-| **Governance** | `policy_register` `policy_list` `policy_check` | Authorisation rules; composes with `certify_action` |-| **RAG** | `segment_retrieve` `graph_projection_lossy_check` | TBox-slice retrieval + projection-loss auditor |-| **Extraction** | `extract_scaffold` `extract_validate` | Schema-guided structured-extraction prompt + validator |-| **CQs** | `cq_run` `verify_cq` `cq_verdicts_list` | Competency-question runner with pitfall hints + judgement loop |-| **Shape induction** | `shape_combinatorics` `shape_induce` | Property-combination lattice + data-driven SHACL induction |-| **Borderline loop** | `borderline_partition` `borderline_record_verdict` | Generalised two-threshold review pattern for any candidate set |-| **SQL sync** | `sql_sync_state` `sql_sync_reset` `sql_sync_states_list` | CDC watermark tracking for incremental SQL ingest |-| **Evaluation** | `eval_alignment` `eval_rag` `eval_rag_mmrag` | Alignment P/R/F1 + RAG Hit@k / MRR / faithfulness + dataset adapter |-------## Extending Open Ontologies--Four extension surfaces, in increasing order of coupling, full map in [ECOSYSTEM.md](ECOSYSTEM.md):--| Surface | Contribution is | How |-| ------- | --------------- | --- |-| **[Community packs](community/README.md)** | Data: an ontology manifest in an open registry, installable via `onto_marketplace` the moment the PR merges (no release) | PR to [`community/registry.json`](community/registry.json) |-| **[Community skills](skills/community/)** | Markdown: workflow recipes teaching agents to chain `onto_*` tools | PR a `SKILL.md` directory |-| **[Companion servers](docs/companion-servers.md)** | An independent MCP server composing with this one in-session (lineage webhook, pack interchange, SPARQL endpoints): [OpenCheir](https://github.com/fabio-rovai/opencheir) is the reference | Follow the five-rule contract, PR an [ECOSYSTEM.md](ECOSYSTEM.md) row |-| **[WASM plugins](docs/plugins.md)** | Code: sandboxed wasm32 tools run in-process with fuel metering, no imports, no IO, per-call capability grants | Implement ABI v1 (reference: [`examples/plugins/`](examples/plugins/)) |--Everything holds the MCP-native convention: extensions provide validation and scaffolding; the connected LLM does the intelligence.-------## Architecture--### Engine--```mermaid-flowchart TD- subgraph Clients["Clients"]- Claude["Claude / LLM\nMCP stdio"]- CLI["CLI\nonto_* subcommands"]- Studio["Studio\nHTTP REST"]- end-- subgraph Server["Open Ontologies Server"]- direction TB-- subgraph Transport["Transport Layer"]- MCP_HTTP["MCP Streamable HTTP\n/mcp"]- REST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]- end-- subgraph ToolGroups["109 Tools"]- direction LR- Core["Core\nvalidate · load · save · clear\nstats · query · diff · lint\nconvert · status"]- DataPipe["Data Pipeline\nmap · ingest · shacl\nreason · extend · import-schema"]- Lifecycle["Lifecycle\nplan · apply · lock · drift\nenforce · monitor · lineage"]- Advanced["Alignment + Clinical\nalign · crosswalk · enrich\nenrich · embed · search · similarity\ndl_explain · dl_check"]- Version["Versioning\nversion · history · rollback"]- end-- subgraph Core2["Core Engine"]- GraphStore["Oxigraph Triple Store\nRDF/OWL in-memory\nSPARQL 1.1"]- SQLite["SQLite\nlineage events\nversion snapshots\nlint/enforce feedback\nembedding vectors"]- Reasoner["DL Reasoner\nSHIQ tableaux\nRDFS · OWL-RL"]- Embedder["Embedding Engine\ntract-onnx (ONNX)\ntext + Poincaré structural"]- end- end-- subgraph External["External Sources"]- PG["PostgreSQL\nschema import"]- SPARQL["Remote SPARQL\nendpoints"]- OWL["OWL URLs\nowl:imports chains"]- Parquet["Parquet / Arrow\nclinical crosswalks\nICD-10 · SNOMED · MeSH"]- Files["Files\nCSV · JSON · XML\nYAML · XLSX · Parquet"]- end-- Claude -->|"MCP stdio"| MCP_HTTP- CLI -->|"subcommands"| MCP_HTTP- Studio -->|"sessionless"| REST-- MCP_HTTP --> ToolGroups- REST --> ToolGroups-- ToolGroups --> GraphStore- ToolGroups --> SQLite- ToolGroups --> Reasoner- ToolGroups --> Embedder-- Reasoner --> GraphStore- Embedder --> SQLite-- DataPipe --> Files- Advanced --> Parquet- Core --> OWL- Core --> SPARQL- DataPipe --> PG-```--### Certified inference--The forward-chaining reasoner (`rdfs`, `owl-rl`, `owl-rl-ext`) can write a-derivation certificate beside its result: `reason --certificate DIR` records-every inferred triple with the rule that produced it and the premises the rule-read. `lean/` holds a checker for that certificate whose soundness is a-machine-checked theorem (`OOCert.certificate_sound`, core Lean, no Mathlib), so-a run whose certificate checks contains only triples entailed by the asserted-graph, whatever this engine did to find them. CI builds the proofs and-certifies every RDF file in this repository, naming with a reason any it cannot-read or that exceeds the size cap. The first thing the checker caught-was in the engine: `cls-svf1` derived the converse of a subclass axiom. Details-in [docs/lean-certificates.md](docs/lean-certificates.md) and-[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).--### Certified satisfiability, and the asymmetry it rests on--A theorem prover's refutation cannot be replayed in core Lean, so-[decision 0005](docs/decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md)-rules its verdict an oracle opinion. A MODEL is the opposite: a finite object,-decidable to check. `fol-model` (also `onto_fol_model`) exports the ontology as-SMT-LIB 2 or LADR, runs Z3 or Mace4, reads the structure back and hands it to a-checker whose soundness is a theorem — `Fol.satisfiable_of_check` — so one-direction of the SAT/SMT family is CERTIFIED while the other stays an oracle,-and the two never share a word. With a goal, a checked countermodel is a-machine-checked NON-ENTAILMENT, the one sentence no prover can produce.--The verdict says what it rests on. `model_checked` requires the checker to have-accepted; an exhausted BOUNDED search is `no_model_up_to_size_k` and is not-unsatisfiability; `unsatisfiable_oracle` can only come from a run with no-cardinality constraint, and can never be more than an opinion. A solver that-answers `sat` whose model the checker rejects is a stop-the-line disagreement-that fails the command. Running it over this repository's own case studies-found an export that was silently weaker than the graph. Details in-[docs/lean-certificates.md](docs/lean-certificates.md) and-[decision 0006](docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md).--### Studio--```mermaid-flowchart TD- subgraph UI["React UI (Vite + Tailwind CSS)"]- Graph["Virtualized Tree\nDOM + virtual scroll"]- Chat["AI Chat Panel\nZustand store"]- Inspector["Property Inspector\nInline SPARQL edit"]- Lineage["Lineage Panel\nAudit trail"]- Save["Named Save\n⌘S → ~/.open-ontologies/"]- end-- subgraph Tauri["Tauri 2 Shell (Rust)"]- IPC["Tauri IPC\ninvoke / event"]- ChatState["ChatState\nstdin/stdout pipe"]- end-- subgraph Engine["Engine Sidecar (Rust / Axum)"]- 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"]- end-- subgraph Agent["Agent Sidecar (Node.js)"]- SDK["Model provider\n@anthropic-ai/sdk or OpenAI-compatible"]- Proto["stdin/stdout JSON protocol"]- end-- Graph -->|"SPARQL SELECT/UPDATE · REST"| REST2- Inspector -->|"SPARQL UPDATE · REST"| REST2- Lineage -->|"GET /api/lineage"| REST2- Save -->|"POST /api/save"| REST2- Chat -->|"invoke send_chat_message"| IPC- IPC --> ChatState- ChatState -->|"stdin { type: chat }"| Proto- Proto --> SDK- SDK -->|"MCP tools/call"| MCP- SDK -->|"stdout { type: text/tool_call/done }"| Proto- Proto -->|"Tauri emit agent-message"| Chat- MCP --> Store- REST2 --> Store- Store --> DB-```--### Design decisions--| Decision | Reason |-| --- | --- |-| UI reads use sessionless REST | No MCP session management needed for SPARQL queries or stats |-| UI writes use REST `/api/update` + `/api/save` | Avoids session lifecycle issues in the Tauri WebKit webview |-| Agent writes go through MCP `tools/call` | The sidecar's own MCP client (`studio/src-tauri/sidecars/agent/mcp.ts`) holds the session, and the model needs the full tool set |-| Shared `Arc<GraphStore>` | All MCP sessions and REST handlers share the same in-memory triple store |-| Agent sidecar over stdin/stdout | Keeps Node.js isolated; Tauri manages the full lifecycle |-------## Stack--| Layer | Tech |-| --- | --- |-| Engine language | Rust (edition 2024): single binary, no JVM |-| Triple store | Oxigraph 0.5, a pure Rust RDF and SPARQL 1.1 engine |-| MCP protocol | rmcp: Streamable HTTP transport |-| State / lineage / feedback | SQLite (rusqlite) |-| Clinical crosswalks | Apache Arrow / Parquet |-| Embeddings runtime | tract-onnx, pure Rust ONNX, behind the `embeddings` Cargo feature and absent from the published binaries |-| Desktop shell | Tauri 2 |-| 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 | Node.js sidecar. `claude-opus-5` on the raw `@anthropic-ai/sdk` when `ANTHROPIC_API_KEY` is set, otherwise a local OpenAI-compatible endpoint (see `studio/src-tauri/sidecars/agent/providers/alias.ts`) |-----+Alongside them, a marketplace of 33 standard ontologies, clinical crosswalks, semantic embeddings,+a lineage audit trail, and a desktop Studio with a virtualized ontology tree, an AI chat panel and+a Protégé-style inspector. No JVM. No Protégé.## Documentationdiff --cc docs/architecture.mdindex ce2fa935,00000000..89884e8emode 100644,000000..100644--- a/docs/architecture.md+++ b/docs/architecture.md@@@ -1,182 -1,0 +1,182 @@@+# Architecture++How the engine is put together: the layers, the tool groups, the data flow and where the+verified checkers sit relative to the untrusted parts.++Extracted from the README on 14 September 2026 so that the README could stay short enough to+read. Nothing here was rewritten in the move.++### Engine++```mermaid+flowchart TD+ subgraph Clients["Clients"]+ Claude["Claude / LLM\nMCP stdio"]+ CLI["CLI\nonto_* subcommands"]+ Studio["Studio\nHTTP REST"]+ end++ subgraph Server["Open Ontologies Server"]+ direction TB++ subgraph Transport["Transport Layer"]+ MCP_HTTP["MCP Streamable HTTP\n/mcp"]+ REST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]+ end+- subgraph ToolGroups["111 Tools"]++ subgraph ToolGroups["112 Tools"]+ direction LR+ Core["Core\nvalidate · load · save · clear\nstats · query · diff · lint\nconvert · status"]+ DataPipe["Data Pipeline\nmap · ingest · shacl\nreason · extend · import-schema"]+ Lifecycle["Lifecycle\nplan · apply · lock · drift\nenforce · monitor · lineage"]+ Advanced["Alignment + Clinical\nalign · crosswalk · enrich\nenrich · embed · search · similarity\ndl_explain · dl_check"]+ Version["Versioning\nversion · history · rollback"]+ end++ subgraph Core2["Core Engine"]+ GraphStore["Oxigraph Triple Store\nRDF/OWL in-memory\nSPARQL 1.1"]+ SQLite["SQLite\nlineage events\nversion snapshots\nlint/enforce feedback\nembedding vectors"]+ Reasoner["DL Reasoner\nSHIQ tableaux\nRDFS · OWL-RL"]+ Embedder["Embedding Engine\ntract-onnx (ONNX)\ntext + Poincaré structural"]+ end+ end++ subgraph External["External Sources"]+ PG["PostgreSQL\nschema import"]+ SPARQL["Remote SPARQL\nendpoints"]+ OWL["OWL URLs\nowl:imports chains"]+ Parquet["Parquet / Arrow\nclinical crosswalks\nICD-10 · SNOMED · MeSH"]+ Files["Files\nCSV · JSON · XML\nYAML · XLSX · Parquet"]+ end++ Claude -->|"MCP stdio"| MCP_HTTP+ CLI -->|"subcommands"| MCP_HTTP+ Studio -->|"sessionless"| REST++ MCP_HTTP --> ToolGroups+ REST --> ToolGroups++ ToolGroups --> GraphStore+ ToolGroups --> SQLite+ ToolGroups --> Reasoner+ ToolGroups --> Embedder++ Reasoner --> GraphStore+ Embedder --> SQLite++ DataPipe --> Files+ Advanced --> Parquet+ Core --> OWL+ Core --> SPARQL+ DataPipe --> PG+```++### Certified inference++The forward-chaining reasoner (`rdfs`, `owl-rl`, `owl-rl-ext`) can write a+derivation certificate beside its result: `reason --certificate DIR` records+every inferred triple with the rule that produced it and the premises the rule+read. `lean/` holds a checker for that certificate whose soundness is a+machine-checked theorem (`OOCert.certificate_sound`, core Lean, no Mathlib), so+a run whose certificate checks contains only triples entailed by the asserted+graph, whatever this engine did to find them. CI builds the proofs and+certifies every RDF file in this repository, naming with a reason any it cannot+read or that exceeds the size cap. The first thing the checker caught+was in the engine: `cls-svf1` derived the converse of a subclass axiom. Details+in [docs/lean-certificates.md](docs/lean-certificates.md) and+[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).++The same run also looks for a contradiction, and writes `refutation.tsv` when it+finds one `oo-refute` can judge. Ten of the seventeen OWL 2 RL rules that+conclude `false` are detected; one of them, `cax-dw`, has a semantic condition+in `lean/` and is the only one a refutation is written for. The other nine are+reported as found by this engine and nothing more, because a file naming a rule+the checker cannot judge would be a certificate-shaped object that certifies+nothing. `cax-dw` needs an individual in two disjoint classes, so a TBox that is+unsatisfiable with no individual asserted is invisible to the rule-based route:+the `owl-dl` tableau sees that case and its answer carries no certificate.+### Rules you wrote++`reason --rules TABLE --certificate DIR` evaluates a rule table you supply and+writes a certificate `lake exe oo-horn check` verifies against+`OOCert.horn_certificate_sound`, one theorem proved for every rule table at+once. `rules-import --from swrl` reads SWRL rules out of a loaded ontology and+`--from rif` reads RIF Core out of its XML syntax, so the table need not be+hand-written.++Only a FRAGMENT of each language is a Horn table over triple patterns. SWRL+built-in atoms, same-individual and different-individual atoms and data ranges+are refused; RIF equality, `External`, `Expr`, `rif:local` constants, list terms+and the presentation syntax are refused. Each refusal is named and counted, and+by default one refusal fails the whole import: a rule set that quietly lost half+its rules still reaches a fixpoint and its certificate still checks green, which+is a sound proof about a rule set nobody wrote.++A rule you supply is an assumption nobody checked, so a certificate over it+earns `entailed_under_supplied_rules` — true in every model of the asserted+graph **that also satisfies your rules** — and never the `entailed` that only+the built-in table earns. Details in+[docs/rule-syntax-front-ends.md](docs/rule-syntax-front-ends.md) and+[decision 0003](docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).+The theorem is conditional, and what it is conditional on is the Rust writing+down the truth: the asserted graph the certificate names, and the steps it+records. That boundary is small, it is the whole trusted base of this layer, and+it is enumerated as twenty-nine checkable properties in+[docs/trusted-computing-base.md](docs/trusted-computing-base.md), with what+checks each and what is still trusted. Read it before relying on a certificate.++### Studio++```mermaid+flowchart TD+ subgraph UI["React UI (Vite + Tailwind CSS)"]+ Graph["Virtualized Tree\nDOM + virtual scroll"]+ Chat["AI Chat Panel\nZustand store"]+ Inspector["Property Inspector\nInline SPARQL edit"]+ Lineage["Lineage Panel\nAudit trail"]+ Save["Named Save\n⌘S → ~/.open-ontologies/"]+ end++ subgraph Tauri["Tauri 2 Shell (Rust)"]+ IPC["Tauri IPC\ninvoke / event"]+ ChatState["ChatState\nstdin/stdout pipe"]+ end++ subgraph Engine["Engine Sidecar (Rust / Axum)"]+ 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"]+ end++ subgraph Agent["Agent Sidecar (Node.js)"]+ SDK["Model provider\n@anthropic-ai/sdk or OpenAI-compatible"]+ Proto["stdin/stdout JSON protocol"]+ end++ Graph -->|"SPARQL SELECT/UPDATE · REST"| REST2+ Inspector -->|"SPARQL UPDATE · REST"| REST2+ Lineage -->|"GET /api/lineage"| REST2+ Save -->|"POST /api/save"| REST2+ Chat -->|"invoke send_chat_message"| IPC+ IPC --> ChatState+ ChatState -->|"stdin { type: chat }"| Proto+ Proto --> SDK+ SDK -->|"MCP tools/call"| MCP+ SDK -->|"stdout { type: text/tool_call/done }"| Proto+ Proto -->|"Tauri emit agent-message"| Chat+ MCP --> Store+ REST2 --> Store+ Store --> DB+```++### Design decisions++| Decision | Reason |+| --- | --- |+| UI reads use sessionless REST | No MCP session management needed for SPARQL queries or stats |+| UI writes use REST `/api/update` + `/api/save` | Avoids session lifecycle issues in the Tauri WebKit webview |+| Agent writes go through MCP `tools/call` | The sidecar's own MCP client (`studio/src-tauri/sidecars/agent/mcp.ts`) holds the session, and the model needs the full tool set |+| Shared `Arc<GraphStore>` | All MCP sessions and REST handlers share the same in-memory triple store |+| Agent sidecar over stdin/stdout | Keeps Node.js isolated; Tauri manages the full lifecycle |+diff --cc docs/decisions/0002-an-inference-carries-a-certificate.mdindex 8c24991d,8c24991d..6ab71465--- a/docs/decisions/0002-an-inference-carries-a-certificate.md+++ b/docs/decisions/0002-an-inference-carries-a-certificate.md@@@ -6,7 -6,7 +6,7 @@@`#guard_msgs` · every shipped ontology certified in CI (`tests/lean_certificate_test.rs`) ·**opt-in, default unchanged** · the `owl-dl` tableaux path refuses the flag rather thanpretending · the SHIQ tableaux reasoner now certifies its POSITIVE answers-- (`Dl.satisfiable_of_checkModel`, decision 0004); its negative answers and the++ (`Dl.satisfiable_of_checkModel`, decision 0006); its negative answers and theparsers remain uncovered- **Written**: 2026-09-13- **Related**: decision 0001 (an inference is not an assertion); issues #131 and #132, fixed thediff --cc docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.mdindex 00000000,438b2e41..70d7148emode 000000,100644..100644--- a/docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md+++ b/docs/decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md@@@ -1,0 -1,301 +1,298 @@@+ # 0006 · A model is a certificate, and a refutation is not++ - **Status**: Implemented, both halves · `lean/Fol/` with `Fol.satisfiable_of_check`,+ `Fol.check_complete` and `Fol.not_entails_of_check` machine-checked, no `sorry`, no+ `native_decide`, no Mathlib · checker `oo-folmodel`, both targets in `defaultTargets` so the CI+ job's bare `lake build` compiles them · Rust half in `src/tptp.rs` (`sym`, `smtlib`, `ladr`,+ `checkfmt`), `src/fol_model.rs` (ingestion, two front ends) and `src/fol_solve.rs` (the+ certifying pipeline), reachable as `fol --format smtlib|ladr`, `fol-model` and `onto_fol_model`,+ with three CI legs over z3 and mace4+ - **Written**: 2026-09-14+ - **Related**: decision 0005 (a prover is an oracle, and a translation is a theorem), which this+ decision is the mirror of; decision 0003 (a rule is data), whose verdict discipline and whose+ sentence about digests are reused verbatim; decision 0002 (an inference carries a certificate)++ ## The problem++ Five automated-reasoning families were the goal. Logic programming is `lean/OOCert/`, description+ logics are `lean/Dl/` and `src/tableaux.rs`, first-order theorem proving is `src/tptp.rs` and+ decision 0005. The SAT and SMT family was entirely absent: no SMT-LIB anywhere in the repository+ and no solver called.++ Decision 0005 settled the hard half of that family before it arrived. A superposition or CDCL(T)+ refutation cannot be replayed in core Lean, so an automated prover's verdict is an oracle opinion+ and never a certificate. Taken at face value that rules the whole family out, and taking it at face+ value would have been wrong.++ ## The asymmetry, which is the whole reason this layer exists++ A refutation and a model are not two answers of the same kind.++ A refutation is a proof object in a calculus this repository does not implement. Checking one needs+ verified unification, a verified ordering, verified redundancy criteria and verified theory+ lemmas. That is a research project, and decision 0005 is right that nothing short of it earns the+ word "certified".++ A model is a finite object. Checking whether a formula holds in a finite structure is decidable,+ the decision procedure is a recursive `Bool`-valued function, and proving it agrees with the+ `Prop`-valued satisfaction relation is an induction over eleven constructors. `lean/Fol/Check.lean`+ is 130 lines of definitions and proof, and `Fol.eval_iff` is the whole of it.++ So one direction of the SAT/SMT family can be CERTIFIED while the other stays an ORACLE, and the+ same is true of every model finder. That includes a dead toolchain's live half: Prover9 is+ unmaintained and its refutations are uncheckable, but Mace4 ships in the same distribution, is a+ finite model finder, and prints exactly the kind of object this layer can certify.++ ## Decisions++ 1. **The satisfiability direction is certified, the refutation direction is not, and they never+ share a word.** `Fol.satisfiable_of_check` turns an accepted structure into `Satisfiable Γ`.+ Nothing in `lean/Fol/` says anything about unsatisfiability in any direction, and the driver's+ own docstring says so in the negative space, in the shape `lean/DlMain.lean` uses.++ 2. **The headline is a NON-ENTAILMENT, because that is the sentence no prover can produce.**+ `Fol.not_entails_of_check` says that a checked model of `¬φ :: Γ` is a machine-checked proof of+ `¬ Entails Γ φ`, under the same `Entails` that `OwlLean.adequacy` is stated about. A prover+ answering "not a theorem" is guessing at worst and reporting a failed search at best. This is+ the one place where the model direction is strictly STRONGER than what an ATP can offer, rather+ than merely different, and it is why the layer is worth building at all.++ 3. **The producer is untrusted by construction.** The checker re-evaluates the original formulas+ against the structure and reads nothing else. It never trusts the solver's clausification, its+ Skolemisation, its preprocessing or its choice of encoding. Mace4 clausifies and Skolemises, so+ its models interpret symbols like `f1(_)` and `c1` that `Fol.FinModel` has no slot for; dropping+ them on the way in is taking the reduct of its structure and needs no lemma here, because the+ checker re-evaluates formulas that cannot mention a symbol the translation never emitted. The+ driver reports the dropped names and their count so the reduct is visible rather than silent.++ 4. **Four verdict words, and the fourth is the one nobody reaches for.** A report carries five+ fields and they are never collapsed:++ ```+ "solver_verdict": "sat" | "unsat" | "unknown" what the oracle said+ "encoding": "unbounded" | "finite(k)" what it was asked+ "checker_exit": 0 | 1 | 2 | null null means never run+ "verdict": "model_checked" CERTIFIED. names Fol.satisfiable_of_check+ | "satisfiable_oracle" sat, no checkable model+ | "no_model_up_to_size_k" bounded search exhausted. NOT unsatisfiability+ | "unsatisfiable_oracle" unsat on the UNBOUNDED encoding. Never more+ | "unknown_oracle" timeout, incomplete, gave up+ "owl_reading": "not_entailed_under_unproved_translation" | null+ ```++ Three rules are mechanical. `model_checked` requires `checker_exit == 0`. `unsatisfiable_oracle`+ may be produced ONLY by a run whose emitted problem carried no cardinality constraint of any+ kind; any bounded run's `unsat` is `no_model_up_to_size_k`. `owl_reading` is non-null only when+ the checker itself reported `goal_negated_present` AND the verdict is `model_checked`, computed+ from what the checker read back rather than from the Rust side's intention.++ `no_model_up_to_size_k` exists because the obvious wiring is wrong and takes ten minutes. A+ finite-domain encoding that returns `unsat` has established that no model of that size exists,+ which is not unsatisfiability and is often not even evidence of it. The formula+ `∀x∃y (r(x,y) ∧ x≠y)` is `unsat` at carrier 1 and `sat` at carrier 2; a driver that mapped the+ first to `unsatisfiable_oracle` would be reporting a falsehood from correct solver output.++ 5. **A solver's `sat` whose model the checker REJECTS is not a statement about the ontology.**+ Z3 can answer `sat` on quantified UF through model-based instantiation with a candidate model+ that `get-value` reports incompletely. The verdict for that is `satisfiable_oracle` with+ `checker_exit: 1` and a `model_not_confirmed` note. It is never `rejected` as though the+ ontology were at fault, and it is never `model_checked`.++ 6. **The coverage gate is about ATTRIBUTION and says so.** `Fol.covers` checks that every symbol+ the problem uses is declared by the model file. Soundness holds without it: `FinModel`'s three+ fields are total, an undeclared symbol is still interpreted, and `check` validates the resulting+ structure from scratch. What the gate buys is that the structure certified is the structure the+ solver described rather than the solver's completed with defaults. It is reported at exit 1 with+ `"reason":"undeclared_symbol"` and `"gate":"attribution"`, it is kept out of `Satisfiable`, out+ of every theorem, and out of the soundness statement. Dressing it up as soundness would be the+ laundering move this repository keeps finding in other people's work and once in its own.++ 7. **The digest binds the two files, and it identifies rather than commits.** `model.tsv` carries a+ digest of the problem the solver was given and the Lean recomputes it from `problem.tsv`. It is+ taken over the canonical re-serialisation of the PARSED formula list, not over the file bytes,+ so labels and spacing cannot forge a match and a relabelled `goal_negated` cannot digest the+ same. FNV-1a 64 is specified in `lean/Fol/Parse.lean` rather than taken from a library, because+ `String.hash` is an opaque extern with no specification a Rust writer could target. It is not a+ cryptographic hash; it exists so two implementations can be compared, not so one can be defended+ against someone who controls the file. That is decision 0003 item 5, in the same words, for the+ same reason.++ 8. **An empty problem is exit 2.** Every structure satisfies the empty formula list, so a+ certificate over one would report `model_checked` and say nothing. An exporter bug that dropped+ every formula would otherwise produce a clean green run, which is the exact shape decision 0005+ item 7 records happening inside this repository already, when the differential exported from a+ reasoned store and every conjecture became trivially entailed.++ 9. **The footprint is pinned at the MEASURED value, not at the habitual one.** Every result in+ `lean/Fol/` is `[propext, Quot.sound]`, and several are `[propext]` or free of axioms entirely.+ `Classical.choice` appears nowhere in the layer. Pinning the `[propext, Classical.choice,+ Quot.sound]` triple that the older layers carry would be looser than the truth and would stop+ catching anything. `lean/Dl/Check.lean` already pins `checkWF_iff` tighter than its neighbours,+ so this is the house habit rather than a new one.++ ## Why `Fol` does not reuse `Dl/Check.lean`++ This looks like duplication and it is not, so the reasons are written down here rather than left+ for someone to re-derive in six months and get wrong.++ 1. `Dl.Sat : Interp → Concept → Name → Prop` evaluates at ONE free variable. First-order+ satisfaction needs an environment `Nat → Dom`. Every clause of `Sat`, `sat` and `sat_iff`+ changes signature.+ 2. `Dl.Sat`'s `.ex r c` quantifies over `I.rext r x`, a successor LIST, not over the carrier.+ Different quantification domain, different recursion, different well-formedness obligation.+ 3. `Dl.Concept` has no equality constructor. `src/tptp.rs` emits `Form::Eq` for `SameAs`,+ `DifferentFrom`, `OneOf` and `HasVal`.+ 4. `Dl.Axiom` is a flat thirteen-constructor enumeration. `tptp::Form` is recursive with `Imp` and+ arbitrary binder nesting, and `Translation::background()` emits shapes with no `Dl.Axiom` at all.+ 5. **Copying `Dl.WellFormed` would be a defect rather than a shortcut.** `Dl` carries `cextInDom`+ and `rextInDom` because `∃R.C` ENUMERATES `rext`, so an out-of-carrier successor would really be+ evaluated. Here every quantifier ranges over the carrier TYPE and atoms are only tested, so+ importing those clauses would make `Fol.check_complete` reject genuine models. The+ well-formedness predicate is not shared; it is different mathematics.+ 6. `Dl.holds_iff` is thirteen axiom cases. The first-order analogue is eleven formula cases with an+ environment threaded through. No case transfers.++ Against that, `lean/Dl/Count.lean`, the 119-line hand-rolled pigeonhole that is the hardest file in+ that directory, has no first-order counterpart at all, because first-order logic has no counting+ constructor. The new library is smaller than the one it does not reuse. What IS reused is the+ shape: the `Interp`-style record, the hash-tables-behind-closures parser idiom, the driver's+ exit-code convention and its explicitly unverified diagnostic pass, the witness file's+ accept/reject/non-triviality triad including its short-bare-names trick, and the `#guard_msgs` plus+ `#print axioms` pinning. `lean/Dl/` is the template, not the library.++ ## What this does not claim++ 1. **Nothing about unsatisfiability, in any direction, ever.**+ 2. **The absence of a finite model implies nothing.** SHIQ lacks the finite model property, so a+ satisfiable ontology can have only infinite models and will never receive a certificate here.+ That is a limitation of the method rather than a defect, and it is the honest counterweight to+ the asymmetry the first section is built on. A bounded search that finds nothing has established+ `no_model_up_to_size_k` and that is all.+ 3. **The OWL-level reading rides on two things this layer does not prove.** `OwlLean.adequacy`+ lives in the sibling project, and the Rust-to-Lean translation correspondence that decision 0005+ item 2 states is pinned by tests and NOT proved. The certified verdict is about the formulas in+ `problem.tsv`; the OWL sentence is strictly weaker and carries its own word,+ `not_entailed_under_unproved_translation`, which must never be shortened to "not entailed".+ 4. **That `Fol.Form`, `Fol.Struc` and `Fol.Entails` are `OwlLean.FOL`'s is a transcription, pinned+ by tests.** It is a far smaller claim than `src/tptp.rs`'s, being about twenty lines of+ inductive types and their semantics rather than a translation, and the two should not be allowed+ to sound equally load-bearing.+ 5. **The parser and the file formats are outside the theorem**, exactly as in `lean/Dl/Parse.lean`.+ A parse error is exit 2 and never a verdict in either direction.+ 6. **`source` and `cardinality_search` are untrusted.** They are what the file claims about its own+ provenance, echoed for a report. Nothing checks them.++ ## Two traps that are already measured, so that nobody has to find them twice++ **A LADR variable letter in the symbol table.** LADR's default convention is that a name beginning+ with `u`, `v`, `w`, `x`, `y` or `z` is a VARIABLE. A mangler that turns an IRI into `w0` therefore+ turns a constant into a universally quantified variable. Measured on this machine with+ LADR 2009-11A: the input `p0(w0). -p0(k0).` is echoed by Mace4 in its own `CLAUSES FOR SEARCH`+ block as++ ```+ formulas(mace4_clauses).+ p0(x).+ -p0(k0).+ end_of_list.+ ```++ and the search then runs until killed, because the mangled problem is unsatisfiable while the real+ one is not. A time limit would report `unknown`, so the failure is silent. The same file with `c0`+ in place of `w0` is echoed unchanged and returns a two-element model at once. The mangler must+ therefore never emit an initial letter in `{u,v,w,x,y,z}`: `p0…` for unary, `r0…` for binary,+ `c0…` for constants, and bound variables as `x0, x1, …` so that they still are variables under the+ same convention. The echoed clause block should be parsed and compared, not assumed.++ **Whitespace in a symbol.** `bare()` in `src/tptp.rs` strips the angle brackets before an IRI+ reaches `Term::Const` or `P1::Cls`, so the symbols are raw IRIs and the whitespace refusal in the+ checker-format writer is load-bearing rather than belt and braces. A symbol with a space in it+ re-parses as a different formula and one with a tab in it re-parses as a different set of fields.+ The 13 September 2026 audit found exactly this truncation class silently disabling any SHACL+ constraint that mentioned a typed literal. The writer must return an error rather than emit such a+ line, and the digest is the second line of defence: a file that splits differently on read-back+ canonicalises differently and the digest mismatches.++ ## What the Lean half found while being built++ `free` was written with `List.erase` on the binder cases, copied from the design prototype.+ `List.erase` removes the FIRST occurrence only, so `free (∀x0. thing(x0) ∧ lit(x0))` came back as+ `[0]` and every formula using a bound variable twice was classified as open. Nothing became+ unsound, because a larger `free` only strengthens the hypothesis of `holds_congr`. What would have+ happened is that `check_complete_closed` would have stopped applying to essentially every real+ problem, and `oo-folmodel` would have reported `closed: false` and quoted the weaker rejection+ sentence for ever, with no test failing. It was caught by a `by decide` in `lean/Fol/Witness.lean`+ asserting that the witness problem is a set of sentences, and the fix is `filter` rather than+ `erase`.++ ## What the Rust half found when it was first run end to end++ **A defect in this repository's own export reporting, of the exact shape this project exists to+ catch.** Running `fol-model --goals` over+ `case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl` returned a MACHINE-CHECKED+ countermodel for five of the nine triples the OWL-RL reasoner derives there. `bf:Hanging` is+ declared `owl:Class` and also carries `bf:hasSeverity bf:HighSeverity`; `bf:hasSeverity` has domain+ `bf:ProcessState`; `rdfs2` fires and the engine derives `bf:Hanging rdf:type bf:ProcessState`. The+ exporter, reading `bf:Hanging` as a class, dropped the assertion — correctly, because+ `OwlLean/Syntax.lean` gives each entity kind its own type and `Sig.Ind` is disjoint from `Sig.Cls`,+ so the punning is outside the fragment. What was wrong is that it dropped it SILENTLY:+ `count_out_of_fragment` knew six named OWL constructs and nothing about punning, so the report said+ `exports_a_weaker_axiom_set: false` over an export that was weaker than the graph. Fixed by+ counting it as `assertion on a punned entity`, with the reason; the reading itself is unchanged, so+ no expected string in `fol_translation_correspondence_test.rs` moved. Five punned assertions+ reported, five certified non-entailments: the loop closes exactly.++ **And one in the ingestion, caught by the pipeline's own stop-the-line block on its first run.**+ Z3's `(define-fun NAME ((args)) SORT BODY)` has the RETURN SORT at index 3 and the body at 4. The+ first parser took index 3 for the body and every ingestion failed with `z3's model uses "Bool"`.+ Nothing was mis-certified, because the disagreement block is what fires when a model cannot be+ turned into a structure, and the verdict was `satisfiable_oracle` with nothing checked. It is+ recorded here because the fix added a sort check whose only job is to make that message name the+ symbol.++ **And a third, in the exit code.** `fol-model` exited non-zero on a stop-the-line only on the+ direct CLI path. `src/batch.rs` decided the exit code from the presence of an `"error"` key, and a+ stop-the-line is not an error — the command ran and answered — so `batch` exited 0 over it. Batch+ is the mode every tool in `tools/` uses, so in the one place the gate has to bite it did not. Fixed+ by reading the `stop_the_line` count as well, keyed on the field rather than on the command name so+ a later command reporting the same thing inherits it. Measured after the fix: the same ontology+ with a deliberately lying `z3` on `PATH` exits 1, and with the real `z3` exits 0.++ ## Still not done++ - **The digest still identifies rather than commits.** FNV-1a is the right tool for comparing two+ implementations and the wrong tool for defending against someone who controls the file. It is now+ written twice, in `lean/Fol/Parse.lean` and in `tptp::checkfmt`, and the two agree on+ `4403d8aaa0c422f7` by test on one side and `#guard` on the other. Neither is a commitment.+ - **The unbounded encoding's models are not ingested.** A `sat` on `declare-sort` is+ `satisfiable_oracle` with `checker_exit: null`, because Z3 answers there through model-based+ instantiation and prints a universe block rather than an enumeration. The bounded ladder is the+ route to a certificate and the unbounded probe is the route to `unsatisfiable_oracle`; joining+ them would need a reader for the universe form and a way to tell a complete model from a+ candidate one.+ - **The ladder starts at 1 and stops at the first model, so the certificates are the SMALLEST+ models.** Measured over the shipped case studies, every one of them is satisfied at carrier 1,+ because none exports an axiom forcing two distinct elements. The certificate is real and the+ property is weak. A `--min-domain` would produce more interesting structures and has not been+ built.+ - **The emitted file asks for `(get-model)` unconditionally**, so an `unsat` run leaves+ `(error "model is not available")` in the solver's captured output after the status line. It is+ harmless — `read_sat` is line-oriented and finds `unsat` on its own line first, and the exit code+ is not consulted for Z3 — but a reader of `z3_unbounded.out` sees an error next to a correct+ answer. A second file without the `get-model` line, or `(set-option :produce-models false)` on+ the probe, would remove it.+ - **Three things are quadratic or repeated and none of them matters yet.** `Fol.covers` is+ O(|Γ| × |declarations|) in the Lean; the Rust `FolProblem::vocabulary()` is rebuilt on every call;+ and `fol_model::mace4::parse_entries` materialises the remaining block as a `String` once per+ entry, so reading a model with `e` entries copies O(e × block) characters. All three are fine at+ the measured sizes — the largest shipped fixture is 2441 formulas and the whole pipeline runs in+ 0.47 s — and all three would want fixing an order of magnitude up.+ - **`lean/Dl/Parse.lean` has an attribution bug of its own**, found while reading it for this work+ and NOT fixed here. `Tables.toInterp` sets `ind := fun a => t.imap.getD a ""` and its docstring+ claims the empty name "is in no domain". That is not guaranteed: `parseModel` accepts a `domain`+ line with an empty element name, at which point `"" ∈ I.dom`, `indInDom` passes, and an+ individual with no `ind` line silently denotes a real carrier element. It is a provenance defect+ and not an unsoundness, since `Dl.Satisfiable` is existential over `Interp` and the interpretation+ produced is a genuine one, so `satisfiable_of_checkModel` still holds. The fix is to refuse an+ empty element name in `parseModel`, and it needs its own test.-- **Decision 0002 references a "decision 0004" that does not exist** in `docs/decisions/`. The- description-logic model certificate it points at is `lean/Dl/` and is implemented; only the- record is missing. Not fixed here, because writing someone else's decision record is not this- agent's to do.++- **Decision 0002's reference to a missing record is resolved.** It cited a "decision 0004" that did not exist when this was written. One was written independently, under that number and with this title, by an agent working from the same base and unable to see this file. The two stated the same decision; this one is the accurate one and is cited from `src/`, `lean/` and the tests, so 0002 was repointed here and the duplicate removed rather than renumbering a dozen call sites.diff --cc docs/lean-certificates.mdindex bf358ced,b983b3dc..30818ae0--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@@ -288,57 -168,182 +288,225 @@@ inference and never the premises. The rruns can be compared, and `tests/lean_horn_certificate_test.rs` fails if a user-rule run everreports the absolute verdict.-Nineteen of the engine's rules are Horn rules and appear in the built-in table. `cls-int1` and-`cls-uni` are not: their premise count is the length of an RDF list, which is data rather than fixed-by the rule, so they remain hardcoded arms. A user rule language stops at the same boundary.+Twenty-seven of the engine's rules are Horn rules and appear in the built-in table, the count+`the_built_in_rules_are_emitted_as_data` pins. Four are not: `cls-int1`, `cls-int2`, `cls-uni` and+`cls-oo` each read an RDF list off the graph, so the LIST is a premise and the premise count is data+rather than fixed by the rule. They remain hardcoded arms. A user rule language stops at the same+boundary.++`reason --rules TABLE --certificate DIR` evaluates a supplied table to a fixpoint over the loaded+graph and writes the three files `oo-horn check` reads. Nothing is materialised: a conclusion drawn+under a table nobody has checked holds only in models that satisfy that table, and writing it into+the store beside the assertions would lose exactly that distinction. See+[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).++## Rules you wrote in SWRL or RIF Core++`rules.tsv` is an internal encoding, not a language anybody writes in. `rules-import` reads two+standard rule syntaxes into it.-The Rust reasoner does not yet evaluate a supplied rule table, so today this layer checks-certificates rather than producing them. See+```bash+open-ontologies load ontology.ttl+open-ontologies rules-import --from swrl --out rules.tsv # SWRL, out of the loaded graph+open-ontologies rules-import --from swrl --file rules.owl --out rules.tsv+open-ontologies rules-import --from rif --file rules.xml --out rules.tsv+open-ontologies reason --rules rules.tsv --certificate cert/+cd lean && lake exe oo-horn check ../cert/rules.tsv ../cert/asserted.tsv ../cert/horn.tsv+```++**Only part of each language is a Horn table over triple patterns, and the exact fragment is in+[docs/rule-syntax-front-ends.md](rule-syntax-front-ends.md) and in every response.** A rule outside+it is named, counted and refused; by default one refusal fails the whole import and writes nothing,+because a table that quietly lost a rule still reaches a fixpoint and still produces a certificate+that checks green, which is a sound proof about a rule set nobody wrote. `--allow-partial` imports+the rest and flags the result `certifies_a_weaker_rule_set`.++Every imported rule is a rule you wrote, so it lands on the second row of the table above without+exception: imported rules are named `swrl/…` and `rif/…`, no built-in rule is, and `oo-horn` awards+the absolute verdict only to a table that renders identically to the built-in one.+The Rust reasoner evaluates a supplied rule table through `reason --rules RULES.tsv --certificate+DIR`, which writes `rules.tsv`, `asserted.tsv` and `horn.tsv` and states no verdict of its own.+Nothing is materialised into the store: a conclusion drawn under a table you wrote holds only in+models that satisfy that table, and merging it in beside the assertions would lose exactly the+distinction this is about. See[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).+## What the checker assumes about the engine++The theorem is conditional. It says that IF the asserted graph is `G` and IF these steps check,+THEN the conclusions hold in every model of `G`. Everything to the left of that is the Rust writing+down the truth, and the checker cannot see any of it: it reads files, not the store and not the+run. `docs/trusted-computing-base.md` enumerates that boundary as twenty-nine checkable properties+and says for each what checks it. Read it before relying on a certificate, because a certificate is+a claim about a file and the file's relationship to the store is the part nobody proved.+ ## First-order model certificates: `oo-folmodel`++ A solver's `sat` answer is worth nothing on its own and everything once the model comes with it.+ `lean/Fol/` holds a checker for a finite first-order structure, and `Fol.satisfiable_of_check` says+ that a structure it accepts really does satisfy every formula of the problem, so the problem is+ satisfiable. `Fol.not_entails_of_check` is the sharper form: a checked model of `¬φ` together with+ `Γ` is a machine-checked proof that `Γ` does **not** entail `φ`.++ ```bash+ cd lean+ lake build # builds the checker AND checks the proofs+ lake exe oo-folmodel PROBLEM.tsv MODEL.tsv+ ```++ ```json+ {"verdict":"model_checked","formulas":5,"domain":2,"closed":true,+ "goal_negated_present":true,"source":"z3","cardinality_search":"1,2",+ "problem_digest":"4403d8aaa0c422f7","theorem":"Fol.satisfiable_of_check",+ "non_entailment_theorem":"Fol.not_entails_of_check"}+ ```++ The two file formats, with a worked example whose digest is pinned by the build, are documented in+ `lean/Fol/Syntax.lean`. Runnable copies of every case below are in `tests/fixtures/folmodel/`.++ **Exit codes, and the fixture that demonstrates each.**++ | exit | verdict | reason | fixture |+ |---|---|---|---|+ | 0 | `model_checked` | | `problem.tsv` + `model.tsv` |+ | 1 | `rejected` | the checker rejected the structure | `model_no_edge.tsv` |+ | 1 | `rejected` | `problem_digest_mismatch` | `model_wrong_digest.tsv`, `problem_other.tsv` |+ | 1 | `rejected` | `undeclared_symbol` | `model_undeclared.tsv` |+ | 2 | `unreadable` | the carrier is empty | `model_empty_domain.tsv` |+ | 2 | `unreadable` | a row contradicts a declared arity | `model_bad_arity.tsv` |+ | 2 | `unreadable` | an index is outside the carrier | `model_index_out_of_range.tsv` |+ | 2 | `unreadable` | a declared symbol has no row | `model_missing_row.tsv` |+ | 2 | `unreadable` | the problem carries no formulas | `problem_empty.tsv` |++ **The verdict tells you what it is relative to, and you must read it.** These four are the SOLVER+ level, and a driver that collapses any two of them is reporting a falsehood from correct solver+ output.++ | solver said | encoding | verdict | theorem | means |+ |---|---|---|---|---|+ | `sat`, with a model the checker accepted | either | `model_checked` | `Fol.satisfiable_of_check` | the problem has a model, exhibited |+ | `sat`, no checkable model | either | `satisfiable_oracle` | none | trust the solver |+ | `unsat` | `finite(k)` | `no_model_up_to_size_k` | none | **not** unsatisfiability |+ | `unsat` | `unbounded` | `unsatisfiable_oracle` | none | trust the solver, and never more |++ `no_model_up_to_size_k` is the one people get wrong. `∀x∃y (r(x,y) ∧ x≠y)` is `unsat` at carrier 1+ and `sat` at carrier 2, so a bounded `unsat` is frequently not evidence of anything. A solver that+ answers `sat` whose model the checker then REJECTS is `satisfiable_oracle` with `checker_exit: 1`,+ never `rejected` as though the ontology were at fault.++ **Two gates that are not soundness gates, and are labelled so.**++ - `undeclared_symbol` is an ATTRIBUTION gate. `Fol.FinModel`'s three fields are total, so an+ undeclared symbol is still interpreted and the theorem holds without the gate. What it buys is+ that the structure certified is the structure the solver described rather than that structure+ completed with defaults. The JSON carries `"gate":"attribution"` so a report cannot quietly+ promote it.+ - `problem_digest_mismatch` binds `model.tsv` to `problem.tsv`. The digest is FNV-1a 64 over the+ canonical re-serialisation of the parsed formula list, specified in `lean/Fol/Parse.lean` so a+ Rust writer can reproduce it. It identifies; it does not commit.++ **Cost, measured on this machine** (Apple silicon, compiled `oo-folmodel`, 2000 formulas at+ quantifier depth 3, so `carrier^3` evaluation points per formula):++ | carrier | evaluation points | user time |+ |---|---|---|+ | 8 | 1.0M | 0.14 s |+ | 16 | 8.2M | 0.92 s |+ | 24 | 27.6M | 2.93 s |+ | 32 | 65.5M | 6.80 s |++ About 9M points per second, cubic in the carrier at this depth. Solvers return carriers in the+ single digits on real ontologies, so this is a cap to state rather than a problem to solve:+ `--max-domain` defaults to 16 and the flag goes higher with the cost documented.++ ### Driving all of it in one command: `fol-model`++ `oo-folmodel` checks a model somebody already has. `open-ontologies fol-model` produces one: it+ exports the ontology, runs Z3 or Mace4, reads the structure back, runs the checker, and reports the+ verdict with the five fields above.++ ```bash+ cd lean && lake build && cd .. # the checker, and its proofs+ printf 'load case-studies/blast-furnace-ironmaking/blast-furnace-ontology.ttl\n\+ fol-model --out /tmp/solve --solver z3 --max-domain 8\n' \+ | open-ontologies --no-connect --data-dir /tmp/store batch -+ ```++ ```json+ {"verdict":"model_checked","solver_verdict":"sat","encoding":"finite(1)","checker_exit":0,+ "owl_reading":null,"theorem":"Fol.satisfiable_of_check","formulas":45,+ "problem_digest":"27751aa61e9de6fd","cardinality_search":[1],+ "bounded_search":"a model was reported at carrier 1","dropped_symbols":[],"seconds":0.084}+ ```++ Every intermediate file lands in `--out`, so a run is reproducible by hand from what it leaves+ behind: `problem.tsv` and its digest, `problem_k1.smt2` (or `problem.in` plus `symbols.tsv` for+ Mace4), the solver's raw output, `model.tsv`, and `checker.json`.++ Pass `--goals` a TSV of triples — `derivations.tsv` from `reason --certificate` is the intended+ input, with `--goals-skip-columns 1` — and each becomes its own run asking whether the ontology+ FAILS to entail it. A `model_checked` there carries `owl_reading:+ "not_entailed_under_unproved_translation"`, which is `Fol.not_entails_of_check` plus two things+ this layer does not prove: `OwlLean.adequacy` lives in a sibling project, and the Rust-to-Lean+ translation correspondence is pinned by tests and not proved. Never shorten it to "not entailed".++ **A rejected model stops the line.** If a solver answers `sat` and the checker rejects the+ structure, the verdict stays `satisfiable_oracle` — it is not a fact about the ontology — but the+ report carries a `disagreement` block with `severity: STOP_THE_LINE`, the run summary counts it,+ and the command exits non-zero. That is the treatment `tools/shacl_differential.py` gives a+ FALSE_CLEAN, for the same reason: a disagreement between a checker and the thing it is checking is+ the one result that must fail a pipeline.++ **The two finders differ in what they can be asked, and the verdict rules read the difference.**++ | | Z3 | Mace4 |+ |---|---|---|+ | format | SMT-LIB 2 (`fol --format smtlib`) | LADR (`fol --format ladr`) |+ | smallest carrier | 1 | 2 — `mace4 -n 1` is a FATAL error, measured |+ | unbounded question | yes, so `unsatisfiable_oracle` is reachable | no, it is a finite model finder |+ | symbols | quoted with vertical bars | MANGLED to `p0`/`r0`/`c0`, table in `symbols.tsv` |+ | reduct | auxiliary functions | Skolem functions and constants |++ Mangling is not a style choice. LADR reads a name whose first letter is in `{u,v,w,x,y,z}` as a+ VARIABLE, so an IRI beginning with one of those becomes universally quantified and Mace4 silently+ searches a different problem. Measured on LADR 2009-11A: `p0(w0). -p0(k0).` is echoed in Mace4's+ own `CLAUSES FOR SEARCH` block as `p0(x).` and `-p0(k0).`, and the run reports `exit (exhausted)`+ with no error at all.++ ## What is proved, and what is not, on this layer++ Every result in `lean/Fol/` has axiom footprint `[propext, Quot.sound]` or smaller, pinned by+ `#guard_msgs` in the source. `Classical.choice` appears nowhere in the layer, which is tighter than+ the triple the older layers carry.++ | theorem | says |+ |---|---|+ | `Fol.eval_iff` | the Boolean evaluator and the `Prop` satisfaction relation agree, at every formula and environment |+ | `Fol.satisfiable_of_check` | an accepted structure is an existence proof: the problem is satisfiable |+ | `Fol.check_complete` | the gate can fail: a rejection is about the structure, not the checker's patience |+ | `Fol.check_complete_closed` | for a problem of sentences, a rejected structure is not a model under **any** assignment |+ | `Fol.not_entails_of_check` | a checked model of `¬φ :: Γ` proves `Γ` does not entail `φ` |++ `lean/Fol/Witness.lean` closes the vacuity question by construction: `employment_is_satisfiable`+ accepts a real structure, `the_model_does_not_satisfy_everything` shows that same structure refuses+ a formula, `not_everything_is_satisfiable` shows `Satisfiable` is not the trivial predicate, and+ five named forgeries are each rejected on their own through `check_complete`, so it is the+ checker's own rejection that is certified rather than an independent argument.++ Not proved, and named next to the verdict rather than in a footnote:++ - **Nothing about unsatisfiability, in any direction, ever.**+ - **The absence of a finite model implies nothing.** SHIQ lacks the finite model property, so a+ satisfiable ontology can have only infinite models and will never receive a certificate.+ - **The OWL-level reading** rides on `OwlLean.adequacy` in the sibling project *and* on the+ Rust-to-Lean translation correspondence, which decision 0005 states is pinned by tests and not+ proved. It carries its own word, `not_entailed_under_unproved_translation`, which must never be+ shortened to "not entailed".+ - **The parser and the file formats** (`lean/Fol/Parse.lean`, `lean/FolMain.lean`). A parse error+ is exit 2 and never a verdict in either direction.++ Nothing in `src/` writes either file yet, so today this layer checks certificates rather than+ producing them. See+ [decision 0006](decisions/0006-a-model-is-a-certificate-and-a-refutation-is-not.md).## Known limitationsdiff --cc docs/reasoning-systems-inventory.mdindex 233d939d,00000000..68f8276bmode 100644,000000..100644--- a/docs/reasoning-systems-inventory.md+++ b/docs/reasoning-systems-inventory.md@@@ -1,153 -1,0 +1,153 @@@+# Reasoning systems: what this project uses, what it refuses, and why++Every external reasoning system that has been considered for this project, with its real status. The+point of the document is that a name appearing in a design discussion is not a capability, and a+reader deserves to know which is which without reading the commit log.+- The organising principle is decision 0004. A model is a finite object and a verified checker can++The organising principle is decision 0006. A model is a finite object and a verified checker can+validate one, so a satisfiability answer can be turned into a certificate. A refutation is a proof in+a calculus nobody has mechanised in core Lean here, so an unsatisfiability answer is testimony. That+single asymmetry decides how each system below is used, and it explains rankings that otherwise look+perverse.++## Status at a glance++| System | Kind | Status here |+| --- | --- | --- |+| Lean 4 | Proof assistant | The kernel. Every checker in this repository. |+| E 3.2.5 | First-order prover | Used as a differential oracle. Never as an authority. |+| Vampire 5.1.0 | First-order prover | Installed, same role as E. |+| Z3 4.16.0 | SMT solver | Model-certificate layer, under construction. |+| Mace4 | Finite model finder | Same. Its output is checkable; Prover9's is not. |+| Prover9 | First-order prover | Declined. Unmaintained since 2011, refutations uncheckable. |+| cvc5 | SMT solver | Not installed. Same role as Z3 when it is. |+| Isabelle/HOL | Proof assistant | Declined for now. Reasons below. |+| Dedukti | Logical framework | Declined. Reasons below. |+| Duper, lean-smt | Lean automation | Declined. Both require Mathlib. |+| Aeneas with Charon | Rust to Lean | Declined. Subset does not contain this codebase. |+| Verus, Creusot, Prusti | Rust verification | Declined. Each needs the code rewritten in its subset. |+| Kani | Rust bounded model checker | Being applied to the trusted boundary only. |+| TPTP and TSTP | Interchange | Implemented. The execution format. |+| CLIF, ISO/IEC 24707 | Interchange | Implemented. The conformance format. |+| SMT-LIB 2 | Interchange | Under construction. |+| RIF Core, SWRL | Rule languages | Front ends under construction. |+| CertifyingDatalog | Prior art | Not a dependency. The Horn layer is our analogue. |++Anything marked under construction is on an unmerged branch and is not a capability yet. This+document will be wrong the moment that changes, so treat the branch state as authoritative.++## The provers, and why the strongest one is still only an oracle++Vampire and E are the live first-order provers. Vampire has dominated the relevant competition+divisions for two decades and E is the more embeddable of the two. Both read TPTP, which is why TPTP+is our execution format regardless of what else we print.++Neither can give us a certificate. Replaying a superposition refutation needs a verified calculus with+unification, term orderings and redundancy criteria, and none exists in core Lean. So both are used the+way pyshacl is used for validation: as a differential oracle whose disagreement with our engine means+one of the two is wrong, and whose agreement means nothing has been proved. On its first real run+against one public vocabulary the comparison disagreed with the engine on fifty-eight of one hundred and+eighty-one claimed entailments, and every one was a real defect, including one in the exporter itself.+That is the value, and it does not require trusting the prover at all.++Prover9 is declined. Its author died in 2011, it has had no maintainer since, and its refutations are+no more checkable than Vampire's. There is no version of the argument where an unmaintained prover+beats a maintained one at the same job.++Mace4, from the same distribution, is a different matter entirely and is kept. It is a finite model+finder, its output is a finite structure, and a verified evaluator can check it. Half of a dead+toolchain is alive here because of what kind of evidence it produces, not how well maintained it is.++## SAT and SMT++Z3 is the fifth reasoning family and the last one to be built. The interesting part is not the SMT-LIB+printer, which is a third rendering of a representation we already have, but that Z3 returns models.+A model that our verified checker accepts converts a solver's opinion into a proof of satisfiability,+which is the only place in this architecture where an external tool's answer is upgraded rather than+merely corroborated.++Its unsat answers stay oracle answers. An unsat core is not a proof object we can replay, and the+proof logs Z3 can emit would need the same mechanised calculus that the first-order case lacks.++## Isabelle, and why not yet++Isabelle/HOL is the obvious comparison, because Sledgehammer does exactly what we cannot: it calls+external provers and then reconstructs their findings through the Isabelle kernel, so an external+prover's answer becomes a proof. That is the capability this project lacks and would most like.++It is declined for now, and not because Isabelle is unsuitable. Adopting it+means a second proof assistant, a second build, a second set of proofs and a second trust surface,+for a codebase whose entire pitch is that the trust surface is small enough to read in an afternoon.+Reconstruction would have to be redone for our translation rather than inherited. And the specific+thing we would gain, kernel-checked refutations, we can already approximate where it matters by+checking models instead.++The version that would pay, and that remains open, is narrower: use Isabelle as an INDEPENDENT SECOND+KERNEL for the statements we already prove in Lean, so that a bug in one kernel or in one+formalisation does not go unnoticed. That is a replication exercise rather than an integration, and it+should be judged on its own when the Lean side is stable.++Nitpick, Isabelle's counterexample finder, belongs to the model-finder family above and would slot+into the certified path the same way Mace4 does.++## Dedukti, and why not++Dedukti is a logical framework designed so that proofs from different systems can be expressed in one+language and rechecked. The motivation is real and it is close to this project's own.++It is declined because it solves a problem we do not have. Dedukti pays when you hold large proof+libraries in several systems and want them to talk. We hold small certificates in one format, checked+by one small kernel, and adding a framework layer would enlarge the trusted base to buy portability+nobody has asked for. If a second consumer of our certificates ever appears, this is the first thing+to revisit.++## Lean automation we do not use++Duper is a superposition prover written inside Lean that produces kernel-checked proof terms, and+lean-smt reconstructs cvc5 proofs the same way. Either would give us precisely the missing capability,+kernel-checked refutations, without leaving Lean.++Both depend on Mathlib. The axiom footprint of every result here is pinned to `propext`,+`Classical.choice` and `Quot.sound`, the build takes no external package, and the argument that anyone+can read the whole checker rests on that. Taking Mathlib to gain refutation checking is a real trade+and might one day be the right one. It is not being made silently.++## Putting the Rust in Lean++The demand that all the code be verified in Lean cannot be met literally. There are roughly fifty+thousand lines of Rust here. Aeneas with Charon translates Rust into Lean for a restricted subset that+this codebase is not inside, and the same is true of Verus, Creusot and Prusti, each of which verifies+Rust written in its own dialect against SMT.++The demand has a real core and that core is small. The Lean theorems are conditional: they say that IF+the asserted graph is what the certificate says and IF the derivation steps are the ones the engine+took, THEN the conclusions follow. Everything to the left of that is the trusted computing base, and+it is a serialiser, a parser and an interner rather than fifty thousand lines. That boundary is what+is being property-tested and, where it pays, model-checked with Kani. What remains trusted after that+work will be named explicitly rather than left for a reader to infer.++## Rule languages++The Horn certificate layer is generic over rule tables, with one soundness theorem covering every+table at once, which is what makes RIF Core, SWRL and Datalog a single problem rather than three. Until+the front ends land, that coverage is architectural rather than actual, because nothing produces a+rule table from a standard rule syntax.++The verdict rule from decision 0003 governs all of it and is the reason this is safe to build. A+certificate over the built-in table earns `entailed`. A certificate over a table a user supplied,+whatever syntax it arrived in, earns `entailed_under_supplied_rules`, because those rules are+assumptions the certificate carries and never facts it establishes.++CertifyingDatalog, presented at ITP 2025, is the closest published prior art and is not a dependency.+It certifies Datalog derivations in Lean; our Horn layer is the analogue reached independently, and the+comparison is worth making in any write-up rather than avoided.++## Interchange formats++TPTP is the execution format, because it is the only one an installed solver will read. CLIF is the+conformance format, because ISO/IEC 21838-1 requires a top-level ontology to carry an axiomatisation in+a language conforming to ISO/IEC 24707 and the Basic Formal Ontology discharges that in CLIF. SMT-LIB+is the model-finding format. All three are printers over one representation, and the correspondence+between that representation and the Lean translation is pinned by hand-computed tests and is not itself+proved. That last sentence is the honest trust boundary of the export layer and should never be dropped+when the layer is described.diff --cc src/batch.rsindex 9493bad3,e6eb459c..590678fd--- a/src/batch.rs+++ b/src/batch.rs@@@ -99,7 -113,7 +113,8 @@@ impl BatchRunner"lint" => self.exec_lint(&cmd.args),"reason" => self.exec_reason(&cmd.args),"fol" => self.exec_fol(&cmd.args),+ "rules-import" | "rules_import" => self.exec_rules_import(&cmd.args),+ "fol-model" | "fol_model" => self.exec_fol_model(&cmd.args),"shacl" => self.exec_shacl(&cmd.args),// The CLI subcommand is spelled with a hyphen and this arm accepted// only the underscore, so every documented invocation was rejected@@@ -306,29 -325,47 +326,70 @@@serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}+ /// `--from swrl` with no `--file` reads the loaded graph, which is why+ /// this command is proxied to the daemon rather than run locally.+ fn exec_rules_import(&self, args: &[String]) -> Value {+ let Some(from) = Self::flag_value(args, "--from") else {+ return json!({+ "error": "rules-import needs --from: 'swrl' (SWRL rules encoded in RDF) or 'rif' \+ (RIF Core, XML syntax)"+ });+ };+ let file = Self::flag_value(args, "--file");+ let out = Self::flag_value(args, "--out");+ let allow_partial = args.iter().any(|a| a == "--allow-partial");+ let result = crate::rulesyntax::run_import(+ &self.graph,+ &from,+ file.as_deref().map(std::path::Path::new),+ out.as_deref().map(std::path::Path::new),+ allow_partial,+ )+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string());+ serde_json::from_str(&result).unwrap_or(json!({"raw": result}))+ }++ /// The certifying pipeline. In-process for the same reason `fol` is: the+ /// store is per process, so loading and solving have to happen in one run.+ fn exec_fol_model(&self, args: &[String]) -> Value {+ use crate::fol_solve::{SolveOptions, Solver, solve_export};+ let Some(out) = Self::flag_value(args, "--out") else {+ return json!({"error": "fol-model requires --out DIR"});+ };+ let solver = match Solver::parse(+ &Self::flag_value(args, "--solver").unwrap_or("z3".to_string()),+ ) {+ Ok(s) => s,+ Err(e) => return json!({"error": e.to_string()}),+ };+ let opts = SolveOptions {+ solver,+ max_domain: Self::flag_value(args, "--max-domain")+ .and_then(|v| v.parse().ok())+ .unwrap_or(16),+ timeout_secs: Self::flag_value(args, "--timeout-secs")+ .and_then(|v| v.parse().ok())+ .unwrap_or(30),+ unbounded_probe: Self::flag_value(args, "--unbounded-probe")+ .map(|v| v != "false")+ .unwrap_or(true),+ checker: Self::flag_value(args, "--checker").map(std::path::PathBuf::from),+ };+ let goals = Self::flag_value(args, "--goals");+ let skip: usize = Self::flag_value(args, "--goals-skip-columns")+ .and_then(|v| v.parse().ok())+ .unwrap_or(0);+ let result = solve_export(+ &self.graph,+ std::path::Path::new(&out),+ &opts,+ goals.as_deref().map(std::path::Path::new),+ skip,+ )+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string());+ serde_json::from_str(&result).unwrap_or(json!({"raw": result}))+ }+fn exec_shacl(&self, args: &[String]) -> Value {use crate::shacl::ShaclValidator;let shapes_path = match args.first() {diff --cc src/main.rsindex 2fd097b6,0bbda9f5..20336cb7--- a/src/main.rs+++ b/src/main.rs@@@ -483,39 -494,46 +499,80 @@@ enum Commands#[arg(long, default_value_t = 0)]goals_skip_columns: usize,},++ /// Read rules written in a STANDARD rule syntax into the `rules.tsv` table+ /// `reason --rules` evaluates and `oo-horn check` verifies.+ ///+ /// Every rule imported is a rule you wrote, so a certificate over the table+ /// this produces can only ever earn `entailed_under_supplied_rules`: true in+ /// every model of the asserted graph THAT ALSO SATISFIES YOUR RULES. The+ /// rules are assumed and never checked.+ RulesImport {+ /// `swrl` for SWRL rules encoded in RDF, `rif` for RIF Core in its XML+ /// syntax. Only part of each language is representable as Horn rules+ /// over triple patterns; the response states the exact fragment and+ /// names every rule it refused.+ #[arg(long)]+ from: String,+ /// The document to read. Required for `rif`. Optional for `swrl`:+ /// without it the LOADED graph is read; with it the file is parsed into+ /// a store of its own, so importing rules never changes what is loaded.+ #[arg(long)]+ file: Option<String>,+ /// Where to write the table. Without it nothing is written and the+ /// table comes back in the response under `rules_tsv`.+ #[arg(long)]+ out: Option<String>,+ /// Import the rules that CAN be represented even though others cannot.+ /// Off by default, and deliberately: a table that quietly lost a rule+ /// still reaches a fixpoint and still produces a certificate that+ /// checks green, which is a sound proof about a rule set nobody wrote.+ /// With this flag the import succeeds, the result carries+ /// `certifies_a_weaker_rule_set: true`, and every lost rule is named.+ #[arg(long)]+ allow_partial: bool,+ },+++ /// Find a finite model and CHECK it, for a verdict that says what it rests on+ ///+ /// Export, run Z3 or Mace4, read the structure back, and hand it to the+ /// verified checker `oo-folmodel`. Only the verdict `model_checked` rests+ /// on a machine-checked theorem (`Fol.satisfiable_of_check`). A solver's+ /// `unsat` is an ORACLE OPINION and can never be more, and an exhausted+ /// BOUNDED search is `no_model_up_to_size_k`, which is not+ /// unsatisfiability. Exits 1 if any run is a stop-the-line disagreement.+ FolModel {+ /// Working directory. Every intermediate file lands here, so a run is+ /// reproducible by hand from what it leaves behind.+ #[arg(long)]+ out: String,+ /// `z3` (SMT-LIB, and the only one that can be asked the UNBOUNDED+ /// question) or `mace4` (LADR, a dedicated finite model finder whose+ /// minimum carrier is 2).+ #[arg(long, default_value = "z3")]+ solver: String,+ /// The largest carrier the ladder tries. The default is from the+ /// measured cost of the compiled checker: about 9M evaluation points+ /// per second, cubic in the carrier at quantifier depth 3.+ #[arg(long, default_value_t = 16)]+ max_domain: u32,+ #[arg(long, default_value_t = 30)]+ timeout_secs: u32,+ /// After a bounded ladder finds nothing, ask the UNBOUNDED question+ /// too. This is the ONLY route to `unsatisfiable_oracle`. Z3 only.+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]+ unbounded_probe: bool,+ /// A TSV of triples to ask as conjectures, one run per line, the same+ /// shape `fol --goals` takes.+ #[arg(long)]+ goals: Option<String>,+ #[arg(long, default_value_t = 0)]+ goals_skip_columns: usize,+ /// Path to `oo-folmodel`. Defaults to `lean/.lake/build/bin/` then+ /// `$PATH`; its absence is reported loudly and never worked around.+ #[arg(long)]+ checker: Option<String>,+ },/// Full pipeline: ingest → SHACL → reasonExtend {data_path: String,@@@ -737,25 -759,40 +798,60 @@@ impl Commands}cmd("fol", a)}++ Commands::RulesImport { from, file, out, allow_partial } => {+ // Proxied because `--from swrl` with no `--file` reads the+ // LOADED graph, which lives in the daemon. Running it locally+ // would read a different store and import a different rule set.+ let mut a = vec!["--from".into(), from.clone()];+ if let Some(f) = file {+ a.push("--file".into());+ a.push(absolutize(f));+ }+ if let Some(o) = out {+ a.push("--out".into());+ a.push(absolutize(o));+ }+ if *allow_partial {+ a.push("--allow-partial".into());+ }+ cmd("rules-import", a)+ }+++ Commands::FolModel {+ out,+ solver,+ max_domain,+ timeout_secs,+ unbounded_probe,+ goals,+ goals_skip_columns,+ checker,+ } => {+ let mut a = vec![+ "--out".into(),+ absolutize(out),+ "--solver".into(),+ solver.clone(),+ "--max-domain".into(),+ max_domain.to_string(),+ "--timeout-secs".into(),+ timeout_secs.to_string(),+ "--unbounded-probe".into(),+ unbounded_probe.to_string(),+ ];+ if let Some(g) = goals {+ a.push("--goals".into());+ a.push(absolutize(g));+ a.push("--goals-skip-columns".into());+ a.push(goals_skip_columns.to_string());+ }+ if let Some(c) = checker {+ a.push("--checker".into());+ a.push(absolutize(c));+ }+ cmd("fol-model", a)+ }Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),Commands::Status => cmd("status", vec![]),Commands::Pull { url, sparql, query } => {diff --cc src/server.rsindex bcbcdd25,05845229..7f2e7154--- a/src/server.rs+++ b/src/server.rs@@@ -1942,18 -1943,30 +1943,42 @@@ impl OpenOntologiesServer.unwrap_or_else(Self::err_json)}+ #[tool(name = "onto_rules_import", description = "Read rules written in a STANDARD rule syntax into the Horn rule table `onto_reason` evaluates with `rules_file` and the proved-sound Lean checker verifies with `lake exe oo-horn check`. `from: \"swrl\"` reads SWRL rules encoded in RDF (swrl:Imp with swrl:body / swrl:head as rdf:List atom lists) out of the loaded graph, or out of `file` if one is given. `from: \"rif\"` reads RIF Core in its normative XML syntax from `file`; the presentation syntax is NOT parsed and is refused rather than half-read. ONLY PART OF EACH LANGUAGE IS A HORN TABLE OVER TRIPLE PATTERNS. SWRL built-in atoms (swrlb: arithmetic and string predicates), swrl:SameIndividualAtom, swrl:DifferentIndividualsAtom, swrl:DataRangeAtom and anonymous class expressions are refused; RIF equality, External functions and predicates, Expr terms, rif:local constants, List terms, Or/Neg/Naf, an existential conclusion and an Atom of arity 0 or 3+ are refused. A refused rule is NAMED AND COUNTED and by default fails the whole import with no table written, because a rule set that quietly lost half its rules still reaches a fixpoint and still produces a certificate that checks green, which is a sound proof about a rule set nobody wrote. `allow_partial: true` imports the rest anyway and flags the result `certifies_a_weaker_rule_set`. Every rule imported is a rule YOU wrote and nothing discharges it, so a certificate over the table can only ever earn `entailed_under_supplied_rules` under `OOCert.horn_certificate_sound`: true in every model of the asserted graph THAT ALSO SATISFIES YOUR RULES. This tool states no verdict; `oo-horn check` is what pronounces.")]+ fn onto_rules_import(&self, Parameters(input): Parameters<OntoRulesImportInput>) -> String {+ crate::rulesyntax::run_import(+ &self.graph,+ &input.from,+ input.file.as_deref().map(std::path::Path::new),+ input.out.as_deref().map(std::path::Path::new),+ input.allow_partial.unwrap_or(false),+ )+ .unwrap_or_else(Self::err_json)+ }++ #[tool(name = "onto_fol_model", description = "Find a finite model of the loaded ontology and CHECK IT, so the answer names what it rests on. This is the SAT/SMT family, and it is deliberately not symmetric. A REFUTATION cannot be replayed in core Lean, so a solver saying `unsat` is an ORACLE OPINION for ever (decision 0005). A MODEL is a finite object, checking a formula against it is decidable, and `lean/Fol/` holds a checker whose soundness is machine-checked: `Fol.satisfiable_of_check` turns an accepted structure into satisfiability of exactly the formulas it was checked against, and `Fol.not_entails_of_check` turns a checked model of the NEGATED goal into a machine-checked NON-ENTAILMENT, which is the one sentence no theorem prover can produce. The pipeline exports SMT-LIB 2 (for Z3) or LADR (for Mace4) and `problem.tsv` from ONE representation, climbs a cardinality ladder, reads the structure back, and runs `oo-folmodel`. FIVE FIELDS THAT ARE NEVER COLLAPSED: `solver_verdict` (sat/unsat/unknown, what the oracle said), `encoding` (unbounded or finite(k), what it was asked), `checker_exit` (null means the checker never ran), `verdict`, and `owl_reading`. The verdict is one of FIVE WORDS: `model_checked` is the ONLY certified one and requires checker_exit 0; `satisfiable_oracle` is sat with nothing checked; `no_model_up_to_size_k` is an exhausted BOUNDED search and IS NOT UNSATISFIABILITY (a theory with no model of size k can have one of size k+1, and SHIQ has no finite model property at all, so a satisfiable ontology can have only infinite models and will never receive a certificate here); `unsatisfiable_oracle` may be produced ONLY by a run with no cardinality constraint of any kind and can never be more than an opinion; `unknown_oracle` is a timeout or a give-up. A solver answering sat whose model the checker REJECTS is a STOP-THE-LINE disagreement reported in its own block with severity STOP_THE_LINE, never `rejected` as though the ontology were at fault and never `model_checked`. The OWL-level reading carries its own word, `not_entailed_under_unproved_translation`, because it rides on OwlLean.adequacy in a sibling project AND on the Rust-to-Lean correspondence that is PINNED BY TESTS AND NOT PROVED. Needs z3 or mace4 on PATH and `oo-folmodel` built (cd lean && lake build); the absence of either is reported loudly in `skipped` and never worked around. See docs/decisions/0006.")]+ async fn onto_fol_model(&self, Parameters(input): Parameters<OntoFolModelInput>) -> String {+ use crate::fol_solve::{SolveOptions, Solver, solve_export};+ let solver = match Solver::parse(input.solver.as_deref().unwrap_or("z3")) {+ Ok(s) => s,+ Err(e) => return Self::err_json(e),+ };+ let opts = SolveOptions {+ solver,+ max_domain: input.max_domain.unwrap_or(16),+ timeout_secs: input.timeout_secs.unwrap_or(30),+ unbounded_probe: input.unbounded_probe.unwrap_or(true),+ checker: None,+ };+ solve_export(+ &self.graph,+ std::path::Path::new(&input.out_dir),+ &opts,+ input.goals_file.as_deref().map(std::path::Path::new),+ input.goals_skip_columns.unwrap_or(0),+ )+ .unwrap_or_else(Self::err_json)+ }+#[tool(name = "onto_dl_explain", description = "Explain why a class is unsatisfiable using DL tableaux reasoning. Returns an explanation trace showing the logical contradictions that make the class impossible to instantiate.")]async fn onto_dl_explain(&self, Parameters(input): Parameters<OntoDlExplainInput>) -> String {use crate::tableaux::DlReasoner;diff --cc tests/readme_claims_test.rsindex 7c944763,00000000..e5c5892emode 100644,000000..100644--- a/tests/readme_claims_test.rs+++ b/tests/readme_claims_test.rs@@@ -1,179 -1,0 +1,179 @@@+//! The README's tool count must be the tool count, in every place it is stated.+//!+//! It drifted. The file said 110 while the server exposed 111, and it said it in four+//! separate places, which is exactly why nobody noticed: a number repeated by hand has+//! four chances to go stale and no mechanism to notice that it has.+//!+//! The house rule is that a figure next to the thing it measures must be DERIVED, never+//! typed. A README cannot compute, so the next best thing is a test that refuses to let+//! the two disagree. This is that test.+//!+//! It deliberately checks each stated claim BY ITS SURROUNDING PHRASE rather than+//! scanning for every "N tools" in the file, because the README also contains subgroup+//! counts that are correctly smaller than the total. A test that flagged those would be+//! noise, and a noisy gate gets disabled.++use std::path::PathBuf;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++/// The measurement. One `#[tool(name = ...)]` attribute per exposed MCP tool.+fn exposed_tool_count() -> usize {+ let server = std::fs::read_to_string(repo().join("src").join("server.rs"))+ .expect("src/server.rs must be readable");+ server.matches("#[tool(name = ").count()+}++/// Every place the docs state the TOTAL, with the file it lives in and the phrase that+/// identifies it as a total rather than a subgroup. Add a row when a new one is written.+///+/// The architecture diagram left README.md for docs/architecture.md on 14 September 2026,+/// when the README was cut from 1213 lines to 171, so it is checked in its new home. The+/// tool-reference heading went with the section it belonged to and no longer exists.+fn total_claims(n: usize) -> Vec<(&'static str, &'static str, String)> {+ vec![+ ("README.md", "the lead paragraph", format!("**{n} tools**")),+ ("README.md", "the default-build sentence", format!("A default build advertises all {n} tools.")),+ ("docs/architecture.md", "the architecture diagram", format!("ToolGroups[\"{n} Tools\"]")),+ ]+}++#[test]+fn the_readme_states_the_tool_count_it_actually_exposes() {+ let n = exposed_tool_count();+ assert!(n > 0, "no #[tool(name = ...)] attributes found; the measurement itself is broken");++ let mut wrong = Vec::new();+ for (file, where_, claim) in total_claims(n) {+ let text = std::fs::read_to_string(repo().join(file))+ .unwrap_or_else(|_| panic!("{file} must exist: a claim is checked against it"));+ if !text.contains(&claim) {+ wrong.push(format!("{file}, {where_}: expected to find {claim:?}"));+ }+ }++ assert!(+ wrong.is_empty(),+ "src/server.rs exposes {n} tools and the README does not say so everywhere it \+ claims a total.\n{}\n\nFix the README rather than this test: the server is the \+ measurement and the prose is the claim. If a claim was deliberately removed or \+ reworded, update `total_claims` in this file and say why in the commit.",+ wrong.join("\n")+ );+}++/// The other half, and the one that catches a HALF-DONE correction: if someone updates+/// three of the four places, a stale number is still in the file and the test above+/// would pass on the three it found. This fails on the leftover.+#[test]+fn no_stale_tool_count_survives_anywhere() {+ let n = exposed_tool_count();+ let readme = ["README.md", "docs/architecture.md"]+ .iter()+ .filter_map(|f| std::fs::read_to_string(repo().join(f)).ok())+ .collect::<Vec<_>>()+ .join("\n");++ // The shapes a total is written in here. Any number in one of them that is not the+ // measured count is a leftover from a partial edit.+ let shapes: [(&str, &str); 4] =+ [("**", " tools**"), ("advertises all ", " tools."), ("", " tools organized by function"), ("ToolGroups[\"", " Tools\"]")];++ let mut stale = Vec::new();+ for (prefix, suffix) in shapes {+ let mut rest = readme.as_str();+ while let Some(i) = rest.find(suffix) {+ let head = &rest[..i];+ let digits: String =+ head.chars().rev().take_while(|c| c.is_ascii_digit()).collect::<Vec<_>>().into_iter().rev().collect();- if !digits.is_empty() && (prefix.is_empty() || head.ends_with(&format!("{prefix}{digits}"))) {- if let Ok(found) = digits.parse::<usize>() {- if found != n {- stale.push(format!("{prefix}{found}{suffix} (server exposes {n})"));- }- }++ let matches_shape =++ !digits.is_empty() && (prefix.is_empty() || head.ends_with(&format!("{prefix}{digits}")));++ if let Some(found) =++ digits.parse::<usize>().ok().filter(|f| matches_shape && *f != n)++ {++ stale.push(format!("{prefix}{found}{suffix} (server exposes {n})"));+ }+ rest = &rest[i + suffix.len()..];+ }+ }++ assert!(+ stale.is_empty(),+ "a tool-count claim in the README disagrees with src/server.rs:\n {}\n\nThis is what \+ a half-finished correction looks like: some copies updated, one left behind.",+ stale.join("\n ")+ );+}++/// The README cites theorems by name. A name that does not exist is a false claim, and it+/// is the easiest false claim to make: a theorem written on one branch is quoted from+/// another, or renamed, and the prose keeps asserting it.+///+/// This caught one. The README claimed `Fol.satisfiable_of_check` while that module lived+/// on an unmerged branch, so the table promised a guarantee this tree could not give.+#[test]+fn every_theorem_the_readme_cites_exists() {+ let readme = std::fs::read_to_string(repo().join("README.md")).expect("README.md must exist");++ // Backticked `Namespace.name` with an upper-case namespace: how this repo spells a+ // theorem reference, and specific enough not to catch file paths or CLI flags.+ let mut cited: Vec<String> = Vec::new();+ for chunk in readme.split('`').skip(1).step_by(2) {+ let Some((ns, name)) = chunk.split_once('.') else { continue };+ // All-caps means a filename, not a namespace: CITATION.cff, not OOCert.foo.+ // Every namespace in this repository is mixed case.+ let ns_ok = ns.chars().next().is_some_and(|c| c.is_ascii_uppercase())+ && ns.chars().all(|c| c.is_ascii_alphanumeric())+ && ns.chars().any(|c| c.is_ascii_lowercase());+ let name_ok = !name.is_empty()+ && name.chars().next().is_some_and(|c| c.is_ascii_lowercase())+ && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');+ if ns_ok && name_ok {+ cited.push(chunk.to_string());+ }+ }+ assert!(!cited.is_empty(), "no theorem references found; the extraction itself is broken");++ let lean = repo().join("lean");+ let mut sources = Vec::new();+ let mut stack = vec![lean];+ while let Some(dir) = stack.pop() {+ let Ok(entries) = std::fs::read_dir(&dir) else { continue };+ for e in entries.flatten() {+ let p = e.path();+ if p.is_dir() {+ if p.file_name().is_some_and(|n| n == ".lake") {+ continue;+ }+ stack.push(p);- } else if p.extension().is_some_and(|x| x == "lean") {- if let Ok(t) = std::fs::read_to_string(&p) {- sources.push((p, t));- }++ } else if p.extension().is_some_and(|x| x == "lean")++ && let Ok(t) = std::fs::read_to_string(&p)++ {++ sources.push((p, t));+ }+ }+ }++ let mut missing = Vec::new();+ for c in &cited {+ let (ns, name) = c.split_once('.').unwrap();+ let found = sources.iter().any(|(_, t)| {+ t.contains(&format!("namespace {ns}"))+ && (t.contains(&format!("theorem {name}")) || t.contains(&format!("def {name}")))+ });+ if !found {+ missing.push(c.clone());+ }+ }++ assert!(+ missing.is_empty(),+ "the README cites {} theorem(s) that do not exist under lean/ on this tree:\n {}\n\n\+ Either the name is wrong, or it lives on a branch that has not merged. Both are false \+ claims in a file people read to decide whether to trust this.",+ missing.len(),+ missing.join("\n ")+ );+}