Skip to content

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

rules: read SWRL and RIF Core into the rule table the verified checker already covers

FABIOTESS0c804a55dbab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 993c50af..28dd6db3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,47 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
### Added
+- **SWRL and RIF Core front ends, so the logic-programming family is covered in
+ fact and not only in architecture.** `lean/OOCert/Horn.lean` proves one
+ soundness theorem good for every rule table at once and decision 0003 names
+ RIF Core, Datalog and SWRL as the reason, but nothing in the repository could
+ produce a rule table from a standard rule syntax: the only format anything
+ read was `rules.tsv`, an internal encoding, and grep found no mention of SWRL
+ or RIF outside that decision record. `rules-import --from swrl|rif`
+ (`onto_rules_import` over MCP, `rules-import` in batch) closes that. SWRL is
+ read out of a loaded RDF graph through the `swrl:Imp` encoding, reusing the
+ one `rdf:first`/`rdf:rest` reader `src/tableaux.rs` already had for
+ `owl:intersectionOf`; RIF Core is read out of its normative XML syntax.
+ Datalog is deliberately not offered as a front end, because it has no single
+ standard concrete syntax and a Datalog program over triples IS a `rules.tsv`
+ table.
+
+ **Only a fragment of each language is a Horn table over triple patterns, and
+ the exact fragment is in docs/rule-syntax-front-ends.md and in every
+ response.** SWRL built-in atoms, `swrl:SameIndividualAtom`,
+ `swrl:DifferentIndividualsAtom`, `swrl:DataRangeAtom`, anonymous class
+ expressions and an empty head are refused; RIF `Equal`, `External`, `Expr`,
+ `rif:local` constants, `List` terms, `Or`/`Neg`/`Naf`, an existential
+ conclusion, an `Atom` of arity 0 or 3+, `rif:Import` and the presentation
+ syntax are refused. Every refusal is NAMED AND COUNTED, and by default one
+ refusal fails the whole import with no table written: 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.
+ `--allow-partial` imports the rest and flags the result
+ `certifies_a_weaker_rule_set`, the name the DL model-certificate block
+ already uses for the same idea.
+
+ Every rule a front end emits is named `swrl/…` or `rif/…` and no built-in
+ rule is, so an imported table can never render identically to the built-in
+ one and can never earn the absolute verdict. It always lands on
+ `entailed_under_supplied_rules` under `OOCert.horn_certificate_sound`.
+ `tests/rule_syntax_frontend_test.rs` runs a real rules file in each syntax
+ through the engine into `lake exe oo-horn check` and asserts the verdict it
+ gets back; `no_front_end_can_name_a_rule_the_way_a_built_in_is_named` pins
+ the naming with no Lean present, and `a_partial_import_can_never_be_silent`
+ pins that no combination of arguments writes a table with a refusal recorded
+ and the weaker-rule-set flag false.
+
- **Derivation certificates, checked by a proved-sound Lean checker.**
`reason --certificate DIR` (also `onto_reason`'s `certificate_dir` and batch
`reason --certificate`) writes `asserted.tsv` and `derivations.tsv`: every
diff --git a/CLAUDE.md b/CLAUDE.md
index b44b6243..308de597 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -77,6 +77,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_defects` | BEFORE trusting any fact-level result, and on every marketplace pack before adopting it. Checks the ONTOLOGY against itself with no data present: `transitive_and_functional`, `symmetric_and_asymmetric`, `subclass_cycle`, `sub_property_cycle`, `disjoint_with_ancestor`, `inherited_disjoint`, `self_inverse`, `inverse_not_mutual`. A different question from `onto_dl_check`: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions the moment instances arrive. Each kind is listed at most 50 times, with the full total under `truncated` |
| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl`. Pass `certificate_dir` to also write a derivation certificate (`asserted.tsv` + `derivations.tsv`) that the proved-sound Lean checker in `lean/` verifies; see docs/lean-certificates.md |
| `onto_reason_incremental` | After adding facts to an already-materialised graph. Derives the consequences of the ADDED triples only (semi-naive evaluation, joining the delta against the closure), so the cost tracks what changed rather than the size of the store: effectively instant against a 1.9M-triple store where full re-materialisation takes seconds. Refuses schema axioms (subClassOf, domain, range, inverseOf, equivalentClass) with an explanation, because those change what the whole store entails: run `onto_reason` for them |
+| `onto_rules_import` | To read rules you wrote in a STANDARD rule syntax into the Horn rule table `onto_reason` evaluates with `rules_file`. `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`; `from: "rif"` reads RIF Core in its XML syntax (the presentation syntax is refused, not half-read). Only a FRAGMENT of each language is a Horn table over triple patterns: SWRL built-in atoms, same-individual and different-individual atoms, data ranges and anonymous class expressions are refused, as are RIF equality, External, Expr, `rif:local` constants, list terms, Or/Neg/Naf, an existential conclusion and an Atom of arity 0 or 3+. Every refusal 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. `allow_partial: true` imports the rest and flags `certifies_a_weaker_rule_set`. A table from this tool can only ever earn `entailed_under_supplied_rules` |
| `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call |
| `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |
| `onto_plan` | Before applying changes — shows added/removed classes, blast radius, risk score |
diff --git a/README.md b/README.md
index eb4d21ca..f27c86f4 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@
---
-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.
+Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **110 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 110 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.
@@ -878,7 +878,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T
## 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`.
+110 tools organized by function, available as MCP tools (prefixed `onto_`) and CLI subcommands. A default build advertises all 110. 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 |
| --- | --- | --- |
@@ -947,7 +947,7 @@ flowchart TD
REST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]
end
- subgraph ToolGroups["109 Tools"]
+ subgraph ToolGroups["110 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"]
@@ -1009,6 +1009,30 @@ 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).
+### 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).
+
### Studio
```mermaid
@@ -1094,6 +1118,7 @@ flowchart TD
| Schema Alignment | [docs/alignment.md](docs/alignment.md) |
| SHIQ Reasoning | [docs/reasoning.md](docs/reasoning.md) |
| Derivation certificates, Lean checker | [docs/lean-certificates.md](docs/lean-certificates.md) |
+| SWRL and RIF Core rule front ends | [docs/rule-syntax-front-ends.md](docs/rule-syntax-front-ends.md) |
| Semantic Embeddings | [docs/embeddings.md](docs/embeddings.md) |
| Clinical Crosswalks | [docs/clinical.md](docs/clinical.md) |
| IES Ecosystem | [docs/ies-ecosystem.md](docs/ies-ecosystem.md) |
diff --git a/SKILL.md b/SKILL.md
index b9891eb7..22d28c32 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -2,7 +2,7 @@
name: open-ontologies
version: "0.5.1"
description: >
- AI-native ontology engineering using 109 MCP tools backed by an in-memory Oxigraph triple store.
+ AI-native ontology engineering using 110 MCP tools backed by an in-memory Oxigraph triple store.
Build, validate, query, and govern RDF/OWL ontologies with a generate-validate-iterate loop.
Use when building ontologies, knowledge graphs, RDF data, SPARQL queries, BORO/4D modeling,
SHACL validation, clinical terminology mapping, ingesting from CSV/JSON/Parquet/XLSX or
diff --git a/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
index 8383580c..6e9c76d8 100644
--- a/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
+++ b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
@@ -60,7 +60,42 @@ cases. The engine's rule count has since grown; the checker covers 29 of the OWL
rules, 30 counting `cax-dw` in the refutation layer, and four of them stay as hand-written arms
because their premise count is the length of an RDF list.
+## The family is now covered in fact and not only in architecture
+
+This decision said the logic-programming family — RIF Core, Datalog, SWRL — was the reason to make
+rules data. For a while that was true of the checker and false of the product: the only rule syntax
+anything here could read was `rules.tsv`, which is an internal encoding and not a language anybody
+writes in, and grep found no mention of SWRL or RIF outside this file. A user holding a rules file
+in a standard syntax could use none of it.
+
+`src/rulesyntax.rs` and `rules-import` / `onto_rules_import` close that. SWRL is read out of a
+loaded RDF graph through the `swrl:Imp` encoding, reusing the one `rdf:first`/`rdf:rest` reader the
+DL parser already had; RIF Core is read out of its normative XML syntax. Datalog is deliberately NOT
+offered as a front end, because it has no single standard concrete syntax and a Datalog program over
+triples IS a `rules.tsv` table.
+
+Three things follow from decision 4 and are not negotiable in that code:
+
+1. **Both front ends produce USER tables.** Every rule is named `swrl/…` or `rif/…`, no built-in
+ rule is, and `oo-horn` awards `entailed` only to a table that renders identically to the
+ built-in one. So an imported table structurally cannot earn the absolute verdict.
+ `a_swrl_rule_never_earns_the_absolute_verdict` and its RIF twin are the front ends' copies of
+ `a_user_rule_never_earns_the_absolute_verdict`, and they run the whole pipeline into `oo-horn`.
+2. **A rule that cannot be represented is refused by name and counted.** Both languages exceed a
+ Horn table: SWRL has built-in atoms, same- and different-individual atoms and data ranges; RIF
+ Core has equality, External, `Expr`, `rif:local` and list terms. By default ONE refusal fails the
+ whole import and no table is written, because a rule set that quietly lost half its rules still
+ reaches a fixpoint and its certificate still checks green — a sound proof about a rule set nobody
+ wrote, which is the laundering failure in its purest form. `allow_partial` is the opt-in and sets
+ `certifies_a_weaker_rule_set`, the name the DL model-certificate block already uses for the same
+ idea.
+3. **The supported fragment is stated, never implied.** `docs/rule-syntax-front-ends.md` and every
+ response carry it. "SWRL is supported" would be the false claim this decision exists to prevent
+ one level up.
+
## Still not done
- Nothing in `src/` writes the refutation format, so inconsistency can be checked and not yet
produced by this engine.
+- The RIF presentation syntax is not parsed. It is refused by name; a half-written parser for it
+ would mis-read rules rather than refuse them.
diff --git a/docs/lean-certificates.md b/docs/lean-certificates.md
index 63a03004..7ca7ed8e 100644
--- a/docs/lean-certificates.md
+++ b/docs/lean-certificates.md
@@ -168,14 +168,43 @@ inference and never the premises. The report carries a digest of the table that
runs can be compared, and `tests/lean_horn_certificate_test.rs` fails if a user-rule run ever
reports 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.
-
-The Rust reasoner does not yet evaluate a supplied rule table, so today this layer checks
-certificates rather than producing them. See
+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.
+
+```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.
+
## Known limitations
Stated rather than discovered later.
diff --git a/docs/rule-syntax-front-ends.md b/docs/rule-syntax-front-ends.md
new file mode 100644
index 00000000..0212e547
--- /dev/null
+++ b/docs/rule-syntax-front-ends.md
@@ -0,0 +1,154 @@
+# Rules you wrote, in SWRL or RIF Core
+
+`lean/OOCert/Horn.lean` proves one soundness theorem good for every rule table at once, and
+`reason --rules` evaluates a table and writes a certificate. Between them they were said to cover
+the logic-programming family: Datalog, the Rule Interchange Format, the Semantic Web Rule Language.
+
+They did not. The only rule syntax anything here could read was `rules.tsv`, the tab-separated
+encoding the Lean parser happens to use, which is an internal format and not a language anybody
+writes in. A user holding a SWRL ontology or a RIF Core document could use none of it. `rules-import`
+is the way in.
+
+```bash
+open-ontologies rules-import --from swrl --out rules.tsv # 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 rules-import --from rif --file rules.xml # table returned inline
+```
+
+MCP: `onto_rules_import` with `from`, `file`, `out`, `allow_partial`.
+
+## What is supported, exactly
+
+Nothing here claims to support SWRL or RIF Core. Each front end supports a FRAGMENT, and the
+fragment is printed in every response under `supported_fragment`.
+
+### SWRL
+
+Rules in the RDF encoding, which is the form a SWRL rule takes inside an OWL ontology: `swrl:Imp`
+with `swrl:body` and `swrl:head` as `rdf:List` atom lists. Three atom forms are read, and they are
+the three that ARE triple patterns.
+
+| SWRL atom | triple pattern |
+|---|---|
+| `swrl:ClassAtom` with `swrl:classPredicate` C, `swrl:argument1` a | `a rdf:type C` |
+| `swrl:IndividualPropertyAtom` with `swrl:propertyPredicate` P, `argument1` a, `argument2` b | `a P b` |
+| `swrl:DatavaluedPropertyAtom` with `swrl:propertyPredicate` P, `argument1` a, `argument2` v | `a P v` |
+
+An argument typed `rdf:type swrl:Variable` becomes a variable; anything else is a constant in its
+N-Triples spelling. A conjunctive head of *n* atoms becomes *n* rules, which is the standard split
+of a conjunctive consequent, and the count is reported as `conjunctive_heads_split`.
+
+### RIF Core
+
+The **XML syntax only**. The presentation syntax is a different grammar and is refused by name
+rather than half-read.
+
+| RIF construct | triple pattern |
+|---|---|
+| `Frame` with object o and slot (p, v) | `o p v` |
+| `Member` with instance i, class c | `i rdf:type c` |
+| `Subclass` with sub a, super b | `a rdfs:subClassOf b` |
+| `Atom` with op p, args (a, b) | `a p b` |
+| `Atom` with op p, args (a) | `a rdf:type p` |
+
+`Forall` wrapping an `Implies` is a rule; a bare `Atom`, `Frame`, `Member` or `Subclass` is a ground
+fact, which becomes a rule with an empty body. `And` in the condition is a conjunction; `And` in the
+conclusion, and a multi-slot `Frame` in the conclusion, become several rules. `Exists` is accepted
+in the condition, where dropping the quantifier is equivalent, and refused in the conclusion, where
+it is not.
+
+`Const type="&rif;iri"` is an IRI; any other type is a typed literal, with `rdf:PlainLiteral` split
+on its trailing `@lang`. Entity references are not expanded: a document written against a DOCTYPE
+declaring `&rif;` must be serialised with them expanded, and one that is not is an error rather than
+a guess, because reading `&rif;iri` as six literal characters would turn every IRI constant into a
+local one.
+
+**`Atom` of arity 1 and 2 is a CONVENTION, not part of RIF.** RIF predicates have their own
+extensions; reading a unary predicate as an RDF class and a binary one as an RDF property is the
+usual mapping and it is the one taken here. `Frame`, `Member` and `Subclass` need no convention:
+they are the RIF constructs the RIF–RDF combination already defines as triples.
+
+### Datalog
+
+Not offered under that name. Datalog has no single standard concrete syntax, and a Datalog program
+over triples IS a `rules.tsv` table, which `reason --rules` already takes. Claiming a Datalog front
+end would be exactly the "covered in architecture" move this work exists to undo.
+
+## What is refused, and why a refusal is loud
+
+| refused | why a Horn table over triple patterns cannot hold it |
+|---|---|
+| `swrl:BuiltinAtom` (`swrlb:` arithmetic, string, date predicates) | a predicate over the data domain, computed rather than matched. The table's atoms match triples that are in the graph |
+| `swrl:SameIndividualAtom` | equality of individuals in the domain, not a triple. `owl:sameAs` would be a different claim: the checker has no congruence, so nothing downstream substitutes equals for equals |
+| `swrl:DifferentIndividualsAtom` | a negative fact; a Horn rule is positive atoms implying one positive atom |
+| `swrl:DataRangeAtom` | a test on the VALUE a literal denotes. The checker compares RDF terms and does no datatype reasoning |
+| a `classPredicate`/`propertyPredicate` that is a blank node | an anonymous class expression. A triple pattern holds a name, not a class expression |
+| a `classPredicate`/`propertyPredicate` that is a variable | SWRL requires an IRI there |
+| an empty `swrl:head` | an integrity constraint: the conclusion is falsity, and there is no head atom to derive |
+| an atom list that does not reach `rdf:nil` | read short it is a rule with FEWER conditions, which fires MORE often than the one written |
+| `rif:Equal`, in the condition or the conclusion | a rule table has no equality. In the conclusion, deriving one would require every later step to substitute equals for equals |
+| `rif:External` term or predicate | computed by a function outside the rule set; nothing here computes |
+| `rif:Expr` | a function application. RIF Core is function-free, and a triple position holds a name or a variable |
+| a `rif:local` constant | scoped to the document and denoting nothing outside it. Giving it an IRI would be minting a name the document does not have |
+| a `rif:List` term | a triple position holds one term |
+| `Or`, `Neg`, `INeg`, `Naf` | outside Core, which is Horn |
+| `Exists` in the conclusion | needs a Skolem constant, which would be a name the rule does not contain |
+| `Atom` of arity 0, or 3 and above | arity 3+ would have to be reified, which is a modelling decision the importer will not take on the author's behalf |
+| a `rif:Import` directive | the imported document is not fetched, so the rule set it defines is larger than the rules read |
+| the RIF presentation syntax | a different grammar. A half-written parser would mis-read rules rather than refuse them |
+
+**A refusal fails the whole import by default, and no table is written.** The reason is the failure
+this project attacks. A rule set that quietly lost half its rules still evaluates to a fixpoint, and
+the certificate over what is left still checks green: a perfectly sound proof, about a rule set
+nobody wrote. `--allow-partial` / `allow_partial: true` imports the rest anyway, and then the
+response carries `certifies_a_weaker_rule_set: true`, a per-construct census under
+`constructs_not_supported`, and every lost rule by name under `refused`. That is the same vocabulary
+the DL model-certificate block uses for the constructs it does not model.
+
+Two more things are checked per rule, and both refuse rather than guess. A head variable that does
+not occur in the body is refused, because the engine would have to invent a term to bind it to. A
+constant not in N-Triples spelling is refused, because it can never equal a term the store holds and
+the rule would silently never fire. Both are enforced by rendering each imported rule to its
+`rules.tsv` line and reading it back with the parser `reason --rules` will use, so what the checker
+verifies and what the importer built are the same rule.
+
+Variables are named by their local name when that identifies them. Two variable IRIs in one rule
+with the same local name would become ONE variable in the table, joining two positions the author
+kept apart, so a collision drops the whole rule to full IRIs instead.
+
+## The verdict, which is why this is safe to build
+
+Every rule a front end produces is a rule you wrote. Nothing discharges it against the RDF
+semantics, so a certificate over such a table earns `entailed_under_supplied_rules` and names
+`OOCert.horn_certificate_sound`: true in every model of the asserted graph THAT ALSO SATISFIES THOSE
+RULES. `tests/fixtures/rules/family_swrl.ttl` contains the rule that makes the point, in SWRL: every
+supplier is compliant. It is a valid SWRL rule, it is assumed and never checked, and a certificate
+over a table containing it checks green for ever.
+
+`oo-horn` awards `entailed` only to a table that renders identically to the built-in one, names
+included. Every imported rule is named `swrl/…` or `rif/…`, and no built-in rule is, so a table out
+of this importer can never be that table. That is structural rather than observed:
+`no_front_end_can_name_a_rule_the_way_a_built_in_is_named` checks the naming against the committed
+built-in table with no Lean present, and
+`a_swrl_rule_never_earns_the_absolute_verdict` / `a_rif_rule_never_earns_the_absolute_verdict` take a
+real rules file in each syntax all the way to the checker and assert the verdict it returns.
+
+The importer itself states no verdict, for the reason `run_horn` gives: a second place that
+pronounces is a second place the two verdicts can be confused. What it reports is which of the two a
+table of its making is ELIGIBLE for, which is a fact about provenance and not a judgement on a
+certificate.
+
+## What this does not do
+
+- No `owl:imports` chasing, and no fetching of `rif:Import`. What is read is the document in front
+ of it.
+- No datatype reasoning. `"01"^^xsd:integer` and `"1"^^xsd:integer` are different terms to the
+ checker even though they denote the same value, so a data-valued atom derives less than its SWRL
+ reading would. Deriving less is the sound direction, and it is stated rather than discovered.
+- No RIF presentation syntax.
+- SWRL variables must be declared `rdf:type swrl:Variable`. One that is not is read as an
+ individual, which makes a rule that fires on nothing; a rule that ends up with no variables at all
+ is flagged under `notes` for exactly that reason.
+- Nothing is materialised into the store, here or in `reason --rules`. The certificate is the
+ output.
diff --git a/src/batch.rs b/src/batch.rs
index a5cede8f..a97a9bca 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -98,6 +98,7 @@ impl BatchRunner {
"validate" => self.exec_validate(&cmd.args),
"lint" => self.exec_lint(&cmd.args),
"reason" => self.exec_reason(&cmd.args),
+ "rules-import" | "rules_import" => self.exec_rules_import(&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
@@ -274,6 +275,29 @@ impl BatchRunner {
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}))
+ }
+
fn exec_shacl(&self, args: &[String]) -> Value {
use crate::shacl::ShaclValidator;
let shapes_path = match args.first() {
diff --git a/src/inputs.rs b/src/inputs.rs
index d0f12725..3a8498ba 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -250,6 +250,28 @@ pub struct OntoVocabCheckInput {
pub namespaces: Option<Vec<String>>,
}
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoRulesImportInput {
+ /// Source rule syntax: `swrl` for SWRL rules encoded in RDF, `rif` (or
+ /// `rif-core`) for RIF Core in its normative XML syntax. The presentation
+ /// syntax is not read.
+ pub from: String,
+ /// 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.
+ pub file: Option<String>,
+ /// Where to write the `rules.tsv`. Without it nothing is written and the
+ /// table is returned under `rules_tsv`.
+ pub out: Option<String>,
+ /// Import the rules that CAN be represented even though others cannot.
+ /// Default false, 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. Set true and the
+ /// import succeeds, `certifies_a_weaker_rule_set` is true, and every rule
+ /// that went is named with the construct that stopped it.
+ pub allow_partial: Option<bool>,
+}
+
#[derive(Deserialize, JsonSchema)]
pub struct OntoReasonInput {
/// Reasoning profile: rdfs (default), owl-rl
diff --git a/src/lib.rs b/src/lib.rs
index a65dec7a..6e9ac55c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -64,6 +64,9 @@ pub mod plugins;
pub mod poincare;
pub mod reason;
pub mod reason_incremental;
+/// Standard rule syntaxes (SWRL, RIF Core) into the Horn rule table
+/// `reason::run_horn` evaluates and `lean/`'s `oo-horn` checks.
+pub mod rulesyntax;
pub mod registry;
pub mod repo;
pub mod runtime;
diff --git a/src/main.rs b/src/main.rs
index 25f5932c..e0a9f84f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -443,6 +443,38 @@ enum Commands {
#[arg(long)]
rules: Option<String>,
},
+ /// 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,
+ },
/// Full pipeline: ingest → SHACL → reason
Extend {
data_path: String,
@@ -645,6 +677,24 @@ impl Commands {
}
cmd("reason", 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::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),
Commands::Status => cmd("status", vec![]),
Commands::Pull { url, sparql, query } => {
@@ -2357,6 +2407,20 @@ async fn async_main() -> anyhow::Result<()> {
};
output_result_checked(&result, cli.pretty);
}
+ Commands::RulesImport { from, file, out, allow_partial } => {
+ let (_db, graph) = setup(&cli.data_dir)?;
+ let result = open_ontologies::rulesyntax::run_import(
+ &graph,
+ &from,
+ file.as_deref().map(std::path::Path::new),
+ out.as_deref().map(std::path::Path::new),
+ allow_partial,
+ )
+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string());
+ // A refused rule puts `error` in the response, so an import that
+ // lost anything exits non-zero and a script cannot walk past it.
+ output_result_checked(&result, cli.pretty);
+ }
Commands::Extend {
data_path,
format: _format,
diff --git a/src/rulesyntax.rs b/src/rulesyntax.rs
new file mode 100644
index 00000000..d6e0b187
--- /dev/null
+++ b/src/rulesyntax.rs
@@ -0,0 +1,1422 @@
+//! Standard rule syntaxes read into the Horn rule table the Lean checker takes.
+//!
+//! # The gap this closes
+//!
+//! `lean/OOCert/Horn.lean` accepts a certificate over ANY rule table and
+//! `OOCert.horn_certificate_sound` is proved once for all of them, so decision
+//! 0003 says the logic-programming family — Datalog, RIF Core, SWRL — is
+//! covered. `src/reason.rs` then evaluates a table and writes the certificate.
+//! What neither of them had was a way IN: the only rule syntax anything here
+//! could read was the tab-separated `rules.tsv` the Lean parser happens to use,
+//! which is an internal encoding and not a language anybody writes. A user
+//! holding a SWRL ontology or a RIF Core document could not use any of it.
+//!
+//! This file is the way in. It reads SWRL out of a loaded RDF graph and RIF
+//! Core out of its normative XML syntax, and produces `crate::reason::
+//! RulePattern` values: the same type `reason::run_horn` evaluates and the same
+//! table `oo-horn check` is given.
+//!
+//! # What a front end may never do, and what it therefore does instead
+//!
+//! Both languages say more than a Horn table over triple patterns can. SWRL has
+//! built-in atoms over the data domain, same-individual and different-individual
+//! atoms, and data ranges. RIF Core has equality, external functions and
+//! predicates, local constants and list terms.
+//!
+//! A rule using any of those is REFUSED BY NAME AND COUNTED. It is never
+//! dropped, never approximated, and never turned into the nearest thing that
+//! fits. The reason is the failure this project exists to attack: a rule set
+//! that quietly lost half its rules, evaluated to a fixpoint, and then reported
+//! a certificate that checks green is assurance laundering with a proof
+//! attached. The certificate would be perfectly sound — about a rule set nobody
+//! wrote.
+//!
+//! So the default is that ONE refused rule fails the whole import and no table
+//! is written. `allow_partial` is the opt-in, and a partial import carries
+//! `certifies_a_weaker_rule_set: true`, a per-construct census and a per-rule
+//! list of what went, in the vocabulary `src/tableaux.rs` already uses for the
+//! constructs its model certificates do not cover.
+//!
+//! # The verdict, which is why this is safe to build at all
+//!
+//! Every rule this file produces is a rule a USER wrote. Nothing discharges it
+//! against the RDF semantics, so a certificate over such a table earns
+//! `entailed_under_supplied_rules` and names `OOCert.horn_certificate_sound`:
+//! true in every model of the asserted graph THAT ALSO SATISFIES THOSE RULES. A
+//! SWRL rule reading "every supplier is compliant" makes certificates that check
+//! green for ever, and the certificate certifies the inference and never the
+//! premises.
+//!
+//! `oo-horn` decides that by comparing the table it is given against
+//! `Builtin.asHorn`, line for line, names included. Every rule emitted here is
+//! named `swrl/…` or `rif/…` and no built-in rule is, so a table out of this
+//! file can never BE the built-in table and can never earn the absolute
+//! verdict. That is a structural property of the naming and not an observation
+//! about the tables anyone has tried; `a_swrl_rule_never_earns_the_absolute_verdict`
+//! and `a_rif_rule_never_earns_the_absolute_verdict` pin it end to end, and
+//! `no_front_end_can_name_a_rule_the_way_a_built_in_is_named` pins the naming
+//! itself without needing Lean present.
+//!
+//! This file states no verdict of its own, for the reason `run_horn` gives: a
+//! second place that pronounces is a second place the two verdicts can be
+//! confused. What it reports is which of the two a table of its making is
+//! ELIGIBLE for, which is a fact about provenance and not a judgement on a
+//! certificate.
+
+use crate::reason::{AtomPat, Pat, RulePattern, parse_rules, rules_tsv};
+use crate::tableaux::TripleIndex;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+// ── Vocabulary ──────────────────────────────────────────────────────────────
+
+const RDF_TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
+const RDFS_SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
+const RDF_NIL: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";
+const RDF_PLAIN_LITERAL: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral";
+
+macro_rules! swrl {
+ ($local:literal) => {
+ concat!("<http://www.w3.org/2003/11/swrl#", $local, ">")
+ };
+}
+
+const SWRL_IMP: &str = swrl!("Imp");
+const SWRL_BODY: &str = swrl!("body");
+const SWRL_HEAD: &str = swrl!("head");
+const SWRL_VARIABLE: &str = swrl!("Variable");
+const SWRL_CLASS_ATOM: &str = swrl!("ClassAtom");
+const SWRL_INDIVIDUAL_PROPERTY_ATOM: &str = swrl!("IndividualPropertyAtom");
+const SWRL_DATAVALUED_PROPERTY_ATOM: &str = swrl!("DatavaluedPropertyAtom");
+const SWRL_SAME_INDIVIDUAL_ATOM: &str = swrl!("SameIndividualAtom");
+const SWRL_DIFFERENT_INDIVIDUALS_ATOM: &str = swrl!("DifferentIndividualsAtom");
+const SWRL_BUILTIN_ATOM: &str = swrl!("BuiltinAtom");
+const SWRL_DATA_RANGE_ATOM: &str = swrl!("DataRangeAtom");
+const SWRL_CLASS_PREDICATE: &str = swrl!("classPredicate");
+const SWRL_PROPERTY_PREDICATE: &str = swrl!("propertyPredicate");
+const SWRL_ARGUMENT1: &str = swrl!("argument1");
+const SWRL_ARGUMENT2: &str = swrl!("argument2");
+const SWRL_BUILTIN: &str = swrl!("builtin");
+
+const RIF_NS: &str = "http://www.w3.org/2007/rif#";
+const RIF_IRI_TYPE: &str = "http://www.w3.org/2007/rif#iri";
+const RIF_LOCAL_TYPE: &str = "http://www.w3.org/2007/rif#local";
+
+/// The prose both the docs and every tool response quote, so the supported
+/// fragment is stated in exactly one place and cannot drift between them.
+pub const SWRL_FRAGMENT: &str = "SWRL rules encoded in RDF (swrl:Imp with swrl:body and swrl:head \
+ as rdf:List atom lists), restricted to the three atom forms that ARE triple patterns: \
+ swrl:ClassAtom over a NAMED class (arg1 rdf:type C), swrl:IndividualPropertyAtom (arg1 P \
+ arg2) and swrl:DatavaluedPropertyAtom (arg1 P literal-or-variable), with arguments that are \
+ swrl:Variable instances, IRIs or literals. A head of n atoms becomes n rules, which is the \
+ standard split of a conjunctive consequent and is reported. Everything else is refused";
+
+pub const RIF_FRAGMENT: &str = "RIF Core in the normative XML syntax (the presentation syntax is \
+ NOT read), restricted to Forall/Implies rules and ground facts whose conditions and \
+ conclusions are Frame, Member, Subclass, or Atom of arity 1 or 2. Frame(o p v) is the \
+ triple (o p v); Member(i c) is (i rdf:type c); Subclass(a b) is (a rdfs:subClassOf b); a \
+ binary Atom p(a b) is (a p b) and a unary Atom p(a) is (a rdf:type p), which reads a RIF \
+ predicate as an RDF property or class and is a CONVENTION, not part of RIF. Exists is \
+ accepted in the condition only, where dropping the quantifier is equivalent. And in the \
+ conclusion, and a multi-slot Frame in it, become several rules. Everything else is refused";
+
+// ── Results ─────────────────────────────────────────────────────────────────
+
+/// One source rule, or one whole document, that could not be represented.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Refusal {
+ /// The rule as the source identifies it.
+ pub rule: String,
+ /// The construct responsible, spelled as the source language spells it.
+ pub construct: String,
+ /// Why a Horn table over triple patterns cannot hold it.
+ pub why: String,
+}
+
+/// What a front end made of a source document.
+#[derive(Debug, Clone, Default)]
+pub struct Import {
+ pub syntax: &'static str,
+ pub fragment: &'static str,
+ /// Rules found in the source, refused ones included.
+ pub source_rules: usize,
+ pub rules: Vec<RulePattern>,
+ pub refused: Vec<Refusal>,
+ /// Source rules whose conclusion was a conjunction and so became several
+ /// rules. Reported because it makes `rules.len()` exceed `source_rules`
+ /// legitimately, and a reader comparing the two deserves to know why.
+ pub head_splits: usize,
+ /// Things true of this import that are neither a rule nor a refusal.
+ pub notes: Vec<String>,
+}
+
+impl Import {
+ fn new(syntax: &'static str, fragment: &'static str) -> Self {
+ Self { syntax, fragment, ..Default::default() }
+ }
+
+ fn refuse(&mut self, rule: &str, construct: &str, why: impl Into<String>) {
+ self.refused.push(Refusal {
+ rule: rule.to_string(),
+ construct: construct.to_string(),
+ why: why.into(),
+ });
+ }
+
+ /// Accept one rule, but only after it has survived the exact round trip the
+ /// certificate depends on: rendered to a `rules.tsv` line and read back by
+ /// `crate::reason::parse_rules`, which is the parser `run_horn` will use on
+ /// the file this import writes. A rule that does not come back identical is
+ /// refused here rather than written out to fail, or worse to succeed as
+ /// something else, later.
+ ///
+ /// This is also what enforces the two conditions the emitter cannot check
+ /// structurally: a head variable must occur in the body, because the engine
+ /// has nothing to bind it to otherwise, and every constant must be in
+ /// N-Triples spelling, because a constant in any other spelling matches
+ /// nothing and the rule silently never fires.
+ fn accept(&mut self, id: &str, name: String, body: Vec<AtomPat>, head: AtomPat) {
+ let rule = RulePattern { name, body, head };
+ let line = rules_tsv(std::slice::from_ref(&rule));
+ match parse_rules(&line) {
+ Ok(back) if back.len() == 1 && back[0] == rule => self.rules.push(rule),
+ Ok(_) => self.refuse(
+ id,
+ "horn-table",
+ "the rule does not read back as itself from the rules.tsv line this would write, \
+ so the checker would verify steps against a different rule than the one imported",
+ ),
+ Err(e) => self.refuse(id, "horn-table", e.to_string()),
+ }
+ }
+
+ /// Accept a source rule whose conclusion is a conjunction of `heads`, as
+ /// `heads.len()` rules sharing one body. `B -> H1 and H2` and
+ /// `(B -> H1) and (B -> H2)` are the same sentence, so nothing is lost and
+ /// nothing is invented; the count changes, and the count is reported.
+ fn accept_split(&mut self, id: &str, body: Vec<AtomPat>, heads: Vec<AtomPat>) {
+ if heads.len() > 1 {
+ self.head_splits += 1;
+ }
+ let many = heads.len() > 1;
+ for (i, head) in heads.into_iter().enumerate() {
+ let name = if many { format!("{id}#{}", i + 1) } else { id.to_string() };
+ self.accept(id, name, body.clone(), head);
+ }
+ }
+
+ /// A census of the constructs that cost rules, most frequent first, in the
+ /// shape `constructs_not_modelled` uses in the DL model-certificate block.
+ fn construct_census(&self) -> Vec<serde_json::Value> {
+ let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
+ for r in &self.refused {
+ *counts.entry(r.construct.as_str()).or_default() += 1;
+ }
+ let mut rows: Vec<(&str, usize)> = counts.into_iter().collect();
+ rows.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
+ rows.into_iter()
+ .map(|(k, n)| serde_json::json!({"construct": k, "occurrences": n}))
+ .collect()
+ }
+
+ /// The part of a response that is the same whatever the caller does next.
+ fn report(&self) -> serde_json::Value {
+ serde_json::json!({
+ "source_syntax": self.syntax,
+ "supported_fragment": self.fragment,
+ "source_rules": self.source_rules,
+ "rules_emitted": self.rules.len(),
+ "rules_refused": self.refused.len(),
+ "conjunctive_heads_split": self.head_splits,
+ // The name the DL layer uses for the same idea: the artefact is
+ // about FEWER axioms than the source states, and the verdict must
+ // be read against this flag rather than on its own.
+ "certifies_a_weaker_rule_set": !self.refused.is_empty(),
+ "constructs_not_supported": self.construct_census(),
+ "refused": self.refused.iter().map(|r| serde_json::json!({
+ "rule": r.rule,
+ "construct": r.construct,
+ "why": r.why,
+ })).collect::<Vec<_>>(),
+ "not_covered":
+ "a rule outside the fragment above is refused and counted, never approximated. \
+ Where rules_refused is non-zero the emitted table is a WEAKER rule set than the \
+ source document states, and a certificate over it is about that weaker set",
+ "notes": self.notes,
+ // Provenance, not a verdict. Every rule here was written by a user
+ // and discharged by nobody, so the only warrant a certificate over
+ // this table can earn is the relativised one.
+ "verdict_this_table_is_eligible_for": "entailed_under_supplied_rules",
+ "theorem": "OOCert.horn_certificate_sound",
+ "means":
+ "a checked certificate over this table says every conclusion is true in every \
+ model of the asserted graph THAT ALSO SATISFIES THESE RULES. The rules are \
+ assumed and never checked: a rule saying every supplier is compliant produces \
+ certificates that check green for ever",
+ "why_not_the_absolute_verdict":
+ "`entailed` is earned only by a certificate over the BUILT-IN table, which \
+ OOCert.Builtin.asHorn_sound discharges against the RDF semantics. Every rule \
+ emitted here is named swrl/… or rif/… and no built-in rule is, so a table out \
+ of this importer is never that table",
+ "pronounced_by":
+ "lean/, through `oo-horn check`. This importer states no verdict of its own",
+ })
+ }
+}
+
+// ── SWRL ────────────────────────────────────────────────────────────────────
+
+/// Read every `swrl:Imp` out of a loaded graph.
+pub fn swrl_from_graph(graph: &Arc<crate::graph::GraphStore>) -> anyhow::Result<Import> {
+ swrl_from_triples(&graph.all_triples()?)
+}
+
+/// The same, over triples already in hand. Terms are in N-Triples spelling,
+/// which is what `GraphStore::all_triples` produces and what a rule table
+/// holds, so no term is respelled anywhere in this path.
+pub fn swrl_from_triples(triples: &[(String, String, String)]) -> anyhow::Result<Import> {
+ let idx = TripleIndex::new(triples);
+ let mut imp = Import::new("swrl", SWRL_FRAGMENT);
+
+ let mut imps: Vec<&str> = triples
+ .iter()
+ .filter(|(_, p, o)| p == RDF_TYPE && o == SWRL_IMP)
+ .map(|(s, _, _)| s.as_str())
+ .collect();
+ imps.sort_unstable();
+ imps.dedup();
+ imp.source_rules = imps.len();
+
+ for node in imps {
+ let id = format!("swrl/{}", strip_iri(node));
+ // One rule, read in three passes: the atom lists, then the variables
+ // they mention, then the atoms themselves. Variables have to be known
+ // before any atom is built, because what a variable is CALLED depends
+ // on which other variables the same rule uses.
+ let body_nodes = match swrl_atom_list(&idx, node, SWRL_BODY, "swrl:body", &id, &mut imp) {
+ Some(v) => v,
+ None => continue,
+ };
+ let head_nodes = match swrl_atom_list(&idx, node, SWRL_HEAD, "swrl:head", &id, &mut imp) {
+ Some(v) => v,
+ None => continue,
+ };
+ if head_nodes.is_empty() {
+ imp.refuse(
+ &id,
+ "swrl:head of length zero",
+ "a rule with an empty consequent concludes falsity, which is an integrity \
+ constraint and not a Horn rule: it has no head atom to derive",
+ );
+ continue;
+ }
+
+ let mut var_iris: Vec<String> = Vec::new();
+ for n in body_nodes.iter().chain(head_nodes.iter()) {
+ for arg in [SWRL_ARGUMENT1, SWRL_ARGUMENT2] {
+ if let Some(v) = idx.object(n, arg)
+ && is_swrl_variable(&idx, &v)
+ && !var_iris.contains(&v)
+ {
+ var_iris.push(v);
+ }
+ }
+ }
+ let names = variable_names(&var_iris);
+
+ let mut body: Vec<AtomPat> = Vec::new();
+ let mut heads: Vec<AtomPat> = Vec::new();
+ let mut failed = false;
+ for (nodes, target) in [(&body_nodes, &mut body), (&head_nodes, &mut heads)] {
+ for n in nodes {
+ match swrl_atom(&idx, n, &names) {
+ Ok(a) => target.push(a),
+ Err((construct, why)) => {
+ imp.refuse(&id, &construct, why);
+ failed = true;
+ break;
+ }
+ }
+ }
+ if failed {
+ break;
+ }
+ }
+ if failed {
+ continue;
+ }
+
+ if names.is_empty() {
+ // Not an error: a ground rule is a legal SWRL rule. It is also what
+ // a rule whose variables were never typed `swrl:Variable` looks
+ // like, and that one matches nothing and fires never. Saying so
+ // costs a line and catches a whole class of silent no-op.
+ imp.notes.push(format!(
+ "{id} has no variables. That is legal, and it is also what a rule looks like when \
+ its variables were not declared `rdf:type swrl:Variable`, in which case they \
+ were read as individuals and the rule will never fire"
+ ));
+ }
+ imp.accept_split(&id, body, heads);
+ }
+
+ Ok(imp)
+}
+
+/// Read one `rdf:List` of atoms hanging off a `swrl:Imp`. A list that does not
+/// reach `rdf:nil` cleanly refuses the rule: a truncated body is a rule that
+/// fires MORE often than the one the author wrote, which is the one direction
+/// an importer may never take quietly.
+fn swrl_atom_list(
+ idx: &TripleIndex,
+ node: &str,
+ predicate: &str,
+ spelling: &str,
+ id: &str,
+ imp: &mut Import,
+) -> Option<Vec<String>> {
+ let Some(head) = idx.object(node, predicate) else {
+ imp.refuse(id, format!("missing {spelling}").as_str(), format!(
+ "a swrl:Imp needs both {spelling} and its counterpart; this one has no {spelling}, so \
+ there is no rule to read"
+ ));
+ return None;
+ };
+ if head == RDF_NIL {
+ return Some(Vec::new());
+ }
+ let (items, defect) = idx.walk_list_checked(&head);
+ if let Some(d) = defect {
+ imp.refuse(
+ id,
+ format!("malformed {spelling} list").as_str(),
+ format!(
+ "{}. A truncated atom list is a DIFFERENT rule, and in the body it is a weaker \
+ condition that fires more often, so the rule is refused rather than read short",
+ d.describe()
+ ),
+ );
+ return None;
+ }
+ Some(items)
+}
+
+fn is_swrl_variable(idx: &TripleIndex, term: &str) -> bool {
+ idx.objects(term, RDF_TYPE).iter().any(|t| t == SWRL_VARIABLE)
+}
+
+/// One SWRL atom as a triple pattern, or the construct that stopped it.
+fn swrl_atom(
+ idx: &TripleIndex,
+ node: &str,
+ names: &BTreeMap<String, String>,
+) -> Result<AtomPat, (String, String)> {
+ let types = idx.objects(node, RDF_TYPE);
+ let ty = types
+ .iter()
+ .find(|t| {
+ matches!(
+ t.as_str(),
+ SWRL_CLASS_ATOM
+ | SWRL_INDIVIDUAL_PROPERTY_ATOM
+ | SWRL_DATAVALUED_PROPERTY_ATOM
+ | SWRL_SAME_INDIVIDUAL_ATOM
+ | SWRL_DIFFERENT_INDIVIDUALS_ATOM
+ | SWRL_BUILTIN_ATOM
+ | SWRL_DATA_RANGE_ATOM
+ )
+ })
+ .map(String::as_str);
+
+ let arg = |which: &str, spelling: &str| -> Result<Pat, (String, String)> {
+ let Some(v) = idx.object(node, which) else {
+ return Err((
+ format!("missing {spelling}"),
+ format!("the atom {node} has no {spelling}, so one of its positions is unknown"),
+ ));
+ };
+ if is_swrl_variable(idx, &v) {
+ let name = names.get(&v).ok_or_else(|| {
+ (
+ "swrl:Variable".to_string(),
+ format!("the variable {v} was not collected for this rule"),
+ )
+ })?;
+ Ok(Pat::Var(name.clone()))
+ } else {
+ Ok(Pat::Const(v))
+ }
+ };
+
+ match ty {
+ Some(SWRL_CLASS_ATOM) => {
+ let c = named_predicate(idx, node, SWRL_CLASS_PREDICATE, "swrl:classPredicate", "class")?;
+ Ok(AtomPat {
+ s: arg(SWRL_ARGUMENT1, "swrl:argument1")?,
+ p: Pat::Const(RDF_TYPE.to_string()),
+ o: Pat::Const(c),
+ })
+ }
+ Some(SWRL_INDIVIDUAL_PROPERTY_ATOM) | Some(SWRL_DATAVALUED_PROPERTY_ATOM) => {
+ let p = named_predicate(
+ idx,
+ node,
+ SWRL_PROPERTY_PREDICATE,
+ "swrl:propertyPredicate",
+ "property",
+ )?;
+ Ok(AtomPat {
+ s: arg(SWRL_ARGUMENT1, "swrl:argument1")?,
+ p: Pat::Const(p),
+ o: arg(SWRL_ARGUMENT2, "swrl:argument2")?,
+ })
+ }
+ Some(SWRL_BUILTIN_ATOM) => {
+ let b = idx.object(node, SWRL_BUILTIN).unwrap_or_else(|| "?".into());
+ Err((
+ format!("swrl:BuiltinAtom {}", strip_iri(&b)),
+ "a built-in atom is a predicate over the data domain (swrlb:greaterThan, \
+ swrlb:add, swrlb:stringConcat and the rest), computed rather than matched. A \
+ Horn table over triple patterns has no computed predicates: its atoms match \
+ triples that are in the graph. Rewriting the built-in as a triple pattern would \
+ invent a property the graph does not hold and would fire on nothing"
+ .to_string(),
+ ))
+ }
+ Some(SWRL_SAME_INDIVIDUAL_ATOM) => Err((
+ "swrl:SameIndividualAtom".to_string(),
+ "the atom asserts EQUALITY OF INDIVIDUALS in the domain, not the presence of a \
+ triple. Writing it as (a owl:sameAs b) would be a different claim: the checker \
+ matches triples and has no congruence, so nothing downstream would substitute equals \
+ for equals, and in the head it would licence a conclusion the rule does not make"
+ .to_string(),
+ )),
+ Some(SWRL_DIFFERENT_INDIVIDUALS_ATOM) => Err((
+ "swrl:DifferentIndividualsAtom".to_string(),
+ "the atom asserts that two individuals are DISTINCT, which is a negative fact. A Horn \
+ rule's head is one positive atom and its body is a conjunction of positive atoms, so \
+ there is no position in the table for it"
+ .to_string(),
+ )),
+ Some(SWRL_DATA_RANGE_ATOM) => Err((
+ "swrl:DataRangeAtom".to_string(),
+ "the atom tests a value against a data range (a datatype or an enumeration), which is \
+ a condition on the VALUE a literal denotes. The checker compares RDF terms and does \
+ no datatype reasoning, so the test has no triple pattern"
+ .to_string(),
+ )),
+ _ => Err((
+ "unrecognised swrl atom".to_string(),
+ format!(
+ "the node {node} in an atom list is typed {} and is none of swrl:ClassAtom, \
+ swrl:IndividualPropertyAtom or swrl:DatavaluedPropertyAtom. An atom this \
+ importer cannot name is not guessed at",
+ if types.is_empty() { "nothing".to_string() } else { types.join(", ") }
+ ),
+ )),
+ }
+}
+
+/// A `swrl:classPredicate` or `swrl:propertyPredicate` that is a named IRI.
+fn named_predicate(
+ idx: &TripleIndex,
+ node: &str,
+ predicate: &str,
+ spelling: &str,
+ what: &str,
+) -> Result<String, (String, String)> {
+ let Some(v) = idx.object(node, predicate) else {
+ return Err((
+ format!("missing {spelling}"),
+ format!("the atom {node} has no {spelling}, so its {what} is unknown"),
+ ));
+ };
+ if is_swrl_variable(idx, &v) {
+ return Err((
+ format!("variable {spelling}"),
+ format!(
+ "{spelling} is the variable {v}. SWRL requires an IRI there, and a rule that \
+ quantifies over {what}es is not a SWRL rule this importer will invent a reading \
+ for"
+ ),
+ ));
+ }
+ if v.starts_with("_:") {
+ return Err((
+ format!("anonymous {what} expression"),
+ format!(
+ "{spelling} is the blank node {v}, which is an anonymous {what} expression (a \
+ restriction, an intersection, a union). A triple pattern can hold a NAME; it \
+ cannot hold a class expression, and unfolding one would be a different rule"
+ ),
+ ));
+ }
+ if !v.starts_with('<') {
+ return Err((
+ format!("non-IRI {spelling}"),
+ format!("{spelling} is {v}, which is not an IRI"),
+ ));
+ }
+ Ok(v)
+}
+
+/// What to call each variable of one rule.
+///
+/// The local name is what a reader wants to see, and it is only safe when it
+/// identifies the variable. Two variable IRIs in one rule with the same local
+/// name would become ONE variable in the table, which silently joins two
+/// positions the author kept apart: a strictly stronger rule, derived from a
+/// cosmetic choice. So a collision, or a local name that is empty or holds
+/// whitespace, drops the whole rule to full IRIs, which cannot collide.
+fn variable_names(iris: &[String]) -> BTreeMap<String, String> {
+ let locals: Vec<String> = iris.iter().map(|i| local_name(i)).collect();
+ let usable = locals.iter().all(|l| {
+ !l.is_empty() && !l.chars().any(|c| c.is_whitespace()) && locals.iter().filter(|x| *x == l).count() == 1
+ });
+ iris.iter()
+ .enumerate()
+ .map(|(i, iri)| {
+ let name = if usable { locals[i].clone() } else { strip_iri(iri).to_string() };
+ (iri.clone(), name)
+ })
+ .collect()
+}
+
+fn strip_iri(term: &str) -> &str {
+ term.strip_prefix('<').and_then(|t| t.strip_suffix('>')).unwrap_or(term)
+}
+
+fn local_name(term: &str) -> String {
+ let body = strip_iri(term);
+ match body.rfind(['#', '/']) {
+ Some(i) => body[i + 1..].to_string(),
+ None => body.to_string(),
+ }
+}
+
+// ── RIF Core, XML syntax ────────────────────────────────────────────────────
+
+/// A parsed XML element, namespace resolved.
+#[derive(Debug, Default)]
+struct El {
+ /// Local name, the prefix or default namespace stripped.
+ name: String,
+ /// The namespace it resolved to, empty when the document declared none.
+ ns: String,
+ attrs: Vec<(String, String)>,
+ text: String,
+ children: Vec<El>,
+}
+
+impl El {
+ fn child(&self, name: &str) -> Option<&El> {
+ self.children.iter().find(|c| c.name == name)
+ }
+ fn children_named(&self, name: &str) -> Vec<&El> {
+ self.children.iter().filter(|c| c.name == name).collect()
+ }
+ fn attr(&self, name: &str) -> Option<&str> {
+ self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
+ }
+ /// The one element a wrapper such as `<formula>` or `<if>` contains.
+ fn only_child(&self) -> Option<&El> {
+ match self.children.len() {
+ 1 => self.children.first(),
+ _ => None,
+ }
+ }
+ fn in_rif(&self) -> bool {
+ self.ns.is_empty() || self.ns == RIF_NS
+ }
+}
+
+/// Read RIF Core out of its XML syntax.
+pub fn rif_core_from_xml(xml: &str) -> anyhow::Result<Import> {
+ let trimmed = xml.trim_start_matches(['\u{feff}', ' ', '\t', '\r', '\n']);
+ if !trimmed.starts_with('<') {
+ anyhow::bail!(
+ "this is not RIF XML. Only the XML syntax is read, because it is the normative \
+ interchange form; the presentation syntax (`Document( Prefix(...) Group( Forall ?x \
+ ( ... :- ... ) ) )`) is a different grammar and is NOT parsed here. A half-written \
+ parser for it would mis-read rules rather than refuse them, which is the one failure \
+ this importer exists to avoid. Serialise the document to RIF XML and pass that"
+ );
+ }
+ let root = parse_xml(trimmed)?;
+ let mut imp = Import::new("rif-core", RIF_FRAGMENT);
+ if root.ns.is_empty() {
+ imp.notes.push(format!(
+ "the document declares no namespace, so its elements were read by local name alone. \
+ RIF XML puts them in {RIF_NS}"
+ ));
+ }
+ if !root.in_rif() {
+ anyhow::bail!(
+ "the document element <{}> is in the namespace {}, not the RIF namespace {RIF_NS}",
+ root.name,
+ root.ns
+ );
+ }
+ if root.name != "Document" {
+ anyhow::bail!(
+ "the document element is <{}>; a RIF document element is <Document>",
+ root.name
+ );
+ }
+
+ for d in root.children_named("directive") {
+ if let Some(i) = d.child("Import") {
+ let loc = i.child("location").map(|l| l.text.clone()).unwrap_or_default();
+ imp.source_rules += 1;
+ imp.refuse(
+ "rif/document",
+ "rif:Import",
+ format!(
+ "the document imports {} and this importer does not fetch it, so the rule set \
+ it defines is larger than the rules read here",
+ if loc.is_empty() { "another document".into() } else { loc }
+ ),
+ );
+ }
+ }
+
+ let mut sentences: Vec<&El> = Vec::new();
+ for p in root.children_named("payload") {
+ collect_sentences(p, &mut sentences);
+ }
+ imp.source_rules += sentences.len();
+
+ for (i, s) in sentences.into_iter().enumerate() {
+ let id = rif_sentence_id(s, i);
+ match rif_rule(s) {
+ Ok((body, heads)) => {
+ if heads.is_empty() {
+ imp.refuse(
+ &id,
+ "empty conclusion",
+ "the conclusion holds no atom, so there is nothing to derive",
+ );
+ } else {
+ imp.accept_split(&id, body, heads);
+ }
+ }
+ Err((construct, why)) => imp.refuse(&id, &construct, why),
+ }
+ }
+
+ Ok(imp)
+}
+
+/// `payload` holds a `Group`; a `Group` holds `sentence`s, each of which may
+/// hold another `Group`. Flatten to the sentences that are not groups.
+fn collect_sentences<'a>(el: &'a El, out: &mut Vec<&'a El>) {
+ for child in &el.children {
+ match child.name.as_str() {
+ "Group" | "payload" | "sentence" | "formula" => {
+ if child.name == "sentence" || child.name == "formula" {
+ match child.only_child() {
+ Some(inner) if inner.name == "Group" => collect_sentences(inner, out),
+ Some(inner) => out.push(inner),
+ None => out.push(child),
+ }
+ } else {
+ collect_sentences(child, out);
+ }
+ }
+ "id" | "meta" => {}
+ _ => out.push(child),
+ }
+ }
+}
+
+/// A RIF sentence's own name, when it has one.
+///
+/// `<id>` hangs off whichever element carries it, and in practice that is the
+/// `Implies` rather than the `Forall` wrapped around it, so the search walks
+/// down through the wrappers instead of looking only at the top. A refusal list
+/// naming the author's own rule identifiers is worth a few lines here.
+fn rif_sentence_id(s: &El, index: usize) -> String {
+ fn find(el: &El, depth: usize) -> Option<String> {
+ if let Some(id) = el.child("id")
+ && let Some(c) = id.child("Const")
+ && !c.text.is_empty()
+ {
+ return Some(c.text.clone());
+ }
+ if depth == 0 {
+ return None;
+ }
+ el.child("formula").and_then(|f| f.only_child()).and_then(|inner| find(inner, depth - 1))
+ }
+ match find(s, 4) {
+ Some(name) => format!("rif/{name}"),
+ None => format!("rif/sentence{}", index + 1),
+ }
+}
+
+type RifRule = (Vec<AtomPat>, Vec<AtomPat>);
+
+/// One RIF sentence as a body and a list of head atoms.
+fn rif_rule(s: &El) -> Result<RifRule, (String, String)> {
+ if !s.in_rif() {
+ return Err((
+ format!("<{}> in {}", s.name, s.ns),
+ format!("the element is not in the RIF namespace {RIF_NS}"),
+ ));
+ }
+ match s.name.as_str() {
+ // The declared variables are not carried across: a RulePattern
+ // quantifies every variable it mentions, and the condition that
+ // actually matters — a head variable must occur in the body — is
+ // enforced by `parse_rules` when the rule is accepted.
+ "Forall" => {
+ let f = s.child("formula").and_then(|f| f.only_child()).ok_or_else(|| {
+ (
+ "malformed Forall".to_string(),
+ "a Forall needs exactly one <formula> holding one element".to_string(),
+ )
+ })?;
+ rif_rule(f)
+ }
+ "Implies" => {
+ let cond = s.child("if").and_then(|f| f.only_child()).ok_or_else(|| {
+ (
+ "malformed Implies".to_string(),
+ "an Implies needs an <if> holding exactly one element".to_string(),
+ )
+ })?;
+ let conc = s.child("then").and_then(|f| f.only_child()).ok_or_else(|| {
+ (
+ "malformed Implies".to_string(),
+ "an Implies needs a <then> holding exactly one element".to_string(),
+ )
+ })?;
+ Ok((rif_formula(cond, true)?, rif_formula(conc, false)?))
+ }
+ // A bare atomic sentence is a fact: an empty body and a ground head.
+ // `parse_rules` refuses it if the head turns out to hold a variable,
+ // which it should, since there would be nothing to bind it to.
+ "Atom" | "Frame" | "Member" | "Subclass" => Ok((Vec::new(), rif_formula(s, false)?)),
+ other => Err((
+ format!("rif:{other} as a sentence"),
+ format!(
+ "a RIF Core sentence is a Forall, an Implies, or a ground fact; <{other}> is none \
+ of those"
+ ),
+ )),
+ }
+}
+
+/// A RIF condition (`in_condition`) or conclusion, as a conjunction of triple
+/// patterns. The two differ in what they are allowed to hold, so the flag is a
+/// parameter rather than two near-identical functions.
+fn rif_formula(el: &El, in_condition: bool) -> Result<Vec<AtomPat>, (String, String)> {
+ if !el.in_rif() {
+ return Err((
+ format!("<{}> in {}", el.name, el.ns),
+ format!("the element is not in the RIF namespace {RIF_NS}"),
+ ));
+ }
+ match el.name.as_str() {
+ "And" => {
+ let mut out = Vec::new();
+ for f in el.children_named("formula") {
+ let inner = f.only_child().ok_or_else(|| {
+ (
+ "malformed And".to_string(),
+ "each <formula> of an And holds exactly one element".to_string(),
+ )
+ })?;
+ out.extend(rif_formula(inner, in_condition)?);
+ }
+ Ok(out)
+ }
+ "Exists" if in_condition => {
+ // `(exists y. B(x,y)) -> H(x)` and `forall y. B(x,y) -> H(x)` are
+ // the same sentence, so the quantifier is dropped and the variable
+ // simply does not occur in the head. That equivalence holds ONLY on
+ // this side of the arrow.
+ let inner = el.child("formula").and_then(|f| f.only_child()).ok_or_else(|| {
+ (
+ "malformed Exists".to_string(),
+ "an Exists needs one <formula> holding one element".to_string(),
+ )
+ })?;
+ rif_formula(inner, in_condition)
+ }
+ "Exists" => Err((
+ "rif:Exists in the conclusion".to_string(),
+ "an existential conclusion asserts that something exists without naming it. \
+ Representing it needs a Skolem term, which is a NEW constant this importer would \
+ have to invent, and a rule with an invented constant is not the rule that was written"
+ .to_string(),
+ )),
+ "Atom" => rif_atom(el),
+ "Frame" => rif_frame(el),
+ "Member" => {
+ let i = rif_term(el.child("instance").and_then(|c| c.only_child()), "Member/instance")?;
+ let c = rif_term(el.child("class").and_then(|c| c.only_child()), "Member/class")?;
+ Ok(vec![AtomPat { s: i, p: Pat::Const(RDF_TYPE.to_string()), o: c }])
+ }
+ "Subclass" => {
+ let a = rif_term(el.child("sub").and_then(|c| c.only_child()), "Subclass/sub")?;
+ let b = rif_term(el.child("super").and_then(|c| c.only_child()), "Subclass/super")?;
+ Ok(vec![AtomPat { s: a, p: Pat::Const(RDFS_SUBCLASS.to_string()), o: b }])
+ }
+ "Equal" => Err((
+ if in_condition { "rif:Equal in the condition" } else { "rif:Equal in the conclusion" }
+ .to_string(),
+ if in_condition {
+ "an equality in the condition is a guard that two terms denote the same thing. The \
+ checker matches RDF TERMS and has no congruence, so it cannot decide one"
+ } else {
+ "an equality in the conclusion asserts that two terms denote the same thing, which \
+ is not a triple. Deriving it would require every later step to substitute equals \
+ for equals, and the Horn checker does not: a rule table has no equality"
+ }
+ .to_string(),
+ )),
+ "External" => Err((
+ "rif:External".to_string(),
+ "an external term or predicate is computed by a function outside the rule set \
+ (func:numeric-add, pred:literal-not-identical and the rest). A Horn table matches \
+ triples that are in the graph and computes nothing"
+ .to_string(),
+ )),
+ "Or" | "Neg" | "INeg" | "Naf" => Err((
+ format!("rif:{}", el.name),
+ format!(
+ "<{}> is outside RIF Core, which is Horn: a conjunction of positive atoms \
+ implying one positive atom. Disjunction and negation have no place in the table",
+ el.name
+ ),
+ )),
+ other => Err((
+ format!("rif:{other}"),
+ format!("<{other}> is not a RIF Core condition or conclusion this importer reads"),
+ )),
+ }
+}
+
+fn rif_atom(el: &El) -> Result<Vec<AtomPat>, (String, String)> {
+ let op = el.child("op").and_then(|c| c.only_child());
+ let Some(op) = op else {
+ return Err((
+ "malformed Atom".to_string(),
+ "an Atom needs an <op> holding one element".to_string(),
+ ));
+ };
+ if op.name != "Const" {
+ return Err((
+ format!("rif:Atom with a {} predicate", op.name),
+ "the predicate of an Atom must be a Const naming an IRI. A variable or an expression \
+ in predicate position is outside RIF Core"
+ .to_string(),
+ ));
+ }
+ let pred = rif_term(Some(op), "Atom/op")?;
+ let args: Vec<&El> = el.children_named("args").into_iter().flat_map(|a| a.children.iter()).collect();
+ match args.len() {
+ 1 => {
+ let a = rif_term(Some(args[0]), "Atom/args")?;
+ Ok(vec![AtomPat { s: a, p: Pat::Const(RDF_TYPE.to_string()), o: pred }])
+ }
+ 2 => {
+ let a = rif_term(Some(args[0]), "Atom/args")?;
+ let b = rif_term(Some(args[1]), "Atom/args")?;
+ Ok(vec![AtomPat { s: a, p: pred, o: b }])
+ }
+ n => Err((
+ format!("rif:Atom of arity {n}"),
+ format!(
+ "a triple has three positions, so a predicate of arity {n} has no triple pattern. \
+ Arity 1 is read as a class and arity 2 as a property; arity 0 says nothing about \
+ any subject, and arity 3 or more would have to be reified, which is a modelling \
+ decision this importer will not take on the author's behalf"
+ ),
+ )),
+ }
+}
+
+fn rif_frame(el: &El) -> Result<Vec<AtomPat>, (String, String)> {
+ let obj = rif_term(el.child("object").and_then(|c| c.only_child()), "Frame/object")?;
+ let slots = el.children_named("slot");
+ if slots.is_empty() {
+ return Err((
+ "rif:Frame with no slot".to_string(),
+ "a frame with no slot states nothing".to_string(),
+ ));
+ }
+ let mut out = Vec::new();
+ for slot in slots {
+ if slot.children.len() != 2 {
+ return Err((
+ "malformed rif:Frame slot".to_string(),
+ format!(
+ "a <slot> holds exactly two terms, a key and a value; this one holds {}",
+ slot.children.len()
+ ),
+ ));
+ }
+ let k = rif_term(Some(&slot.children[0]), "Frame/slot key")?;
+ let v = rif_term(Some(&slot.children[1]), "Frame/slot value")?;
+ out.push(AtomPat { s: obj.clone(), p: k, o: v });
+ }
+ Ok(out)
+}
+
+/// One RIF term as a pattern position.
+fn rif_term(el: Option<&El>, where_: &str) -> Result<Pat, (String, String)> {
+ let Some(el) = el else {
+ return Err((
+ format!("missing {where_}"),
+ format!("{where_} holds no term"),
+ ));
+ };
+ if !el.in_rif() {
+ return Err((
+ format!("<{}> in {}", el.name, el.ns),
+ format!("the term at {where_} is not in the RIF namespace {RIF_NS}"),
+ ));
+ }
+ match el.name.as_str() {
+ "Var" => {
+ if el.text.is_empty() || el.text.chars().any(|c| c.is_whitespace()) {
+ return Err((
+ "malformed rif:Var".to_string(),
+ format!("the variable name at {where_} is empty or holds whitespace"),
+ ));
+ }
+ Ok(Pat::Var(el.text.clone()))
+ }
+ "Const" => {
+ let Some(ty) = el.attr("type") else {
+ return Err((
+ "rif:Const with no type".to_string(),
+ format!(
+ "the constant at {where_} has no type attribute, so whether it names an \
+ IRI or a literal is unknown"
+ ),
+ ));
+ };
+ match ty {
+ RIF_IRI_TYPE => Ok(Pat::Const(format!("<{}>", el.text))),
+ RIF_LOCAL_TYPE => Err((
+ "rif:local constant".to_string(),
+ format!(
+ "the constant \"{}\" at {where_} is rif:local, which is scoped to the \
+ document and denotes nothing outside it. Giving it an IRI would be \
+ minting a name the document does not have",
+ el.text
+ ),
+ )),
+ RDF_PLAIN_LITERAL => Ok(Pat::Const(plain_literal(&el.text))),
+ dt => Ok(Pat::Const(format!("\"{}\"^^<{dt}>", escape_literal(&el.text)))),
+ }
+ }
+ "Expr" => Err((
+ "rif:Expr".to_string(),
+ format!(
+ "the term at {where_} is a function application. RIF Core is function-free by \
+ definition, and a triple pattern position holds a name or a variable, never a \
+ term to be evaluated"
+ ),
+ )),
+ "External" => Err((
+ "rif:External term".to_string(),
+ format!("the term at {where_} is computed by an external function, and nothing here computes"),
+ )),
+ "List" => Err((
+ "rif:List term".to_string(),
+ format!(
+ "the term at {where_} is a list. A triple position holds one term; an RDF \
+ collection would be several triples and a different graph shape"
+ ),
+ )),
+ other => Err((
+ format!("rif:{other} as a term"),
+ format!("<{other}> at {where_} is not a RIF Core term this importer reads"),
+ )),
+ }
+}
+
+/// `rdf:PlainLiteral` carries its language tag inside the lexical form, after
+/// the last `@`, and an empty tag means no tag at all.
+fn plain_literal(text: &str) -> String {
+ match text.rfind('@') {
+ Some(i) if i + 1 < text.len() => {
+ format!("\"{}\"@{}", escape_literal(&text[..i]), &text[i + 1..])
+ }
+ Some(i) => format!("\"{}\"", escape_literal(&text[..i])),
+ None => format!("\"{}\"", escape_literal(text)),
+ }
+}
+
+/// N-Triples literal escaping. The tab matters twice over: a raw tab in a
+/// literal would split a `rules.tsv` line into extra fields and make the rule
+/// unreadable, and a raw newline would make it two rules.
+fn escape_literal(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '\\' => out.push_str("\\\\"),
+ '"' => out.push_str("\\\""),
+ '\n' => out.push_str("\\n"),
+ '\r' => out.push_str("\\r"),
+ '\t' => out.push_str("\\t"),
+ c => out.push(c),
+ }
+ }
+ out
+}
+
+/// Read the document into `El`s, namespaces resolved.
+///
+/// Entities beyond the five XML predefines and numeric character references are
+/// an error rather than a guess. RIF documents in the wild declare `&rif;` and
+/// `&xs;` in a DOCTYPE, which is not processed here, and reading `&rif;iri` as
+/// the literal six characters would silently turn every IRI constant into a
+/// local one.
+fn parse_xml(xml: &str) -> anyhow::Result<El> {
+ use quick_xml::events::Event;
+ use quick_xml::name::ResolveResult;
+
+ let mut reader = quick_xml::NsReader::from_str(xml);
+ reader.config_mut().trim_text(true);
+ let decoder = reader.decoder();
+
+ let mut stack: Vec<El> = Vec::new();
+ let mut root: Option<El> = None;
+
+ let finish = |stack: &mut Vec<El>, root: &mut Option<El>, el: El| {
+ match stack.last_mut() {
+ Some(parent) => parent.children.push(el),
+ None => *root = Some(el),
+ }
+ };
+
+ loop {
+ let (ns, ev) = reader
+ .read_resolved_event()
+ .map_err(|e| anyhow::anyhow!("the document is not well-formed XML: {e}"))?;
+ let ns = match ns {
+ ResolveResult::Bound(n) => String::from_utf8_lossy(n.as_ref()).into_owned(),
+ _ => String::new(),
+ };
+ match ev {
+ Event::Start(e) => stack.push(start_element(&ns, &e, decoder)?),
+ Event::Empty(e) => {
+ let el = start_element(&ns, &e, decoder)?;
+ finish(&mut stack, &mut root, el);
+ }
+ Event::End(_) => {
+ let el = stack
+ .pop()
+ .ok_or_else(|| anyhow::anyhow!("the document has an unmatched closing tag"))?;
+ finish(&mut stack, &mut root, el);
+ }
+ Event::Text(e) => {
+ let text = e.unescape().map_err(|err| {
+ anyhow::anyhow!(
+ "text content could not be unescaped ({err}). Entities other than the \
+ five XML predefines are not expanded here: a RIF document written \
+ against a DOCTYPE that declares &rif; or &xs; must be serialised with \
+ those expanded"
+ )
+ })?;
+ if let Some(top) = stack.last_mut() {
+ top.text.push_str(text.as_ref());
+ }
+ }
+ Event::CData(e) => {
+ if let Some(top) = stack.last_mut() {
+ top.text.push_str(&String::from_utf8_lossy(e.as_ref()));
+ }
+ }
+ Event::Eof => break,
+ _ => {}
+ }
+ }
+
+ if !stack.is_empty() {
+ anyhow::bail!("the document has {} unclosed element(s)", stack.len());
+ }
+ root.ok_or_else(|| anyhow::anyhow!("the document holds no elements"))
+}
+
+fn start_element(
+ ns: &str,
+ e: &quick_xml::events::BytesStart<'_>,
+ decoder: quick_xml::encoding::Decoder,
+) -> anyhow::Result<El> {
+ let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
+ let mut attrs = Vec::new();
+ for a in e.attributes() {
+ let a = a.map_err(|err| anyhow::anyhow!("attribute of <{name}> is malformed: {err}"))?;
+ let key = String::from_utf8_lossy(a.key.local_name().as_ref()).into_owned();
+ let value = a.decode_and_unescape_value(decoder).map_err(|err| {
+ anyhow::anyhow!(
+ "the {key} attribute of <{name}> could not be unescaped ({err}). Entities other \
+ than the five XML predefines are not expanded here, so a type=\"&rif;iri\" must \
+ be serialised as the full IRI"
+ )
+ })?;
+ attrs.push((key, value.into_owned()));
+ }
+ Ok(El { name, ns: ns.to_string(), attrs, text: String::new(), children: Vec::new() })
+}
+
+// ── The one entry point the CLI and the MCP tool share ──────────────────────
+
+/// Which front end to run.
+pub fn run_import(
+ graph: &Arc<crate::graph::GraphStore>,
+ from: &str,
+ file: Option<&std::path::Path>,
+ out: Option<&std::path::Path>,
+ allow_partial: bool,
+) -> anyhow::Result<String> {
+ let imp = match from {
+ "swrl" => match file {
+ // A rules file that is not the data: loaded into a store of its
+ // own so importing rules never changes what is loaded.
+ Some(p) => {
+ let scratch = Arc::new(crate::graph::GraphStore::new());
+ scratch.load_file(&p.display().to_string()).map_err(|e| {
+ anyhow::anyhow!("cannot read {} as RDF: {e}", p.display())
+ })?;
+ swrl_from_graph(&scratch)?
+ }
+ None => swrl_from_graph(graph)?,
+ },
+ "rif" | "rif-core" => {
+ let Some(p) = file else {
+ anyhow::bail!(
+ "rif needs a file: RIF Core is an XML document, not something held in the RDF \
+ store"
+ );
+ };
+ let xml = std::fs::read_to_string(p)
+ .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", p.display()))?;
+ rif_core_from_xml(&xml)?
+ }
+ other => anyhow::bail!(
+ "unknown rule syntax '{other}'. This reads 'swrl' (out of an RDF graph) and 'rif' \
+ (RIF Core, XML syntax). Datalog has no single standard concrete syntax and is not \
+ offered under that name: a Datalog program IS a rules.tsv table, which \
+ `reason --rules` already takes"
+ ),
+ };
+
+ let mut report = imp.report();
+
+ // The loud half. A refusal fails the import unless the caller has said, in
+ // as many words, that a weaker rule set is what they want. Silence here is
+ // the whole failure mode: a table that lost a rule, evaluated to a
+ // fixpoint, and produced a certificate that checks green is a sound proof
+ // about a rule set nobody wrote.
+ if !imp.refused.is_empty() && !allow_partial {
+ report["error"] = serde_json::json!(format!(
+ "{} of {} rule(s) in this {} document cannot be represented as Horn rules over triple \
+ patterns, so no table was written. Each one is listed under `refused` with the \
+ construct that stopped it. Pass allow_partial to import the rest ANYWAY, which \
+ produces a table that is a WEAKER rule set than the document states and is flagged \
+ as such",
+ imp.refused.len(),
+ imp.source_rules,
+ imp.syntax
+ ));
+ report["rules_written"] = serde_json::json!(false);
+ return Ok(report.to_string());
+ }
+
+ if imp.rules.is_empty() {
+ report["error"] = serde_json::json!(format!(
+ "no rules were imported from this {} document. An empty table derives nothing, so \
+ there is no rule set to write and nothing for `reason --rules` to evaluate",
+ imp.syntax
+ ));
+ report["rules_written"] = serde_json::json!(false);
+ return Ok(report.to_string());
+ }
+
+ let tsv = rules_tsv(&imp.rules);
+ // The same round trip `run_horn` does before it writes a certificate: what
+ // the checker will read must be what this importer built. Each rule already
+ // survived it alone; this catches anything that only goes wrong in company.
+ match parse_rules(&tsv) {
+ Ok(back) if back == imp.rules => {}
+ Ok(_) => anyhow::bail!(
+ "internal: the rule table this importer writes does not read back as the table it \
+ built, so `reason --rules` would evaluate different rules. Refusing to write it"
+ ),
+ Err(e) => anyhow::bail!(
+ "internal: the rule table this importer writes does not parse ({e}). Refusing to \
+ write it"
+ ),
+ }
+
+ let digest = {
+ use sha2::{Digest, Sha256};
+ format!("{:x}", Sha256::digest(tsv.as_bytes()))
+ };
+ report["rules_tsv_sha256"] = serde_json::json!(digest);
+
+ match out {
+ Some(path) => {
+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::write(path, &tsv)?;
+ report["rules_written"] = serde_json::json!(true);
+ report["rules_file"] = serde_json::json!(path.display().to_string());
+ report["next"] = serde_json::json!(format!(
+ "open-ontologies reason --rules {p} --certificate DIR, then cd lean && lake exe \
+ oo-horn check DIR/rules.tsv DIR/asserted.tsv DIR/horn.tsv",
+ p = path.display()
+ ));
+ }
+ None => {
+ report["rules_written"] = serde_json::json!(false);
+ report["rules_tsv"] = serde_json::json!(tsv);
+ report["next"] = serde_json::json!(
+ "write rules_tsv to a file, then `reason --rules FILE --certificate DIR` and \
+ `lake exe oo-horn check` on what that writes"
+ );
+ }
+ }
+ Ok(report.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn triples(ttl: &str) -> Vec<(String, String, String)> {
+ let g = Arc::new(crate::graph::GraphStore::new());
+ g.load_turtle(ttl, None).unwrap();
+ g.all_triples().unwrap()
+ }
+
+ const PREFIXES: &str = r#"
+ @prefix : <http://ex.org/> .
+ @prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+ @prefix var: <urn:swrl#> .
+ "#;
+
+ #[test]
+ fn a_class_atom_becomes_an_rdf_type_pattern() {
+ let imp = swrl_from_triples(&triples(&format!(
+ r#"{PREFIXES}
+ var:x a swrl:Variable .
+ [] a swrl:Imp ;
+ swrl:body ( [ a swrl:ClassAtom ; swrl:classPredicate :Supplier ; swrl:argument1 var:x ] ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :Compliant ; swrl:argument1 var:x ] ) ."#
+ )))
+ .unwrap();
+ assert!(imp.refused.is_empty(), "{:?}", imp.refused);
+ assert_eq!(imp.rules.len(), 1);
+ let r = &imp.rules[0];
+ assert_eq!(r.body.len(), 1);
+ assert_eq!(r.body[0].p, Pat::Const(RDF_TYPE.to_string()));
+ assert_eq!(r.body[0].s, Pat::Var("x".into()));
+ assert_eq!(r.head.o, Pat::Const("<http://ex.org/Compliant>".into()));
+ }
+
+ #[test]
+ fn a_built_in_atom_is_refused_by_name() {
+ let imp = swrl_from_triples(&triples(&format!(
+ r#"{PREFIXES}
+ @prefix swrlb: <http://www.w3.org/2003/11/swrlb#> .
+ var:x a swrl:Variable . var:n a swrl:Variable .
+ [] a swrl:Imp ;
+ swrl:body ( [ a swrl:BuiltinAtom ; swrl:builtin swrlb:greaterThan ] ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :Big ; swrl:argument1 var:x ] ) ."#
+ )))
+ .unwrap();
+ assert_eq!(imp.rules.len(), 0);
+ assert_eq!(imp.refused.len(), 1);
+ assert!(imp.refused[0].construct.contains("swrlb#greaterThan"), "{:?}", imp.refused[0]);
+ }
+
+ #[test]
+ fn a_conjunctive_head_becomes_several_rules_and_says_so() {
+ let imp = swrl_from_triples(&triples(&format!(
+ r#"{PREFIXES}
+ var:x a swrl:Variable .
+ [] a swrl:Imp ;
+ swrl:body ( [ a swrl:ClassAtom ; swrl:classPredicate :A ; swrl:argument1 var:x ] ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :B ; swrl:argument1 var:x ]
+ [ a swrl:ClassAtom ; swrl:classPredicate :C ; swrl:argument1 var:x ] ) ."#
+ )))
+ .unwrap();
+ assert!(imp.refused.is_empty(), "{:?}", imp.refused);
+ assert_eq!(imp.rules.len(), 2);
+ assert_eq!(imp.head_splits, 1);
+ assert_eq!(imp.source_rules, 1);
+ }
+
+ #[test]
+ fn colliding_local_names_fall_back_to_full_iris_rather_than_join_two_variables() {
+ // `urn:a#x` and `urn:b#x` are different variables with the same local
+ // name. Calling both `?x` would make them ONE variable and silently
+ // strengthen the rule into one that joins two positions the author kept
+ // apart.
+ let t = triples(&format!(
+ r#"{PREFIXES}
+ @prefix a: <urn:a#> . @prefix b: <urn:b#> .
+ a:x a swrl:Variable . b:x a swrl:Variable .
+ [] a swrl:Imp ;
+ swrl:body ( [ a swrl:IndividualPropertyAtom ; swrl:propertyPredicate :p ;
+ swrl:argument1 a:x ; swrl:argument2 b:x ] ) ;
+ swrl:head ( [ a swrl:IndividualPropertyAtom ; swrl:propertyPredicate :q ;
+ swrl:argument1 a:x ; swrl:argument2 b:x ] ) ."#
+ ));
+ let imp = swrl_from_triples(&t).unwrap();
+ assert!(imp.refused.is_empty(), "{:?}", imp.refused);
+ let r = &imp.rules[0];
+ assert_eq!(r.body[0].s, Pat::Var("urn:a#x".into()));
+ assert_eq!(r.body[0].o, Pat::Var("urn:b#x".into()));
+ }
+
+ #[test]
+ fn a_literal_holding_a_tab_is_escaped_rather_than_splitting_the_line() {
+ // A raw tab inside a rule would add fields to the `rules.tsv` line and
+ // a raw newline would make it two rules.
+ assert_eq!(escape_literal("a\tb\nc\"d\\e"), "a\\tb\\nc\\\"d\\\\e");
+ }
+
+ #[test]
+ fn the_presentation_syntax_is_refused_rather_than_guessed_at() {
+ let e = rif_core_from_xml("Document( Group( Forall ?x ( p(?x) :- q(?x) ) ) )").unwrap_err();
+ assert!(e.to_string().contains("presentation syntax"), "{e}");
+ }
+
+ #[test]
+ fn a_rif_frame_is_a_triple_and_equality_in_the_head_is_refused() {
+ let xml = r#"<Document xmlns="http://www.w3.org/2007/rif#"><payload><Group>
+ <sentence><Forall><declare><Var>x</Var></declare><formula><Implies>
+ <if><Frame><object><Var>x</Var></object>
+ <slot><Const type="http://www.w3.org/2007/rif#iri">http://ex.org/p</Const>
+ <Const type="http://www.w3.org/2007/rif#iri">http://ex.org/o</Const></slot>
+ </Frame></if>
+ <then><Frame><object><Var>x</Var></object>
+ <slot><Const type="http://www.w3.org/2007/rif#iri">http://ex.org/q</Const>
+ <Const type="http://www.w3.org/2007/rif#iri">http://ex.org/o</Const></slot>
+ </Frame></then>
+ </Implies></formula></Forall></sentence>
+ <sentence><Forall><declare><Var>y</Var></declare><formula><Implies>
+ <if><Member><instance><Var>y</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://ex.org/C</Const></class></Member></if>
+ <then><Equal><left><Var>y</Var></left>
+ <right><Const type="http://www.w3.org/2007/rif#iri">http://ex.org/a</Const></right></Equal></then>
+ </Implies></formula></Forall></sentence>
+ </Group></payload></Document>"#;
+ let imp = rif_core_from_xml(xml).unwrap();
+ assert_eq!(imp.source_rules, 2);
+ assert_eq!(imp.rules.len(), 1);
+ assert_eq!(imp.rules[0].body[0].p, Pat::Const("<http://ex.org/p>".into()));
+ assert_eq!(imp.refused.len(), 1);
+ assert_eq!(imp.refused[0].construct, "rif:Equal in the conclusion");
+ }
+}
diff --git a/src/server.rs b/src/server.rs
index 9dff0247..b5b80371 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1922,6 +1922,18 @@ 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_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;
@@ -2890,6 +2902,6 @@ impl OpenOntologiesServer {
impl ServerHandler for OpenOntologiesServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().enable_prompts().build())
- .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 109 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 109 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")
+ .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 110 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 110 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")
}
}
diff --git a/src/tableaux.rs b/src/tableaux.rs
index b77c4bc8..be05087b 100644
--- a/src/tableaux.rs
+++ b/src/tableaux.rs
@@ -216,12 +216,58 @@ impl Interner {
// ── Triple Index ────────────────────────────────────────────────────────
-struct TripleIndex {
+/// A by-subject view of a graph, with the one RDF list reader this crate has.
+///
+/// `pub(crate)` rather than private because `rulesyntax.rs` reads SWRL atom
+/// lists, which are `rdf:List`s exactly as `owl:intersectionOf`'s operand list
+/// is. A second traversal of `rdf:first`/`rdf:rest` would be a second thing to
+/// keep right; there is one, and `walk_list_checked` is it.
+pub(crate) struct TripleIndex {
by_subject: HashMap<String, Vec<(String, String)>>,
}
+/// Why a traversal of an `rdf:List` did not reach `rdf:nil`.
+///
+/// `walk_list` drops this, which is right for the DL parser: a malformed
+/// `owl:intersectionOf` list yields a shorter conjunction, the reasoner derives
+/// less, and deriving less is the sound direction. It is NOT right for a rule
+/// importer, where a truncated body is a DIFFERENT RULE that fires more often
+/// than the one the user wrote. So the defect is returned and the caller
+/// decides.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum ListDefect {
+ /// A cell with no `rdf:first`. Its position in the list is lost.
+ NoFirst(String),
+ /// A cell with no `rdf:rest`, so the list never reaches `rdf:nil`.
+ Unterminated(String),
+ /// Still walking after `MAX_LIST_CELLS` cells: a cycle, or a list longer
+ /// than anything this reads.
+ TooLong,
+}
+
+impl ListDefect {
+ pub(crate) fn describe(&self) -> String {
+ match self {
+ ListDefect::NoFirst(cell) => {
+ format!("the list cell {cell} has no rdf:first, so an element is missing")
+ }
+ ListDefect::Unterminated(cell) => format!(
+ "the list cell {cell} has no rdf:rest, so the list never reaches rdf:nil and its \
+ remaining elements are unknown"
+ ),
+ ListDefect::TooLong => format!(
+ "the list did not reach rdf:nil within {MAX_LIST_CELLS} cells, which means a \
+ cycle through rdf:rest or a list longer than this reads"
+ ),
+ }
+ }
+}
+
+/// The cell budget both list readers share.
+pub(crate) const MAX_LIST_CELLS: usize = 1000;
+
impl TripleIndex {
- fn new(triples: &[(String, String, String)]) -> Self {
+ pub(crate) fn new(triples: &[(String, String, String)]) -> Self {
let mut by_subject: HashMap<String, Vec<(String, String)>> = HashMap::new();
for (s, p, o) in triples {
by_subject
@@ -232,7 +278,7 @@ impl TripleIndex {
Self { by_subject }
}
- fn objects(&self, subject: &str, predicate: &str) -> Vec<String> {
+ pub(crate) fn objects(&self, subject: &str, predicate: &str) -> Vec<String> {
self.by_subject
.get(subject)
.map(|pairs| {
@@ -245,26 +291,46 @@ impl TripleIndex {
.unwrap_or_default()
}
- fn object(&self, subject: &str, predicate: &str) -> Option<String> {
+ pub(crate) fn object(&self, subject: &str, predicate: &str) -> Option<String> {
self.objects(subject, predicate).into_iter().next()
}
- fn walk_list(&self, head: &str) -> Vec<String> {
+ /// Walk an `rdf:List`, reporting the FIRST thing that stopped it reaching
+ /// `rdf:nil` cleanly. The items are gathered exactly as `walk_list` has
+ /// always gathered them, so the two readings differ only in what they SAY,
+ /// never in what they collect.
+ pub(crate) fn walk_list_checked(&self, head: &str) -> (Vec<String>, Option<ListDefect>) {
let mut items = Vec::new();
+ let mut defect: Option<ListDefect> = None;
let mut current = head.to_string();
- for _ in 0..1000 {
+ for _ in 0..MAX_LIST_CELLS {
if current == RDF_NIL {
- break;
+ return (items, defect);
}
- if let Some(first) = self.object(&current, RDF_FIRST) {
- items.push(first);
+ match self.object(&current, RDF_FIRST) {
+ Some(first) => items.push(first),
+ // Skipped, not fatal: that is what this reader has always done.
+ None => {
+ defect.get_or_insert_with(|| ListDefect::NoFirst(current.clone()));
+ }
}
match self.object(&current, RDF_REST) {
Some(rest) => current = rest,
- None => break,
+ None => {
+ defect.get_or_insert(ListDefect::Unterminated(current));
+ return (items, defect);
+ }
}
}
- items
+ (items, Some(defect.unwrap_or(ListDefect::TooLong)))
+ }
+
+ /// The DL parser's reading: take what there is and say nothing about a
+ /// malformed tail. A short `owl:intersectionOf` list yields a smaller
+ /// conjunction and the reasoner derives less, which is the sound direction
+ /// there. Behaviour is unchanged.
+ fn walk_list(&self, head: &str) -> Vec<String> {
+ self.walk_list_checked(head).0
}
}
diff --git a/tests/fixtures/rules/family.ttl b/tests/fixtures/rules/family.ttl
new file mode 100644
index 00000000..30a8adb8
--- /dev/null
+++ b/tests/fixtures/rules/family.ttl
@@ -0,0 +1,8 @@
+# The data the imported rules run over. Deliberately small: two facts that fire
+# the uncle rule and one that fires the supplier rule, so a certificate over the
+# imported table has something in it and the derived triples can be named.
+@prefix : <http://example.org/family#> .
+
+:john :hasParent :sue .
+:sue :hasBrother :bob .
+:acme a :Supplier .
diff --git a/tests/fixtures/rules/family_rif.xml b/tests/fixtures/rules/family_rif.xml
new file mode 100644
index 00000000..d1b12bba
--- /dev/null
+++ b/tests/fixtures/rules/family_rif.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ The same two rules as family_swrl.ttl, written in RIF Core's XML syntax.
+
+ Entity references are expanded: this importer does not process a DOCTYPE, and
+ reading `&rif;iri` as six literal characters would silently turn every IRI
+ constant into a local one. An unexpanded entity is an error here, not a guess.
+
+ The first rule uses Frame, which is the RIF construct that IS an RDF triple.
+ The second uses Member, which is rdf:type.
+-->
+<Document xmlns="http://www.w3.org/2007/rif#">
+ <payload>
+ <Group>
+
+ <sentence>
+ <Forall>
+ <declare><Var>x</Var></declare>
+ <declare><Var>y</Var></declare>
+ <declare><Var>z</Var></declare>
+ <formula>
+ <Implies>
+ <id><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#uncle</Const></id>
+ <if>
+ <And>
+ <formula>
+ <Frame>
+ <object><Var>x</Var></object>
+ <slot ordered="yes">
+ <Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#hasParent</Const>
+ <Var>y</Var>
+ </slot>
+ </Frame>
+ </formula>
+ <formula>
+ <Frame>
+ <object><Var>y</Var></object>
+ <slot ordered="yes">
+ <Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#hasBrother</Const>
+ <Var>z</Var>
+ </slot>
+ </Frame>
+ </formula>
+ </And>
+ </if>
+ <then>
+ <Frame>
+ <object><Var>x</Var></object>
+ <slot ordered="yes">
+ <Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#hasUncle</Const>
+ <Var>z</Var>
+ </slot>
+ </Frame>
+ </then>
+ </Implies>
+ </formula>
+ </Forall>
+ </sentence>
+
+ <sentence>
+ <Forall>
+ <declare><Var>x</Var></declare>
+ <formula>
+ <Implies>
+ <id><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#every-supplier-is-compliant</Const></id>
+ <if>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Supplier</Const></class>
+ </Member>
+ </if>
+ <then>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Compliant</Const></class>
+ </Member>
+ </then>
+ </Implies>
+ </formula>
+ </Forall>
+ </sentence>
+
+ </Group>
+ </payload>
+</Document>
diff --git a/tests/fixtures/rules/family_rif_external.xml b/tests/fixtures/rules/family_rif_external.xml
new file mode 100644
index 00000000..f39ffff8
--- /dev/null
+++ b/tests/fixtures/rules/family_rif_external.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ A rule using an External predicate. `pred:numeric-greater-than` is computed by
+ a function outside the rule set; a Horn table matches triples that are in the
+ graph and computes nothing. The RIF counterpart of a SWRL built-in atom.
+-->
+<Document xmlns="http://www.w3.org/2007/rif#">
+ <payload>
+ <Group>
+ <sentence>
+ <Forall>
+ <declare><Var>x</Var></declare>
+ <declare><Var>n</Var></declare>
+ <formula>
+ <Implies>
+ <id><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#adults-only</Const></id>
+ <if>
+ <And>
+ <formula>
+ <Frame>
+ <object><Var>x</Var></object>
+ <slot ordered="yes">
+ <Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#age</Const>
+ <Var>n</Var>
+ </slot>
+ </Frame>
+ </formula>
+ <formula>
+ <External>
+ <content>
+ <Atom>
+ <op><Const type="http://www.w3.org/2007/rif#iri">http://www.w3.org/2007/rif-builtin-predicate#numeric-greater-than</Const></op>
+ <args ordered="yes">
+ <Var>n</Var>
+ <Const type="http://www.w3.org/2001/XMLSchema#integer">17</Const>
+ </args>
+ </Atom>
+ </content>
+ </External>
+ </formula>
+ </And>
+ </if>
+ <then>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Adult</Const></class>
+ </Member>
+ </then>
+ </Implies>
+ </formula>
+ </Forall>
+ </sentence>
+ </Group>
+ </payload>
+</Document>
diff --git a/tests/fixtures/rules/family_rif_head_equality.xml b/tests/fixtures/rules/family_rif_head_equality.xml
new file mode 100644
index 00000000..93e27f84
--- /dev/null
+++ b/tests/fixtures/rules/family_rif_head_equality.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ A rule whose conclusion is not a permitted form: an Equal in the `then`.
+
+ Deriving an equality would require every later step to substitute equals for
+ equals. The Horn checker matches RDF terms and has no congruence, so a table
+ cannot hold it. The second rule is representable, so a partial import has
+ something to keep.
+-->
+<Document xmlns="http://www.w3.org/2007/rif#">
+ <payload>
+ <Group>
+
+ <sentence>
+ <Forall>
+ <declare><Var>x</Var></declare>
+ <formula>
+ <Implies>
+ <id><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#one-true-supplier</Const></id>
+ <if>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Supplier</Const></class>
+ </Member>
+ </if>
+ <then>
+ <Equal>
+ <left><Var>x</Var></left>
+ <right><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#acme</Const></right>
+ </Equal>
+ </then>
+ </Implies>
+ </formula>
+ </Forall>
+ </sentence>
+
+ <sentence>
+ <Forall>
+ <declare><Var>x</Var></declare>
+ <formula>
+ <Implies>
+ <id><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#supplier</Const></id>
+ <if>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Supplier</Const></class>
+ </Member>
+ </if>
+ <then>
+ <Member>
+ <instance><Var>x</Var></instance>
+ <class><Const type="http://www.w3.org/2007/rif#iri">http://example.org/family#Compliant</Const></class>
+ </Member>
+ </then>
+ </Implies>
+ </formula>
+ </Forall>
+ </sentence>
+
+ </Group>
+ </payload>
+</Document>
diff --git a/tests/fixtures/rules/family_rif_presentation.rifps b/tests/fixtures/rules/family_rif_presentation.rifps
new file mode 100644
index 00000000..7d6ee3d4
--- /dev/null
+++ b/tests/fixtures/rules/family_rif_presentation.rifps
@@ -0,0 +1,11 @@
+(* The presentation syntax, which this importer does NOT read. It is a
+ different grammar, and a half-written parser for it would mis-read rules
+ rather than refuse them. *)
+Document(
+ Prefix(fam <http://example.org/family#>)
+ Group(
+ Forall ?x ?y ?z (
+ ?x[fam:hasUncle -> ?z] :- And( ?x[fam:hasParent -> ?y] ?y[fam:hasBrother -> ?z] )
+ )
+ )
+)
diff --git a/tests/fixtures/rules/family_swrl.ttl b/tests/fixtures/rules/family_swrl.ttl
new file mode 100644
index 00000000..2bb9b622
--- /dev/null
+++ b/tests/fixtures/rules/family_swrl.ttl
@@ -0,0 +1,33 @@
+# Two SWRL rules in the RDF encoding, the form a SWRL rule takes inside an OWL
+# ontology: swrl:Imp with swrl:body and swrl:head as rdf:List atom lists.
+#
+# The second rule is the one decision 0003 warns about. It is a perfectly valid
+# SWRL rule, it is assumed and never checked, and a certificate over a table
+# containing it checks green for ever. That is why a table out of this importer
+# can only earn `entailed_under_supplied_rules`.
+@prefix : <http://example.org/family#> .
+@prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+@prefix var: <urn:swrl#> .
+
+var:x a swrl:Variable .
+var:y a swrl:Variable .
+var:z a swrl:Variable .
+
+:uncle a swrl:Imp ;
+ swrl:body (
+ [ a swrl:IndividualPropertyAtom ;
+ swrl:propertyPredicate :hasParent ;
+ swrl:argument1 var:x ; swrl:argument2 var:y ]
+ [ a swrl:IndividualPropertyAtom ;
+ swrl:propertyPredicate :hasBrother ;
+ swrl:argument1 var:y ; swrl:argument2 var:z ]
+ ) ;
+ swrl:head (
+ [ a swrl:IndividualPropertyAtom ;
+ swrl:propertyPredicate :hasUncle ;
+ swrl:argument1 var:x ; swrl:argument2 var:z ]
+ ) .
+
+:every-supplier-is-compliant a swrl:Imp ;
+ swrl:body ( [ a swrl:ClassAtom ; swrl:classPredicate :Supplier ; swrl:argument1 var:x ] ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :Compliant ; swrl:argument1 var:x ] ) .
diff --git a/tests/fixtures/rules/family_swrl_builtin.ttl b/tests/fixtures/rules/family_swrl_builtin.ttl
new file mode 100644
index 00000000..e350e891
--- /dev/null
+++ b/tests/fixtures/rules/family_swrl_builtin.ttl
@@ -0,0 +1,28 @@
+# A SWRL rule using a built-in atom. `swrlb:greaterThan` is a predicate over the
+# data domain, computed rather than matched, and a Horn table over triple
+# patterns has no computed predicates. The whole import fails on it unless
+# allow_partial is passed.
+@prefix : <http://example.org/family#> .
+@prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+@prefix swrlb: <http://www.w3.org/2003/11/swrlb#> .
+@prefix var: <urn:swrl#> .
+
+var:x a swrl:Variable .
+var:n a swrl:Variable .
+
+:adults-only a swrl:Imp ;
+ swrl:body (
+ [ a swrl:DatavaluedPropertyAtom ;
+ swrl:propertyPredicate :age ;
+ swrl:argument1 var:x ; swrl:argument2 var:n ]
+ [ a swrl:BuiltinAtom ;
+ swrl:builtin swrlb:greaterThan ;
+ swrl:arguments ( var:n 17 ) ]
+ ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :Adult ; swrl:argument1 var:x ] ) .
+
+# A second rule that IS representable, so the partial import has something to
+# keep and the weaker-rule-set flag has something to be weaker than.
+:supplier a swrl:Imp ;
+ swrl:body ( [ a swrl:ClassAtom ; swrl:classPredicate :Supplier ; swrl:argument1 var:x ] ) ;
+ swrl:head ( [ a swrl:ClassAtom ; swrl:classPredicate :Compliant ; swrl:argument1 var:x ] ) .
diff --git a/tests/fixtures/rules/family_swrl_empty_head.ttl b/tests/fixtures/rules/family_swrl_empty_head.ttl
new file mode 100644
index 00000000..810be91d
--- /dev/null
+++ b/tests/fixtures/rules/family_swrl_empty_head.ttl
@@ -0,0 +1,13 @@
+# A rule whose head is not a permitted form: an empty consequent. In SWRL that
+# is an integrity constraint (the body must never hold); a Horn rule has exactly
+# one head atom and there is nothing here to derive.
+@prefix : <http://example.org/family#> .
+@prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+@prefix var: <urn:swrl#> .
+
+var:x a swrl:Variable .
+
+:no-supplier-is-banned a swrl:Imp ;
+ swrl:body ( [ a swrl:ClassAtom ; swrl:classPredicate :Supplier ; swrl:argument1 var:x ]
+ [ a swrl:ClassAtom ; swrl:classPredicate :Banned ; swrl:argument1 var:x ] ) ;
+ swrl:head () .
diff --git a/tests/fixtures/rules/family_swrl_truncated.ttl b/tests/fixtures/rules/family_swrl_truncated.ttl
new file mode 100644
index 00000000..4fe18d56
--- /dev/null
+++ b/tests/fixtures/rules/family_swrl_truncated.ttl
@@ -0,0 +1,20 @@
+# A malformed rule: the body's atom list has a cell with no rdf:rest, so it
+# never reaches rdf:nil. Read short it would be a rule with FEWER conditions,
+# which fires MORE often than the one written. Refused rather than truncated.
+@prefix : <http://example.org/family#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+@prefix swrl: <http://www.w3.org/2003/11/swrl#> .
+@prefix var: <urn:swrl#> .
+
+var:x a swrl:Variable .
+var:y a swrl:Variable .
+
+:truncated a swrl:Imp ;
+ swrl:body _:cell1 ;
+ swrl:head ( [ a swrl:IndividualPropertyAtom ;
+ swrl:propertyPredicate :hasUncle ;
+ swrl:argument1 var:x ; swrl:argument2 var:y ] ) .
+
+_:cell1 rdf:first [ a swrl:IndividualPropertyAtom ;
+ swrl:propertyPredicate :hasParent ;
+ swrl:argument1 var:x ; swrl:argument2 var:y ] .
diff --git a/tests/rule_syntax_frontend_test.rs b/tests/rule_syntax_frontend_test.rs
new file mode 100644
index 00000000..ee2ca031
--- /dev/null
+++ b/tests/rule_syntax_frontend_test.rs
@@ -0,0 +1,460 @@
+//! Standard rule syntaxes into the Horn certificate layer, end to end.
+//!
+//! `lean/OOCert/Horn.lean` proves one soundness theorem good for every rule
+//! table, and `reason --rules` evaluates a table and writes a certificate. What
+//! neither had was a way IN from a language anybody writes: the only rule syntax
+//! the repository could read was the tab-separated internal encoding. These
+//! tests take a real SWRL ontology and a real RIF Core XML document, turn each
+//! into a table, run the engine over it, and hand the certificate to the Lean
+//! checker.
+//!
+//! # The distinction these tests exist to protect
+//!
+//! Exactly one table earns `entailed`: the BUILT-IN one, because
+//! `OOCert.Builtin.asHorn_sound` discharges its rules against the RDF
+//! semantics. Every rule a front end imports was written by a user and is
+//! discharged by nobody, so a certificate over it earns
+//! `entailed_under_supplied_rules` under `OOCert.horn_certificate_sound`: true
+//! in every model of the asserted graph THAT ALSO SATISFIES THOSE RULES.
+//!
+//! `family_swrl.ttl` contains the rule that makes the point, spelled in SWRL:
+//! every supplier is compliant. It is a valid SWRL rule, it is assumed and never
+//! checked, and a certificate over a table containing it checks green for ever.
+//! `a_swrl_rule_never_earns_the_absolute_verdict` and its RIF twin are the
+//! `a_user_rule_never_earns_the_absolute_verdict` of the front ends, and
+//! `no_front_end_can_name_a_rule_the_way_a_built_in_is_named` pins the
+//! structural reason without needing Lean present.
+
+mod common;
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::reason::{Reasoner, RulePattern, rules_tsv};
+use open_ontologies::rulesyntax::{Import, rif_core_from_xml, run_import, swrl_from_graph};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::{Arc, OnceLock};
+
+fn repo() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn lean_dir() -> PathBuf {
+ repo().join("lean")
+}
+
+fn fixture(name: &str) -> PathBuf {
+ repo().join("tests").join("fixtures").join("rules").join(name)
+}
+
+fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("oo-rulesyntax-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+/// A store holding only the data, never the rules: the SWRL encoding triples
+/// are not facts the rules should reason over.
+fn data_graph() -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_file(&fixture("family.ttl").display().to_string()).unwrap();
+ g
+}
+
+fn import_swrl(path: &str) -> Import {
+ let g = Arc::new(GraphStore::new());
+ g.load_file(&fixture(path).display().to_string()).unwrap();
+ swrl_from_graph(&g).unwrap()
+}
+
+fn import_rif(path: &str) -> Import {
+ rif_core_from_xml(&std::fs::read_to_string(fixture(path)).unwrap()).unwrap()
+}
+
+fn json(s: &str) -> serde_json::Value {
+ serde_json::from_str(s).unwrap_or_else(|e| panic!("not JSON ({e}): {s}"))
+}
+
+// ── Lean plumbing, the same shape lean_horn_certificate_test.rs uses ─────────
+
+fn lake_available() -> bool {
+ Command::new("lake")
+ .arg("--version")
+ .current_dir(lean_dir())
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+}
+
+fn skip() -> bool {
+ common::skip_unless(
+ lake_available(),
+ "lake (the Lean 4 build tool)",
+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",
+ )
+}
+
+/// Build once per test binary. The proofs are part of the build, so a failure
+/// here is a failure and never a skip.
+fn checker() -> &'static Path {
+ static BUILT: OnceLock<PathBuf> = OnceLock::new();
+ BUILT.get_or_init(|| {
+ let out = Command::new("lake")
+ .arg("build")
+ .current_dir(lean_dir())
+ .output()
+ .expect("run lake build");
+ assert!(
+ out.status.success(),
+ "lake build failed:\n{}\n{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-horn");
+ assert!(exe.exists(), "checker binary missing at {}", exe.display());
+ exe
+ })
+}
+
+fn field<'a>(json: &'a str, key: &str) -> &'a str {
+ let pat = format!("\"{key}\":\"");
+ let start = json.find(&pat).unwrap_or_else(|| panic!("no {key} in {json}")) + pat.len();
+ let rest = &json[start..];
+ &rest[..rest.find('"').expect("unterminated")]
+}
+
+/// Import → evaluate → certify → check. Returns the engine's response and the
+/// checker's, so a test can assert on both halves of the pipeline.
+fn round_trip(name: &str, rules: &[RulePattern]) -> (serde_json::Value, i32, String) {
+ let dir = scratch(name);
+ let table = dir.join("imported.tsv");
+ std::fs::write(&table, rules_tsv(rules)).unwrap();
+
+ let cert = dir.join("cert");
+ let engine = json(&Reasoner::run_horn(&data_graph(), &table, &cert).unwrap());
+
+ let out = Command::new(checker())
+ .arg("check")
+ .arg(cert.join("rules.tsv"))
+ .arg(cert.join("asserted.tsv"))
+ .arg(cert.join("horn.tsv"))
+ .output()
+ .expect("run oo-horn");
+ (engine, out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).to_string())
+}
+
+// ── The laundering guards ───────────────────────────────────────────────────
+
+#[test]
+fn a_swrl_rule_never_earns_the_absolute_verdict() {
+ // `family_swrl.ttl` holds "every supplier is compliant" as a SWRL rule. The
+ // certificate still checks, because the inference is still valid under the
+ // rule; the verdict must say what it is relative to.
+ if skip() {
+ return;
+ }
+ let imp = import_swrl("family_swrl.ttl");
+ assert!(imp.refused.is_empty(), "{:?}", imp.refused);
+ let (engine, code, out) = round_trip("swrl", &imp.rules);
+
+ assert_eq!(code, 0, "{out}");
+ assert_ne!(
+ field(&out, "verdict"),
+ "entailed",
+ "a run over rules imported from SWRL must NOT report absolute entailment: {out}"
+ );
+ assert_eq!(field(&out, "verdict"), "entailed_under_supplied_rules", "{out}");
+ assert_eq!(field(&out, "theorem"), "OOCert.horn_certificate_sound", "{out}");
+ assert_ne!(
+ field(&out, "rules_digest"),
+ field(&out, "builtin_rules_digest"),
+ "the digest must show the imported table differed from the built-ins: {out}"
+ );
+ assert!(
+ field(&out, "means").contains("assumed, not checked"),
+ "the report must say the rules are assumed: {out}"
+ );
+
+ // The rules really did fire, so the verdict is about a certificate with
+ // something in it rather than an empty one.
+ assert_eq!(engine["derived_triples"], 2, "{engine}");
+ let derived: Vec<&str> =
+ engine["sample_derivations"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect();
+ assert!(
+ derived.contains(
+ &"<http://example.org/family#john> <http://example.org/family#hasUncle> <http://example.org/family#bob>"
+ ),
+ "{derived:?}"
+ );
+ assert!(
+ derived.contains(
+ &"<http://example.org/family#acme> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/family#Compliant>"
+ ),
+ "{derived:?}"
+ );
+}
+
+#[test]
+fn a_rif_rule_never_earns_the_absolute_verdict() {
+ if skip() {
+ return;
+ }
+ let imp = import_rif("family_rif.xml");
+ assert!(imp.refused.is_empty(), "{:?}", imp.refused);
+ let (engine, code, out) = round_trip("rif", &imp.rules);
+
+ assert_eq!(code, 0, "{out}");
+ assert_ne!(
+ field(&out, "verdict"),
+ "entailed",
+ "a run over rules imported from RIF Core must NOT report absolute entailment: {out}"
+ );
+ assert_eq!(field(&out, "verdict"), "entailed_under_supplied_rules", "{out}");
+ assert_eq!(field(&out, "theorem"), "OOCert.horn_certificate_sound", "{out}");
+ assert_ne!(field(&out, "rules_digest"), field(&out, "builtin_rules_digest"), "{out}");
+ assert_eq!(engine["derived_triples"], 2, "{engine}");
+}
+
+#[test]
+fn no_front_end_can_name_a_rule_the_way_a_built_in_is_named() {
+ // Why the two tests above cannot come out the other way, without needing
+ // Lean present to see it. `oo-horn` awards the absolute verdict only when
+ // the table it is given renders IDENTICALLY to the built-in one, names
+ // included. Every imported rule is named `swrl/…` or `rif/…`; no built-in
+ // rule is; so the tables can never coincide whatever the rules say.
+ let builtin =
+ std::fs::read_to_string(repo().join("tests/fixtures/horn/builtin_rules.tsv")).unwrap();
+ let builtin_names: Vec<&str> =
+ builtin.lines().filter(|l| !l.is_empty()).map(|l| l.split('\t').next().unwrap()).collect();
+ assert_eq!(builtin_names.len(), 27, "the built-in table changed shape");
+ for n in &builtin_names {
+ assert!(
+ !n.starts_with("swrl/") && !n.starts_with("rif/"),
+ "a built-in rule is named {n}, which an imported rule could now collide with"
+ );
+ }
+
+ for (what, rules) in [
+ ("swrl", import_swrl("family_swrl.ttl").rules),
+ ("rif", import_rif("family_rif.xml").rules),
+ ] {
+ assert!(!rules.is_empty(), "{what} imported nothing");
+ for r in &rules {
+ assert!(
+ r.name.starts_with("swrl/") || r.name.starts_with("rif/"),
+ "{what} emitted the rule name {}, which is not provenance-marked",
+ r.name
+ );
+ }
+ assert_ne!(rules_tsv(&rules), builtin, "{what} produced the built-in table");
+ }
+}
+
+#[test]
+fn the_two_front_ends_agree_on_the_same_two_rules() {
+ // family_swrl.ttl and family_rif.xml say the same thing in two languages.
+ // Two independently written parsers landing on the same patterns is the
+ // strongest check available that neither is quietly mis-reading its input.
+ // Only the NAMES differ, and they must, because the provenance is different.
+ // Matched by the local part of the rule's name rather than by position:
+ // SWRL rules come out in the order of their subject IRIs, RIF rules in
+ // document order, and neither ordering is the other's.
+ let swrl = import_swrl("family_swrl.ttl").rules;
+ let rif = import_rif("family_rif.xml").rules;
+ assert_eq!(swrl.len(), 2);
+ assert_eq!(rif.len(), 2);
+ let tail = |n: &str| n.rsplit(['#', '/']).next().unwrap().to_string();
+ for a in &swrl {
+ let b = rif
+ .iter()
+ .find(|b| tail(&b.name) == tail(&a.name))
+ .unwrap_or_else(|| panic!("no RIF counterpart for {}", a.name));
+ assert_eq!(a.body, b.body, "bodies differ for {} and {}", a.name, b.name);
+ assert_eq!(a.head, b.head, "heads differ for {} and {}", a.name, b.name);
+ assert!(a.name.starts_with("swrl/") && b.name.starts_with("rif/"));
+ }
+}
+
+// ── Every refusal, and the flag that says a table lost something ────────────
+
+#[test]
+fn a_built_in_atom_refuses_the_import_and_writes_no_table() {
+ let dir = scratch("builtin-refused");
+ let out = dir.join("rules.tsv");
+ let r = json(
+ &run_import(
+ &data_graph(),
+ "swrl",
+ Some(&fixture("family_swrl_builtin.ttl")),
+ Some(&out),
+ false,
+ )
+ .unwrap(),
+ );
+ assert!(r["error"].is_string(), "a refused rule must fail the import: {r}");
+ assert_eq!(r["rules_written"], false);
+ assert!(!out.exists(), "no table may be written when a rule was refused");
+ assert_eq!(r["rules_refused"], 1);
+ assert_eq!(r["certifies_a_weaker_rule_set"], true);
+ assert!(
+ r["refused"][0]["construct"].as_str().unwrap().contains("swrlb#greaterThan"),
+ "the refusal must name the built-in: {r}"
+ );
+}
+
+#[test]
+fn allow_partial_writes_the_rest_and_flags_it_as_a_weaker_rule_set() {
+ // The opt-in half. A table that lost a rule still reaches a fixpoint and
+ // still produces a certificate that checks green, so the loss has to be
+ // visible in the artefact and not only in a log line.
+ let dir = scratch("builtin-partial");
+ let out = dir.join("rules.tsv");
+ let r = json(
+ &run_import(
+ &data_graph(),
+ "swrl",
+ Some(&fixture("family_swrl_builtin.ttl")),
+ Some(&out),
+ true,
+ )
+ .unwrap(),
+ );
+ assert!(r["error"].is_null(), "{r}");
+ assert_eq!(r["rules_written"], true);
+ assert_eq!(r["source_rules"], 2);
+ assert_eq!(r["rules_emitted"], 1);
+ assert_eq!(r["rules_refused"], 1);
+ assert_eq!(
+ r["certifies_a_weaker_rule_set"], true,
+ "a partial import must SAY the rule set is weaker than the source: {r}"
+ );
+ assert_eq!(r["constructs_not_supported"][0]["occurrences"], 1);
+ assert_eq!(r["verdict_this_table_is_eligible_for"], "entailed_under_supplied_rules");
+ assert!(out.exists());
+}
+
+#[test]
+fn a_partial_import_can_never_be_silent() {
+ // The invariant behind the flag, stated so a later edit cannot lose it:
+ // there is no combination of arguments that writes a table with a refusal
+ // recorded and `certifies_a_weaker_rule_set` false.
+ for (syntax, file) in [
+ ("swrl", "family_swrl_builtin.ttl"),
+ ("swrl", "family_swrl_truncated.ttl"),
+ ("swrl", "family_swrl_empty_head.ttl"),
+ ("rif", "family_rif_head_equality.xml"),
+ ("rif", "family_rif_external.xml"),
+ ] {
+ for allow_partial in [false, true] {
+ let dir = scratch("silent");
+ let out = dir.join("rules.tsv");
+ let r = json(
+ &run_import(
+ &data_graph(),
+ syntax,
+ Some(&fixture(file)),
+ Some(&out),
+ allow_partial,
+ )
+ .unwrap(),
+ );
+ assert!(r["rules_refused"].as_u64().unwrap() > 0, "{file}: {r}");
+ assert_eq!(
+ r["certifies_a_weaker_rule_set"], true,
+ "{file} (allow_partial={allow_partial}) wrote a report that does not admit it \
+ lost a rule: {r}"
+ );
+ assert!(
+ !r["refused"].as_array().unwrap().is_empty(),
+ "{file}: the lost rule must be named, not just counted: {r}"
+ );
+ if !allow_partial {
+ assert!(r["error"].is_string(), "{file}: {r}");
+ assert!(!out.exists(), "{file}: a refused import wrote a table anyway");
+ }
+ }
+ }
+}
+
+#[test]
+fn a_truncated_atom_list_is_refused_rather_than_read_short() {
+ let imp = import_swrl("family_swrl_truncated.ttl");
+ assert!(imp.rules.is_empty());
+ assert_eq!(imp.refused.len(), 1);
+ assert!(imp.refused[0].construct.contains("swrl:body"), "{:?}", imp.refused[0]);
+ assert!(imp.refused[0].why.contains("rdf:rest"), "{:?}", imp.refused[0]);
+ assert!(
+ imp.refused[0].why.contains("fires more often"),
+ "the refusal must say WHY a short read is unsafe: {:?}",
+ imp.refused[0]
+ );
+}
+
+#[test]
+fn an_empty_head_is_refused_because_there_is_nothing_to_derive() {
+ let imp = import_swrl("family_swrl_empty_head.ttl");
+ assert!(imp.rules.is_empty());
+ assert_eq!(imp.refused.len(), 1);
+ assert_eq!(imp.refused[0].construct, "swrl:head of length zero");
+}
+
+#[test]
+fn equality_in_the_conclusion_is_refused_and_the_rest_is_kept_only_on_request() {
+ let imp = import_rif("family_rif_head_equality.xml");
+ assert_eq!(imp.source_rules, 2);
+ assert_eq!(imp.rules.len(), 1);
+ assert_eq!(imp.refused.len(), 1);
+ assert_eq!(imp.refused[0].construct, "rif:Equal in the conclusion");
+ assert!(imp.refused[0].why.contains("substitute equals for equals"), "{:?}", imp.refused[0]);
+}
+
+#[test]
+fn an_external_predicate_is_refused() {
+ let imp = import_rif("family_rif_external.xml");
+ assert!(imp.rules.is_empty());
+ assert_eq!(imp.refused.len(), 1);
+ assert_eq!(imp.refused[0].construct, "rif:External");
+}
+
+#[test]
+fn the_presentation_syntax_is_refused_by_name_rather_than_half_read() {
+ let r = run_import(
+ &data_graph(),
+ "rif",
+ Some(&fixture("family_rif_presentation.rifps")),
+ None,
+ true,
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(r.contains("presentation syntax"), "{r}");
+ assert!(r.contains("XML"), "{r}");
+}
+
+#[test]
+fn datalog_is_not_offered_as_a_syntax_it_does_not_have() {
+ // The family decision 0003 names is Datalog, RIF Core and SWRL. Datalog has
+ // no single standard concrete syntax, and claiming one would be exactly the
+ // "covered in architecture" move this work exists to undo.
+ let e = run_import(&data_graph(), "datalog", None, None, false).unwrap_err().to_string();
+ assert!(e.contains("Datalog"), "{e}");
+ assert!(e.contains("rules.tsv"), "the error must say where a Datalog program already goes: {e}");
+}
+
+#[test]
+fn the_reported_fragment_names_what_is_not_supported() {
+ // The response is what a user reads, so the fragment has to be IN it and
+ // has to be specific. "SWRL is supported" would be the false claim.
+ let r = json(&run_import(&data_graph(), "swrl", Some(&fixture("family_swrl.ttl")), None, false).unwrap());
+ let frag = r["supported_fragment"].as_str().unwrap();
+ for must in ["swrl:ClassAtom", "swrl:IndividualPropertyAtom", "Everything else is refused"] {
+ assert!(frag.contains(must), "the SWRL fragment does not mention {must}: {frag}");
+ }
+ assert!(r["rules_tsv"].is_string(), "with no --out the table comes back inline: {r}");
+
+ let r = json(&run_import(&data_graph(), "rif", Some(&fixture("family_rif.xml")), None, false).unwrap());
+ let frag = r["supported_fragment"].as_str().unwrap();
+ for must in ["presentation syntax is NOT read", "Frame", "CONVENTION"] {
+ assert!(frag.contains(must), "the RIF fragment does not mention {must}: {frag}");
+ }
+}