Skip to main content
cairn — five stones, five layers

cairn

Verifiable codebase memory for AI agents — a structural graph + compass + wiki + tribal memory, all local, all traceable to source.

The precise call graph, without the guesswork · every answer re-derivable from local data · 100% local SQLite, no network calls · LLM never in the query path

PyPI version License: MIT Python versions CI

cairn parses your repos with tree-sitter into a resolution-labeled structural graph (15 languages), fuses it with code-grounded tribal memory, compass, and wiki, and serves all of it through one MCP server (25 tools) + a cairn CLI. The product is a verification contract: every exact edge is actually resolved, every symbol in a synthesized doc is graph-verified by a deterministic critic, and the LLM never sits in the query path.

Contents

Get Started

1. Install the CLI

pip install cairn-intel

Already installed? cairn upgrade updates in place (detects uv tool / pipx / pip; --check previews without changing anything).

2. Wire up your agent(s)

cairn install-agents

Detects which AI clients you have (Claude Code, Cursor, ZCode, Droid, Claude Desktop, opencode, agy, kilo, omp), shows what's already wired, and prompts for scope: workspace (per-project ./.claude/, ./.cursor/ …) or global (~/.claude/ — every project inherits it). Non-interactive: cairn install-agents --yes --scope global. Manual wiring is one JSON block (stdio — or point clients that support SSE at http://127.0.0.1:9876/sse after cairn serve start, which is what install-agents does by default):

{ "mcpServers": { "cairn": { "command": "cairn", "args": ["serve"] } } }

3. Build the graph

cairn build          # parse the workspace, resolve edges (first run; ~4s on cairn itself)

4. No more syncing

cairn update         # incremental reindex — only what changed since the last build

With the optional [watch] extra, a running cairn serve watches the workspace and reindexes edits within a ~2s debounce window — no restart, no manual update. Pending files carry a staleness banner on results until the update lands.

Uninstall — cairn uninstall removes agent wiring, hooks, and the graph store; --dry-run previews the scope; cairn uninstall-agents only removes client configs.

Language Support

Fifteen languages, one uniform contract: definitions, call edges (labeled exact / ambiguous / unresolved), references, and inheritance wherever the grammar carries them. .h headers are sniffed to Objective-C / C++ / C.

Language Extensions Status
Kotlin .kt Full
Java .java Full
Swift .swift Full
TypeScript .ts .tsx .mts .cts Full · JSX component refs tracked
JavaScript .js .jsx .mjs .cjs Full · React <Comp/> JSX refs tracked as references edges
Python .py Full
Go .go Full
Dart .dart Full
Objective-C .m .mm Full · .h sniffed
PHP .php .phtml .php3-5 Full (pure-PHP grammar, no HTML mixing)
Ruby .rb .rbw Full
C# .cs .csx Full
C .c Full · .h sniffed
C++ .cpp .cc .cxx .hpp Full · .h sniffed
Rust .rs Generic tier · pinned grammar; call edges stay unresolved

Not indexed (yet): Vue / Svelte single-file components, CSS, HTML. Details: docs/indexing.md.

Why cairn?

A code graph alone is commoditized — several tools index symbols and call edges. Generic agent memory is ungrounded — it lets an LLM silently rewrite what it "remembers." cairn is the narrow intersection: a structural graph fused with code-grounded memory, where every output is traceable to source and every synthesized doc is fact-checked before it lands.

Three promises cairn can machine-check — and does, in CI, on cairn's own code:

  1. Every exact edge is actually resolved. The resolver pins each edge to one definition before labeling it exact (target_id IS NOT NULL); an invariant test guards this on every build.
  2. Every symbol in a compass / wiki / memory doc exists in the graph. A deterministic critic fact-checks every LLM-synthesized doc against the graph before it is written; hallucinated references are rejected or flagged.
  3. Every answer is re-derivable from local data. cairn never calls an LLM in the query path — the LLM stays on a task queue behind the critic gate, so outputs are verifiable, not probabilistic.

Resolution labels are the evidence for promise #1. Every code graph can tell you "who calls this." cairn tells you whether to trust the answer: exact (pinned to one definition — trusted), ambiguous (multiple candidates; the resolver declined to guess), unresolved (external / stdlib). Graph tools default to precise mode — only exact edges — so blast radius is never inflated by name collisions:

