Skip to content

Troubleshooting

This comprehensive guide covers common issues you may encounter when installing, running, or extending Mistaber. Each section includes symptoms, causes, and step-by-step solutions.

Quick Diagnostic Script

Before diving into specific issues, run this diagnostic script to identify common problems:

#!/bin/bash
# mistaber-diagnose.sh - Quick diagnostic check

echo "=== Mistaber Diagnostic Report ==="
echo "Date: $(date)"
echo ""

# Python version
echo "## Python Environment"
python3 --version 2>/dev/null || echo "  [ERROR] Python3 not found"
which python3 2>/dev/null || echo "  [ERROR] Python3 not in PATH"
echo ""

# Virtual environment
echo "## Virtual Environment"
if [ -n "$VIRTUAL_ENV" ]; then
    echo "  Active venv: $VIRTUAL_ENV"
else
    echo "  [WARNING] No virtual environment active"
fi
echo ""

# Clingo installation
echo "## Clingo Installation"
python3 -c "import clingo; print(f'  Version: {clingo.__version__}')" 2>/dev/null || echo "  [ERROR] Clingo not installed or not importable"
echo ""

# Mistaber installation
echo "## Mistaber Installation"
python3 -c "from mistaber.engine import HsrsEngine; print('  [OK] mistaber.engine imports successfully')" 2>/dev/null || echo "  [ERROR] Mistaber not installed or import error"
mistaber --version 2>/dev/null || echo "  [WARNING] mistaber CLI not in PATH"
echo ""

# Ontology path
echo "## Ontology Directory"
if [ -d "./mistaber/ontology" ]; then
    echo "  [OK] ./mistaber/ontology exists"
    echo "  Files: $(find ./mistaber/ontology -name '*.lp' | wc -l) .lp files"
elif [ -d "$MISTABER_ONTOLOGY" ]; then
    echo "  [OK] MISTABER_ONTOLOGY=$MISTABER_ONTOLOGY"
else
    echo "  [WARNING] No ontology directory found in default locations"
fi
echo ""

# Optional dependencies
echo "## Optional Dependencies"
python3 -c "import xclingo; print('  [OK] xclingo (explanations)')" 2>/dev/null || echo "  [INFO] xclingo not installed (optional)"
which asprin >/dev/null 2>&1 && echo "  [OK] asprin (preferences)" || echo "  [INFO] asprin not installed (optional)"
echo ""

echo "=== End Diagnostic Report ==="

Save this script and run it with bash mistaber-diagnose.sh to quickly identify configuration issues.


Installation Issues

Python Version Conflicts

Symptoms:

  • SyntaxError: invalid syntax when importing modules
  • ModuleNotFoundError for standard library modules
  • python command runs Python 2.x

Cause: Mistaber requires Python 3.10 or higher due to modern type hint syntax and match statements.

Solution:

  1. Check your Python version:

    python3 --version
    # Should output: Python 3.10.x or higher
    
  2. If Python version is too old, install a newer version:

    Ubuntu/Debian:

    sudo apt update
    sudo apt install python3.11 python3.11-venv python3.11-dev
    

    macOS (Homebrew):

    brew install python@3.11
    

    Windows (via pyenv-win or official installer): Download from python.org or use:

    winget install Python.Python.3.11
    

  3. Use the correct Python when creating virtual environments:

    python3.11 -m venv venv
    source venv/bin/activate
    pip install -e .
    
  4. Verify the correct Python is active:

    which python
    # Should point to your venv
    python --version
    # Should be 3.10+
    

Clingo Installation Problems

Clingo is the Answer Set Programming solver that powers Mistaber's reasoning engine. Installation can vary by platform.

"ModuleNotFoundError: No module named 'clingo'"

Symptoms:

ModuleNotFoundError: No module named 'clingo'

Solution:

pip install clingo

If that fails, try with specific version:

pip install clingo==5.6.2

"ImportError: libclingo.so not found" (Linux)

Symptoms:

ImportError: libclingo.so: cannot open shared object file: No such file or directory

Cause: The clingo pip package requires system libraries that aren't present.

Solution for Ubuntu/Debian:

# Install gringo system package first
sudo apt-get update
sudo apt-get install gringo

# Then reinstall clingo pip package
pip install --force-reinstall clingo

Solution for Fedora/RHEL:

sudo dnf install clingo
pip install --force-reinstall clingo

Clingo Build Failures on macOS

Symptoms:

error: command 'clang' failed with exit status 1

