Skip to content

Ontologies, Type Schemas & Fuzzy Types in .kgraph ​

Kompile treats typing as a first-class, portable layer inside every .kgraph container — connecting corpus extraction schemas, OWL-RL ontologies, multi-type hierarchies, and graded (fuzzy) memberships across search, verification, FOL, Datalog, PSL, and MEBN.


1. The three typing layers ​

Kompile separates typing into three composable layers so extraction stays flexible while reasoning stays rigorous:

LayerRepresentationStored in .kgraphRole
1. Type Schema (GraphSchema)JSON (nodeTypes, relationshipTypes, patterns)models/schema/canonical-graph-schema.jsonGuides LLM extraction (NONE / LENIENT / STRICT), defines parentType inheritance and typed properties, and supplies domain/range endpoint patterns.
2. OWL-RL Ontology (OwlOntology)OWL/Turtle (.ttl)models/ontology.ttlDeclares rdfs:subClassOf, owl:equivalentClass, owl:disjointWith, owl:ObjectProperty (domain, range, transitive, functional), and owl:DatatypeProperty axioms for entailment and conformance.
3. Entity Memberships (Crisp & Fuzzy)GraphEntity type, additionalTypes, fuzzyTypesentities.jsonl (v2 & v3)Records both crisp ABox assertions (degree = 1.0, asserted = true) and soft/probabilistic candidates (0.0 < degree <= 1.0, asserted = false) with provenance.

Effective ontology precedence ​

Whenever a local .kgraph is queried, verified, or checked for conformance, LocalProjectGraphBackend resolves the active ontology in strict precedence order:

text
1. Declared models/ontology.ttl artifact          (explicitly bound via bind_ontology)
        │  (if absent)
        ▼
2. models/schema/canonical-graph-schema.json      (bridged via GraphSchemaOntologyBridge)
        │  (if absent)
        ▼
3. Graph-derived ontology                         (inferred from observed node/edge types)

Calling knowledge_graph with action="get_ontology" reports which tier is active (ontologySource: declared-artifact, canonical-graph-schema, or graph-derived), along with class hierarchies, object properties, and crisp vs. fuzzy member counts per class.


2. Type schemas (GraphSchema) & baseline hierarchy ​

Baseline vocabulary (SchemaHierarchyVocabulary) ​

Every corpus-derived or custom GraphSchema builds on 14 stable, domain-neutral baseline entity types (with built-in hierarchy LAW ⊆ DOCUMENT ⊆ CREATIVE_WORK) and 16 connection families:

CategoryBuilt-in values
Baseline entity types (14)PERSON, ORGANIZATION, GROUP, SOFTWARE_AGENT, LOCATION, EVENT, ACTIVITY, PRODUCT, SERVICE, CREATIVE_WORK, DOCUMENT (parentType: CREATIVE_WORK), LAW (parentType: DOCUMENT), LANGUAGE, CONCEPT
Connection families (16)IDENTITY, HIERARCHY, PART_WHOLE, AFFILIATION, SOCIAL, PARTICIPATION, ATTRIBUTION, OWNERSHIP, SPATIAL, COMMUNICATION, TRANSFER, REFERENCE, DERIVATION, DEPENDENCY, CAUSATION, TEMPORAL

Connection families are classification metadata for specific predicates; they are never emitted directly as raw edge types. Baseline entity types cannot reparent to a conflicting parent (SchemaHierarchyVocabulary.withBaseline).

GraphSchema JSON format ​

A GraphSchema specifies nodeTypes (with optional parentType and typed properties), relationshipTypes, and Cypher-like endpoint patterns:

json
{
  "nodeTypes": [
    {
      "label": "Organization",
      "description": "A formal collective actor"
    },
    {
      "label": "Subsidiary",
      "description": "A company controlled by a parent organization",
      "parentType": "Organization",
      "properties": [
        { "name": "jurisdiction", "type": "STRING" },
        { "name": "ownershipPct", "type": "FLOAT" }
      ]
    },
    {
      "label": "Person",
      "description": "A named individual"
    }
  ],
  "relationshipTypes": [
    { "type": "SUBSIDIARY_OF", "description": "Corporate ownership hierarchy" },
    { "type": "WORKS_FOR", "description": "Employment relationship" }
  ],
  "patterns": [
    "(Subsidiary)-[:SUBSIDIARY_OF]->(Organization)",
    "(Person)-[:WORKS_FOR]->(Organization)"
  ]
}

