Install
openclaw skills install graph-rule-engine-builderCreate rule-based reasoning systems for knowledge graphs that infer new relationships and facts from existing data using declarative logic rules. Supports derivation, constraint, aggregation, and conditional rules with cycle detection.
openclaw skills install graph-rule-engine-builderCreate rule-based reasoning systems for knowledge graphs that derive new relationships and facts from existing data.
This skill enables comprehensive rule-based inference by defining declarative logic rules that automatically derive new knowledge, validate constraints, and apply business logic to graph data.
Derives new facts from existing patterns using IF-THEN logic.
IF (Person)-[WORKS_AT]->(Company)
AND (Person2)-[WORKS_AT]->(Company)
THEN (Person)-[COLLEAGUE_OF]->(Person2)
Properties: Declarative, deterministic, generates new knowledge
Creates transitive or hierarchical relationships.
IF (A)-[BORN_IN]->(City)
AND (City)-[LOCATED_IN]->(Country)
THEN (A)-[BORN_IN_COUNTRY]->(Country)
Use: Geographic inference, hierarchies, transitive closure
Validates data and flags violations.
IF (Account)-[TRANSFERRED]->(Account)
AND (Account)-[TRANSFERRED]->(Account)
AND (Account)-[TRANSFERRED]->(Account)
THEN Flag(FraudRing, confidence=0.95)
Use: Fraud detection, compliance, data validation
Computes metrics from patterns.
IF aggregate(count((Employee)-[WORKS_AT]->(Company)))
THEN Company.employee_count = count
Use: Analytics, metrics, summarization
Applies logic with conditions.
IF (Person)-[AGE]->(age)
AND age > 65
THEN (Person)-[STATUS]->(Retired)
Use: Classification, segmentation, categorization
Apply all rules to derive all possible inferences (data-driven).
1. Load graph data
2. Find all rule pattern matches
3. Apply THEN inferences
4. Repeat until fixpoint (no new inferences)
Best For: Complete materialization, data warehouse Complexity: May be expensive for large graphs
Query-driven inference - derive facts only when queried.
1. Receive query for fact (person)-[COLLEAGUE_OF]->(other)
2. Check if exists in graph
3. If not, try rules with COLLEAGUE_OF as consequence
4. Recursively check rule conditions
Best For: Lazy evaluation, query optimization Complexity: Lower memory, higher query latency
Combine forward and backward chaining.
Forward chain core rules → Materialized facts
Backward chain on-demand rules → Query results
Best For: Balanced performance and completeness
Rule Name: colleague_inference
Type: derivation
Priority: 100
Condition (IF):
MATCH (person1:Person)-[:WORKS_AT]->(company:Company)
MATCH (person2:Person)-[:WORKS_AT]->(company:Company)
WHERE person1 != person2
Inference (THEN):
CREATE (person1)-[:COLLEAGUE_OF]->(person2)
CREATE (person2)-[:COLLEAGUE_OF]->(person1)
Constraints:
Cycle Detection: true
Materialization: true
Supported patterns:
(n) Single node
(n:Label) Node with label
(n {prop: value}) Node with property
(n)-[r]->(m) Relationship
(n)-[r:TYPE]->(m) Typed relationship
(a)-[:TYPE*1..3]->(b) Variable-length path
(a)-[:TYPE1|:TYPE2]->(b) Multiple relationship types
WHERE conditions:
n.property = value
n.age > 21
NOT exists(n)-[:EXCLUDES]->(m)
size(n.tags) > 0
Aggregate conditions:
count(nodes) > 10
avg(property) < 50
sum(values) = 100
Extend relationships transitively.
IF (a)-[REL]->(b)
AND (b)-[REL]->(c)
THEN (a)-[REL_TRANSITIVE]->(c)
Example: Manager chains, geographic nesting
Combine multiple relationship types.
IF (a)-[BORN_IN]->(city)
AND (city)-[LOCATED_IN]->(country)
AND (country)-[PART_OF]->(region)
THEN (a)-[BORN_IN_REGION]->(region)
Derive properties from relationships.
IF (person)-[WORKS_AT]->(company)
AND aggregate(count(person)) as count
THEN company.employee_count = count
Apply rules conditionally.
IF (person)-[AGE]->(age)
WHERE age >= 65
THEN (person)-[LIFECYCLE_STAGE]->(Retired)
IF (person)-[AGE]->(age)
WHERE age < 25
THEN (person)-[LIFECYCLE_STAGE]->(Junior)
Flag patterns matching suspicious rules.
IF (account1)-[TRANSFERRED]->(account2)
AND (account2)-[TRANSFERRED]->(account3)
AND (account3)-[TRANSFERRED]->(account1)
AND NOT EXISTS (account1)-[AUTHORIZED_TRANSFER]->(account3)
THEN Flag(TransferCycle, risk_level=HIGH)
Detect rules that could cause infinite loops.
Rule A: IF X THEN Y
Rule B: IF Y THEN X
→ Circular dependency detected!
Create indexes on frequently matched properties.
Index on: Person.age, Company.name
Benefit: Faster pattern matching
Execute high-impact, low-cost rules first.
Rule Priority:
1. Simple derivations (low cost, high impact)
2. Complex pattern matches (high cost)
3. Constraint checks (validation)
4. Aggregations (expensive computations)
Update inferences only on data changes.
On Insert (person)-[WORKS_AT]->(company):
→ Check all rules with WORKS_AT pattern
→ Derive only affected consequences
→ Update materialized views
Compute and store all inferences.
Pros: Fast queries, explicit facts
Cons: Storage cost, update latency, staleness
Compute on-demand during queries.
Pros: Storage efficient, always current
Cons: Query latency, repeated computation
Materialize important inferences, compute others on-demand.
Pros: Balanced approach
Implementation: Tier inferences by importance
Rules with higher priority execute first.
Rule A (priority=100): (a)-[R]->(b) THEN (a)-[T]->(b)
Rule B (priority=50): (a)-[R]->(b) THEN (a)-[U]->(b)
→ Rule A executes first
More specific patterns override general ones.
General: (a)-[REL]->(b) THEN ...
Specific: (a:Person)-[REL]->(b:Person) THEN ...
→ Specific rule wins for Person nodes
Later rules override earlier ones.
v1: IF condition THEN inference1
v2: IF condition THEN inference2 (overrides v1)
| Issue | Cause | Solution |
|---|---|---|
| Infinite loops | Circular rules | Enable cycle detection, set depth limit |
| Duplicate inferences | Multiple matching rules | Add constraints, use priorities |
| Memory overflow | Too many inferences | Lazy materialization, limit scope |
| Performance degradation | Complex patterns | Index optimization, rule reordering |
| Constraint violations | Invalid inferences | Add validation, pre-check rules |
| Stale materialized facts | Data changes not applied | Incremental updates, refresh triggers |
✓ Define rules clearly - Use consistent patterns and naming
✓ Avoid circular dependencies - Design acyclic rule sets
✓ Test rules thoroughly - Validate inferences before materialization
✓ Use priorities wisely - Order rules by cost and impact
✓ Index strategically - Index frequently matched properties
✓ Consider materialization - Choose strategy based on query patterns
✓ Document assumptions - Clarify rule semantics and constraints
✓ Monitor performance - Track rule execution times
✓ Version rules - Allow rule evolution and rollback
✓ Validate inferred data - Check quality before use
Combine rules to build complex inference chains.
Support negative conditions (NOT EXISTS).
Generate rules from examples or patterns.
Rules that consider timestamps and time windows.
Rules with confidence scores and uncertainty.
Apply rules spanning multiple graphs or sources.
This skill integrates with:
Drools - Java rule engineProlog - Logic programmingRete - Rule matching algorithmnetworkx - Graph algorithmsregex - Pattern matchingpyparsing - Grammar parsingantlr4-python3-runtime - Parser generatorpyswip - Python-Prolog integrationowlready2 - OWL ontology reasoningrdflib - RDF/SPARQLneo4j - Neo4j driverVersion: 1.0.0