Solution:

  1. Ensure Xcode Command Line Tools are installed:

    xcode-select --install
    
  2. Install via Homebrew first:

    brew install clingo
    
  3. Then install the Python bindings:

    pip install clingo
    
  4. If still failing, try conda:

    conda install -c potassco clingo
    

Clingo on Windows WSL

Symptoms:

  • Clingo works on native Windows but fails in WSL
  • DLL loading errors

Solution:

In WSL, treat it as a Linux environment:

# Inside WSL (Ubuntu)
sudo apt-get update
sudo apt-get install gringo python3-pip python3-venv
python3 -m venv venv
source venv/bin/activate
pip install clingo

Do NOT try to use a Windows-installed clingo from WSL.


Virtual Environment Setup Issues

"pip install -e ." Fails

Symptoms:

ERROR: File "setup.py" not found

or

ERROR: pyproject.toml does not contain a build-system section

Solution:

Ensure you have the build tools:

pip install --upgrade pip build hatchling
pip install -e .

Packages Installing Globally Instead of in venv

Symptoms:

  • Packages install to system Python
  • which pip points outside your venv

Solution:

  1. Deactivate and recreate the venv:

    deactivate
    rm -rf venv
    python3 -m venv venv
    source venv/bin/activate
    
  2. Verify pip is in venv:

    which pip
    # Should be: /path/to/your/project/venv/bin/pip
    
  3. Upgrade pip inside venv:

    pip install --upgrade pip
    

Dependency Conflicts

Version Conflicts with Other Packages

Symptoms:

ERROR: Cannot install mistaber because these package versions have conflicting dependencies.

Solution:

  1. Create a fresh virtual environment:

    python3 -m venv mistaber-venv
    source mistaber-venv/bin/activate
    
  2. Install mistaber first:

    pip install -e .
    
  3. Then add other packages as needed, checking compatibility:

    pip install other-package
    

Clingo Version Mismatch

Symptoms:

  • Clingo functions behave unexpectedly
  • API errors after upgrade

Solution:

Mistaber requires clingo 5.6.0 or higher:

pip install "clingo>=5.6.0"

# Verify version
python -c "import clingo; print(clingo.__version__)"

Runtime Errors

UNSAT - Unsatisfiable Rules

Symptoms:

UNSATISFIABLE
No stable models found

or the engine returns empty results when you expect data.

Cause: The logical rules contain a contradiction - two or more rules assert facts that cannot all be true simultaneously.