cairn impact invoke              # precise (default): real callers only — ground truth
cairn impact invoke --fuzzy      # candidate list (name matches), each labelled unverified

Measured on this repo: 82% of fuzzy results for common names are name-collision noise that precise mode excludes. An empty precise result means "no resolvable callers," not "unused" — retry with --fuzzy before concluding a symbol is dead. And explore surfaces ambiguous dispatch hops — polymorphism that grep fundamentally cannot see.

Honest trade-offs

  • Semantic retrieval is opt-in and mid-band. On the hand-verified ground truth, pooled recall/MRR sit at 0.4174 / 0.2862 — below the 0.50 / 0.33 shipping targets, which is exactly why the semantic stack is an extra, not the default path; the structural tools carry the precision story.
  • The [semantic] extra is heavy. Real embeddings pull sentence-transformers (+ torch on Linux); a one-time ~836 MB model download lives in ~/.cairn/lib/ (scoped per Python version). The default install is torch-free and network-free. Alternative with no download at all: point CAIRN_EMBED_BACKEND at a local OpenAI-compatible embeddings server (oMLX, Ollama, LM Studio) — same bge-m3 vectors, zero torch footprint (configuration.md).
  • Synthesized docs need an LLM pass. Compass/wiki generation runs through the task queue (cairn task) with the critic gate — deterministic, but it won't happen purely locally without any model access.

Key Features

  • Surgical context — explore(query) returns matching symbols' verbatim source, the call paths between them, and a blast-radius summary in one round trip. The recommended first call for agents.
  • Trust-labeled blast radius — precise mode follows only resolved edges; --fuzzy gives an explicitly-labelled candidate list for auditing and dead-code hunts.
  • Cross-repo reach — cross_repo_deps(repo) maps who consumes your public API across registered repos; impact_analysis reports consumer reach.
  • Code-grounded memory — decisions / patterns / mistakes / workarounds, symbol-keyed, recalled alongside graph results; promotion and decay lifecycles keep it honest.
  • Docs as first-class knowledge — cairn knowledge ingest stages markdown / PDF / DOCX (repo doc-trees or fed files) through a reviewable dry-run manifest before anything lands in the store; classification, redaction, and collision-safe identities included.
  • Always fresh — incremental cairn update (git-diff-driven), optional live watch with staleness banners, and cairn doctor's 11 health checks gating CI.
  • 100% local — one SQLite store under ~/.cairn; no network calls, no telemetry egress (OTLP export is opt-in and best-effort).
  • Agent-first surfaces — the same store backs 24 MCP tools and the CLI; cairn install-agents wires every detected client in one command.
  • Local dashboard — cairn dashboard opens a loopback web console at 127.0.0.1:8765: interactive graph with symbol search, recorded tool-call history and token usage (MCP + CLI, mode-labeled estimates), session chains, health/memory panels, a global workspace selector in the topbar (every view follows the selection), a Ctrl/Cmd+K command palette (views, workspaces, symbol search), repo-scoped wiki navigation (grouped catalog with filters and search, breadcrumbs, in-page TOCs, prev/next, graph cross-links), knowledge views over the ingested docs (/knowledge catalog with family/status/tag filters, per-doc detail with supersede chain, relationship panel, and linked code refs, and a /knowledge/graph relationship canvas whose legend chips filter edges in place), a collapsible grouped sidebar, a dark/light theme whose flip re-colors the live graph canvas in place (no reload; canvas physics respects prefers-reduced-motion), CSV/JSON export of any filtered view, an Embeddings status view (probe health, fallback state, per-knob config sources) with the degradation banner, and a Settings page that persists embedding-backend configuration to ~/.cairn/config.json.

How It Works

cairn architecture: AI agents query the MCP server and CLI, which read one local SQLite store; an LLM task queue runs off-path, admitted only through a critic gate

The query path is deterministic: tree-sitter parsing → SQLite graph → FTS5/BM25 fused with vectors (RRF, always on when embeddings exist) and a confidence-gated optional rerank → labeled results. The LLM only ever runs off-path, generating compass/wiki/memory candidates that the deterministic critic verifies symbol-by-symbol against the graph.

