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.

common logic: emit the second dialect, and say which axioms the rules never saw

FABIOTESS04dd0ac5b8a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a0e39c9..433b0876 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,58 @@ All notable changes to Open Ontologies are documented here.
than letting it be assumed away.
### Added
+- **Common Logic has three dialects and this engine emitted one, so `fol --format cgif` writes a
+ second.** ISO/IEC 24707 defines CLIF, CGIF and XCL, and ISO/IEC 21838-1 clause 4.3 names all
+ three as qualifying; emitting CLIF and calling the result Common Logic support was a partial
+ claim nothing said out loud. `onto_fol_export` now takes `cgif` as a fifth serialiser over the
+ SAME translation, so the file is not a second reading of the ontology. What is emitted is **core
+ CGIF** (Annex B.2, not the extended B.3 syntax: no type labels, no `@every`, no `[If: … [Then:
+ …]]`), in the sub-dialects clause 7.1.1 names: compact (no sequence markers, which clause 6.5
+ says is what takes Common Logic past first order), unstructured and single domain, plus no `#?`
+ type label and no actor. The encoding is the standard's own — `[]` is truth and `~[]` is falsity
+ (B.2.5, B.2.8), conjunction is juxtaposition with no operator (B.2.6), an equation is a
+ coreference concept `[: ?X0 ?X1]` because CGIF has no `=`, and implication, disjunction and the
+ universal are B.3.5's and B.3.7's own rewrites into core. Every binder is given a context of its
+ own, because `trAx` reuses variable indices between an axiom's antecedent and its consequent and
+ B.2.10 forbids two defining labels with one name in one context; renumbering was not available,
+ since `owl-lean` uses named variables precisely so that freshness is a proof obligation.
+ **Conformance here is pinned by our own checker and not by an independent parser, and the two
+ are not called the same thing.** The CLIF claims in `docs/first-order-export.md` rest on two
+ external parsers disagreeing with us in recorded ways; no installable CGIF parser exists, so the
+ CGIF claims rest on a lexer, parser and syntax checker transcribed from Annex B's EBNF in
+ `tests/fol_cgif_export_test.rs`, plus a round trip of every sentence back to the `Form` it came
+ from, exact up to the two rewrites core CGIF forces. A comment that would close itself early is
+ REFUSED with the clause and the reason rather than rewritten, which is the rule
+ `UnwritableSymbol` already follows; that path is reachable and an earlier draft of the CGIF
+ header tripped it on every run. XCL is still not emitted and the report says so in
+ `common_logic_dialects_not_emitted`.
+- **`onto_dlp_boundary`: which of YOUR axioms the rule table can actually see.** `onto_rules_import`
+ already polices the Description Logic Programs boundary on the way IN, refusing a non-Horn SWRL
+ or RIF construct by name and count. Nothing policed the other direction: a user could load an
+ ontology, reason, and receive a certificate the Lean checker accepts, with nothing anywhere
+ saying how much of the TBox the rules ever read. The certificate is sound about the fragment the
+ rules could see and silent about the rest, which is the same assurance-laundering shape with the
+ loss moved from the rule table to the ontology. The new tool classifies every schema axiom and
+ **keeps two failures apart that a single "not covered" bucket would destroy**: an axiom
+ `outside_the_fragment` is not Horn and no implementation effort changes that (disjunction in the
+ consequent, existential in the head, cardinality restriction, negation in the antecedent, each
+ listed per axiom with the reason), while an axiom `inside_the_fragment_but_a_rule_is_not_implemented`
+ IS Horn, has an OWL 2 RL rule, and is invisible only because this engine does not run it —
+ `owl:hasKey` (`prp-key`) and `owl:propertyChainAxiom` (`prp-spo2`) are the two that bite. One is
+ a rewrite of the ontology and the other a patch to `src/reason.rs`, and merging them tells the
+ reader to do the wrong thing. An axiom that splits soundly is `partially_inside`, and the
+ asymmetry is checked: a conjunction splits in a consequent and NOT in an antecedent, because
+ dropping a conjunct from a rule body makes it fire more often, which is unsound rather than
+ weaker. Where the abstract DLP line and OWL 2 RL's differ the difference is named rather than
+ smoothed over: `owl:ReflexiveProperty` is a Horn clause OWL 2 RL excludes as an axiom form, and
+ it carries `horn_but_outside_owl2_rl`. The figure six other files state as "29 of OWL 2 RL's 78
+ rules" is now DERIVED rather than typed: `reason::RULES_EVALUATED` is the 29, a test greps
+ `src/reason.rs` for its own `emit` calls and fails if the two disagree, and the 78-rule
+ transcription is cross-checked against the independently written list of seventeen
+ false-concluding rules already in that file — a list that said SIXTEEN until it was checked
+ against the W3C source. Every triple in the store lands in an axiom bucket or in a counted
+ `not_classified` one.
+
- **The cross-kernel corpus was one step deep, and now goes to nineteen.**
`tests/cross_kernel_differential_test.rs` ran the Lean and the Isabelle
checker over 1,718 certificates, and exactly ONE of the 61 base certificates
@@ -276,6 +328,23 @@ All notable changes to Open Ontologies are documented here.
pair of theorems rather than as a remark.
### Fixed
+- **`src/server.rs` disagreed with itself about the tool count, and the gate that exists to catch
+ that covered four of the five places it is written.** The MCP instructions string said "MCP
+ server with 114 tools" and, one sentence later, "All 112 tools are advertised in a default
+ build". `total_claims` in `tests/readme_claims_test.rs` covered the first and no shape covered
+ the second, so the file contradicted itself while the suite stayed green. The fifth shape is now
+ in `no_stale_tool_count_survives_anywhere`.
+- **`docs/first-order-export.md` said nobody here had read ISO/IEC 24707:2018, and the reason it
+ gave for that was wrong too.** The page said downloading it "needs a free ISO account, which is
+ an owner action". It does not: 24707:2018 is in ISO's *Publicly Available Standards* list behind
+ a click-through licence and no account at all. It has now been read (sha256
+ `e920b0c43a932e1ad0e2c76d3501f56e2b11ee5547265b14aeb69a5866eae5e3`), which retires two hedges
+ the page carried. A.4.2's exactly-conformant sentence is in the second edition VERBATIM, so the
+ CLIF claim no longer needs its first-edition caveat, and the sentence saying nothing was claimed
+ about the second edition is gone rather than left standing. The 2007 first edition is no longer
+ in the PAS list, so the URL Sowa and Wikipedia cite now fails. Neither part of ISO/IEC 21838 has
+ been read and every claim sourced to those is still scoped to the text actually read.
+
- **Four claims the certificate layer made and had not earned, withdrawn rather
than edited away.** (1) Soundness here does **not** carry over to the OWL 2
Direct Semantics read through triples; nobody verified it, and it is false as
diff --git a/CLAUDE.md b/CLAUDE.md
index ba7953a9..4e8d819f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -18,28 +18,29 @@ When building or modifying ontologies, follow this workflow. Claude decides whic
### Reason
6. Call `onto_defects` FIRST. A reasoner amplifies whatever the declarations say, so a self-contradicting ontology makes every inference suspect. Fix what it reports before materializing anything
-7. Call `onto_reason` with profile `rdfs` or `owl-rl` to materialize inferred triples (transitive subclass chains, domain/range propagation, equivalentClass expansion)
-8. Call `onto_stats` again to verify inferred triple counts are reasonable
+7. Call `onto_dlp_boundary` SECOND, and read it before trusting anything `onto_reason` returns. `onto_defects` asks whether the declarations contradict each other; this asks a different question the rest of the pipeline never answers: **which of your axioms the rule table can actually see**. A certificate from `onto_reason` is a sound proof about the axioms the rules read and says nothing at all about the ones no rule fires on, so a green certificate over an ontology whose TBox is half invisible is true and misleading at once. The report keeps three failures apart and you act on each differently, because they are fixed in three different places. An axiom `outside_the_fragment` (a disjunction in the consequent, an existential in the head, a cardinality restriction, a negation in the antecedent) is not Horn, and only a rewrite of the ontology helps. An axiom `inside_the_fragment_but_a_rule_is_not_implemented` (`owl:hasKey`, `owl:propertyChainAxiom`, `owl:FunctionalProperty`) is Horn, has an OWL 2 RL rule, and is invisible only because this engine does not run it, so nothing about the ontology is wrong. And an axiom `partially_inside_the_fragment` is half seen, and the question is which half you needed. `not_fully_seen_by_the_rule_table` carries all three counts and never adds them
+8. Call `onto_reason` with profile `rdfs` or `owl-rl` to materialize inferred triples (transitive subclass chains, domain/range propagation, equivalentClass expansion). The profile decides how much of the rule table runs: `rdfs` evaluates 6 of the 29 rules, `owl-rl` 17 and `owl-rl-ext` all 29, and `onto_dlp_boundary` reports which
+9. Call `onto_stats` again to verify inferred triple counts are reasonable
### Verify
-9. Call `onto_lint` to check for missing labels, comments, domains, ranges — fix any issues found
-10. Call `onto_enforce` with rule pack `generic` to check design pattern compliance — fix any violations
-11. Call `onto_query` with SPARQL to verify structure:
+10. Call `onto_lint` to check for missing labels, comments, domains, ranges — fix any issues found
+11. Call `onto_enforce` with rule pack `generic` to check design pattern compliance — fix any violations
+12. Call `onto_query` with SPARQL to verify structure:
- Are all expected classes present?
- Do subclass hierarchies match the spec?
- Can competency questions be answered?
-12. If a reference ontology exists, call `onto_diff` to compare
+13. If a reference ontology exists, call `onto_diff` to compare
### Iterate
-13. If any step above reveals problems, fix the Turtle and restart from step 3
-14. This loop continues until validation passes, stats match, lint is clean, enforce has no violations, and SPARQL queries return expected results
+14. If any step above reveals problems, fix the Turtle and restart from step 3
+15. This loop continues until validation passes, stats match, lint is clean, enforce has no violations, and SPARQL queries return expected results
### Persist
-15. Call `onto_save` to write the final ontology to a .ttl file
-16. Call `onto_version` to save a named snapshot for rollback — always version after save
+16. Call `onto_save` to write the final ontology to a .ttl file
+17. Call `onto_version` to save a named snapshot for rollback — always version after save
### Key Principle
@@ -75,6 +76,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) |
| `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` |
| `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_dlp_boundary` | BEFORE trusting any `onto_reason` result, in the same register as `onto_defects`. Asks which of YOUR axioms the rule engine can actually SEE. A certificate from `onto_reason` is a sound proof about the axioms the rules read and says nothing about the ones no rule fires on, so a user can reason, get a green machine-checked certificate, and never learn that a third of the TBox was invisible. TWO DIMENSIONS THAT ARE NEVER MERGED, because one is a rewrite of the ontology and the other is a patch to this engine. (1) THE FRAGMENT: is the axiom Horn at all? The line is OWL 2 RL's class grammar (OWL 2 Profiles 4.3), and `outside` there would hold of a perfect OWL 2 RL engine: disjunction in the consequent, existential in the head, cardinality restriction, negation in the antecedent, each listed per axiom with the reason. (2) THIS ENGINE: does a rule fire on it? `owl:hasKey` and `owl:propertyChainAxiom` are Horn, OWL 2 RL has `prp-key` and `prp-spo2`, and this engine runs neither, so they are INSIDE the fragment and still invisible. An axiom that splits soundly is `partially_inside`: `A subClassOf (B and Out)` keeps its `A subClassOf B` half, and an `owl:equivalentClass` with an existential on one side keeps the direction `cls-svf1` evaluates. A conjunction in the ANTECEDENT does not split, because dropping a conjunct from a rule body makes it fire more often. The rule-table figures (78 OWL 2 RL rules, 29 evaluated, 10 more detected only as a clash, 7 that conclude false and are not looked for) are DERIVED from `src/reason.rs`, not typed. Every triple lands in an axiom bucket or a counted `not_classified` one. NOT a consistency check |
| `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, plus `refutation.tsv` when the run finds a contradiction `oo-refute` can judge. Ten of the seventeen OWL 2 RL rules that conclude `false` are detected and only `cax-dw` is certifiable, so `inconsistency.verdict` is `clash_found_by_this_engine` and NEVER the checker's `unsatisfiable_under_disjointness`; no clash found is not consistency; 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` |
@@ -106,7 +108,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_enforce_feedback` | To accept/dismiss an enforce violation — teaches enforce to suppress repeatedly dismissed violations |
| `onto_dl_explain` | To explain why a class is unsatisfiable using DL tableaux reasoning — returns clash trace |
| `onto_dl_check` | To check if one class is subsumed by another using DL tableaux reasoning |
-| `onto_fol_export` | To hand the ontology to the automated-theorem-proving ecosystem. Writes TPTP FOF (what E and Vampire read), ISO/IEC 24707 CLIF (the standards-track interchange syntax, and what ISO/IEC 21838-2 publishes BFO in), restricted both to the first-order-equivalent fragment of Common Logic and to the subdialect ISO/IEC 24707 A.4.2 calls exactly semantically conformant, each checked by a test rather than asserted. Both are serialisers over ONE translation: the one `OwlLean.adequacy` in the sibling owl-lean project is machine-checked about, including the background axioms and the individual typing axioms that theorem requires. The correspondence between this emitter and that Lean is PINNED BY TESTS AND NOT PROVED, and the emitted file says so. Constructs outside the fragment are named with counts and reasons in `constructs_not_exported`, never dropped silently. CLIF sentences are emitted BARE with standalone `(cl:comment '...')` labels, because the two CLIF parsers that exist both return an EMPTY theory from the wrapped `(cl:comment '...' SENTENCE)` form that ISO/IEC 21838-2's own BFO files use; `clif_comments: "wrapped"` restores that form and loses the content. `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, every symbol MANGLED with the table in `symbols.tsv`, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE) write the same translation for MODEL FINDERS, and assert the NEGATED goal because a countermodel to `G |= phi` is a model of `G + {not phi}`. Every run also writes `problem.tsv` with its digest, the format the verified checker reads. Pass `goals_file` to also write one problem per conjecture. A PROVER'S VERDICT ON THE OUTPUT IS AN ORACLE OPINION AND NEVER A CERTIFICATE: use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it. See docs/first-order-export.md and decision 0005 |
+| `onto_fol_export` | To hand the ontology to the automated-theorem-proving ecosystem. Writes TPTP FOF (what E and Vampire read), ISO/IEC 24707 CLIF (the standards-track interchange syntax, and what ISO/IEC 21838-2 publishes BFO in), restricted both to the first-order-equivalent fragment of Common Logic and to the subdialect ISO/IEC 24707 A.4.2 calls exactly semantically conformant, each checked by a test rather than asserted, and ISO/IEC 24707 CGIF, the second of Common Logic's three dialects, in CORE CGIF and in the compact sub-dialect clause 7.1.1 names (no sequence markers, which is what clause 6.5 says takes Common Logic past first order; also no `#?` type label and no actor). CGIF conformance is pinned by a lexer, parser and checker written from Annex B's EBNF IN THE TEST, not by an independent parser, because no installable CGIF parser exists; the CLIF claims rest on two external parsers and the CGIF claims do not, and the report names XCL as the dialect still not emitted. Both are serialisers over ONE translation: the one `OwlLean.adequacy` in the sibling owl-lean project is machine-checked about, including the background axioms and the individual typing axioms that theorem requires. The correspondence between this emitter and that Lean is PINNED BY TESTS AND NOT PROVED, and the emitted file says so. Constructs outside the fragment are named with counts and reasons in `constructs_not_exported`, never dropped silently. CLIF sentences are emitted BARE with standalone `(cl:comment '...')` labels, because the two CLIF parsers that exist both return an EMPTY theory from the wrapped `(cl:comment '...' SENTENCE)` form that ISO/IEC 21838-2's own BFO files use; `clif_comments: "wrapped"` restores that form and loses the content. `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, every symbol MANGLED with the table in `symbols.tsv`, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE) write the same translation for MODEL FINDERS, and assert the NEGATED goal because a countermodel to `G |= phi` is a model of `G + {not phi}`. Every run also writes `problem.tsv` with its digest, the format the verified checker reads. Pass `goals_file` to also write one problem per conjecture. A PROVER'S VERDICT ON THE OUTPUT IS AN ORACLE OPINION AND NEVER A CERTIFICATE: use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it. See docs/first-order-export.md and decision 0005 |
| `onto_fol_model` | To find a FINITE MODEL of the loaded ontology and CHECK it, so the answer names what it rests on. The SAT/SMT family, and deliberately not symmetric: a refutation cannot be replayed in core Lean, so a solver's `unsat` is an ORACLE OPINION for ever, while a MODEL is a finite object and `Fol.satisfiable_of_check` in `lean/Fol/` turns an accepted structure into satisfiability of exactly the formulas it was checked against. With a goal, `Fol.not_entails_of_check` gives a machine-checked NON-ENTAILMENT, the one sentence no prover can produce. FIVE FIELDS THAT ARE NEVER COLLAPSED: `solver_verdict`, `encoding`, `checker_exit`, `verdict`, `owl_reading`. Five verdict words: `model_checked` is the ONLY certified one and requires `checker_exit: 0`; `no_model_up_to_size_k` is an exhausted BOUNDED search and IS NOT unsatisfiability; `unsatisfiable_oracle` may come only from a run with no cardinality constraint. A solver answering `sat` whose model the checker REJECTS is a STOP_THE_LINE disagreement, never `rejected` and never `model_checked`. Needs z3 or mace4 and `oo-folmodel` (`cd lean && lake build`); the absence of either is reported in `skipped`. See docs/decisions/0006 |
| `onto_embed` | After loading an ontology — generates text + Poincaré structural embeddings for all classes. The default local model is **multilingual** (`paraphrase-multilingual-MiniLM-L12-v2`), so labels in different natural languages embed into a shared space. Honours `[embeddings] provider = "local" \| "openai"` in `config.toml`; OpenAI-compatible gateways (Azure, Ollama, vLLM, LocalAI, …) are supported via `OPEN_ONTOLOGIES_EMBEDDINGS_*` env vars |
| `onto_search` | To find classes by natural language description — requires onto_embed first |
diff --git a/README.md b/README.md
index 1c27972d..49e98713 100644
--- a/README.md
+++ b/README.md
@@ -239,8 +239,8 @@ Restart, and the `onto_*` tools are available. Cursor, Windsurf, Zed and VS Code
## What is in the box
-**114 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify
-and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises all 114 tools.
+**115 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify
+and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises all 115 tools.
Eight need an optional Cargo feature and return an error without it: four need `embeddings`, two
need `plugins`, two need `postgres` or `duckdb`. The published binaries and the GHCR image are
built with the default feature set, so they do not carry those eight.
diff --git a/docs/architecture.md b/docs/architecture.md
index 04e5e140..8fd9a60d 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -24,7 +24,7 @@ flowchart TD
REST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]
end
- subgraph ToolGroups["114 Tools"]
+ subgraph ToolGroups["115 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"]
diff --git a/docs/first-order-export.md b/docs/first-order-export.md
index 9c534cec..e425edc4 100644
--- a/docs/first-order-export.md
+++ b/docs/first-order-export.md
@@ -1,9 +1,9 @@
# First-order export, and what an ATP verdict is worth
The engine can hand an ontology to the automated-theorem-proving ecosystem, in TPTP FOF, in
-ISO/IEC 24707 CLIF, in SMT-LIB 2 and in LADR. The translation it emits is the one a machine-checked
-adequacy theorem is about, so a reader of the file can cite a kernel-checked result about what it
-means.
+ISO/IEC 24707 CLIF, in ISO/IEC 24707 CGIF, in SMT-LIB 2 and in LADR. The translation it emits is
+the one a machine-checked adequacy theorem is about, so a reader of the file can cite a
+kernel-checked result about what it means.
This page is the how-to. The design and its limits are in
[decision 0005](decisions/0005-a-prover-is-an-oracle-and-a-translation-is-a-theorem.md) for the
@@ -36,6 +36,11 @@ printf 'load ontology.ttl\nfol --out /tmp/fol --format tptp\n' \
printf 'load ontology.ttl\nfol --out /tmp/fol --format clif --clif-dialect iso\n' \
| open-ontologies --no-connect --data-dir /tmp/store batch -
+# ISO/IEC 24707 CGIF, the second Common Logic dialect. CORE CGIF, and a compact
+# sub-dialect of it. No dialect or comment flag: there is one spelling.
+printf 'load ontology.ttl\nfol --out /tmp/fol --format cgif\n' \
+ | open-ontologies --no-connect --data-dir /tmp/store batch -
+
# SMT-LIB 2, for Z3. Omit --smt-domain for the UNBOUNDED encoding, where `unsat`
# really is unsatisfiability; give it k for an enumeration carrier of exactly k
# elements, where a `sat` comes with a structure the verified checker can check.
@@ -61,7 +66,7 @@ one of those files therefore says the conjecture is NOT entailed. The negation h
`FolProblem::checker_entries`, and `problem.tsv` is a fold over the same list, which is the
mechanical reason the solver cannot be asked a different question from the one the checker checks.
-`ontology.p` (or `ontology.clif`) lands in the directory. With `--goals FILE`, where FILE is a TSV
+`ontology.p` (or `ontology.clif`, or `ontology.cgif`) lands in the directory. With `--goals FILE`, where FILE is a TSV
whose first three columns are a triple, one problem per goal lands under `goals/` with a
`goals.json` manifest. `derivations.tsv` from `reason --certificate` is the intended input; it puts
the rule in column one, so pass `--goals-skip-columns 1`.
@@ -267,8 +272,10 @@ character in CLIF and is Common Lisp's convention, not CLIF's.
### The exactly semantically conformant subdialect
-ISO/IEC 24707 first edition Annex A.4.2, verbatim: "The subdialect of CLIF which does not use
-numerals or quoted strings is exactly semantically conformant". A numeral and a quoted string are
+ISO/IEC 24707 Annex A.4.2, verbatim, in the **2018 second edition** and identically in the first:
+"The subdialect of CLIF which does not use numerals or quoted strings is exactly semantically
+conformant, as can be shown by inverting the above construction of J from I". A numeral and a
+quoted string are
interpreted names, and a text containing them constrains its own interpretations in a way abstract
Common Logic does not. Stay out of them and CLIF entailment and Common Logic entailment coincide,
so the adequacy theorem's biconditional needs no qualification at the CLIF end.
@@ -283,10 +290,11 @@ The property is checked rather than asserted:
`clif_stays_in_the_exactly_conformant_subdialect` walks every emitted sentence, skips the comment
annotations, and fails on a bare decimal or a single-quoted string.
-Nothing here is claimed about the second edition's Annex A.3, which this project has not read. In
-particular this page does not say that Common Logic requires infinite universes; abstract Common
-Logic requires only non-emptiness, and the infinite-universe requirement is CLIF-specific, appears
-in the withdrawn first edition, and sits awkwardly beside A.4.2 in that same edition.
+**This page used to say that nobody here had read the second edition.** That stopped being true on
+15 September 2026 and the sentence has been removed rather than left standing; see the limitations
+section for what the second edition turned out to say. In particular this page does not say that
+Common Logic requires infinite universes: abstract Common Logic requires only non-emptiness
+(clause 4.2), and the infinite-universe requirement is CLIF-specific.
### The two dialects, and what actually reads them
@@ -386,6 +394,184 @@ strongest available argument that a fragment gate and an external parser check a
normative corpus published by a standards body does not survive contact with either of the two
parsers that read its language.
+## CGIF, the second Common Logic dialect
+
+ISO/IEC 24707 defines **three** dialects: CLIF (Annex A), CGIF (Annex B) and XCL (Annex C). This
+engine emitted one of them and called the result Common Logic support. That is the shape of
+overclaim this project spends its time finding in other people's work, so `--format cgif` closes
+half of it. XCL is still absent, and the export report says so in a field
+(`common_logic_dialects_not_emitted`) rather than leaving a reader to assume otherwise.
+
+It matters for the same reason CLIF does. ISO/IEC 21838-1:2021 clause 4.3 asks that a top-level
+ontology be available through an axiomatisation in a language conforming to ISO/IEC 24707, and its
+note names CLIF, CGIF and XCL as the three that qualify. CGIF is not a lesser member of that list:
+Annex B.4 states that core CGIF, extended CGIF and the abstract CG syntax are all "fully conformant
+CL dialects in the sense that every CL sentence can be translated to a semantically equivalent
+sentence in each of them".
+
+### Core, not extended, and what that costs
+
+Annex B specifies two concrete syntaxes. **Core CGIF (B.2) is what this emitter writes.** B.3.1's
+own list of what extended CGIF adds is: type labels and type expressions on concepts, universal
+quantifiers, the Boolean contexts `[If: … [Then: …]]`, `[Either: [Or: …]]` and `[Equiv: [Iff: …]]`,
+concepts inside an arc sequence, and importing a text into a text. None of that is emitted.
+
+Core costs exactly one thing in readability, and B.1.2 states the reduction itself: "The concept
+`[Go:*x]`, for example, becomes an untyped concept `[*x]` and a conceptual relation `(Go ?x)`."
+So a class membership is written `("c:http://e/A" ?X0)` and not `[A: *x]`. Taking that reduction
+means the file needs no Annex B.3 rewrite pass before anything can read it.
+
+### The encoding, production by production
+
+| `Form` | CGIF | clause |
+|---|---|---|
+| `App1(p,t)` | `(p t)` | B.2.7 `ordinaryRelation` |
+| `App2(p,t,u)` | `(p t u)` | B.2.7, at arity two |
+| `Eq(t,u)` | `[: t u]` | B.2.5 `coreferenceConcept`. **CGIF has no `=`** |
+| `Tru` | `[]` | B.2.5: "an empty context `[ ]` is translated to CLIF as `(and)`, which is true by definition" |
+| `Fls` | `~[]` | B.2.8: "The negation of the blank CG, written `~[ ]`, is always false" |
+| `Neg(g)` | `~[ g ]` | B.2.8 `negation = "~", context` |
+| `And(g,h)` | `g h` | juxtaposition. B.2.6 makes a CG's nodes a conjunction and gives it no operator |
+| `Or(g,h)` | `~[ ~[g] ~[h] ]` | B.3.5's own `eitherOr` rewrite into core |
+| `Imp(g,h)` | `~[ g ~[h] ]` | B.3.5's own `ifThen` rewrite into core |
+| `All(n,g)` | `~[ [*Xn] ~[g] ]` | B.3.7: a CG with universal concepts becomes "a nest of two negations" |
+| `Ex(n,g)` | `[ [*Xn] g ]` | B.2.6: a CG with existential concepts is `∃names.` over the rest |
+
+The three derived forms are not this project's encoding choices. B.3.5 and B.3.7 are rewrite rules
+FROM extended CGIF INTO core, and the right-hand sides above are what those rules produce.
+
+**Equality is the one that surprises people.** There is no equality relation in CGIF and there
+could not be: `=` is a CLIF reserved token and a CGIF `identifier` must begin with a letter. B.2.5
+gives `[: ?x Cicero Tully ?abcd]` as translating to `(and (= x Cicero) (= x Tully) (= x abcd))`.
+One caveat travels with that and is written down rather than smoothed over: B.2.5 defines the
+references as a SET, so `[: n n]` denotes `(and)`, truth, rather than `n = n`. The two agree in
+every model, and the only axiom that could produce one is a self-`owl:sameAs`, which is a tautology
+either way.
+
+### Every binder gets a context of its own
+
+B.2.10: "If a concept x with a defining label with name n is directly contained in some context c,
+then c shall not contain any concept other than x with a defining label with the same CG name n."
+
+`OwlLean.trAx` restarts its variable counter per axiom and calls `tr c 0 2` and `tr d 0 2` for an
+axiom's antecedent and its consequent, so two `[*X2]` really can arise in one sentence. Renumbering
+them is not available: `owl-lean` uses named variables rather than de Bruijn indices precisely so
+that freshness is a proof obligation, and an exporter that renumbered would be emitting a different
+formula. So an existential is written `[ [*Xn] … ]` rather than as a bare `[*Xn]` juxtaposed with
+its body, and each sentence is wrapped in a context of its own. No context then directly contains
+two defining labels at all, whatever the counter did.
+
+**B.2.10 is self-contradictory about shadowing** and the emitter does not depend on the answer. It
+says both that a context "shall not contain any concept other than x with a defining label with the
+same CG name n" — where *contains* is transitive — and, in the next sentence, that a nested context
+may redeclare one. `no_defining_label_is_ever_shadowed` checks that the emitted text is legal under
+either reading.
+
+### The restriction, in the standard's own vocabulary
+
+Clause 7.1.1 names three sub-dialects and the emitted text is all three:
+
+| clause 7.1.1 term | verbatim | ours |
+|---|---|---|
+| compact sub-dialect | "a dialect that does not recognize sequence markers" | no `[*...x]`, no `?...x` |
+| unstructured sub-dialect | "a dialect that does not recognize titlings and importation statements" | neither is emitted |
+| single domain sub-dialect | "a dialect that does not recognize domain restrictions" | none is emitted |
+
+The first is the one that matters, and clause 6.5 says why: Common Logic with sequence markers "is
+not compact, and therefore not first-order". `OwlLean.adequacy` is about plain first-order logic,
+so a text using one would sit outside the theorem.
+
+Two further exclusions have no clause-7 name and would leave first-order logic just as surely. **No
+`#?` type label**, which B.2.7's own comment says is how "CGIF supports the CL ability to quantify
+over relations and functions" — the CGIF spelling of the thing the CLIF restriction already
+excludes. And **no actor**, B.2.1, which is how a CL function is written; `OwlLean.FOL`'s `FSig`
+has P1, P2 and Const and no function symbol of positive arity, so `Form` cannot express one.
+
+### Interpreted names, and the exception CGIF does not need
+
+A.4.2's "exactly semantically conformant" result is stated for **CLIF** and Annex B states no
+analogue for CGIF. This page therefore does not borrow the label. What the emitter does is hold the
+property: no numeral and no single-quoted string stands anywhere in the text, checked by
+`cgif_uses_no_interpreted_name`.
+
+CGIF holds it with **no exception to declare**, where CLIF needs one. A CLIF label has to ride on
+`cl:comment`, whose argument is a quoted string by definition, so the CLIF page above has to carve
+comment annotations out of the claim. B.2.4 makes a CGIF comment a LEXICAL construct, `/* … */`,
+which is not a name at all.
+
+The same clause is why a comment can be **refused**: "The string enclosed by the delimiters `/*`
+and `*/` shall not contain a substring `*/`", and no escape is defined. Rewriting the text would
+emit a different comment and dropping it would lose the label that says which axiom a sentence is,
+so `to_cgif` returns an `UnwritableComment` and writes no file. That path is reachable rather than
+theoretical: an earlier draft of the CGIF header named the delimiters literally and tripped it on
+every run.
+
+### Names
+
+B.1.1's `identifier` is `letter, {letter | digit | "_"}` — no colon, no slash, no dot, no hyphen —
+and B.1.1 states the consequence: "the category CGname requires that all CLIF name sequences except
+those in the CGIF category identifier shall be enclosed in quotes". So every IRI is a double-quoted
+enclosed name, **including the text's own name**, where the CLIF writer emits a bare IRI because
+Macleod's lexer has no double-quote token. The two writers share `clif::enclosed` rather than each
+having its own, because B.1.1 defines `CGname` to include CLIF's `enclosedname` category.
+
+`X0`, `thing` and `lit` are identifiers. A defining label here is `Xn` and a constant here begins
+`i:`, so the two can never collide, which B.2.10's last clause forbids outright: "No constant with
+CG name n shall be in the scope associated with some concept with a defining label with CG name n."
+
+`letter` is used in that production and **never defined anywhere in ISO/IEC 24707:2018**. That is a
+defect in the standard, not a reading of it. The emitter produces ASCII letters only and the
+checker reads it that way, and the choice is written down here rather than assumed.
+
+### How CGIF conformance is checked, and how that differs from CLIF
+
+**By our own checker, not by an independent parser.** This is the weaker of the two footings in
+this document and the difference is stated rather than blurred.
+
+For CLIF, two external parsers were run over five exports and the table above records what they do,
+including that both return an EMPTY theory from the wrapped comment shape ISO's own BFO files use.
+Nothing of that kind exists for CGIF. There is no `cgif` package on PyPI; py-typedlogic, which
+reads the CLIF output, has no CGIF front end; Macleod reads CLIF. So conformance here is pinned by
+the lexer, parser and checker in `tests/fol_cgif_export_test.rs`, transcribed from Annex B's EBNF
+with the clause cited at each rule.
+
+What that transcription is worth: it is a SECOND reading of the grammar, written against the
+emitter rather than with it, so a shape both agree on is a shape two readings of Annex B agree on.
+It is not an independent implementation and this page does not call it one.
+
+Alongside the syntax check there is a **round trip**. Every sentence is read back into a `Form` and
+must equal the formula it was built from, up to the two rewrites core CGIF forces: implication and
+disjunction have no operators (B.3.5 defines both by the rewrite), and conjunction is "an unordered
+set of concepts, conceptual relations, negations, and comments" (B.2.6) rather than a binary
+connective, so the associativity of an `And` tree cannot survive. Both sides are normalised by
+those two facts and by nothing else.
+
+One source was deliberately NOT used. `jfsowa.com/cg/annexb.htm` is a **pre-publication draft** of
+the same annex, not the published standard, and the 2018 Foreword says "the list of syntactic
+errors that have already been identified in the Defect Report has been fixed". Measured differences
+that would have mattered: the draft's `equiv` rewrite emits `~[` where the published text emits
+`[`, turning a conjunction of two implications into a tautology; its `nestedOrs` termination test
+drops the last disjunct; its `text` name slot is `constant` rather than `CGname`; and its B.4 says
+"[This section is incomplete.]" where the published B.4 carries the complete Table B.1.
+
+### Defects found in ISO/IEC 24707:2018 itself
+
+Listed because a checker written from a standard inherits the standard's gaps, and a reader of the
+emitted file should know which lines rest on a reading rather than on a rule.
+
+| clause | what |
+|---|---|
+| B.1.1 | `letter` is used in `identifier` and defined nowhere in the document |
+| B.2.10 | the no-duplicate clause uses *contains* transitively and the next sentence licenses shadowing; the two cannot both hold |
+| B.3.1 / Table B.1 E17 | "the ability to import text into a text" is listed as a feature and no production defines it; only `[cg_Imports N]` in the table hints at the syntax |
+| B.3.9 | cross-references "A.3" for module elimination; A.3 in this edition is CLIF semantics |
+| Table B.1 E6, E19 | write a coreference concept and a text without the `:` that B.2.5 and B.2.11 make mandatory |
+| B.1.1 | `CGname`'s second branch is subsumed by its fourth, so the rule is ambiguous (harmless) |
+| B.1.4.1 | "zero or more characters of white space may occur" at every comma is false for two adjacent identifiers |
+| B.2.5 vs B.3.6 | `[]` is truth under core and `∃x.⊤` under extended. Both true given clause 4.2's non-empty universe, and not the same graph |
+| B.2.11 vs B.3.6 | `text` and an extended `concept` both match `[Proposition: N …]` with different readings, and `text` is not a member of `CG` while Table B.1 E19 can generate nested texts |
+| B.2.5 | `existentialConcept` admits `[*7]` and `[*'str']`, which A.2.3.8's `bvar` cannot bind. The checker refuses them |
+
## Known limitations
Stated rather than discovered later.
@@ -405,12 +591,28 @@ Stated rather than discovered later.
with that reason.
- **Nothing runs the differential in CI.** It needs a prover on `PATH` and skips loudly without
one. A CI leg that installs E is not wired.
-- **Nobody here has read ISO/IEC 24707:2018 or either part of ISO/IEC 21838.** All three are priced
- at CHF 0, 70 pages for 24707, but downloading them needs a free ISO account, which is an owner
- action. The old ITTF free-standards site closed in 2025; catalogue pages are reachable at
- `committee.iso.org` when `www.iso.org` returns 403. Every clause cited on this page is scoped to
- the edition and the text actually read, and the second edition's Annex A.3 has not been read at
- all.
+- **CGIF conformance is pinned by our own checker and not by an independent parser.** There is no
+ installable CGIF parser to differ from: no `cgif` package on PyPI, no CGIF front end in
+ py-typedlogic, and Macleod reads CLIF. The CLIF claims on this page rest on two external parsers
+ disagreeing with us in recorded ways; the CGIF claims rest on a second reading of Annex B's EBNF
+ in `tests/fol_cgif_export_test.rs`. That is a real difference in footing and it is not narrowed
+ by calling both "checked".
+- **XCL is not emitted.** ISO/IEC 24707 has three dialects and two are written here. The report
+ says which, in `common_logic_dialects_emitted` and `common_logic_dialects_not_emitted`, so a
+ reader is not left to infer that "Common Logic support" means all three.
+- **ISO/IEC 24707:2018 HAS now been read; neither part of ISO/IEC 21838 has.** This item said the
+ opposite until 15 September 2026, and the claim it made about ACCESS was wrong as well as stale:
+ 24707:2018 is in ISO's *Publicly Available Standards* list and needs no account at all, only a
+ click-through licence, which is a POST with a cookie jar rather than an owner action. It was
+ downloaded (`standards.iso.org/ittf/PubliclyAvailableStandards/c066249_ISO_IEC_24707_2018.zip`,
+ sha256 `e920b0c43a932e1ad0e2c76d3501f56e2b11ee5547265b14aeb69a5866eae5e3`) and Annexes A and B
+ were read in full for the CGIF work. Three things follow. A.4.2's exactly-conformant sentence is
+ in the second edition verbatim, so the CLIF claim above no longer needs its edition caveat. The
+ 2007 first edition is **no longer in the PAS list**, so the URL Sowa and Wikipedia cite now
+ fails; 2018 cancels and replaces it. And ISO/IEC 21838-1 and -2 are still unread, so every claim
+ on this page sourced to them is still scoped to the text actually read, including that clause
+ 4.3's "shall be available" modality comes from the Russian identical adoption and not from the
+ English.
- **Only E has actually been run.** Every number on this page comes from E 3.2.5. The Vampire
branch of the prover detection has never executed, because Vampire is not installed here; its
argument vector and its SZS parsing are written from the documented interface and are untested.
diff --git a/docs/reasoning.md b/docs/reasoning.md
index c8b87b23..caeef967 100644
--- a/docs/reasoning.md
+++ b/docs/reasoning.md
@@ -48,9 +48,9 @@ measurements are in
| Profile | What it does |
| ------- | ------------ |
-| `rdfs` | Subclass closure, domain/range inference |
-| `owl-rl` | + transitive/symmetric/inverse, sameAs, equivalentClass |
-| `owl-rl-ext` | + someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf |
+| `rdfs` | Subclass closure, domain/range inference. 6 of the 29 rules |
+| `owl-rl` | + transitive/symmetric/inverse, sameAs, equivalentClass. 17 of the 29 |
+| `owl-rl-ext` | + someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf. All 29 |
| `owl-dl` | SHIQ tableaux: satisfiability, classification, ABox reasoning. Nominals are not implemented and datatype ranges are skipped |
## Tools
@@ -58,9 +58,68 @@ measurements are in
| Tool | Purpose |
| ---- | ------- |
| `onto_reason` | Run inference with selected profile |
+| `onto_dlp_boundary` | Which of YOUR axioms the rule table can see. Run it BEFORE trusting a result |
| `onto_dl_explain` | Explain why a class is unsatisfiable (clash trace) |
| `onto_dl_check` | Check if one class is subsumed by another |
+## What the rule table cannot see, and the three reasons it cannot
+
+A certificate from `onto_reason` is a sound proof about **the axioms the rules
+read**. It says nothing about the ones no rule fires on. Both halves of that
+sentence are true at once, which is why a green machine-checked certificate over
+an ontology whose TBox is half invisible is misleading without being wrong.
+
+`onto_dlp_boundary` is the report that closes the gap. It is the mirror of the
+discipline `onto_rules_import` already applies on the way in: that tool refuses
+a non-Horn SWRL or RIF construct by name and count, so nobody gets a certificate
+over a rule set they did not write. This one says which of the axioms they DID
+write the rule table never looked at.
+
+**It separates three failures that a single "not covered" bucket would destroy.**
+Two DIMENSIONS produce them: whether the axiom is Horn at all, and whether this
+engine runs the rule for it.
+
+| bucket | what it means | what fixes it |
+| ------ | ------------- | ------------- |
+| `outside_the_fragment` | the axiom is not a Horn rule over triple patterns and no implementation makes it one. Disjunction in the consequent, existential in the head, cardinality restriction, negation in the antecedent | rewriting the ontology, or a different reasoner family |
+| `inside_the_fragment_but_a_rule_is_not_implemented` | the axiom IS Horn and OWL 2 RL has a rule for it. This engine does not run that rule | a patch to `src/reason.rs`. Nothing about the ontology is wrong |
+| `partially_inside_the_fragment` | part of it splits off soundly and is seen. `A ⊑ B ⊓ Out` keeps `A ⊑ B`; `A ≡ ∃r.B` keeps the direction `cls-svf1` evaluates | depends on which half you needed |
+
+`not_fully_seen_by_the_rule_table` is the headline and carries all three counts
+separately rather than adding them. They are fixed in three different places, so
+one number would be the least useful summary available.
+
+`owl:hasKey` and `owl:propertyChainAxiom` are the two that bite most often: both
+are Horn, OWL 2 RL has `prp-key` and `prp-spo2` for them, and this engine has
+neither. Calling those "outside the fragment" would send someone rewriting an
+ontology that is already fine.
+
+The splitting asymmetry is not decoration. A conjunction splits in a CONSEQUENT
+and does not split in an ANTECEDENT, because dropping a conjunct from a rule
+body makes the rule fire **more** often, which is unsound rather than merely
+weaker. A disjunction splits the other way round, in an antecedent.
+
+The line the classifier draws is OWL 2 RL's class grammar (OWL 2 Profiles
+section 4.3), because OWL 2 RL is the standardised descendant of Description
+Logic Programs that this rule table targets. Where the abstract DLP line and the
+OWL 2 RL line differ, the difference is named rather than smoothed over:
+`owl:ReflexiveProperty` is a Horn clause (`⊤(x) → r(x,x)`) that OWL 2 RL
+excludes as an axiom form, and it carries `horn_but_outside_owl2_rl` saying so.
+
+### Where the figures come from
+
+`78`, `29`, `10`, `7` and `32` are derived, not typed. `OWL2_RL_RULES` in
+`src/dlp.rs` is the profile's 78 inference rules; `reason::RULES_EVALUATED` is
+the 29 the fixpoint runs and `reason::CLASH_RULES_NOT_DETECTED` is the 7 that
+conclude `false` and are not looked for, and the rest falls out.
+
+Three tests hold it together. `the_evaluated_rule_list_is_the_rules_this_file_emits`
+greps `src/reason.rs` for its own `emit` calls and fails if the constant and the
+code disagree. `the_seventeen_false_concluding_rules_agree_with_the_engine`
+checks the rules marked as concluding `false` against the independently written
+list in `src/reason.rs`'s own comment — a list that said SIXTEEN until it was
+checked against the W3C source. `the_rule_table_adds_up` checks the partition.
+
## Certified inference
Every profile except `owl-dl` can emit a derivation certificate
diff --git a/src/dlp.rs b/src/dlp.rs
new file mode 100644
index 00000000..7ff579e0
--- /dev/null
+++ b/src/dlp.rs
@@ -0,0 +1,1513 @@
+//! Which of YOUR axioms the rule engine can actually see.
+//!
+//! # The gap this closes
+//!
+//! `src/rulesyntax.rs` polices the Description Logic Programs boundary in one
+//! direction already. A SWRL built-in atom or a RIF `External` call is refused
+//! by name and counted, because a rule table that quietly lost half its rules
+//! still reaches a fixpoint and still produces a certificate that checks green.
+//! That is the import direction.
+//!
+//! Nothing policed the other direction. A user loads an ontology, runs
+//! `onto_reason --profile owl-rl-ext --certificate`, and gets a certificate the
+//! Lean checker accepts. Everything about that is true and none of it says how
+//! much of the TBox the rule table ever looked at. An `owl:unionOf` in a
+//! consequent, an existential in a head, a `owl:propertyChainAxiom`, an
+//! `owl:hasKey`: each is simply not seen, no rule fires on it, the fixpoint
+//! closes, and the certificate is a sound proof about the FRAGMENT of the
+//! ontology the rules could read. The user is never told which fragment that
+//! was. That is the same assurance-laundering shape, with the loss moved from
+//! the rule table to the ontology.
+//!
+//! This file is that report. It classifies every schema axiom in the loaded
+//! graph and says, for each one, whether the rule engine can see it — and when
+//! it cannot, which of the two very different reasons applies.
+//!
+//! # The two dimensions, which are never merged
+//!
+//! **Dimension one, the FRAGMENT.** Is the axiom expressible as Horn rules over
+//! triple patterns at all? `A ⊑ B ⊔ C` is not: a disjunction in the consequent
+//! is not a Horn clause, and no implementation effort will make it one. This is
+//! a fact about the LANGUAGE and it would hold of a perfect OWL 2 RL engine.
+//!
+//! **Dimension two, THIS ENGINE.** Is there a rule in the table that fires on
+//! it? `owl:hasKey` is perfectly Horn — a conjunction of matching property
+//! values implies `owl:sameAs` — and OWL 2 RL has a rule for it, `prp-key`.
+//! This engine does not implement that rule. So the axiom is INSIDE the
+//! fragment and still invisible. A different engine would see it; a different
+//! language would not help.
+//!
+//! Merging those two into one "not covered" bucket destroys the only
+//! information a reader can act on. One is a rewrite of the ontology; the other
+//! is a patch to `src/reason.rs`. The report keeps them apart, and
+//! `an_unimplemented_rule_is_not_reported_as_outside_the_fragment` in
+//! `tests/dlp_boundary_test.rs` is the gate that they stay apart.
+//!
+//! # Where the line is drawn, exactly
+//!
+//! DLP is a family of fragments, not a single line. Grosof, Horrocks, Volz and
+//! Decker's *Description Logic Programs: Combining Logic Programs with
+//! Description Logic* (WWW 2003) defines the intersection; OWL 2 RL is the
+//! standardised descendant of it, and OWL 2 RL is what this engine's rule table
+//! targets. **So the line drawn here is OWL 2 RL's**, taken from the class
+//! expression grammar in section 4.3 of the OWL 2 Profiles recommendation:
+//! `subClassExpression` for what may stand in an antecedent and
+//! `superClassExpression` for what may stand in a consequent.
+//!
+//! Two places where the abstract DLP line and the OWL 2 RL line differ are
+//! named rather than smoothed over, and carry `horn_but_outside_owl2_rl`:
+//! `ReflexiveObjectProperty` and `DisjointUnion` are both excluded from OWL 2
+//! RL as axioms, and reflexivity in particular IS a Horn clause (`⊤(x) →
+//! r(x,x)`). Saying "outside the fragment" about it without that qualification
+//! would be false.
+//!
+//! # Where this classifier is MORE generous than the grammar, and says so
+//!
+//! The OWL 2 RL grammar rejects a whole axiom when any part of it is outside.
+//! Two shapes split soundly, and this classifier splits them and reports
+//! `partially_inside` rather than `outside`:
+//!
+//! * a CONJUNCTION in the consequent. `A ⊑ B ⊓ Out` is `A ⊑ B` and `A ⊑ Out`,
+//! so the `A ⊑ B` half is a Horn rule whatever `Out` is.
+//! * a DISJUNCTION in the antecedent. `(A ⊔ Out) ⊑ C` is `A ⊑ C` and
+//! `Out ⊑ C`, so again one half survives.
+//!
+//! The asymmetry is the whole point and is not symmetric by accident. A
+//! conjunction in the ANTECEDENT does not split: dropping a conjunct from a
+//! rule body makes the rule fire MORE often, which is unsound, so
+//! `A ⊓ Out ⊑ C` is outside as a whole. Neither does a disjunction in the
+//! consequent. `a_conjunctive_body_with_one_bad_conjunct_is_outside_not_partial`
+//! pins that.
+//!
+//! **`owl:equivalentClass` is the third and largest generosity.** OWL 2 RL has
+//! a THIRD class grammar, `equivClassExpression`, tighter than either of the
+//! other two: a named class, an intersection of those, `ObjectHasValue` and
+//! `DataHasValue`, and nothing else. So the profile rejects
+//! `EquivalentClasses(C, ObjectSomeValuesFrom(r, D))` outright at the syntax
+//! level. This classifier reads it as the two subsumptions it means and reports
+//! that ONE of them is evaluated, because the profile's own rules `cax-eqc1`
+//! and `cax-eqc2` perform exactly that split and `cls-svf1` really does fire on
+//! the surviving direction. Reporting the axiom as wholly outside would say the
+//! rules see nothing of it, which is false. The generosity is written down here
+//! because it is a deliberate departure from the grammar and not an oversight.
+//!
+//! Nothing propagates a split through `owl:complementOf`. Weakening under a
+//! negation strengthens, so the partial flag is dropped when the classifier
+//! crosses one.
+//!
+//! # What this is NOT
+//!
+//! It is not a consistency check, not a profile validator, and not a claim
+//! about what OWL 2 RL entails. It reports what the rule table in
+//! `src/reason.rs` can and cannot read, and the count of rules it does not
+//! implement is derived from `reason::RULES_EVALUATED` and
+//! `reason::CLASH_RULES_NOT_DETECTED` rather than typed here.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+use crate::graph::GraphStore;
+use crate::tableaux::TripleIndex;
+
+// ── Vocabulary ──────────────────────────────────────────────────────────────
+
+macro_rules! owl {
+ ($local:literal) => {
+ concat!("<http://www.w3.org/2002/07/owl#", $local, ">")
+ };
+}
+macro_rules! rdfs {
+ ($local:literal) => {
+ concat!("<http://www.w3.org/2000/01/rdf-schema#", $local, ">")
+ };
+}
+
+const RDF_TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
+
+const RDFS_SUBCLASS: &str = rdfs!("subClassOf");
+const RDFS_SUBPROP: &str = rdfs!("subPropertyOf");
+const RDFS_DOMAIN: &str = rdfs!("domain");
+const RDFS_RANGE: &str = rdfs!("range");
+
+const OWL_THING: &str = owl!("Thing");
+const OWL_NOTHING: &str = owl!("Nothing");
+const OWL_EQUIV_CLASS: &str = owl!("equivalentClass");
+const OWL_EQUIV_PROP: &str = owl!("equivalentProperty");
+const OWL_DISJOINT_WITH: &str = owl!("disjointWith");
+const OWL_ALL_DISJOINT_CLASSES: &str = owl!("AllDisjointClasses");
+const OWL_ALL_DISJOINT_PROPS: &str = owl!("AllDisjointProperties");
+const OWL_ALL_DIFFERENT: &str = owl!("AllDifferent");
+const OWL_DISJOINT_UNION: &str = owl!("disjointUnionOf");
+const OWL_COMPLEMENT_OF: &str = owl!("complementOf");
+const OWL_INVERSE_OF: &str = owl!("inverseOf");
+const OWL_PROPERTY_CHAIN: &str = owl!("propertyChainAxiom");
+const OWL_PROP_DISJOINT_WITH: &str = owl!("propertyDisjointWith");
+const OWL_HAS_KEY: &str = owl!("hasKey");
+const OWL_NEGATIVE_PROP_ASSERTION: &str = owl!("NegativePropertyAssertion");
+const OWL_SAME_AS: &str = owl!("sameAs");
+const OWL_DIFFERENT_FROM: &str = owl!("differentFrom");
+
+const OWL_INTERSECTION_OF: &str = owl!("intersectionOf");
+const OWL_UNION_OF: &str = owl!("unionOf");
+const OWL_ONE_OF: &str = owl!("oneOf");
+const OWL_RESTRICTION: &str = owl!("Restriction");
+const OWL_ON_PROPERTY: &str = owl!("onProperty");
+const OWL_ON_CLASS: &str = owl!("onClass");
+const OWL_ON_DATA_RANGE: &str = owl!("onDataRange");
+const OWL_SOME_VALUES_FROM: &str = owl!("someValuesFrom");
+const OWL_ALL_VALUES_FROM: &str = owl!("allValuesFrom");
+const OWL_HAS_VALUE: &str = owl!("hasValue");
+const OWL_HAS_SELF: &str = owl!("hasSelf");
+const OWL_MIN_CARDINALITY: &str = owl!("minCardinality");
+const OWL_MAX_CARDINALITY: &str = owl!("maxCardinality");
+const OWL_CARDINALITY: &str = owl!("cardinality");
+const OWL_MIN_QUALIFIED_CARDINALITY: &str = owl!("minQualifiedCardinality");
+const OWL_MAX_QUALIFIED_CARDINALITY: &str = owl!("maxQualifiedCardinality");
+const OWL_QUALIFIED_CARDINALITY: &str = owl!("qualifiedCardinality");
+const OWL_ON_DATATYPE: &str = owl!("onDatatype");
+const OWL_WITH_RESTRICTIONS: &str = owl!("withRestrictions");
+const OWL_DATATYPE_COMPLEMENT: &str = owl!("datatypeComplementOf");
+
+const OWL_TRANSITIVE: &str = owl!("TransitiveProperty");
+const OWL_SYMMETRIC: &str = owl!("SymmetricProperty");
+const OWL_ASYMMETRIC: &str = owl!("AsymmetricProperty");
+const OWL_REFLEXIVE: &str = owl!("ReflexiveProperty");
+const OWL_IRREFLEXIVE: &str = owl!("IrreflexiveProperty");
+const OWL_FUNCTIONAL: &str = owl!("FunctionalProperty");
+const OWL_INVERSE_FUNCTIONAL: &str = owl!("InverseFunctionalProperty");
+
+// ── The OWL 2 RL rule table ─────────────────────────────────────────────────
+
+/// One rule of the OWL 2 RL profile's inference tables.
+///
+/// The seventy-eight names below are transcribed from Tables 4 to 9 of the W3C
+/// OWL 2 Web Ontology Language Profiles recommendation (Second Edition, 11
+/// December 2012), section 4.3. A transcription is a claim, so it is checked
+/// two ways rather than asserted.
+///
+/// **Mechanically, against the source.** The rule names were extracted from the
+/// recommendation's HTML on 15 September 2026 by reading the `<span
+/// class="name" id="…">` of each table's first column, and the six tables came
+/// back 9 / 20 / 19 / 5 / 5 / 20 with the names and the order below. That pass
+/// also found the bug this module carried in its first hour: `owl:Thing` is
+/// excluded from the top-level `Class` alternative of BOTH class grammars and
+/// is ADMITTED as a filler in `subObjectSomeValuesFrom` and in
+/// `superObjectMaxCardinality`, which `cls-svf2`, `cls-maxqc2` and `cls-maxqc4`
+/// are the rules for. Refusing it was a false positive on legal OWL 2 RL.
+///
+/// **Against this repository, which read the tables independently.** Seventeen
+/// of these rules conclude `false` rather than a triple, `src/reason.rs` names
+/// the same seventeen in a list written before this one and without reference
+/// to it, and `the_seventeen_false_concluding_rules_agree_with_the_engine`
+/// fails if the two ever differ. The total of 78 and the counts 29 / 10 / 7 /
+/// 32 are asserted by `the_rule_table_adds_up`, so a mistyped row cannot pass.
+///
+/// One defect in the recommendation, noted because a reader may hit it:
+/// Appendix 6.3's standalone RL grammar alternates on `superComplementOf`,
+/// while the production under it and every other use of the name is
+/// `superObjectComplementOf`. Section 4.2.3 is unambiguous and is what this
+/// module follows.
+pub struct RlRule {
+ /// The W3C name.
+ pub name: &'static str,
+ /// Which of the W3C tables it is in.
+ pub table: &'static str,
+ /// True when the rule's conclusion is `false`, so a fixpoint over triples
+ /// cannot hold it and the clash detector is where it would live.
+ pub concludes_false: bool,
+ /// What `src/reason.rs` spells it, where the two differ. Equal to `name`
+ /// otherwise.
+ pub engine_name: &'static str,
+}
+
+const fn r(name: &'static str, table: &'static str) -> RlRule {
+ RlRule { name, table, concludes_false: false, engine_name: name }
+}
+const fn rf(name: &'static str, table: &'static str) -> RlRule {
+ RlRule { name, table, concludes_false: true, engine_name: name }
+}
+const fn ra(name: &'static str, table: &'static str, engine_name: &'static str) -> RlRule {
+ RlRule { name, table, concludes_false: false, engine_name }
+}
+
+/// The OWL 2 RL profile's inference rules. Seventy-eight of them.
+pub const OWL2_RL_RULES: &[RlRule] = &[
+ // Table 4: The Semantics of Equality.
+ r("eq-ref", "eq"),
+ r("eq-sym", "eq"),
+ r("eq-trans", "eq"),
+ r("eq-rep-s", "eq"),
+ r("eq-rep-p", "eq"),
+ r("eq-rep-o", "eq"),
+ rf("eq-diff1", "eq"),
+ rf("eq-diff2", "eq"),
+ rf("eq-diff3", "eq"),
+ // Table 5: The Semantics of Axioms about Properties.
+ r("prp-ap", "prp"),
+ ra("prp-dom", "prp", "rdfs2"),
+ ra("prp-rng", "prp", "rdfs3"),
+ r("prp-fp", "prp"),
+ r("prp-ifp", "prp"),
+ rf("prp-irp", "prp"),
+ r("prp-symp", "prp"),
+ rf("prp-asyp", "prp"),
+ r("prp-trp", "prp"),
+ ra("prp-spo1", "prp", "rdfs7"),
+ r("prp-spo2", "prp"),
+ r("prp-eqp1", "prp"),
+ r("prp-eqp2", "prp"),
+ rf("prp-pdw", "prp"),
+ rf("prp-adp", "prp"),
+ r("prp-inv1", "prp"),
+ r("prp-inv2", "prp"),
+ r("prp-key", "prp"),
+ rf("prp-npa1", "prp"),
+ rf("prp-npa2", "prp"),
+ // Table 6: The Semantics of Classes.
+ r("cls-thing", "cls"),
+ r("cls-nothing1", "cls"),
+ rf("cls-nothing2", "cls"),
+ r("cls-int1", "cls"),
+ r("cls-int2", "cls"),
+ r("cls-uni", "cls"),
+ rf("cls-com", "cls"),
+ r("cls-svf1", "cls"),
+ r("cls-svf2", "cls"),
+ r("cls-avf", "cls"),
+ r("cls-hv1", "cls"),
+ r("cls-hv2", "cls"),
+ rf("cls-maxc1", "cls"),
+ r("cls-maxc2", "cls"),
+ rf("cls-maxqc1", "cls"),
+ rf("cls-maxqc2", "cls"),
+ r("cls-maxqc3", "cls"),
+ r("cls-maxqc4", "cls"),
+ r("cls-oo", "cls"),
+ // Table 7: The Semantics of Class Axioms.
+ ra("cax-sco", "cax", "rdfs9"),
+ r("cax-eqc1", "cax"),
+ r("cax-eqc2", "cax"),
+ rf("cax-dw", "cax"),
+ rf("cax-adc", "cax"),
+ // Table 8: The Semantics of Datatypes.
+ r("dt-type1", "dt"),
+ r("dt-type2", "dt"),
+ r("dt-eq", "dt"),
+ r("dt-diff", "dt"),
+ rf("dt-not-type", "dt"),
+ // Table 9: The Semantics of Schema Vocabulary.
+ r("scm-cls", "scm"),
+ ra("scm-sco", "scm", "rdfs11"),
+ r("scm-eqc1", "scm"),
+ r("scm-eqc2", "scm"),
+ r("scm-op", "scm"),
+ r("scm-dp", "scm"),
+ ra("scm-spo", "scm", "rdfs5"),
+ r("scm-eqp1", "scm"),
+ r("scm-eqp2", "scm"),
+ r("scm-dom1", "scm"),
+ r("scm-dom2", "scm"),
+ r("scm-rng1", "scm"),
+ r("scm-rng2", "scm"),
+ r("scm-hv", "scm"),
+ r("scm-svf1", "scm"),
+ r("scm-svf2", "scm"),
+ r("scm-avf1", "scm"),
+ r("scm-avf2", "scm"),
+ r("scm-int", "scm"),
+ r("scm-uni", "scm"),
+];
+
+/// What this engine does with an OWL 2 RL rule.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum RuleStatus {
+ /// Evaluated in the forward-chaining fixpoint, under the named profile.
+ Evaluated(&'static str),
+ /// Concludes `false`, and the clash detector looks for it.
+ ClashDetected,
+ /// Concludes `false`, and the clash detector does NOT look for it. The
+ /// reason travels with it, from `reason::CLASH_RULES_NOT_DETECTED`.
+ ClashNotDetected(&'static str),
+ /// No rule in this engine fires on it, and there is no clash detector for
+ /// it either.
+ NotImplemented,
+}
+
+impl RuleStatus {
+ pub fn word(self) -> &'static str {
+ match self {
+ RuleStatus::Evaluated(_) => "evaluated",
+ RuleStatus::ClashDetected => "clash_detected",
+ RuleStatus::ClashNotDetected(_) => "clash_not_detected",
+ RuleStatus::NotImplemented => "not_implemented",
+ }
+ }
+ /// Whether an axiom this rule would evaluate is visible to a run at all.
+ pub fn is_seen(self) -> bool {
+ matches!(self, RuleStatus::Evaluated(_) | RuleStatus::ClashDetected)
+ }
+}
+
+/// What this engine does with the named rule. Derived from `src/reason.rs`,
+/// never typed here: the two figures are then one figure.
+pub fn rule_status(name: &str) -> RuleStatus {
+ let Some(rule) = OWL2_RL_RULES.iter().find(|r| r.name == name) else {
+ return RuleStatus::NotImplemented;
+ };
+ if let Some((_, profile)) = crate::reason::RULES_EVALUATED
+ .iter()
+ .find(|(n, _)| *n == rule.engine_name)
+ {
+ return RuleStatus::Evaluated(profile);
+ }
+ if rule.concludes_false {
+ return match crate::reason::CLASH_RULES_NOT_DETECTED
+ .iter()
+ .find(|(n, _)| *n == rule.name)
+ {
+ Some((_, why)) => RuleStatus::ClashNotDetected(why),
+ None => RuleStatus::ClashDetected,
+ };
+ }
+ RuleStatus::NotImplemented
+}
+
+// ── Classifying a class expression ──────────────────────────────────────────
+
+/// Which side of an axiom a class expression stands on.
+///
+/// Not cosmetic and not symmetric. `owl:someValuesFrom` is legal in an
+/// antecedent (`∃r.B ⊑ C` is the Horn rule `r(x,y) ∧ B(y) → C(x)`) and illegal
+/// in a consequent (`C ⊑ ∃r.B` asserts a successor into existence, which a
+/// rule over a fixed set of terms cannot do). Half of this module is that one
+/// distinction.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Position {
+ Antecedent,
+ Consequent,
+}
+
+impl Position {
+ fn word(self) -> &'static str {
+ match self {
+ Position::Antecedent => "antecedent",
+ Position::Consequent => "consequent",
+ }
+ }
+}
+
+/// One construct that puts an axiom outside the fragment, with the reason.
+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
+pub struct Excluded {
+ /// The OWL construct, spelled as the ontology spells it.
+ pub construct: String,
+ /// Which side of the axiom it stands on.
+ pub position: &'static str,
+ /// Why a Horn rule over triple patterns cannot hold it. The category a
+ /// reader acts on: `disjunction in the consequent`, `existential in the
+ /// head`, `cardinality restriction`, `negation in the antecedent`.
+ pub reason: String,
+}
+
+/// What a class expression contributes in one position.
+#[derive(Default)]
+struct Verdict {
+ excluded: Vec<Excluded>,
+ /// True when something of the axiom still lands inside the fragment even
+ /// though `excluded` is not empty. Only a conjunction in the consequent and
+ /// a disjunction in the antecedent set it: those two SPLIT soundly and
+ /// nothing else does.
+ partial: bool,
+}
+
+impl Verdict {
+ fn inside() -> Verdict {
+ Verdict::default()
+ }
+ fn out(construct: impl Into<String>, position: Position, reason: impl Into<String>) -> Verdict {
+ Verdict {
+ excluded: vec![Excluded {
+ construct: construct.into(),
+ position: position.word(),
+ reason: reason.into(),
+ }],
+ partial: false,
+ }
+ }
+ fn is_inside(&self) -> bool {
+ self.excluded.is_empty()
+ }
+}
+
+/// How deep a chain of anonymous class expressions is followed before the
+/// classifier gives up and says so.
+///
+/// A blank-node cycle through `owl:intersectionOf` is legal RDF and is not
+/// legal OWL, and a classifier that recursed into one would hang. The visited
+/// set catches the cycle; the cap catches a legal-but-absurd nesting. Either
+/// way the axiom is REPORTED as unclassifiable and never passed over.
+const MAX_DEPTH: usize = 40;
+
+/// The short, shared spellings of the four reasons a reader acts on. Written
+/// once so a grep for one of them finds every site that produces it.
+const WHY_DISJUNCTIVE_HEAD: &str =
+ "disjunction in the consequent: a Horn clause has one atom in its head, and no rule table \
+ over triple patterns can conclude `A or B`";
+const WHY_EXISTENTIAL_HEAD: &str =
+ "existential in the head: the axiom asserts a successor into existence, and a rule over a \
+ fixed set of terms can only ever conclude about terms it already has";
+const WHY_NEGATIVE_BODY: &str =
+ "negation in the antecedent: a Horn body is a conjunction of positive atoms, and deciding \
+ that something is NOT of a class needs a closed world this engine does not assume";
+const WHY_UNIVERSAL_BODY: &str =
+ "a universal restriction in the antecedent: `all r . B` unfolds to a negated existential, \
+ which is a disjunction once it reaches the body of a rule";
+
+struct Classifier<'a> {
+ index: &'a TripleIndex,
+}
+
+impl Classifier<'_> {
+ fn has_type(&self, node: &str, ty: &str) -> bool {
+ self.index.objects(node, RDF_TYPE).iter().any(|o| o == ty)
+ }
+
+ fn cardinality(&self, node: &str, predicate: &str) -> Option<u32> {
+ let raw = self.index.object(node, predicate)?;
+ // A literal arrives as `"1"^^<...>`; take what is between the quotes.
+ let inner = raw.strip_prefix('"').and_then(|r| r.split('"').next())?;
+ inner.trim().parse::<u32>().ok()
+ }
+
+ /// Classify a class expression standing in `position`.
+ fn class(&self, node: &str, position: Position, seen: &mut BTreeSet<String>, depth: usize) -> Verdict {
+ if depth > MAX_DEPTH {
+ return Verdict::out(
+ "a class expression nested deeper than this classifier follows",
+ position,
+ format!(
+ "the nesting passed {MAX_DEPTH} levels. Reported rather than passed over: an \
+ expression nobody classified is not an expression nobody has to worry about"
+ ),
+ );
+ }
+ if !seen.insert(node.to_string()) {
+ return Verdict::out(
+ "a cyclic class expression",
+ position,
+ "the blank-node graph of this class expression contains a cycle, which is legal \
+ RDF and is not a legal OWL class expression, so nothing here can classify it",
+ );
+ }
+
+ let v = self.class_inner(node, position, seen, depth);
+ seen.remove(node);
+ v
+ }
+
+ fn class_inner(
+ &self,
+ node: &str,
+ position: Position,
+ seen: &mut BTreeSet<String>,
+ depth: usize,
+ ) -> Verdict {
+ if node == OWL_THING {
+ // `A subClassOf owl:Thing` is a tautology. The OWL 2 RL grammar
+ // excludes owl:Thing from BOTH positions, but it excludes it in the
+ // consequent for triviality and in the antecedent for expressive
+ // power, and reporting a tautology as a trust gap would be a false
+ // alarm.
+ return match position {
+ Position::Consequent => Verdict::inside(),
+ Position::Antecedent => Verdict::out(
+ "owl:Thing",
+ position,
+ "owl:Thing in the antecedent asks a rule to fire on every element of the \
+ domain, including the ones no term names. OWL 2 RL excludes owl:Thing from \
+ subClassExpression for that reason",
+ ),
+ };
+ }
+ if node == OWL_NOTHING {
+ return Verdict::inside();
+ }
+ // A named class with no class-expression machinery on it.
+ if node.starts_with('<') && self.class_construct(node).is_none() {
+ return Verdict::inside();
+ }
+ match self.class_construct(node) {
+ Some(Construct::Intersection(items)) => self.boolean(items, position, seen, depth, true),
+ Some(Construct::Union(items)) => self.boolean(items, position, seen, depth, false),
+ Some(Construct::OneOf) => match position {
+ Position::Antecedent => Verdict::inside(),
+ Position::Consequent => Verdict::out(
+ "owl:oneOf",
+ position,
+ format!(
+ "{WHY_DISJUNCTIVE_HEAD}. An enumeration in the consequent is exactly a \
+ disjunction of equalities"
+ ),
+ ),
+ },
+ Some(Construct::Complement(inner)) => match position {
+ // `A subClassOf (not B)` is `A and B subClassOf Nothing`, which
+ // IS Horn: the head is `false`. The negated operand moves to the
+ // body, so it is classified there.
+ Position::Consequent => {
+ let mut v = self.class(&inner, Position::Antecedent, seen, depth + 1);
+ // A split under a negation is not sound: weakening `B` makes
+ // `not B` stronger.
+ v.partial = false;
+ v
+ }
+ Position::Antecedent => {
+ Verdict::out("owl:complementOf", position, WHY_NEGATIVE_BODY)
+ }
+ },
+ Some(Construct::Restriction) => self.restriction(node, position, seen, depth),
+ Some(Construct::DataRange(what)) => Verdict::out(
+ what,
+ position,
+ "a constructed data range is outside the OWL 2 RL data-range grammar, and this \
+ engine has no datatype value space at all: none of dt-type1, dt-type2, dt-eq, \
+ dt-diff or dt-not-type is implemented",
+ ),
+ None => Verdict::out(
+ "an anonymous node in a class position with no recognised class construct",
+ position,
+ format!(
+ "the node {node} stands where a class expression must and carries none of \
+ owl:intersectionOf, owl:unionOf, owl:oneOf, owl:complementOf or \
+ owl:Restriction. It is reported rather than skipped, because an expression \
+ nobody read is not an expression nobody has to worry about"
+ ),
+ ),
+ }
+ }
+
+ /// A conjunction or a disjunction. `intersection` picks which.
+ ///
+ /// The splitting asymmetry lives here and nowhere else. A conjunction
+ /// splits in the CONSEQUENT (`A ⊑ B ⊓ C` is two axioms) and a disjunction
+ /// splits in the ANTECEDENT (`A ⊔ B ⊑ C` is two axioms). In the other
+ /// position neither splits, and dropping an operand there would be
+ /// UNSOUND rather than merely weaker.
+ fn boolean(
+ &self,
+ items: Vec<String>,
+ position: Position,
+ seen: &mut BTreeSet<String>,
+ depth: usize,
+ intersection: bool,
+ ) -> Verdict {
+ let splits = match position {
+ Position::Consequent => intersection,
+ Position::Antecedent => !intersection,
+ };
+ if !splits && !intersection {
+ return Verdict::out("owl:unionOf", position, WHY_DISJUNCTIVE_HEAD);
+ }
+ let mut excluded = Vec::new();
+ let mut any_inside = false;
+ let mut any_partial = false;
+ for item in &items {
+ let v = self.class(item, position, seen, depth + 1);
+ if v.is_inside() {
+ any_inside = true;
+ }
+ any_partial |= v.partial;
+ excluded.extend(v.excluded);
+ }
+ if excluded.is_empty() {
+ return Verdict::inside();
+ }
+ Verdict {
+ excluded,
+ // A conjunctive BODY does not split: dropping a conjunct from a
+ // rule body makes the rule fire more often, which is unsound, so
+ // one bad conjunct takes the whole axiom out.
+ partial: splits && (any_inside || any_partial),
+ }
+ }
+
+ fn restriction(
+ &self,
+ node: &str,
+ position: Position,
+ seen: &mut BTreeSet<String>,
+ depth: usize,
+ ) -> Verdict {
+ if let Some(filler) = self.index.object(node, OWL_SOME_VALUES_FROM) {
+ return match position {
+ // owl:Thing is excluded from the top-level `Class` alternative
+ // of subClassExpression and ADMITTED here: the grammar's second
+ // alternative is `'ObjectSomeValuesFrom' '(' OPE owl:Thing ')'`
+ // outright. Rule cls-svf2 is that case. Refusing it here was a
+ // false positive on legal OWL 2 RL, and it is the one the W3C
+ // grammar check of 15 September 2026 caught.
+ Position::Antecedent if filler == OWL_THING => Verdict::inside(),
+ Position::Antecedent => self.class(&filler, Position::Antecedent, seen, depth + 1),
+ Position::Consequent => {
+ Verdict::out("owl:someValuesFrom", position, WHY_EXISTENTIAL_HEAD)
+ }
+ };
+ }
+ if let Some(filler) = self.index.object(node, OWL_ALL_VALUES_FROM) {
+ return match position {
+ Position::Consequent => self.class(&filler, Position::Consequent, seen, depth + 1),
+ Position::Antecedent => {
+ Verdict::out("owl:allValuesFrom", position, WHY_UNIVERSAL_BODY)
+ }
+ };
+ }
+ if self.index.object(node, OWL_HAS_VALUE).is_some() {
+ return Verdict::inside();
+ }
+ if self.index.object(node, OWL_HAS_SELF).is_some() {
+ return Verdict::out(
+ "owl:hasSelf",
+ position,
+ "owl:hasSelf is in neither subClassExpression nor superClassExpression in the \
+ OWL 2 RL class grammar, in either position",
+ );
+ }
+ for (pred, spelling) in [
+ (OWL_MIN_CARDINALITY, "owl:minCardinality"),
+ (OWL_MIN_QUALIFIED_CARDINALITY, "owl:minQualifiedCardinality"),
+ ] {
+ if let Some(n) = self.cardinality(node, pred) {
+ if n == 0 {
+ // `min 0` constrains nothing at all.
+ return Verdict::inside();
+ }
+ return Verdict::out(
+ spelling,
+ position,
+ format!(
+ "cardinality restriction, and the existential half of one: a minimum of \
+ {n} asserts {n} successors into existence. {WHY_EXISTENTIAL_HEAD}"
+ ),
+ );
+ }
+ }
+ for (pred, spelling, qualified) in [
+ (OWL_MAX_CARDINALITY, "owl:maxCardinality", false),
+ (OWL_MAX_QUALIFIED_CARDINALITY, "owl:maxQualifiedCardinality", true),
+ ] {
+ if let Some(n) = self.cardinality(node, pred) {
+ if position == Position::Antecedent {
+ return Verdict::out(
+ spelling,
+ position,
+ "cardinality restriction in the antecedent: OWL 2 RL admits a maximum \
+ cardinality in superClassExpression only, because counting successors \
+ in a rule BODY needs the closed world it does not assume",
+ );
+ }
+ if n > 1 {
+ return Verdict::out(
+ spelling,
+ position,
+ format!(
+ "cardinality restriction above 1: a maximum of {n} concludes that \
+ SOME pair among {m} successors is equal, which is a disjunction in \
+ the head. OWL 2 RL admits 0 and 1 and no more",
+ m = n + 1
+ ),
+ );
+ }
+ // `max 0` and `max 1` are Horn: the head is `false` and
+ // `owl:sameAs` respectively. The QUALIFYING class stands in a
+ // body position, because the rule reads it to decide whether a
+ // successor counts, so it is classified as an antecedent.
+ // `owl:onDataRange` needs no recursion: a data range is not a
+ // class expression.
+ return match self.index.object(node, OWL_ON_CLASS) {
+ // Admitted by the grammar's second alternative,
+ // `'ObjectMaxCardinality' '(' zeroOrOne OPE owl:Thing ')'`,
+ // and axiomatised by cls-maxqc2 and cls-maxqc4, which key
+ // on `T(?x, owl:onClass, owl:Thing)`.
+ Some(on) if qualified && on != OWL_THING => {
+ self.class(&on, Position::Antecedent, seen, depth + 1)
+ }
+ _ => Verdict::inside(),
+ };
+ }
+ }
+ for (pred, spelling) in [
+ (OWL_CARDINALITY, "owl:cardinality"),
+ (OWL_QUALIFIED_CARDINALITY, "owl:qualifiedCardinality"),
+ ] {
+ if let Some(n) = self.cardinality(node, pred) {
+ return Verdict::out(
+ spelling,
+ position,
+ format!(
+ "cardinality restriction: an exact cardinality is a minimum and a maximum \
+ at once, and the minimum half is an existential. OWL 2 RL's class \
+ grammar has ObjectMaxCardinality and no exact form at all, so even \
+ `{spelling} 0`, which IS equivalent to a maximum of 0, is outside it, \
+ and this engine reads no such equivalence. Found {n}"
+ ),
+ );
+ }
+ }
+ Verdict::out(
+ "an owl:Restriction with no recognised restriction predicate",
+ position,
+ format!(
+ "the node {node} is typed owl:Restriction and carries none of \
+ owl:someValuesFrom, owl:allValuesFrom, owl:hasValue, owl:hasSelf or a \
+ cardinality predicate"
+ ),
+ )
+ }
+
+ fn class_construct(&self, node: &str) -> Option<Construct> {
+ if let Some(head) = self.index.object(node, OWL_INTERSECTION_OF) {
+ return Some(Construct::Intersection(self.index.walk_list_checked(&head).0));
+ }
+ if let Some(head) = self.index.object(node, OWL_UNION_OF) {
+ return Some(Construct::Union(self.index.walk_list_checked(&head).0));
+ }
+ if self.index.object(node, OWL_ONE_OF).is_some() {
+ // The members are individuals, not class expressions, so nothing
+ // recurses into them and the list is not walked.
+ return Some(Construct::OneOf);
+ }
+ if let Some(c) = self.index.object(node, OWL_COMPLEMENT_OF) {
+ return Some(Construct::Complement(c));
+ }
+ if self.index.object(node, OWL_DATATYPE_COMPLEMENT).is_some() {
+ return Some(Construct::DataRange("owl:datatypeComplementOf"));
+ }
+ if self.index.object(node, OWL_WITH_RESTRICTIONS).is_some()
+ || self.index.object(node, OWL_ON_DATATYPE).is_some()
+ {
+ return Some(Construct::DataRange("a datatype facet restriction"));
+ }
+ if self.has_type(node, OWL_RESTRICTION) || self.index.object(node, OWL_ON_PROPERTY).is_some()
+ {
+ return Some(Construct::Restriction);
+ }
+ None
+ }
+}
+
+enum Construct {
+ Intersection(Vec<String>),
+ Union(Vec<String>),
+ OneOf,
+ Complement(String),
+ Restriction,
+ DataRange(&'static str),
+}
+
+// ── Axioms ──────────────────────────────────────────────────────────────────
+
+/// Where an axiom stands against the fragment.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Standing {
+ /// Every part of it is a Horn rule over triple patterns.
+ Inside,
+ /// Part of it is and part of it is not, and the parts separate soundly.
+ Partial,
+ /// None of it is.
+ Outside,
+}
+
+impl Standing {
+ pub fn word(self) -> &'static str {
+ match self {
+ Standing::Inside => "inside",
+ Standing::Partial => "partially_inside",
+ Standing::Outside => "outside",
+ }
+ }
+}
+
+/// One classified axiom.
+pub struct Classified {
+ pub kind: &'static str,
+ pub subject: String,
+ pub object: Option<String>,
+ pub standing: Standing,
+ pub excluded: Vec<Excluded>,
+ /// The OWL 2 RL rules that would evaluate an axiom of this shape.
+ pub rules: Vec<&'static str>,
+ /// Set on the two axiom forms that ARE Horn and are still excluded from
+ /// OWL 2 RL, so "outside the fragment" is never said about them without
+ /// the qualification.
+ pub horn_but_outside_owl2_rl: Option<&'static str>,
+}
+
+impl Classified {
+ /// The rules that would evaluate this axiom and are not implemented here.
+ fn unseen_rules(&self) -> Vec<(&'static str, RuleStatus)> {
+ self.rules
+ .iter()
+ .map(|n| (*n, rule_status(n)))
+ .filter(|(_, s)| !s.is_seen())
+ .collect()
+ }
+ fn seen_rules(&self) -> Vec<&'static str> {
+ self.rules.iter().copied().filter(|n| rule_status(n).is_seen()).collect()
+ }
+}
+
+// ── The report ──────────────────────────────────────────────────────────────
+
+/// The most rows of any one list that are printed individually.
+///
+/// The same bound `onto_defects` uses, for the same reason: one bad pattern in
+/// a shared vocabulary produces thousands of identical rows and a reader facing
+/// a thousand identical rows decides nothing from them. The totals are still
+/// reported, so the cap hides the listing and never the scale.
+pub const MAX_LISTED: usize = 50;
+
+#[derive(Default)]
+struct Counts {
+ total: u64,
+ inside: u64,
+ partial: u64,
+ outside: u64,
+ fully_seen: u64,
+ rule_not_implemented: u64,
+}
+
+pub struct DlpBoundary;
+
+impl DlpBoundary {
+ pub fn check(graph: &Arc<GraphStore>) -> anyhow::Result<String> {
+ let triples = graph.all_triples()?;
+ let total_triples = triples.len();
+ let index = TripleIndex::new(&triples);
+ let cl = Classifier { index: &index };
+
+ let mut axioms: Vec<Classified> = Vec::new();
+ let mut not_classified: BTreeMap<&'static str, u64> = BTreeMap::new();
+
+ for (s, p, o) in &triples {
+ match Self::axiom(&cl, s, p, o) {
+ Some(a) => axioms.push(a),
+ None => *not_classified.entry(Self::unclassified_kind(p, o)).or_default() += 1,
+ }
+ }
+
+ // ── Fold ────────────────────────────────────────────────────────────
+ let mut by_kind: BTreeMap<&'static str, Counts> = BTreeMap::new();
+ let mut outside_list: Vec<serde_json::Value> = Vec::new();
+ let mut partial_list: Vec<serde_json::Value> = Vec::new();
+ let mut unimplemented_list: Vec<serde_json::Value> = Vec::new();
+ let mut outside_total = 0u64;
+ let mut partial_total = 0u64;
+ let mut unimplemented_total = 0u64;
+ let mut reason_census: BTreeMap<String, u64> = BTreeMap::new();
+
+ for a in &axioms {
+ let c = by_kind.entry(a.kind).or_default();
+ c.total += 1;
+ match a.standing {
+ Standing::Inside => c.inside += 1,
+ Standing::Partial => c.partial += 1,
+ Standing::Outside => c.outside += 1,
+ }
+ let unseen = a.unseen_rules();
+ let seen = a.seen_rules();
+ if a.standing != Standing::Outside && !unseen.is_empty() {
+ c.rule_not_implemented += 1;
+ unimplemented_total += 1;
+ if unimplemented_list.len() < MAX_LISTED {
+ unimplemented_list.push(serde_json::json!({
+ "axiom_type": a.kind,
+ "subject": a.subject,
+ "object": a.object,
+ "standing": a.standing.word(),
+ "rules_that_would_evaluate_it": a.rules,
+ "rules_this_engine_runs": seen,
+ "rules_this_engine_does_not": unseen.iter().map(|(n, s)| {
+ serde_json::json!({
+ "rule": n,
+ "status": s.word(),
+ "why": match s {
+ RuleStatus::ClashNotDetected(why) => Some(*why),
+ _ => None,
+ },
+ })
+ }).collect::<Vec<_>>(),
+ }));
+ }
+ } else if a.standing == Standing::Inside && unseen.is_empty() {
+ c.fully_seen += 1;
+ }
+ // The two are listed apart. A bucket called `outside` that also
+ // held the axioms half of which the rules DO evaluate would be
+ // saying something false in its own name, which is the failure
+ // this whole module is about.
+ if a.standing != Standing::Inside {
+ for e in &a.excluded {
+ *reason_census.entry(e.reason.clone()).or_default() += 1;
+ }
+ let entry = serde_json::json!({
+ "axiom_type": a.kind,
+ "subject": a.subject,
+ "object": a.object,
+ "standing": a.standing.word(),
+ "outside_because": a.excluded,
+ "horn_but_outside_owl2_rl": a.horn_but_outside_owl2_rl,
+ });
+ if a.standing == Standing::Outside {
+ outside_total += 1;
+ if outside_list.len() < MAX_LISTED {
+ outside_list.push(entry);
+ }
+ } else {
+ partial_total += 1;
+ if partial_list.len() < MAX_LISTED {
+ partial_list.push(entry);
+ }
+ }
+ }
+ }
+
+ let classified: u64 = by_kind.values().map(|c| c.total).sum();
+ let not_fully_seen = outside_total + partial_total + unimplemented_total;
+
+ let by_kind_json: Vec<serde_json::Value> = by_kind
+ .iter()
+ .map(|(k, c)| {
+ serde_json::json!({
+ "axiom_type": k,
+ "total": c.total,
+ "inside": c.inside,
+ "partially_inside": c.partial,
+ "outside": c.outside,
+ "inside_and_every_rule_implemented": c.fully_seen,
+ "inside_but_a_rule_is_not_implemented": c.rule_not_implemented,
+ })
+ })
+ .collect();
+
+ let evaluated = OWL2_RL_RULES
+ .iter()
+ .filter(|r| matches!(rule_status(r.name), RuleStatus::Evaluated(_)))
+ .count();
+ let clash_detected = OWL2_RL_RULES
+ .iter()
+ .filter(|r| rule_status(r.name) == RuleStatus::ClashDetected)
+ .count();
+ let clash_not_detected = OWL2_RL_RULES
+ .iter()
+ .filter(|r| matches!(rule_status(r.name), RuleStatus::ClashNotDetected(_)))
+ .count();
+ let not_implemented: Vec<&str> = OWL2_RL_RULES
+ .iter()
+ .filter(|r| rule_status(r.name) == RuleStatus::NotImplemented)
+ .map(|r| r.name)
+ .collect();
+ // Per profile, counted rather than written down. A run at `rdfs`
+ // evaluates a fraction of the table, and a report that said 29 to such
+ // a run would be describing a table the run never used. The profiles
+ // nest: `owl-rl` adds to `rdfs` and `owl-rl-ext` adds to `owl-rl`.
+ let at_rdfs = crate::reason::RULES_EVALUATED.iter().filter(|(_, p)| *p == "rdfs").count();
+ let at_owl_rl = at_rdfs
+ + crate::reason::RULES_EVALUATED.iter().filter(|(_, p)| *p == "owl-rl").count();
+
+ let report = serde_json::json!({
+ "ok": true,
+ "triples": total_triples,
+ "axioms_classified": classified,
+ "question": "Which of the axioms YOU wrote can the rule engine see? A certificate \
+ from onto_reason is sound about the axioms the rules read, and says \
+ nothing about the ones no rule fires on. This is that second thing",
+ "two_dimensions_never_merged": {
+ "fragment": "whether the axiom is expressible as Horn rules over triple patterns \
+ at all. `outside` here is a fact about the LANGUAGE and would hold \
+ of a perfect OWL 2 RL engine. The line drawn is OWL 2 RL's class \
+ grammar (OWL 2 Profiles section 4.3): subClassExpression for an \
+ antecedent, superClassExpression for a consequent",
+ "engine": "whether a rule in THIS engine's table fires on it. \
+ `inside_but_a_rule_is_not_implemented` is an axiom that a different \
+ engine would see and that no rewriting of your ontology will help. \
+ owl:hasKey and owl:propertyChainAxiom are the two that bite most \
+ often",
+ "why_they_are_separate": "one is a rewrite of the ontology and the other is a \
+ patch to src/reason.rs. A single `not covered` bucket \
+ destroys the only thing a reader can act on",
+ },
+ "by_axiom_type": by_kind_json,
+ "outside_the_fragment": {
+ "count": outside_total,
+ "listed": outside_list.len(),
+ "truncated": outside_total > outside_list.len() as u64,
+ "what_this_means": "NO part of the axiom is a Horn rule over triple patterns. \
+ This is a fact about the LANGUAGE: it would hold of a \
+ perfect OWL 2 RL engine, and the fix, if there is one, is a \
+ rewriting of the ontology",
+ "axioms": outside_list,
+ },
+ "partially_inside_the_fragment": {
+ "count": partial_total,
+ "listed": partial_list.len(),
+ "truncated": partial_total > partial_list.len() as u64,
+ "why_not_outside": "part of the axiom IS evaluated and reporting it beside the \
+ wholly-outside ones would say the rules see nothing of it. Two shapes split \
+ soundly: a conjunction in the CONSEQUENT (`A subClassOf (B and Out)` keeps \
+ `A subClassOf B`) and a disjunction in the ANTECEDENT. A conjunction in the \
+ antecedent does NOT split, because dropping a conjunct from a rule body \
+ makes it fire more often, which is unsound and not merely weaker",
+ "axioms": partial_list,
+ },
+ "reasons": reason_census.iter().map(|(r, n)| {
+ serde_json::json!({"reason": r, "occurrences": n})
+ }).collect::<Vec<_>>(),
+ "inside_the_fragment_but_a_rule_is_not_implemented": {
+ "count": unimplemented_total,
+ "listed": unimplemented_list.len(),
+ "truncated": unimplemented_total > unimplemented_list.len() as u64,
+ "why_this_is_a_different_failure": "these axioms ARE Horn. OWL 2 RL has a rule \
+ for each of them and this engine does not run it. Rewriting the ontology \
+ will not help and the fix is in src/reason.rs",
+ "axioms": unimplemented_list,
+ },
+ "not_fully_seen_by_the_rule_table": {
+ "axioms": not_fully_seen,
+ "of_classified": classified,
+ "wholly_outside_the_fragment": outside_total,
+ "partially_inside_the_fragment": partial_total,
+ "inside_but_a_rule_is_not_implemented": unimplemented_total,
+ "what_this_means": "a reasoning result over this ontology is sound about the \
+ axioms the rules read and silent about what these carry. It \
+ is not wrong; it is narrower than the ontology, and nothing \
+ else in the pipeline says by how much",
+ "why_the_three_are_not_added_into_one_verdict": "they are fixed in three \
+ different places. The first needs the ontology rewritten, the second is \
+ already half seen and the question is which half you needed, and the third \
+ needs a rule added to src/reason.rs and nothing changed about the ontology \
+ at all",
+ },
+ "rule_table": {
+ "owl2_rl_rules": OWL2_RL_RULES.len(),
+ "evaluated_in_the_fixpoint": evaluated,
+ "detected_as_a_clash": clash_detected,
+ "concludes_false_and_not_detected": clash_not_detected,
+ "not_implemented": not_implemented.len(),
+ "not_implemented_names": not_implemented,
+ "source": "the counts are derived from reason::RULES_EVALUATED and \
+ reason::CLASH_RULES_NOT_DETECTED, not typed here, so this figure and \
+ the rule table cannot drift apart",
+ "evaluated_by_profile": {
+ "rdfs": at_rdfs,
+ "owl-rl": at_owl_rl,
+ "owl-rl-ext": evaluated,
+ "why": "the profiles NEST, and a run evaluates only its own share. A report \
+ quoting the full table to an `rdfs` run would be describing rules \
+ that run never used. Counted from reason::RULES_EVALUATED, which \
+ carries the profile per rule",
+ },
+ },
+ "not_classified": {
+ "why": "this tool asks about the SCHEMA. Class and property assertions, \
+ declarations and annotations are counted here and not classified: every \
+ assertion form in OWL 2 RL is inside the fragment, and an annotation has \
+ no Direct Semantics content at all. Counted rather than passed over in \
+ silence",
+ "counts": not_classified.iter().map(|(k, n)| {
+ serde_json::json!({"what": k, "occurrences": n})
+ }).collect::<Vec<_>>(),
+ },
+ "not_a_consistency_check": "this says nothing about whether the ontology is \
+ satisfiable, and nothing about whether OWL 2 RL entails anything. Run \
+ onto_defects for self-defeating declarations and onto_dl_check for \
+ satisfiability",
+ });
+ Ok(serde_json::to_string(&report)?)
+ }
+
+ /// The axiom a triple states, classified, or `None` when the triple is not
+ /// a schema axiom this tool reads.
+ fn axiom(cl: &Classifier, s: &str, p: &str, o: &str) -> Option<Classified> {
+ let mut seen = BTreeSet::new();
+ let simple = |kind, rules: Vec<&'static str>| Classified {
+ kind,
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ standing: Standing::Inside,
+ excluded: Vec::new(),
+ rules,
+ horn_but_outside_owl2_rl: None,
+ };
+ match p {
+ RDFS_SUBCLASS => {
+ let body = cl.class(s, Position::Antecedent, &mut seen, 0);
+ seen.clear();
+ let head = cl.class(o, Position::Consequent, &mut seen, 0);
+ let mut excluded = body.excluded;
+ let any_partial = body.partial || head.partial;
+ excluded.extend(head.excluded);
+ let standing = if excluded.is_empty() {
+ Standing::Inside
+ } else if any_partial {
+ Standing::Partial
+ } else {
+ Standing::Outside
+ };
+ let mut rules = vec!["cax-sco", "scm-sco"];
+ rules.extend(Self::construct_rules(cl, s));
+ rules.extend(Self::construct_rules(cl, o));
+ rules.sort_unstable();
+ rules.dedup();
+ Some(Classified {
+ kind: "rdfs:subClassOf",
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ standing,
+ excluded,
+ rules,
+ horn_but_outside_owl2_rl: None,
+ })
+ }
+ OWL_EQUIV_CLASS => {
+ // Two axioms, and they are classified separately: `A ≡ ∃r.B`
+ // is the textbook case where one direction is a Horn rule
+ // (cls-svf1) and the other is an existential in the head.
+ let forward = Self::direction(cl, s, o);
+ let backward = Self::direction(cl, o, s);
+ let standing = match (forward.is_inside(), backward.is_inside()) {
+ (true, true) => Standing::Inside,
+ (false, false) => {
+ if forward.partial || backward.partial {
+ Standing::Partial
+ } else {
+ Standing::Outside
+ }
+ }
+ _ => Standing::Partial,
+ };
+ let mut excluded = forward.excluded;
+ excluded.extend(backward.excluded);
+ let mut rules = vec!["cax-eqc1", "cax-eqc2", "scm-eqc1", "scm-eqc2"];
+ rules.extend(Self::construct_rules(cl, s));
+ rules.extend(Self::construct_rules(cl, o));
+ rules.sort_unstable();
+ rules.dedup();
+ Some(Classified {
+ kind: "owl:equivalentClass",
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ standing,
+ excluded,
+ rules,
+ horn_but_outside_owl2_rl: None,
+ })
+ }
+ OWL_DISJOINT_WITH => {
+ // `A ⊓ B ⊑ ⊥`. A Horn clause with `false` in the head, so it is
+ // inside; the operands stand in ANTECEDENT position.
+ let mut excluded = cl.class(s, Position::Antecedent, &mut seen, 0).excluded;
+ seen.clear();
+ excluded.extend(cl.class(o, Position::Antecedent, &mut seen, 0).excluded);
+ Some(Classified {
+ kind: "owl:disjointWith",
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ standing: if excluded.is_empty() { Standing::Inside } else { Standing::Outside },
+ excluded,
+ rules: vec!["cax-dw"],
+ horn_but_outside_owl2_rl: None,
+ })
+ }
+ // Only on a NAMED class. A blank-node subject carrying
+ // owl:complementOf is an anonymous class EXPRESSION, an operand of
+ // whichever axiom uses it, and is classified there. Reading it as
+ // an axiom of its own would report the same exclusion twice and
+ // inflate every count in the report.
+ OWL_COMPLEMENT_OF if s.starts_with('<') => Some(Classified {
+ kind: "owl:complementOf",
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ // `A ≡ ¬B` is `A ⊓ B ⊑ ⊥` (Horn, cls-com) AND `⊤ ⊑ A ⊔ B`
+ // (a disjunction with no antecedent, and not Horn).
+ standing: Standing::Partial,
+ excluded: vec![Excluded {
+ construct: "owl:complementOf, the covering half".to_string(),
+ position: "consequent",
+ reason: format!(
+ "{WHY_DISJUNCTIVE_HEAD}. A complement says two things: nothing is in both \
+ (which IS Horn, and is what cls-com checks) and everything is in one \
+ (which is `A or B` with no antecedent at all)"
+ ),
+ }],
+ rules: vec!["cls-com"],
+ horn_but_outside_owl2_rl: None,
+ }),
+ OWL_DISJOINT_UNION => Some(Classified {
+ kind: "owl:disjointUnionOf",
+ subject: s.to_string(),
+ object: Some(o.to_string()),
+ standing: Standing::Partial,
+ excluded: vec![Excluded {
+ construct: "owl:disjointUnionOf".to_string(),
+ position: "consequent",
+ reason: format!(
+ "{WHY_DISJUNCTIVE_HEAD}. The pairwise disjointness half IS Horn and this \
+ engine reads it only in its owl:disjointWith spelling"
+ ),
+ }],
+ rules: vec!["cax-dw"],
+ horn_but_outside_owl2_rl: Some(
+ "DisjointUnion is excluded from OWL 2 RL as an axiom form, so the profile \
+ rejects it whole, while the disjointness half of what it says is Horn",
+ ),
+ }),
+ RDFS_SUBPROP => Some(simple("rdfs:subPropertyOf", vec!["prp-spo1", "scm-spo"])),
+ OWL_EQUIV_PROP => Some(simple(
+ "owl:equivalentProperty",
+ vec!["prp-eqp1", "prp-eqp2", "scm-eqp1", "scm-eqp2"],
+ )),
+ RDFS_DOMAIN => {
+ let mut c = simple("rdfs:domain", vec!["prp-dom", "scm-dom1", "scm-dom2"]);
+ c.excluded = cl.class(o, Position::Consequent, &mut seen, 0).excluded;
+ if !c.excluded.is_empty() {
+ c.standing = Standing::Outside;
+ }
+ Some(c)
+ }
+ RDFS_RANGE => {
+ let mut c = simple("rdfs:range", vec!["prp-rng", "scm-rng1", "scm-rng2"]);
+ c.excluded = cl.class(o, Position::Consequent, &mut seen, 0).excluded;
+ if !c.excluded.is_empty() {
+ c.standing = Standing::Outside;
+ }
+ Some(c)
+ }
+ OWL_INVERSE_OF => Some(simple("owl:inverseOf", vec!["prp-inv1", "prp-inv2"])),
+ OWL_PROPERTY_CHAIN => Some(simple("owl:propertyChainAxiom", vec!["prp-spo2"])),
+ OWL_PROP_DISJOINT_WITH => {
+ Some(simple("owl:propertyDisjointWith", vec!["prp-pdw"]))
+ }
+ OWL_HAS_KEY => Some(simple("owl:hasKey", vec!["prp-key"])),
+ OWL_SAME_AS => Some(simple(
+ "owl:sameAs",
+ vec!["eq-sym", "eq-trans", "eq-rep-s", "eq-rep-p", "eq-rep-o"],
+ )),
+ OWL_DIFFERENT_FROM => Some(simple("owl:differentFrom", vec!["eq-diff1"])),
+ RDF_TYPE => Self::typed_axiom(s, o),
+ _ => None,
+ }
+ }
+
+ /// The axioms stated by typing a node rather than by a predicate: the six
+ /// property characteristics, and the four list-shaped forms.
+ ///
+ /// The four list-shaped ones are INSIDE the fragment and are exactly where
+ /// this engine's rule table stops: `cax-adc`, `prp-adp`, `eq-diff2` and
+ /// `eq-diff3` are all in `reason::CLASH_RULES_NOT_DETECTED` because the
+ /// clash detector reads no RDF lists. The pairwise spellings of the same
+ /// three axioms ARE detected, which is the difference a reader needs.
+ fn typed_axiom(s: &str, o: &str) -> Option<Classified> {
+ let (kind, rules): (&'static str, Vec<&'static str>) = match o {
+ OWL_ALL_DISJOINT_CLASSES => ("owl:AllDisjointClasses", vec!["cax-adc"]),
+ OWL_ALL_DISJOINT_PROPS => ("owl:AllDisjointProperties", vec!["prp-adp"]),
+ OWL_ALL_DIFFERENT => ("owl:AllDifferent", vec!["eq-diff2", "eq-diff3"]),
+ OWL_NEGATIVE_PROP_ASSERTION => {
+ ("owl:NegativePropertyAssertion", vec!["prp-npa1", "prp-npa2"])
+ }
+ _ => return Self::characteristic(s, o),
+ };
+ Some(Classified {
+ kind,
+ subject: s.to_string(),
+ object: None,
+ standing: Standing::Inside,
+ excluded: Vec::new(),
+ rules,
+ horn_but_outside_owl2_rl: None,
+ })
+ }
+
+ /// One direction of an equivalence, as a subsumption.
+ fn direction(cl: &Classifier, sub: &str, sup: &str) -> Verdict {
+ let mut seen = BTreeSet::new();
+ let body = cl.class(sub, Position::Antecedent, &mut seen, 0);
+ seen.clear();
+ let head = cl.class(sup, Position::Consequent, &mut seen, 0);
+ let mut excluded = body.excluded;
+ let partial = body.partial || head.partial;
+ excluded.extend(head.excluded);
+ Verdict { excluded, partial }
+ }
+
+ /// A property-characteristic declaration, as an axiom.
+ fn characteristic(s: &str, o: &str) -> Option<Classified> {
+ let mk = |kind, rules: Vec<&'static str>, standing, excluded, note| Classified {
+ kind,
+ subject: s.to_string(),
+ object: None,
+ standing,
+ excluded,
+ rules,
+ horn_but_outside_owl2_rl: note,
+ };
+ match o {
+ OWL_TRANSITIVE => Some(mk(
+ "owl:TransitiveProperty",
+ vec!["prp-trp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_SYMMETRIC => Some(mk(
+ "owl:SymmetricProperty",
+ vec!["prp-symp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_ASYMMETRIC => Some(mk(
+ "owl:AsymmetricProperty",
+ vec!["prp-asyp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_IRREFLEXIVE => Some(mk(
+ "owl:IrreflexiveProperty",
+ vec!["prp-irp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_FUNCTIONAL => Some(mk(
+ "owl:FunctionalProperty",
+ vec!["prp-fp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_INVERSE_FUNCTIONAL => Some(mk(
+ "owl:InverseFunctionalProperty",
+ vec!["prp-ifp"],
+ Standing::Inside,
+ Vec::new(),
+ None,
+ )),
+ OWL_REFLEXIVE => Some(mk(
+ "owl:ReflexiveProperty",
+ Vec::new(),
+ Standing::Outside,
+ vec![Excluded {
+ construct: "owl:ReflexiveProperty".to_string(),
+ position: "consequent",
+ reason: "ReflexiveObjectProperty is one of the two axiom forms OWL 2 RL \
+ excludes outright, so no rule of the profile evaluates it and there \
+ is nothing for an engine to implement"
+ .to_string(),
+ }],
+ Some(
+ "reflexivity IS a Horn clause: `thing(x) -> r(x,x)`. It is outside OWL 2 RL \
+ and not outside Horn logic, and saying `outside the fragment` without that \
+ qualification would be false. What OWL 2 RL's exclusion protects is the \
+ unnamed part of the domain, which a rule over the terms in the graph cannot \
+ reach",
+ ),
+ )),
+ _ => None,
+ }
+ }
+
+ /// The class-construct rules a node contributes, so a `subClassOf` whose
+ /// consequent is `all r . B` is reported against `cls-avf` and not only
+ /// against `cax-sco`.
+ fn construct_rules(cl: &Classifier, node: &str) -> Vec<&'static str> {
+ match cl.class_construct(node) {
+ Some(Construct::Intersection(_)) => vec!["cls-int1", "cls-int2", "scm-int"],
+ Some(Construct::Union(_)) => vec!["cls-uni", "scm-uni"],
+ Some(Construct::OneOf) => vec!["cls-oo"],
+ Some(Construct::Complement(_)) => vec!["cls-com"],
+ Some(Construct::Restriction) => {
+ if cl.index.object(node, OWL_SOME_VALUES_FROM).is_some() {
+ vec!["cls-svf1", "cls-svf2", "scm-svf1", "scm-svf2"]
+ } else if cl.index.object(node, OWL_ALL_VALUES_FROM).is_some() {
+ vec!["cls-avf", "scm-avf1", "scm-avf2"]
+ } else if cl.index.object(node, OWL_HAS_VALUE).is_some() {
+ vec!["cls-hv1", "cls-hv2", "scm-hv"]
+ } else if cl.index.object(node, OWL_MAX_CARDINALITY).is_some() {
+ vec!["cls-maxc1", "cls-maxc2"]
+ } else if cl.index.object(node, OWL_MAX_QUALIFIED_CARDINALITY).is_some() {
+ vec!["cls-maxqc1", "cls-maxqc2", "cls-maxqc3", "cls-maxqc4"]
+ } else {
+ Vec::new()
+ }
+ }
+ _ => Vec::new(),
+ }
+ }
+
+ /// What a triple that is not a schema axiom is, so the count of what this
+ /// tool did not look at is a NUMBER and not a silence.
+ ///
+ /// Every triple in the store lands in exactly one of these buckets or in
+ /// `axioms`, and `every_triple_lands_somewhere` is the gate that the
+ /// partition is total. A tool that reports on a fragment and leaves the
+ /// rest uncounted is the shape this whole module exists to attack.
+ fn unclassified_kind(p: &str, o: &str) -> &'static str {
+ const OWL_NS: &str = "<http://www.w3.org/2002/07/owl#";
+ const RDF_NS: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+ const RDFS_NS: &str = "<http://www.w3.org/2000/01/rdf-schema#";
+
+ if p == RDF_TYPE {
+ if o == OWL_RESTRICTION {
+ return "a class expression node, classified with the axiom that uses it";
+ }
+ if o.starts_with(OWL_NS) || o.starts_with(RDFS_NS) {
+ return "a declaration (owl:Class, owl:ObjectProperty and the rest)";
+ }
+ return "a class assertion";
+ }
+ // The operand of a class expression, or the RDF list carrying it. Read
+ // as PART of the axiom it belongs to rather than as an axiom of its
+ // own, which is why it is counted here and classified there.
+ if p.starts_with(RDF_NS) {
+ return "RDF list machinery inside a class expression or an axiom";
+ }
+ if matches!(
+ p,
+ OWL_INTERSECTION_OF
+ | OWL_UNION_OF
+ | OWL_ONE_OF
+ | OWL_ON_PROPERTY
+ | OWL_ON_CLASS
+ | OWL_ON_DATA_RANGE
+ | OWL_SOME_VALUES_FROM
+ | OWL_ALL_VALUES_FROM
+ | OWL_HAS_VALUE
+ | OWL_HAS_SELF
+ | OWL_MIN_CARDINALITY
+ | OWL_MAX_CARDINALITY
+ | OWL_CARDINALITY
+ | OWL_MIN_QUALIFIED_CARDINALITY
+ | OWL_MAX_QUALIFIED_CARDINALITY
+ | OWL_QUALIFIED_CARDINALITY
+ | OWL_ON_DATATYPE
+ | OWL_WITH_RESTRICTIONS
+ | OWL_DATATYPE_COMPLEMENT
+ | OWL_COMPLEMENT_OF
+ ) {
+ return "the body of a class expression, classified with the axiom that uses it";
+ }
+ if p.starts_with(RDFS_NS) || p.starts_with("<http://www.w3.org/2004/02/skos/core#")
+ || p.starts_with("<http://purl.org/dc/")
+ {
+ return "an annotation, which carries no Direct Semantics content";
+ }
+ if p.starts_with(OWL_NS) {
+ return "other OWL vocabulary, neither a schema axiom this tool reads nor an assertion";
+ }
+ if o.starts_with('"') {
+ return "a data-property assertion";
+ }
+ "an object-property assertion"
+ }
+}
diff --git a/src/inputs.rs b/src/inputs.rs
index b75ce110..68c0eb11 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -308,12 +308,17 @@ pub struct OntoReasonInput {
#[derive(Deserialize, JsonSchema)]
pub struct OntoFolExportInput {
- /// Directory to write the export to. `ontology.p` (TPTP) or
- /// `ontology.clif` lands here, plus one problem per goal under `goals/`.
+ /// Directory to write the export to. `ontology.p` (TPTP), `ontology.clif`
+ /// or `ontology.cgif` lands here, plus one problem per goal under
+ /// `goals/`.
pub out_dir: String,
- /// `tptp` (FOF, what E and Vampire read) or `clif` (ISO/IEC 24707 Common
- /// Logic Interchange Format, restricted to the first-order-equivalent
- /// fragment). Default `tptp`. Both are renderings of ONE translation.
+ /// `tptp` (FOF, what E and Vampire read), `clif` (ISO/IEC 24707 Common
+ /// Logic Interchange Format), `cgif` (ISO/IEC 24707 Conceptual Graph
+ /// Interchange Format, the SECOND Common Logic dialect, emitted as CORE
+ /// CGIF in a compact sub-dialect and taking no flags of its own),
+ /// `smtlib` or `ladr`. Default `tptp`. All five are renderings of ONE
+ /// translation, and the two Common Logic ones are restricted to the
+ /// first-order-equivalent fragment of it.
pub format: Option<String>,
/// A TSV of triples to ask as conjectures, one problem file per line. The
/// `derivations.tsv` written by `onto_reason` with `certificate_dir` is
diff --git a/src/lib.rs b/src/lib.rs
index 40a6e944..b80a599a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,6 +19,7 @@ pub mod communities;
pub mod config;
pub mod cq;
pub mod defects;
+pub mod dlp;
pub mod drift;
pub mod dynamics;
pub mod dynamics_bcplus;
diff --git a/src/main.rs b/src/main.rs
index 0e278e76..261b4aa1 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -466,16 +466,21 @@ enum Commands {
/// verdict on the output is an oracle opinion, never a certificate. A
/// MODEL is the other case: see `fol-model`.
Fol {
- /// Output directory. `ontology.p`, `.clif`, `.smt2` or `.in` lands
- /// here, plus one problem per goal under `goals/` when --goals is
+ /// Output directory. `ontology.p`, `.clif`, `.cgif`, `.smt2` or `.in`
+ /// lands here, plus one problem per goal under `goals/` when --goals is
/// given. Every run also writes `problem.tsv`, the format the verified
/// checker `oo-folmodel` reads, with its digest in the report.
#[arg(long)]
out: String,
- /// `tptp` (FOF, what provers read), `clif` (ISO/IEC 24707 Common
- /// Logic, restricted to the first-order-equivalent fragment),
- /// `smtlib` (SMT-LIB 2, what Z3 reads) or `ladr` (what Mace4 reads,
- /// with every symbol MANGLED and the table in `symbols.tsv`).
+ /// `tptp` (FOF, what provers read), `clif` or `cgif` (two of ISO/IEC
+ /// 24707 Common Logic's three dialects, both restricted to the
+ /// first-order-equivalent fragment), `smtlib` (SMT-LIB 2, what Z3
+ /// reads) or `ladr` (what Mace4 reads, with every symbol MANGLED and
+ /// the table in `symbols.tsv`).
+ ///
+ /// `cgif` is CORE CGIF in the compact sub-dialect clause 7.1.1 names:
+ /// no sequence markers, which is what clause 6.5 says takes Common
+ /// Logic past first order. It takes no dialect or comment flag.
///
/// The last two assert the NEGATED goal rather than declaring a
/// conjecture, because they are read by model finders and a
diff --git a/src/reason.rs b/src/reason.rs
index ecad9591..b014bd8b 100644
--- a/src/reason.rs
+++ b/src/reason.rs
@@ -108,7 +108,12 @@ fn clash_is_certifiable(rule: &str) -> bool {
/// The clash rules this engine does NOT look for, each with the reason. Listed
/// so that "no clash found" is never read as "consistent": the honest reading
/// of a clean run is that none of the rules below was even tried.
-const CLASH_RULES_NOT_DETECTED: &[(&str, &str)] = &[
+///
+/// `pub` because `src/dlp.rs` subtracts this list from the seventeen OWL 2 RL
+/// rules that conclude `false` to arrive at the ten that ARE detected. That
+/// number is then derived from this file rather than typed a second time
+/// somewhere else, which is the only way two copies of a figure stay equal.
+pub const CLASH_RULES_NOT_DETECTED: &[(&str, &str)] = &[
("cax-adc", "owl:AllDisjointClasses states its members in an RDF list, and this detector reads \
no lists. The pairwise owl:disjointWith spelling of the same axiom IS detected."),
("prp-adp", "owl:AllDisjointProperties states its members in an RDF list, and this detector \
@@ -124,6 +129,59 @@ const CLASH_RULES_NOT_DETECTED: &[(&str, &str)] = &[
nothing by value, so there is no notion here of a literal outside its type."),
];
+/// Every rule the forward-chaining fixpoint evaluates, with the profile that
+/// switches it on, spelled exactly as the `emit` call in this file spells it.
+///
+/// **This is the rule table, written down.** Twenty-nine names, and the figure
+/// "29 of OWL 2 RL's 78 rules" that six other files repeat is this list's
+/// length rather than a number somebody typed. `src/dlp.rs` reads it to decide
+/// whether an axiom a user wrote is one the rule engine can actually see, and
+/// `the_evaluated_rule_list_is_the_rules_this_file_emits` in
+/// `tests/dlp_boundary_test.rs` greps THIS FILE for its `emit` calls and fails
+/// if the two disagree. So a rule added below without an `emit`, or an `emit`
+/// added without a line here, is a test failure and not a silent drift.
+///
+/// The six RDFS spellings are OWL 2 RL rules under other names: `rdfs2` is
+/// `prp-dom`, `rdfs3` is `prp-rng`, `rdfs5` is `scm-spo`, `rdfs7` is
+/// `prp-spo1`, `rdfs9` is `cax-sco` and `rdfs11` is `scm-sco`. `src/dlp.rs`
+/// carries that map, because a user reading a W3C rule name has to be able to
+/// find it here.
+///
+/// The profile matters and is not decoration: a run at `rdfs` evaluates SIX of
+/// these and a report that said 29 to such a run would be describing a table
+/// the run never used.
+pub const RULES_EVALUATED: &[(&str, &str)] = &[
+ ("rdfs2", "rdfs"),
+ ("rdfs3", "rdfs"),
+ ("rdfs5", "rdfs"),
+ ("rdfs7", "rdfs"),
+ ("rdfs9", "rdfs"),
+ ("rdfs11", "rdfs"),
+ ("eq-sym", "owl-rl"),
+ ("prp-inv1", "owl-rl"),
+ ("prp-inv2", "owl-rl"),
+ ("prp-symp", "owl-rl"),
+ ("prp-trp", "owl-rl"),
+ ("scm-dom1", "owl-rl"),
+ ("scm-dom2", "owl-rl"),
+ ("scm-eqc1", "owl-rl"),
+ ("scm-eqp1", "owl-rl"),
+ ("scm-rng1", "owl-rl"),
+ ("scm-rng2", "owl-rl"),
+ ("cls-avf", "owl-rl-ext"),
+ ("cls-hv1", "owl-rl-ext"),
+ ("cls-hv2", "owl-rl-ext"),
+ ("cls-int1", "owl-rl-ext"),
+ ("cls-int2", "owl-rl-ext"),
+ ("cls-oo", "owl-rl-ext"),
+ ("cls-svf1", "owl-rl-ext"),
+ ("cls-uni", "owl-rl-ext"),
+ ("scm-avf1", "owl-rl-ext"),
+ ("scm-avf2", "owl-rl-ext"),
+ ("scm-svf1", "owl-rl-ext"),
+ ("scm-svf2", "owl-rl-ext"),
+];
+
/// The interned vocabulary [`find_clashes`] reads. Gathered into one value so
/// the detector takes three arguments rather than eighteen.
struct ClashVocab {
diff --git a/src/server.rs b/src/server.rs
index 06005f73..506dec36 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -445,6 +445,14 @@ impl OpenOntologiesServer {
crate::defects::Defects::check(&self.graph).unwrap_or_else(Self::err_json)
}
+ #[tool(name = "onto_dlp_boundary", description = "Ask which of YOUR axioms the rule engine can actually SEE, before trusting a reasoning result. A certificate from onto_reason is a sound proof about the axioms the rules read, and it says nothing at all about the ones no rule fires on. A user can reason, get a green machine-checked certificate, and never learn that a third of the TBox was invisible to the rule table. This is that second question, and it is in the same register as onto_defects: run it after onto_load and BEFORE trusting any onto_reason result. TWO DIMENSIONS THAT ARE NEVER MERGED, because one is a rewrite of your ontology and the other is a patch to this engine. (1) THE FRAGMENT: is the axiom expressible as Horn rules over triple patterns at all? The line drawn is OWL 2 RL's class grammar (OWL 2 Profiles section 4.3), and `outside` there is a fact about the LANGUAGE that would hold of a perfect OWL 2 RL engine: a disjunction in the consequent, an existential in the head, a cardinality restriction, a negation in the antecedent. Each such axiom is listed individually with the reason. (2) THIS ENGINE: is there a rule in the table that fires on it? owl:hasKey and owl:propertyChainAxiom are perfectly Horn, OWL 2 RL has prp-key and prp-spo2 for them, and this engine implements neither, so those axioms are INSIDE the fragment and still invisible. They are reported in `inside_the_fragment_but_a_rule_is_not_implemented` and never in `outside_the_fragment`. An axiom that splits soundly gets a third bucket of its own, `partially_inside_the_fragment`, because a bucket called `outside` holding an axiom the rules half evaluate would be false in its own name: `A subClassOf (B and Out)` keeps its `A subClassOf B` half, and an owl:equivalentClass with an existential on one side keeps the direction cls-svf1 evaluates. `not_fully_seen_by_the_rule_table` is the headline and carries the three causes separately, because they are fixed in three different places. A conjunction in the ANTECEDENT does not split, because dropping a conjunct from a rule body makes it fire more often. The rule-table figures (78 OWL 2 RL rules, 29 evaluated in the fixpoint, 10 more detected only as a clash, 7 that conclude false and are not looked for, and the names of the rest) are DERIVED from reason::RULES_EVALUATED and reason::CLASH_RULES_NOT_DETECTED rather than typed. Every triple in the store lands in an axiom bucket or in a counted `not_classified` bucket, so nothing is passed over in silence. This is NOT a consistency check and states no verdict about satisfiability.")]
+ fn onto_dlp_boundary(&self) -> String {
+ if let Err(e) = self.registry.ensure_loaded() {
+ return Self::err_json(format!("ensure_loaded: {e}"));
+ }
+ crate::dlp::DlpBoundary::check(&self.graph).unwrap_or_else(Self::err_json)
+ }
+
#[tool(name = "onto_stats", description = "Get statistics about the loaded ontology (triple count, classes, properties, individuals)")]
fn onto_stats(&self) -> String {
if let Err(e) = self.registry.ensure_loaded() {
@@ -1980,7 +1988,7 @@ impl OpenOntologiesServer {
.unwrap_or_else(Self::err_json)
}
- #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. FOUR syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read), `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position), `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, with every symbol MANGLED and the table written beside it as symbols.tsv, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE and has no quoting construct that survives an IRI). The last two are read by MODEL FINDERS, so they assert the NEGATED goal rather than declaring a conjecture: a countermodel to `G |= phi` is a model of `G + {not phi}`. With `smtlib`, omit `smt_domain` for the UNBOUNDED encoding, where `unsat` really is unsatisfiability, or set it to k for an enumeration carrier of exactly k elements, where a `sat` comes with a structure `oo-folmodel` can CHECK and an `unsat` establishes only that no model of size k exists. Every run also writes `problem.tsv`, the checker's own format, with its digest, so a solver result can be handed to `oo-folmodel` without going back through the engine; use onto_fol_model to do all of that in one call. The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]
+ #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. FIVE syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read), `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position), `cgif` (ISO/IEC 24707 Conceptual Graph Interchange Format, the SECOND of Common Logic's three dialects, in CORE CGIF and in the compact sub-dialect clause 7.1.1 names: no sequence markers, which clause 6.5 says is what takes Common Logic past first order, plus no `#?` type label and no actor. It takes no dialect or comment flag, because CGIF has one spelling of its operators and a lexical comment syntax of its own. `[]` is truth, `~[]` is falsity, conjunction is juxtaposition with no operator and an equation is a coreference concept `[: ?X0 ?X1]`, because CGIF has no `=`. CGIF conformance is pinned by a lexer, parser and checker transcribed from Annex B's EBNF IN THE TEST and NOT by an independent parser, because no installable CGIF parser exists, which is a weaker footing than the CLIF side and is reported rather than blurred. XCL, the third dialect, is still not emitted and the report names it in `common_logic_dialects_not_emitted`), `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, with every symbol MANGLED and the table written beside it as symbols.tsv, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE and has no quoting construct that survives an IRI). The last two are read by MODEL FINDERS, so they assert the NEGATED goal rather than declaring a conjecture: a countermodel to `G |= phi` is a model of `G + {not phi}`. With `smtlib`, omit `smt_domain` for the UNBOUNDED encoding, where `unsat` really is unsatisfiability, or set it to k for an enumeration carrier of exactly k elements, where a `sat` comes with a structure `oo-folmodel` can CHECK and an `unsat` establishes only that no model of size k exists. Every run also writes `problem.tsv`, the checker's own format, with its digest, so a solver result can be handed to `oo-folmodel` without going back through the engine; use onto_fol_model to do all of that in one call. The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]
async fn onto_fol_export(&self, Parameters(input): Parameters<OntoFolExportInput>) -> String {
let syntax = match crate::tptp::Syntax::parse(
input.format.as_deref().unwrap_or("tptp"),
@@ -3005,6 +3013,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 114 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 112 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 115 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 115 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/tptp.rs b/src/tptp.rs
index 4149f770..3d2ce002 100644
--- a/src/tptp.rs
+++ b/src/tptp.rs
@@ -106,10 +106,14 @@
//! So: single quotes in TPTP, double quotes in CLIF, for the same IRI, for
//! opposite reasons.
//!
-//! # Two serialisers, one translation
+//! # Several serialisers, one translation
//!
-//! [`Form`] is computed once. [`tptp`] and [`clif`] are renderings of it and
-//! contain no OWL-specific logic at all; each is a fold over `Form`. CLIF is
+//! [`Form`] is computed once. [`fof`], [`clif`], [`cgif`], [`smtlib`] and
+//! [`ladr`] are renderings of it and contain no OWL-specific logic at all;
+//! each is a fold over `Form`. Two of them are Common Logic dialects: ISO/IEC
+//! 24707 defines CLIF, CGIF and XCL, and emitting one and calling that Common
+//! Logic support is a partial claim. CGIF is emitted in its CORE dialect and
+//! in the compact sub-dialect clause 7.1.1 names; see [`cgif`]. CLIF is
//! restricted to the first-order-equivalent fragment of Common Logic on
//! purpose: no sequence markers, fixed arity at every position, no
//! quantification into a predicate position. Common Logic is NOT plain
@@ -1036,6 +1040,35 @@ impl FolProblem {
s.push_str(")\n");
s
}
+
+ /// ISO/IEC 24707 CGIF, core dialect, in a compact sub-dialect.
+ ///
+ /// The third of Common Logic's three dialects to be emitted here, over the
+ /// same [`FolProblem::formulas`] the TPTP and CLIF writers walk. The text
+ /// is a B.2.11 `text`: `"[", [comment], "Proposition", ":", [CGname], CG,
+ /// [endComment], "]"`, which is what Table B.1's row E20 maps a named
+ /// `(cl:text N …)` to, so the CGIF file is the standard's own image of the
+ /// CLIF file rather than a second convention.
+ ///
+ /// Unlike the CLIF writer this has no dialect flag and no comment-placement
+ /// flag. There is one spelling of the CGIF operators, and B.2.4 gives
+ /// comments a lexical syntax of their own, so the `cl:comment` trap that
+ /// made the CLIF writer's default a measured decision does not arise:
+ /// nothing has to be put INSIDE a comment for a label to attach to it.
+ pub fn to_cgif(&self, name: &str) -> Result<String, cgif::UnwritableComment> {
+ let mut s = String::new();
+ let _ = writeln!(s, "[Proposition: {}", cgif::text_name(name));
+ let header = cgif::comment(&header_text(self.conjecture.is_some(), CGIF_STYLE))?;
+ for line in header.lines() {
+ let _ = writeln!(s, " {line}");
+ }
+ for (label, role, f) in self.formulas() {
+ let _ = writeln!(s, " {}", cgif::comment(&format!("{label} ({role})"))?);
+ let _ = writeln!(s, " {}", cgif::sentence(f));
+ }
+ s.push_str("]\n");
+ Ok(s)
+ }
}
/// The header every serialiser carries, with each line prefixed by the
@@ -1161,6 +1194,60 @@ const CLIF_NOTES: &[&str] = &{
const CLIF_STYLE: HeaderStyle = HeaderStyle { extra: CLIF_NOTES, goal: ORACLE_GOAL };
+/// The CGIF paragraphs of the header.
+const CGIF_NOTES: &[&str] = &[
+ "",
+ "CGIF, ISO/IEC 24707 Annex B. This is CORE CGIF, not extended CGIF. A core",
+ "concept has no type field, so a class membership is an ordinary relation",
+ "`(\"c:IRI\" ?X0)` and not `[C: *x]`; B.1.2 gives that reduction itself.",
+ "Nothing here uses a type label, a type expression, `@every`, `[If: ...",
+ "[Then: ...]]`, `[Either: [Or: ...]]`, `[Equiv: [Iff: ...]]`, a concept in an",
+ "arc sequence, or an import. B.4 states that core CGIF is a fully conformant",
+ "Common Logic dialect on its own.",
+ "",
+ "THE COMPACT SUB-DIALECT. Clause 7.1.1: \"A compact sub-dialect is a dialect",
+ "that does not recognize sequence markers.\" This text is one, and that is the",
+ "restriction that matters: clause 6.5 says Common Logic with sequence markers",
+ "\"is not compact, and therefore not first-order\", and the adequacy theorem is",
+ "about plain first-order logic. No `[*...x]` and no `?...x` appears, in either",
+ "position B.2.5 and B.2.3 allow one. By the same clause this text is also an",
+ "unstructured sub-dialect (no titlings, no importation) and a single domain",
+ "sub-dialect (no domain restrictions). Two further exclusions have no clause-7",
+ "name: no `#?` type label, which B.2.7 says is how CGIF quantifies over",
+ "relations, and no actor, which is how B.2.1 writes a function.",
+ "",
+ "THE ENCODING. `[]` is truth and `~[]` is falsity (B.2.5, B.2.8). Conjunction",
+ "is juxtaposition and has no operator (B.2.6). An equation is a coreference",
+ "concept `[: ?X0 ?X1]` (B.2.5); CGIF has no `=`. Implication is `~[A ~[B]]`",
+ "and disjunction is `~[~[A] ~[B]]`, which are B.3.5's own `ifThen` and",
+ "`eitherOr` rewrites into core. A universal is `~[[*X0] ~[...]]`, which is",
+ "B.3.7's \"nest of two negations\".",
+ "",
+ "EVERY BINDER HAS A CONTEXT OF ITS OWN, and every sentence is bracketed.",
+ "B.2.10 forbids two defining labels with one name in one context, and the",
+ "translation reuses variable indices between an axiom's antecedent and its",
+ "consequent. Renumbering them would emit a different formula, so each binder",
+ "is given a context instead. No defining label in this text stands in the",
+ "scope of another with the same name, so nothing here depends on B.2.10's",
+ "shadowing sentence, which contradicts the sentence before it.",
+ "",
+ "NAMES. B.1.1's `identifier` is letters, digits and underscore, so every IRI",
+ "is a DOUBLE-QUOTED enclosed name, the text's own name included. `X0`, `thing`",
+ "and `lit` are identifiers. A defining label is `Xn` and a constant begins",
+ "`i:`, so the two can never collide, which B.2.10 forbids outright.",
+ "",
+ "INTERPRETED NAMES. No numeral and no single-quoted string stands anywhere in",
+ "this text. A.4.2 states the `exactly semantically conformant` result for",
+ "CLIF and Annex B states no analogue for CGIF, so the property is held here",
+ "and the label is not borrowed. CGIF needs no exception for its comments: B.2.4",
+ "makes a comment a LEXICAL construct, delimited rather than quoted, which is",
+ "not what a CLIF `cl:comment` can be. Its own delimiters are the one string a",
+ "comment may not contain, and B.2.4 gives no escape for them, so a comment",
+ "carrying one is REFUSED by this exporter rather than rewritten.",
+];
+
+const CGIF_STYLE: HeaderStyle = HeaderStyle { extra: CGIF_NOTES, goal: ORACLE_GOAL };
+
/// The SMT-LIB paragraphs.
const SMTLIB_NOTES: &[&str] = &[
"",
@@ -1566,7 +1653,14 @@ pub mod clif {
/// The kind prefixes come from [`super::sym`], the same module the TPTP
/// and SMT-LIB serialisers read, for the same reason: `OwlP1` and `OwlP2`
/// are disjoint sums in the Lean.
- fn enclosed(image: &str) -> String {
+ ///
+ /// `pub` because [`super::cgif`] writes the SAME construct and must not
+ /// write its own. That is not convenience: ISO/IEC 24707:2018 B.1.1 defines
+ /// `CGname` as `identifier | '"', (namesequence - identifier), '"' |
+ /// numeral | enclosedname | quotedstring`, where `enclosedname` is A.2.2's
+ /// category, CLIF's. The two syntaxes quote a name the same way because the
+ /// standard says they do, and a second copy here could only ever drift.
+ pub fn enclosed(image: &str) -> String {
let mut s = String::with_capacity(image.len() + 4);
s.push('"');
for ch in image.chars() {
@@ -1700,7 +1794,286 @@ pub mod clif {
}
}
-// ── Serialiser 3: SMT-LIB 2 ─────────────────────────────────────────────────
+// ── Serialiser 3: ISO/IEC 24707 CGIF ────────────────────────────────────────
+
+/// CGIF rendering of [`Form`]: **core CGIF**, in a compact sub-dialect.
+///
+/// ISO/IEC 24707 Common Logic has three dialects, and Common Logic conformance
+/// is a claim about the language and not about one serialisation of it. This
+/// engine emitted CLIF only, which made its Common Logic support partial in a
+/// way nothing said out loud. This module is the second of the three. XCL,
+/// Annex C, is still not emitted and is named in the docs as absent.
+///
+/// # Core, not extended, and what that costs
+///
+/// B.3.1 lists what extended CGIF adds to core: type labels and type
+/// expressions on concepts, `@every` for universal quantification, the Boolean
+/// contexts `[If: … [Then: …]]`, `[Either: [Or: …]]` and
+/// `[Equiv: [Iff: …]]`, concepts in an arc sequence, actors with zero or
+/// several output arcs, and importing a text into a text. **None of that is
+/// emitted here.** Everything below is core CGIF (B.2), which B.4 states is a
+/// fully conformant CL dialect in its own right: "every CL sentence can be
+/// translated to a semantically equivalent sentence in each of them".
+///
+/// Core costs exactly one thing in readability. A core concept has no type
+/// field, so `[Cat: *x]` is not available and a class membership is written as
+/// an ordinary relation. B.1.2 gives that reduction itself: "The concept
+/// `[Go:*x]`, for example, becomes an untyped concept `[*x]` and a conceptual
+/// relation `(Go ?x)`." That reduction is the whole difference, and taking it
+/// means the file needs no Annex B.3 rewrite pass to be read.
+///
+/// # The restriction, in the standard's own vocabulary
+///
+/// Clause 7.1.1 names three sub-dialects, and this emitter is all three:
+///
+/// * a **compact sub-dialect**, "a dialect that does not recognize sequence
+/// markers". That is the restriction that matters: clause 6.5 says Common
+/// Logic with sequence markers "is not compact, and therefore not
+/// first-order", and the adequacy theorem is about plain first-order logic.
+/// No `[*...x]` and no `?...x` is emitted, in either position the grammar
+/// allows one (B.2.5's `existentialConcept`, B.2.3's `arcSequence`).
+/// * an **unstructured sub-dialect**, "a dialect that does not recognize
+/// titlings and importation statements".
+/// * a **single domain sub-dialect**, "a dialect that does not recognize
+/// domain restrictions".
+///
+/// Two further exclusions have no clause-7 name and are listed because they
+/// would leave first-order logic just as surely:
+///
+/// * **no `#?` type label.** B.2.7's `ordinaryRelation` admits `["#", "?"],
+/// CGname`, and its own comment says why: "By allowing the type label of a
+/// conceptual relation to be a bound label, CGIF supports the CL ability to
+/// quantify over relations and functions." That is quantifying into a
+/// predicate position, and it is the CGIF spelling of the thing the CLIF
+/// restriction already excludes.
+/// * **no actors.** B.2.1's `actor` is how a CL FUNCTION is written. `OwlLean.
+/// FOL`'s `FSig` has P1, P2 and Const and no function symbol of positive
+/// arity, so [`Form`] cannot express one and none is emitted.
+///
+/// [`Form`] cannot express any of the five, which is the structural reason the
+/// restriction holds; `cgif_stays_in_the_compact_first_order_sub_dialect` in
+/// `tests/fol_cgif_export_test.rs` is the check that it still does.
+///
+/// # The core encoding, production by production
+///
+/// | `Form` | CGIF | why |
+/// |---|---|---|
+/// | `App1(p,t)` | `(p t)` | B.2.7 `ordinaryRelation` |
+/// | `App2(p,t,u)` | `(p t u)` | the same, at arity two |
+/// | `Eq(t,u)` | `[: t u]` | B.2.5 `coreferenceConcept`. CGIF has NO equality relation |
+/// | `Tru` | `[]` | B.2.5: "an empty context `[ ]` is translated to CLIF as `(and)`, which is true by definition" |
+/// | `Fls` | `~[]` | B.2.8: "The negation of the blank CG, written `~[ ]`, is always false" |
+/// | `Neg(g)` | `~[ g ]` | B.2.8 `negation = "~", context` |
+/// | `And(g,h)` | `g h` | juxtaposition. B.2.6 makes a CG's nodes a conjunction |
+/// | `Or(g,h)` | `~[ ~[g] ~[h] ]` | B.3.5's own `eitherOr` rewrite into core |
+/// | `Imp(g,h)` | `~[ g ~[h] ]` | B.3.5's own `ifThen` rewrite into core |
+/// | `All(n,g)` | `~[ [*Xn] ~[g] ]` | B.3.7's `@every` rewrite: a nest of two negations |
+/// | `Ex(n,g)` | `[ [*Xn] g ]` | B.2.6: a CG with existential concepts is `∃names. rest` |
+///
+/// The three derived forms are not this project's inventions. B.3.5 gives
+/// `ifThen` as `"~[", CG(ante), "~[", CG(conse), "]", "]"` and `eitherOr` as a
+/// negation containing one `~[…]` per disjunct, and B.3.7 says of a CG
+/// containing universal concepts that "the output string shall be a nest of two
+/// negations. The outer context shall contain the translations of all the
+/// universal concepts, and the inner context shall contain the translations of
+/// all other nodes". This module emits what the standard's own rewrite rules
+/// produce.
+///
+/// # Every binder gets its own context, and why that is not decoration
+///
+/// B.2.10: "If a concept x with a defining label with name n is directly
+/// contained in some context c, then c shall not contain any concept other than
+/// x with a defining label with the same CG name n." Two things follow, and
+/// both bite.
+///
+/// **An existential is emitted as `[ [*Xn] … ]` and never as a bare `[*Xn]`
+/// juxtaposed with its body.** `OwlLean.trAx` restarts its variable counter for
+/// each axiom and reuses indices between an axiom's antecedent and its
+/// consequent (`tr c 0 2` and `tr d 0 2` are both called at 2), so two `[*X2]`
+/// really can arise in one sentence. Giving each binder a context of its own
+/// means no context ever directly contains two defining labels at all, whatever
+/// the counter did.
+///
+/// Renumbering would also have fixed it and is forbidden: `owl-lean` uses named
+/// variables rather than de Bruijn indices precisely so that freshness is a
+/// proof obligation, and an exporter that renumbered would be emitting a
+/// different formula.
+///
+/// **Each sentence is wrapped in a context of its own** for the same reason at
+/// the file level, so nothing a sentence binds can reach the next sentence.
+/// `[ s ]` is `(and s)`, which is `s`.
+///
+/// **Shadowing is avoided rather than relied on.** B.2.10 says both that a
+/// context "shall not contain any concept other than x with a defining label
+/// with the same CG name n" — where *contains* is transitive — and, in the very
+/// next sentence, that a nested context may redeclare one. The two cannot both
+/// hold. This emitter never produces a defining label inside the scope of
+/// another with the same name, so it does not depend on which reading is right,
+/// and `no_defining_label_is_ever_shadowed` is the check.
+///
+/// # Names
+///
+/// B.1.1's `identifier = letter, {letter | digit | "_"}` is far narrower than
+/// CLIF's `namecharsequence`: no colon, no slash, no dot, no hyphen. An IRI is
+/// therefore ALWAYS written as a double-quoted enclosed name, including in the
+/// text's name slot, where the CLIF writer emits a bare IRI for Macleod's sake.
+/// B.1.1 states the rule: "the category CGname requires that all CLIF name
+/// sequences except those in the CGIF category identifier shall be enclosed in
+/// quotes".
+///
+/// `X0`, `X1`, … and the bare `thing` and `lit` are legal identifiers. Every
+/// other image out of [`sym`] carries a colon and is enclosed. Those two facts
+/// together are why a defining label can never collide with a constant, which
+/// B.2.10's last clause forbids outright: "No constant with CG name n shall be
+/// in the scope associated with some concept with a defining label with CG name
+/// n." A defining label here is `Xn`; a constant here begins `i:`.
+///
+/// # Interpreted names
+///
+/// A.4.2 says of CLIF, in the 2018 edition as in the first, that "The
+/// subdialect of CLIF which does not use numerals or quoted strings is exactly
+/// semantically conformant". Annex B states **no** analogue for CGIF, so this
+/// module does not borrow the label. What it does is hold the property: no
+/// numeral and no single-quoted string stands anywhere in this output.
+///
+/// CGIF gets that for free where CLIF could not. A CLIF label has to ride on
+/// `cl:comment`, whose argument is a quoted string, so the CLIF writer needs a
+/// named exception for its comments. B.2.4 makes a CGIF comment a LEXICAL
+/// construct, `/* … */`, which is not a name at all, so the CGIF output holds
+/// the property with no exception to declare.
+pub mod cgif {
+ use super::{Form, P1, P2, Term, clif, sym};
+
+ /// The delimiter that may not appear inside a comment.
+ ///
+ /// B.2.4: "The string enclosed by the delimiters `/*` and `*/` shall not
+ /// contain a substring `*/`." There is no escape for it, so a text that
+ /// contained one could not be commented at all. Nothing this emitter puts
+ /// in a comment can contain it — the header is a constant and a label is
+ /// `background_1 (axiom)` — and `no_emitted_comment_can_close_itself_early`
+ /// is the check rather than the assumption.
+ pub const COMMENT_CLOSE: &str = "*/";
+
+ /// A comment text this exporter cannot write, with the reason.
+ ///
+ /// Returned rather than escaped or dropped, which is the rule
+ /// [`super::UnwritableSymbol`] already follows for SMT-LIB and LADR: a
+ /// dropped comment loses the label that says which axiom a sentence is,
+ /// and a rewritten one is a different comment. B.2.4 gives no escape for
+ /// the closing delimiter, so there is no third option.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub struct UnwritableComment {
+ pub text: String,
+ pub why: &'static str,
+ }
+
+ impl std::fmt::Display for UnwritableComment {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "the comment {:?} cannot be written in CGIF: {}", self.text, self.why)
+ }
+ }
+
+ impl std::error::Error for UnwritableComment {}
+
+ /// Whether a string may be written inside a CGIF comment.
+ pub fn comment_is_writable(text: &str) -> bool {
+ !text.contains(COMMENT_CLOSE)
+ }
+
+ /// A `/* … */` comment. B.2.4 permits one "intermixed with the concepts and
+ /// conceptual relations of any conceptual graph", which is where every
+ /// comment in the emitted file stands.
+ ///
+ /// This is also exactly what ISO/IEC 24707 B.4's Table B.1 maps a CLIF
+ /// `(cl:comment 'string' P)` to: "A comment and a CG: `"/*"`, 'string',
+ /// `"*/"`, cl2cg(P)". So the CGIF file's label shape is the standard's own
+ /// image of the CLIF file's label shape, rather than a second convention.
+ pub fn comment(text: &str) -> Result<String, UnwritableComment> {
+ if !comment_is_writable(text) {
+ return Err(UnwritableComment {
+ text: text.to_string(),
+ why: "ISO/IEC 24707 B.2.4: \"The string enclosed by the delimiters `/*` and \
+ `*/` shall not contain a substring `*/`\", and the standard defines no \
+ escape for it. Rewriting the text would emit a different comment and \
+ dropping it would lose the label that says which axiom the sentence is",
+ });
+ }
+ Ok(format!("/*{text}*/"))
+ }
+
+ /// A text name. Always a double-quoted enclosed name.
+ ///
+ /// Unlike the CLIF writer, which emits a bare IRI because Macleod's lexer
+ /// has no double-quote token, this has no choice: B.1.1's `identifier`
+ /// admits letters, digits and underscore only, so no IRI is one.
+ pub fn text_name(iri: &str) -> String {
+ clif::enclosed(iri)
+ }
+
+ fn p1(p: &P1) -> String {
+ match p {
+ P1::Thing => "thing".to_string(),
+ P1::Lit => "lit".to_string(),
+ other => clif::enclosed(&sym::p1(other)),
+ }
+ }
+
+ fn p2(p: &P2) -> String {
+ clif::enclosed(&sym::p2(p))
+ }
+
+ /// An arc: B.2.9's `reference = ["?"], CGname`. A bound coreference label
+ /// carries the `?`; a constant carries nothing.
+ fn arc(t: &Term) -> String {
+ match t {
+ Term::Var(n) => format!("?X{n}"),
+ Term::Const(a) => clif::enclosed(&sym::constant(a)),
+ }
+ }
+
+ /// Render a formula as a CG: a sequence of one or more nodes, whose
+ /// conjunction B.2.6 makes the meaning of the graph.
+ ///
+ /// `And` is the only arm that returns more than one node, which is not an
+ /// implementation detail: conjunction has no operator in CGIF. Sowa puts it
+ /// plainly and B.2.6 says it formally — "A conceptual graph consists of an
+ /// unordered set of concepts, conceptual relations, negations, and
+ /// comments", and a CG's meaning is the conjunction of its nodes.
+ pub fn graph(f: &Form) -> String {
+ match f {
+ Form::App1(p, t) => format!("({} {})", p1(p), arc(t)),
+ Form::App2(p, t, u) => format!("({} {} {})", p2(p), arc(t), arc(u)),
+ // B.2.5: a coreference concept is "translated to a conjunction of
+ // equations". With two references that conjunction is one equation.
+ // CGIF has no `=` and could not have one: `=` is a CLIF reserved
+ // token and a CGIF identifier must begin with a letter.
+ Form::Eq(t, u) => format!("[: {} {}]", arc(t), arc(u)),
+ Form::Tru => "[]".to_string(),
+ Form::Fls => "~[]".to_string(),
+ Form::Neg(g) => format!("~[{}]", graph(g)),
+ Form::And(g, h) => format!("{} {}", graph(g), graph(h)),
+ Form::Or(g, h) => format!("~[~[{}] ~[{}]]", graph(g), graph(h)),
+ Form::Imp(g, h) => format!("~[{} ~[{}]]", graph(g), graph(h)),
+ Form::All(n, g) => format!("~[[*X{n}] ~[{}]]", graph(g)),
+ Form::Ex(n, g) => format!("[[*X{n}] {}]", graph(g)),
+ }
+ }
+
+ /// One formula as a single node: `[ CG ]`.
+ ///
+ /// The bracket is a B.2.5 `context`, whose meaning is the conjunction of
+ /// what it holds, so it changes nothing about the theory. It buys two
+ /// things. A formula whose root is `And` is several nodes and would
+ /// otherwise spread across the text's own graph, so the label comment in
+ /// front of it would attach to the first node and not to the formula. And
+ /// the context bounds every quantifier the formula opens, so no sentence
+ /// can reach into the next one.
+ pub fn sentence(f: &Form) -> String {
+ format!("[{}]", graph(f))
+ }
+}
+
+// ── Serialiser 4: SMT-LIB 2 ─────────────────────────────────────────────────
/// SMT-LIB 2 rendering of [`Form`]. The third printer over the same [`Form`],
/// and no more OWL-specific than the other two.
@@ -1839,7 +2212,7 @@ pub mod smtlib {
}
}
-// ── Serialiser 4: LADR, for Mace4 ───────────────────────────────────────────
+// ── Serialiser 5: LADR, for Mace4 ───────────────────────────────────────────
/// LADR rendering of [`Form`], for Mace4, the finite model finder that ships
/// with Prover9.
@@ -2092,7 +2465,7 @@ pub mod ladr {
}
}
-// ── Serialiser 5: the checker format ────────────────────────────────────────
+// ── Serialiser 6: the checker format ────────────────────────────────────────
/// `problem.tsv`, the file `oo-folmodel` reads, and the digest that binds a
/// model file to it.
@@ -3589,8 +3962,13 @@ pub fn triple_as_axiom(
// ── The export itself ───────────────────────────────────────────────────────
-/// Output syntax. Two serialisers over one translation, never two
+/// Output syntax. FIVE serialisers over ONE translation, never five
/// translations.
+///
+/// Two of the five are Common Logic dialects. ISO/IEC 24707 defines three —
+/// CLIF, CGIF and XCL — and emitting one of them and calling the support
+/// "Common Logic" is the kind of partial claim this repository exists to stop
+/// making. XCL is still absent and is named as absent in the report.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Syntax {
/// TPTP FOF, the format every first-order prover reads and the one the
@@ -3601,6 +3979,12 @@ pub enum Syntax {
/// syntax for the same first-order content, and the one ISO/IEC 21838-2
/// publishes BFO in.
Clif(ClifDialect, ClifComments),
+ /// ISO/IEC 24707 Conceptual Graph Interchange Format, CORE dialect, in
+ /// the compact sub-dialect clause 7.1.1 names. The second of Common
+ /// Logic's three dialects this engine emits; XCL, Annex C, is still not
+ /// emitted. There is no dialect flag: unlike CLIF, CGIF has one spelling
+ /// of its operators and a lexical comment syntax of its own.
+ Cgif,
/// SMT-LIB 2, the format the SAT/SMT family reads. The goal is asserted
/// NEGATED, because this is the syntax a MODEL comes back out of and a
/// model is the thing this repository can certify.
@@ -3625,6 +4009,7 @@ impl Syntax {
ClifDialect::parse(dialect.unwrap_or("iso"))?,
ClifComments::parse(comments.unwrap_or("standalone"))?,
)),
+ "cgif" | "cg" | "conceptual-graph" => Ok(Syntax::Cgif),
"smtlib" | "smt" | "smt2" | "smt-lib" => Ok(Syntax::Smtlib(match domain {
None => smtlib::SmtEncoding::Unbounded,
Some(0) => anyhow::bail!(
@@ -3635,8 +4020,8 @@ impl Syntax {
})),
"ladr" | "mace4" | "prover9" => Ok(Syntax::Ladr),
other => anyhow::bail!(
- "unknown first-order syntax {other:?}; expected `tptp`, `clif`, `smtlib` or \
- `ladr`"
+ "unknown first-order syntax {other:?}; expected `tptp`, `clif`, `cgif`, \
+ `smtlib` or `ladr`"
),
}
}
@@ -3644,6 +4029,7 @@ impl Syntax {
match self {
Syntax::Tptp => "p",
Syntax::Clif(..) => "clif",
+ Syntax::Cgif => "cgif",
Syntax::Smtlib(_) => "smt2",
Syntax::Ladr => "in",
}
@@ -3652,6 +4038,7 @@ impl Syntax {
match self {
Syntax::Tptp => "tptp",
Syntax::Clif(..) => "clif",
+ Syntax::Cgif => "cgif",
Syntax::Smtlib(_) => "smtlib",
Syntax::Ladr => "ladr",
}
@@ -3680,6 +4067,7 @@ impl Syntax {
Ok(match self {
Syntax::Tptp => problem.to_tptp(),
Syntax::Clif(d, c) => problem.to_clif(d, c, name),
+ Syntax::Cgif => problem.to_cgif(name)?,
Syntax::Smtlib(e) => problem.to_smtlib(e)?,
Syntax::Ladr => {
let tab = ladr::SymbolTable::build(problem)?;
@@ -3816,6 +4204,18 @@ pub fn export(
"clif_dialect": syntax.dialect().map(|d| d.name()),
"clif_comments": syntax.comments().map(|c| c.name()),
"clif_text_name": syntax.dialect().map(|_| ontology_iri.clone()),
+ // CGIF has no dialect FLAG, and it does have a dialect: core rather
+ // than extended, and a compact sub-dialect of that. Reported as a value
+ // so a consumer never has to read the header to learn which.
+ "cgif_dialect": (syntax == Syntax::Cgif).then_some("core"),
+ "cgif_sub_dialect": (syntax == Syntax::Cgif).then_some(
+ "compact (no sequence markers, ISO/IEC 24707 clause 7.1.1), unstructured (no \
+ titlings or importation) and single domain (no domain restrictions). Also no `#?` \
+ type label, which is how B.2.7 quantifies over relations, and no actor, which is \
+ how B.2.1 writes a function"),
+ "cgif_text_name": (syntax == Syntax::Cgif).then(|| ontology_iri.clone()),
+ "common_logic_dialects_emitted": ["clif", "cgif"],
+ "common_logic_dialects_not_emitted": ["xcl (ISO/IEC 24707 Annex C, the XML dialect)"],
"smt_encoding": syntax.encoding().map(|e| e.name()),
"dir": dir.display().to_string(),
"ontology_file": main.display().to_string(),
diff --git a/tests/dlp_boundary_test.rs b/tests/dlp_boundary_test.rs
new file mode 100644
index 00000000..0b470433
--- /dev/null
+++ b/tests/dlp_boundary_test.rs
@@ -0,0 +1,769 @@
+//! The DLP boundary report, and the one distinction it exists to keep.
+//!
+//! `onto_rules_import` refuses a non-Horn SWRL or RIF construct by name and
+//! count, so nobody gets a certificate over a rule set they did not write.
+//! `onto_dlp_boundary` is the same discipline pointed the other way: it says
+//! which of the axioms a user DID write the rule table can see.
+//!
+//! The tests are grouped:
+//!
+//! 1. The rule table adds up, and its figures are the engine's own rather
+//! than a second copy that can drift.
+//! 2. A disjunctive axiom is reported OUTSIDE the fragment.
+//! 3. An axiom INSIDE the fragment whose rule is unimplemented is reported in
+//! the other bucket, and the two are never merged. This is the test the
+//! whole tool is for: `owl:hasKey` and `owl:propertyChainAxiom` are Horn,
+//! OWL 2 RL has `prp-key` and `prp-spo2`, and this engine runs neither.
+//! 4. The splitting asymmetry: a conjunction splits in a consequent and does
+//! NOT split in an antecedent, because dropping a conjunct from a rule
+//! body makes it fire more often, which is unsound rather than weaker.
+//! 5. Nothing is passed over in silence: every triple lands in a bucket.
+
+use open_ontologies::dlp::{DlpBoundary, OWL2_RL_RULES, RuleStatus, rule_status};
+use open_ontologies::graph::GraphStore;
+use std::collections::BTreeSet;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+fn repo() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn report(ttl: &str) -> serde_json::Value {
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(ttl, None).expect("turtle parses");
+ let json = DlpBoundary::check(&graph).expect("the report is built");
+ serde_json::from_str(&json).expect("the report is JSON")
+}
+
+const PREFIXES: &str = r#"
+@prefix : <http://e/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+"#;
+
+/// Every axiom of a given type in the report, whatever bucket it is in.
+fn kind_row<'a>(v: &'a serde_json::Value, kind: &str) -> &'a serde_json::Value {
+ v["by_axiom_type"]
+ .as_array()
+ .expect("by_axiom_type is a list")
+ .iter()
+ .find(|r| r["axiom_type"] == kind)
+ .unwrap_or_else(|| panic!("no row for {kind} in {}", v["by_axiom_type"]))
+}
+
+fn subjects(v: &serde_json::Value, bucket: &str) -> Vec<String> {
+ v[bucket]["axioms"]
+ .as_array()
+ .unwrap_or_else(|| panic!("{bucket} has no axiom list in {v}"))
+ .iter()
+ .map(|a| a["subject"].as_str().unwrap_or("").to_string())
+ .collect()
+}
+
+fn outside_axioms(v: &serde_json::Value) -> Vec<String> {
+ subjects(v, "outside_the_fragment")
+}
+
+fn unimplemented_axioms(v: &serde_json::Value) -> Vec<String> {
+ subjects(v, "inside_the_fragment_but_a_rule_is_not_implemented")
+}
+
+// ── 1. The rule table ───────────────────────────────────────────────────────
+
+/// **Gate.** The transcription of the OWL 2 RL inference tables adds up.
+///
+/// Seventy-eight rules, and the four coverage buckets partition them exactly.
+/// A mistyped or duplicated row fails here rather than quietly changing a
+/// figure six other files in this repository repeat.
+#[test]
+fn the_rule_table_adds_up() {
+ assert_eq!(
+ OWL2_RL_RULES.len(),
+ 78,
+ "the OWL 2 RL profile has 78 inference rules across Tables 4 to 9"
+ );
+ let names: BTreeSet<&str> = OWL2_RL_RULES.iter().map(|r| r.name).collect();
+ assert_eq!(names.len(), 78, "a rule name is repeated in the table");
+
+ let evaluated = OWL2_RL_RULES
+ .iter()
+ .filter(|r| matches!(rule_status(r.name), RuleStatus::Evaluated(_)))
+ .count();
+ let clash = OWL2_RL_RULES
+ .iter()
+ .filter(|r| rule_status(r.name) == RuleStatus::ClashDetected)
+ .count();
+ let undetected = OWL2_RL_RULES
+ .iter()
+ .filter(|r| matches!(rule_status(r.name), RuleStatus::ClashNotDetected(_)))
+ .count();
+ let unimplemented = OWL2_RL_RULES
+ .iter()
+ .filter(|r| rule_status(r.name) == RuleStatus::NotImplemented)
+ .count();
+
+ assert_eq!(evaluated, 29, "the figure six other files state as `29 of 78`");
+ assert_eq!(clash, 10, "ten of the seventeen false-concluding rules are detected");
+ assert_eq!(undetected, 7, "and seven are not: reason::CLASH_RULES_NOT_DETECTED");
+ assert_eq!(unimplemented, 32);
+ assert_eq!(evaluated + clash + undetected + unimplemented, 78);
+}
+
+/// **Gate.** The seventeen rules this table marks as concluding `false` are the
+/// seventeen `src/reason.rs` names, in a list written independently of it.
+///
+/// This is the cross-check that makes the transcription above evidence rather
+/// than an assertion. `src/reason.rs`'s comment says seventeen and names them;
+/// that list said SIXTEEN until it was checked against the W3C source. Two
+/// independent transcriptions agreeing is the only thing available here, since
+/// nobody on this project holds the standard in machine-readable form.
+#[test]
+fn the_seventeen_false_concluding_rules_agree_with_the_engine() {
+ let ours: BTreeSet<&str> = OWL2_RL_RULES
+ .iter()
+ .filter(|r| r.concludes_false)
+ .map(|r| r.name)
+ .collect();
+ assert_eq!(ours.len(), 17, "got {ours:?}");
+
+ let source = std::fs::read_to_string(repo().join("src").join("reason.rs"))
+ .expect("src/reason.rs must be readable");
+ let block = source
+ .split("Seventeen rules of the OWL 2 RL profile")
+ .nth(1)
+ .expect("the comment naming the seventeen must still be there")
+ .split("(Seventeen is the count")
+ .next()
+ .expect("the comment ends before the aside about how the count was taken");
+ for name in &ours {
+ assert!(
+ block.contains(&format!("`{name}`")),
+ "src/reason.rs's own list of the seventeen does not name {name}"
+ );
+ }
+
+ // And every rule the clash detector says it does NOT look for is one of the
+ // seventeen. A name there that concludes a triple would be a category error.
+ for (name, _) in open_ontologies::reason::CLASH_RULES_NOT_DETECTED {
+ assert!(
+ ours.contains(name),
+ "{name} is listed as an undetected CLASH rule and does not conclude false"
+ );
+ }
+}
+
+/// **Gate.** `reason::RULES_EVALUATED` is the rules `src/reason.rs` emits.
+///
+/// The list is the source of the figure "29 of 78". A figure next to the thing
+/// it measures must be derived and never typed, and a `const` is typed, so this
+/// greps the file for its own `emit` calls and refuses to let the two disagree.
+/// Add a rule without a line, or a line without a rule, and this fails.
+#[test]
+fn the_evaluated_rule_list_is_the_rules_this_file_emits() {
+ let source = std::fs::read_to_string(repo().join("src").join("reason.rs"))
+ .expect("src/reason.rs must be readable");
+
+ let mut emitted: BTreeSet<String> = BTreeSet::new();
+ for chunk in source.split("emit((").skip(1) {
+ // `emit((conclusion), "rule-name", &[premises])`: the first quoted
+ // string after the conclusion is the rule.
+ let Some(open) = chunk.find('"') else { continue };
+ let rest = &chunk[open + 1..];
+ let Some(close) = rest.find('"') else { continue };
+ emitted.insert(rest[..close].to_string());
+ }
+ assert!(!emitted.is_empty(), "the grep itself is broken: no emit call found");
+
+ let declared: BTreeSet<String> = open_ontologies::reason::RULES_EVALUATED
+ .iter()
+ .map(|(n, _)| n.to_string())
+ .collect();
+ assert_eq!(
+ declared, emitted,
+ "reason::RULES_EVALUATED and the emit calls in src/reason.rs disagree. The emit calls \
+ are the measurement and the constant is the claim"
+ );
+ assert_eq!(declared.len(), 29);
+
+ // The profile column is one of the three the reasoner accepts.
+ for (name, profile) in open_ontologies::reason::RULES_EVALUATED {
+ assert!(
+ ["rdfs", "owl-rl", "owl-rl-ext"].contains(profile),
+ "{name} is gated on a profile that does not exist: {profile}"
+ );
+ }
+}
+
+/// Every rule name the classifier attaches to an axiom exists in the table.
+///
+/// A typo would silently land in `NotImplemented` and report an axiom as
+/// invisible when it is not, which is the failure mode this tool is supposed
+/// to be the cure for.
+#[test]
+fn every_rule_the_classifier_names_is_a_real_rule() {
+ let ttl = format!(
+ "{PREFIXES}
+:A a owl:Class ; rdfs:subClassOf :B ; owl:equivalentClass :C ; owl:disjointWith :D .
+:B a owl:Class . :C a owl:Class . :D a owl:Class .
+:r a owl:ObjectProperty, owl:TransitiveProperty, owl:SymmetricProperty, owl:FunctionalProperty,
+ owl:InverseFunctionalProperty, owl:AsymmetricProperty, owl:IrreflexiveProperty ;
+ rdfs:domain :A ; rdfs:range :B ; rdfs:subPropertyOf :s ; owl:inverseOf :s ;
+ owl:propertyDisjointWith :s ; owl:equivalentProperty :s ; owl:propertyChainAxiom ( :s :s ) .
+:s a owl:ObjectProperty .
+:A owl:hasKey ( :r ) .
+:a owl:sameAs :b ; owl:differentFrom :c .
+:E a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :r ; owl:allValuesFrom :B ] .
+:F a owl:Class ; owl:equivalentClass [ owl:intersectionOf ( :A :B ) ] .
+:G a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :r ; owl:hasValue :a ] .
+"
+ );
+ let v = report(&ttl);
+ assert!(v["axioms_classified"].as_u64().unwrap_or(0) > 15, "{v}");
+
+ let known: BTreeSet<&str> = OWL2_RL_RULES.iter().map(|r| r.name).collect();
+ let mut checked = 0usize;
+ for bucket in [
+ &v["inside_the_fragment_but_a_rule_is_not_implemented"]["axioms"],
+ &v["outside_the_fragment"]["axioms"],
+ ] {
+ for a in bucket.as_array().expect("a list") {
+ for r in a["rules_that_would_evaluate_it"].as_array().unwrap_or(&Vec::new()) {
+ let name = r.as_str().expect("a rule name");
+ assert!(known.contains(name), "{name} is not an OWL 2 RL rule");
+ checked += 1;
+ }
+ }
+ }
+ assert!(checked > 0, "no rule name was checked, so this gate proved nothing");
+}
+
+// ── 2. Outside the fragment ─────────────────────────────────────────────────
+
+/// **Gate.** A disjunction in the consequent is reported OUTSIDE the fragment,
+/// with the reason, and it is not in the unimplemented bucket.
+///
+/// `Adult ⊑ Man ⊔ Woman` is the textbook non-Horn axiom: a Horn clause has one
+/// atom in its head. No amount of work on `src/reason.rs` makes this visible,
+/// and reporting it beside `owl:hasKey` would tell a reader to file the wrong
+/// bug.
+#[test]
+fn a_disjunctive_consequent_is_reported_outside_the_fragment() {
+ let ttl = format!(
+ "{PREFIXES}
+:Adult a owl:Class ; rdfs:subClassOf [ owl:unionOf ( :Man :Woman ) ] .
+:Man a owl:Class . :Woman a owl:Class .
+:Safe a owl:Class ; rdfs:subClassOf :Adult .
+"
+ );
+ let v = report(&ttl);
+
+ let row = kind_row(&v, "rdfs:subClassOf");
+ assert_eq!(row["total"], 2, "two subsumptions: {row}");
+ assert_eq!(row["outside"], 1, "exactly one of them is disjunctive: {row}");
+ assert_eq!(row["inside"], 1, "and the other is not: {row}");
+ assert_eq!(row["partially_inside"], 0, "a disjunctive HEAD does not split: {row}");
+
+ assert_eq!(v["outside_the_fragment"]["count"], 1);
+ assert_eq!(outside_axioms(&v), vec!["<http://e/Adult>"]);
+
+ let entry = &v["outside_the_fragment"]["axioms"][0];
+ assert_eq!(entry["standing"], "outside");
+ let reason = entry["outside_because"][0]["reason"].as_str().unwrap_or("");
+ assert!(
+ reason.contains("disjunction in the consequent"),
+ "the reason must name the construct a reader acts on, got {reason:?}"
+ );
+ assert_eq!(entry["outside_because"][0]["construct"], "owl:unionOf");
+ assert_eq!(entry["outside_because"][0]["position"], "consequent");
+
+ // And it is NOT in the other bucket. This is the whole distinction.
+ assert!(
+ !unimplemented_axioms(&v).contains(&"<http://e/Adult>".to_string()),
+ "a non-Horn axiom is not an unimplemented rule: {}",
+ v["inside_the_fragment_but_a_rule_is_not_implemented"]
+ );
+}
+
+/// The other three reasons, each on an axiom built for it, each named.
+#[test]
+fn the_four_reasons_are_each_named_with_a_count() {
+ let ttl = format!(
+ "{PREFIXES}
+:A a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :B ] .
+:B a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :r ; owl:minCardinality 2 ] .
+:C a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :r ; owl:maxCardinality 3 ] .
+[ owl:complementOf :B ] rdfs:subClassOf :C .
+:r a owl:ObjectProperty .
+"
+ );
+ let v = report(&ttl);
+ let reasons: Vec<String> = v["reasons"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|r| r["reason"].as_str().unwrap_or("").to_string())
+ .collect();
+ let joined = reasons.join(" || ");
+
+ for wanted in [
+ "existential in the head",
+ "cardinality restriction",
+ "negation in the antecedent",
+ ] {
+ assert!(joined.contains(wanted), "no reason mentions {wanted:?}: {joined}");
+ }
+ // Counted, not merely named.
+ let total: u64 = v["reasons"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|r| r["occurrences"].as_u64().unwrap_or(0))
+ .sum();
+ assert_eq!(total, 4, "four axioms, four reasons: {:?}", reasons);
+}
+
+/// **Gate.** `owl:ReflexiveProperty` is outside OWL 2 RL and is NOT outside
+/// Horn logic, and the report says both.
+///
+/// `⊤(x) → r(x,x)` is a Horn clause. OWL 2 RL excludes the axiom form anyway,
+/// because a rule over the terms in the graph cannot reach the part of the
+/// domain nothing names. Saying "outside the fragment" without that
+/// qualification would be false, so the qualification is a field.
+#[test]
+fn a_horn_axiom_that_owl2_rl_excludes_carries_the_qualification() {
+ let ttl = format!("{PREFIXES}:r a owl:ObjectProperty, owl:ReflexiveProperty .\n");
+ let v = report(&ttl);
+ let entry = v["outside_the_fragment"]["axioms"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .find(|a| a["axiom_type"] == "owl:ReflexiveProperty")
+ .unwrap_or_else(|| panic!("no ReflexiveProperty row in {}", v["outside_the_fragment"]));
+ let note = entry["horn_but_outside_owl2_rl"].as_str().unwrap_or("");
+ assert!(
+ note.contains("Horn clause"),
+ "the qualification must say it IS Horn, got {note:?}"
+ );
+}
+
+// ── 3. Inside the fragment, and still invisible ─────────────────────────────
+
+/// **Gate.** An axiom INSIDE the fragment whose rule this engine does not
+/// implement lands in its own bucket, not with the non-Horn ones.
+///
+/// This is the test the tool exists for. `owl:hasKey` is a conjunction of
+/// property matches implying `owl:sameAs`: Horn through and through, and OWL 2
+/// RL has `prp-key` for it. This engine has no `prp-key`. So the axiom is
+/// inside the fragment AND invisible, and the fix is a patch to
+/// `src/reason.rs` rather than a rewrite of the ontology. Merging the two
+/// buckets would tell the reader to do the wrong thing.
+#[test]
+fn an_unimplemented_rule_is_not_reported_as_outside_the_fragment() {
+ let ttl = format!(
+ "{PREFIXES}
+:Person a owl:Class ; owl:hasKey ( :ssn ) .
+:ssn a owl:DatatypeProperty .
+:ancestor a owl:ObjectProperty ; owl:propertyChainAxiom ( :parent :ancestor ) .
+:parent a owl:ObjectProperty .
+:A a owl:Class ; rdfs:subClassOf :B .
+:B a owl:Class .
+"
+ );
+ let v = report(&ttl);
+
+ // Neither of the two is outside the fragment: both are Horn.
+ assert_eq!(
+ v["outside_the_fragment"]["count"], 0,
+ "hasKey and a property chain are BOTH Horn: {}",
+ v["outside_the_fragment"]
+ );
+ assert_eq!(kind_row(&v, "owl:hasKey")["outside"], 0);
+ assert_eq!(kind_row(&v, "owl:hasKey")["inside"], 1);
+ assert_eq!(kind_row(&v, "owl:propertyChainAxiom")["inside"], 1);
+
+ // Both ARE invisible, in the other bucket, each naming the rule that would
+ // have seen them.
+ assert_eq!(v["inside_the_fragment_but_a_rule_is_not_implemented"]["count"], 2);
+ let subjects = unimplemented_axioms(&v);
+ assert!(subjects.contains(&"<http://e/Person>".to_string()), "{subjects:?}");
+ assert!(subjects.contains(&"<http://e/ancestor>".to_string()), "{subjects:?}");
+
+ let key = v["inside_the_fragment_but_a_rule_is_not_implemented"]["axioms"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .find(|a| a["axiom_type"] == "owl:hasKey")
+ .expect("the hasKey row");
+ assert_eq!(key["standing"], "inside", "hasKey is inside the fragment");
+ assert_eq!(key["rules_this_engine_does_not"][0]["rule"], "prp-key");
+ assert_eq!(key["rules_this_engine_does_not"][0]["status"], "not_implemented");
+
+ let chain = v["inside_the_fragment_but_a_rule_is_not_implemented"]["axioms"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .find(|a| a["axiom_type"] == "owl:propertyChainAxiom")
+ .expect("the chain row");
+ assert_eq!(chain["rules_this_engine_does_not"][0]["rule"], "prp-spo2");
+
+ // And the clean subsumption is in neither bucket: `cax-sco` and `scm-sco`
+ // are both implemented, so the flag means something.
+ assert!(!subjects.contains(&"<http://e/A>".to_string()), "{subjects:?}");
+ assert_eq!(kind_row(&v, "rdfs:subClassOf")["inside_and_every_rule_implemented"], 1);
+
+ // The headline: what the rule table does not fully see, however it came to
+ // be that way, with the three causes still separately available because
+ // they are fixed in three different places.
+ let head = &v["not_fully_seen_by_the_rule_table"];
+ assert_eq!(head["axioms"], 2);
+ assert_eq!(head["wholly_outside_the_fragment"], 0);
+ assert_eq!(head["partially_inside_the_fragment"], 0);
+ assert_eq!(head["inside_but_a_rule_is_not_implemented"], 2);
+}
+
+/// A rule that concludes `false` and that the clash detector does not look for
+/// is reported as such, with the engine's own reason, and not as
+/// `not_implemented`.
+///
+/// `owl:AllDisjointClasses` is the case: it IS detected in its pairwise
+/// `owl:disjointWith` spelling and is not detected in its list spelling,
+/// because the clash detector reads no RDF lists. A reader who rewrites the
+/// axiom pairwise gets it back, and only the specific reason tells them that.
+#[test]
+fn an_undetected_clash_rule_keeps_its_own_word_and_its_own_reason() {
+ let ttl = format!(
+ "{PREFIXES}
+[] a owl:AllDisjointClasses ; owl:members ( :A :B :C ) .
+:A a owl:Class ; owl:disjointWith :B .
+:B a owl:Class . :C a owl:Class .
+"
+ );
+ let v = report(&ttl);
+
+ // The pairwise spelling is fully seen: cax-dw is in the clash detector.
+ assert_eq!(kind_row(&v, "owl:disjointWith")["inside_and_every_rule_implemented"], 1);
+
+ let adc = v["inside_the_fragment_but_a_rule_is_not_implemented"]["axioms"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .find(|a| a["axiom_type"] == "owl:AllDisjointClasses")
+ .unwrap_or_else(|| {
+ panic!("no AllDisjointClasses row: {}", v["inside_the_fragment_but_a_rule_is_not_implemented"])
+ });
+ assert_eq!(adc["standing"], "inside");
+ assert_eq!(adc["rules_this_engine_does_not"][0]["rule"], "cax-adc");
+ assert_eq!(
+ adc["rules_this_engine_does_not"][0]["status"], "clash_not_detected",
+ "a rule that concludes `false` and is not looked for is not the same failure as a rule \
+ nobody wrote"
+ );
+ let why = adc["rules_this_engine_does_not"][0]["why"].as_str().unwrap_or("");
+ assert!(
+ why.contains("owl:disjointWith"),
+ "the reason must name the spelling that IS detected, got {why:?}"
+ );
+}
+
+/// **Regression.** `owl:Thing` is excluded from the top-level `Class`
+/// alternative of both OWL 2 RL class grammars and is ADMITTED as a filler, and
+/// this classifier refused it as a filler for its first hour.
+///
+/// Section 4.2.3's `subObjectSomeValuesFrom` has a second alternative that is
+/// literally `'ObjectSomeValuesFrom' '(' ObjectPropertyExpression owl:Thing
+/// ')'`, and `superObjectMaxCardinality` has the matching one. `cls-svf2`,
+/// `cls-maxqc2` and `cls-maxqc4` are the rules for exactly those cases, and
+/// `cls-maxqc2` keys on `T(?x, owl:onClass, owl:Thing)` outright. Reporting
+/// such an axiom as outside the fragment is a FALSE POSITIVE, and a report
+/// whose job is to tell a user what is invisible has to be trusted not to
+/// invent losses.
+///
+/// Found by extracting the two grammars from the recommendation's HTML rather
+/// than by reasoning about them, which is the only reason it was found at all.
+#[test]
+fn owl_thing_as_a_filler_is_inside_the_fragment() {
+ let ttl = format!(
+ "{PREFIXES}
+[ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom owl:Thing ] rdfs:subClassOf :A .
+:B rdfs:subClassOf
+ [ a owl:Restriction ; owl:onProperty :r ; owl:maxQualifiedCardinality 1 ; owl:onClass owl:Thing ] .
+:A a owl:Class . :B a owl:Class . :r a owl:ObjectProperty .
+"
+ );
+ let v = report(&ttl);
+ assert_eq!(
+ v["outside_the_fragment"]["count"], 0,
+ "`exists r . Thing subClassOf A` is cls-svf2 and `B subClassOf max 1 r . Thing` is \
+ cls-maxqc4; both are legal OWL 2 RL: {v}"
+ );
+ assert_eq!(v["partially_inside_the_fragment"]["count"], 0, "{v}");
+ assert_eq!(kind_row(&v, "rdfs:subClassOf")["inside"], 2, "{v}");
+
+ // And `owl:Thing` in the ANTECEDENT of a subsumption, which is the position
+ // the grammar really does exclude, is still reported. Otherwise this test
+ // would pass on a classifier that had stopped looking at owl:Thing at all.
+ let universal = format!("{PREFIXES}owl:Thing rdfs:subClassOf :A .\n:A a owl:Class .\n");
+ let v = report(&universal);
+ assert_eq!(v["outside_the_fragment"]["count"], 1, "{v}");
+ let why = v["outside_the_fragment"]["axioms"][0]["outside_because"][0]["reason"]
+ .as_str()
+ .unwrap_or("");
+ assert!(why.contains("every element of the domain"), "got {why:?}");
+}
+
+// ── 4. Partial, and the splitting asymmetry ─────────────────────────────────
+
+/// An equivalence with an existential on one side keeps the direction the rule
+/// table evaluates, and is reported `partially_inside` rather than as either
+/// extreme.
+///
+/// `A ≡ ∃r.B` is `∃r.B ⊑ A`, which is exactly `cls-svf1`, and `A ⊑ ∃r.B`,
+/// which is an existential in the head. Reporting the whole axiom as outside
+/// would say the engine sees nothing of it, and reporting it as inside would
+/// say it sees all of it. Both are false.
+#[test]
+fn an_equivalence_with_one_horn_direction_is_partial() {
+ let ttl = format!(
+ "{PREFIXES}
+:Parent a owl:Class ;
+ owl:equivalentClass [ a owl:Restriction ; owl:onProperty :hasChild ; owl:someValuesFrom :Person ] .
+:Person a owl:Class .
+:hasChild a owl:ObjectProperty .
+"
+ );
+ let v = report(&ttl);
+ let row = kind_row(&v, "owl:equivalentClass");
+ assert_eq!(row["partially_inside"], 1, "{row}");
+ assert_eq!(row["inside"], 0, "{row}");
+ assert_eq!(row["outside"], 0, "{row}");
+
+ // In the PARTIAL bucket and not the outside one. A bucket called `outside`
+ // holding an axiom the rules half evaluate would be false in its own name.
+ assert_eq!(v["outside_the_fragment"]["count"], 0, "{v}");
+ assert_eq!(v["partially_inside_the_fragment"]["count"], 1, "{v}");
+ let entry = &v["partially_inside_the_fragment"]["axioms"][0];
+ assert_eq!(entry["standing"], "partially_inside");
+ let reason = entry["outside_because"][0]["reason"].as_str().unwrap_or("");
+ assert!(reason.contains("existential in the head"), "{reason}");
+ assert!(
+ v["partially_inside_the_fragment"]["why_not_outside"]
+ .as_str()
+ .unwrap_or("")
+ .contains("does NOT split"),
+ "the report states the asymmetry that makes the split sound: {v}"
+ );
+}
+
+/// **Gate.** The asymmetry: a conjunction splits in the consequent and does
+/// NOT split in the antecedent.
+///
+/// `A ⊑ B ⊓ Out` keeps `A ⊑ B`, so it is `partially_inside`. `A ⊓ Out ⊑ C`
+/// keeps nothing, because dropping a conjunct from a rule BODY makes the rule
+/// fire more often, which is unsound rather than weaker, so it is `outside`.
+/// A classifier that treated the two alike would be reporting a rule that
+/// fires on cases the user never wrote.
+#[test]
+fn a_conjunctive_body_with_one_bad_conjunct_is_outside_not_partial() {
+ let head = format!(
+ "{PREFIXES}
+:A a owl:Class ; rdfs:subClassOf
+ [ owl:intersectionOf ( :B [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :C ] ) ] .
+:B a owl:Class . :C a owl:Class . :r a owl:ObjectProperty .
+"
+ );
+ let v = report(&head);
+ let row = kind_row(&v, "rdfs:subClassOf");
+ assert_eq!(
+ row["partially_inside"], 1,
+ "`A subClassOf (B and exists r.C)` keeps its `A subClassOf B` half: {row}"
+ );
+ assert_eq!(row["outside"], 0, "{row}");
+
+ let body = format!(
+ "{PREFIXES}
+[ owl:intersectionOf ( :B [ a owl:Restriction ; owl:onProperty :r ; owl:allValuesFrom :C ] ) ]
+ rdfs:subClassOf :A .
+:A a owl:Class . :B a owl:Class . :C a owl:Class . :r a owl:ObjectProperty .
+"
+ );
+ let v = report(&body);
+ let row = kind_row(&v, "rdfs:subClassOf");
+ assert_eq!(
+ row["outside"], 1,
+ "a conjunctive BODY does not split: dropping a conjunct makes the rule fire more \
+ often, which is unsound and not merely weaker. {row}"
+ );
+ assert_eq!(row["partially_inside"], 0, "{row}");
+}
+
+/// A disjunction in the ANTECEDENT splits, which is the mirror of the above and
+/// the reason the asymmetry is about position and not about the connective.
+#[test]
+fn a_disjunctive_body_splits_where_a_disjunctive_head_does_not() {
+ let ttl = format!(
+ "{PREFIXES}
+[ owl:unionOf ( :B [ a owl:Restriction ; owl:onProperty :r ; owl:allValuesFrom :C ] ) ]
+ rdfs:subClassOf :A .
+:A a owl:Class . :B a owl:Class . :C a owl:Class . :r a owl:ObjectProperty .
+"
+ );
+ let v = report(&ttl);
+ assert_eq!(
+ kind_row(&v, "rdfs:subClassOf")["partially_inside"], 1,
+ "`(B or all r.C) subClassOf A` keeps `B subClassOf A`: {v}"
+ );
+}
+
+// ── 5. Nothing is passed over in silence ────────────────────────────────────
+
+/// **Gate.** Every triple in the store is either classified as an axiom or
+/// counted in a named `not_classified` bucket.
+///
+/// A tool that reports on a fragment and leaves the rest uncounted is the shape
+/// this module exists to attack, so it must not be that shape itself.
+#[test]
+fn every_triple_lands_somewhere() {
+ // Built here rather than loaded, and deliberately mixed: schema axioms of
+ // every standing, a class expression with its RDF list, an annotation, a
+ // declaration, a data assertion and an object assertion. A fixture that
+ // happened to contain no schema axiom would pass the partition check while
+ // proving nothing, which is how this test first went green on a file that
+ // turned out to be pure instance data.
+ let ttl = format!(
+ "{PREFIXES}
+:A a owl:Class ; rdfs:label \"A\" ; rdfs:subClassOf [ owl:unionOf ( :B :C ) ] .
+:B a owl:Class ; rdfs:subClassOf :C ; owl:disjointWith :D .
+:C a owl:Class ; owl:equivalentClass
+ [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :D ] .
+:D a owl:Class ; owl:hasKey ( :r ) .
+:r a owl:ObjectProperty, owl:TransitiveProperty ; rdfs:domain :A ; rdfs:range :B ;
+ owl:propertyChainAxiom ( :r :r ) ; owl:inverseOf :s .
+:s a owl:ObjectProperty .
+:p a owl:DatatypeProperty .
+:a a :A ; :r :b ; :p \"x\" ; owl:sameAs :b .
+:b a :B .
+"
+ );
+ let v = report(&ttl);
+
+ let classified = v["axioms_classified"].as_u64().expect("a count");
+ let unclassified: u64 = v["not_classified"]["counts"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|c| c["occurrences"].as_u64().unwrap_or(0))
+ .sum();
+ assert_eq!(
+ classified + unclassified,
+ v["triples"].as_u64().expect("a count"),
+ "the partition is not total: {classified} + {unclassified} against {}",
+ v["triples"]
+ );
+ assert!(classified >= 11, "the fixture has schema axioms of every standing: {classified}");
+ // And each of the three standings is present, so the partition above is
+ // over a real mixture rather than over one bucket.
+ assert!(v["outside_the_fragment"]["count"].as_u64().unwrap_or(0) > 0, "{v}");
+ assert!(
+ v["inside_the_fragment_but_a_rule_is_not_implemented"]["count"]
+ .as_u64()
+ .unwrap_or(0)
+ > 0,
+ "{v}"
+ );
+ let partial: u64 = v["by_axiom_type"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|r| r["partially_inside"].as_u64().unwrap_or(0))
+ .sum();
+ assert!(partial > 0, "the equivalentClass with an existential on one side is partial: {v}");
+ // The three causes are disjoint and sum to the headline.
+ let head = &v["not_fully_seen_by_the_rule_table"];
+ assert_eq!(
+ head["wholly_outside_the_fragment"].as_u64().unwrap_or(0)
+ + head["partially_inside_the_fragment"].as_u64().unwrap_or(0)
+ + head["inside_but_a_rule_is_not_implemented"].as_u64().unwrap_or(0),
+ head["axioms"].as_u64().unwrap_or(0),
+ "{head}"
+ );
+ assert_eq!(head["partially_inside_the_fragment"].as_u64().unwrap_or(0), partial);
+ let outside: u64 = v["by_axiom_type"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|r| r["outside"].as_u64().unwrap_or(0))
+ .sum();
+ assert_eq!(head["wholly_outside_the_fragment"].as_u64().unwrap_or(0), outside);
+}
+
+/// An ontology entirely inside the fragment, with every rule implemented,
+/// reports nothing invisible. Without this the flag could be true always and
+/// still pass every test above.
+#[test]
+fn an_ontology_the_rule_table_fully_sees_reports_nothing_invisible() {
+ let ttl = format!(
+ "{PREFIXES}
+:A a owl:Class ; rdfs:subClassOf :B ; owl:disjointWith :D .
+:B a owl:Class ; rdfs:subClassOf :Top .
+:D a owl:Class . :Top a owl:Class .
+:r a owl:ObjectProperty, owl:TransitiveProperty ; rdfs:domain :A ; rdfs:range :B .
+:a a :A . :a :r :b . :b a :B .
+"
+ );
+ let v = report(&ttl);
+ assert_eq!(v["outside_the_fragment"]["count"], 0, "{v}");
+ assert_eq!(
+ v["inside_the_fragment_but_a_rule_is_not_implemented"]["count"], 0,
+ "{}",
+ v["inside_the_fragment_but_a_rule_is_not_implemented"]
+ );
+ assert_eq!(v["not_fully_seen_by_the_rule_table"]["axioms"], 0);
+ assert_eq!(v["axioms_classified"], 6, "{v}");
+}
+
+/// A long listing is capped and the cap is reported, so it hides the listing
+/// and never the scale. The same discipline `onto_defects` uses.
+#[test]
+fn a_long_listing_is_capped_and_says_so() {
+ let mut ttl = String::from(PREFIXES);
+ for i in 0..60 {
+ ttl.push_str(&format!(
+ ":C{i} a owl:Class ; rdfs:subClassOf [ owl:unionOf ( :X :Y ) ] .\n"
+ ));
+ }
+ ttl.push_str(":X a owl:Class . :Y a owl:Class .\n");
+ let v = report(&ttl);
+ assert_eq!(v["outside_the_fragment"]["count"], 60);
+ assert_eq!(v["outside_the_fragment"]["listed"], 50, "capped at MAX_LISTED");
+ assert_eq!(v["outside_the_fragment"]["truncated"], true);
+}
+
+/// The report's rule-table figures are the derived ones, in the output, so a
+/// reader does not have to take the prose for it.
+#[test]
+fn the_report_carries_the_derived_rule_counts() {
+ let v = report(&format!("{PREFIXES}:A a owl:Class .\n"));
+ assert_eq!(v["rule_table"]["owl2_rl_rules"], 78);
+ assert_eq!(v["rule_table"]["evaluated_in_the_fixpoint"], 29);
+ assert_eq!(v["rule_table"]["detected_as_a_clash"], 10);
+ assert_eq!(v["rule_table"]["concludes_false_and_not_detected"], 7);
+ assert_eq!(v["rule_table"]["not_implemented"], 32);
+ let names = v["rule_table"]["not_implemented_names"].as_array().expect("a list");
+ assert_eq!(names.len(), 32);
+ // The per-profile counts are derived from reason::RULES_EVALUATED and nest.
+ // A report quoting all 29 to an `rdfs` run would describe a table that run
+ // never used.
+ let by_profile = &v["rule_table"]["evaluated_by_profile"];
+ assert_eq!(by_profile["rdfs"], 6);
+ assert_eq!(by_profile["owl-rl"], 17);
+ assert_eq!(by_profile["owl-rl-ext"], 29);
+ assert!(names.iter().any(|n| n == "prp-key"));
+ assert!(names.iter().any(|n| n == "prp-spo2"));
+ assert!(names.iter().any(|n| n == "eq-trans"));
+ // And the two dimensions are described in the output, not only in a doc.
+ assert!(v["two_dimensions_never_merged"]["fragment"].is_string());
+ assert!(v["two_dimensions_never_merged"]["engine"].is_string());
+}
diff --git a/tests/fol_cgif_export_test.rs b/tests/fol_cgif_export_test.rs
new file mode 100644
index 00000000..37966d88
--- /dev/null
+++ b/tests/fol_cgif_export_test.rs
@@ -0,0 +1,1220 @@
+//! CGIF, the second of ISO/IEC 24707's three Common Logic dialects.
+//!
+//! This engine emitted CLIF only, which made its Common Logic support partial
+//! in a way nothing said out loud. ISO/IEC 21838-1:2021 clause 4.3 asks for an
+//! axiomatisation in a language conforming to ISO/IEC 24707, and its note names
+//! CLIF, CGIF and XCL as the three that qualify. Emitting one of them and
+//! calling it Common Logic support is the shape of overclaim this repository
+//! exists to attack, in its own output. XCL is still absent and the report says
+//! so in a field.
+//!
+//! # What conformance rests on here, stated first
+//!
+//! **There is no independent CGIF parser to check the output against.** No
+//! package named `cgif` exists on PyPI; py-typedlogic, which reads the CLIF
+//! output, has no CGIF front end; the Macleod toolchain reads CLIF. So the
+//! conformance of the emitted text is **pinned by the checker in this file and
+//! not by an independent implementation**, and every claim below is exactly as
+//! good as that checker.
+//!
+//! That is a weaker footing than the CLIF side has, and the difference is
+//! stated rather than blurred. `docs/first-order-export.md` records what two
+//! external CLIF parsers do with the CLIF output, including that both return an
+//! EMPTY theory from the wrapped comment shape. Nothing of that kind is
+//! available here.
+//!
+//! What IS available is the normative text. ISO/IEC 24707:2018 is in ISO's
+//! Publicly Available Standards list and was downloaded and read for this work
+//! (sha256 e920b0c43a932e1ad0e2c76d3501f56e2b11ee5547265b14aeb69a5866eae5e3).
+//! The checker below is transcribed from Annex B's EBNF, clause by clause, with
+//! the clause cited at each rule. A transcription is a claim like any other;
+//! what makes it worth something is that it is a SECOND reading of the grammar,
+//! written against the emitter rather than with it, so a shape both agree on is
+//! a shape two readings of Annex B agree on.
+//!
+//! Sowa's `jfsowa.com/cg/annexb.htm` is a PRE-PUBLICATION DRAFT of the same
+//! annex and was not used: its `equiv` rewrite emits `~[` where the published
+//! text emits `[`, which turns a conjunction of two implications into a
+//! tautology, and its `nestedOrs` termination test drops the last disjunct.
+//!
+//! # The groups
+//!
+//! 1. A lexer and a parser for core CGIF, from Annex B.2.
+//! 2. Syntax conformance: the emitted text parses, and it stays inside the
+//! compact first-order sub-dialect.
+//! 3. Round trip: every sentence reads back to the `Form` it was built from,
+//! up to the two rewrites core CGIF forces.
+//! 4. One translation, two Common Logic dialects: the CGIF and the CLIF file
+//! carry the same sentences, in the same order, under the same labels.
+//! 5. What cannot be exported is named and counted, and what cannot be
+//! WRITTEN is refused rather than rewritten.
+
+use open_ontologies::tptp::{
+ cgif, clif, ClifComments, ClifDialect, Concept, FolProblem, Form, Ope, OwlAxiom, Syntax,
+ Translation, P1, P2, Term,
+};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+const TEXT_NAME: &str = "http://e/ontology";
+
+fn c(s: &str) -> Concept {
+ Concept::Atom(format!("http://e/{s}"))
+}
+fn iri(s: &str) -> String {
+ format!("http://e/{s}")
+}
+
+/// A corpus that exercises every constructor of `Form` at least once. The same
+/// one `tests/fol_translation_correspondence_test.rs` uses for CLIF, so the two
+/// dialects are checked over the same axioms.
+fn corpus() -> Vec<OwlAxiom> {
+ vec![
+ OwlAxiom::SubClass(c("A"), c("B")),
+ OwlAxiom::SubClass(c("A"), Concept::Some_(iri("r"), Box::new(c("B")))),
+ OwlAxiom::SubClass(c("A"), Concept::All_(iri("r"), Box::new(c("B")))),
+ OwlAxiom::SubClass(c("A"), Concept::MinCard(2, iri("r"), Box::new(c("B")))),
+ OwlAxiom::SubClass(c("A"), Concept::MaxCard(1, iri("r"), Box::new(Concept::Top))),
+ OwlAxiom::SubClass(Concept::Bot, Concept::Compl(Box::new(c("B")))),
+ OwlAxiom::SubClass(
+ Concept::Inter(Box::new(c("A")), Box::new(c("B"))),
+ Concept::Union(Box::new(c("A")), Box::new(c("B"))),
+ ),
+ OwlAxiom::SubClass(c("A"), Concept::OneOf(vec![iri("a"), iri("b")])),
+ OwlAxiom::SubClass(c("A"), Concept::HasVal(iri("r"), iri("a"))),
+ OwlAxiom::SubClass(c("A"), Concept::HasSelf(iri("r"))),
+ OwlAxiom::SubClass(c("A"), Concept::DataSome(iri("p"), iri("D"))),
+ OwlAxiom::SubClass(c("A"), Concept::DataAll(iri("p"), iri("D"))),
+ OwlAxiom::EquivClass(c("A"), c("B")),
+ OwlAxiom::DisjointWith(c("A"), c("B")),
+ OwlAxiom::SubOProp(Ope::Named(iri("r")), Ope::Inv(iri("s"))),
+ OwlAxiom::OPropDomain(Ope::Inv(iri("r")), c("A")),
+ OwlAxiom::OPropRange(Ope::Named(iri("r")), c("A")),
+ OwlAxiom::DPropDomain(iri("p"), c("A")),
+ OwlAxiom::DPropRange(iri("p"), iri("D")),
+ OwlAxiom::Transitive(iri("r")),
+ OwlAxiom::Symmetric(iri("r")),
+ OwlAxiom::Asymmetric(iri("r")),
+ OwlAxiom::Reflexive(iri("r")),
+ OwlAxiom::Irreflexive(iri("r")),
+ OwlAxiom::Functional(iri("r")),
+ OwlAxiom::InvFunctional(iri("r")),
+ OwlAxiom::InverseOf(iri("r"), iri("s")),
+ OwlAxiom::PropDisjoint(iri("r"), iri("s")),
+ OwlAxiom::Chain(vec![iri("r"), iri("s")], iri("t")),
+ OwlAxiom::ClassAssert(c("A"), iri("a")),
+ OwlAxiom::OPropAssert(iri("r"), iri("a"), iri("b")),
+ OwlAxiom::SameAs(iri("a"), iri("b")),
+ OwlAxiom::DifferentFrom(iri("a"), iri("b")),
+ ]
+}
+
+// ── 1. A lexer and parser for core CGIF, from Annex B.2 ─────────────────────
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Tok {
+ Open,
+ Close,
+ LParen,
+ RParen,
+ Tilde,
+ Star,
+ Query,
+ Colon,
+ Bar,
+ Hash,
+ At,
+ /// `/* … */`, with the delimiters stripped. B.2.4.
+ Comment(String),
+ /// A bare token: an `identifier`, a `numeral`, or a `seqmark`. Which one it
+ /// is, is the checker's business and not the lexer's.
+ Bare(String),
+ /// `"…"`, a B.1.1 `enclosedname`, with the quotes stripped and escapes
+ /// undone.
+ Enclosed(String),
+ /// `'…'`, a CLIF `quotedstring`. An INTERPRETED name, which is why the
+ /// checker refuses one.
+ Quoted(String),
+}
+
+/// Lex core CGIF. Everything the grammar can produce gets a token, including
+/// the constructs the emitter must never produce, because a checker that could
+/// not LEX an actor could not refuse one either.
+fn lex(src: &str) -> Vec<Tok> {
+ let mut out = Vec::new();
+ let mut chars = src.chars().peekable();
+ while let Some(&ch) = chars.peek() {
+ match ch {
+ c if c.is_whitespace() => {
+ chars.next();
+ }
+ '[' => {
+ chars.next();
+ out.push(Tok::Open);
+ }
+ ']' => {
+ chars.next();
+ out.push(Tok::Close);
+ }
+ '(' => {
+ chars.next();
+ out.push(Tok::LParen);
+ }
+ ')' => {
+ chars.next();
+ out.push(Tok::RParen);
+ }
+ '~' => {
+ chars.next();
+ out.push(Tok::Tilde);
+ }
+ '*' => {
+ chars.next();
+ out.push(Tok::Star);
+ }
+ '?' => {
+ chars.next();
+ out.push(Tok::Query);
+ }
+ ':' => {
+ chars.next();
+ out.push(Tok::Colon);
+ }
+ '|' => {
+ chars.next();
+ out.push(Tok::Bar);
+ }
+ '#' => {
+ chars.next();
+ out.push(Tok::Hash);
+ }
+ '@' => {
+ chars.next();
+ out.push(Tok::At);
+ }
+ '/' => {
+ chars.next();
+ assert_eq!(chars.next(), Some('*'), "a bare / is not a CGIF token");
+ let mut body = String::new();
+ loop {
+ let c = chars.next().expect("unterminated /* comment");
+ if c == '*' && chars.peek() == Some(&'/') {
+ chars.next();
+ break;
+ }
+ body.push(c);
+ }
+ out.push(Tok::Comment(body));
+ }
+ '"' | '\'' => {
+ let delim = ch;
+ chars.next();
+ let mut body = String::new();
+ loop {
+ match chars.next().expect("unterminated name or string") {
+ '\\' => body.push(chars.next().expect("escape at end of input")),
+ c if c == delim => break,
+ c => body.push(c),
+ }
+ }
+ out.push(if delim == '"' { Tok::Enclosed(body) } else { Tok::Quoted(body) });
+ }
+ _ => {
+ let mut name = String::new();
+ while let Some(&n) = chars.peek() {
+ if n.is_whitespace()
+ || matches!(n, '[' | ']' | '(' | ')' | '~' | '*' | '?' | ':' | '|' | '"' | '\'' | '#' | '@' | '/')
+ {
+ break;
+ }
+ name.push(n);
+ chars.next();
+ }
+ assert!(!name.is_empty(), "lexer stuck at {ch:?}");
+ out.push(Tok::Bare(name));
+ }
+ }
+ }
+ out
+}
+
+/// A CG name. B.1.1: `CGname = identifier | '"', (namesequence - identifier),
+/// '"' | numeral | enclosedname | quotedstring`.
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+enum Name {
+ Bare(String),
+ Enclosed(String),
+ /// A `quotedstring`. Legal CGIF and an interpreted name, so the checker
+ /// refuses one in this text.
+ Quoted(String),
+}
+
+/// B.2.9: `reference = ["?"], CGname`. `bound` is the `?`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct Ref {
+ bound: bool,
+ name: Name,
+}
+
+/// The core CGIF node kinds, B.2.5 to B.2.8.
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Node {
+ Comment(String),
+ /// B.2.7 `ordinaryRelation`. `bound_type_label` records a `#?` prefix, the
+ /// construct that quantifies into a predicate position.
+ Relation { bound_type_label: bool, name: Name, args: Vec<Ref>, seqmark: bool },
+ /// B.2.1 `actor`, the CL function form. Parsed so it can be refused.
+ Actor,
+ /// B.2.8 `negation = "~", context`.
+ Negation(Vec<Node>),
+ /// B.2.5 `context`.
+ Context(Vec<Node>),
+ /// B.2.5 `existentialConcept`: `[*x]`. `seqmark` is `[*...x]`.
+ Existential { name: Name, seqmark: bool },
+ /// B.2.5 `coreferenceConcept`: `[: r …]`.
+ Coreference(Vec<Ref>),
+ /// Anything the core grammar does not have in a concept: a type label, a
+ /// type expression, `@every`. Extended CGIF only, parsed so it can be
+ /// refused rather than silently reinterpreted.
+ ExtendedConcept(String),
+}
+
+struct Parser {
+ toks: Vec<Tok>,
+ i: usize,
+}
+
+impl Parser {
+ fn peek(&self) -> Option<&Tok> {
+ self.toks.get(self.i)
+ }
+ fn next(&mut self) -> Tok {
+ let t = self.toks.get(self.i).cloned().expect("unexpected end of CGIF");
+ self.i += 1;
+ t
+ }
+ fn eat(&mut self, t: Tok) {
+ let got = self.next();
+ assert_eq!(got, t, "expected {t:?}");
+ }
+
+ fn name(&mut self) -> Name {
+ match self.next() {
+ Tok::Bare(s) => Name::Bare(s),
+ Tok::Enclosed(s) => Name::Enclosed(s),
+ Tok::Quoted(s) => Name::Quoted(s),
+ other => panic!("expected a CGname, found {other:?}"),
+ }
+ }
+
+ /// B.2.9 `reference = ["?"], CGname`.
+ fn reference(&mut self) -> Ref {
+ if self.peek() == Some(&Tok::Query) {
+ self.next();
+ Ref { bound: true, name: self.name() }
+ } else {
+ Ref { bound: false, name: self.name() }
+ }
+ }
+
+ /// B.2.6 `CG = {concept | conceptualRelation | negation | comment}`.
+ fn cg(&mut self, terminator: Tok) -> Vec<Node> {
+ let mut nodes = Vec::new();
+ while self.peek() != Some(&terminator) {
+ nodes.push(self.node());
+ }
+ nodes
+ }
+
+ fn node(&mut self) -> Node {
+ match self.peek().cloned().expect("unexpected end of CGIF") {
+ Tok::Comment(_) => match self.next() {
+ Tok::Comment(s) => Node::Comment(s),
+ _ => unreachable!(),
+ },
+ Tok::Tilde => {
+ self.next();
+ self.eat(Tok::Open);
+ let body = self.cg(Tok::Close);
+ self.eat(Tok::Close);
+ Node::Negation(body)
+ }
+ Tok::Open => {
+ self.next();
+ self.concept_after_open()
+ }
+ Tok::LParen => {
+ self.next();
+ self.relation_after_lparen()
+ }
+ other => panic!("not the start of a CGIF node: {other:?}"),
+ }
+ }
+
+ fn concept_after_open(&mut self) -> Node {
+ match self.peek().cloned() {
+ // `[*x]` or `[*...x]`. B.2.5 existentialConcept.
+ Some(Tok::Star) => {
+ self.next();
+ let name = self.name();
+ let seqmark = matches!(&name, Name::Bare(s) if s.starts_with("..."));
+ self.eat(Tok::Close);
+ Node::Existential { name, seqmark }
+ }
+ // `[: r …]`. B.2.5 coreferenceConcept, `{reference}-`.
+ Some(Tok::Colon) => {
+ self.next();
+ let mut refs = Vec::new();
+ while self.peek() != Some(&Tok::Close) {
+ refs.push(self.reference());
+ }
+ self.eat(Tok::Close);
+ assert!(!refs.is_empty(), "a coreference concept takes at least one reference");
+ Node::Coreference(refs)
+ }
+ // `[@every*x]` or `[@*x …]`. Extended CGIF only, B.3.6 and B.3.10.
+ Some(Tok::At) => {
+ let mut depth = 1;
+ while depth > 0 {
+ match self.next() {
+ Tok::Open => depth += 1,
+ Tok::Close => depth -= 1,
+ _ => {}
+ }
+ }
+ Node::ExtendedConcept("@ (a universal quantifier or a type expression)".into())
+ }
+ // A bare name here is a TYPE LABEL, which core CGIF has no field
+ // for: B.1.2, "extended syntax of CGIF, which adds type labels on
+ // concepts".
+ Some(Tok::Bare(_)) | Some(Tok::Enclosed(_)) | Some(Tok::Quoted(_)) => {
+ let label = format!("{:?}", self.peek().expect("peeked"));
+ let mut depth = 1;
+ while depth > 0 {
+ match self.next() {
+ Tok::Open => depth += 1,
+ Tok::Close => depth -= 1,
+ _ => {}
+ }
+ }
+ Node::ExtendedConcept(format!("a type label on a concept: {label}"))
+ }
+ // `[ CG ]`. B.2.5 context, the arm every other case is not.
+ _ => {
+ let body = self.cg(Tok::Close);
+ self.eat(Tok::Close);
+ Node::Context(body)
+ }
+ }
+ }
+
+ fn relation_after_lparen(&mut self) -> Node {
+ let bound_type_label = if self.peek() == Some(&Tok::Hash) {
+ self.next();
+ self.eat(Tok::Query);
+ true
+ } else {
+ false
+ };
+ let name = self.name();
+ let mut args = Vec::new();
+ let mut seqmark = false;
+ let mut actor = false;
+ loop {
+ match self.peek().cloned().expect("unterminated conceptual relation") {
+ Tok::RParen => {
+ self.next();
+ break;
+ }
+ // B.2.1 actor: the bar splits the arc sequence.
+ Tok::Bar => {
+ self.next();
+ actor = true;
+ }
+ _ => {
+ let r = self.reference();
+ if matches!(&r.name, Name::Bare(s) if s.starts_with("...")) {
+ seqmark = true;
+ }
+ args.push(r);
+ }
+ }
+ }
+ if actor {
+ return Node::Actor;
+ }
+ Node::Relation { bound_type_label, name, args, seqmark }
+ }
+}
+
+/// B.2.11 `text = "[", [comment], "Proposition", ":", [CGname], CG,
+/// [endComment], "]"`. Returns the text's name and its CG.
+fn parse_text(src: &str) -> (Name, Vec<Node>) {
+ let mut p = Parser { toks: lex(src), i: 0 };
+ p.eat(Tok::Open);
+ assert_eq!(
+ p.next(),
+ Tok::Bare("Proposition".to_string()),
+ "B.2.11 spells the text's type label `Proposition`"
+ );
+ p.eat(Tok::Colon);
+ let name = p.name();
+ let body = p.cg(Tok::Close);
+ p.eat(Tok::Close);
+ assert_eq!(p.i, p.toks.len(), "trailing tokens after the text");
+ (name, body)
+}
+
+// ── 2. Syntax conformance ───────────────────────────────────────────────────
+
+/// **Gate.** The emitted text is a B.2.11 `text` whose every node is a core
+/// CGIF node, and it parses to the end.
+///
+/// A file nothing can read is the failure this whole layer exists to catch: the
+/// CLIF side found that both parsers that exist return an EMPTY theory from the
+/// shape ISO's own BFO files use. The check here is a second reading of the
+/// grammar rather than an independent implementation, and the module header
+/// says so.
+#[test]
+fn the_emitted_cgif_parses_as_a_core_cgif_text() {
+ let problem = FolProblem::build(&corpus(), None).expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("no comment closes itself early");
+ let (name, body) = parse_text(&text);
+
+ assert_eq!(
+ name,
+ Name::Enclosed(TEXT_NAME.to_string()),
+ "B.1.1 admits only letters, digits and underscore in a bare identifier, so an IRI must \
+ be an enclosed name. The CLIF writer emits a bare IRI for Macleod's sake and this one \
+ cannot"
+ );
+
+ let n = problem.formulas().len();
+ let comments = body.iter().filter(|x| matches!(x, Node::Comment(_))).count();
+ let sentences: Vec<&Node> = body.iter().filter(|x| !matches!(x, Node::Comment(_))).collect();
+ assert_eq!(comments, n + 1, "one label comment per formula, plus the header");
+ assert_eq!(sentences.len(), n, "one sentence node per formula");
+ for s in &sentences {
+ assert!(
+ matches!(s, Node::Context(_)),
+ "every sentence is wrapped in a context of its own, so a formula whose root is a \
+ conjunction cannot spread across the text's own graph: {s:?}"
+ );
+ }
+}
+
+/// Walk every node of a parse, calling `f` on each, with the path depth.
+fn walk(nodes: &[Node], f: &mut impl FnMut(&Node)) {
+ for n in nodes {
+ f(n);
+ match n {
+ Node::Negation(b) | Node::Context(b) => walk(b, f),
+ _ => {}
+ }
+ }
+}
+
+/// **Gate.** The text stays inside the compact, first-order sub-dialect.
+///
+/// ISO/IEC 24707 clause 7.1.1 names it: "A compact sub-dialect is a dialect
+/// that does not recognize sequence markers." Clause 6.5 says why that is the
+/// one that matters: Common Logic with sequence markers "is not compact, and
+/// therefore not first-order", and `OwlLean.adequacy` is about plain
+/// first-order logic, so a text using one would sit outside the theorem.
+///
+/// Six properties, each tied to the production that would otherwise admit the
+/// construct:
+///
+/// * no sequence marker, in B.2.5's `existentialConcept` or B.2.3's
+/// `arcSequence`,
+/// * no `#?` type label, which B.2.7's own comment says is how CGIF
+/// "supports the CL ability to quantify over relations and functions",
+/// * no actor, B.2.1, which is how a CL FUNCTION is written,
+/// * no extended-CGIF concept: no type label, no type expression, no
+/// `@every`,
+/// * every relation name used at ONE arity throughout,
+/// * no bound coreference label in a relation's type-label position.
+#[test]
+fn cgif_stays_in_the_compact_first_order_sub_dialect() {
+ let problem = FolProblem::build(&corpus(), Some(&OwlAxiom::SubClass(c("A"), c("B"))))
+ .expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("writable");
+ let (_, body) = parse_text(&text);
+ // The check is on the PARSE and not on the raw text, because the header
+ // names the constructs it excludes and a substring search for `...` finds
+ // the header saying it emits none. B.2.4 lets a comment hold anything but
+ // its own closing delimiter, so only the nodes can be searched.
+ for n in &body {
+ if let Node::Comment(_) = n {
+ continue;
+ }
+ assert!(
+ !format!("{n:?}").contains("..."),
+ "a sequence marker in a sentence would take the text out of the compact sub-dialect"
+ );
+ }
+
+ let mut arity: HashMap<Name, usize> = HashMap::new();
+ let mut relations = 0usize;
+ walk(&body, &mut |n| match n {
+ Node::Actor => panic!("an actor is a CL function, and FSig has no function symbol"),
+ Node::ExtendedConcept(what) => panic!("extended CGIF construct in a core text: {what}"),
+ Node::Existential { seqmark, name } => {
+ assert!(!seqmark, "a defining sequence label: {name:?}");
+ assert!(
+ matches!(name, Name::Bare(_)),
+ "a defining label is an identifier, never a numeral or a quoted string, which \
+ CLIF's `bvar` could not bind: {name:?}"
+ );
+ }
+ Node::Relation { bound_type_label, name, args, seqmark } => {
+ assert!(!bound_type_label, "a `#?` type label quantifies into a predicate position");
+ assert!(!seqmark, "a bound sequence label in an arc sequence");
+ relations += 1;
+ let seen = arity.entry(name.clone()).or_insert(args.len());
+ assert_eq!(
+ *seen,
+ args.len(),
+ "{name:?} is used at two arities, which is arity-free Common Logic and not plain \
+ first-order logic"
+ );
+ }
+ _ => {}
+ });
+ assert!(relations > 0, "no relation was checked, so this gate proved nothing");
+ assert_eq!(arity[&Name::Bare("thing".to_string())], 1);
+ assert_eq!(arity[&Name::Bare("lit".to_string())], 1);
+}
+
+/// **Gate.** No numeral and no single-quoted string stands anywhere in the
+/// text, and every predicate and constant is a name the grammar admits.
+///
+/// A.4.2 says of CLIF that "The subdialect of CLIF which does not use numerals
+/// or quoted strings is exactly semantically conformant", and Annex B states no
+/// analogue for CGIF, so this test holds the PROPERTY and the emitter does not
+/// borrow the label. CGIF gets it without the exception CLIF needs: a CLIF
+/// label rides on `cl:comment`, whose argument is a quoted string, while B.2.4
+/// makes a CGIF comment a lexical construct that is not a name at all.
+#[test]
+fn cgif_uses_no_interpreted_name() {
+ let problem = FolProblem::build(&corpus(), None).expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("writable");
+ let (_, body) = parse_text(&text);
+
+ fn ok_name(n: &Name) {
+ match n {
+ Name::Quoted(s) => panic!(
+ "a single-quoted string is an INTERPRETED name, whose denotation is fixed in \
+ every interpretation: {s}"
+ ),
+ Name::Bare(s) => {
+ assert!(
+ !s.starts_with(|c: char| c.is_ascii_digit()),
+ "a bare decimal is a CGIF numeral, which is an interpreted name: {s}"
+ );
+ // B.1.1: `identifier = letter, {letter | digit | "_"}`. `letter`
+ // is used there and never defined anywhere in ISO/IEC
+ // 24707:2018, which is a defect in the standard; the emitter
+ // produces ASCII letters only, so the ASCII reading is the one
+ // checked and the choice is written down rather than assumed.
+ let mut cs = s.chars();
+ assert!(
+ cs.next().is_some_and(|c| c.is_ascii_alphabetic()),
+ "an identifier begins with a letter: {s}"
+ );
+ assert!(
+ cs.all(|c| c.is_ascii_alphanumeric() || c == '_'),
+ "an identifier is letters, digits and underscore, and an IRI is none of \
+ those, so it must be an enclosed name: {s}"
+ );
+ }
+ Name::Enclosed(_) => {}
+ }
+ }
+
+ let mut checked = 0usize;
+ walk(&body, &mut |n| match n {
+ Node::Relation { name, args, .. } => {
+ ok_name(name);
+ checked += 1;
+ for a in args {
+ ok_name(&a.name);
+ }
+ }
+ Node::Coreference(refs) => {
+ for r in refs {
+ ok_name(&r.name);
+ }
+ }
+ Node::Existential { name, .. } => ok_name(name),
+ _ => {}
+ });
+ assert!(checked > 0);
+}
+
+/// **Gate.** No defining coreference label is ever shadowed, and no context
+/// directly contains two of them.
+///
+/// B.2.10 says both that a context "shall not contain any concept other than x
+/// with a defining label with the same CG name n" — where *contains* is
+/// transitive — and, in the sentence after it, that a nested context may
+/// redeclare one. The two cannot both hold. The emitter gives every binder a
+/// context of its own and never redeclares a name inside its own scope, so the
+/// text is legal under EITHER reading and nothing here depends on which is
+/// right.
+///
+/// The third clause of B.2.10 is checked too: "No constant with CG name n shall
+/// be in the scope associated with some concept with a defining label with CG
+/// name n." That one holds structurally — a defining label is `Xn` and a
+/// constant begins `i:` — and is checked rather than argued.
+#[test]
+fn no_defining_label_is_ever_shadowed() {
+ let problem = FolProblem::build(&corpus(), None).expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("writable");
+ let (_, body) = parse_text(&text);
+
+ fn check(nodes: &[Node], in_scope: &mut BTreeSet<Name>, path: &str) {
+ let mut here: BTreeMap<Name, usize> = BTreeMap::new();
+ for n in nodes {
+ if let Node::Existential { name, .. } = n {
+ *here.entry(name.clone()).or_default() += 1;
+ assert!(
+ !in_scope.contains(name),
+ "the defining label {name:?} at {path} is inside the scope of another with \
+ the same name. B.2.10 is self-contradictory about whether that shadows or \
+ is illegal, and this emitter must not depend on the answer"
+ );
+ }
+ }
+ for (name, count) in &here {
+ assert_eq!(
+ *count, 1,
+ "the context at {path} directly contains {count} defining labels named \
+ {name:?}; B.2.10 admits one"
+ );
+ }
+ let added: Vec<Name> = here.keys().cloned().collect();
+ for n in &added {
+ in_scope.insert(n.clone());
+ }
+ for (i, n) in nodes.iter().enumerate() {
+ // A constant whose name equals a defining label in scope is
+ // forbidden outright by B.2.10's last clause.
+ let names: Vec<&Ref> = match n {
+ Node::Relation { args, .. } => args.iter().collect(),
+ Node::Coreference(refs) => refs.iter().collect(),
+ _ => Vec::new(),
+ };
+ for r in names {
+ if !r.bound {
+ assert!(
+ !in_scope.contains(&r.name),
+ "the constant {:?} stands in the scope of a defining label of the same \
+ name, which B.2.10 forbids",
+ r.name
+ );
+ }
+ }
+ if let Node::Negation(b) | Node::Context(b) = n {
+ check(b, in_scope, &format!("{path}/{i}"));
+ }
+ }
+ for n in &added {
+ in_scope.remove(n);
+ }
+ }
+
+ let mut scope = BTreeSet::new();
+ check(&body, &mut scope, "text");
+
+ // And the text's own graph directly contains no defining label at all, so
+ // no sentence can bind a name another sentence reads.
+ for n in &body {
+ assert!(
+ !matches!(n, Node::Existential { .. }),
+ "a defining label directly in the text's CG would scope over every later sentence"
+ );
+ }
+}
+
+/// Every comment the emitter writes can be written: B.2.4 forbids `*/` inside
+/// one and gives no escape.
+#[test]
+fn no_emitted_comment_can_close_itself_early() {
+ let problem = FolProblem::build(&corpus(), Some(&OwlAxiom::SubClass(c("A"), c("B"))))
+ .expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("writable");
+ let (_, body) = parse_text(&text);
+ let mut seen = 0usize;
+ walk(&body, &mut |n| {
+ if let Node::Comment(s) = n {
+ seen += 1;
+ assert!(cgif::comment_is_writable(s), "a comment closes itself early: {s}");
+ }
+ });
+ assert!(seen > 1, "the header and at least one label were checked");
+}
+
+// ── 3. The round trip ───────────────────────────────────────────────────────
+
+/// Read a CG back into a `Form`.
+///
+/// B.2.6 gives the rule this inverts: "Let E be the subset of C of existential
+/// concepts; and let X be the set of all concepts, conceptual relations, and
+/// negations of g except for those in E. […] If E is non-empty, then cg2cl(g)
+/// is a quantified sentence of type existential with the set of names
+/// consisting of the CGname of the defining coreference label of every e in E
+/// and with the body B." So an existential concept scopes over the whole graph
+/// it sits in, and the rest of the graph is a conjunction.
+fn read_cg(nodes: &[Node]) -> Form {
+ let mut binders: Vec<u32> = Vec::new();
+ let mut parts: Vec<Form> = Vec::new();
+ for n in nodes {
+ match n {
+ Node::Comment(_) => {}
+ Node::Existential { name, .. } => binders.push(var_index(name)),
+ other => parts.push(read_node(other)),
+ }
+ }
+ let body = conj(parts);
+ binders.into_iter().rev().fold(body, |acc, n| Form::Ex(n, Box::new(acc)))
+}
+
+fn conj(mut parts: Vec<Form>) -> Form {
+ match parts.len() {
+ 0 => Form::Tru,
+ 1 => parts.pop().expect("length checked"),
+ _ => {
+ let head = parts.remove(0);
+ Form::And(Box::new(head), Box::new(conj(parts)))
+ }
+ }
+}
+
+fn var_index(n: &Name) -> u32 {
+ let Name::Bare(s) = n else { panic!("a defining label is an identifier, found {n:?}") };
+ s.strip_prefix('X')
+ .and_then(|d| d.parse().ok())
+ .unwrap_or_else(|| panic!("a variable is Xn, found {s}"))
+}
+
+fn read_ref(r: &Ref) -> Term {
+ match (&r.name, r.bound) {
+ (Name::Bare(s), true) => Term::Var(
+ s.strip_prefix('X')
+ .and_then(|d| d.parse().ok())
+ .unwrap_or_else(|| panic!("a bound label is ?Xn, found {s}")),
+ ),
+ (Name::Enclosed(s), false) => Term::Const(
+ s.strip_prefix("i:")
+ .unwrap_or_else(|| panic!("a constant carries the i: prefix, found {s}"))
+ .to_string(),
+ ),
+ other => panic!("not a term in this fragment: {other:?}"),
+ }
+}
+
+fn read_p1(n: &Name) -> P1 {
+ match n {
+ Name::Bare(s) if s == "thing" => P1::Thing,
+ Name::Bare(s) if s == "lit" => P1::Lit,
+ Name::Enclosed(s) => {
+ if let Some(r) = s.strip_prefix("c:") {
+ P1::Cls(r.to_string())
+ } else if let Some(r) = s.strip_prefix("d:") {
+ P1::Dt(r.to_string())
+ } else {
+ panic!("a unary predicate carries no kind prefix: {s}")
+ }
+ }
+ other => panic!("not a unary predicate: {other:?}"),
+ }
+}
+
+fn read_p2(n: &Name) -> P2 {
+ let Name::Enclosed(s) = n else { panic!("not a binary predicate: {n:?}") };
+ if let Some(r) = s.strip_prefix("op:") {
+ P2::Op(r.to_string())
+ } else if let Some(r) = s.strip_prefix("dp:") {
+ P2::Dp(r.to_string())
+ } else {
+ panic!("a binary predicate carries no kind prefix: {s}")
+ }
+}
+
+fn read_node(n: &Node) -> Form {
+ match n {
+ Node::Relation { name, args, .. } => match args.len() {
+ 1 => Form::App1(read_p1(name), read_ref(&args[0])),
+ 2 => Form::App2(read_p2(name), read_ref(&args[0]), read_ref(&args[1])),
+ k => panic!("no first-order atom of arity {k}"),
+ },
+ // B.2.5: a coreference concept is a conjunction of equations. With two
+ // references that conjunction is one equation. The standard lets the
+ // first term be "any reference in R", so reading the first written as
+ // the first term is one of the permitted readings and equality is
+ // symmetric either way.
+ Node::Coreference(refs) => {
+ assert_eq!(refs.len(), 2, "the emitter writes exactly two references");
+ Form::Eq(read_ref(&refs[0]), read_ref(&refs[1]))
+ }
+ Node::Context(body) => read_cg(body),
+ Node::Negation(body) => {
+ let real: Vec<&Node> = body.iter().filter(|x| !matches!(x, Node::Comment(_))).collect();
+ // `~[ ]` is falsity. B.2.8: "The negation of the blank CG, written
+ // `~[ ]`, is always false".
+ if real.is_empty() {
+ return Form::Fls;
+ }
+ // `~[ [*Xn] ~[ … ] ]` is a universal. B.3.7: the translation of a
+ // CG containing universal concepts "shall be a nest of two
+ // negations. The outer context shall contain the translations of
+ // all the universal concepts, and the inner context shall contain
+ // the translations of all other nodes". Nothing else can produce a
+ // BARE existential concept directly inside a negation, because an
+ // `Ex` is always emitted inside a context of its own.
+ if real.len() == 2
+ && let (Node::Existential { name, .. }, Node::Negation(inner)) =
+ (real[0], real[1])
+ {
+ return Form::All(var_index(name), Box::new(read_cg(inner)));
+ }
+ Form::Neg(Box::new(read_cg(body)))
+ }
+ Node::Comment(_)
+ | Node::Actor
+ | Node::ExtendedConcept(_)
+ | Node::Existential { .. } => panic!("not a sentence node: {n:?}"),
+ }
+}
+
+/// The two rewrites core CGIF forces, applied to a `Form` so both sides of a
+/// round trip are compared in the same shape.
+///
+/// **Implication and disjunction have no operator in core CGIF.** B.3.5 defines
+/// both by rewriting them away: `ifThen` becomes `"~[", CG(ante), "~[",
+/// CG(conse), "]", "]"` and `eitherOr` becomes a negation holding one `~[…]`
+/// per disjunct. Those are the standard's own definitions of the connectives,
+/// not this project's encoding of them, so a round trip that recovered `Imp`
+/// and `Or` would be recovering something the syntax does not carry.
+///
+/// **Conjunction is a SET of nodes, not a binary connective.** B.2.6: "A
+/// conceptual graph consists of an unordered set of concepts, conceptual
+/// relations, negations, and comments." So the associativity of an `And` tree
+/// cannot survive either, and both sides are right-associated.
+fn primitive(f: &Form) -> Form {
+ let mut parts = Vec::new();
+ spread(f, &mut parts);
+ conj(parts)
+}
+
+/// The nodes a formula becomes in the CG it is written into.
+///
+/// The two jobs are one job, which is why they are one function. A conjunction
+/// contributes its conjuncts as SEPARATE NODES, so nesting on either side
+/// vanishes; and an implication's antecedent is written into the SAME graph as
+/// the negation that carries its consequent, so the antecedent's conjuncts sit
+/// beside that negation rather than under an `And` with it. Expanding the
+/// implication first and flattening afterwards would produce a different tree
+/// from the one the file can be read back as, which is how this function was
+/// got wrong the first time.
+fn spread(f: &Form, out: &mut Vec<Form>) {
+ match f {
+ Form::And(g, h) => {
+ spread(g, out);
+ spread(h, out);
+ }
+ // `~[ CG(g) ~[ CG(h) ]]`, B.3.5's own `ifThen` rewrite. `g`'s nodes and
+ // the negation of `h` are siblings in one graph.
+ Form::Imp(g, h) => {
+ let mut inner = Vec::new();
+ spread(g, &mut inner);
+ inner.push(Form::Neg(Box::new(primitive(h))));
+ out.push(Form::Neg(Box::new(conj(inner))));
+ }
+ // `~[ ~[CG(g)] ~[CG(h)] ]`, B.3.5's `eitherOr`. Each disjunct is under
+ // a negation of its own, so neither spreads.
+ Form::Or(g, h) => out.push(Form::Neg(Box::new(conj(vec![
+ Form::Neg(Box::new(primitive(g))),
+ Form::Neg(Box::new(primitive(h))),
+ ])))),
+ Form::Neg(g) => out.push(Form::Neg(Box::new(primitive(g)))),
+ Form::All(n, g) => out.push(Form::All(*n, Box::new(primitive(g)))),
+ Form::Ex(n, g) => out.push(Form::Ex(*n, Box::new(primitive(g)))),
+ other => out.push(other.clone()),
+ }
+}
+
+/// **Gate.** Every sentence reads back to the formula it was built from.
+///
+/// Not a golden file. The reader above is written from Annex B's translation
+/// clauses rather than from the emitter, so a drift in either is caught, which
+/// is the same argument `clif_round_trips_to_the_same_forms` makes for CLIF.
+#[test]
+fn cgif_round_trips_to_the_same_forms() {
+ let problem = FolProblem::build(&corpus(), None).expect("translates");
+ let formulas = problem.formulas();
+ assert!(formulas.len() >= 36, "the corpus should be substantial");
+ for (name, _role, f) in &formulas {
+ let mut p = Parser { toks: lex(&cgif::sentence(f)), i: 0 };
+ let node = p.node();
+ assert_eq!(p.i, p.toks.len(), "trailing tokens in the sentence for {name}");
+ assert_eq!(
+ &read_node(&node),
+ &primitive(f),
+ "CGIF round trip differs for {name}: {}",
+ cgif::sentence(f)
+ );
+ }
+}
+
+/// Hand-pinned CGIF for the worked cases the CLIF test pins by hand too. The
+/// round trip proves the writer and the reader agree; these pin what they agree
+/// ON, against the productions rather than against a recorded run.
+#[test]
+fn cgif_worked_cases_are_pinned_by_hand() {
+ // `A subClassOf exists r . B`. `allObj 0 (imp (cls A) (exObj 2 …))`.
+ // `allObj n f` is `~[[*Xn] ~[ f ]]` and `imp g h` is `~[ g ~[ h ]]`.
+ let f = Translation::axiom(&OwlAxiom::SubClass(
+ c("A"),
+ Concept::Some_(iri("r"), Box::new(c("B"))),
+ ))
+ .unwrap();
+ assert_eq!(
+ cgif::graph(&f),
+ "~[[*X0] ~[~[(thing ?X0) ~[~[(\"c:http://e/A\" ?X0) \
+ ~[[[*X2] (thing ?X2) (\"op:http://e/r\" ?X0 ?X2) (\"c:http://e/B\" ?X2)]]]]]]]"
+ );
+
+ let b = Translation::background();
+ // `forall X0 . not (thing X0 and lit X0)`.
+ assert_eq!(cgif::graph(&b[0]), "~[[*X0] ~[~[(thing ?X0) (lit ?X0)]]]");
+ // `exists X0 . thing X0`. B.2.6: the existential concept scopes over its
+ // whole graph, so the body needs no further bracket.
+ assert_eq!(cgif::graph(&b[1]), "[[*X0] (thing ?X0)]");
+
+ // B.2.5 and B.2.8: `[]` is truth, `~[]` is falsity. CGIF has no truth
+ // constants any more than CLIF does.
+ assert_eq!(cgif::graph(&Form::Tru), "[]");
+ assert_eq!(cgif::graph(&Form::Fls), "~[]");
+
+ // B.2.5: an equation is a coreference concept. CGIF has no `=`.
+ let same = Translation::axiom(&OwlAxiom::SameAs(iri("a"), iri("b"))).unwrap();
+ assert_eq!(cgif::graph(&same), "[: \"i:http://e/a\" \"i:http://e/b\"]");
+}
+
+// ── 4. One translation, two Common Logic dialects ───────────────────────────
+
+/// **Gate.** The CGIF file and the CLIF file carry the same sentences, in the
+/// same order, under the same labels.
+///
+/// This is the claim the whole design rests on: five serialisers, one
+/// translation, never five translations. Each formula is checked three ways —
+/// the CLIF file contains its CLIF rendering, the CGIF file contains its CGIF
+/// rendering, and the CGIF rendering reads back to the formula — so a writer
+/// that dropped, added, reordered or altered one sentence breaks it.
+#[test]
+fn cgif_and_clif_carry_the_same_sentences_from_the_same_translation() {
+ let problem = FolProblem::build(&corpus(), Some(&OwlAxiom::SubClass(c("A"), c("B"))))
+ .expect("translates");
+ let clif_text = problem.to_clif(ClifDialect::Iso, ClifComments::Standalone, TEXT_NAME);
+ let cgif_text = problem.to_cgif(TEXT_NAME).expect("writable");
+
+ let formulas = problem.formulas();
+ for (label, role, f) in &formulas {
+ assert!(
+ clif_text.contains(&clif::form(f)),
+ "the CLIF file does not carry {label}"
+ );
+ assert!(
+ cgif_text.contains(&cgif::sentence(f)),
+ "the CGIF file does not carry {label}"
+ );
+ assert!(
+ clif_text.contains(&format!("(cl:comment '{label} ({role})')")),
+ "the CLIF label for {label} is missing"
+ );
+ assert!(
+ cgif_text.contains(&format!("/*{label} ({role})*/")),
+ "the CGIF label for {label} is missing"
+ );
+ }
+
+ // The label SEQUENCES, read out of the two files independently, are equal.
+ // A count alone would pass on a reordering.
+ let clif_labels: Vec<String> = clif_text
+ .match_indices("(cl:comment '")
+ .map(|(i, m)| {
+ let rest = &clif_text[i + m.len()..];
+ rest[..rest.find('\'').expect("a closed comment string")].to_string()
+ })
+ .collect();
+ let (_, cgif_body) = parse_text(&cgif_text);
+ let cgif_labels: Vec<String> = cgif_body
+ .iter()
+ .filter_map(|n| match n {
+ Node::Comment(s) => Some(s.clone()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(clif_labels.len(), formulas.len() + 1, "one per formula plus the header");
+ assert_eq!(cgif_labels.len(), formulas.len() + 1);
+ // Both files put the header first; after it the labels must agree exactly.
+ assert_eq!(
+ clif_labels[1..],
+ cgif_labels[1..],
+ "the two Common Logic dialects disagree about which sentences the file has, or about \
+ their order"
+ );
+
+ // And the CGIF sentences, read back, are the formulas themselves.
+ let sentences: Vec<&Node> =
+ cgif_body.iter().filter(|n| !matches!(n, Node::Comment(_))).collect();
+ assert_eq!(sentences.len(), formulas.len());
+ for (node, (label, _, f)) in sentences.iter().zip(formulas.iter()) {
+ assert_eq!(&read_node(node), &primitive(f), "sentence {label} differs");
+ }
+}
+
+/// The emitted CGIF states its own restriction, in the file. A limit stated
+/// only in a README gets read without one.
+#[test]
+fn the_cgif_header_states_the_restriction() {
+ let problem = FolProblem::build(&corpus(), None).expect("translates");
+ let text = problem.to_cgif(TEXT_NAME).expect("writable");
+ for wanted in [
+ "CORE CGIF, not extended CGIF",
+ "THE COMPACT SUB-DIALECT",
+ "clause 6.5",
+ "PINNED BY TESTS AND IS NOT ITSELF PROVED",
+ "[Proposition:",
+ ] {
+ assert!(text.contains(wanted), "the header does not say {wanted:?}");
+ }
+ assert!(
+ !text.contains("ORACLE OPINION"),
+ "a file with no conjecture says nothing about a prover's verdict"
+ );
+ let with_goal = FolProblem::build(&[], Some(&OwlAxiom::SubClass(c("A"), c("B"))))
+ .unwrap()
+ .to_cgif(TEXT_NAME)
+ .expect("writable");
+ assert!(with_goal.contains("ORACLE OPINION, not a certificate"));
+}
+
+/// `cgif` is a syntax the parser knows, it takes no dialect or encoding flag,
+/// and the refusal message for an unknown syntax names it.
+#[test]
+fn cgif_is_a_syntax_and_takes_no_flags() {
+ let s = Syntax::parse("cgif", None, None, None).expect("cgif is a syntax");
+ assert_eq!(s.name(), "cgif");
+ assert_eq!(s.extension(), "cgif");
+ assert_eq!(s.dialect(), None, "CGIF has one spelling of its operators");
+ assert_eq!(s.comments(), None, "B.2.4 gives comments a lexical syntax of their own");
+ assert_eq!(s.encoding(), None);
+ assert_eq!(Syntax::parse("cg", None, None, None).expect("an alias").name(), "cgif");
+
+ let e = Syntax::parse("sexpr", None, None, None).expect_err("sexpr is not a syntax");
+ assert!(
+ ["tptp", "clif", "cgif", "smtlib", "ladr"].iter().all(|n| e.to_string().contains(n)),
+ "the message must name every alternative, cgif included: {e}"
+ );
+}
+
+// ── 5. Nothing is dropped, and nothing is rewritten ─────────────────────────
+
+/// **Gate.** A construct outside the fragment is NAMED AND COUNTED in a CGIF
+/// run, exactly as in a TPTP or CLIF one.
+///
+/// The restriction discipline is a property of the translation and not of a
+/// serialiser, so adding a fourth output must not create a fourth place where
+/// the report could be silent. `owl:hasKey` is outside `OwlLean/Syntax.lean`;
+/// the CGIF report must say so, with the count and the reason, and must set
+/// `exports_a_weaker_axiom_set`.
+#[test]
+fn a_cgif_run_names_and_counts_what_it_cannot_export() {
+ let ttl = r#"
+@prefix : <http://e/> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+:A a owl:Class ; rdfs:subClassOf :B .
+:B a owl:Class .
+:k a owl:ObjectProperty .
+:A owl:hasKey ( :k ) .
+"#;
+ let graph = std::sync::Arc::new(open_ontologies::graph::GraphStore::new());
+ graph.load_turtle(ttl, None).expect("turtle parses");
+ let dir = tempfile::tempdir().expect("tempdir");
+ let report = open_ontologies::tptp::export(&graph, dir.path(), Syntax::Cgif, None, 0)
+ .expect("export");
+ let v: serde_json::Value = serde_json::from_str(&report).expect("json");
+
+ assert_eq!(v["syntax"], "cgif");
+ assert_eq!(v["cgif_dialect"], "core");
+ assert!(v["cgif_sub_dialect"].as_str().unwrap_or("").contains("compact"));
+ assert_eq!(
+ v["common_logic_dialects_emitted"],
+ serde_json::json!(["clif", "cgif"]),
+ "two of ISO/IEC 24707's three dialects"
+ );
+ assert!(
+ v["common_logic_dialects_not_emitted"][0]
+ .as_str()
+ .unwrap_or("")
+ .contains("xcl"),
+ "the third is named as absent rather than left to be assumed present"
+ );
+
+ assert_eq!(
+ v["exports_a_weaker_axiom_set"], true,
+ "owl:hasKey is outside the fragment, so the export is weaker than the ontology"
+ );
+ let named: Vec<String> = v["constructs_not_exported"]
+ .as_array()
+ .expect("a list")
+ .iter()
+ .map(|d| d["construct"].as_str().unwrap_or("").to_string())
+ .collect();
+ assert!(named.iter().any(|n| n.contains("hasKey")), "got {named:?}");
+ let entry = &v["constructs_not_exported"][0];
+ assert!(entry["occurrences"].as_u64().unwrap_or(0) >= 1, "counted, not only named");
+ assert!(!entry["why"].as_str().unwrap_or("").is_empty(), "with the reason");
+
+ // The file itself lands, parses, and carries the subsumption that IS in the
+ // fragment. A report that named the drop while writing nothing would be
+ // worse than either.
+ let text = std::fs::read_to_string(dir.path().join("ontology.cgif")).expect("the file");
+ let (_, body) = parse_text(&text);
+ assert!(body.iter().any(|n| matches!(n, Node::Context(_))), "sentences landed");
+ assert!(text.contains("owl_1_subClassOf"));
+}
+
+/// **Gate.** A comment that would close itself early is REFUSED, with the
+/// reason, and no file is written.
+///
+/// B.2.4 forbids `*/` inside a comment and defines no escape, so there are
+/// three possible behaviours and two of them are wrong: rewriting the text
+/// emits a different comment, and dropping it loses the label that says which
+/// axiom a sentence is. This is the same rule `UnwritableSymbol` follows for
+/// SMT-LIB and LADR.
+///
+/// The refusal is reachable rather than theoretical: the CGIF header describes
+/// the comment syntax, and an earlier draft of it named the delimiters
+/// literally and tripped this on every run.
+#[test]
+fn a_comment_that_could_close_itself_early_is_refused() {
+ assert!(cgif::comment("background_1 (axiom)").is_ok());
+ let e = cgif::comment("a comment that ends the comment */ and then some")
+ .expect_err("B.2.4 forbids it");
+ assert!(e.text.contains("*/"));
+ assert!(
+ e.why.contains("B.2.4") && e.why.contains("no escape"),
+ "the refusal must name the clause and say why there is no third option: {}",
+ e.why
+ );
+ assert!(
+ e.to_string().contains("cannot be written in CGIF"),
+ "got {e}"
+ );
+ assert!(!cgif::comment_is_writable("*/"));
+ assert!(cgif::comment_is_writable("/* nested opener is fine"));
+}
diff --git a/tests/readme_claims_test.rs b/tests/readme_claims_test.rs
index 0b3f2fe8..ba0a51a1 100644
--- a/tests/readme_claims_test.rs
+++ b/tests/readme_claims_test.rs
@@ -83,8 +83,20 @@ fn no_stale_tool_count_survives_anywhere() {
// The shapes a total is written in here. Any number in one of them that is not the
// measured count is a leftover from a partial edit.
- let shapes: [(&str, &str); 4] =
- [("**", " tools**"), ("advertises all ", " tools."), ("", " tools organized by function"), ("ToolGroups[\"", " Tools\"]")];
+ //
+ // `All N tools are advertised` is the fifth shape and it was added on 15 September 2026,
+ // after the gate missed exactly the drift it exists to catch: the instructions string in
+ // `src/server.rs` said "MCP server with 114 tools" and, one sentence later, "All 112 tools
+ // are advertised in a default build". The first copy was covered by `total_claims` and the
+ // second by no shape at all, so the file disagreed with ITSELF while the suite stayed green.
+ // A gate that covers four of five places makes the fifth harder to notice.
+ let shapes: [(&str, &str); 5] = [
+ ("**", " tools**"),
+ ("advertises all ", " tools."),
+ ("", " tools organized by function"),
+ ("ToolGroups[\"", " Tools\"]"),
+ ("All ", " tools are advertised"),
+ ];
let mut stale = Vec::new();
for (prefix, suffix) in shapes {