Diagnosis:

  1. Enable verbose clingo output:

    clingo --verbose=2 mistaber/ontology/worlds/*.lp mistaber/ontology/base/*.lp your_scenario.lp
    
  2. Look for conflicting assertions:

    % Example conflict: same item both permitted and forbidden
    asserts(mechaber, issur(achiila, item, d_oraita)).
    asserts(mechaber, heter(achiila, item)).  % Contradiction!
    

Common Causes and Solutions:

Cause Example Solution
Direct contradiction Both issur and heter for same action/item Use override/3 to resolve conflicts
Missing disjointness Item classified as both basar and chalav Check classification facts
Circular negation a :- not b. b :- not a. without choice Add {a} choice rule or constraints
Invalid override Override references non-existent assertion Verify parent world has the assertion

Example Fix:

% WRONG - contradiction
asserts(rema, issur(achiila, fish_dairy, sakana)).
asserts(rema, heter(achiila, fish_dairy)).

% CORRECT - use override pattern
% In mechaber world:
asserts(mechaber, issur(achiila, fish_dairy, sakana)).

% In rema world (override):
override(rema, issur(achiila, fish_dairy, sakana), permitted).
asserts(rema, heter(achiila, fish_dairy)).

Grounding Errors - Unsafe Variables

Symptoms:

error: unsafe variables in:
  asserts(W, issur(achiila, X, L)) :- world(W).

Cause: ASP requires all variables in rule heads to appear in positive literals in the rule body. A variable that only appears in the head or only in negated body literals is "unsafe."

Solution:

Bind all variables to domains:

% WRONG - X and L are unsafe
asserts(W, issur(achiila, X, L)) :- world(W).

% CORRECT - all variables bound
asserts(W, issur(achiila, X, L)) :-
    world(W),
    food(X),
    madrega(L),
    is_forbidden_food(X, W).

% CORRECT - using explicit domain predicates
asserts(W, issur(achiila, X, L)) :-
    world(W),
    forbidden_item(X),
    forbidden_level(X, L).

Common Patterns:

% Variables in negation must also appear positively
% WRONG
forbidden(X) :- not permitted(X).

% CORRECT
forbidden(X) :- food(X), not permitted(X).

Memory Issues with Large Ontologies

Symptoms:

  • Process killed by OS (OOM killer)
  • MemoryError exceptions
  • System becomes unresponsive during grounding

Cause: The grounding phase can produce a very large number of ground atoms, especially with many variables and large domains.

Solutions:

  1. Reduce variable domains:

    % Instead of grounding over all foods:
    applies_to(Rule, Food) :- rule(Rule), food(Food).
    
    % Constrain to relevant items:
    applies_to(Rule, Food) :-
        rule(Rule),
        food(Food),
        rule_category(Rule, Cat),
        food_category(Food, Cat).
    
  2. Use projection to reduce model size:

    #project asserts/2.
    #project holds/2.
    
  3. Split queries into smaller scopes:

    # Instead of querying all worlds at once:
    for world in ["mechaber", "rema", "gra"]:
        results = engine.query(f"holds(X, {world})")
    
  4. Increase available memory:

    # For Docker deployments
    docker run --memory=4g mistaber-image
    
    # For local testing, close other applications
    
  5. Use incremental grounding:

    clingo --configuration=frugal ontology.lp
    

Timeout Issues

Symptoms:

  • Queries hang indefinitely
  • CLI becomes unresponsive
  • "Timeout exceeded" errors in wrapper scripts

Cause: Complex queries with many choice points can cause the solver to explore a vast search space.

Solutions:

  1. Set explicit timeouts:

    import signal
    
    def timeout_handler(signum, frame):
        raise TimeoutError("Query timed out")
    
    signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(30)  # 30 second timeout
    
    try:
        results = engine.query(pattern)
    finally:
        signal.alarm(0)
    
  2. Limit answer set count:

    # In custom queries, limit models
    ctl.configuration.solve.models = 1  # Only find first model
    
  3. Add constraints to prune search space:

    % Constrain early to reduce search
    :- holds(X, W1), holds(X, W2), W1 != W2, conflicting(X).
    
  4. Use query-specific ontology subsets:

    # Load only relevant worlds for the query
    engine = HsrsEngine(
        ontology_path=Path("mistaber/ontology"),
        worlds_filter=["mechaber", "rema"]  # Only load needed worlds
    )
    

Query Issues

"No Results" - Missing Facts

Symptoms:

  • engine.query() returns empty list []
  • engine.ask() returns False for expected truths

Diagnosis Steps:

  1. Verify the ontology loaded:

    print(f"Engine loaded: {engine.is_loaded}")
    # Should be True
    
  2. Check basic facts exist:

    worlds = engine.query("world(X)")
    print(f"Worlds found: {len(worlds)}")
    # Should be 7 for default ontology
    
  3. Verify your query syntax:

    # Variables must be uppercase
    engine.query("world(X)")   # Correct
    engine.query("world(x)")   # Wrong - 'x' is a constant
    
    # Predicate names are case-sensitive
    engine.query("World(X)")   # Wrong - predicate is 'world'
    
  4. Check required facts exist:

    # If querying holds(issur(...), mechaber), verify:
    print(engine.query("world(mechaber)"))  # World exists?
    print(engine.query("asserts(mechaber, X)"))  # Any assertions?
    

Common Causes:

Symptom Cause Solution
No worlds Ontology path wrong Check -o option or ontology_path
World exists but no results Query pattern mismatch Verify predicate name and arity
Base facts missing Wrong scenario Include required facts in scenario
Results in wrong world World inheritance Check accessible/2 relationships

Unexpected Results - Rule Scoping Issues

Symptoms:

  • Results appear in worlds that shouldn't have them
  • Rules not inheriting as expected
  • Overrides not taking effect

Diagnosis:

  1. Check world inheritance:

    accessible = engine.query("accessible(X, Y)")
    for r in accessible:
        print(f"{r['X']} inherits from {r['Y']}")
    
  2. Verify rule scoping:

    % Check what world the rule is scoped to
    scope(rule_name, target_world).
    
  3. Trace assertion flow:

    # What does mechaber assert directly?
    direct = engine.query("asserts(mechaber, X)")
    
    # What holds in mechaber (including inherited)?
    holds = engine.query("holds(X, mechaber)")
    

Common Issues:

% PROBLEM: Rule scoped to base propagates everywhere
scope(r_specific_rule, base).  % This affects ALL worlds!

% SOLUTION: Scope to correct tradition
scope(r_specific_rule, mechaber).  % Only affects mechaber and children

Performance - Slow Queries

Symptoms:

  • Simple queries take multiple seconds
  • Performance degrades with each query
  • Memory usage grows over time

Solutions:

  1. Reuse engine instances:

    # SLOW - recreates engine each time
    for item in items:
        engine = HsrsEngine(ontology_path)
        engine.query(f"status({item}, X)")
    
    # FAST - reuse engine
    engine = HsrsEngine(ontology_path)
    for item in items:
        engine.query(f"status({item}, X)")
    
  2. Use analyze() for isolated scenarios:

    # analyze() creates a fresh context, doesn't pollute main engine
    result = engine.analyze(scenario_code, world="mechaber")
    
  3. Batch related queries:

    # Instead of multiple queries:
    # engine.query("holds(issur(achiila, X, D), mechaber)")
    # engine.query("holds(issur(bishul, X, D), mechaber)")
    
    # Use a single broader query:
    all_issurim = engine.query("holds(issur(A, X, D), mechaber)")
    # Then filter in Python
    achiila = [r for r in all_issurim if r['A'] == 'achiila']
    
  4. Add #show directives for focused output:

    % In custom scenarios, limit output
    #show holds/2.
    #show asserts/2.
    

World Inheritance Problems

Symptoms:

  • Child world doesn't have parent's rulings
  • Override in child doesn't prevent parent's assertion
  • Diamond inheritance (ashk_ah) gives unexpected results

Understanding World Inheritance:

graph TD
    base[base] --> mechaber[mechaber]
    base --> rema[rema]
    base --> gra[gra]
    mechaber --> sefardi_yo[sefardi_yo]
    rema --> ashk_mb[ashk_mb]
    rema --> ashk_ah[ashk_ah]
    gra --> ashk_ah

Debugging Steps:

  1. Verify accessibility chain:

    # For sefardi_yo, should see mechaber and base
    chain = engine.query("accessible(sefardi_yo, X)")
    # Also check transitive closure
    reachable = engine.query("reachable(sefardi_yo, X)")
    
  2. Check for override conflicts:

    % If parent has assertion and child overrides:
    asserts(mechaber, position_a(X)).
    override(sefardi_yo, position_a(X), position_b).
    
    % Verify override is properly scoped
    scope(r_override, sefardi_yo).
    
  3. Handle diamond inheritance explicitly:

    % ashk_ah inherits from both rema and gra
    % If they conflict, explicitly resolve in ashk_ah
    
    % rema says X
    asserts(rema, opinion_x(topic)).
    
    % gra says Y
    asserts(gra, opinion_y(topic)).
    
    % ashk_ah must choose - override the one not followed
    override(ashk_ah, opinion_x(topic), follows_gra).
    asserts(ashk_ah, opinion_y(topic)).
    

Encoding Issues (mistaber-skills Plugin)

These issues are specific to users encoding new halachic content using the mistaber-skills Claude Code plugin.

HLL Compilation Errors

Symptoms:

CompileError: Syntax error at line 5: unexpected token 'rule'

Common Causes and Solutions:

  1. Missing semicolons:

    % WRONG
    rule(r_example)
    makor(r_example, sa("yd:87:1"))
    
    % CORRECT
    rule(r_example).
    makor(r_example, sa("yd:87:1")).
    
  2. Invalid predicate syntax:

    % WRONG - uppercase predicate name
    Rule(r_example).
    
    % CORRECT - lowercase
    rule(r_example).
    
  3. Mismatched parentheses:

    % WRONG
    asserts(mechaber, issur(achiila, M, d_oraita).
    
    % CORRECT
    asserts(mechaber, issur(achiila, M, d_oraita)).
    
  4. String quoting issues:

    % WRONG - unescaped quotes
    makor(r_ex, sa("yd:87:1, "important")).
    
    % CORRECT - proper string handling
    makor(r_ex, sa("yd:87:1")).
    note(r_ex, "important rule").
    

Predicate Not Found Errors

Symptoms:

ValidationError: Unknown predicate 'sakana' with arity 1

Cause: Using a predicate not defined in the ontology schema.

Solutions:

  1. Check existing predicates:

    grep -r "^[a-z_]*(" mistaber/ontology/schema/
    
  2. Use the predicate registry:

    See the Predicate Registry for available predicates.

  3. If predicate is needed, add to schema:

    % In mistaber/ontology/schema/predicates.lp
    % Document the new predicate:
    % sakana(M) - M poses a health danger
    #defined sakana/1.
    
  4. For custom extensions, use the extension protocol:

    % In mistaber/ontology/extensions/my_extension.lp
    % Define local predicate
    my_custom_pred(X) :- condition(X).
    

World Inheritance Problems in Encoding

Symptoms:

  • Encoded rule appears in wrong worlds
  • Rule doesn't propagate to child worlds
  • Override doesn't take effect

Checklist:

  1. Verify world exists:

    % Check kripke_rules.lp has:
    world(mechaber).
    accessible(mechaber, base).
    
  2. Scope rule to correct world:

    % Rule only affects mechaber and children
    scope(r_my_rule, mechaber).
    
    % NOT base unless truly universal
    % scope(r_my_rule, base).  % Avoid unless certain
    
  3. Use correct override pattern:

    % Parent assertion exists
    asserts(mechaber, original_position(X)).
    
    % Child overrides
    override(sefardi_yo, original_position(X), new_position).
    asserts(sefardi_yo, new_position(X)).
    

Checkpoint Failures

Symptoms:

BLOCKED: Checkpoint Not Approved

Cannot proceed from 'corpus-prep' to 'hll-encode'
Current checkpoint status: pending_review

Cause: The encoding workflow requires human approval at each phase.

Solutions:

  1. Review pending checkpoint:

    User: "Show me the corpus preparation summary"
    [Review the artifacts]
    User: "Approved - corpus preparation is accurate"
    
  2. Check session state:

    cat .mistaber-session.yaml
    
  3. If checkpoint was already approved but state lost:

    # Manually update .mistaber-session.yaml
    checkpoints:
      corpus-prep:
        status: approved
        approved_by: human
        timestamp: "2026-01-25T10:00:00Z"
    
  4. Reset if needed:

    # Caution: loses progress
    rm .mistaber-session.yaml
    

Sefaria MCP Connection Issues

Symptoms:

  • "Connection refused" when fetching sources
  • Sefaria tool calls fail silently
  • Empty text returned for valid references

Solutions:

  1. Check MCP configuration:

    # Project-level config
    cat .mcp.json
    
    # User-level config
    cat ~/.config/claude-code/.mcp.json
    
  2. Verify MCP server is available:

    npx -y @sefaria/mcp-server --help
    
  3. Restart Claude Code to reinitialize MCP:

    Close and reopen your Claude Code session.

  4. Use canonical reference format:

    % WRONG
    "YD 87:3"
    "Shulchan Aruch 87:3"
    
    % CORRECT
    "Shulchan Arukh, Yoreh De'ah 87:3"
    
  5. Validate references first:

    User: "Validate the reference 'Yoreh Deah 87:3'"
    

Common Error Messages Reference

Error Message Cause Solution
ModuleNotFoundError: No module named 'clingo' Clingo not installed pip install clingo
ImportError: libclingo.so not found Missing system library Install gringo system package
RuntimeError: Ontology not loaded Engine initialization failed Check ontology path
UNSATISFIABLE Contradictory rules Debug rule conflicts
error: unsafe variables Unbound variables in rules Bind all variables to domains
FileNotFoundError: ontology Wrong working directory Run from project root
SyntaxError: invalid syntax Wrong Python version Use Python 3.10+
CompileError HLL syntax error Check rule syntax
ValidationError: Unknown predicate Predicate not in schema Add to registry or use existing
TimeoutError Query too complex Add constraints, limit scope
MemoryError Large grounding Reduce domains, use projection
WorldNotFoundError Referenced invalid world Check world name spelling
CyclicWorldError Cycle in world graph Fix accessible/2 declarations

Debug Mode

Enabling Verbose Output

For CLI:

# Verbose clingo output
MISTABER_DEBUG=1 mistaber query "world(X)"

# Or use clingo directly with verbose flag
clingo --verbose=2 mistaber/ontology/worlds/*.lp query.lp

For Python API:

import logging
logging.basicConfig(level=logging.DEBUG)

from mistaber.engine import HsrsEngine
engine = HsrsEngine(ontology_path)
# Debug output will show loading and solving steps

For Hook Scripts (encoding plugin):

export MISTABER_DEBUG=1
# Hook scripts will output detailed state information

Inspecting Grounded Program

To see what rules clingo actually generates:

# Output grounded program without solving
clingo --text mistaber/ontology/worlds/*.lp mistaber/ontology/base/*.lp

# Save to file for analysis
clingo --text ontology.lp > grounded.lp

Interpreting grounded output:

% Original rule with variables:
holds(P, W) :- asserts(W, P), world(W).

% Becomes multiple ground instances:
holds(issur(achiila,m1,d_oraita),mechaber) :- asserts(mechaber,issur(achiila,m1,d_oraita)), world(mechaber).
holds(issur(achiila,m1,d_oraita),rema) :- asserts(rema,issur(achiila,m1,d_oraita)), world(rema).
% ... etc for all combinations

Tracing Rule Derivations

Use xclingo for detailed derivation traces:

# Install xclingo
pip install xclingo

# Run with tracing
xclingo mistaber/ontology/worlds/*.lp mistaber/ontology/base/*.lp -n 1

Using the Python API:

explanation = engine.explain("holds(issur(achiila, m1, d_oraita), mechaber)")
print(explanation['tree'])

Example output:

holds(issur(achiila, m1, d_oraita), mechaber)
  <- asserts(mechaber, issur(achiila, m1, d_oraita))
     <- is_beheima_chalav_mixture(m1)
        <- mixture(m1)
        <- contains(m1, beef)
        <- contains(m1, milk)
        <- food_type(beef, beheima)
        <- food_type(milk, chalav)
     <- madrega(d_oraita)
     <- scope(r_bb_achiila, mechaber)

Log File Locations

Log Location Content
Engine debug stderr (when DEBUG=1) Loading, solving steps
Encoding session .mistaber-artifacts/session.log Workflow events
Source fetches .mistaber-artifacts/source-chain-log.yaml Sefaria API calls
Validation .mistaber-artifacts/validation.log Test results
Git operations .git/logs/HEAD Commit history

Getting Help

Collecting Diagnostic Information

When reporting issues, include this diagnostic output:

#!/bin/bash
# collect-diagnostics.sh

echo "=== Mistaber Issue Report ===" > issue-report.txt
echo "Date: $(date)" >> issue-report.txt
echo "" >> issue-report.txt

echo "## System Information" >> issue-report.txt
uname -a >> issue-report.txt
echo "" >> issue-report.txt

echo "## Python Version" >> issue-report.txt
python3 --version >> issue-report.txt 2>&1
echo "" >> issue-report.txt

echo "## Installed Packages" >> issue-report.txt
pip list | grep -E "clingo|mistaber|click|lark|pyyaml" >> issue-report.txt
echo "" >> issue-report.txt

echo "## Clingo Version" >> issue-report.txt
python3 -c "import clingo; print(clingo.__version__)" >> issue-report.txt 2>&1
echo "" >> issue-report.txt

echo "## Ontology Structure" >> issue-report.txt
find ./mistaber/ontology -name "*.lp" | head -20 >> issue-report.txt
echo "" >> issue-report.txt

echo "## Recent Errors (if any)" >> issue-report.txt
# Add any error output here

echo "Diagnostic information saved to issue-report.txt"

Reporting Issues

When reporting bugs, include:

  1. Error message: Complete error output
  2. Steps to reproduce: Minimal code or commands to trigger the issue
  3. Expected behavior: What you expected to happen
  4. Actual behavior: What actually happened
  5. Environment: Python version, OS, clingo version
  6. Diagnostic output: Run the diagnostic script above

Community Resources

Useful External Resources


Quick Reference: Error Resolution Flowchart

flowchart TD
    start[Error Occurred] --> type{Error Type?}

    type -->|Import Error| import[Check pip install]
    type -->|UNSAT| unsat[Check rule conflicts]
    type -->|Grounding Error| ground[Check variable safety]
    type -->|No Results| results[Check query syntax]
    type -->|Memory Error| memory[Reduce domains]
    type -->|Timeout| timeout[Add constraints]

    import --> pyver{Python 3.10+?}
    pyver -->|No| upgradepy[Upgrade Python]
    pyver -->|Yes| clingo{Clingo installed?}
    clingo -->|No| installclingo[pip install clingo]
    clingo -->|Yes| venv{In venv?}
    venv -->|No| createvenv[Create venv]
    venv -->|Yes| reimport[Reinstall package]

    unsat --> trace[Enable --verbose=2]
    trace --> findconflict[Find conflicting rules]
    findconflict --> useoverride[Use override pattern]

    ground --> findvar[Find unsafe variable]
    findvar --> addbound[Add domain binding]

    results --> checkcase[Check case sensitivity]
    checkcase --> checkmatch[Verify pattern matches]
    checkmatch --> checkload[Verify ontology loaded]

    memory --> projection[Add #project]
    projection --> splitquery[Split into smaller queries]

    timeout --> constraints[Add constraints]
    constraints --> limitmodels[Limit model count]