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.

Three things a crosswalk, a module set and a number can now be asked (#252)

Fabio Rovaic23f910c521c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f1b90360..6b3ad5ba 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -502,6 +502,17 @@ jobs:
# batch executor and the single-command path, which are different code
# that have already differed once.
run: OO_REQUIRE_FIXTURES=1 cargo test --test cli_verified_shacl_test -- --nocapture
+ - name: A numeric claim, checked in Lean
+ # The integer path earns MatCert.mul_of_check, and the two cheaper
+ # paths must NOT. Strict, because a skip here would let the three
+ # verdict words drift together unnoticed, and the whole design is that
+ # they stay apart.
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test matcert_numeric_test -- --nocapture
+ - name: The certified-claims figure says what a fresh run says
+ # Strict for the reason the figure exists: it is generated, so it can
+ # go stale while the generator stays right. A skip would let the
+ # drawing and the code disagree in a release.
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test certified_claims_asset_test -- --nocapture
- name: Check the description-logic refutation certificates
# The other half of the line above. That one certifies that an ontology
# HAS a model by exhibiting one; this certifies that it has NONE by
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 525f1e5f..fe6f734a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,62 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
+## [2.0.0] - 2026-09-21
+
+A major number because the engine now answers three questions it could not
+answer before, and because every checker it ships can say which binary it is.
+
+### Added
+
+- **A crosswalk's match type is checked, not asserted.** `crosswalk-certify`
+ reasons over each side alone, translates the entailed ancestors through the
+ mapping itself, and reports the tightest SKOS predicate the evidence supports.
+ An `exactMatch` the entailments do not support comes back downgraded with the
+ reason. Output is valid SSSOM with extra columns, so existing tooling reads it
+ unchanged.
+- **What cannot map is named.** A source term with no row, and an ancestor with
+ no image in the target, both travel in the same file. That second case is the
+ one that disappears from every crosswalk export today.
+- **A contradiction probe.** The translated claims are carried into the target
+ and reasoned over. A clash means the target denies what the mapping carried
+ in, which is a disagreement and not a granularity gap.
+- **Modules that reason alone, with k-of-n promotion.** Each module keeps its
+ own store, so two contexts may disagree without either becoming inconsistent.
+ A fact earns "true everywhere" when k of n modules entail it independently.
+ The report states that agreement is a count and not a proof.
+- **A numeric certificate.** `oo-matcert` recomputes a matrix product from the
+ definition and discharges `MatCert.mul_of_check`. Integers only, in core Lean,
+ under the no-dependency rule. Freivalds is offered as an O(n²) opinion with
+ its bound printed, and the floating-point path reports a tolerance and names
+ no theorem, because a proof over the reals says nothing about IEEE-754.
+- **Every checker names the binary that is running** (#204). `--version` and a
+ `checker` block carrying the name, the Lean toolchain and the SHA-256 of the
+ file the process is running from, matchable against the release `SHASUMS.txt`.
+- **The certified token says which artefact was accepted** (#164). It carries
+ the digest of the inputs the accepting run was handed, and is no longer `Copy`.
+- **The verified SHACL evaluator is reachable from the command line** (#203).
+- **The SHACL compiler names what it ignores** (#206), instead of discarding
+ `sh:severity` and `sh:message` in silence.
+- **Ten clash fixtures with near-miss twins** (#160), so every detector is
+ exercised by a graph written to trip it and a control that must stay clean.
+
+### Changed
+
+- The release refuses a tag that does not carry the version it claims, and
+ refuses to publish a binary whose `status` disagrees with its tag. Eleven
+ historical tags did not, including v1.6.0, which reports 1.5.0.
+- The try page uses the palette of the figures beside it.
+- The front-page graph uses the width of its panel, and no two labels overlap.
+
+### Fixed
+
+- `Cargo.toml` said 1.5.0 under the v1.6.0 tag (#248).
+- Two tests raced over shared files; one wrote a script while a sibling forked,
+ which Linux answers with `ETXTBSY`.
+- The HQDM panel heading overlapped the right column in browsers whose fonts
+ render wider than Chrome's.
+
+
## [1.6.0] - 2026-09-21
### Added
diff --git a/Cargo.lock b/Cargo.lock
index df2c566c..949bdaa0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2811,7 +2811,7 @@ dependencies = [
[[package]]
name = "open-ontologies"
-version = "1.6.0"
+version = "2.0.0"
dependencies = [
"anyhow",
"arrow 54.3.1",
diff --git a/Cargo.toml b/Cargo.toml
index 7b702b97..94c0f154 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "open-ontologies"
-version = "1.6.0"
+version = "2.0.0"
edition = "2024"
description = "AI-native ontology engine: an MCP server and CLI for building, validating, querying and reasoning over RDF and OWL, with a native SHIQ tableaux reasoner, SHACL validation and SPARQL. Single binary, no JVM."
license = "MIT"
diff --git a/README.md b/README.md
index dfa6f8b9..29694a1b 100644
--- a/README.md
+++ b/README.md
@@ -134,9 +134,6 @@ checker again. The test fails if the figure and the checker do not agree.
## With a proof, and without a proof
-Here is the same question. An ordinary reasoner answers first, and then this
-engine answers.
-
| | An ordinary reasoner | Open Ontologies |
| --- | --- | --- |
| The answer | `Northwind needs enhanced due diligence` | the same answer |
@@ -148,8 +145,7 @@ engine answers.
| What an auditor receives | a screenshot | a file that the auditor can check again |
| Guarantee on an unsatisfiability answer | asserted | **none, and the tool says so** |
-The last row is the purpose of this project. If the tool measures a property, the
-tool says *measured*. If a prover gives an opinion, that opinion never takes the
+If the tool measures a property, the tool says *measured*. If a prover gives an opinion, that opinion never takes the
vocabulary of the checker. Read [what the tool proves, and what it does not
prove](#what-the-tool-proves).
@@ -170,8 +166,7 @@ prove](#what-the-tool-proves).
## Run the checker yourself
-The repository holds the three files. The output below is the output of the
-checker. It shows only the important fields.
+The repository holds the three files. The output shows only the important fields.
```bash
$ cd lean && lake build # builds the checkers, core Lean 4, no Mathlib
@@ -205,7 +200,7 @@ flowchart LR
## Run the tool on your own ontology
The repository ships those fixtures. Now do the same steps with a file that you
-write. The [Install](#install) section is below. These steps take one minute.
+write. These steps take one minute.
```bash
mkdir /tmp/oo-demo && cd /tmp/oo-demo
@@ -325,6 +320,24 @@ environment variable. Thus a demonstration without that flag writes into
The discipline behind this work has a cost, and the discipline has earned that
cost: [what the rules are, and what each rule caught](docs/decisions/).
+## Three claims that used to travel on trust
+
+![Three claims, each one checked against a real run](docs/assets/certified-claims.svg)
+
+A crosswalk states a match type. Nothing checked that statement. The engine now reasons over each side alone. It compares what each side entails, through the mapping itself. It then reports the tightest match type the evidence supports.
+
+An `exactMatch` that the entailments do not support comes back downgraded. The report gives the reason. It also names every term the crosswalk does not carry. That second list is the one that disappears from most crosswalk files. The output is valid SSSOM, so your tools read it today.
+
+A second question is sharper than a downgrade. The engine carries the translated claims into the target and reasons again. A clash means the target denies what the mapping carried in. That is a disagreement, and a person must settle it.
+
+Contexts can disagree. Birds fly. Penguins are birds, and penguins do not fly. One graph that holds both is inconsistent, and this engine finds the clash. Each module reasons alone instead. A fact earns "true everywhere" when k modules of n entail it.
+
+A number can now carry a certificate. `oo-matcert` recomputes a matrix product from the definition. It prints `MatCert.mul_of_check` when it accepts. Integers only, and that is the condition for the sentence to hold. Freivalds costs less and gives a probability, so it stays an opinion with its bound printed. Floating point reports a tolerance, because a proof over the real numbers says nothing about IEEE-754.
+
+```bash
+open-ontologies batch plan.json # crosswalk-certify, modules --threshold k, matcert
+```
+
## What the tool proves
| You ask | You get back | Checked against |
@@ -337,8 +350,7 @@ cost: [what the rules are, and what each rule caught](docs/decisions/).
| Does this data fit the shapes | A validation report | `Shacl.validate_spec` |
| Does a retrieval slice still support the answer | Preservation for each claim | `OOCert.certificate_sound` |
-Read that last row two times. A retrieval slice with 99% coverage can lose the one
-triple that an answer needs. A slice with 60% coverage can keep each claim that
+A retrieval slice with 99% coverage can lose the one triple that an answer needs. A slice with 60% coverage can keep each claim that
matters. Coverage is a proxy, and the proxy rises as the slice grows.
Thus a retriever that you tune on coverage learns to fetch more, and not to fetch
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 6fda0ccb..a646ad0d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -123,8 +123,6 @@ new consequences 901 rule table owl-rl, in 0.04s
## 有证明,和没有证明
-下面是同一个问题。先由一个普通推理机回答,然后由本引擎回答。
-
| | 普通推理机 | Open Ontologies |
| --- | --- | --- |
| 答案 | `Northwind needs enhanced due diligence` | 同样的答案 |
@@ -136,7 +134,7 @@ new consequences 901 rule table owl-rl, in 0.04s
| 审计人员收到什么 | 一张截图 | 一个他们可以再次核验的文件 |
| 对“不可满足”这一答案的保证 | 断言 | **没有保证,而且工具明说这一点** |
-最后一行就是本项目的目的。如果工具测量了一个性质,工具就说*测量*。如果一个证明器给出的是
+如果工具测量了一个性质,工具就说*测量*。如果一个证明器给出的是
意见,那个意见绝不会借用检查器的词汇。请阅读[本工具证明了什么,没有证明什么](#本工具证明了什么)。
## 本工具能做什么
@@ -156,7 +154,7 @@ new consequences 901 rule table owl-rl, in 0.04s
## 自己运行检查器
-本仓库中有这三个文件。下面的输出就是检查器的输出,只保留了重要的字段。
+本仓库中有这三个文件。输出只保留了重要的字段。
```bash
$ cd lean && lake build # builds the checkers, core Lean 4, no Mathlib
@@ -187,7 +185,7 @@ flowchart LR
## 在你自己的本体上运行本工具
-本仓库随附那些夹具。现在用一个你自己写的文件做同样的步骤。[安装](#安装)一节在下面。
+本仓库随附那些夹具。现在用一个你自己写的文件做同样的步骤。
这些步骤需要一分钟。
```bash
@@ -292,6 +290,24 @@ rdfs9 <ex:myCup> <rdf:type> <ex:Drink> <ex:myCup> <rdf:type> <e
这套纪律是有代价的,而这套纪律已经挣回了这个代价:
[规则是什么,以及每条规则抓到了什么](docs/decisions/)。
+## 三个曾经只能靠信任的声明
+
+![三个声明,每一个都对照真实运行核验过](docs/assets/certified-claims.zh-CN.svg)
+
+对照表会写下一个匹配类型。以前没有任何东西核验它。现在引擎分别在两边各自推理。它通过对照表本身,比较两边各自蕴涵了什么。然后它报告证据能支持的最紧的匹配类型。
+
+蕴涵不支持的 `exactMatch` 会被降级返回。报告给出理由。它还列出对照表没有收录的每一个词。后面这份清单,正是大多数对照表文件里会消失的那一份。输出是合法的 SSSOM,你现有的工具今天就能读。
+
+还有一个比降级更尖锐的问题。引擎把翻译后的声明带进目标方,再推理一次。出现冲突,说明目标方否定了对照表带进去的东西。那是分歧,需要人来裁决。
+
+语境之间可以互相矛盾。鸟会飞。企鹅是鸟,而企鹅不会飞。一张图同时装下两者就不一致,本引擎会找出这个冲突。改成每个模块单独推理。一条事实要在 n 个模块中有 k 个蕴涵它,才算"处处为真"。
+
+数字现在也能带证书。`oo-matcert` 按定义重算矩阵乘积。接受时它打印 `MatCert.mul_of_check`。只接受整数,这正是那句话成立的条件。Freivalds 代价更低但给的是概率,所以它只是意见,并附上自己的界。浮点只报告容差,因为在实数上的证明对 IEEE-754 什么也没说。
+
+```bash
+open-ontologies batch plan.json # crosswalk-certify, modules --threshold k, matcert
+```
+
## 本工具证明了什么
| 你问什么 | 你得到什么 | 对照什么检查 |
@@ -304,7 +320,7 @@ rdfs9 <ex:myCup> <rdf:type> <ex:Drink> <ex:myCup> <rdf:type> <e
| 这些数据符合这些形状吗 | 一份校验报告 | `Shacl.validate_spec` |
| 一个检索切片是否仍然支持该答案 | 针对每条主张的保持 | `OOCert.certificate_sound` |
-最后一行请读两遍。一个覆盖率 99% 的检索切片,可能丢掉某个答案所需要的那条三元组。一个覆盖率
+一个覆盖率 99% 的检索切片,可能丢掉某个答案所需要的那条三元组。一个覆盖率
60% 的切片,可能保住每一条重要的主张。覆盖率是一个代理指标,而这个代理指标随切片变大而上升。
因此,你用覆盖率去调优的检索器,学会的是取回更多,而不是取回正确的三元组。蕴涵保持才是你想要
diff --git a/docs/assets/certified-claims.py b/docs/assets/certified-claims.py
new file mode 100644
index 00000000..ba473e83
--- /dev/null
+++ b/docs/assets/certified-claims.py
@@ -0,0 +1,283 @@
+#!/usr/bin/env python3
+"""Three claims this engine could not check before, and what it says now.
+
+ certified-claims.py CROSSWALK.json MODULES.json MATCERT.json OUT.svg [lang]
+
+EVERY NUMBER IN THE DRAWING COMES OUT OF THOSE FILES. Nothing is typed into
+this script: the counts, the predicates, the module names, the matrices and the
+theorem name are all read from real runs of `crosswalk-certify`, `modules` and
+`oo-matcert`. `tests/certified_claims_asset_test.rs` re-runs all three and
+fails if the drawing and a fresh run disagree, which is the only way a figure
+stays true after the code under it moves.
+
+The palette is the one `knowledge-graph.py` uses, because these drawings sit on
+the same page and a reader should not have to ask whether they came from the
+same tool.
+"""
+
+import json
+import sys
+
+W, H = 1100, 430
+BG, BG2 = "#020617", "#070d20"
+PANEL, LINE = "#0b1428", "#1e3a5f"
+INK, MUTED, DIM = "#e2e8f0", "#94a3b8", "#64748b"
+OK, BAD, WARN, NODE = "#34d399", "#fb3b53", "#fbbf24", "#7dd3fc"
+
+TEXT = {
+ "en": {
+ "title": "Three claims that used to travel on trust",
+ "sub": "each column is a real run; every number here is read from its output, never typed",
+ "c1": "A CROSSWALK'S MATCH TYPE",
+ "c1sub": "claimed, then checked against what each side entails",
+ "c2": "CONTEXTS THAT DISAGREE",
+ "c2sub": "each module reasons alone; a fact earns “true everywhere”",
+ "c3": "A NUMBER",
+ "c3sub": "recomputed from the definition, in Lean",
+ "upheld": "upheld",
+ "down": "downgraded",
+ "gap": "{n} term the crosswalk does not carry",
+ "gaps": "{n} terms the crosswalk does not carry",
+ "because": "the target has no word for ies:ResponsibleActor, so nothing stronger is defensible",
+ "entails": "entails {n}",
+ "promoted": "{n} fact entailed in {k} of {t} modules",
+ "contested": "{n} held by fewer, and named rather than dropped",
+ "merged": "one graph holding both is inconsistent; kept apart, both are fine",
+ "cost": "cost",
+ "verdictcol": "verdict",
+ "thm": "theorem",
+ "none": "none",
+ "v1": "recompute, integers",
+ "v2": "Freivalds, integers",
+ "v3": "Freivalds, doubles",
+ "v1w": "product_checked",
+ "v2w": "survived, 2⁻⁴⁰",
+ "v3w": "within tolerance",
+ "foot": "A word here is this engine's unless a checker earned it. Only the top row of "
+ "the right column names a theorem, and only because oo-matcert exited zero "
+ "having printed it.",
+ },
+ "zh": {
+ "title": "三个曾经只能靠信任的声明",
+ "sub": "每列都是一次真实运行;此处每个数字都读自其输出,不是写上去的",
+ "c1": "对照表的匹配类型",
+ "c1sub": "先声明,再对照两边的蕴涵核验",
+ "c2": "互相矛盾的语境",
+ "c2sub": "每个模块单独推理;事实要自己挡得“处处为真”",
+ "c3": "一个数字",
+ "c3sub": "在 Lean 中按定义重算",
+ "upheld": "维持",
+ "down": "降级",
+ "gap": "{n} 个词对照表未收录",
+ "gaps": "{n} 个词对照表未收录",
+ "because": "目标方没有 ies:ResponsibleActor 对应的词,因此更强的声明都立不住",
+ "entails": "蕴涵 {n}",
+ "promoted": "{n} 条事实在 {t} 个模块中的 {k} 个里被蕴涵",
+ "contested": "{n} 条只有更少模块持有,逐条列出而不丢弃",
+ "merged": "合并成一张图则不一致;分开则两边都成立",
+ "cost": "代价",
+ "verdictcol": "结论",
+ "thm": "定理",
+ "none": "无",
+ "v1": "重算,整数",
+ "v2": "Freivalds,整数",
+ "v3": "Freivalds,双精度",
+ "v1w": "product_checked",
+ "v2w": "通过,2⁻⁴⁰",
+ "v3w": "在容差内",
+ "foot": "除非核验器挡下,否则此处的词都只是本引擎的意见。只有右列首行引用了定理,且因为 oo-matcert 已将其打印并以 0 退出。",
+ },
+}
+
+
+def text_width(s, size):
+ """Conservative width. CJK is one em, Latin about half. Same function and
+ same reason as the two companion figures."""
+ w = 0.0
+ for ch in s:
+ o = ord(ch)
+ if 0x2E80 <= o <= 0x9FFF or 0xAC00 <= o <= 0xD7AF or 0xFF00 <= o <= 0xFF60:
+ w += size
+ elif o < 0x2000 and ch.islower():
+ w += size * 0.50
+ else:
+ w += size * 0.60
+ return w
+
+
+def must_fit(s, size, budget, where):
+ """Refuse to draw a line that will not fit. The companion figures learned
+ this the hard way: a heading nobody measured grew until it overlapped the
+ next column, and only a reader noticed."""
+ if text_width(s, size) > budget:
+ raise SystemExit(
+ f"{where}: {text_width(s, size):.0f} units of text at font-size {size} "
+ f"in {budget:.0f} units of space. Shorten it or widen the column.\n {s}"
+ )
+ return s
+
+
+def esc(s):
+ return (str(s).replace("&", "&amp;").replace("<", "&lt;")
+ .replace(">", "&gt;").replace('"', "&quot;"))
+
+
+def short(iri):
+ return str(iri).rsplit("/", 1)[-1].rsplit("#", 1)[-1]
+
+
+def main(cw_path, mod_path, mc_path, out_path, lang="en"):
+ T = TEXT[lang]
+ cw = json.load(open(cw_path))
+ cw = cw.get("result", cw)
+ md = json.load(open(mod_path))
+ md = md.get("result", md)
+ mc = json.load(open(mc_path))
+
+ out = []
+ A = out.append
+ A(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" '
+ f'font-family="ui-sans-serif,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">')
+ A('<defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">'
+ f'<stop offset="0" stop-color="{BG}"/><stop offset="1" stop-color="{BG2}"/>'
+ '</linearGradient></defs>')
+ A(f'<rect width="{W}" height="{H}" rx="14" fill="url(#bg)"/>')
+
+ A(f'<text x="34" y="40" font-size="17" font-weight="800" fill="{INK}">'
+ f'{esc(must_fit(T["title"], 17, W - 68, "title"))}</text>')
+ A(f'<text x="34" y="60" font-size="11.5" fill="{DIM}">'
+ f'{esc(must_fit(T["sub"], 11.5, W - 68, "subtitle"))}</text>')
+
+ COLS = 3
+ GAP = 18
+ CW_ = (W - 68 - GAP * (COLS - 1)) / COLS
+ TOP, BOT = 84, H - 66
+
+ def column(i, head, sub):
+ x = 34 + i * (CW_ + GAP)
+ A(f'<rect x="{x:.0f}" y="{TOP}" width="{CW_:.0f}" height="{BOT - TOP}" rx="11" '
+ f'fill="{PANEL}" stroke="{LINE}" stroke-width="1"/>')
+ A(f'<text x="{x + 16:.0f}" y="{TOP + 26}" font-size="11.5" font-weight="800" '
+ f'letter-spacing="0.6" fill="{NODE}">'
+ f'{esc(must_fit(head, 11.5, CW_ - 32, f"column {i} heading"))}</text>')
+ A(f'<text x="{x + 16:.0f}" y="{TOP + 42}" font-size="10" fill="{DIM}">'
+ f'{esc(must_fit(sub, 10, CW_ - 32, f"column {i} subtitle"))}</text>')
+ return x
+
+ # ── 1 · the crosswalk ───────────────────────────────────────────────
+ x = column(0, T["c1"], T["c1sub"])
+ y = TOP + 70
+ for row in cw["rows"]:
+ claimed, supported = short(row["claimed"]), short(row["supported"])
+ down = row["downgraded"]
+ col = WARN if down else OK
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="10.5" fill="{INK}">'
+ f'{esc(must_fit(short(row["subject"]), 10.5, CW_ - 150, "crosswalk subject"))}</text>')
+ A(f'<text x="{x + CW_ - 16:.0f}" y="{y}" font-size="10" text-anchor="end" fill="{col}">'
+ f'{esc(claimed)} → {esc(supported)}</text>')
+ y += 17
+ y += 4
+ A(f'<line x1="{x + 16:.0f}" y1="{y - 10}" x2="{x + CW_ - 16:.0f}" y2="{y - 10}" '
+ f'stroke="{LINE}"/>')
+ n_gap = cw["gaps"]
+ label = T["gap" if n_gap == 1 else "gaps"].format(n=n_gap)
+ A(f'<text x="{x + 16:.0f}" y="{y + 8}" font-size="10" fill="{MUTED}">'
+ f'{esc(must_fit(label, 10, CW_ - 32, "gap count"))}</text>')
+ for g in cw["unmapped"][:3]:
+ y += 15
+ A(f'<text x="{x + 24:.0f}" y="{y + 8}" font-size="10" fill="{DIM}">'
+ f'· {esc(short(g["term"]))}</text>')
+ y += 26
+ for line in wrap(T["because"], 10, CW_ - 32):
+ A(f'<text x="{x + 16:.0f}" y="{y + 8}" font-size="10" fill="{WARN}">{esc(line)}</text>')
+ y += 14
+
+ # ── 2 · the modules ─────────────────────────────────────────────────
+ x = column(1, T["c2"], T["c2sub"])
+ y = TOP + 74
+ for mod in md["modules"]:
+ A(f'<rect x="{x + 16:.0f}" y="{y - 12}" width="{CW_ - 32:.0f}" height="24" rx="7" '
+ f'fill="#060e20" stroke="{LINE}"/>')
+ A(f'<text x="{x + 26:.0f}" y="{y + 4}" font-size="10.5" fill="{INK}">'
+ f'{esc(mod["name"])}</text>')
+ A(f'<text x="{x + CW_ - 26:.0f}" y="{y + 4}" font-size="10" text-anchor="end" '
+ f'fill="{DIM}">{esc(T["entails"].format(n=mod["entails"]))}</text>')
+ y += 32
+ y += 6
+ promoted = T["promoted"].format(n=md["promoted"], k=md["threshold"], t=len(md["modules"]))
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="10.5" font-weight="700" fill="{OK}">'
+ f'{esc(must_fit(promoted, 10.5, CW_ - 32, "promoted line"))}</text>')
+ y += 17
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="10" fill="{MUTED}">'
+ f'{esc(must_fit(T["contested"].format(n=md["contested"]), 10, CW_ - 32, "contested"))}</text>')
+ y += 24
+ for line in wrap(T["merged"], 10, CW_ - 32):
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="10" fill="{BAD}">{esc(line)}</text>')
+ y += 14
+
+ # ── 3 · the number ──────────────────────────────────────────────────
+ x = column(2, T["c3"], T["c3sub"])
+ y = TOP + 74
+ dims = f'{mc["m"]}×{mc["p"]} · {mc["p"]}×{mc["n"]}'
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="10.5" fill="{MUTED}">'
+ f'A × B = C &#160;&#160;{esc(dims)}</text>')
+ y += 24
+ rows = [
+ (T["v1"], "O(n³)", T["v1w"], mc["theorem"], OK),
+ (T["v2"], "O(n²)", T["v2w"], T["none"], NODE),
+ (T["v3"], "O(n²)", T["v3w"], T["none"], WARN),
+ ]
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="9" letter-spacing="0.5" fill="{DIM}">'
+ f'{esc(T["cost"].upper())}</text>')
+ A(f'<text x="{x + 74:.0f}" y="{y}" font-size="9" letter-spacing="0.5" fill="{DIM}">'
+ f'{esc(T["verdictcol"].upper())}</text>')
+ A(f'<text x="{x + CW_ - 16:.0f}" y="{y}" font-size="9" letter-spacing="0.5" '
+ f'text-anchor="end" fill="{DIM}">{esc(T["thm"].upper())}</text>')
+ y += 8
+ A(f'<line x1="{x + 16:.0f}" y1="{y}" x2="{x + CW_ - 16:.0f}" y2="{y}" stroke="{LINE}"/>')
+ y += 18
+ for name, cost, word, thm, col in rows:
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="9.5" fill="{DIM}">{esc(cost)}</text>')
+ A(f'<text x="{x + 74:.0f}" y="{y}" font-size="10" fill="{col}">{esc(word)}</text>')
+ A(f'<text x="{x + CW_ - 16:.0f}" y="{y}" font-size="9" text-anchor="end" '
+ f'fill="{OK if thm != T["none"] else DIM}">{esc(thm)}</text>')
+ y += 16
+ A(f'<text x="{x + 16:.0f}" y="{y}" font-size="9" fill="{DIM}">{esc(name)}</text>')
+ y += 20
+
+ A(f'<line x1="34" y1="{BOT + 16}" x2="{W - 34}" y2="{BOT + 16}" stroke="{LINE}"/>')
+ fy = BOT + 34
+ for line in wrap(T["foot"], 10, W - 68):
+ A(f'<text x="34" y="{fy}" font-size="10" fill="{DIM}">{esc(line)}</text>')
+ fy += 13
+ A("</svg>")
+
+ svg = "\n".join(out)
+ import re as _re
+ stray = _re.findall(r">[^<>]*(\{[a-z_]+\})[^<>]*<", svg)
+ if stray:
+ raise SystemExit(f"the drawing carries unsubstituted placeholders: {stray}")
+ open(out_path, "w").write(svg)
+ print(f"wrote {out_path}: {cw['checked']} mappings checked, {cw['downgraded']} downgraded, "
+ f"{cw['gaps']} gap; {md['promoted']} promoted of {len(md['modules'])} modules; "
+ f"{mc['verdict']}")
+
+
+def wrap(s, size, budget):
+ """Greedy wrap on the measured width, so a long sentence never leaves the
+ panel it was written into."""
+ words, lines, cur = s.split(" "), [], ""
+ for w in words:
+ trial = (cur + " " + w).strip()
+ if text_width(trial, size) > budget and cur:
+ lines.append(cur)
+ cur = w
+ else:
+ cur = trial
+ if cur:
+ lines.append(cur)
+ return lines
+
+
+if __name__ == "__main__":
+ main(*sys.argv[1:6])
diff --git a/docs/assets/certified-claims.svg b/docs/assets/certified-claims.svg
new file mode 100644
index 00000000..6fcb3bae
--- /dev/null
+++ b/docs/assets/certified-claims.svg
@@ -0,0 +1,60 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1100 430" font-family="ui-sans-serif,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">
+<defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#020617"/><stop offset="1" stop-color="#070d20"/></linearGradient></defs>
+<rect width="1100" height="430" rx="14" fill="url(#bg)"/>
+<text x="34" y="40" font-size="17" font-weight="800" fill="#e2e8f0">Three claims that used to travel on trust</text>
+<text x="34" y="60" font-size="11.5" fill="#64748b">each column is a real run; every number here is read from its output, never typed</text>
+<rect x="34" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="50" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">A CROSSWALK'S MATCH TYPE</text>
+<text x="50" y="126" font-size="10" fill="#64748b">claimed, then checked against what each side entails</text>
+<text x="50" y="154" font-size="10.5" fill="#e2e8f0">Person</text>
+<text x="350" y="154" font-size="10" text-anchor="end" fill="#fbbf24">exactMatch → relatedMatch</text>
+<text x="50" y="171" font-size="10.5" fill="#e2e8f0">Organisation</text>
+<text x="350" y="171" font-size="10" text-anchor="end" fill="#fbbf24">exactMatch → relatedMatch</text>
+<text x="50" y="188" font-size="10.5" fill="#e2e8f0">Entity</text>
+<text x="350" y="188" font-size="10" text-anchor="end" fill="#34d399">exactMatch → exactMatch</text>
+<text x="50" y="205" font-size="10.5" fill="#e2e8f0">Event</text>
+<text x="350" y="205" font-size="10" text-anchor="end" fill="#34d399">exactMatch → exactMatch</text>
+<line x1="50" y1="216" x2="350" y2="216" stroke="#1e3a5f"/>
+<text x="50" y="234" font-size="10" fill="#94a3b8">1 term the crosswalk does not carry</text>
+<text x="58" y="249" font-size="10" fill="#64748b">· ResponsibleActor</text>
+<text x="50" y="275" font-size="10" fill="#fbbf24">the target has no word for ies:ResponsibleActor, so</text>
+<text x="50" y="289" font-size="10" fill="#fbbf24">nothing stronger is defensible</text>
+<rect x="384" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="400" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">CONTEXTS THAT DISAGREE</text>
+<text x="400" y="126" font-size="10" fill="#64748b">each module reasons alone; a fact earns “true everywhere”</text>
+<rect x="400" y="146" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="162" font-size="10.5" fill="#e2e8f0">birds</text>
+<text x="690" y="162" font-size="10" text-anchor="end" fill="#64748b">entails 3</text>
+<rect x="400" y="178" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="194" font-size="10.5" fill="#e2e8f0">penguins</text>
+<text x="690" y="194" font-size="10" text-anchor="end" fill="#64748b">entails 4</text>
+<rect x="400" y="210" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="226" font-size="10.5" fill="#e2e8f0">field_guide</text>
+<text x="690" y="226" font-size="10" text-anchor="end" fill="#64748b">entails 3</text>
+<text x="400" y="260" font-size="10.5" font-weight="700" fill="#34d399">1 fact entailed in 2 of 3 modules</text>
+<text x="400" y="277" font-size="10" fill="#94a3b8">8 held by fewer, and named rather than dropped</text>
+<text x="400" y="301" font-size="10" fill="#fb3b53">one graph holding both is inconsistent; kept apart, both</text>
+<text x="400" y="315" font-size="10" fill="#fb3b53">are fine</text>
+<rect x="734" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="750" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">A NUMBER</text>
+<text x="750" y="126" font-size="10" fill="#64748b">recomputed from the definition, in Lean</text>
+<text x="750" y="158" font-size="10.5" fill="#94a3b8">A × B = C &#160;&#160;2×3 · 3×2</text>
+<text x="750" y="182" font-size="9" letter-spacing="0.5" fill="#64748b">COST</text>
+<text x="808" y="182" font-size="9" letter-spacing="0.5" fill="#64748b">VERDICT</text>
+<text x="1050" y="182" font-size="9" letter-spacing="0.5" text-anchor="end" fill="#64748b">THEOREM</text>
+<line x1="750" y1="190" x2="1050" y2="190" stroke="#1e3a5f"/>
+<text x="750" y="208" font-size="9.5" fill="#64748b">O(n³)</text>
+<text x="808" y="208" font-size="10" fill="#34d399">product_checked</text>
+<text x="1050" y="208" font-size="9" text-anchor="end" fill="#34d399">MatCert.mul_of_check</text>
+<text x="750" y="224" font-size="9" fill="#64748b">recompute, integers</text>
+<text x="750" y="244" font-size="9.5" fill="#64748b">O(n²)</text>
+<text x="808" y="244" font-size="10" fill="#7dd3fc">survived, 2⁻⁴⁰</text>
+<text x="1050" y="244" font-size="9" text-anchor="end" fill="#64748b">none</text>
+<text x="750" y="260" font-size="9" fill="#64748b">Freivalds, integers</text>
+<text x="750" y="280" font-size="9.5" fill="#64748b">O(n²)</text>
+<text x="808" y="280" font-size="10" fill="#fbbf24">within tolerance</text>
+<text x="1050" y="280" font-size="9" text-anchor="end" fill="#64748b">none</text>
+<text x="750" y="296" font-size="9" fill="#64748b">Freivalds, doubles</text>
+<line x1="34" y1="380" x2="1066" y2="380" stroke="#1e3a5f"/>
+<text x="34" y="398" font-size="10" fill="#64748b">A word here is this engine's unless a checker earned it. Only the top row of the right column names a theorem, and only because oo-matcert exited zero having printed it.</text>
+</svg>
\ No newline at end of file
diff --git a/docs/assets/certified-claims.zh-CN.svg b/docs/assets/certified-claims.zh-CN.svg
new file mode 100644
index 00000000..fdaeedfd
--- /dev/null
+++ b/docs/assets/certified-claims.zh-CN.svg
@@ -0,0 +1,59 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1100 430" font-family="ui-sans-serif,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">
+<defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#020617"/><stop offset="1" stop-color="#070d20"/></linearGradient></defs>
+<rect width="1100" height="430" rx="14" fill="url(#bg)"/>
+<text x="34" y="40" font-size="17" font-weight="800" fill="#e2e8f0">三个曾经只能靠信任的声明</text>
+<text x="34" y="60" font-size="11.5" fill="#64748b">每列都是一次真实运行;此处每个数字都读自其输出,不是写上去的</text>
+<rect x="34" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="50" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">对照表的匹配类型</text>
+<text x="50" y="126" font-size="10" fill="#64748b">先声明,再对照两边的蕴涵核验</text>
+<text x="50" y="154" font-size="10.5" fill="#e2e8f0">Person</text>
+<text x="350" y="154" font-size="10" text-anchor="end" fill="#fbbf24">exactMatch → relatedMatch</text>
+<text x="50" y="171" font-size="10.5" fill="#e2e8f0">Organisation</text>
+<text x="350" y="171" font-size="10" text-anchor="end" fill="#fbbf24">exactMatch → relatedMatch</text>
+<text x="50" y="188" font-size="10.5" fill="#e2e8f0">Entity</text>
+<text x="350" y="188" font-size="10" text-anchor="end" fill="#34d399">exactMatch → exactMatch</text>
+<text x="50" y="205" font-size="10.5" fill="#e2e8f0">Event</text>
+<text x="350" y="205" font-size="10" text-anchor="end" fill="#34d399">exactMatch → exactMatch</text>
+<line x1="50" y1="216" x2="350" y2="216" stroke="#1e3a5f"/>
+<text x="50" y="234" font-size="10" fill="#94a3b8">1 个词对照表未收录</text>
+<text x="58" y="249" font-size="10" fill="#64748b">· ResponsibleActor</text>
+<text x="50" y="275" font-size="10" fill="#fbbf24">目标方没有 ies:ResponsibleActor</text>
+<text x="50" y="289" font-size="10" fill="#fbbf24">对应的词,因此更强的声明都立不住</text>
+<rect x="384" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="400" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">互相矛盾的语境</text>
+<text x="400" y="126" font-size="10" fill="#64748b">每个模块单独推理;事实要自己挡得“处处为真”</text>
+<rect x="400" y="146" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="162" font-size="10.5" fill="#e2e8f0">birds</text>
+<text x="690" y="162" font-size="10" text-anchor="end" fill="#64748b">蕴涵 3</text>
+<rect x="400" y="178" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="194" font-size="10.5" fill="#e2e8f0">penguins</text>
+<text x="690" y="194" font-size="10" text-anchor="end" fill="#64748b">蕴涵 4</text>
+<rect x="400" y="210" width="300" height="24" rx="7" fill="#060e20" stroke="#1e3a5f"/>
+<text x="410" y="226" font-size="10.5" fill="#e2e8f0">field_guide</text>
+<text x="690" y="226" font-size="10" text-anchor="end" fill="#64748b">蕴涵 3</text>
+<text x="400" y="260" font-size="10.5" font-weight="700" fill="#34d399">1 条事实在 3 个模块中的 2 个里被蕴涵</text>
+<text x="400" y="277" font-size="10" fill="#94a3b8">8 条只有更少模块持有,逐条列出而不丢弃</text>
+<text x="400" y="301" font-size="10" fill="#fb3b53">合并成一张图则不一致;分开则两边都成立</text>
+<rect x="734" y="84" width="332" height="280" rx="11" fill="#0b1428" stroke="#1e3a5f" stroke-width="1"/>
+<text x="750" y="110" font-size="11.5" font-weight="800" letter-spacing="0.6" fill="#7dd3fc">一个数字</text>
+<text x="750" y="126" font-size="10" fill="#64748b">在 Lean 中按定义重算</text>
+<text x="750" y="158" font-size="10.5" fill="#94a3b8">A × B = C &#160;&#160;2×3 · 3×2</text>
+<text x="750" y="182" font-size="9" letter-spacing="0.5" fill="#64748b">代价</text>
+<text x="808" y="182" font-size="9" letter-spacing="0.5" fill="#64748b">结论</text>
+<text x="1050" y="182" font-size="9" letter-spacing="0.5" text-anchor="end" fill="#64748b">定理</text>
+<line x1="750" y1="190" x2="1050" y2="190" stroke="#1e3a5f"/>
+<text x="750" y="208" font-size="9.5" fill="#64748b">O(n³)</text>
+<text x="808" y="208" font-size="10" fill="#34d399">product_checked</text>
+<text x="1050" y="208" font-size="9" text-anchor="end" fill="#34d399">MatCert.mul_of_check</text>
+<text x="750" y="224" font-size="9" fill="#64748b">重算,整数</text>
+<text x="750" y="244" font-size="9.5" fill="#64748b">O(n²)</text>
+<text x="808" y="244" font-size="10" fill="#7dd3fc">通过,2⁻⁴⁰</text>
+<text x="1050" y="244" font-size="9" text-anchor="end" fill="#64748b">无</text>
+<text x="750" y="260" font-size="9" fill="#64748b">Freivalds,整数</text>
+<text x="750" y="280" font-size="9.5" fill="#64748b">O(n²)</text>
+<text x="808" y="280" font-size="10" fill="#fbbf24">在容差内</text>
+<text x="1050" y="280" font-size="9" text-anchor="end" fill="#64748b">无</text>
+<text x="750" y="296" font-size="9" fill="#64748b">Freivalds,双精度</text>
+<line x1="34" y1="380" x2="1066" y2="380" stroke="#1e3a5f"/>
+<text x="34" y="398" font-size="10" fill="#64748b">除非核验器挡下,否则此处的词都只是本引擎的意见。只有右列首行引用了定理,且因为 oo-matcert 已将其打印并以 0 退出。</text>
+</svg>
\ No newline at end of file
diff --git a/docs/assets/claims/crosswalk.json b/docs/assets/claims/crosswalk.json
new file mode 100644
index 00000000..8f8d37ef
--- /dev/null
+++ b/docs/assets/claims/crosswalk.json
@@ -0,0 +1 @@
+{"command":"crosswalk-certify","result":{"checked":4,"downgraded":2,"gaps":1,"means":"each side was reasoned INDEPENDENTLY under OWL 2 RL and the entailed named ancestors were compared through the mapping itself. A supported predicate means nothing this engine can see refutes it. It is NOT a proof: the comparison is over 29 of OWL 2 RL's 78 rules, and an axiom no rule fires on contributes to neither side. Run onto_dlp_boundary to see which of your axioms were invisible. No Lean checker has a theorem about SKOS match types, so nothing here is certified in this repository's sense of that word.","rows":[{"because":"1 entailed ancestor(s) of the subject have no image in the target vocabulary, so the two cannot be compared where it matters most. This is the case a crosswalk hides: the target does not carry the distinction.","claimed":"http://www.w3.org/2004/02/skos/core#exactMatch","downgraded":true,"object":"http://hqdm.example/Person","object_ancestors":["http://hqdm.example/Thing"],"subject":"http://ies.example/Person","subject_ancestors":["http://ies.example/Entity","http://ies.example/ResponsibleActor"],"supported":"http://www.w3.org/2004/02/skos/core#relatedMatch","untranslatable":["http://ies.example/ResponsibleActor"]},{"because":"1 entailed ancestor(s) of the subject have no image in the target vocabulary, so the two cannot be compared where it matters most. This is the case a crosswalk hides: the target does not carry the distinction.","claimed":"http://www.w3.org/2004/02/skos/core#exactMatch","downgraded":true,"object":"http://hqdm.example/Organisation","object_ancestors":["http://hqdm.example/Thing"],"subject":"http://ies.example/Organisation","subject_ancestors":["http://ies.example/Entity","http://ies.example/ResponsibleActor"],"supported":"http://www.w3.org/2004/02/skos/core#relatedMatch","untranslatable":["http://ies.example/ResponsibleActor"]},{"because":"both sides entail the same ancestors once translated, and nothing was lost in translation.","claimed":"http://www.w3.org/2004/02/skos/core#exactMatch","downgraded":false,"object":"http://hqdm.example/Thing","object_ancestors":[],"subject":"http://ies.example/Entity","subject_ancestors":[],"supported":"http://www.w3.org/2004/02/skos/core#exactMatch","untranslatable":[]},{"because":"both sides entail the same ancestors once translated, and nothing was lost in translation.","claimed":"http://www.w3.org/2004/02/skos/core#exactMatch","downgraded":false,"object":"http://hqdm.example/Activity","object_ancestors":["http://hqdm.example/Thing"],"subject":"http://ies.example/Event","subject_ancestors":["http://ies.example/Entity"],"supported":"http://www.w3.org/2004/02/skos/core#exactMatch","untranslatable":[]}],"unmapped":[{"reason":"the crosswalk carries no row for this term, so a reader cannot tell whether it was considered and rejected or never looked at","side":"source","term":"http://ies.example/ResponsibleActor"}],"verdict":"checked_by_this_engine"},"seq":0}
diff --git a/docs/assets/claims/hqdm-side.ttl b/docs/assets/claims/hqdm-side.ttl
new file mode 100644
index 00000000..6d69a099
--- /dev/null
+++ b/docs/assets/claims/hqdm-side.ttl
@@ -0,0 +1,9 @@
+# The other side. It has Person and Organisation, but it does NOT put them
+# under a common responsible-actor class: both hang straight off the top.
+@prefix hqdm: <http://hqdm.example/> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+hqdm:Person a owl:Class ; rdfs:subClassOf hqdm:Thing .
+hqdm:Organisation a owl:Class ; rdfs:subClassOf hqdm:Thing .
+hqdm:Thing a owl:Class .
+hqdm:Activity a owl:Class ; rdfs:subClassOf hqdm:Thing .
diff --git a/docs/assets/claims/ies-side.ttl b/docs/assets/claims/ies-side.ttl
new file mode 100644
index 00000000..b6e842a5
--- /dev/null
+++ b/docs/assets/claims/ies-side.ttl
@@ -0,0 +1,9 @@
+# A small, real-shaped slice: a vocabulary with a three-deep hierarchy.
+@prefix ies: <http://ies.example/> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+ies:Person a owl:Class ; rdfs:subClassOf ies:ResponsibleActor .
+ies:Organisation a owl:Class ; rdfs:subClassOf ies:ResponsibleActor .
+ies:ResponsibleActor a owl:Class ; rdfs:subClassOf ies:Entity .
+ies:Entity a owl:Class .
+ies:Event a owl:Class ; rdfs:subClassOf ies:Entity .
diff --git a/docs/assets/claims/mapping.tsv b/docs/assets/claims/mapping.tsv
new file mode 100644
index 00000000..4f2a33e4
--- /dev/null
+++ b/docs/assets/claims/mapping.tsv
@@ -0,0 +1,5 @@
+subject_id predicate_id object_id
+http://ies.example/Person skos:exactMatch http://hqdm.example/Person
+http://ies.example/Organisation skos:exactMatch http://hqdm.example/Organisation
+http://ies.example/Entity skos:exactMatch http://hqdm.example/Thing
+http://ies.example/Event skos:exactMatch http://hqdm.example/Activity
diff --git a/docs/assets/claims/matcert.json b/docs/assets/claims/matcert.json
new file mode 100644
index 00000000..01ec6666
--- /dev/null
+++ b/docs/assets/claims/matcert.json
@@ -0,0 +1 @@
+{"ok":true,"verdict":"product_checked","m":2,"p":3,"n":2,"theorem":"MatCert.mul_of_check","means":"every entry of C within the stated shape is the sum over k of A[i][k]*B[k][j], recomputed here from the definition. Integers only. This says nothing about any floating-point computation that produced these numbers.","checker":{"name":"oo-matcert","self_sha256":"82ecc2457ea2bf5f638465eeccb0fca53fa05b93ed546519264c7aa0d9f3fab4","toolchain":"4.33.1","means":"the digest of the FILE this process is running from, read at run time. Match it against the SHASUMS.txt of the release you expected. It does not make this binary honest: a hostile one can print any block it likes. It lets an honest build say which build it is."}}
diff --git a/docs/assets/claims/mod-birds.ttl b/docs/assets/claims/mod-birds.ttl
new file mode 100644
index 00000000..036a3274
--- /dev/null
+++ b/docs/assets/claims/mod-birds.ttl
@@ -0,0 +1,4 @@
+@prefix : <http://ex.org/> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+:Bird rdfs:subClassOf :Flier .
+:tweety a :Bird .
diff --git a/docs/assets/claims/mod-guide.ttl b/docs/assets/claims/mod-guide.ttl
new file mode 100644
index 00000000..efba26ed
--- /dev/null
+++ b/docs/assets/claims/mod-guide.ttl
@@ -0,0 +1,4 @@
+@prefix : <http://ex.org/> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+:Bird rdfs:subClassOf :Flier .
+:robin a :Bird .
diff --git a/docs/assets/claims/mod-penguins.ttl b/docs/assets/claims/mod-penguins.ttl
new file mode 100644
index 00000000..f1d8dbd1
--- /dev/null
+++ b/docs/assets/claims/mod-penguins.ttl
@@ -0,0 +1,6 @@
+@prefix : <http://ex.org/> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+:Penguin rdfs:subClassOf :Bird .
+:Penguin owl:disjointWith :Flier .
+:pingu a :Penguin .
diff --git a/docs/assets/claims/modules.json b/docs/assets/claims/modules.json
new file mode 100644
index 00000000..be4902f2
--- /dev/null
+++ b/docs/assets/claims/modules.json
@@ -0,0 +1 @@
+{"command":"modules","result":{"contested":8,"contested_facts":[{"agreed":1,"modules":["penguins"],"triple":"<http://ex.org/Penguin> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Bird> ."},{"agreed":1,"modules":["penguins"],"triple":"<http://ex.org/Penguin> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Flier> ."},{"agreed":1,"modules":["penguins"],"triple":"<http://ex.org/pingu> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Bird> ."},{"agreed":1,"modules":["penguins"],"triple":"<http://ex.org/pingu> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Penguin> ."},{"agreed":1,"modules":["field_guide"],"triple":"<http://ex.org/robin> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Bird> ."},{"agreed":1,"modules":["field_guide"],"triple":"<http://ex.org/robin> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Flier> ."},{"agreed":1,"modules":["birds"],"triple":"<http://ex.org/tweety> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Bird> ."},{"agreed":1,"modules":["birds"],"triple":"<http://ex.org/tweety> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Flier> ."}],"means":"each module was reasoned ALONE under OWL 2 RL, in its own store, so no module's axioms answered another's questions. A promoted fact is one at least k modules entailed independently. This is a COUNT and not a proof: modules that copied the same mistaken axiom agree just as loudly, and agreement is evidence only to the degree the modules really are independent, which nothing here checks. A contested fact is not an error; it is the disagreement made visible, which one graph would have hidden by refusing to hold both.","modules":[{"entails":3,"name":"birds"},{"entails":4,"name":"penguins"},{"entails":3,"name":"field_guide"}],"promoted":1,"promoted_facts":[{"agreed":2,"modules":["birds","field_guide"],"triple":"<http://ex.org/Bird> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Flier> ."}],"threshold":2,"verdict":"agreed_by_k_of_n_modules"},"seq":0}
diff --git a/docs/assets/claims/product.matcert b/docs/assets/claims/product.matcert
new file mode 100644
index 00000000..7120f698
--- /dev/null
+++ b/docs/assets/claims/product.matcert
@@ -0,0 +1,9 @@
+matcert/1
+dims 2 3 2
+A 2 1 3
+A 0 4 1
+B 1 2
+B 3 0
+B 1 1
+C 8 7
+C 13 1
diff --git a/docs/ci-gates.md b/docs/ci-gates.md
index 5de0c2fe..149ff29a 100644
--- a/docs/ci-gates.md
+++ b/docs/ci-gates.md
@@ -59,6 +59,8 @@ job invokes the file at all.
| `shacl_core_verified_test.rs` | lake + vendored W3C SHACL suite | `lean` job | **strict** |
| `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** |
| `shacl_verified_tool_test.rs` | lake + `oo-shacl` | `lean` job | **strict** |
+| `matcert_numeric_test.rs` | lake + `oo-matcert` | `lean` job | **strict** |
+| `certified_claims_asset_test.rs` | lake + `oo-matcert` | `lean` job | **strict** |
| `shacl_ignored_is_named_test.rs` | lake + `oo-shacl` | `lean` job | **strict** |
| `checker_self_identification_test.rs` | lake + every checker | `lean` job | **strict** |
| `cli_verified_shacl_test.rs` | lake + `oo-shacl` | `lean` job | **strict** |
diff --git a/lean/MatCert/All.lean b/lean/MatCert/All.lean
new file mode 100644
index 00000000..f129a4bf
--- /dev/null
+++ b/lean/MatCert/All.lean
@@ -0,0 +1 @@
+import MatCert.Basic
diff --git a/lean/MatCert/Basic.lean b/lean/MatCert/Basic.lean
new file mode 100644
index 00000000..9095e1c9
--- /dev/null
+++ b/lean/MatCert/Basic.lean
@@ -0,0 +1,99 @@
+/-!
+# A numeric claim, checked
+
+`OOCert` certifies that a triple follows from a graph. Nothing in this
+repository could certify that a NUMBER follows from other numbers, and the gap
+showed: an ontology pipeline that computes a similarity score, an alignment
+metric or a risk figure hands that number on with no more standing than an
+assertion.
+
+This is the smallest honest closure of that gap: matrix multiplication over the
+integers, checked by recomputation against the definition, with a theorem in
+core Lean saying what an acceptance means.
+
+## Why integers, and why this is the exact path only
+
+Freivalds' algorithm checks `A × B = C` in O(n²) by multiplying both sides by a
+random vector, and its soundness is a PROBABILISTIC statement: the check passes
+a wrong product with probability at most 2⁻ᵏ after k trials. Stating that needs
+probability theory, and this development has no Mathlib by deliberate choice —
+`lakefile.toml` says why. So the probabilistic path stays where it can be
+honest: in Rust, as this engine's own opinion, with its bound printed and the
+word `certified` withheld.
+
+Floating point is worse and is excluded outright. A proof over ℝ says nothing
+about IEEE-754: rounding makes `A × B = C` fail for a correct implementation
+and hold for an incorrect one. A certificate proved over the reals and run on
+hardware is unsound, silently. `Mat.check` takes integers and the Rust side
+refuses to hand it anything else.
+
+## What the theorem says
+
+`MatCert.mul_of_check` : if `check A B C` returns true then every entry of `C`
+is the sum over k of `A[i][k] * B[k][j]`. That is the textbook definition,
+written out in `spec`, and the checker is measured against it rather than
+against a second implementation that could share its mistakes.
+
+The theorem is deliberately about the DEFINITION and not about `A × B` as some
+other function computes it. A checker that agreed with a wrong multiplier would
+be worthless, and this one cannot: it recomputes from the spec.
+-/
+
+namespace Mat
+
+abbrev Matrix := List (List Int)
+
+/-- `A[i][j]`, or zero outside the matrix. Out of range is not an error here:
+the shape check below refuses ragged input before this is ever reached, so a
+default keeps the arithmetic total without hiding anything. -/
+def at! (M : Matrix) (i j : Nat) : Int :=
+ match M[i]? with
+ | none => 0
+ | some row => match row[j]? with
+ | none => 0
+ | some v => v
+
+/-- The definition: `C[i][j] = Σ_{k<p} A[i][k] * B[k][j]`. -/
+def spec (A B : Matrix) (p i j : Nat) : Int :=
+ (List.range p).foldl (fun acc k => acc + at! A i k * at! B k j) 0
+
+/-- Every row has the stated width. Ragged input is refused rather than padded,
+because a padded row is a different matrix and would be checked as one. -/
+def rectangular (M : Matrix) (w : Nat) : Bool :=
+ M.all (fun row => row.length == w)
+
+/-- Shapes agree: `A` is m×p, `B` is p×n, `C` is m×n. -/
+def shapesAgree (A B C : Matrix) (m p n : Nat) : Bool :=
+ A.length == m && B.length == p && C.length == m
+ && rectangular A p && rectangular B n && rectangular C n
+
+/-- The check: every entry of `C` equals the definition. -/
+def check (A B C : Matrix) (m p n : Nat) : Bool :=
+ shapesAgree A B C m p n
+ && (List.range m).all (fun i =>
+ (List.range n).all (fun j => at! C i j == spec A B p i j))
+
+end Mat
+
+namespace MatCert
+
+/-- **What an acceptance means.**
+
+If `Mat.check` returns true then every entry of `C` within the stated shape is
+the sum of products the definition calls for. Nothing weaker and nothing more:
+it says nothing about entries outside the shape, because `shapesAgree` has
+already refused those inputs. -/
+theorem mul_of_check {A B C : Mat.Matrix} {m p n : Nat}
+ (h : Mat.check A B C m p n = true) :
+ ∀ i, i < m → ∀ j, j < n → Mat.at! C i j = Mat.spec A B p i j := by
+ simp [Mat.check, Bool.and_eq_true] at h
+ exact h.2
+
+/-- The shapes the acceptance was about, so a reader cannot apply the theorem
+to a different matrix by reading only its conclusion. -/
+theorem shapes_of_check {A B C : Mat.Matrix} {m p n : Nat}
+ (h : Mat.check A B C m p n = true) : Mat.shapesAgree A B C m p n = true := by
+ simp [Mat.check, Bool.and_eq_true] at h
+ exact h.1
+
+end MatCert
diff --git a/lean/MatCertMain.lean b/lean/MatCertMain.lean
new file mode 100644
index 00000000..1c4bb851
--- /dev/null
+++ b/lean/MatCertMain.lean
@@ -0,0 +1,121 @@
+import MatCert.All
+import SelfId.All
+
+/-!
+# `oo-matcert`: check a numeric claim
+
+ oo-matcert CERT.matcert
+
+`matcert/1` is a line format, tab separated, integers only:
+
+ matcert/1
+ dims<TAB>m<TAB>p<TAB>n
+ A<TAB>1 2 3
+ B<TAB>4 5
+ C<TAB>...
+
+Exit 0 with a verdict, 1 when the claim does not check, 2 when the file cannot
+be read or parsed. The same three codes every checker here uses, so a caller
+that already handles one handles this.
+
+Integers by construction. The parser refuses anything with a decimal point
+rather than rounding it, because a certificate about floating-point numbers
+checked as if they were reals is unsound in a way that never announces itself.
+That path exists in Rust, says so, and does not print a theorem name.
+-/
+
+open Mat
+
+def jsonStr (s : String) : String :=
+ "\"" ++ (s.foldl (fun acc c =>
+ acc ++ (match c with
+ | '"' => "\\\"" | '\\' => "\\\\" | '\n' => "\\n" | c => c.toString)) "") ++ "\""
+
+def emitError (reason : String) : IO UInt32 := do
+ IO.println ("{\"ok\":false,\"error\":" ++ jsonStr reason ++ "}")
+ return 2
+
+/-- One integer, or nothing. A decimal point is refused by name. -/
+def readInt (s : String) : Option Int :=
+ let t := s.trim
+ if t.isEmpty then none
+ else if t.contains '.' then none
+ else if t.startsWith "-" then (String.toNat? (String.mk (t.toList.drop 1))).map (fun n => -(Int.ofNat n))
+ else (String.toNat? t).map Int.ofNat
+
+def readRow (s : String) : Option (List Int) :=
+ ((s.trim.splitOn " ").filter (fun w => !w.isEmpty)).foldr
+ (fun w acc => match acc, readInt w with
+ | some xs, some v => some (v :: xs)
+ | _, _ => none)
+ (some [])
+
+structure Cert where
+ m : Nat
+ p : Nat
+ n : Nat
+ A : Matrix
+ B : Matrix
+ C : Matrix
+
+def parse (text : String) : Except String Cert := do
+ let lines := (text.splitOn "\n").filter (fun l => !l.trim.isEmpty)
+ match lines with
+ | [] => throw "the certificate is empty"
+ | hdr :: rest =>
+ if hdr.trim != "matcert/1" then
+ throw s!"expected a matcert/1 header, found {hdr.trim}"
+ else
+ let mut dims : Option (Nat × Nat × Nat) := none
+ let mut a : List (List Int) := []
+ let mut b : List (List Int) := []
+ let mut c : List (List Int) := []
+ for line in rest do
+ match line.splitOn "\t" with
+ | ["dims", ms, ps, ns] =>
+ match String.toNat? ms.trim, String.toNat? ps.trim, String.toNat? ns.trim with
+ | some m, some p, some n => dims := some (m, p, n)
+ | _, _, _ => throw s!"dims must be three naturals: {line}"
+ | [tag, row] =>
+ match readRow row with
+ | none => throw s!"a row carries something that is not an integer: {line}. \
+ Refused rather than rounded: a numeric certificate that quietly turned 1.5 into \
+ 1 would check a claim nobody made."
+ | some r =>
+ if tag == "A" then a := a ++ [r]
+ else if tag == "B" then b := b ++ [r]
+ else if tag == "C" then c := c ++ [r]
+ else throw s!"unknown row tag {tag}"
+ | _ => throw s!"unreadable line: {line}"
+ match dims with
+ | none => throw "the certificate states no dims line"
+ | some (m, p, n) => return { m := m, p := p, n := n, A := a, B := b, C := c }
+
+def main (args : List String) : IO UInt32 := do
+ match args with
+ | ["--version"] => SelfId.emitVersion
+ | [path] =>
+ let text ← try IO.FS.readFile path catch _ =>
+ return ← emitError s!"could not read {path}"
+ match parse text with
+ | .error e => emitError e
+ | .ok cert =>
+ if check cert.A cert.B cert.C cert.m cert.p cert.n then
+ SelfId.println ("{\"ok\":true,\"verdict\":\"product_checked\"," ++
+ "\"m\":" ++ toString cert.m ++ ",\"p\":" ++ toString cert.p ++
+ ",\"n\":" ++ toString cert.n ++
+ ",\"theorem\":\"MatCert.mul_of_check\"," ++
+ "\"means\":" ++ jsonStr
+ "every entry of C within the stated shape is the sum over k of A[i][k]*B[k][j], \
+ recomputed here from the definition. Integers only. This says nothing about any \
+ floating-point computation that produced these numbers." ++ "}")
+ return 0
+ else
+ SelfId.println ("{\"ok\":false,\"verdict\":\"product_not_checked\"," ++
+ "\"means\":" ++ jsonStr
+ "either the shapes disagree with the stated dims or some entry of C is not the \
+ sum of products. No theorem is named, because none was discharged." ++ "}")
+ return 1
+ | _ =>
+ IO.eprintln "usage: oo-matcert CERT.matcert"
+ return 2
diff --git a/lean/lakefile.toml b/lean/lakefile.toml
index 42d37f01..af8e27ab 100644
--- a/lean/lakefile.toml
+++ b/lean/lakefile.toml
@@ -1,6 +1,6 @@
name = "oocert"
version = "0.1.0"
-defaultTargets = ["SelfId", "OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution", "Lrat", "oo-lrat", "Fo", "oo-resolution"]
+defaultTargets = ["SelfId", "MatCert", "oo-matcert", "OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution", "Lrat", "oo-lrat", "Fo", "oo-resolution"]
# Every library and executable here is in defaultTargets on purpose. A target
# left out of the default set is not built by a bare `lake build`, which is what
@@ -131,3 +131,23 @@ root = "FoMain"
name = "SelfId"
roots = ["SelfId.All"]
globs = ["SelfId.+"]
+
+
+# A numeric claim, checked. Matrix multiplication over the INTEGERS, recomputed
+# against the textbook definition, with `MatCert.mul_of_check` saying what an
+# acceptance means.
+#
+# Integers only, and that is the whole design. Freivalds' O(n^2) check is sound
+# only probabilistically, which needs probability theory this development does
+# not have and will not take a dependency for; and a proof over the reals says
+# NOTHING about IEEE-754, where rounding makes a correct product compare unequal
+# and an incorrect one compare equal. Both of those live in Rust as this
+# engine's opinion, with their bounds printed and the certified word withheld.
+[[lean_lib]]
+name = "MatCert"
+roots = ["MatCert.All"]
+globs = ["MatCert.+"]
+
+[[lean_exe]]
+name = "oo-matcert"
+root = "MatCertMain"
diff --git a/src/batch.rs b/src/batch.rs
index e06374d6..c3cdfb84 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -152,6 +152,9 @@ impl BatchRunner {
"push" => self.exec_push(&cmd.args).await,
"ingest" => self.exec_ingest(&cmd.args),
"induce" => self.exec_induce(&cmd.args),
+ "crosswalk-certify" | "crosswalk_certify" => Self::exec_crosswalk(&cmd.args),
+ "modules" | "distributed" => Self::exec_modules(&cmd.args),
+ "matcert" => Self::exec_matcert(&cmd.args),
"drift" => self.exec_drift(&cmd.args),
"lock" => self.exec_lock(&cmd.args),
"monitor" => self.exec_monitor(),
@@ -636,6 +639,108 @@ impl BatchRunner {
}
}
+ /// Certify a crosswalk's match types against what the two ontologies entail.
+ ///
+ /// Takes its own two stores rather than the loaded one, because the whole
+ /// point is that each side is reasoned INDEPENDENTLY: merging them into
+ /// one graph would let each side's axioms answer the other's questions,
+ /// which is the comparison this is supposed to make, not an input to it.
+ fn exec_crosswalk(args: &[String]) -> Value {
+ let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with("--")).collect();
+ if pos.len() < 3 {
+ return json!({"error": "crosswalk-certify needs SOURCE TARGET MAPPINGS.tsv"});
+ }
+ match crate::crosswalk::certify_files(pos[0], pos[1], pos[2]) {
+ Ok((rep, tsv)) => {
+ if let Some(out) = Self::flag_value(args, "--sssom") {
+ if let Err(e) = std::fs::write(&out, &tsv) {
+ return json!({"error": format!("could not write {out}: {e}")});
+ }
+ let mut r = rep;
+ r["sssom_written"] = json!(out);
+ return r;
+ }
+ rep
+ }
+ Err(e) => json!({"error": e.to_string()}),
+ }
+ }
+
+ /// Reason each module alone, then promote what k of n agree on.
+ ///
+ /// Modules are `NAME=FILE` pairs. Separate arguments rather than one
+ /// merged graph, because the entire point is that no module's axioms
+ /// answer another's questions.
+ fn exec_modules(args: &[String]) -> Value {
+ let k: usize = match Self::flag_value(args, "--threshold").map(|v| v.parse()) {
+ Some(Ok(k)) => k,
+ Some(Err(_)) => return json!({"error": "--threshold takes a whole number"}),
+ None => return json!({"error": "modules needs --threshold k"}),
+ };
+ // `--threshold 2` is TWO arguments, so a naive "not a flag" filter reads
+ // the 2 as a module name. Skip the value that follows a flag which
+ // takes one.
+ let mut positional: Vec<&String> = Vec::new();
+ let mut skip = false;
+ for a in args {
+ if skip {
+ skip = false;
+ continue;
+ }
+ if a == "--threshold" {
+ skip = true;
+ continue;
+ }
+ if a.starts_with("--") {
+ continue;
+ }
+ positional.push(a);
+ }
+ let mut mods = Vec::new();
+ for a in positional {
+ let Some((name, path)) = a.split_once('=') else {
+ return json!({"error": format!("expected NAME=FILE, found {a}")});
+ };
+ match crate::graph::GraphStore::read_as_turtle(path) {
+ Ok(ttl) => mods.push(crate::modules::Module {
+ name: name.to_string(),
+ ttl,
+ }),
+ Err(e) => return json!({"error": format!("{path}: {e}")}),
+ }
+ }
+ match crate::modules::distributed(&mods, k) {
+ Ok(v) => v,
+ Err(e) => json!({"error": e.to_string()}),
+ }
+ }
+
+ /// Check a numeric claim. `matcert CERT.matcert` runs the Lean checker
+ /// over a certificate somebody else wrote.
+ fn exec_matcert(args: &[String]) -> Value {
+ let Some(path) = args.iter().find(|a| !a.starts_with("--")) else {
+ return json!({"error": "matcert needs a CERT.matcert path"});
+ };
+ let Some(bin) = crate::matcert::find_checker() else {
+ return json!({
+ "error": "oo-matcert was not found",
+ "install": "run `lake build oo-matcert` in lean/, or set $OO_MATCERT",
+ "means": "a missing checker is never an acceptance",
+ });
+ };
+ let out = std::process::Command::new(&bin).arg(path).output();
+ match out {
+ Ok(o) => {
+ let text = String::from_utf8_lossy(&o.stdout).to_string();
+ serde_json::from_str(&text).unwrap_or_else(|_| json!({
+ "exit": o.status.code(),
+ "raw": text,
+ }))
+ }
+ Err(e) => json!({"error": format!("{} could not be run: {e}", bin.display())}),
+ }
+ }
+
/// Closed-world vocabulary check against the loaded ontology.
///
/// This function existed and was never reachable: no arm of the dispatch
diff --git a/src/crosswalk.rs b/src/crosswalk.rs
new file mode 100644
index 00000000..b3a89fb7
--- /dev/null
+++ b/src/crosswalk.rs
@@ -0,0 +1,460 @@
+//! Certify what a crosswalk CLAIMS against what the two ontologies ENTAIL.
+//!
+//! A mapping file says `ies:Person skos:exactMatch hqdm:Person`. Nothing checks
+//! it. `src/align.rs` chooses that predicate from label similarity and property
+//! overlap, which is a guess from surface features, and once written down the
+//! guess is indistinguishable from a fact. Every crosswalk export in this space
+//! has the same property: the match TYPE is asserted and never verified.
+//!
+//! That matters because the type is the whole claim. `exactMatch` and
+//! `broadMatch` licence different downstream reasoning, and the case this
+//! repository has already measured is the expensive one: the Foundry crosswalk
+//! found IES 5.0.3 losing 202 `rdfs:subPropertyOf` axioms against HQDM. A
+//! mapping asserting `exactMatch` across that gap is not slightly wrong, it is
+//! claiming two concepts are interchangeable when one side cannot express what
+//! the other says.
+//!
+//! # What is checked
+//!
+//! For a pair `(a, b)`, each side is reasoned INDEPENDENTLY under OWL 2 RL, in
+//! its own store. Then the entailed named superclasses of `a` are translated
+//! into the target vocabulary through the mapping itself, and compared with
+//! those of `b`.
+//!
+//! * The two translated ancestor sets agree, and nothing was lost in
+//! translation: `exactMatch` stands.
+//! * `a` is under everything `b` is under and more: `a` is the more specific
+//! concept, so `a ⊑ b`, so the tightest true predicate is `broadMatch` —
+//! `skos:broadMatch` is a sub-property of `skos:broader`, and `A broader B`
+//! means B is the BROADER concept. Getting that direction backwards is the
+//! exact silent error this module exists to catch, so
+//! `tests/crosswalk_certify_test.rs` pins it with a worked example rather
+//! than trusting this paragraph.
+//! * `b` is the more specific one: `narrowMatch`.
+//! * The two disagree in both directions, or an ancestor has no image in the
+//! target at all: `relatedMatch`, which is the weakest thing SKOS lets you
+//! say and the honest answer when the vocabularies do not line up.
+//!
+//! # What is NOT checked, and is said rather than hidden
+//!
+//! This is not a proof. The comparison is over NAMED superclasses entailed by
+//! this engine's OWL 2 RL rule table, which is 29 of the profile's 78 rules,
+//! and a class whose relationship is expressible only through a construct
+//! those rules do not evaluate contributes nothing to either side. So a
+//! `certified_exact` here means "nothing this engine can see refutes it", not
+//! "the two concepts are identical". The report says so in its own `means`
+//! field, and `onto_dlp_boundary` is the tool that says which of your axioms
+//! were invisible.
+//!
+//! Nothing here mints a `verdict::Certified`. No Lean checker has a theorem
+//! about SKOS match types, so the word `certified` in this module is this
+//! engine's own and is spelled `checked_by_this_engine` on the wire, exactly
+//! as `EngineRefutation` spells its own opinions.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+use crate::graph::GraphStore;
+use crate::reason::{InferenceTarget, Reasoner};
+
+/// The SKOS mapping predicates, tightest first.
+///
+/// Order matters: the certifier reports the TIGHTEST predicate the evidence
+/// supports, so a scan that stopped at the first supported one would report
+/// `relatedMatch` for everything.
+pub const TIGHTEST_FIRST: [&str; 4] =
+ ["exactMatch", "broadMatch", "narrowMatch", "relatedMatch"];
+
+const SKOS: &str = "http://www.w3.org/2004/02/skos/core#";
+
+/// One row of a crosswalk: a claim about two terms.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Mapping {
+ pub subject: String,
+ pub predicate: String,
+ pub object: String,
+}
+
+/// What the evidence supports for one pair.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Certified {
+ pub mapping: Mapping,
+ /// The tightest predicate the entailments support.
+ pub supported: &'static str,
+ /// True when the claim was stronger than the evidence.
+ pub downgraded: bool,
+ /// Ancestors of the subject, in the subject's own vocabulary.
+ pub subject_ancestors: BTreeSet<String>,
+ /// Ancestors of the object.
+ pub object_ancestors: BTreeSet<String>,
+ /// Subject ancestors the mapping cannot carry into the target vocabulary.
+ /// A non-empty set here is the Foundry case: the target cannot express
+ /// something the source says.
+ pub untranslatable: BTreeSet<String>,
+ /// Why, in one sentence a reader can act on.
+ pub because: String,
+}
+
+/// A term the crosswalk cannot map, and the reason.
+///
+/// This is the half that vanishes from every crosswalk export. A reviewer
+/// needs the list of what CANNOT map at least as much as the list of what
+/// does, and today that information is simply absent from the file.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Gap {
+ pub term: String,
+ pub side: &'static str,
+ pub reason: String,
+}
+
+fn strip(t: &str) -> String {
+ t.trim().trim_start_matches('<').trim_end_matches('>').to_string()
+}
+
+/// Entailed named superclasses of every class, under OWL 2 RL.
+///
+/// `materialize` is true because the comparison is about what each ontology
+/// ENTAILS, not about what its author happened to write down. That is the
+/// whole point: a crosswalk that looks right against asserted triples can be
+/// wrong against entailed ones.
+fn ancestors(store: &Arc<GraphStore>) -> anyhow::Result<BTreeMap<String, BTreeSet<String>>> {
+ Reasoner::run_full(store, "owl-rl", true, InferenceTarget::DefaultGraph, None)?;
+ let q = "SELECT ?c ?p WHERE { ?c <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?p . \
+ FILTER(!isBlank(?c) && !isBlank(?p) && ?c != ?p) }";
+ let js: serde_json::Value = serde_json::from_str(&store.sparql_select(q)?)?;
+ let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
+ for row in js["results"].as_array().cloned().unwrap_or_default() {
+ let (Some(c), Some(p)) = (row["c"].as_str(), row["p"].as_str()) else { continue };
+ let (c, p) = (strip(c), strip(p));
+ // owl:Thing is entailed above everything and distinguishes nothing.
+ if p.ends_with("#Thing") {
+ continue;
+ }
+ out.entry(c).or_default().insert(p);
+ }
+ Ok(out)
+}
+
+/// The tightest SKOS predicate two ancestor sets support.
+///
+/// Returns the predicate and the sentence explaining it. Superset means MORE
+/// ancestors, which means the more specific concept: a concept under more
+/// things is lower in the hierarchy.
+fn tightest(
+ sub_in_target: &BTreeSet<String>,
+ obj: &BTreeSet<String>,
+ untranslatable: &BTreeSet<String>,
+) -> (&'static str, String) {
+ if !untranslatable.is_empty() {
+ let n = untranslatable.len();
+ return (
+ "relatedMatch",
+ format!(
+ "{n} entailed ancestor(s) of the subject have no image in the target \
+ vocabulary, so the two cannot be compared where it matters most. This is \
+ the case a crosswalk hides: the target does not carry the distinction."
+ ),
+ );
+ }
+ if sub_in_target == obj {
+ return (
+ "exactMatch",
+ "both sides entail the same ancestors once translated, and nothing was lost in \
+ translation."
+ .to_string(),
+ );
+ }
+ if sub_in_target.is_superset(obj) {
+ return (
+ "broadMatch",
+ "the subject is under every ancestor the object is under, and more, so the \
+ subject is the MORE SPECIFIC concept and the object is the broader one."
+ .to_string(),
+ );
+ }
+ if obj.is_superset(sub_in_target) {
+ return (
+ "narrowMatch",
+ "the object is under every ancestor the subject is under, and more, so the \
+ object is the more specific concept."
+ .to_string(),
+ );
+ }
+ (
+ "relatedMatch",
+ "each side entails an ancestor the other does not, so neither subsumes the other \
+ and only a related-match is defensible."
+ .to_string(),
+ )
+}
+
+/// Certify a crosswalk against the two ontologies it claims to connect.
+pub fn certify(
+ source: &Arc<GraphStore>,
+ target: &Arc<GraphStore>,
+ mappings: &[Mapping],
+) -> anyhow::Result<(Vec<Certified>, Vec<Gap>)> {
+ let sa = ancestors(source)?;
+ let ta = ancestors(target)?;
+
+ // The mapping is its own translation table, which is the point: a bridge
+ // is checked against itself rather than against a second, unstated one.
+ let fwd: BTreeMap<&str, &str> =
+ mappings.iter().map(|m| (m.subject.as_str(), m.object.as_str())).collect();
+
+ let mut rows = Vec::new();
+ for m in mappings {
+ let empty = BTreeSet::new();
+ let s_anc = sa.get(&m.subject).unwrap_or(&empty).clone();
+ let o_anc = ta.get(&m.object).unwrap_or(&empty).clone();
+
+ let mut translated = BTreeSet::new();
+ let mut untranslatable = BTreeSet::new();
+ for c in &s_anc {
+ match fwd.get(c.as_str()) {
+ Some(img) => {
+ translated.insert((*img).to_string());
+ }
+ None => {
+ untranslatable.insert(c.clone());
+ }
+ }
+ }
+
+ let (supported, because) = tightest(&translated, &o_anc, &untranslatable);
+ let claimed = m.predicate.rsplit(['#', '/']).next().unwrap_or("").to_string();
+ let rank = |p: &str| TIGHTEST_FIRST.iter().position(|q| *q == p).unwrap_or(usize::MAX);
+ rows.push(Certified {
+ mapping: m.clone(),
+ supported,
+ // Stronger than the evidence, by the SKOS ordering. A claim that was
+ // already weaker than the evidence is not "upgraded" here: the file
+ // said less than it could, which is not a defect.
+ downgraded: rank(&claimed) < rank(supported),
+ subject_ancestors: s_anc,
+ object_ancestors: o_anc,
+ untranslatable,
+ because,
+ });
+ }
+
+ // Every source class with no row at all. Silence in a crosswalk reads as
+ // "nothing to say"; it should read as "not mapped, and here is why".
+ let mapped: BTreeSet<&str> = mappings.iter().map(|m| m.subject.as_str()).collect();
+ let mut gaps = Vec::new();
+ for c in sa.keys() {
+ if !mapped.contains(c.as_str()) {
+ gaps.push(Gap {
+ term: c.clone(),
+ side: "source",
+ reason: "the crosswalk carries no row for this term, so a reader cannot tell \
+ whether it was considered and rejected or never looked at"
+ .to_string(),
+ });
+ }
+ }
+ Ok((rows, gaps))
+}
+
+/// The report, as the JSON every other tool here returns.
+pub fn report(rows: &[Certified], gaps: &[Gap]) -> serde_json::Value {
+ let downgrades = rows.iter().filter(|r| r.downgraded).count();
+ serde_json::json!({
+ "checked": rows.len(),
+ "downgraded": downgrades,
+ "gaps": gaps.len(),
+ "rows": rows.iter().map(|r| serde_json::json!({
+ "subject": r.mapping.subject,
+ "object": r.mapping.object,
+ "claimed": r.mapping.predicate,
+ "supported": format!("{SKOS}{}", r.supported),
+ "downgraded": r.downgraded,
+ "because": r.because,
+ "subject_ancestors": r.subject_ancestors.iter().collect::<Vec<_>>(),
+ "object_ancestors": r.object_ancestors.iter().collect::<Vec<_>>(),
+ "untranslatable": r.untranslatable.iter().collect::<Vec<_>>(),
+ })).collect::<Vec<_>>(),
+ "unmapped": gaps.iter().map(|g| serde_json::json!({
+ "term": g.term, "side": g.side, "reason": g.reason,
+ })).collect::<Vec<_>>(),
+ "verdict": "checked_by_this_engine",
+ "means": "each side was reasoned INDEPENDENTLY under OWL 2 RL and the entailed named \
+ ancestors were compared through the mapping itself. A supported predicate \
+ means nothing this engine can see refutes it. It is NOT a proof: the \
+ comparison is over 29 of OWL 2 RL's 78 rules, and an axiom no rule fires on \
+ contributes to neither side. Run onto_dlp_boundary to see which of your \
+ axioms were invisible. No Lean checker has a theorem about SKOS match types, \
+ so nothing here is certified in this repository's sense of that word.",
+ })
+}
+
+/// A valid SSSOM mapping set, with the certification as extra columns.
+///
+/// Extra columns rather than a new format, so a reader who already has SSSOM
+/// tooling gets this as a strict upgrade and nobody is asked to adopt
+/// anything. `predicate_id` carries the SUPPORTED predicate, because a file
+/// whose predicate column still said `exactMatch` after this ran would be
+/// worse than no check at all.
+pub fn to_sssom(rows: &[Certified], gaps: &[Gap]) -> String {
+ let mut out = String::from(
+ "subject_id\tpredicate_id\tobject_id\tmapping_justification\t\
+ claimed_predicate_id\tcertification\tcomment\n",
+ );
+ for r in rows {
+ out.push_str(&format!(
+ "{}\tskos:{}\t{}\tsemapv:LogicalReasoning\t{}\t{}\t{}\n",
+ r.mapping.subject,
+ r.supported,
+ r.mapping.object,
+ r.mapping.predicate,
+ if r.downgraded { "downgraded" } else { "upheld" },
+ r.because.replace('\t', " "),
+ ));
+ }
+ for g in gaps {
+ out.push_str(&format!(
+ "{}\tsssom:NoMapping\t\tsemapv:LogicalReasoning\t\tgap\t{}\n",
+ g.term,
+ g.reason.replace('\t', " ")
+ ));
+ }
+ out
+}
+
+/// Read an SSSOM mapping set.
+///
+/// Tab separated with a header naming the columns, which is the format the
+/// standard specifies and the one anybody already holding a crosswalk has.
+/// Comment lines beginning `#` carry SSSOM's YAML metadata block and are
+/// skipped rather than parsed: nothing here reads it, and pretending to would
+/// be worse than ignoring it.
+///
+/// A row missing any of the three required columns is an ERROR naming the
+/// line, not a row quietly dropped. A crosswalk that silently loses rows
+/// during certification is the failure this whole module is about.
+pub fn parse_sssom(text: &str) -> anyhow::Result<Vec<Mapping>> {
+ let mut lines = text.lines().filter(|l| !l.trim_start().starts_with('#') && !l.trim().is_empty());
+ let header = lines.next().ok_or_else(|| anyhow::anyhow!("the mapping file is empty"))?;
+ let cols: Vec<&str> = header.split('\t').map(|c| c.trim()).collect();
+ let find = |name: &str| {
+ cols.iter().position(|c| *c == name).ok_or_else(|| {
+ anyhow::anyhow!("SSSOM requires a {name} column; this file has {cols:?}")
+ })
+ };
+ let (si, pi, oi) = (find("subject_id")?, find("predicate_id")?, find("object_id")?);
+ let mut out = Vec::new();
+ for (n, line) in lines.enumerate() {
+ let f: Vec<&str> = line.split('\t').collect();
+ let get = |i: usize| f.get(i).map(|s| s.trim()).unwrap_or("");
+ let (s, p, o) = (get(si), get(pi), get(oi));
+ if s.is_empty() || p.is_empty() || o.is_empty() {
+ anyhow::bail!(
+ "row {} is missing one of subject_id, predicate_id, object_id: {line:?}. \
+ Refused rather than dropped, because a crosswalk that loses rows while \
+ being certified is the defect this tool exists to find.",
+ n + 2
+ );
+ }
+ out.push(Mapping {
+ subject: strip(s),
+ predicate: expand(p),
+ object: strip(o),
+ });
+ }
+ Ok(out)
+}
+
+/// `skos:exactMatch` and the full IRI are the same predicate and must compare
+/// equal, or a file using the customary prefix would certify as something else.
+fn expand(p: &str) -> String {
+ let p = strip(p);
+ match p.strip_prefix("skos:") {
+ Some(local) => format!("{SKOS}{local}"),
+ None => p,
+ }
+}
+
+/// Certify a crosswalk from three files, as the command line hands them over.
+pub fn certify_files(
+ source_path: &str,
+ target_path: &str,
+ mapping_path: &str,
+) -> anyhow::Result<(serde_json::Value, String)> {
+ let source = Arc::new(GraphStore::new());
+ source.load_file(source_path)?;
+ let target = Arc::new(GraphStore::new());
+ target.load_file(target_path)?;
+ let mappings = parse_sssom(&std::fs::read_to_string(mapping_path)?)?;
+ let (rows, gaps) = certify(&source, &target, &mappings)?;
+ Ok((report(&rows, &gaps), to_sssom(&rows, &gaps)))
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The contradiction probe
+// ───────────────────────────────────────────────────────────────────────────
+
+/// Does translating the source's claims into the target CONTRADICT the target?
+///
+/// A different question from the match-type check above, and a sharper one. A
+/// downgrade says the two sides differ in granularity. A contradiction says
+/// they DISAGREE: the target's own axioms actively deny something the source
+/// asserts, once the mapping has carried it across. That is either a wrong
+/// mapping row or two ontologies that genuinely encode incompatible claims
+/// about the world, and a person has to decide which.
+///
+/// The probe is mechanical: build a scratch store holding the TARGET's axioms
+/// plus the translated source subsumptions, and reason over it. A clash means
+/// the target denies something the mapping carried in. This reuses the ten
+/// clash detectors in `reason::find_clashes` rather than inventing a second
+/// notion of contradiction, so what counts as a disagreement here is exactly
+/// what counts as one everywhere else in this engine.
+///
+/// The limit travels with the answer: those ten are the rules this engine
+/// LOOKS FOR, out of the seventeen in OWL 2 RL that conclude false. A clean
+/// probe is not a proof of compatibility.
+pub fn contradiction_probe(
+ source: &Arc<GraphStore>,
+ target_ttl: &str,
+ mappings: &[Mapping],
+) -> anyhow::Result<serde_json::Value> {
+ let sa = ancestors(source)?;
+ let fwd: BTreeMap<&str, &str> =
+ mappings.iter().map(|m| (m.subject.as_str(), m.object.as_str())).collect();
+
+ let mut carried = Vec::new();
+ let mut nt = String::new();
+ for (c, anc) in &sa {
+ let Some(ci) = fwd.get(c.as_str()) else { continue };
+ for a in anc {
+ let Some(ai) = fwd.get(a.as_str()) else { continue };
+ nt.push_str(&format!(
+ "<{ci}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <{ai}> .\n"
+ ));
+ carried.push(serde_json::json!({"subject": ci, "ancestor": ai, "from": c}));
+ }
+ }
+
+ let probe = Arc::new(GraphStore::new());
+ probe.load_turtle(target_ttl, None)?;
+ probe.load_turtle(&nt, None)?;
+ let out = Reasoner::run_full(&probe, "owl-rl", false, InferenceTarget::DefaultGraph, None)?;
+ let r: serde_json::Value = serde_json::from_str(&out)?;
+ let found = r["inconsistency"]["found"] == serde_json::Value::Bool(true);
+
+ Ok(serde_json::json!({
+ "carried": carried.len(),
+ "carried_claims": carried,
+ "contradicted": found,
+ "clashes": r["inconsistency"]["clashes"],
+ "by_rule": r["inconsistency"]["by_rule"],
+ "verdict": if found { "the_target_denies_what_the_mapping_carried" }
+ else { "no_contradiction_among_the_rules_this_engine_looks_for" },
+ "means": "the target's own axioms, plus the source's entailed subsumptions translated \
+ through the mapping, reasoned together. A contradiction here is a DISAGREEMENT \
+ and not a granularity gap: either the mapping row is wrong or the two \
+ ontologies encode incompatible claims, and a person has to decide which. A \
+ clean probe is NOT proof of compatibility: ten of the seventeen OWL 2 RL \
+ rules that conclude false are looked for, and nothing was checked about the \
+ other seven.",
+ }))
+}
diff --git a/src/lib.rs b/src/lib.rs
index b46419d0..4c89c5e8 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -25,6 +25,9 @@ pub mod config;
pub mod cq;
pub mod defects;
pub mod dl_refute;
+pub mod crosswalk;
+pub mod matcert;
+pub mod modules;
pub mod dlp;
pub mod drift;
pub mod dynamics;
diff --git a/src/matcert.rs b/src/matcert.rs
new file mode 100644
index 00000000..2e16f53f
--- /dev/null
+++ b/src/matcert.rs
@@ -0,0 +1,231 @@
+//! A numeric claim, and the two different things this repository can say
+//! about one.
+//!
+//! An ontology pipeline computes numbers: a similarity score, an alignment
+//! metric, a risk figure. Until now every one of those was handed on with the
+//! standing of an assertion, while the triples beside them carried
+//! certificates. This closes that, and it closes it in two pieces that are
+//! deliberately NOT merged, because they support different sentences.
+//!
+//! # 1. Certified, and it means what it says
+//!
+//! [`check`] writes a `matcert/1` file and runs `oo-matcert`, which recomputes
+//! every entry from the definition and, on acceptance, prints
+//! `MatCert.mul_of_check`. The token comes back through
+//! [`crate::verdict::CheckerRun::accepted_naming`] like every other certified
+//! word here, so it cannot be spelled without a run that earned it.
+//!
+//! Integers only. That is not a limitation to be lifted later, it is the
+//! condition under which the sentence is true.
+//!
+//! # 2. An opinion, with its bound printed
+//!
+//! [`freivalds`] multiplies both sides by random vectors and compares, which
+//! costs O(n²) per trial against O(n³) for the recomputation. Its soundness is
+//! probabilistic: a wrong product survives k trials with probability at most
+//! 2⁻ᵏ. Stating THAT needs probability theory, and `lean/` has no Mathlib by
+//! deliberate choice, so no theorem here covers it. It returns this engine's
+//! own word and prints the bound, and the word is not `certified`.
+//!
+//! # Floating point is refused, and this is the important paragraph
+//!
+//! [`freivalds_f64`] exists and reports a TOLERANCE rather than an equality.
+//! A proof over the reals says nothing about IEEE-754: rounding makes a
+//! correct product compare unequal and an incorrect one compare equal, and a
+//! certificate proved over ℝ and run on hardware is unsound silently. So the
+//! float path never reaches Lean, never names a theorem, and carries the
+//! tolerance it used in its own report. A caller who needs a guarantee
+//! converts to integers, pays O(n³), and gets one.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use crate::verdict::{CheckerBinary, CheckerRun, Certified};
+
+/// Row-major, rectangular. Ragged input is an error rather than padded.
+pub type IntMatrix = Vec<Vec<i64>>;
+
+fn rectangular(m: &IntMatrix, w: usize) -> bool {
+ m.iter().all(|r| r.len() == w)
+}
+
+/// The `matcert/1` file the Lean checker reads.
+pub fn write_cert(a: &IntMatrix, b: &IntMatrix, c: &IntMatrix, dir: &Path) -> anyhow::Result<PathBuf> {
+ let (m, p, n) = (a.len(), b.len(), c.first().map(|r| r.len()).unwrap_or(0));
+ if !rectangular(a, p) || !rectangular(b, n) || !rectangular(c, n) {
+ anyhow::bail!(
+ "ragged input: A must be {m}x{p}, B {p}x{n}, C {m}x{n}. Refused rather than padded, \
+ because a padded row is a different matrix and would be checked as one."
+ );
+ }
+ std::fs::create_dir_all(dir)?;
+ let path = dir.join("product.matcert");
+ let mut s = format!("matcert/1\ndims\t{m}\t{p}\t{n}\n");
+ for (tag, mat) in [("A", a), ("B", b), ("C", c)] {
+ for row in mat {
+ s.push_str(tag);
+ s.push('\t');
+ s.push_str(&row.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(" "));
+ s.push('\n');
+ }
+ }
+ std::fs::write(&path, s)?;
+ Ok(path)
+}
+
+/// Where `oo-matcert` is, by the rule every other checker here follows.
+pub fn find_checker() -> Option<PathBuf> {
+ if let Ok(p) = std::env::var("OO_MATCERT") {
+ let p = PathBuf::from(p);
+ return p.exists().then_some(p);
+ }
+ let built = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean/.lake/build/bin/oo-matcert");
+ built.exists().then_some(built)
+}
+
+/// What a run of the checker produced.
+pub enum Checked {
+ /// Accepted, with the token that proves a checker said so.
+ Accepted(Certified, String),
+ /// Ran and refused. Exit 1 is a rejection; 2 is a file it could not read.
+ Refused { exit: i32, output: String },
+ /// No checker on this machine. Never silently a pass.
+ Absent(String),
+}
+
+/// Write the certificate and run the checker over it.
+pub fn check(a: &IntMatrix, b: &IntMatrix, c: &IntMatrix, dir: &Path) -> anyhow::Result<Checked> {
+ let path = write_cert(a, b, c, dir)?;
+ let Some(bin) = find_checker() else {
+ return Ok(Checked::Absent(
+ "oo-matcert was not found. Build it with `lake build oo-matcert` in lean/, or set \
+ $OO_MATCERT. A missing checker is not an acceptance."
+ .to_string(),
+ ));
+ };
+ let mut cmd = Command::new(&bin);
+ cmd.arg(&path);
+ // The run names the file it is about (#164). It is the certificate, which
+ // is also the only thing on the command line, so the digest the token
+ // carries is a digest of exactly the claim that was checked.
+ let run = CheckerRun::spawn(&CheckerBinary::found_at(bin), cmd, &[&path])?;
+ match run.accepted_naming(&["MatCert.mul_of_check"]) {
+ Some(token) => Ok(Checked::Accepted(token, run.output())),
+ None => Ok(Checked::Refused { exit: run.exit(), output: run.output() }),
+ }
+}
+
+/// Freivalds over the integers: this engine's own opinion, with its bound.
+///
+/// `trials` random 0/1 vectors. A wrong product survives all of them with
+/// probability at most 2⁻ᵗʳⁱᵃˡˢ. Forty is the default elsewhere in the
+/// literature because 2⁻⁴⁰ is below the rate at which hardware flips a bit,
+/// which is the honest comparison: past that point the arithmetic is not the
+/// least reliable thing in the room.
+///
+/// Deterministic for a given seed, so a report can be reproduced.
+pub fn freivalds(a: &IntMatrix, b: &IntMatrix, c: &IntMatrix, trials: u32, seed: u64) -> serde_json::Value {
+ let m = a.len();
+ let p = b.len();
+ let n = c.first().map(|r| r.len()).unwrap_or(0);
+ if !rectangular(a, p) || !rectangular(b, n) || !rectangular(c, n) || c.len() != m {
+ return serde_json::json!({
+ "verdict": "not_checked_shapes_disagree",
+ "means": "the three matrices do not have compatible shapes, so there is no claim \
+ to check.",
+ });
+ }
+ let mut state = seed | 1;
+ let mut next = || {
+ // xorshift64*, so the report is reproducible from the seed.
+ state ^= state >> 12;
+ state ^= state << 25;
+ state ^= state >> 27;
+ state.wrapping_mul(0x2545_F491_4F6C_DD1D)
+ };
+ for _ in 0..trials {
+ let r: Vec<i64> = (0..n).map(|_| (next() & 1) as i64).collect();
+ // B·r, then A·(B·r)
+ let br: Vec<i64> = (0..p)
+ .map(|i| (0..n).map(|j| b[i][j].wrapping_mul(r[j])).fold(0i64, |s, v| s.wrapping_add(v)))
+ .collect();
+ let abr: Vec<i64> = (0..m)
+ .map(|i| (0..p).map(|k| a[i][k].wrapping_mul(br[k])).fold(0i64, |s, v| s.wrapping_add(v)))
+ .collect();
+ let cr: Vec<i64> = (0..m)
+ .map(|i| (0..n).map(|j| c[i][j].wrapping_mul(r[j])).fold(0i64, |s, v| s.wrapping_add(v)))
+ .collect();
+ if abr != cr {
+ return serde_json::json!({
+ "verdict": "refuted_by_this_engine",
+ "trials_run": trials,
+ "means": "a random vector separated A(Br) from Cr, so the claimed product is \
+ WRONG. A refutation from Freivalds is certain, unlike its \
+ acceptance: one counterexample settles it.",
+ });
+ }
+ }
+ serde_json::json!({
+ "verdict": "survived_freivalds",
+ "trials": trials,
+ "error_bound": format!("2^-{trials}"),
+ "seed": seed,
+ "means": "the claimed product survived every trial. This is an OPINION of this engine \
+ and not a certificate: the bound is probabilistic and no theorem in lean/ \
+ covers it, because stating it needs probability theory this development \
+ deliberately has no dependency for. For a certified answer run `check`, \
+ which recomputes every entry in O(n^3) and comes back with a token from a \
+ checker that named the statement it discharged. The name of that statement \
+ is deliberately NOT repeated here: it should appear only where it was \
+ earned, so that grepping for it finds acceptances and nothing else.",
+ })
+}
+
+/// The same idea over doubles, and the reason it can never be more than a
+/// smoke test.
+///
+/// Reports agreement within a TOLERANCE, never equality. Two implementations
+/// of the same correct product disagree in the last bits, and a wrong one can
+/// agree inside any tolerance you pick. The tolerance travels in the report so
+/// a reader can judge it rather than inherit it.
+pub fn freivalds_f64(
+ a: &[Vec<f64>],
+ b: &[Vec<f64>],
+ c: &[Vec<f64>],
+ trials: u32,
+ tolerance: f64,
+) -> serde_json::Value {
+ let m = a.len();
+ let p = b.len();
+ let n = c.first().map(|r| r.len()).unwrap_or(0);
+ let mut worst = 0.0f64;
+ let mut state = 0x9E37_79B9_7F4A_7C15u64;
+ for _ in 0..trials {
+ let r: Vec<f64> = (0..n)
+ .map(|_| {
+ state ^= state >> 12;
+ state ^= state << 25;
+ state ^= state >> 27;
+ (state & 1) as f64
+ })
+ .collect();
+ for i in 0..m {
+ let br: Vec<f64> =
+ (0..p).map(|k| (0..n).map(|j| b[k][j] * r[j]).sum::<f64>()).collect();
+ let abr: f64 = (0..p).map(|k| a[i][k] * br[k]).sum();
+ let cr: f64 = (0..n).map(|j| c[i][j] * r[j]).sum();
+ worst = worst.max((abr - cr).abs());
+ }
+ }
+ serde_json::json!({
+ "verdict": if worst <= tolerance { "within_tolerance" } else { "outside_tolerance" },
+ "worst_absolute_difference": worst,
+ "tolerance": tolerance,
+ "trials": trials,
+ "means": "AGREEMENT WITHIN A TOLERANCE, never equality, and never a certificate. A \
+ proof over the real numbers says nothing about IEEE-754: rounding makes a \
+ correct product compare unequal and an incorrect one compare equal. This \
+ path never reaches Lean and names no theorem. If you need a guarantee, \
+ convert to integers and use `check`.",
+ })
+}
diff --git a/src/modules.rs b/src/modules.rs
new file mode 100644
index 00000000..2b12845f
--- /dev/null
+++ b/src/modules.rs
@@ -0,0 +1,138 @@
+//! Many small graphs that reason separately, and a fact promoted when enough
+//! of them agree.
+//!
+//! One global graph forces every context to be consistent with every other at
+//! once. That is the qualification problem in its practical form: birds fly,
+//! penguins do not, and a single graph holding both is inconsistent unless
+//! somebody writes the exception into the rule. The usual answers are
+//! non-monotonic and give up machine-checkability.
+//!
+//! This gives up neither, by refusing the premise. Each module is its own
+//! store and reasons ALONE. Within one module it is still ordinary monotonic
+//! OWL 2 RL, so every module's entailments are exactly as checkable as they
+//! were before, and `onto_reason --certificate` still produces a certificate
+//! `oo-cert` accepts. What changes is that two modules are ALLOWED to
+//! disagree: that is a fact about them, queryable, rather than an error state.
+//!
+//! "True everywhere" then stops being an assumption baked into the schema and
+//! becomes something a fact has to earn: entailed independently in at least
+//! `k` of `n` modules.
+//!
+//! # What this is not
+//!
+//! It is not a consensus protocol and there is no cryptography in it. `k` of
+//! `n` modules agreeing is a COUNT, and the report says so. Ten modules that
+//! all copied the same mistaken axiom agree ten times; agreement is evidence
+//! about independence only to the degree the modules really are independent,
+//! which this cannot check and does not claim to.
+//!
+//! It also inherits every limit of the rule table underneath. A fact no rule
+//! fires on is entailed in zero modules and is not "disagreed about", it is
+//! unseen. `onto_dlp_boundary` is the tool that says which.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+use crate::graph::GraphStore;
+use crate::reason::{InferenceTarget, Reasoner};
+
+/// One context: a name and the axioms that hold in it.
+#[derive(Clone, Debug)]
+pub struct Module {
+ pub name: String,
+ pub ttl: String,
+}
+
+/// Everything one module entails, on its own.
+fn entailed(m: &Module) -> anyhow::Result<BTreeSet<String>> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(&m.ttl, None)?;
+ // materialize, because the question is what the module ENTAILS and not
+ // what its author wrote down.
+ Reasoner::run_full(&g, "owl-rl", true, InferenceTarget::DefaultGraph, None)?;
+ let nt = g.snapshot("ntriples")?;
+ Ok(nt
+ .lines()
+ .map(|l| l.trim())
+ .filter(|l| !l.is_empty() && !l.starts_with('#'))
+ // Blank nodes are labelled per store, so the same structure in two
+ // modules would compare unequal for a reason that has nothing to do
+ // with agreement. Counted separately would be worse than not counted.
+ .filter(|l| !l.contains("_:"))
+ .map(|l| l.to_string())
+ .collect())
+}
+
+/// Reason every module alone, then promote what enough of them agree on.
+pub fn distributed(modules: &[Module], k: usize) -> anyhow::Result<serde_json::Value> {
+ if modules.is_empty() {
+ anyhow::bail!("no modules: there is nothing for a threshold to count");
+ }
+ if k == 0 || k > modules.len() {
+ anyhow::bail!(
+ "a threshold of {k} over {} modules is not a question that has an answer",
+ modules.len()
+ );
+ }
+
+ let mut per: Vec<(String, BTreeSet<String>)> = Vec::new();
+ for m in modules {
+ per.push((m.name.clone(), entailed(m)?));
+ }
+
+ // Who entails what.
+ let mut who: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
+ for (name, set) in &per {
+ for t in set {
+ who.entry(t.as_str()).or_default().push(name.as_str());
+ }
+ }
+
+ let mut promoted = Vec::new();
+ let mut contested = Vec::new();
+ for (t, names) in &who {
+ let row = serde_json::json!({
+ "triple": t,
+ "agreed": names.len(),
+ "modules": names,
+ });
+ if names.len() >= k {
+ promoted.push(row);
+ } else {
+ contested.push(row);
+ }
+ }
+
+ Ok(serde_json::json!({
+ "modules": per.iter().map(|(n, s)| serde_json::json!({
+ "name": n, "entails": s.len(),
+ })).collect::<Vec<_>>(),
+ "threshold": k,
+ "promoted": promoted.len(),
+ "contested": contested.len(),
+ "promoted_facts": promoted,
+ "contested_facts": contested,
+ "verdict": "agreed_by_k_of_n_modules",
+ "means": "each module was reasoned ALONE under OWL 2 RL, in its own store, so no \
+ module's axioms answered another's questions. A promoted fact is one at \
+ least k modules entailed independently. This is a COUNT and not a proof: \
+ modules that copied the same mistaken axiom agree just as loudly, and \
+ agreement is evidence only to the degree the modules really are \
+ independent, which nothing here checks. A contested fact is not an error; \
+ it is the disagreement made visible, which one graph would have hidden by \
+ refusing to hold both.",
+ }))
+}
+
+/// The promoted facts as N-Triples, ready to load as a module of their own.
+pub fn promoted_ntriples(report: &serde_json::Value) -> String {
+ report["promoted_facts"]
+ .as_array()
+ .map(|rows| {
+ rows.iter()
+ .filter_map(|r| r["triple"].as_str())
+ .map(|t| format!("{t}\n"))
+ .collect::<String>()
+ })
+ .unwrap_or_default()
+}
diff --git a/tests/certified_claims_asset_test.rs b/tests/certified_claims_asset_test.rs
new file mode 100644
index 00000000..63d02ff9
--- /dev/null
+++ b/tests/certified_claims_asset_test.rs
@@ -0,0 +1,168 @@
+//! The figure says what a fresh run says, or it is not a figure.
+//!
+//! `docs/assets/certified-claims.svg` shows counts, predicates, module names
+//! and a theorem. Every one of those is read out of a real run by the
+//! generator and none is typed into it, but that is a property of the script
+//! and not of the committed file: the script could be right and the SVG stale.
+//!
+//! So these re-run the tools against the same committed fixtures and compare
+//! with what the drawing says. A figure that drifts from the code under it is
+//! worse than no figure, because it carries the authority of having been
+//! generated.
+
+mod common;
+
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use open_ontologies::crosswalk::{certify, parse_sssom};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::modules::{distributed, Module};
+
+fn repo() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn claims() -> PathBuf {
+ repo().join("docs").join("assets").join("claims")
+}
+
+fn svg(lang: &str) -> String {
+ let name = if lang == "zh" { "certified-claims.zh-CN.svg" } else { "certified-claims.svg" };
+ std::fs::read_to_string(repo().join("docs").join("assets").join(name))
+ .unwrap_or_else(|e| panic!("read {name}: {e}"))
+}
+
+fn store(rel: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_file(&claims().join(rel).display().to_string()).expect("fixture loads");
+ g
+}
+
+#[test]
+fn the_crosswalk_panel_matches_a_fresh_run() {
+ let maps = parse_sssom(&std::fs::read_to_string(claims().join("mapping.tsv")).unwrap())
+ .expect("the fixture is valid SSSOM");
+ let (rows, gaps) = certify(&store("ies-side.ttl"), &store("hqdm-side.ttl"), &maps)
+ .expect("certifies");
+
+ let s = svg("en");
+ // Every subject, with the predicate the run supports, must appear as the
+ // drawing shows it.
+ for r in &rows {
+ let subject = r.mapping.subject.rsplit('/').next().unwrap();
+ assert!(s.contains(subject), "the figure does not name {subject}");
+ assert!(
+ s.contains(&format!("exactMatch → {}", r.supported)),
+ "a fresh run supports {} for {subject} and the figure does not show it",
+ r.supported
+ );
+ }
+ let downgraded = rows.iter().filter(|r| r.downgraded).count();
+ assert_eq!(downgraded, 2, "the fixture is built to produce two downgrades");
+ assert!(
+ s.contains(&format!("{} term the crosswalk does not carry", gaps.len()))
+ || s.contains(&format!("{} terms the crosswalk does not carry", gaps.len())),
+ "the gap count in the figure disagrees with a fresh run ({})",
+ gaps.len()
+ );
+}
+
+#[test]
+fn the_modules_panel_matches_a_fresh_run() {
+ let mods: Vec<Module> = [("birds", "mod-birds.ttl"), ("penguins", "mod-penguins.ttl"),
+ ("field_guide", "mod-guide.ttl")]
+ .iter()
+ .map(|(n, f)| Module {
+ name: n.to_string(),
+ ttl: std::fs::read_to_string(claims().join(f)).expect("fixture"),
+ })
+ .collect();
+ let js = distributed(&mods, 2).expect("runs");
+ let s = svg("en");
+
+ for m in js["modules"].as_array().unwrap() {
+ let name = m["name"].as_str().unwrap();
+ let n = m["entails"].as_u64().unwrap();
+ assert!(s.contains(name), "the figure does not name the module {name}");
+ assert!(
+ s.contains(&format!("entails {n}")),
+ "a fresh run has {name} entailing {n}, which the figure does not show"
+ );
+ }
+ let promoted = js["promoted"].as_u64().unwrap();
+ assert!(
+ s.contains(&format!("{promoted} fact entailed in 2 of 3 modules")),
+ "the promoted count drifted from a fresh run ({promoted})"
+ );
+ let contested = js["contested"].as_u64().unwrap();
+ assert!(
+ s.contains(&format!("{contested} held by fewer")),
+ "the contested count drifted from a fresh run ({contested})"
+ );
+}
+
+#[test]
+fn the_numeric_panel_names_the_theorem_the_checker_printed() {
+ if common::skip_unless(
+ open_ontologies::matcert::find_checker().is_some(),
+ "the numeric checker (oo-matcert)",
+ "run `lake build oo-matcert` in lean/",
+ ) {
+ return;
+ }
+ // Run the committed certificate through the real binary.
+ let bin = open_ontologies::matcert::find_checker().unwrap();
+ let out = std::process::Command::new(bin)
+ .arg(claims().join("product.matcert"))
+ .output()
+ .expect("runs");
+ assert_eq!(out.status.code(), Some(0), "the committed certificate must check");
+ let js: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).expect("JSON");
+ let theorem = js["theorem"].as_str().expect("an accepted run names its theorem");
+
+ let s = svg("en");
+ assert!(
+ s.contains(theorem),
+ "the figure shows a theorem the checker did not print. The name in a drawing must \
+ come from a run: {theorem}"
+ );
+ // And only there. The other two rows are opinions and the figure says so.
+ assert_eq!(
+ s.matches(theorem).count(),
+ 1,
+ "the theorem name appears more than once, so the figure is lending it to a row that \
+ did not earn it"
+ );
+}
+
+#[test]
+fn both_languages_draw_the_same_numbers() {
+ let en = svg("en");
+ let zh = svg("zh");
+ // The LABEL is translated and the NUMBER is not, which is the whole point:
+ // a figure that shared its prose would be untranslated, and one that
+ // differed in its counts would be two different claims.
+ for n in [3u32, 4] {
+ assert!(en.contains(&format!("entails {n}")), "the English figure lost 'entails {n}'");
+ assert!(zh.contains(&format!("蕴涵 {n}")), "the Chinese figure lost its count {n}");
+ }
+ assert!(zh.contains("MatCert.mul_of_check"), "the theorem is a name, not a translation");
+ // A figure that lost its Chinese text would still pass the numbers, so
+ // check it is actually translated.
+ assert!(zh.contains("对照表"), "the Chinese figure is not in Chinese");
+}
+
+#[test]
+fn the_figure_is_well_formed_and_carries_no_placeholders() {
+ for lang in ["en", "zh"] {
+ let s = svg(lang);
+ assert!(s.starts_with("<svg"), "{lang}: not an SVG");
+ assert!(s.trim_end().ends_with("</svg>"), "{lang}: truncated");
+ assert!(
+ !s.contains("{n}") && !s.contains("{k}") && !s.contains("{t}"),
+ "{lang}: an unsubstituted placeholder reached the file"
+ );
+ }
+}
diff --git a/tests/crosswalk_certify_test.rs b/tests/crosswalk_certify_test.rs
new file mode 100644
index 00000000..91f77fe4
--- /dev/null
+++ b/tests/crosswalk_certify_test.rs
@@ -0,0 +1,219 @@
+//! A crosswalk's match TYPE is a claim, and this is the thing that checks it.
+//!
+//! `src/align.rs` picks `exactMatch` when label similarity exceeds 0.8 and
+//! `closeMatch` otherwise. That is a guess from surface features, and once it
+//! is written into a mapping file it is indistinguishable from a fact. Every
+//! crosswalk export in this space has that property.
+//!
+//! The case this repository already measured is the expensive one: the Foundry
+//! crosswalk found IES 5.0.3 losing 202 `rdfs:subPropertyOf` axioms against
+//! HQDM. A row asserting `exactMatch` across a gap like that is not slightly
+//! wrong; it claims two concepts are interchangeable when one side cannot
+//! express what the other says.
+//!
+//! # The direction is pinned by a worked example, not by a docstring
+//!
+//! `skos:broadMatch` is a sub-property of `skos:broader`, and `A skos:broader
+//! B` means **B is the broader concept**. So when the subject is the more
+//! specific of the two, the correct predicate is `broadMatch`. Getting that
+//! backwards would silently invert every downgrade this tool produces, which
+//! is worse than not checking at all, so
+//! `the_skos_direction_is_pinned_by_a_worked_example` asserts it on a
+//! three-class hierarchy a reader can check by hand.
+
+use std::sync::Arc;
+
+use open_ontologies::crosswalk::{certify, report, to_sssom, Mapping};
+use open_ontologies::graph::GraphStore;
+
+const P: &str = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n";
+
+/// The richer side. `Employee` is under `Person`, and `Person` under `Agent`.
+/// `Contractor` is deliberately left out of every mapping below, so there is
+/// always something for the gap report to find.
+const SOURCE: &str = "@prefix s: <http://src.example/> .\n\
+ s:Employee a owl:Class ; rdfs:subClassOf s:Person .\n\
+ s:Contractor a owl:Class ; rdfs:subClassOf s:Person .\n\
+ s:Person a owl:Class ; rdfs:subClassOf s:Agent .\n\
+ s:Agent a owl:Class .\n";
+
+/// The poorer side. It HAS a `Person`, but it does not put `Employee` under
+/// it: `Employee` is only an `Agent`. So the target says strictly less.
+const TARGET: &str = "@prefix t: <http://tgt.example/> .\n\
+ t:Employee a owl:Class ; rdfs:subClassOf t:Agent .\n\
+ t:Person a owl:Class ; rdfs:subClassOf t:Agent .\n\
+ t:Agent a owl:Class .\n";
+
+fn store(ttl: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(&format!("{P}{ttl}"), None).expect("turtle parses");
+ g
+}
+
+fn m(s: &str, p: &str, o: &str) -> Mapping {
+ Mapping { subject: s.to_string(), predicate: p.to_string(), object: o.to_string() }
+}
+
+const EXACT: &str = "http://www.w3.org/2004/02/skos/core#exactMatch";
+
+fn full_mapping() -> Vec<Mapping> {
+ vec![
+ m("http://src.example/Employee", EXACT, "http://tgt.example/Employee"),
+ m("http://src.example/Person", EXACT, "http://tgt.example/Person"),
+ m("http://src.example/Agent", EXACT, "http://tgt.example/Agent"),
+ ]
+}
+
+#[test]
+fn the_skos_direction_is_pinned_by_a_worked_example() {
+ // Worked by hand: s:Employee is under Person AND Agent. t:Employee is
+ // under Agent only. So the SUBJECT is the more specific concept, which
+ // means subject ⊑ object, which in SKOS is `subject broadMatch object`
+ // because broadMatch points AT the broader term.
+ let (rows, _) = certify(&store(SOURCE), &store(TARGET), &full_mapping()).expect("certifies");
+ let emp = rows.iter().find(|r| r.mapping.subject.ends_with("Employee")).expect("row");
+ assert_eq!(
+ emp.supported, "broadMatch",
+ "the subject is the more specific term, so the object is BROADER and the predicate \
+ points at it. If this ever reads narrowMatch the direction has been inverted and \
+ every downgrade this tool produces is backwards: {}",
+ emp.because
+ );
+ assert!(emp.downgraded, "the file claimed exactMatch, which the entailments do not support");
+}
+
+#[test]
+fn a_truthful_exact_match_is_upheld() {
+ // s:Person is under Agent; t:Person is under Agent. Same, once translated.
+ let (rows, _) = certify(&store(SOURCE), &store(TARGET), &full_mapping()).expect("certifies");
+ let p = rows.iter().find(|r| r.mapping.subject.ends_with("/Person")).expect("row");
+ assert_eq!(p.supported, "exactMatch", "{}", p.because);
+ assert!(!p.downgraded, "a claim the evidence supports must not be reported as downgraded");
+}
+
+#[test]
+fn an_ancestor_the_target_cannot_express_forces_a_related_match() {
+ // THE FOUNDRY CASE. The mapping carries no image for s:Person, so the
+ // target cannot express something the source says about s:Employee. No
+ // comparison of the two is defensible beyond relatedMatch.
+ let partial = vec![
+ m("http://src.example/Employee", EXACT, "http://tgt.example/Employee"),
+ m("http://src.example/Agent", EXACT, "http://tgt.example/Agent"),
+ ];
+ let (rows, _) = certify(&store(SOURCE), &store(TARGET), &partial).expect("certifies");
+ let emp = rows.iter().find(|r| r.mapping.subject.ends_with("Employee")).expect("row");
+ assert_eq!(emp.supported, "relatedMatch", "{}", emp.because);
+ assert!(
+ emp.untranslatable.iter().any(|u| u.ends_with("/Person")),
+ "the report must NAME the ancestor that has no image, or a reader cannot act on it: \
+ {:?}",
+ emp.untranslatable
+ );
+ assert!(emp.because.contains("no image"), "and say so in words: {}", emp.because);
+}
+
+#[test]
+fn a_source_term_with_no_row_is_reported_as_a_gap() {
+ // The half that vanishes from every crosswalk export.
+ let one = vec![m("http://src.example/Agent", EXACT, "http://tgt.example/Agent")];
+ let (_, gaps) = certify(&store(SOURCE), &store(TARGET), &one).expect("certifies");
+ let terms: Vec<&str> = gaps.iter().map(|g| g.term.as_str()).collect();
+ assert!(
+ terms.iter().any(|t| t.ends_with("Employee"))
+ && terms.iter().any(|t| t.ends_with("/Person"))
+ && terms.iter().any(|t| t.ends_with("Contractor")),
+ "every unmapped source class must be listed, not silently absent: {terms:?}"
+ );
+ assert!(gaps.iter().all(|g| !g.reason.is_empty()), "a gap without a reason is a blank line");
+}
+
+#[test]
+fn the_output_is_valid_sssom_and_carries_the_supported_predicate() {
+ let (rows, gaps) = certify(&store(SOURCE), &store(TARGET), &full_mapping()).expect("certifies");
+ let tsv = to_sssom(&rows, &gaps);
+ let header = tsv.lines().next().expect("a header");
+ for col in ["subject_id", "predicate_id", "object_id", "mapping_justification"] {
+ assert!(header.contains(col), "SSSOM requires {col}: {header}");
+ }
+ // The predicate column must carry what is SUPPORTED. A file still saying
+ // exactMatch after this ran would be worse than no check at all, because
+ // it would now carry a certification column vouching for it.
+ let emp = tsv.lines().find(|l| l.contains("src.example/Employee")).expect("the row");
+ assert!(emp.contains("skos:broadMatch"), "the supported predicate belongs in the file: {emp}");
+ assert!(emp.contains(EXACT), "and the original claim is kept, so the change is auditable");
+ assert!(
+ tsv.lines().any(|l| l.contains("sssom:NoMapping")),
+ "the gaps travel in the same file; that is the point of them"
+ );
+}
+
+#[test]
+fn the_report_does_not_claim_a_word_it_has_not_earned() {
+ // The laundering guard, in the pattern lean_horn_certificate_test set. No
+ // Lean checker has a theorem about SKOS match types, so nothing here may
+ // wear a checker's word.
+ let (rows, gaps) = certify(&store(SOURCE), &store(TARGET), &full_mapping()).expect("certifies");
+ let js = report(&rows, &gaps).to_string();
+ for forbidden in [
+ "certificate_sound",
+ "validate_spec",
+ "unsat_of_check",
+ "\"verdict\":\"certified\"",
+ "machine-checked",
+ ] {
+ assert!(!js.contains(forbidden), "the report claims {forbidden}, which nothing proved");
+ }
+ assert!(js.contains("checked_by_this_engine"), "it must say whose opinion this is");
+ assert!(js.contains("29 of OWL 2 RL's 78 rules"), "and how much of the profile it read");
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The contradiction probe: a disagreement, not a granularity gap
+// ───────────────────────────────────────────────────────────────────────────
+
+/// A target that actively DENIES what the mapping carries in.
+///
+/// `t:Employee` and `t:Machine` are disjoint here. The mapping will say
+/// `s:Employee` is `t:Machine`, and the source entails `s:Employee ⊑ s:Person`
+/// which maps to `t:Employee`. So the probe carries in `t:Machine ⊑
+/// t:Employee`, and the target's own disjointness denies it.
+const HOSTILE_TARGET: &str = "@prefix t: <http://tgt.example/> .\n\
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
+ t:Employee a owl:Class ; rdfs:subClassOf t:Agent ; owl:disjointWith t:Machine .\n\
+ t:Machine a owl:Class .\n\
+ t:Person a owl:Class ; rdfs:subClassOf t:Agent .\n\
+ t:Agent a owl:Class .\n\
+ t:m1 a t:Machine , t:Employee .\n";
+
+#[test]
+fn a_target_that_denies_what_the_mapping_carries_is_reported_as_a_contradiction() {
+ use open_ontologies::crosswalk::contradiction_probe;
+ let bad = vec![
+ m("http://src.example/Employee", EXACT, "http://tgt.example/Machine"),
+ m("http://src.example/Person", EXACT, "http://tgt.example/Employee"),
+ m("http://src.example/Agent", EXACT, "http://tgt.example/Agent"),
+ ];
+ let js = contradiction_probe(&store(SOURCE), HOSTILE_TARGET, &bad).expect("probes");
+ assert_eq!(js["contradicted"], true, "the target denies the carried claim: {js}");
+ assert!(
+ js["carried"].as_u64().unwrap_or(0) > 0,
+ "and the probe must say WHAT it carried across, or the result is unactionable: {js}"
+ );
+ assert_eq!(js["verdict"], "the_target_denies_what_the_mapping_carried");
+}
+
+#[test]
+fn a_probe_that_finds_nothing_says_only_that_and_names_its_limit() {
+ use open_ontologies::crosswalk::contradiction_probe;
+ let target_ttl = format!("{P}{TARGET}");
+ let js = contradiction_probe(&store(SOURCE), &target_ttl, &full_mapping()).expect("probes");
+ assert_eq!(js["contradicted"], false, "{js}");
+ assert_eq!(js["verdict"], "no_contradiction_among_the_rules_this_engine_looks_for");
+ // A clean probe that read as "compatible" would be the laundering this
+ // repository exists to refuse.
+ let means = js["means"].as_str().unwrap_or_default();
+ assert!(means.contains("NOT proof of compatibility"), "{means}");
+ assert!(means.contains("ten of the seventeen"), "it must state how much it looked at: {means}");
+}
diff --git a/tests/lean_certificate_test.rs b/tests/lean_certificate_test.rs
index e3a18d8e..da155428 100644
--- a/tests/lean_certificate_test.rs
+++ b/tests/lean_certificate_test.rs
@@ -302,6 +302,12 @@ fn corpus() -> Vec<PathBuf> {
// and the same treatment as `tests/fixtures/horn-coverage/`.
// `tests/clash_detector_coverage_test.rs` asserts this exclusion is still here.
.filter(|p| !p.starts_with("tests/fixtures/clash-coverage/"))
+ // `docs/assets/claims/` holds the tiny ontologies the certified-claims
+ // figure is drawn from. They exist to demonstrate a downgrade and a
+ // disagreement, not to be ontologies, and counted as corpus they would
+ // dilute a measurement of what this repository actually ships. Same
+ // reasoning and same treatment as `tests/fixtures/horn-coverage/`.
+ .filter(|p| !p.starts_with("docs/assets/claims/"))
.filter(|p| !SKIP_DIRS.iter().any(|d| p.split('/').any(|seg| seg == *d)))
.map(|p| repo().join(p))
.collect();
diff --git a/tests/matcert_numeric_test.rs b/tests/matcert_numeric_test.rs
new file mode 100644
index 00000000..d01a20dd
--- /dev/null
+++ b/tests/matcert_numeric_test.rs
@@ -0,0 +1,155 @@
+//! A numeric claim, and the two different sentences this repository can say
+//! about one.
+//!
+//! The split is the whole design and these tests exist to keep it. Recomputing
+//! over the integers earns `MatCert.mul_of_check` and the word `certified`.
+//! Freivalds is O(n²) and probabilistic, so it earns an OPINION with its bound
+//! printed. Floating point earns a tolerance and nothing else, because a proof
+//! over the reals says nothing about IEEE-754.
+//!
+//! If those three ever collapse into one word, the cheapest of them will be
+//! read as the strongest, which is exactly the laundering this repository is
+//! built to refuse.
+
+mod common;
+
+use std::path::PathBuf;
+
+use open_ontologies::matcert::{check, freivalds, freivalds_f64, write_cert, Checked, IntMatrix};
+
+fn dir(tag: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("oo-matcert-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+/// [[1,2],[3,4]] × [[5,6],[7,8]] = [[19,22],[43,50]], by hand.
+fn a() -> IntMatrix { vec![vec![1, 2], vec![3, 4]] }
+fn b() -> IntMatrix { vec![vec![5, 6], vec![7, 8]] }
+fn c_right() -> IntMatrix { vec![vec![19, 22], vec![43, 50]] }
+fn c_wrong() -> IntMatrix { vec![vec![19, 22], vec![43, 51]] }
+
+fn skip() -> bool {
+ common::skip_unless(
+ open_ontologies::matcert::find_checker().is_some(),
+ "the numeric checker (oo-matcert)",
+ "run `lake build oo-matcert` in lean/, or point $OO_MATCERT at a built one",
+ )
+}
+
+#[test]
+fn a_correct_product_earns_the_theorem() {
+ if skip() {
+ return;
+ }
+ match check(&a(), &b(), &c_right(), &dir("right")).expect("runs") {
+ Checked::Accepted(token, out) => {
+ assert_eq!(token.theorem(), "MatCert.mul_of_check");
+ assert!(out.contains("product_checked"), "{out}");
+ }
+ Checked::Refused { exit, output } => panic!("refused a correct product: {exit} {output}"),
+ Checked::Absent(w) => panic!("{w}"),
+ }
+}
+
+#[test]
+fn one_wrong_entry_is_refused_and_names_no_theorem() {
+ if skip() {
+ return;
+ }
+ match check(&a(), &b(), &c_wrong(), &dir("wrong")).expect("runs") {
+ Checked::Refused { exit, output } => {
+ assert_eq!(exit, 1, "a rejection is exit 1: {output}");
+ assert!(
+ !output.contains("MatCert.mul_of_check"),
+ "a refusal must not name the theorem it did not discharge: {output}"
+ );
+ }
+ Checked::Accepted(..) => panic!("accepted a product that is wrong in one entry"),
+ Checked::Absent(w) => panic!("{w}"),
+ }
+}
+
+#[test]
+fn ragged_input_is_refused_before_anything_is_written() {
+ let ragged: IntMatrix = vec![vec![1, 2], vec![3]];
+ let e = write_cert(&ragged, &b(), &c_right(), &dir("ragged")).expect_err("refused");
+ assert!(
+ e.to_string().contains("padded"),
+ "the refusal has to say why padding would be wrong: {e}"
+ );
+}
+
+#[test]
+fn freivalds_refutes_a_wrong_product_with_certainty() {
+ // A refutation from Freivalds is certain even though its acceptance is not:
+ // one separating vector settles it.
+ let js = freivalds(&a(), &b(), &c_wrong(), 40, 7);
+ assert_eq!(js["verdict"], "refuted_by_this_engine", "{js}");
+ assert!(js["means"].as_str().unwrap().contains("certain"), "{js}");
+}
+
+#[test]
+fn freivalds_accepts_with_a_bound_and_never_with_a_theorem() {
+ let js = freivalds(&a(), &b(), &c_right(), 40, 7);
+ assert_eq!(js["verdict"], "survived_freivalds");
+ assert_eq!(js["error_bound"], "2^-40", "the bound belongs in the report, not a docstring");
+ let s = js.to_string();
+ // The theorem name appears only where it was earned, so a grep for it
+ // finds acceptances and nothing else.
+ assert!(!s.contains("MatCert.mul_of_check"), "no theorem covers the probabilistic path");
+ // The VERDICT is what a consumer reads and switches on. It is the field
+ // that must not wear a certified word; the prose around it is free to say
+ // "not a certificate", and has to.
+ let verdict = js["verdict"].as_str().unwrap();
+ for earned in ["certified", "checked", "proved", "product_checked"] {
+ assert_ne!(verdict, earned, "the probabilistic verdict must not be a word a proof earns");
+ }
+ assert!(js["means"].as_str().unwrap().contains("not a certificate"), "{s}");
+ assert!(s.contains("OPINION of this engine"), "it must say whose word this is");
+}
+
+#[test]
+fn the_same_seed_gives_the_same_answer() {
+ // A report nobody can reproduce is not evidence.
+ let x = freivalds(&a(), &b(), &c_right(), 12, 99);
+ let y = freivalds(&a(), &b(), &c_right(), 12, 99);
+ assert_eq!(x, y);
+}
+
+#[test]
+fn the_float_path_reports_a_tolerance_and_refuses_the_word() {
+ let af = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
+ let bf = vec![vec![5.0, 6.0], vec![7.0, 8.0]];
+ let cf = vec![vec![19.0, 22.0], vec![43.0, 50.0]];
+ let js = freivalds_f64(&af, &bf, &cf, 8, 1e-9);
+ assert_eq!(js["verdict"], "within_tolerance", "{js}");
+ assert!(js["tolerance"].is_number(), "the tolerance travels with the answer: {js}");
+ let s = js.to_string();
+ assert!(!s.contains("MatCert.mul_of_check") && !s.contains("certified"), "{s}");
+ assert!(
+ s.contains("says nothing about IEEE-754"),
+ "the reason floating point cannot be certified has to be IN the report: {s}"
+ );
+}
+
+#[test]
+fn the_three_verdicts_are_three_different_words() {
+ // The guard on the whole design. If the cheap check and the proved one
+ // ever share a word, the cheap one will be read as the strong one.
+ let certified_path = check(&a(), &b(), &c_right(), &dir("words"));
+ let probabilistic = freivalds(&a(), &b(), &c_right(), 8, 3).to_string();
+ let floating = freivalds_f64(
+ &[vec![1.0]], &[vec![1.0]], &[vec![1.0]], 2, 1e-9,
+ ).to_string();
+
+ assert!(probabilistic.contains("survived_freivalds"));
+ assert!(floating.contains("within_tolerance"));
+ assert!(!probabilistic.contains("within_tolerance"));
+ assert!(!floating.contains("survived_freivalds"));
+ if let Ok(Checked::Accepted(_, out)) = certified_path {
+ assert!(out.contains("product_checked"));
+ assert!(!out.contains("survived_freivalds") && !out.contains("within_tolerance"));
+ }
+}
diff --git a/tests/modules_k_of_n_test.rs b/tests/modules_k_of_n_test.rs
new file mode 100644
index 00000000..e3dcfe4c
--- /dev/null
+++ b/tests/modules_k_of_n_test.rs
@@ -0,0 +1,128 @@
+//! Modules that reason alone, and facts that earn "true everywhere".
+//!
+//! The premise is not assumed, it is DEMONSTRATED by
+//! `the_merged_graph_is_inconsistent_where_the_modules_are_not`. Birds fly.
+//! Penguins are birds and do not fly. In one graph that is a contradiction and
+//! the engine finds it. In two modules it is two consistent contexts that
+//! disagree, each still ordinary monotonic OWL 2 RL, each still carrying a
+//! certificate `oo-cert` accepts.
+//!
+//! That is the whole argument for this module, so a test has to make it rather
+//! than a docstring asserting it.
+
+use open_ontologies::modules::{distributed, promoted_ntriples, Module};
+
+const P: &str = "@prefix : <http://ex.org/> .\n\
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n";
+
+/// Birds fly, and tweety is a bird.
+const BIRDS: &str = ":Bird rdfs:subClassOf :Flier .\n:tweety a :Bird .\n";
+
+/// Penguins are birds and are not fliers, and pingu is one. On its own this is
+/// perfectly consistent: nothing in HERE says birds fly.
+const PENGUINS: &str =
+ ":Penguin rdfs:subClassOf :Bird .\n:Penguin owl:disjointWith :Flier .\n:pingu a :Penguin .\n";
+
+/// A third context that happens to agree with the first about birds.
+const FIELD_GUIDE: &str = ":Bird rdfs:subClassOf :Flier .\n:robin a :Bird .\n";
+
+fn m(name: &str, body: &str) -> Module {
+ Module { name: name.to_string(), ttl: format!("{P}{body}") }
+}
+
+fn three() -> Vec<Module> {
+ vec![m("birds", BIRDS), m("penguins", PENGUINS), m("field_guide", FIELD_GUIDE)]
+}
+
+#[test]
+fn the_merged_graph_is_inconsistent_where_the_modules_are_not() {
+ use std::sync::Arc;
+ use open_ontologies::graph::GraphStore;
+ use open_ontologies::reason::{InferenceTarget, Reasoner};
+
+ // One graph holding both contexts.
+ let merged = Arc::new(GraphStore::new());
+ merged.load_turtle(&format!("{P}{BIRDS}{PENGUINS}"), None).expect("parses");
+ let out =
+ Reasoner::run_full(&merged, "owl-rl", false, InferenceTarget::DefaultGraph, None).unwrap();
+ let r: serde_json::Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(
+ r["inconsistency"]["found"], true,
+ "the premise of this whole module is that one graph cannot hold both contexts. If \
+ this is ever false the argument is gone: {r}"
+ );
+
+ // The same axioms, kept apart, are two consistent contexts.
+ let js = distributed(&three(), 2).expect("runs");
+ assert_eq!(js["modules"].as_array().unwrap().len(), 3);
+ // Nothing above blew up, which is the point: each module reasoned alone
+ // and neither had to be made consistent with the other.
+ assert!(js["promoted"].as_u64().unwrap() > 0, "{js}");
+}
+
+#[test]
+fn no_module_inherits_another_modules_axioms() {
+ let js = distributed(&three(), 2).expect("runs");
+ let all = js.to_string();
+ // `pingu a :Flier` follows ONLY if the penguin module is handed the bird
+ // module's rule. It must appear nowhere.
+ assert!(
+ !all.contains("pingu> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Flier>"),
+ "a module inherited another's axioms, which is exactly what this design refuses"
+ );
+}
+
+#[test]
+fn a_fact_two_of_three_entail_is_promoted_at_two_and_not_at_three() {
+ let want = "<http://ex.org/Bird> <http://www.w3.org/2000/01/rdf-schema#subClassOf> \
+ <http://ex.org/Flier> .";
+ let at2 = distributed(&three(), 2).expect("runs");
+ let promoted2 = promoted_ntriples(&at2);
+ assert!(promoted2.contains(want), "two modules entail it, so k=2 promotes it");
+
+ let at3 = distributed(&three(), 3).expect("runs");
+ let promoted3 = promoted_ntriples(&at3);
+ assert!(
+ !promoted3.contains(want),
+ "the penguin module does not entail it, so k=3 must NOT promote it. A threshold that \
+ promoted regardless would make the count decorative"
+ );
+}
+
+#[test]
+fn a_fact_only_one_module_entails_is_contested_and_named() {
+ let js = distributed(&three(), 2).expect("runs");
+ let contested = js["contested_facts"].as_array().cloned().unwrap_or_default();
+ let pingu = contested.iter().find(|r| {
+ r["triple"].as_str().unwrap_or_default().contains("/pingu")
+ });
+ let row = pingu.expect("pingu's own facts are entailed in one module only");
+ assert_eq!(row["agreed"], 1);
+ assert_eq!(
+ row["modules"].as_array().unwrap()[0], "penguins",
+ "a contested fact must name WHO holds it, or the disagreement is not actionable"
+ );
+}
+
+#[test]
+fn a_threshold_that_cannot_be_met_is_refused_rather_than_answered() {
+ assert!(distributed(&three(), 0).is_err(), "k=0 promotes everything and means nothing");
+ assert!(distributed(&three(), 4).is_err(), "k above n can never be met");
+ assert!(distributed(&[], 1).is_err(), "no modules, nothing to count");
+}
+
+#[test]
+fn the_report_says_agreement_is_a_count_and_not_a_proof() {
+ let js = distributed(&three(), 2).expect("runs");
+ let means = js["means"].as_str().unwrap_or_default();
+ assert!(means.contains("COUNT and not a proof"), "{means}");
+ assert!(
+ means.contains("copied the same mistaken axiom"),
+ "the failure mode of counting agreement has to be stated, not implied: {means}"
+ );
+ assert_eq!(js["verdict"], "agreed_by_k_of_n_modules");
+ for forbidden in ["certificate_sound", "machine-checked", "proved"] {
+ assert!(!js.to_string().contains(forbidden), "claims {forbidden}, which nothing proved");
+ }
+}
diff --git a/tests/projection_monotonicity_corpus_test.rs b/tests/projection_monotonicity_corpus_test.rs
index 47c99437..f927bed8 100644
--- a/tests/projection_monotonicity_corpus_test.rs
+++ b/tests/projection_monotonicity_corpus_test.rs
@@ -99,6 +99,12 @@ fn corpus() -> Vec<PathBuf> {
// and the same treatment as `tests/fixtures/horn-coverage/`.
// `tests/clash_detector_coverage_test.rs` asserts this exclusion is still here.
.filter(|p| !p.starts_with("tests/fixtures/clash-coverage/"))
+ // `docs/assets/claims/` holds the tiny ontologies the certified-claims
+ // figure is drawn from. They exist to demonstrate a downgrade and a
+ // disagreement, not to be ontologies, and counted as corpus they would
+ // dilute a measurement of what this repository actually ships. Same
+ // reasoning and same treatment as `tests/fixtures/horn-coverage/`.
+ .filter(|p| !p.starts_with("docs/assets/claims/"))
.filter(|p| !SKIP_DIRS.iter().any(|d| p.split('/').any(|seg| seg == *d)))
.map(|p| repo().join(p))
.collect();
diff --git a/tests/readme_simplified_english_test.rs b/tests/readme_simplified_english_test.rs
index aa820ca3..7e581b8a 100644
--- a/tests/readme_simplified_english_test.rs
+++ b/tests/readme_simplified_english_test.rs
@@ -290,6 +290,7 @@ fn the_translated_page_carries_the_same_structure() {
for (stem, translated) in [
("knowledge-graph", true),
("hqdm-audit", true),
+ ("certified-claims", true),
("demo-certify", false),
("logo.png", false),
] {
diff --git a/tests/reason_rl_coverage_test.rs b/tests/reason_rl_coverage_test.rs
index 0c303387..f7d1ea67 100644
--- a/tests/reason_rl_coverage_test.rs
+++ b/tests/reason_rl_coverage_test.rs
@@ -519,6 +519,12 @@ fn the_new_rules_earn_their_place_on_the_shipped_corpus() {
// and the same treatment as `tests/fixtures/horn-coverage/`.
// `tests/clash_detector_coverage_test.rs` asserts this exclusion is still here.
.filter(|p| !p.starts_with("tests/fixtures/clash-coverage/"))
+ // `docs/assets/claims/` holds the tiny ontologies the certified-claims
+ // figure is drawn from. They exist to demonstrate a downgrade and a
+ // disagreement, not to be ontologies, and counted as corpus they would
+ // dilute a measurement of what this repository actually ships. Same
+ // reasoning and same treatment as `tests/fixtures/horn-coverage/`.
+ .filter(|p| !p.starts_with("docs/assets/claims/"))
.filter(|p| !SKIP_DIRS.iter().any(|d| p.split('/').any(|seg| seg == *d)))
.map(|p| repo().join(p))
.collect();