DocsCode Knowledge Graph
Core Feature

Code Knowledge Graph

A queryable graph of your codebase built from AST analysis — imports, calls, inheritance, and cross-file relationships resolved in milliseconds.

What is the Code Knowledge Graph?

The Code Knowledge Graph is Krnl's semantic understanding layer for your codebase. It parses every Python file in your project using Tree-sitter (with a built-in ast fallback), builds a graph of modules, classes, functions, imports, calls, and inheritance relationships, and stores it in an indexed SQLite database. The agent queries this graph to understand code context without reading entire files.

Why a graph? Flat file lists don't capture how code connects. The graph lets the agent answer questions like "what calls this function?" or "where is this class used?" in milliseconds — without grep.

With vs. Without the Graph

Here's the same task — “add input validation to the login handler” — executed with and without the Code Knowledge Graph:

Without Graph — The agent reads files blindly

terminal
$ ✦ Krnl Agent · openai · gpt-4o-mini
Workspace: /home/dev/myapp
you ❯ add input validation to the login handler
● Thinking...
⚙ read_file src/handlers/auth.py
⚙ read_file src/models/user.py
⚙ read_file src/utils/validate.py (not found — guessing)
⚙ read_file src/middleware.py (not relevant)
⚙ grep "login" src/ (scanning 47 files...)
⚙ read_file src/routes/login.py
⚙ read_file src/decorators/auth.py
✓ 8 files read, 2 irrelevant, task took 23s
⚠ The agent wasted 3 reads on irrelevant files
⚠ Missed the validate_input() utility in src/lib/helpers.py
⚠ Created a duplicate validator instead of reusing the existing one

With Graph — The agent knows the codebase structure

terminal
$ ✦ Krnl Agent · openai · gpt-4o-mini
Workspace: /home/dev/myapp
● Graph DB: .krnl/graph.db · 312 nodes · 847 edges
you ❯ add input validation to the login handler
● Thinking...
● Graph resolved: "login" → src/routes/login.py::login_handler()
● Graph neighbors: calls validate_input() in src/lib/helpers.py
● Graph neighbors: uses User model from src/models/user.py
⚙ read_file src/routes/login.py (target)
⚙ read_file src/lib/helpers.py (called by login_handler)
⚙ read_file src/models/user.py (imported by login_handler)
✓ 3 relevant files read, task took 6s
✓ Reused existing validate_input() — added call in 2 lines
✓ No duplicates, no wasted reads
Result: 62% fewer files read, 73% faster task completion, zero duplicate code created. The graph eliminated blind guessing.

Architecture

The graph is built from three layers working together:

1. Parser Layer

Tree-sitter parses Python files into concrete syntax trees. Falls back to Python's built-in ast module when Tree-sitter is not installed. Extracts: modules, classes, functions, imports, function calls, and inheritance.

2. Graph Layer

A NetworkX MultiDiGraph holds nodes (Module, Class, Function) and edges (imports, calls, inherits, defines) in memory for fast traversal. Cross-file references are resolved via a ModulePathIndex.

3. Persistence Layer

SQLite database stores the full graph with WAL mode for concurrent access. The graph is rebuilt per-file on invalidation (triggered by file writes) — no full rebuilds needed.

Graph Model

Node TypeDescriptionAttributes
ModuleA Python filefile_path, language
ClassA class definitionqualified_name, parent_class, line_start, line_end
FunctionA function or methodqualified_name, parent_class, line_start, line_end
Edge TypeMeaning
importsA file imports a symbol from another module
callsA function calls another function or method
inheritsA class inherits from another class
definesA module defines a class or function

Graph-Aware Context

When you give the agent a task, it analyzes the task text for mentioned symbols, looks them up in the graph, and automatically pulls in neighbor nodes up to a configurable hop limit. This means:

  • Mention a function name → the agent also reads its callers and callees
  • Mention a class → the agent also reads its parent class and subclasses
  • Edit a file → the graph invalidates only that file (incremental update)
  • No full rebuilds — changes are propagated per-file with zero downtime

Real-World Example

When you ask the agent to “refactor the User class to use a factory pattern”, the graph automatically:

Step 1: Symbol Resolution

Graph locates User class at src/models/user.py and identifies all subclasses (AdminUser, GuestUser)

Step 2: Dependency Mapping

Graph finds all files that import or instantiate User (auth.py, routes.py, tests/)

Step 3: Context Assembly

Agent reads only the relevant files (5 files) instead of scanning the entire codebase (47 files)

Step 4: Incremental Update

After edit, only src/models/user.py is re-parsed — no full graph rebuild needed

Performance: The graph is built once at agent startup (configurable). For large projects, the initial build happens in a background thread and doesn't block the first task.

Configuration

All three features are opt-in. Enable them in your project's config.yaml or via the VS Code extension settings panel:

Option 1: config.yaml

graph:
  enabled: true              # Enable the code knowledge graph
  backend: networkx          # Graph backend (networkx)
  db_path: .krnl/graph.db    # SQLite database path
  languages:                 # File types to parse
    - python

context:
  graph_aware: true          # Enrich prompts with graph context
  graph_hop_limit: 1         # How many hops to traverse (1-5)
  differential_updates: true # Only send changed nodes

memory:
  per_session: true          # Persist structured memory per session

Option 2: VS Code Extension

Open the Krnl Code settings panel in VS Code and toggle the checkboxes under Advanced Features:

  • Enable Code Knowledge Graph — builds the graph at startup
  • Graph Hop Limit — sets how many levels of neighbors to traverse (1–5). Higher = more context, more tokens.
  • Enable Graph-Aware Context — uses graph for smarter context selection
  • Enable Per-Session Memory — persists structured memory across sessions
Note: Tree-sitter parsing requires the tree_sitter and tree_sitter_python packages. Without them, the system falls back to Python's built-in ast module (less precise but always available).

Visual Indicators

When the Code Knowledge Graph is enabled, you'll see visual indicators across all interfaces:

CLI Startup

terminal
$ krnl
Firebase UID: abc123
● Graph DB: .krnl/graph.db · 312 nodes · 847 edges
┌─────────────────────────────────────────────┐
│ Krnl Agent · openai · gpt-4o-mini │
│ ⬡ Graph ON ◎ Context ON Memory ON │
│ Workspace: /home/dev/myapp │
│ Type a task, or /help for commands. │
└─────────────────────────────────────────────┘

VS Code Extension

The view tab shows which features are active: ⬡ ◎ ◆ symbols appear in the panel header when Graph, Context-Aware, and Per-Session Memory are enabled respectively.

Terminal: /config Command

terminal
you ❯ /config
provider : openai
model : gpt-4o-mini
base_url : (default)
api key : set
graph : enabled · 312 nodes · .krnl/graph.db
context : graph_aware (hop_limit=1, differential)
memory : per_session (staleness_check)