How GraphSchemaOntologyBridge compiles schemas to OWL & TypeRegistry ​

When a GraphSchema is persisted during a crawl (models/schema/canonical-graph-schema.json) or passed to bind_ontology via ontology_schema_json, GraphSchemaOntologyBridge automatically converts it into an OwlOntology TBox and a MEBN TypeRegistry:

  • Each NodeType becomes an OwlClass (and ancestor chains are closed automatically through parentType and SchemaHierarchyVocabulary.baselineParent).
  • Each PropertyType becomes an OwlDataProperty with its XSD range.
  • Endpoint patterns like (Person)-[:WORKS_FOR]->(Organization) generate OwlObjectProperty domain and range axioms (and TypeConstraint.RelationConstraint rules).
  • Built-in transitive predicates (PART_OF, IS_PART_OF, COMPONENT_OF, MEMBER_OF, CONTAINS, SUBCLASS_OF, LOCATED_IN, ANCESTOR_OF, PARENT_OF) are automatically marked owl:TransitiveProperty.

Extraction enforcement modes & presets ​

During server or CLI extraction (kompile graph config set --schema-mode=...):

ModeBehavior
NONENo schema enforcement — the extractor emits any types it discovers.
LENIENTSchema-guided prompt; novel types outside the schema are still accepted.
STRICTOnly types declared in the schema are accepted; undeclared types are discarded.

Presets live at ~/.kompile/config/schema-presets/ and can be inspected or applied with kompile graph config presets / kompile graph config apply-preset --id=<preset> (or knowledge_graph list_presets / apply_preset).


3. Multi-typing & first-class fuzzy types ​

Real-world entities rarely belong to a single crisp bucket: an entity might be asserted as Subsidiary (which entails Organization), while an LLM or neural classifier also assigns soft candidate memberships like FinTech: 0.82 or RegulatedEntity: 0.65.

Crisp vs. fuzzy memberships (FuzzyTypeMembership) ​

Every GraphEntity separates crisp and soft typing cleanly:

  • Crisp memberships (typeMemberships()): strictly crisp (asserted = true, degree = 1.0). Aggregates primary type, additionalTypes, schema.parentType, schema.typeAncestors, entity_subtype, and entity_category. Only crisp assertions feed deterministic OWL ABox axioms.
  • Fuzzy memberships (fuzzyTypeMemberships()): immutable FuzzyTypeMembership(type, degree, source, asserted) records with degree in [0.0, 1.0] and provenance source (for example "llm", "samediff", "owl-fuzzy"). Serialized on each entity in entities.jsonl under fuzzyTypes (and compatible with ontology.typeCandidates):
json
{
  "id": "ent-acme-pay",
  "name": "Acme Pay",
  "type": "Subsidiary",
  "additionalTypes": ["Organization"],
  "fuzzyTypes": [
    { "type": "FinTech", "degree": 0.82, "confidence": 0.82, "source": "llm" },
    { "type": "RegulatedEntity", "degree": 0.65, "confidence": 0.65, "source": "owl-fuzzy" }
  ]
}

Upward propagation & entity resolution ​

  • Gödel supremum upward propagation (TypeHierarchy): If FinTech ⊆ Organization and an entity has FinTech at degree 0.82, TypeHierarchy.membershipDegree(entity, "Organization") propagates upward taking the maximum (supremum) across asserted crisp memberships and soft descendants.
  • OWL-RL fuzzy entailment (OwlRlReasoner): Infers both crisp types (inferredTypes) and graded fuzzy types (inferredFuzzyTypes) across subClassOf, equivalentClass, domain, and range axioms. On local crawl/extract (when deriveOntology=true) or on bind_ontology, TableMemberOntologyBridge.materializeInferredTypes(graph, ontology) materializes both crisp and fuzzy inferences onto entities.
  • Entity merge safety (UnifiedGraphEntityResolver): Merging duplicate entity clusters unions all crisp additionalTypes/typeMemberships and max-merges non-asserted fuzzyTypeMemberships so higher-confidence type evidence is never lost.

