LeanKG
Every code-graph answer says which rung it came from, how fresh it is, and whether you are allowed to see it.
A self-hosted code knowledge graph for AI coding agents, for engineering organizations whose agents must answer from the real codebase under their own access rules.
Agents stop grepping blind. They ask a structured question, get a traceable answer from the real repository, under your access rules.
Get started · Architecture · CLI · Live demo
The problem
An AI coding agent starts every session with no structural knowledge of the repository it is working in. It compensates the only way it can: search, open files, read, search again. That loop is expensive in tokens and time, and it is unreliable, the answer depends on which grep happened to match.
Three failures follow from it:
- Cost. Whole files enter the context window to answer a question about one function.
- Trust. A plausible answer cannot be traced to an exact symbol, a keyword hit, or a semantic guess.
- Control. The agent's tooling rarely enforces who may read which repository, and shared servers often have no gate at all.
What LeanKG is
LeanKG indexes a repository into a graph of code elements and relationships, then answers agent questions from that graph. It is one CGO-free binary with an embedded store, and it can serve one developer or a team behind HTTP.
| What it gives an agent | How |
|---|---|
| A targeted answer instead of a file scan | Callers, callees, impact, paths, context and compressed reads from one graph |
| A traceable answer | Every response reports the retrieval rung, the reason, and index freshness |
| Team knowledge in the same place | Memory, incidents, ownership, environments and requirements share the store |
| One server for many clients | MCP over stdio and HTTP, REST, ConnectRPC, CLI and a web UI over one engine |
| Access rules at the door | Viewer, Contributor and Admin roles per route, bearer tokens, project grants |
Why LeanKG
- Provenance on every code-graph answer. A
queryanswer names the retrieval rung it came from (retrieval.rung,retrieval.reason) and how fresh the index is:freshness(cold,freshorpossibly_stale),indexed_at, andhead_syncon a git-indexed store. A consumer can tell an exact match from a fallback and a current index from a stale one. The ontology, session, prd, incidents, env_conflicts, service_context, compress and languages actions carry no retrieval, and a portfolio fan-out has none at the top level (each child answer has its own); see the tool contract. - Per-project access. A bearer token can be limited to named projects with
project:<name>scopes, and the grant is checked on MCP, REST, auto-config, the dashboard API and project switcher, and portfolio reads. RPC has no grant check of its own: a token that does not cover the default project is refused there. A restricted token lists and revokes only its own token, and cannot create orgs or claim resources. Every query answer'saccessblock states the role and project the caller was served as. Viewer, Contributor and Admin roles are declared per HTTP route, and a non-loopback bind is refused without a token. - Several repositories, one server.
LEANKG_PROJECT_DIRSregisters several repositories in one process. Each request selects its project, and a portfolio query skips the projects the caller cannot see. - Deployment control. One CGO-free binary and a container image. SQLite needs no database server. PostgreSQL with pgvector is the opt-in for shared, server-scale deployments.
- Lower agent cost. Agents ask for a targeted subgraph (callers, dependents, impact, tests, docs) instead of running grep-and-read loops over whole files. The archived A/B figures are in Performance; they have not been re-run on the Go engine.
A real query answer, trimmed to the provenance keys (hits, query and limit omitted). It is the output of leankg query -action exact Greet on a three-function Go fixture indexed in a git repository, run through the CLI, which calls the same engine as the MCP tool. indexed_at is a unix time and differs on each index run.
{
"access": {
"project": "fixture-repo",
"restricted": false,
"role": "admin",
"via": "local"
},
"freshness": "fresh",
"head_sync": "match",
"indexed_at": 1795510603,
"retrieval": {
"reason": "exact identifier match",
"rung": "L1",
"scope": "all"
}
}
How it works
From repository to answer
flowchart LR
Repo["Repository<br/>HEAD commit or working tree"] --> Indexer["Indexer<br/>regex · tree-sitter · ast-grep"]
Indexer --> Graph[("Element graph<br/>files · symbols · edges")]
Indexer --> FTS[("Keyword index<br/>FTS5 / full-text")]
Graph --> Embed["Embedding pipeline<br/>local · OpenAI-compatible"]
Embed --> Vectors[("Vectors<br/>model-stamped")]
Graph --> Engine["Query engine<br/>retrieval ladder · graph traversal"]
FTS --> Engine
Vectors --> Engine
Engine --> Doors["MCP · REST · ConnectRPC · CLI · Web UI"]
Doors --> Agent["AI coding agent"]
Indexing extracts elements (files, functions, types, modules) and their
relationships (contains, calls, imports, references). In a git
repository the HEAD commit is the source of truth, so uncommitted and ignored
files do not leak into the graph. Embeddings are incremental, and every vector
writer is model-stamp guarded: changing the model fails loudly instead of
mixing vector spaces.
The retrieval ladder
flowchart TD
Q["Question or symbol"] --> L1{"L1 exact identifier"}
L1 -->|hit| A["Answer with retrieval.rung + freshness"]
L1 -->|miss| L2{"L2 keyword / fuzzy"}
L2 -->|hit| A
L2 -->|miss| L3{"L3 semantic"}
L3 -->|hit| A
L3 -->|"unavailable or miss"| D["Best available rung<br/>reason states why"]
D --> A
A query stops at the first rung that can answer. Exact and keyword matches
need no embedding round trip; semantic search is used when they miss. When a
rung is unavailable, no vectors yet, for example, the answer comes from the
next rung down and says so in retrieval. The consumer can therefore tell an
exact match from a fallback without trusting the prose.
One engine, many doors
flowchart LR
A1["stdio harness"] -->|MCP| MCP["MCP server<br/>import · query · status · authenticate"]
A2["HTTP agent or IDE"] -->|"MCP over HTTP"| MCP
A3["CI and scripts"] -->|REST| REST["REST API"]
A4["Browser"] -->|"web API"| WEB["Web UI server"]
MCP --> CORE["One query engine"]
REST --> CORE
WEB --> CORE
CORE --> STORE[("Project store<br/>SQLite · PostgreSQL + pgvector")]
The same question returns the same answer whichever door it came through.
A process can serve several repositories; on a multi-project server the
project argument is required, because guessing the graph produces confident
wrong answers.
Read the detailed component map, indexer tiers and trust boundaries in Architecture, and the request and data flows in Flow diagrams.
Comparison with context-mode (2026-11-24)
Source: the public README of context-mode, read as of 2026-11-24. This is not a code audit of context-mode. "Not documented" means that README is silent on the point.
| Capability | LeanKG | context-mode |
|---|---|---|
| Provenance per answer | Every answer carries access. Index-backed answers carry retrieval{rung,reason}, naming the rung (L0-L3, ast-grep, lsp, graph, memory, git) |
Search hits show the source file and heading |
| Per-answer freshness | freshness (cold, fresh, possibly_stale), indexed_at and head_sync (match, stale) on index-backed answers; the key is omitted from an answer when the head state is unknown, and status reports unknown |
Not documented for indexed content |
| Role/ACL on reads | Viewer, Contributor and Admin roles per route; project:<name> grants enforced on the routed surfaces; RPC has no grant check of its own and refuses a token that lacks the default project |
Not documented. The README mentions a PreToolUse deny list, not read roles |
| Multi-project from one server | LEANKG_PROJECT_DIRS serves several repositories from one process; each request selects one |
One context.db per project under ~/.context-mode; serving several projects from one server is not documented |
| Measured answer quality | No quality figure published yet; the judge-blind run in benchmarks/cross_tool is pending |
Not documented. It reports bytes-based reduction (ctx_bytes against raw_bytes) |
At a glance
| Area | Value |
|---|---|
| Language profiles | 40, supported languages |
| MCP tools | 4: import, query, status, authenticate, tool contract |
| Access roles | 3: Viewer, Contributor, Admin, security model |
| Storage | SQLite (default), PostgreSQL + pgvector (opt-in), architecture |
| Transports | MCP (stdio, HTTP), REST, ConnectRPC, CLI, web UI |
| Client targets | claude-code, cursor, codex, gemini, opencode, omp, xdev |
| Footprint | One CGO-free binary; no database server required |
Get started
# 1. Install the CLI and server
go install github.com/FreePeak/LeanKG/cmd/leankg@latest
# 2. Index the repository (creates .leankg/leankg.db)
cd your-project
leankg index .
# 3. Wire an AI client, then restart it
leankg install --target claude-code
Serve one graph to many clients instead:
leankg serve --http 127.0.0.1:9699 --rest 127.0.0.1:8080 --memory
leankg install --target claude-code --http --url http://127.0.0.1:9699/mcp
Requirements: macOS or Linux. Go 1.25+ is needed only to build from source. No Docker and no PostgreSQL are needed for the default SQLite store.
Continue with Getting started for prebuilt archives, client wiring, semantic search, verification and troubleshooting.
Documentation
| Document | Contents |
|---|---|
| Getting started | Install, first index, client wiring, semantic search, troubleshooting |
| Architecture | Components, indexing tiers, retrieval ladder, trust boundaries, limits |
| Flow diagrams | Component, data, request and storage diagrams |
| CLI reference | Commands, query actions, authentication, environment variables |
| Central agent memory | Cross-repository Claude Code memory: sync, session hook, recall, rollback |
| Deployment and security | Deployment models, security model, scale-out, operations, enterprise limits |
| Performance | Measured A/B results, benchmark harness, how to read them |
| Languages | The 40 profiles and extraction tiers |
| Embeddings | Providers, EmbeddingGemma 2, bulk embedding, model stamps |
| MCP tool contract | Tools, arguments, stability tiers and deprecation policy |
| Multi-project scoping | How project selection and grants resolve |
| Telemetry | Consent-gated capture and transcript linking |
| PRD | Product requirements, the single source of truth |
| Task tracker | Done, in progress, to do |
| AGENTS.md | Agent context, build and test commands, auth runbook |
| Changelog | Release history |
Project status
LeanKG is in active development on the self-host dogfood loop: this repository is served by its own HTTP server, indexed, embedded and memorized, and used to build LeanKG itself before scaling to nested-repo parents. See the PRD and task tracker.
Known gaps are documented rather than omitted:
- Enterprise limits, no SSO, no TLS termination, audit append not wired, no application-level encryption.
- Indexer limits, call edges resolve by name within a directory; repository scope is the unit.
- Language limits, language servers are an optional query-time tier, not an indexing requirement.
Contributing
- Fork, then work on a feature branch; a git worktree is preferred.
- Update the docs when behavior changes: PRD and task tracker.
- Run
make go-build,make go-testandmake go-vet. Storage-layer changes also needmake dual-engine. - Open a pull request with a summary and a test plan.
mainis protected.
See CONTRIBUTING.md and CODE_OF_CONDUCT.md.
Security
Report vulnerabilities according to SECURITY.md. Do not open a public issue for a security problem.