Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
fix(demo): dedupe reconcile and remove crop-protection/cell-biology vocabulary
FABIOTESS6951a7a4bd55
diff --git a/demo/README.md b/demo/README.mdindex dfda60b2..fd613e56 100644--- a/demo/README.md+++ b/demo/README.md@@ -34,7 +34,7 @@ back to the document and section it came from.because it is redundant with the partition and is the one form areasoner cannot check for contradictions. Status and State are exempt,because a status is a property of a thing over time, not a kind of- thing (`ontology_from_docs.py`, function `reconcile`).+ thing (`ontology_from_docs.py`, function `_reconcile_ttl`).7. **Populate.** Instances are extracted from the documents, constrained tothe derived and reconciled ontology so nothing gets invented(`ontology_from_docs.py`, stage POPULATE; `extract.py`).diff --git a/demo/contradiction_scan.py b/demo/contradiction_scan.pyindex 2cce9907..c9ba8489 100644--- a/demo/contradiction_scan.py+++ b/demo/contradiction_scan.py@@ -55,7 +55,7 @@ EXTRA = sorted((ROOT / "demo" / "corpus_extracted").glob("*.ttl"))LLM_BASE = os.environ.get("ONTO_LLM_BASE_URL", "http://localhost:8081/v1").rstrip("/")LLM_KEY = os.environ.get("ONTO_LLM_API_KEY", "not-needed")-PREFIXES = """PREFIX crd: <https://w3id.org/dcat-us-demo#>+PREFIXES = """PREFIX dcus: <https://w3id.org/dcat-us-demo#>PREFIX owl: <http://www.w3.org/2002/07/owl#>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>PREFIX prov: <http://www.w3.org/ns/prov#>@@ -88,12 +88,12 @@ TIER1 = [),("domain-rule",- "A candidate declares a control target the register classifies as beneficial",+ "A candidate declares a target term the register classifies as deprecated",PREFIXES- + """SELECT DISTINCT ?subject ?organism ?viaClass WHERE {- ?subject crd:targetsOrganism ?organism .- ?organism a ?viaClass .- ?viaClass rdfs:subClassOf* crd:BeneficialOrganism .+ + """SELECT DISTINCT ?subject ?term ?viaClass WHERE {+ ?subject dcus:targetsTerm ?term .+ ?term a ?viaClass .+ ?viaClass rdfs:subClassOf* dcus:DeprecatedTerm .}""",),]@@ -108,18 +108,18 @@ TIER1 = [# - require the two claims to share vocabulary. Claims about the same# individual that share no significant term are rarely contradictory.TIER2 = PREFIXES + """SELECT ?entity ?docA ?secA ?claimA ?docB ?secB ?claimB WHERE {- ?a a crd:Claim ; crd:aboutEntity ?entity ; crd:claimText ?claimA ; crd:statedIn ?sa .- ?b a crd:Claim ; crd:aboutEntity ?entity ; crd:claimText ?claimB ; crd:statedIn ?sb .+ ?a a dcus:Claim ; dcus:aboutEntity ?entity ; dcus:claimText ?claimA ; dcus:statedIn ?sa .+ ?b a dcus:Claim ; dcus:aboutEntity ?entity ; dcus:claimText ?claimB ; dcus:statedIn ?sb .FILTER(STR(?a) < STR(?b))FILTER NOT EXISTS { ?entity a owl:Class }FILTER NOT EXISTS { ?someone a ?entity }- ?sa crd:sectionNumber ?secA . ?da crd:hasSection ?sa ; crd:docId ?docA .- ?sb crd:sectionNumber ?secB . ?db crd:hasSection ?sb ; crd:docId ?docB .+ ?sa dcus:sectionNumber ?secA . ?da dcus:hasSection ?sa ; dcus:docId ?docA .+ ?sb dcus:sectionNumber ?secB . ?db dcus:hasSection ?sb ; dcus:docId ?docB .FILTER(?docA != ?docB)}"""# Total claims, for an honest reduction ratio rather than a bare count.-CLAIM_COUNT = PREFIXES + "SELECT (COUNT(?c) AS ?n) WHERE { ?c a crd:Claim }"+CLAIM_COUNT = PREFIXES + "SELECT (COUNT(?c) AS ?n) WHERE { ?c a dcus:Claim }"# Which source asserted each conflicting fact.PROVENANCE = PREFIXES + """SELECT ?thing ?sourceLabel WHERE {diff --git a/demo/corpus_pipeline.py b/demo/corpus_pipeline.pyindex 831bd086..72d27652 100644--- a/demo/corpus_pipeline.py+++ b/demo/corpus_pipeline.py@@ -46,14 +46,14 @@ if os.environ.get("NO_COLOR"):else:BOLD, DIM, RED, GRN, YEL, OFF = "\033[1m", "\033[2m", "\033[31m", "\033[32m", "\033[33m", "\033[0m"-VOCAB_HINT = """Classes: :Document :StandardOperatingProcedure :RegulatoryGuidance :TrialReport- :Section :Claim :Control :ReferenceSource :Candidate :Organism :Pest :Pathogen- :BeneficialOrganism :Pollinator :NaturalEnemy :FieldTrial :TargetProtein :Mutation- :EvidenceGap :StageGate+VOCAB_HINT = """Classes: :Document :Specification :ImplementationGuide :ConformanceReport+ :Section :Claim :Requirement :ReferenceSource :Candidate :Dataset :Distribution+ :Catalog :Publisher :Licence :Theme :ContactPoint :ConformanceProfile :Frequency+ :ConformanceGap :ReleaseStageObject properties: :hasSection :parentSection :relatedSection :statedIn :aboutEntity- :supersedes :declaresControl :controlOver :blocksProgressionOf :documentsRiskIn+ :supersedes :declaresRequirement :requirementOver :blocksReleaseOf :documentsGapInDatatype properties: :docId :classification :aclGroup :sectionNumber :claimText- :isAutomated :isBlocking rdfs:label rdfs:comment"""+ :isMandatory :isBlocking rdfs:label rdfs:comment"""PROMPT = """Extract a knowledge graph from this controlled document.@@ -72,10 +72,11 @@ Extract:and its most specific document type.2. A :Section per numbered section, IRI :SEC_{safe}_<number with dots as underscores>,with :sectionNumber and rdfs:label, linked by :hasSection.-3. :Claim nodes for assertions about candidate progression, organism classification,- thresholds, or safeguards. Each with :claimText, :statedIn, and :aboutEntity where- the subject is identifiable.-4. Where a section states a safeguard, a :Control with :isAutomated and :isBlocking.+3. :Claim nodes for assertions about candidate adoption, dataset classification,+ thresholds, or conformance requirements. Each with :claimText, :statedIn, and+ :aboutEntity where the subject is identifiable.+4. Where a section states a conformance requirement, a :Requirement with+ :isMandatory and :isBlocking.DOCUMENT ID: {docid}diff --git a/demo/cq/run-cross-doc.py b/demo/cq/run-cross-doc.pyindex e77ad0af..2dc83bd6 100644--- a/demo/cq/run-cross-doc.py+++ b/demo/cq/run-cross-doc.py@@ -15,58 +15,58 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent.parentBIN = ROOT / "target" / "release" / "open-ontologies"BUNDLE = ROOT / "demo" / "bundle" / "dcat-us-full.ttl"-P = """PREFIX crd: <https://w3id.org/dcat-us-demo#>+P = """PREFIX dcus: <https://w3id.org/dcat-us-demo#>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"""QUESTIONS = [("XD-1",- "Which controls should block SYN-4471, are they automated, and who declares them?",+ "Which requirements should block DS-4471, are they mandatory, and who declares them?",P- + """SELECT ?docId ?control ?blocking ?automated WHERE {- ?ctrl crd:blocksProgressionOf crd:SYN_4471 ;- rdfs:label ?control ; crd:isBlocking ?blocking ; crd:isAutomated ?automated .- ?doc crd:declaresControl ?ctrl ; crd:docId ?docId . }""",+ + """SELECT ?docId ?requirement ?blocking ?mandatory WHERE {+ ?req dcus:blocksReleaseOf dcus:DS_4471 ;+ rdfs:label ?requirement ; dcus:isBlocking ?blocking ; dcus:isMandatory ?mandatory .+ ?doc dcus:declaresRequirement ?req ; dcus:docId ?docId . }""",),("XD-2",- "Root cause: every claim about the mis-mapped bucket or the hoverfly, with its source",+ "Root cause: every claim about the mis-mapped theme or the harvest feed, with its source",P+ """SELECT ?docId ?section ?claim WHERE {- ?c a crd:Claim ; crd:claimText ?claim ; crd:statedIn ?sec ; crd:aboutEntity ?e .- VALUES ?e { crd:AphidAssociatedArthropod crd:EpisyrphusBalteatus crd:SRC_PestScoutingFeed }- ?sec crd:sectionNumber ?section .- ?doc crd:hasSection ?sec ; crd:docId ?docId . }""",+ ?c a dcus:Claim ; dcus:claimText ?claim ; dcus:statedIn ?sec ; dcus:aboutEntity ?e .+ VALUES ?e { dcus:EnergyTheme dcus:Theme_PublicTransit dcus:SRC_HarvestFeed }+ ?sec dcus:sectionNumber ?section .+ ?doc dcus:hasSection ?sec ; dcus:docId ?docId . }""",),("XD-3",- "Which safeguards exist only on paper (blocking or not, but not automated)?",+ "Which requirements exist only on paper (blocking or not, but not mandatory)?",P- + """SELECT ?docId ?control ?blocking WHERE {- ?ctrl a crd:Control ; rdfs:label ?control ;- crd:isAutomated false ; crd:isBlocking ?blocking .- ?doc crd:declaresControl ?ctrl ; crd:docId ?docId . }""",+ + """SELECT ?docId ?requirement ?blocking WHERE {+ ?req a dcus:Requirement ; rdfs:label ?requirement ;+ dcus:isMandatory false ; dcus:isBlocking ?blocking .+ ?doc dcus:declaresRequirement ?req ; dcus:docId ?docId . }""",),("XD-4","Which reference source is superseded, and which section documents its defect?",P+ """SELECT ?supersedingSource ?supersededSource ?documentingDoc ?section ?sectionLabel WHERE {- ?winner crd:supersedes ?loser .+ ?winner dcus:supersedes ?loser .BIND(REPLACE(STR(?winner), "^.*#", "") AS ?supersedingSource)BIND(REPLACE(STR(?loser), "^.*#", "") AS ?supersededSource)- ?sec crd:documentsRiskIn ?loser ; crd:sectionNumber ?section ; rdfs:label ?sectionLabel .- ?doc crd:hasSection ?sec ; crd:docId ?documentingDoc . }""",+ ?sec dcus:documentsGapIn ?loser ; dcus:sectionNumber ?section ; rdfs:label ?sectionLabel .+ ?doc dcus:hasSection ?sec ; dcus:docId ?documentingDoc . }""",),("XD-5","Cross-document section links: which section of one document bears on another?",P+ """SELECT ?fromDoc ?fromSec ?toDoc ?toSec WHERE {- ?a crd:relatedSection ?b .- ?da crd:hasSection ?a ; crd:docId ?fromDoc . ?a crd:sectionNumber ?fromSec .- ?db crd:hasSection ?b ; crd:docId ?toDoc . ?b crd:sectionNumber ?toSec .+ ?a dcus:relatedSection ?b .+ ?da dcus:hasSection ?a ; dcus:docId ?fromDoc . ?a dcus:sectionNumber ?fromSec .+ ?db dcus:hasSection ?b ; dcus:docId ?toDoc . ?b dcus:sectionNumber ?toSec .FILTER(?fromDoc != ?toDoc) }""",),(@@ -74,7 +74,7 @@ QUESTIONS = ["Access control: which ACL groups would a reader need to see this whole chain?",P+ """SELECT DISTINCT ?docId ?classification ?acl WHERE {- ?doc crd:docId ?docId ; crd:classification ?classification ; crd:aclGroup ?acl . }""",+ ?doc dcus:docId ?docId ; dcus:classification ?classification ; dcus:aclGroup ?acl . }""",),]diff --git a/demo/extract.py b/demo/extract.pyindex f60135e1..524c6b4c 100644--- a/demo/extract.py+++ b/demo/extract.py@@ -34,17 +34,17 @@ LLM_KEY = os.environ.get("ONTO_LLM_API_KEY", "not-needed")VOCAB_HINT = """Classes you may use:- :Document :StandardOperatingProcedure :RegulatoryGuidance :TrialReport- :Section :Claim :Control :ReferenceSource- :Candidate :Organism :Pest :Pathogen :BeneficialOrganism :Pollinator :NaturalEnemy- :FieldTrial :TargetProtein :Mutation :EvidenceGap :StageGate+ :Document :Specification :ImplementationGuide :ConformanceReport+ :Section :Claim :Requirement :ReferenceSource+ :Candidate :Dataset :Distribution :Catalog :Publisher :Licence :Theme+ :ContactPoint :ConformanceProfile :Frequency :ConformanceGap :ReleaseStageObject properties you may use::hasSection :parentSection :relatedSection :statedIn :aboutEntity- :supersedes :declaresControl :controlOver :blocksProgressionOf :documentsRiskIn+ :supersedes :declaresRequirement :requirementOver :blocksReleaseOf :documentsGapInDatatype properties you may use:- :docId :classification :aclGroup :sectionNumber :claimText :isAutomated :isBlocking+ :docId :classification :aclGroup :sectionNumber :claimText :isMandatory :isBlockingrdfs:label rdfs:comment"""@@ -66,12 +66,12 @@ Extract::classification, :aclGroup, and the most specific document type.2. A :Section node per numbered section, IRI :SEC_{docid_safe}_<number with dots as underscores>,with :sectionNumber and rdfs:label, linked by :hasSection from the document.-3. :Claim nodes for assertions that matter to candidate progression or organism+3. :Claim nodes for assertions that matter to candidate adoption or datasetclassification. Each with :claimText and :statedIn pointing at its section.-4. Where a section states a safeguard, a :Control node with :isAutomated and- :isBlocking, linked with :declaresControl.+4. Where a section states a conformance requirement, a :Requirement node with+ :isMandatory and :isBlocking, linked with :declaresRequirement.5. Where a section records a defect or limitation of a data source, link the- section with :documentsRiskIn.+ section with :documentsGapIn.DOCUMENT ID: {docid}diff --git a/demo/kpi_context_graph.py b/demo/kpi_context_graph.pyindex f71a768d..10fea422 100644--- a/demo/kpi_context_graph.py+++ b/demo/kpi_context_graph.py@@ -19,7 +19,7 @@ Three things it does that a drawn diagram cannot:Usage:python3 demo/kpi_context_graph.py graph- python3 demo/kpi_context_graph.py impact :targetsOrganism+ python3 demo/kpi_context_graph.py impact :targetsTermpython3 demo/kpi_context_graph.py breach"""@@ -35,7 +35,7 @@ LOADS = [ROOT / "demo" / "ontology" / "dcat-us-kpi.ttl",]-P = """PREFIX crd: <https://w3id.org/dcat-us-demo#>+P = """PREFIX dcus: <https://w3id.org/dcat-us-demo#>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>PREFIX owl: <http://www.w3.org/2002/07/owl#>"""@@ -76,18 +76,18 @@ def cmd_graph():Grouped into layers and styled so it reads at a glance: what the model iscomputed FROM on the left, the indicators in the middle, what they measureand what mandates them on the right. Blocking indicators are highlighted,- because "which of these stops a stage gate" is the first thing anyone asks.+ because "which of these stops a release" is the first thing anyone asks."""- inputs = query(P + "SELECT ?kpi ?input WHERE { ?kpi a/rdfs:subClassOf* crd:KPI ; crd:computedFrom ?input }")- applies = query(P + "SELECT ?kpi ?cls WHERE { ?kpi a/rdfs:subClassOf* crd:KPI ; crd:appliesTo ?cls }")- comps = query(P + "SELECT ?kpi ?component WHERE { ?kpi crd:dependsOnKPI ?component }")- govs = query(P + "SELECT ?kpi ?doc WHERE { ?kpi crd:governedBy ?doc }")+ inputs = query(P + "SELECT ?kpi ?input WHERE { ?kpi a/rdfs:subClassOf* dcus:KPI ; dcus:computedFrom ?input }")+ applies = query(P + "SELECT ?kpi ?cls WHERE { ?kpi a/rdfs:subClassOf* dcus:KPI ; dcus:appliesTo ?cls }")+ comps = query(P + "SELECT ?kpi ?component WHERE { ?kpi dcus:dependsOnKPI ?component }")+ govs = query(P + "SELECT ?kpi ?doc WHERE { ?kpi dcus:governedBy ?doc }")labels = {r["kpi"]: r["label"] for r in- query(P + "SELECT ?kpi ?label WHERE { ?kpi a/rdfs:subClassOf* crd:KPI ; rdfs:label ?label }")}- # Scope to KPIs: Controls also carry isBlocking, and would otherwise leak+ query(P + "SELECT ?kpi ?label WHERE { ?kpi a/rdfs:subClassOf* dcus:KPI ; rdfs:label ?label }")}+ # Scope to KPIs: Requirements also carry isBlocking, and would otherwise leak# into the indicator styling.blocking = {r["kpi"] for r in- query(P + "SELECT ?kpi WHERE { ?kpi a/rdfs:subClassOf* crd:KPI ; crd:isBlocking true }")}+ query(P + "SELECT ?kpi WHERE { ?kpi a/rdfs:subClassOf* dcus:KPI ; dcus:isBlocking true }")}kpis = sorted(labels)ins = sorted({r["input"] for r in inputs})@@ -163,17 +163,17 @@ def cmd_impact(changed):direct = query(P+ f"""SELECT ?kpi ?label ?blocking WHERE {{- ?kpi crd:computedFrom crd:{term} .+ ?kpi dcus:computedFrom dcus:{term} .OPTIONAL {{ ?kpi rdfs:label ?label }}- OPTIONAL {{ ?kpi crd:isBlocking ?blocking }}+ OPTIONAL {{ ?kpi dcus:isBlocking ?blocking }}}}""")# dependsOnKPI is transitive, so the closure comes back from one query.downstream = query(P+ f"""SELECT DISTINCT ?composite ?label WHERE {{- ?direct crd:computedFrom crd:{term} .- ?composite crd:dependsOnKPI ?direct .+ ?direct dcus:computedFrom dcus:{term} .+ ?composite dcus:dependsOnKPI ?direct .OPTIONAL {{ ?composite rdfs:label ?label }}}}""")@@ -197,16 +197,16 @@ def cmd_breach():print("Indicator evaluation against the loaded graph\n")checks = [- ("Field translation efficiency", 0.80, "lower value is a breach",- P + "SELECT ?c ?v WHERE { ?c crd:fieldToScreenRatio ?v . FILTER(?v < 0.80) }"),- ("Unexplained residual variance", 0.20, "higher value is a breach",- P + "SELECT ?c ?v WHERE { ?c crd:unexplainedResidualVariance ?v . FILTER(?v > 0.20) }"),- ("Binding evidence freshness", 1.0, "any stale protein is a breach",- P + "SELECT ?p WHERE { ?p crd:affectedByMutation ?m ; crd:isStale true }"),- ("Evidence gap closure", 1.0, "any open gap is a breach",- P + "SELECT ?c ?g WHERE { ?c crd:hasEvidenceGap ?g }"),- ("Trial data completeness", 1.0, "a field trial with no plot is a breach",- P + "SELECT ?t WHERE { ?t a crd:FieldTrial . FILTER NOT EXISTS { ?t crd:hasPlot ?p } }"),+ ("Distribution coverage ratio", 0.80, "lower value is a breach",+ P + "SELECT ?c ?v WHERE { ?c dcus:distributionCoverageRatio ?v . FILTER(?v < 0.80) }"),+ ("Unthemed dataset ratio", 0.20, "higher value is a breach",+ P + "SELECT ?c ?v WHERE { ?c dcus:unthemedDatasetRatio ?v . FILTER(?v > 0.20) }"),+ ("Licence currency", 1.0, "any stale licence record is a breach",+ P + "SELECT ?d WHERE { ?d dcus:affectedByLicenceChange ?m ; dcus:isStale true }"),+ ("Conformance gap closure", 1.0, "any open gap is a breach",+ P + "SELECT ?c ?g WHERE { ?c dcus:hasConformanceGap ?g }"),+ ("Catalogue completeness", 1.0, "a catalogue with no dataset is a breach",+ P + "SELECT ?t WHERE { ?t a dcus:Catalog . FILTER NOT EXISTS { ?t dcus:hasDataset ?p } }"),]breaches = 0for name, threshold, note, sparql in checks:@@ -220,23 +220,23 @@ def cmd_breach():safety = query(P- + """SELECT ?candidate ?organism ?doc WHERE {- ?candidate crd:targetsOrganism ?organism .- ?organism a ?cls . ?cls rdfs:subClassOf* crd:BeneficialOrganism .- OPTIONAL { ?kpi a crd:SafetyKPI ; crd:governedBy ?d . ?d crd:docId ?doc }+ + """SELECT ?candidate ?term ?doc WHERE {+ ?candidate dcus:targetsTerm ?term .+ ?term a ?cls . ?cls rdfs:subClassOf* dcus:DeprecatedTerm .+ OPTIONAL { ?kpi a dcus:GovernanceKPI ; dcus:governedBy ?d . ?d dcus:docId ?doc }}""")print()if safety:breaches += 1- print(f" [ BREACH] Beneficial organism exposure [BLOCKING, threshold 0.0]")+ print(f" [ BREACH] Deprecated term targeting [BLOCKING, threshold 0.0]")for r in safety:gov = f", mandated by {r['doc']}" if r.get("doc") else ""- print(f" {r['candidate']} targets {r['organism']}{gov}")+ print(f" {r['candidate']} targets {r['term']}{gov}")else:- print(" [ ok] Beneficial organism exposure")+ print(" [ ok] Deprecated term targeting")- print(f"\n {breaches} indicators breached. Stage gate readiness: FAIL")+ print(f"\n {breaches} indicators breached. Release readiness: FAIL")print(" Every breach traces to a triple, and the blocking one traces to the")print(" controlled document that mandates it.")@@ -248,7 +248,7 @@ def main():if cmd == "graph":cmd_graph()elif cmd == "impact":- cmd_impact(sys.argv[2] if len(sys.argv) > 2 else ":targetsOrganism")+ cmd_impact(sys.argv[2] if len(sys.argv) > 2 else ":targetsTerm")elif cmd == "breach":cmd_breach()else:diff --git a/demo/ontology_from_docs.py b/demo/ontology_from_docs.pyindex 3e625cec..ce274c12 100644--- a/demo/ontology_from_docs.py+++ b/demo/ontology_from_docs.py@@ -3,9 +3,8 @@Ontology out of text: derive the ontology FROM a document corpus, thenpopulate it, with PII tokenised before anything reaches a model.-This is domain-agnostic. Nothing about crop protection, biology or any other-subject is hardcoded; the vocabulary is whatever the documents turn out to be-about.+This is domain-agnostic. Nothing about any particular subject is hardcoded;+the vocabulary is whatever the documents turn out to be about.STAGE 1 READ every document in the folderSTAGE 2 TOKENISE detect and replace sensitive values with stable tokens@@ -45,8 +44,6 @@ import timeimport urllib.errorimport urllib.request-from rdflib import Graph, OWL, RDF, RDFS, URIRef-ROOT = pathlib.Path(__file__).resolve().parent.parentBIN = ROOT / "target" / "release" / "open-ontologies"ENGINE = os.environ.get("ONTO_ENGINE", "http://127.0.0.1:8137")@@ -384,31 +381,31 @@ Produce:has a class for that kind, TYPE the thing with that class. Never create anindividual to stand for the kind itself.- "Culture07 is maintained as an adherent line"- correct: :Culture07 a :AdherentLine ; rdfs:label "Culture07" .- WRONG: :Culture07 a :CellLine .- :ADHERENT_LINE a :CellLine ; rdfs:label "Adherent line" .+ "Dataset07 is catalogued as a published dataset"+ correct: :Dataset07 a :PublishedDataset ; rdfs:label "Dataset07" .+ WRONG: :Dataset07 a :Dataset .+ :PUBLISHED_DATASET a :Dataset ; rdfs:label "Published dataset" .The wrong form loses the fact entirely: it records that something called- "adherent line" exists, not that Culture07 is one.+ "published dataset" exists, not that Dataset07 is one.Give each individual EXACTLY ONE type: the single most specific class that- fits. A registry row listing a cell line's genotype, doubling time and- growth conditions describes ONE cell line; it does not make that cell line- a genotype or a doubling time. Attach those as properties, never as extra+ fits. A registry row listing a dataset's licence, update frequency and+ access level describes ONE dataset; it does not make that dataset a+ licence or an update frequency. Attach those as properties, never as extratypes.- correct: :Culture07 a :AdherentLine ;- :hasGenotype :GENOTYPE_WT ;- :hasDoublingTime "24h" .- WRONG: :Culture07 a :CellLine, :CellLineGenotype, :CellLineDoublingTime .+ correct: :Dataset07 a :PublishedDataset ;+ :hasLicence :LICENCE_CC_BY ;+ :hasUpdateFrequency "monthly" .+ WRONG: :Dataset07 a :Dataset, :Licence, :UpdateFrequency .4. Name each individual after the thing itself and nothing else. The IRI for- Culture07 is :Culture07 in every document that mentions it. Do not prefix it+ Dataset07 is :Dataset07 in every document that mentions it. Do not prefix itwith the document id, and do not qualify it with the context it appeared in- (:CULTURE07_STR, :CELL_LINE_CULTURE07_REGISTRY). The same real thing must- get the same IRI everywhere, because that is what lets facts from different- documents meet.+ (:DATASET07_STR, :DATASET_CATALOGUE_DATASET07_REGISTRY). The same real thing+ must get the same IRI everywhere, because that is what lets facts from+ different documents meet.5. The relationships and attribute values the document asserts.Values that look like TOK_ followed by capitals and a hex string are tokens@@ -434,8 +431,8 @@ def derive_one(args):def snap_to_vocab(body: str, declared: set[str]) -> str:"""Snap a term to a declared term it differs from only in case.- The generator writes `:HasCellLine` where the ontology declares- `:hasCellLine`. Closed-world checking is right to reject it, but the intent+ The generator writes `:HasPublisher` where the ontology declares+ `:hasPublisher`. Closed-world checking is right to reject it, but the intentis unambiguous and there is exactly one candidate, so resolving it here issound rather than charitable. Anything that does not match a declared termunder case folding is left alone: that is real invention and it must stay@@ -470,8 +467,8 @@ DISJOINT_PROMPT = """Here is a list of classes from an ontology derived from adocument corpus.Identify pairs that are MUTUALLY EXCLUSIVE: a single thing cannot be both at-the same time. Examples of the kind of pair that qualifies: a culture that is-adherent versus one in suspension; a sample that passed versus failed; a+the same time. Examples of the kind of pair that qualifies: a dataset that is+published versus one that is a draft; a check that passed versus failed; arecord that is authenticated versus unauthenticated.Return ONLY Turtle, one statement per line, no prose and no fences:@@ -496,9 +493,9 @@ def _sibling_groups(classes: list[str], cap: int = 60) -> list[list[str]]:looks merely unlucky.Grouping is by head noun rather than arbitrary slicing, because that is- where mutual exclusivity actually lives. `AdherentLine` and- `SuspensionLine` are candidates precisely because they are both kinds- of `Line`; two classes with nothing in common almost never need an axiom+ where mutual exclusivity actually lives. `PublishedDataset` and+ `DraftDataset` are candidates precisely because they are both kinds+ of `Dataset`; two classes with nothing in common almost never need an axiombetween them. Small groups are pooled so a group of one is not a call."""def head(name: str) -> str:@@ -528,7 +525,7 @@ def add_disjointness(merged_path: pathlib.Path) -> int:Deliberately a SEPARATE pass over the merged class list rather than part ofper-document derivation. Disjointness is a cross-document property: whether- "adherent" and "suspension" are mutually exclusive is not visible from+ "published" and "draft" are mutually exclusive is not visible frominside one document that only mentions one of them. Asking per documentreliably produced none at all.@@ -621,11 +618,11 @@ def _reconcile_ttl(merged_path: pathlib.Path) -> list[str]:"""Collapse competing modelling patterns left behind by the merge.Per-document derivation is independent, so one document models a mode- as a subclass partition (:AdherentLine, :SuspensionLine) while another- models the same notion as an attribute class (:LineType). Concatenating+ as a subclass partition (:PublishedDataset, :DraftDataset) while another+ models the same notion as an attribute class (:DatasetType). Concatenatingfragments keeps both, and the extractor then legitimately picks whicheverit likes. It reliably picks the attribute class, which is the one form- disjointness cannot reach: :Culture07Type a :LineType says nothing the+ disjointness cannot reach: :Dataset07 a :DatasetType says nothing thereasoner can contradict.The rule: where a parent has a subclass partition (two or more@@ -638,8 +635,7 @@ def _reconcile_ttl(merged_path: pathlib.Path) -> list[str]:catches this today; it is a merge problem, not a single-ontology problem.Operates on the Turtle text on disk, mirroring the file-based fragment- merge the rest of this pipeline stage uses. `reconcile()` below applies- the identical rule to an in-memory RDF graph.+ merge the rest of this pipeline stage uses."""ttl = merged_path.read_text()classes = set(re.findall(r":(\w+)\s+(?:a|rdf:type)\s+owl:Class", ttl))@@ -671,76 +667,6 @@ def _reconcile_ttl(merged_path: pathlib.Path) -> list[str]:return doomed-def _split_iri(iri: URIRef) -> tuple[str, str]:- """Namespace and local name of an IRI, splitting on the last '#' or '/'."""- s = str(iri)- if "#" in s:- ns, _, local = s.rpartition("#")- return ns + "#", local- ns, _, local = s.rpartition("/")- return ns + "/", local---def reconcile(graph: Graph) -> Graph:- """Collapse competing modelling patterns left behind by the merge.-- Per-document derivation is independent, so one document models a mode- as a subclass partition (:AdherentLine, :SuspensionLine) while another- models the same notion as an attribute class (:LineType). Concatenating- fragments keeps both, and the extractor then legitimately picks whichever- it likes. It reliably picks the attribute class, which is the one form- disjointness cannot reach: :Culture07Type a :LineType says nothing the- reasoner can contradict.-- The rule: where a parent has a subclass partition (two or more- subclasses) AND the vocabulary also declares parent+KIND_SUFFIX, the- attribute class is redundant with the partition and loses. Remove it,- and remove any property whose domain or range points at it, so the only- way left to express the distinction is the one that supports reasoning.- Status and State are deliberately absent from KIND_SUFFIXES: a status is- a property of a thing over time, not a kind of thing, so an attribute- class named parent+Status or parent+State is genuinely an attribute and- is spared.-- None of the engine's enforce packs (generic, hierarchy, value_partition)- catches this today; it is a merge problem, not a single-ontology problem.-- Same rule as `_reconcile_ttl` above, expressed directly over RDF triples- instead of the Turtle text on disk, so it can run against a graph that- was never serialised to a file.- """- classes = set(graph.subjects(RDF.type, OWL.Class))- children: dict[URIRef, set[URIRef]] = {}- for child, parent in graph.subject_objects(RDFS.subClassOf):- children.setdefault(parent, set()).add(child)-- doomed: set[URIRef] = set()- for parent, kids in children.items():- if len(kids) < 2:- continue- ns, name = _split_iri(parent)- for suf in KIND_SUFFIXES:- candidate = URIRef(ns + name + suf)- if candidate in classes:- doomed.add(candidate)-- for cls in doomed:- # Properties anchored to the removed class go with it. A property- # whose range no longer exists invites the extractor to mint an- # untyped individual to fill it, which recreates the pattern that- # was just removed.- for prop in set(graph.subjects(RDFS.domain, cls)) | set(graph.subjects(RDFS.range, cls)):- graph.remove((prop, None, None))- # disjointWith triples referencing the removed class, either direction.- for s, o in list(graph.subject_objects(OWL.disjointWith)):- if s == cls or o == cls:- graph.remove((s, OWL.disjointWith, o))- # The class declaration itself, and everything else hanging off it.- graph.remove((cls, None, None))-- return graph--def _name_tokens(name: str) -> tuple[str, ...]:return tuple(sorted(t.lower() for t in re.findall(r"[A-Z][a-z0-9]*|^[a-z]+[0-9]*", name)if t.lower() != "has"))@@ -754,10 +680,10 @@ def mech_resolve(body: str, bad: list[str], onto_ttl: str, doc: str = "") -> strA token equality hasConcentrationValue -> ConcentrationValueB unique superset hasContainmentLevel -> ContainmentLevelValue- C has{Class} inversion S :hasCellLineGenotype O, where- CellLineGenotype is a declared CLASS: the generator manufactured a+ C has{Class} inversion S :hasDistributionFormat O, where+ DistributionFormat is a declared CLASS: the generator manufactured aforward property where the vocabulary models the inverse. Rewritten- as O a :CellLineGenotype ; :hasCellLine S, which is the declared+ as O a :DistributionFormat ; :hasDistribution S, which is the declaredpattern every other document uses.Anything ambiguous (hasName with five plausible targets) is left alone@@ -857,9 +783,9 @@ GATE_PROMPT = """One document contains these excerpts mentioning "{label}":Question: does "{label}" name a {parent}?The excerpts may be registry rows, change logs, or procedures ABOUT the thing;-those still count: a registry row about a cell line is describing a cell line.+those still count: a registry row about a dataset is describing a dataset.Answer no only when "{label}" names a different KIND of thing, such as a-reagent batch, a measurement, a document, or a person.+licence code, a file format, a document, or a person.Reply exactly yes or no."""@@ -917,7 +843,7 @@ def refine(merged_path: pathlib.Path, instances: list[pathlib.Path],prompt entirely. For each individual typed with a bare partition parent,the excerpts mentioning it are shown back with the subclass names as aclosed choice. A model that cannot follow "use the most specific class"- inside a 16k-character extraction task answers "adherent or suspension+ inside a 16k-character extraction task answers "published or draftor unstated" correctly, because there is nothing else to do.This is the LLM-Modulo shape end to end: generation is decomposed until@@ -968,7 +894,7 @@ def refine(merged_path: pathlib.Path, instances: list[pathlib.Path],seen_subjects.add(subj)if subj in all_classes:# An INDIVIDUAL whose IRI is a declared class (a source- # document emitted a literal :CellLine individual). Retyping it+ # document emitted a literal :Dataset individual). Retyping it# would rewrite what looks like vocabulary. Humans only.with open(merged_path.parent / "_review.jsonl", "a") as rq:rq.write(json.dumps({@@ -1001,9 +927,9 @@ def refine(merged_path: pathlib.Path, instances: list[pathlib.Path],snippets = "\n".join(f"- {l[:220]}" for l in lines[:6])# The gate is its own binary question. Offered only as an# extra option inside the partition question, "other" loses- # to pattern-matching: an FBS lot mentioned alongside- # adherent cultures came back "AdherentLine". Asked- # alone, "is Lot A itself a cell line?" gets the right no.+ # to pattern-matching: a licence code mentioned alongside+ # published datasets came back "PublishedDataset". Asked+ # alone, "is CC-BY-4.0 itself a dataset?" gets the right no.try:gate = call_model(GATE_PROMPT.format(label=label, parent=parent, snippets=snippets),@@ -1040,11 +966,11 @@ def refine(merged_path: pathlib.Path, instances: list[pathlib.Path],elif anskey == "other":# The extractor mistyped it upstream. An automatic# second guess was tried here and reintroduced the- # failure it was meant to fix (an FBS lot became- # :CellLineGrowthRateComparison with :FBSLot sitting- # in the candidate list). Wrong-type-with-confidence- # is worse than wrong-type-in-a-queue: the type stays- # as asserted and a human decides.+ # failure it was meant to fix (a licence code became+ # :DatasetUpdateFrequencyComparison with :LicenceCode+ # sitting in the candidate list). Wrong-type-with-+ # confidence is worse than wrong-type-in-a-queue: the+ # type stays as asserted and a human decides.entry = {"doc": doc, "subject": subj, "label": label,"asserted": parent,"reason": f"not a {parent} per gate question"}@@ -1081,7 +1007,7 @@ def prune_to_used(onto_ttl: str, data: str) -> tuple[str, dict]:Derivation over-proposes by an order of magnitude: 10 documents produced346 classes, most of them compositional one-offs- (CellLineGrowthRateMeasurementStatisticalSignificanceAnalysis) that no+ (DatasetDistributionFormatConformanceAssessmentOutcome) that noinstance ever uses. Rendering all of that buries the dozen entities thecorpus is actually about. The FULL vocabulary stays on disk and keepsconstraining extraction; the store the graph view and chat read carries@@ -1129,8 +1055,8 @@ def prune_to_used(onto_ttl: str, data: str) -> tuple[str, dict]:frontier.append(p)# View collapse. Two shapes of noise survive the instance-count filter:- # specialisation chains (CellLineGrowthRateMeasurementStatistical...- # extending CellLineGrowthRate token by token) and families of near+ # specialisation chains (DatasetDistributionFormatConformance...+ # extending DatasetDistributionFormat token by token) and families of near# duplicate siblings (fourteen ChangeLogEntryChange* classes). A box per# variant hides the dozen entities the corpus is about. Chains collapse# into their shortest kept prefix; families keep their two most@@ -1189,8 +1115,8 @@ def sources_of(instances: list[pathlib.Path]) -> dict[tuple[str, str], set[str]]"""Which document asserted that a given individual has a given type.Provenance is what separates the two things a disjointness violation can- mean. If one document types Culture07 as both a cell line and a doubling- time, that is a broken extraction. If two documents disagree about which+ mean. If one document types Dataset07 as both a dataset and an update+ frequency, that is a broken extraction. If two documents disagree about whichof two mutually exclusive classes it belongs to, that is the corpuscontradicting itself, and it is the only kind worth showing anyone.@@ -1212,7 +1138,7 @@ def vocab_summary(ttl: str) -> str:"""Vocabulary for the populate prompt, WITH definitions.A bare list of names invites the model to invent near-misses: given- :CellLine it will happily write :CellLineType or :CellLineInRoutineUse+ :Dataset it will happily write :DatasetType or :DatasetArchivedbecause they sound plausible. Including each term's label and comment makesthe existing vocabulary concrete enough to reuse instead of extend, whichis what the closed-world check is measuring.diff --git a/demo/requirements.txt b/demo/requirements.txtindex 8177212d..eea9b4f6 100644--- a/demo/requirements.txt+++ b/demo/requirements.txt@@ -1,3 +1,2 @@-rdflib>=7.0presidio-analyzer>=2.2pytest>=8.0diff --git a/demo/tests/test_reconcile.py b/demo/tests/test_reconcile.pyindex f93d5200..8c851a6c 100644--- a/demo/tests/test_reconcile.py+++ b/demo/tests/test_reconcile.py@@ -1,28 +1,42 @@-from rdflib import Graph, Namespace, RDFS, OWL, RDF--from demo.ontology_from_docs import reconcile--EX = Namespace("https://example.org/t#")---def _graph(pairs):- g = Graph()- for sub, parent in pairs:- g.add((sub, RDF.type, OWL.Class))- g.add((sub, RDFS.subClassOf, parent))- return g---def test_attribute_class_is_removed_when_a_partition_exists():- g = _graph([(EX.PublishedDataset, EX.Dataset), (EX.DraftDataset, EX.Dataset)])- g.add((EX.DatasetType, RDF.type, OWL.Class))- out = reconcile(g)- assert (EX.DatasetType, RDF.type, OWL.Class) not in out- assert (EX.PublishedDataset, RDFS.subClassOf, EX.Dataset) in out---def test_status_is_spared_because_states_are_attributes():- g = _graph([(EX.ActiveThing, EX.Thing), (EX.RetiredThing, EX.Thing)])- g.add((EX.ThingStatus, RDF.type, OWL.Class))- out = reconcile(g)- assert (EX.ThingStatus, RDF.type, OWL.Class) in out+from demo.ontology_from_docs import _reconcile_ttl++PREFIXES = ("@prefix : <https://example.org/t#> .\n"+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n"+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n")+++def _merged(tmp_path, body):+ path = tmp_path / "merged.ttl"+ path.write_text(PREFIXES + body)+ return path+++def test_attribute_class_is_removed_when_a_partition_exists(tmp_path):+ path = _merged(tmp_path, """+:Dataset a owl:Class .+:PublishedDataset a owl:Class .+:PublishedDataset rdfs:subClassOf :Dataset .+:DraftDataset a owl:Class .+:DraftDataset rdfs:subClassOf :Dataset .+:DatasetType a owl:Class .+""")+ doomed = _reconcile_ttl(path)+ assert doomed == ["DatasetType"]+ out = path.read_text()+ assert ":DatasetType a owl:Class ." not in out+ assert ":PublishedDataset rdfs:subClassOf :Dataset ." in out+++def test_status_is_spared_because_states_are_attributes(tmp_path):+ path = _merged(tmp_path, """+:Thing a owl:Class .+:ActiveThing a owl:Class .+:ActiveThing rdfs:subClassOf :Thing .+:RetiredThing a owl:Class .+:RetiredThing rdfs:subClassOf :Thing .+:ThingStatus a owl:Class .+""")+ doomed = _reconcile_ttl(path)+ assert doomed == []+ out = path.read_text()+ assert ":ThingStatus a owl:Class ." in outdiff --git a/demo/verify.py b/demo/verify.pyindex 4ffef134..9cfb784b 100644--- a/demo/verify.py+++ b/demo/verify.py@@ -117,8 +117,8 @@ def main() -> int:# class for the same notion. The extractor reliably picks the attribute# class, which is the one form disjointness cannot reach, so leaving both# in the vocabulary quietly disables contradiction detection. None of the- # engine's enforce packs catches this; the pipeline's reconcile() removes- # them, and this check keeps it removed.+ # engine's enforce packs catches this; the pipeline's _reconcile_ttl()+ # removes them, and this check keeps it removed.import re as _rettl_text = ONTOLOGY.read_text()cls = set(_re.findall(r":(\w+)\s+(?:a|rdf:type)\s+owl:Class", ttl_text))