4. How ontologies & schemas live inside .kgraph ​

A .kgraph ZIP container (UnifiedGraphFormat) stores ontology, schema, and fuzzy-type state directly alongside topology and learned models:

text
project.kgraph
├── manifest.json                                # Format v2/v3, counts, ontology.source & inferred counts
├── entities.jsonl                               # Entities with type, additionalTypes, fuzzyTypes[]
├── relations.jsonl                              # Portable-v2 edges (or topology/*.bin in Compact-v3)
├── schemas/index.json                           # Portable-v2 container schema inventory
├── weights.json & opinions.jsonl                # Learned rule weights & subjective-logic opinions
├── vectors/*.kvec                               # Dense / KGE vector layers
└── models/
    ├── ontology.ttl                             # Declared OWL/Turtle TBox (bind_ontology)
    ├── schema/canonical-graph-schema.json       # Crawl-derived GraphSchema (bridged to OWL)
    ├── datalog_rules                            # Bundled Datalog rules (materialized with soft support)
    ├── kge.json                                 # Trained TransE/RotatE KGE artifact
    └── reasoning/
        ├── fol-psl-program.v1.json              # Portable PSL/HL-MRF program
        ├── graph-psl-weights.v1.json            # Learned graph-PSL rule weights
        └── mebn-theory.v1.json                  # Learned MEBN theory (with ontology TypeRegistry)

Both PORTABLE_V2 (used by graph_export and cross-machine/Android exchange) and COMPACT_V3 (used by folder-local saves under data/crawls/<kb>/graph.kgraph) round-trip fuzzyTypes, additionalTypes, models/ontology.ttl, and models/schema/canonical-graph-schema.json with zero loss. See the KGraph Portability Contract for activation rules.


5. How every reasoning & query layer uses ontologies & fuzzy types ​

SubsystemOntology & Fuzzy-Type Behavior
Search & Node Listing (knowledge_graph list_nodes / search_nodes, graph_search)Matches entities across the full TypeHierarchy (querying Organization returns Subsidiary members). Set include_fuzzy_types=true (and optional min_type_confidence, default 0.3 when fuzzy is enabled, 1.0 when crisp) to include graded matches; returned nodes expose typeMemberships and fuzzyTypes.
Pattern Query (ask_graph_query)Supports 1-argument entity-type conjuncts (e.g. {"predicate": "Organization", "args": ["?x"]}) with subclass subsumption and Lukasiewicz conjunction across crisp and fuzzy memberships.
Claim Verification (ask_graph_verify, DefaultKbVerifier)Verifies 1-argument crisp, subclass-entailed, and fuzzy type claims; enforces ontology owl:FunctionalProperty uniqueness and emits counter-evidence / REFUTED on owl:disjointWith violations.
Conformance & Contradictions (ontology_conformance, ContradictionDetector, ProbabilisticContradictionDetector)Scores conformance against real OWL inconsistencies, undeclared types, functional/disjoint violations, and hierarchy-aware TypeConstraint.RelationConstraint / CardinalityConstraint checks — without penalizing valid subclass entailments.
Schema Discovery & Aggregation (graph_reasoning_query SCHEMA, graph_aggregate, graph_forecast)SCHEMA reports both crisp entity types and fuzzyEntityTypes; aggregations and forecasts honor TypeHierarchy subsumption and fuzzy thresholds.
FOL & Datalog/TMS (FolInferenceService, ForwardChainingMaterializer, LocalKbState)ReasoningGraphKnowledgeBase.withOntology(graph) propagates ancestor degrees; FolInferenceService emits both unary Type_<Name>(nX) and binary Type(nX, Name) atoms; Constraints.hasFuzzyType + graded evaluateDegree evaluate soft rules; ForwardChainingMaterializer.materializeSoft propagates sub-0.5 fuzzy Viterbi rules; TypeConstraintFolRuleCompiler compiles isA links into schema_subclass_* rules.
PSL (OntologicalConstraintBuilder, GraphPslProgramBuilder)OntologicalConstraintBuilder.fromOntology(OwlOntology) builds domain/range/subclass/disjoint constraints; GraphPslProgramBuilder supports includeTypeAtoms(true) and ontology(OwlOntology).
MEBN (MebnInferenceService, UnifiedGraphReasoningLifecycle, ask_graph_mebn)Uses resolved TypeHierarchy (including restricted-scope handling for neighborhood MTheories) for multi-type indexing and prefers declared ontology domain/range signatures when building MTheories.
Answer Synthesis (ask_graph_synthesize, LocalGraphReasoningBridge)Projects crisp and fuzzy unary type facts into the local KB and fuses graded SignalGroup.TYPE evidence during answer synthesis.

6. Practical workflows (MCP & CLI) ​

Bind an OWL/Turtle ontology to a local .kgraph ​

json
{
  "tool": "knowledge_graph",
  "arguments": {
    "action": "bind_ontology",
    "ontology_turtle": "@prefix : <urn:kompile:finance#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n@prefix owl: <http://www.w3.org/2002/07/owl#> .\n:Subsidiary rdfs:subClassOf :Organization .\n:Competitor owl:disjointWith :Subsidiary .\n:worksFor a owl:ObjectProperty ; rdfs:domain :Person ; rdfs:range :Organization ."
  }
}

Or bind directly from a GraphSchema JSON payload (automatically compiled to Turtle via GraphSchemaOntologyBridge):

json
{
  "tool": "knowledge_graph",
  "arguments": {
    "action": "bind_ontology",
    "ontology_schema_json": "{\"nodeTypes\":[{\"label\":\"Subsidiary\",\"parentType\":\"Organization\"}],\"patterns\":[\"(Person)-[:WORKS_FOR]->(Organization)\"]}"
  }
}

bind_ontology writes models/ontology.ttl, runs OwlRlReasoner + TableMemberOntologyBridge.materializeInferredTypes, persists updated crisp and fuzzy memberships atomically to the .kgraph, and returns class/property counts, inferred counts, and consistency status.

Inspect active ontology & audit conformance ​

json
{ "tool": "knowledge_graph", "arguments": { "action": "get_ontology" } }
json
{ "tool": "knowledge_graph", "arguments": { "action": "ontology_conformance" } }

ontology_conformance returns conformanceScore, totalEntities, conformingEntities, violatingEntities, undeclaredTypeViolations, constraintViolationCount, and entitiesWithInferredTypes.

Query with subclass subsumption & fuzzy types ​

json
{
  "tool": "knowledge_graph",
  "arguments": {
    "action": "list_nodes",
    "node_type": "Organization",
    "include_fuzzy_types": true,
    "min_type_confidence": 0.6
  }
}
json
{
  "tool": "ask_graph_verify",
  "arguments": { "atom": "Organization(Acme Pay)" }
}
json
{
  "tool": "graph_reasoning_query",
  "arguments": { "operation": "SCHEMA" }
}

Remove a declared ontology ​

json
{ "tool": "knowledge_graph", "arguments": { "action": "unbind_ontology" } }

Removing models/ontology.ttl causes the graph to fall back cleanly to models/schema/canonical-graph-schema.json (if present) or graph-derived types.

Server-side fact-sheet ontology binding & presets ​

When connected to a Kompile server (:8080 / :8082), bind_ontology binds a registered schema by ID and optional version (fact_sheet_id, ontology_schema_id, ontology_version), while CLI schema presets manage extraction typing:

bash
kompile graph config presets
kompile graph config apply-preset --id=technology
kompile graph config set --schema-mode=LENIENT

Released under the Apache-2.0 License.