Deep dives with diagrams: architecture · indexing · retrieval · knowledge & memory.

Measured Results

Agent effort vs a grep-and-read baseline (cairn bench --suite agent; deterministic arms, no LLM, reproducible in CI — 300-file corpus, 6 task shapes, medians):

metric grep-only baseline with cairn reduction
tokens / query 217,187 1,146 99.5%
tool calls / query 153.2 1.5 99.0%
wall-clock / query 24.9 ms 7.6 ms 3.3×

Depth-3 blast radius is the extreme: 2 tool calls and 712 tokens vs 303 calls and 429,600 tokens — grep must read every name-collision hit; precise edges don't.

SWE-bench efficiency (cairn bench --suite swe-bench; deterministic no-LLM arms over the pinned 50-task SWE-bench Lite subset, benchmarks/datasource/swe-bench-subset.json @ revision 6ec7bb89…. Efficiency medians are their own metric class — not comparable to resolve-rate results like RepoGraph's +32.8%):

metric (median / task) grep baseline with cairn reduction
tool calls 19.5 3.0 84.6%
est. tokens 151,007.5 1,555.5 99.0%

Reproduce: cairn bench --suite swe-bench --smoke (first 2 pinned tasks, fast) or cairn bench --suite swe-bench --json (full pinned subset; the first run fetches the split, reruns run offline). Methodology, determinism and offline contracts, and the stamped result: docs/benchmarks.md.

Query latency (cairn bench --suite perf, p95): find_definition 0.03 ms · get_callers 0.06 ms · impact_analysis 0.11 ms · search_symbols 6.25 ms · semantic_search 201.67 ms (with embeddings) · explore 513.73 ms. First-semantic_search latency after boot warm-up: 15.5 s cold → 232.6 ms warm.

Self-demo — cairn indexes its own source in ~4s (~1,900 symbols / ~11,500 edges), and CI re-runs the build + resolution invariant on every push (tests/test_self_demo.py), so the dogfood cannot silently rot. Reproduce:

git clone https://github.com/tanlnm512/cairn && cd cairn
cairn build
cairn def build_graph               # -> src/cairn/graph/builder.py
cairn impact build_graph            # -> real transitive callers (non-empty)
sqlite3 "$(cairn config --db)" \
  "SELECT COUNT(*) FROM edges WHERE resolution='exact' AND target_id IS NULL"   # -> 0

Run the suites yourself: cairn bench --help and cairn eval --help.

CLI Reference

cairn --help (or cairn <group> --help) is authoritative. The essentials:

Command What it does
cairn serve Run the stdio MCP server
cairn dashboard Local web console, loopback :8765 (views + Settings)
cairn build [--lsp] / cairn update Full build (--lsp optionally upgrades ambiguous Python calls with pyright) / incremental reindex
cairn def <symbol> Find a symbol's definition
cairn impact <symbol> Within-repo blast radius (precise default; --fuzzy to audit)
cairn blast Diff-based reverse-dependency radius (--base <ref>, text/markdown/mermaid/json, precise default with --fuzzy opt-in; empty radius exits 0, unknown base reports fetch-depth guidance)
cairn map Deterministic repository orientation: directory clusters, counts, hubs, hotspots, and dropped counts (--json; capped with --max-clusters / --max-hubs / --max-hotspots)
cairn grep <pattern> Regex or literal search across indexed files, grouped by enclosing symbol (-i, --fixed, --in <prefix>, --max-hits; reports dropped hits/groups)
cairn ask "<question>" Natural-language query routed across all layers
cairn context <file> Compass + memory + wiki context for a file
cairn memory / compass / wiki / task / knowledge … The layered stores + LLM task queue
cairn install-agents / cairn uninstall Wire / remove agent integration
cairn upgrade In-place update from PyPI (--check to preview)
cairn eval / cairn bench Retrieval-quality / performance harnesses
cairn doctor 11 health checks (PASS/WARN/FAIL; exit code gates CI)
cairn report Redacted diagnostic bundle for bug reports (never uploads)

Deep reference: docs/cli-reference.md.

MCP Tools

25 tools across four layers — same store as the CLI:

Layer Tools
graph (12) find_definition, get_callers / get_callees, impact_analysis, cross_repo_deps, semantic_search, search_symbols, repo_map, file_api, explore (the aggregator — recommended first call), federated_search (cross-store), visualize_graph
compass + knowledge base (5) get_compass, search_knowledge, ask_compass (cross-layer router), trace_flow, generate_flow
memory (2) tribal memory: recall_memory, record_memory (lifecycle verbs are CLI-only: `cairn memory digest
knowledge (6) OKF business docs / workflows: add / search / status / delete / trace_workflow / wiki_generate

Per-tool shapes and examples: docs/mcp-tools.md.

Configuration

Workspace cairn.json may set "include_nested_repos": true to index initialized submodules and nested child repositories under prefixed repo ids; the default is false. A linked worktree without a store is seeded from the main checkout graph and then refreshed for worktree drift; the main store is never mutated.

The default install is dependency-light and network-free. Opt in with extras:

Extra Adds Key env var
[semantic] sentence-transformers — real embeddings and rerank (torch-based, large) CAIRN_RERANK=1/=0; CAIRN_FUSION (default on)
[ann] sqlite-vec — explicit ANN install (core since 0.14) CAIRN_ANN_BACKEND=sqlite-vec
[ingest] pymupdf4llm + mammoth + markdownify — PDF/DOCX conversion for cairn knowledge ingest cairn.json ingest key (classification rules)
[watch] watchdog — live rebuilds while cairn serve runs CAIRN_WATCH=0 disables
[otlp] OpenTelemetry export of local telemetry events CAIRN_OTEL_ENDPOINT (unset = off)

Also: CAIRN_HOME (store location, default ~/.cairn), CAIRN_TELEMETRY=off (master kill switch). Full reference: docs/configuration.md.

Supported Platforms & Agents

  • Platforms — anywhere Python ≥ 3.10 runs; CI tests 3.10–3.14 (macOS + Linux; make ci-local replicates CI in a clean Linux container).
  • Agents — Claude Code, Cursor, ZCode, Droid, Claude Desktop, opencode, agy, kilo, omp — wired by cairn install-agents, or any MCP client via the manual JSON block above.

Documentation

Full index: docs/README.md. The short map:

Read For
docs/architecture.md system shape, storage layout, module map
docs/indexing.md how cairn build / update work, resolver tiers
docs/retrieval.md the hybrid query pipeline and its knobs
docs/knowledge-and-memory.md doc ingestion, memory tiers, task queue, critic
docs/mcp-tools.md · docs/cli-reference.md the two tool surfaces
docs/configuration.md cairn.json, env vars, install extras
docs/benchmarks.md benchmark suites, methodology, reproducing published numbers

Visual overviews (standalone HTML) live in docs/diagrams/: system architecture, the C4 model, indexing, retrieval, and doc-ingestion pipelines. Contribution and release procedures: docs/review-checklist.md · docs/release-checklist.md.

Troubleshooting

  • cairn doctor — 11 health checks with PASS/WARN/FAIL each; non-zero exit means an active degradation (agents can gate on it).
  • cairn report — redacted diagnostic bundle for bug reports; it never uploads anything.
  • Empty impact / get_callers on a symbol you know is used → it's precise mode: retry --fuzzy / fuzzy=True; the name-matches list is labelled.
  • cairn update did nothing on a fresh clone → that's correct (clean tree, no diff); run cairn build first.

Development

pip install -e ".[dev]"   # full review gate: pytest, ruff, mypy, bandit,
                            # pip-audit, pre-commit, commitizen
                            # (compiles the vendored Kotlin grammar — needs a C toolchain)
pytest -m core            # fast <3s smoke subset (one test per core function)
pytest                    # full suite (default gate + infra tier; CI splits them)
pytest -m infra           # bench/dataset/soak tier alone (CI runs it on main pushes)
make ci-local             # clean-room CI replication in a Linux container

pytest -m core includes the cairn-on-cairn self-demo: cairn indexes its own source in an isolated temp DB and asserts the core queries return correct results for known symbols — and that the resolution invariant holds on the verifier's own code. Releases are cut by tagging vX.Y.Z (tag-triggered workflow; see docs/release-checklist.md). Contributions follow docs/review-checklist.md.

Dependency Licenses

MIT-licensed; dependencies are all permissive (MIT, BSD, Apache-2.0, MPL-2.0, PSF) — see NOTICE. The optional [semantic] extra resolves torch (+ NVIDIA CUDA components on Linux, under their own licenses) at install time; the BAAI/bge-m3 embedding model (MIT) downloads on demand to ~/.cairn/lib/cp<version>/ and is not redistributed with cairn.

Status

Beta — pre-1.0 (v0.18.0). Public surfaces (CLI flags, MCP tool shapes, knowledge-file layout) may still shift before 1.0. Feedback welcome via GitHub issues.

License

MIT — © 2025–2026 Tan Le

Metadata

Release files for cairn-intel 0.21.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cairn-intel 0.21.0
File Size Uploaded
cairn_intel-0.21.0.tar.gz 4.6 MB Details

Built distributions (wheels)

Table of built distributions (wheels) for cairn-intel 0.21.0
File
cairn_intel-0.21.0-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details
cairn_intel-0.21.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl CPython 3.10 abi3 Linux glibc 2.17+ x86-64, Linux glibc 2.28+ x86-64 Details
cairn_intel-0.21.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl CPython 3.10 abi3 Linux glibc 2.28+ ARM64, Linux glibc 2.17+ ARM64 Details
cairn_intel-0.21.0-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details

Total release size: 15.1 MB

Release files / cairn_intel-0.21.0.tar.gz

Download URL cairn_intel-0.21.0.tar.gz
Size 4.6 MB
Tags Source
SHA-256 checksum
How to use checksums
16a3b981de6a68c40a9069cd15eb96ad208152cbc9cff8fc2434a495b50defa9
BLAKE2b-256 checksum
How to use checksums
703cb972c86ac83789c1de31d1c582ffda8e225537a2578c8a3f4511b5af4cc1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.

Transparency log

Release files / cairn_intel-0.21.0-cp310-abi3-win_amd64.whl

Download URL cairn_intel-0.21.0-cp310-abi3-win_amd64.whl
Size 2.6 MB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
14a99771349e123531ac0c9cc47d2cbce3f7c093452d31e94ebd2a72325094b6
BLAKE2b-256 checksum
How to use checksums
1531250fdc8494f2003fd266216737d40bf8fd43d02535be8d881d1d27bcd569
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.

Transparency log

Release files / cairn_intel-0.21.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl

Download URL cairn_intel-0.21.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
Size 2.6 MB
Tags CPython 3.10 Linux glibc 2.17+ x86-64 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
75ec3b27cc361d71f28c304a0d441dde752453f98a37768484fa5af2c00b7260
BLAKE2b-256 checksum
How to use checksums
75325ae532e135dd635993d510f42e2bfe873354d3c24a3cdf528884afe49b32
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.

Transparency log

Release files / cairn_intel-0.21.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl

Download URL cairn_intel-0.21.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl
Size 2.6 MB
Tags CPython 3.10 Linux glibc 2.17+ ARM64 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
696d46592f96da65ba40fa31dcf886484b5d5243720ef10932e7a178a2c18397
BLAKE2b-256 checksum
How to use checksums
214a3b250211ae93984a30246ea4b4de53e0d514e6d726c93a697f9c97c70cca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.

Transparency log

Release files / cairn_intel-0.21.0-cp310-abi3-macosx_11_0_arm64.whl

Download URL cairn_intel-0.21.0-cp310-abi3-macosx_11_0_arm64.whl
Size 2.6 MB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
1ada82a9841d79d80f379f1e843e8b08364063bee66ae09330b449e454a9606f
BLAKE2b-256 checksum
How to use checksums
522ce03fc90b9938cfb4f85966bc379784c2a1e4413b7474ea70e5b654715588
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.

Transparency log

Release history Release notifications | RSS feed

0.21.2

5 release files

0.21.1

5 release files

This release

0.21.0 This release

5 release files

0.20.2

5 release files

0.20.1

5 release files

0.20.0

5 release files

0.19.1

5 release files

0.16.2

5 release files

0.16.1

5 release files

0.16.0

5 release files

0.15.0

5 release files

0.14.4

5 release files

0.14.3

5 release files

0.14.2

5 release files

0.14.1

5 release files

0.14.0

5 release files

0.13.0

2 release files

0.12.1

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page