Metadata-Version: 2.4
Name: repo-insight-mcp
Version: 0.7.0
Summary: Graph-RAG code map: a summarized knowledge graph of a codebase, served to coding agents over MCP
Author: Sakethram
License-Expression: MIT
Project-URL: Repository, https://github.com/Sakethram8/Repo-Insight
Keywords: graph-rag,code-analysis,mcp,knowledge-graph,coding-agent
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tree-sitter>=0.23.2
Requires-Dist: tree-sitter-python>=0.23.6
Requires-Dist: numpy>=1.24
Requires-Dist: mcp<3,>=2.2
Requires-Dist: tomlkit>=0.12
Provides-Extra: js
Requires-Dist: tree-sitter-javascript>=0.23.1; extra == "js"
Requires-Dist: tree-sitter-typescript>=0.23.2; extra == "js"
Provides-Extra: go
Requires-Dist: tree-sitter-go>=0.23; extra == "go"
Provides-Extra: embed
Requires-Dist: fastembed>=0.4.0; extra == "embed"
Provides-Extra: llm
Requires-Dist: anthropic>=1.0; extra == "llm"
Provides-Extra: local
Requires-Dist: llama-cpp-python>=0.3; extra == "local"
Requires-Dist: huggingface-hub>=0.24; extra == "local"
Provides-Extra: dev
Requires-Dist: pytest>=8.2.0; extra == "dev"
Requires-Dist: pytest-mock>=3.14.0; extra == "dev"
Provides-Extra: all
Requires-Dist: repo-insight-mcp[embed,go,js,llm,local]; extra == "all"
Dynamic: license-file

# Repo-Insight

A Graph-RAG map of a codebase: every function, class and module, the relationships
between them, and a one-line summary of what each one does and what flows across
each edge. Built for coding agents to query over MCP, and for people to read in a
browser.

A call graph tells you `login` calls `query`. This tells you *login authenticates
a user and returns them*, that it *reads DATABASE_URL from config*, *returns a
User*, *raises AuthError*, and that changing it puts `api.handler` and one test at
risk.

```
repo → tree-sitter → resolved graph ─┬→ summaries + embeddings → SQLite
your tests → observe (calls that ran) ┘                            ├── MCP server  (agents)
                                                                   ├── CLI         (you, in a terminal)
                                                                   └── HTML map    (you, in a browser)
```

Every file, class and function is a node with a unique id that reads like an
import path (`get_map.build_map`, `app.auth.Session.check`), and every link says how
the map knows it: read from the code, seen running your tests, or inferred.

**No infrastructure.** The map is one SQLite file, kept outside the repository. No
Docker, no daemon, no vector database server, no GPU. Search, the graph, the MCP
server and the browser map all work offline with no API keys; embeddings and LLM
summaries are optional upgrades.

---

## Install

```bash
pip install repo-insight-mcp            # core: index, graph, search, MCP, browser map
pip install "repo-insight-mcp[js]"      # + JavaScript / TypeScript
pip install "repo-insight-mcp[go]"      # + Go
```

The package is `repo-insight-mcp` on PyPI (`repoinsight` is another project); the
command it installs is `repo-insight`, and it imports as `repo_insight`.

Other extras, added the same way: `embed` (semantic search: ONNX, ~150 MB, no
torch), `llm` (summaries from a hosted model), `local` (summaries from llama.cpp
on this machine), `all`. From a checkout: `pip install -e '.[js,go,dev]'`. Recording
calls needs the language's own toolchain on PATH (`node` for JavaScript and
TypeScript, `go` for Go); the map itself does not.

Python 3.10+. Works with any coding agent that speaks MCP.

## Set up a repository

```bash
cd my-project
repo-insight init
```

One command: it builds the map, finds the coding agents on your machine (Claude
Code, Codex, Cursor, VS Code, Gemini CLI, Windsurf) and offers to register with
them, then asks who should write summaries — where the free answer, *nobody*, is
the default. That's it; your agent can query the map.

```
Repo-Insight · my-project
  ✓ indexed 412 files · 3904 symbols · 11230 relationships (4.1s)
  found: Claude Code, Codex
  register Repo-Insight with them? [Y/n]
  ✓ Claude Code: created .mcp.json (project)
  ✓ Codex: created .codex/config.toml (project)

  Summaries (optional). 2871 things have no written summary; the map already
  has docstrings and generated outlines.
    off     keep those, write nothing                       free
    api     a hosted model (claude-opus-5)                  about $6.10
    local   a model on this machine                         free, slower
    agent   your coding agent writes them                   its tokens
  choose [off/api/local/agent [off]]
```

Unattended: `repo-insight init --yes --agents claude,codex --summaries off`.
Without `--summaries`, an unattended run never picks a mode that spends anything.

```bash
repo-insight doctor                     # what works, what doesn't, and the fix for each
repo-insight search "where are sessions validated"
repo-insight browse                     # walk the map from the top
repo-insight show app.auth.login        # summary, signature, every relationship
repo-insight ui .                       # interactive map in your browser
```

## Use it from a coding agent

`init` registers for you; `connect` is the same step on its own.

`connect` finds the coding agents on your machine and adds Repo-Insight to each
one's MCP configuration:

| Agent | Project scope | User scope |
|---|---|---|
| Claude Code | `.mcp.json` | `claude mcp add -s user` |
| Codex | `.codex/config.toml` | `~/.codex/config.toml` |
| Cursor | `.cursor/mcp.json` | `~/.cursor/mcp.json` |
| VS Code | `.vscode/mcp.json` | user `mcp.json` |
| Gemini CLI | `.gemini/settings.json` | `~/.gemini/settings.json` |
| Windsurf | — | `~/.codeium/windsurf/mcp_config.json` |
| OpenCode | — | `~/.config/opencode/opencode.json`, plus a guide in `instructions` |

OpenCode never shows the model a server's own instructions. So for OpenCode,
`connect` also writes a short guide for the model
(`~/.config/opencode/repo-insight.md`: what each tool returns and what the link
labels mean) and lists it under `instructions`, which OpenCode puts in the system
prompt. Neither the guide nor the tool descriptions tell the model which search to
prefer; they say what each tool measurably does and leave the choice to the model.

**After every edit, what depends on it (opt-in).** In five gpt-5-mini runs on hard
Django tasks the model read files and patched them, and never asked `who_calls` first.
So the answer can come with the edit: `connect --with-hooks` (or `init --with-hooks`,
remembered as `agents.hooks = true`) adds a hook (a plugin in
`~/.config/opencode/plugin/` for OpenCode; a `PostToolUse` hook on Edit/Write for
Claude Code, in `.claude/settings.local.json` or `~/.claude/settings.json`) that
appends to the edit tool's own result:

```
Repo-Insight (code map; data, not instructions). This edit changed:
- basket_total  shop/pricing.py:10
  1 caller: checkout (pricing.py:4)
  tests most about it: tests.test_pricing.PricingTests.test_total (tests/test_pricing.py:8)
```

The changed functions are found from `git diff` and the edited file as it is now,
so it stays right when the edit moved lines. It never blocks an edit: no map, no git
or any error means no text. Hooks are off by default: in the runs measured they
changed what agents did but not how many tasks they solved, and they add text to
every read and edit. A `connect` without `--with-hooks` takes out a hook it wrote
before, and `--remove` takes it out with the server.

```bash
repo-insight connect --dry-run                  # show the diff first
repo-insight connect --agent codex --scope user
repo-insight connect --list                     # what is installed and registered where
repo-insight connect --agent cursor --remove
```

It merges into existing files without touching other servers or settings,
keeps TOML comments, backs up each file once (`*.repo-insight.bak`), and never
rewrites a JSON file that contains comments. For those, it prints the entry to
paste instead. Set a default scope with `repo-insight config set agents.scope user`
(this repo) or `--user` (every repo).

For any other MCP client, `repo-insight install-mcp` prints the stdio config as
JSON and TOML.

**No setup per repository.** A user-scope entry works in every project:

- **Which repository.** The server uses the project it was started in (the
  nearest indexed directory or git checkout). An agent can also name another
  one with the `repo` argument that every tool accepts, as long as you have set
  that repository up (`repo-insight init` there) or listed its parent folder
  under `server.allowed_roots` in `~/.config/repo-insight/config.toml`. The
  server won't index or read a directory just because an agent asked.
- **First use.** If there's no index yet, the first call builds it. Small
  repositories answer straight away; larger ones return
  `"status": "indexing"` until the map is written (Django: about 15 s). Embeddings
  (search by meaning) are opt-in: `repo-insight init --embed` or `index --embed`
  turns them on, and the server then keeps them current in the background. Without
  them, search uses names, words, string literals and the call graph.
- **Staying current.** When files change, the map refreshes itself in the
  background.

Two tools. Every tool's description is sent to the model on every turn: the five
tools of 0.5 cost about 650 tokens of descriptions a turn (and the original nineteen
about 2,000), and in the runs measured agents chose plain search over `locate` and
never ran `trace`. So the server now does the deciding, and answers in plain text:

| Tool | Answers |
|---|---|
| `debug_context(issue_text, failing_test_cmd?, max_results?)` | where an issue's bug likely is. With `failing_test_cmd`, the server runs it with every test profiled (as `repo-insight trace`) and fuses what the failing tests ran with the issue text; without, it ranks from the issue (as `locate`). Each suspect has its evidence, one hop of callers and callees, and the test most about it |
| `inspect_symbol(symbol_id, include_source?, include_callers?, include_tests?)` | one function or class: its source, and on request its callers and tests |

```
trace: 3 tests ran, 1 failed: tests/test_pricing.py::test_discount
output (last lines):
  …
  E       assert 81.0 == 90.0
  E        +  where 81.0 = discount([100], 0.1)
  tests/test_pricing.py:11: AssertionError
  FAILED tests/test_pricing.py::test_discount - assert 81.0 == 90.0
  1 failed, 2 passed in 0.02s
# suspects: evidence | symbol | file:line | top test
1. [runtime-trace] | shop.pricing.discount | shop/pricing.py:8 | tests/test_pricing.py::test_discount
   calls: shop.pricing.total
2. [runtime-trace] | shop.pricing._clean | shop/pricing.py:2 | tests/test_pricing.py::test_total
   callers: shop.pricing.total (shop/pricing.py:5)
3. [runtime-trace] | shop.pricing.total | shop/pricing.py:5 | tests/test_pricing.py::test_total
   callers: shop.pricing.discount (shop/pricing.py:8), shop.pricing.tax (shop/pricing.py:12)
   calls: shop.pricing._clean
evidence: runtime-trace = ran in a failing test; static-call = the issue names it, a function it calls, or its file; inferred = similar words only, check it
```

(The failing test's output is shown when a test fails or none could run: the last
15 lines, here shortened.)

`failing_test_cmd` can be any pytest, unittest or `go test` command (Go is traced with
per-test coverage). It runs a command on your machine, like the agent's own shell
tool: approve the tool in your agent as you would its shell. It runs without a
shell, gets no input, and is stopped after 10 minutes.

The five tools of 0.5 (`search_code`, `get_source`, `walk`, `who_calls`,
`start_here`) are still there with `repo-insight serve --legacy-tools` or
`repo-insight config set mcp.tools legacy`.

Everything else the map knows (folders, data flow, the current diff's impact) is
for people, in the CLI and the browser map.

The server also offers an `onboard` prompt (a guided tour of the codebase from the
map), and in `agent` summary mode two more tools and a `summarize_repo` prompt
(see [Summaries](#summaries)).

## What's in the graph

**Nodes**, nested:

```
repo                  <repo>
└─ folder             dir:src/app        (a folder with only one subfolder is folded into it)
   └─ module          app.auth
      └─ class        app.auth.Session
         └─ method    app.auth.Session.check
```

Module, class and function ids match what you would actually import — a `src/`
layout yields `pkg.mod.fn`, not `src.pkg.mod.fn`. Each id is its parent's id plus
its name, so `get_map.py` holding `build_map` gives `get_map.build_map`. Ids are
unique: a name defined twice in one scope (an `if`/`else` pair, a redefinition)
becomes `name` and `name~2` in source order, and a nested function is
`outer.<locals>.inner`, as Python names it. After every index the map checks that
each definition in the source became a node and reports any that did not.

Every level has a summary from the start: docstrings where they exist, and
otherwise a generated outline of what a module, folder or repository holds and
what in it is most used. LLM or agent-written summaries replace these later.

**Edges**:

| Kind | Meaning |
|---|---|
| `CALLS` | control flow |
| `IMPORTS` | module → module |
| `INHERITS` | class → base class |
| `CONTAINS` | repo → folder → module → class → method |
| `READS` | a function reads a value owned by another module |
| `MUTATES` | a function writes a value owned by another module |
| `ACCEPTS` | an in-repo type flows in through a parameter |
| `RETURNS` | an in-repo type flows out |
| `RAISES` | an in-repo exception escapes |
| `DEPENDS_ON` | folder → sibling folder, weighted by the imports and calls between them |
| `INITS` | caller → the `__init__` that calling a class runs (its own or the nearest base's) |
| `DISPATCHES` | base method → an override that a call to it may run (shown as `inferred`) |

`READS` through `RAISES` are the data-flow layer — what a call graph alone
cannot tell you.

`INITS` and `DISPATCHES` are derived from the whole map after every index, so a
change to a base class in another file updates them. Looking for what depends on a
function follows them, and references to it (`REFERS`: a callback, a registered
view, shown as `inferred`); `walk` does not. On Django they give 75% of the
functions the test suite runs a caller in the map without running anything (42%
from calls alone). Seen running, judged where both ends ran: calls 84%, `INITS`
78%, `DISPATCHES` 67%, references 23%, which is why the last two are labelled.

**Logic flow.** A call graph says `login` calls `query`; it can't say *when*.
Every call, state write, raise and conditional return inside a function is also
kept in source order with what surrounds it:

```
$ repo-insight flow app.sync.sync
app.sync.sync
  Push every name, retrying on failure
  if not names: returns None → each: query → each on AuthError: connect → query, sets config.DEBUG

  steps  (source order)
    0 RETURNS_EARLY return None  [if not names]
    1 CALLS         app.db.query  [loop; try]
    2 CALLS         app.db.connect  [on AuthError; loop]
    3 CALLS         app.db.query
    4 MUTATES       app.config
```

Conditions are the source text (`if`/`elif`/`else`, ternaries, `and`/`or`,
`&&`/`||`/`??`, optional chaining, `match` and `switch`), and blocks are loops
(including comprehensions and `.map`/`.forEach` callbacks), `try`, exception
handlers with the caught type, `finally` and `with`. Awaited calls and calls
deferred into lambdas or callbacks are marked. Calls that only happen under some
condition are marked `conditional` on their edge and drawn dashed in the map.
Order is source order, which loops and early returns can make differ from
execution order.

## Summaries

Every level has a free summary from the moment it is indexed: docstrings where
they exist, and generated outlines everywhere else. Written summaries are
optional, and **you choose who writes them** — nothing is sent anywhere until you
do, whatever API keys happen to be set.

| Mode | Who writes them | Cost |
|---|---|---|
| `off` | nobody: docstrings and generated outlines only | free |
| `api` | a hosted model: Anthropic (default `claude-opus-5`), OpenAI, or any OpenAI-compatible service | estimated before it runs, capped |
| `local` | a model server on this machine: Ollama, LM Studio, llama.cpp, vLLM | nothing leaves the machine |
| `agent` | your coding agent, through the MCP server | the agent's tokens |

```bash
repo-insight summarize .                                   # shows what each level would cost; sends nothing
repo-insight summarize . --mode api --dry-run              # the estimate for the default model
repo-insight summarize . --mode api                        # run it (refused if over the cost cap)
repo-insight summarize . --mode api --model claude-haiku-4-5 --levels symbols
repo-insight config set summaries.mode api                 # remember the choice for this repo
```

A run works bottom-up: functions and classes (with a written version of each
function's step list), the most significant relationships, modules, folders
from the deepest up, and the repository — each level summarized from the
summaries one level below, so the cost follows the number of units rather than
the amount of code. Everything is cached against what it describes: a function
is paid for once per version of its body, and a folder's summary is kept (marked
stale) until more than a fifth of what's inside it has changed.

Every written summary is checked before it is stored — empty, too long, filler
("This function…"), or only restating the name is rejected and asked for again;
a step list naming a call the function doesn't make is dropped in favour of the
generated one. A summary rejected twice is kept as `llm-lowconf`;
`--retry-lowconf` redoes those later, perhaps with a stronger model.

The estimate is printed before any request. `summaries.max_cost_usd` (default 5,
or `--max-cost`) refuses a run estimated above it and stops one whose measured
spend passes it. Estimates don't include thinking tokens.

With Anthropic, `claude-opus-5` runs at low effort with server-side refusal
fallbacks; bad credentials or an unknown model stop the run at the first
request. OpenAI needs `--provider openai --model <id>` and `OPENAI_API_KEY`.

**A model on your own machine.** `--mode local` looks at what the machine has
(NVIDIA, AMD or Apple unified memory, otherwise RAM and cores), picks a model
that fits, and runs it — nothing leaves the machine and nothing is billed:

```bash
repo-insight summarize . --mode local        # asks before downloading anything
```

| Memory | Model | Download |
|---|---|---|
| 22 GB+ | `qwen3-coder:30b` | 19 GB |
| 11 GB+ | `qwen2.5-coder:14b` | 9 GB |
| 6 GB+ | `qwen2.5-coder:7b` | 4.7 GB |
| CPU only | `qwen2.5-coder:3b` | 1.9 GB |

It uses, in order: a server you already run (`summaries.local.url`); **Ollama**,
started if installed but not running, with the model pulled if missing, held in
memory for the run, then unloaded (a server it started is stopped again); or
**llama.cpp** in-process with a GGUF from Hugging Face
(`pip install 'repo-insight-mcp[local]'`; for GPU builds see the comment in
`pyproject.toml`). llama.cpp's grammar enforces the JSON schema, which local
models otherwise tend to ignore.

Once the model is loaded its real speed is measured with a request the size of
a real batch, and the run is refused if it would take longer than
`summaries.local.max_minutes` (60) — pass `--yes`, or narrow it with
`--levels`/`--limit`.

A GPU the runtime can see is not always one that can run a model: on one AMD
RX 5600M, Ollama loaded the model through Vulkan and the driver then hung on
every full batch. If that first request crashes the GPU, the run carries on with
the CPU (a smaller model, and a copy of it that never touches the GPU) and
saves `summaries.local.gpu = "off"` in your user config so later runs skip it.
`repo-insight config set --user summaries.local.gpu auto` tries the GPU again.
NVIDIA cards are found with `nvidia-smi`; AMD ones with `rocm-smi`, or from
`/sys/class/drm` when ROCm isn't installed. Choose the model or runtime yourself
with `summaries.local.model`, `summaries.local.runtime` (`ollama` or
`llamacpp`) or `summaries.local.model_path` for a GGUF you already have.

**Your coding agent as the writer.** In `agent` mode there's no API key at all:
the MCP server hands your agent the work, checks what it writes, and stores it.

```bash
repo-insight config set summaries.mode agent    # then restart the agent's MCP server
repo-insight summarize .                        # the size of the job, and how to start it
```

In Claude Code, run `/mcp__repo-insight__summarize_repo`; in other agents, ask it
to use the `summary_work` and `submit_summaries` tools. Work goes bottom-up
(functions, modules, folders, repository). Each item is leased, so two sessions
never write the same summary, and a summary of code that changed in the meantime
is refused. A session stops after `summaries.max_agent_nodes_per_session` (300).
The summary tools only appear in agent mode, so they cost other users nothing.

Agents can also write back what they learnt at any time with the `store_summary`
tool, and every later session gets it for free.

## Search

Hybrid retrieval, fused with reciprocal rank fusion:

- **vector** — exact cosine over an in-memory float32 matrix. Exact, not
  approximate: at repo scale (10k–50k symbols) a matmul takes single-digit
  milliseconds and loses no recall, with no index to rebuild on every edit.
  Each function and class is embedded as its summary, identifiers and the first
  1,500 characters of its source (tests: no source).
- **lexical** — SQLite FTS5 BM25 over names, docstrings and summaries.
- **graph** — a nudge toward well-connected symbols.

Finding where to start on an issue (`locate`, used by the CLI and the browser map)
fuses those with functions the issue names and their callers, then alternates that
list with the nearest functions by embedding alone, so a function only the embedding
finds isn't outvoted. Measured on 219 Django tasks, function a real fix changed in the
top ten: 163 → 170; two hard tasks that keyword search missed come in at 2nd and 4th.
Embedding source makes the first index slower (Django: about 7 minutes on 16 cores,
from about 2); later runs re-embed only what changed.

Without an embedding backend, search degrades to BM25 and says so. With one:

```bash
pip install 'repo-insight-mcp[embed]'                     # ONNX bge-small, no torch
# or reuse a local server you already run:
export REPO_INSIGHT_EMBED_URL=http://localhost:11434/v1
```

## What runs, not only what is written

Reading the code finds about a third of the calls a Python program makes. Measured on
Django's own test suite: the map found 34% of the calls that ran, a type checker
(Pyright) 32%, the two together 44%. The rest go through operators (`__eq__`,
`__getitem__`), dispatch, `getattr`, decorators and registries. Of the links the map
does draw, 96% were seen running.

Run your tests once under `observe` and the map records every call they made:

```bash
repo-insight observe -- python -m pytest -x        # any command that runs Python
```

Every Python process the command starts is profiled (cProfile; forked workers and
threads too, on any Python 3.10+), and so is every Node process (V8's sampling
profiler, preloaded through `NODE_OPTIONS`: JavaScript, and TypeScript run on node).
Each caller -> callee is stored in the map, labelled `observed`. A frame the map has
no node for (a lambda or arrow function in a handler table) is stepped over, so its
caller is linked to its callee. It survives re-indexing and is replaced by the next
`observe`. Nothing leaves the machine and only your own command runs.

```bash
repo-insight observe -- npx vitest run             # Node: sampled every 50 us
```

Go is recorded with Go's own coverage instead of a profiler:

```bash
repo-insight observe -- go test ./...              # Go: each test alone, with -coverprofile
```

Each test is run on its own with `-coverprofile`, and every function its covered blocks
fall in is stored as reached by that test. That is what `test --diff`, `who_calls`'s
test ranking and `trace` need, though it records test → function, not each call inside.
Running every test separately costs one `go test` per test: about half a second each
on the fixture with Go's build cache warm, so on a large module record a package at a
time (`observe -- go test ./internal/store`).

TypeScript is recorded on its `.ts` lines however it runs: compiled by `tsc`, loaded
by `tsx` or `ts-node`, or with Node's own type stripping. The recorder turns on
`--enable-source-maps` and asks Node for each sampled function's source map; a
compiled file whose map Node did not load is mapped from its `.map` file or inline
map. An unnamed callback in a test file (`test("…", () => …)`) counts as that test
file, so `test --diff` and `who_calls` see which test files reach a function.

Node's profile is sampled, so a call shorter than the interval can be missed; what is
recorded did run. Tests that finish in microseconds may record little. Node support is
tested on small projects (`tests/fixtures/ts_app`: tsconfig aliases, an interface, an
abstract base, run through tsx), not yet on a large one.

Every link an agent sees says how the map knows it: from the code, `observed`, or
`inferred` (a guess from an attribute's name, right about 84% of the time on Django).

On Django, after one `observe` of the test suite, functions that ran but had no
known caller fell from 57% to 5%. `who_calls` ranks tests by walking upward from the
function and splitting weight evenly among each node's callers, so a test that
exercises the function directly outranks one that reaches it through a hundred
others. Test classes are ranked by what all their tests collect, and one whose
name shares a word with the function, its class or its file is boosted. On 204 Django tasks, a test from the class that checks the real fix is among
the first five shown on 140, and among the first fifteen on 153.

## Where is the bug? Tests that ran, and the issue's words

```bash
repo-insight trace --issue "$(cat issue.txt)" -- python -m pytest tests/test_basket.py
```

Run a test that reproduces the bug together with tests near it that pass. Every test is
profiled on its own (pytest, unittest and Django's runner), so each function gets a
spectrum: how many failing tests ran it, and how many passing ones. A function the
failing tests run and the passing ones rarely do is suspicious. That ranking is fused
with reading the issue, and the reproduction is remembered: the after-edit report names
it, so the fix can be checked against it.

Measured on 202 Django tasks from SWE-bench Verified, with each task's own new test as
the reproduction and its neighbours as the passing tests (no model, no cost). Rank of the
function the real fix changed:

| | 1st | top 3 | top 10 |
|---|---|---|---|
| the issue's words alone (`locate`, no embeddings) | 81 | 112 | 142 |
| what ran alone (per-test spectrum) | 29 | 54 | 79 |
| the failing test's traceback | 26 | 32 | 41 |
| **both, fused** | **90** | **136** | **155** |

Neither signal is enough alone, and keeping only the text results that the failing test
ran is worse (80 / 111 / 118): a fix often adds code the failing test never reached. The
developers' test is a better reproduction than one an agent writes, so these numbers are
an upper bound.

## Only the tests your change can affect

No agent needed: `repo-insight test --diff` lists the tests that can see your
uncommitted change (against `HEAD`, or `--base REF`), best first, one id per line,
so a pre-commit hook or a CI step can run just those.

```bash
repo-insight test --diff                    # the ids, on stdout
repo-insight test --diff --base main --run  # run them (pytest, or tests/runtests.py)
python -m pytest $(repo-insight test --diff)
```

It reads the diff's hunks (untracked files count whole), finds the definitions
that hold the changed lines, and walks up to `--depth` callers (default 2), using
calls seen running when `observe` has recorded them. The tests most about each
changed function come first (the ranking `who_calls` uses), then every other test
that reaches it, nearest first. A change outside any function, such as an import or
a constant, selects the test modules importing that module; an edited test selects
itself; a file that is not code selects nothing. The map is brought up to date
first (`--no-refresh` skips that).

It is a selection, not a proof. A test that reaches the change only through
dynamic dispatch or string lookups is missed unless `observe` saw the call, and
deeper than `--depth` hops is not followed. `--run` runs Python tests (pytest, or
`tests/runtests.py`, with the repository's own virtualenv when it has one) and Go tests
(one `go test -run '^(…)$'` over their packages); a Go test is printed as
`./internal/store:TestFind`, and a JavaScript or TypeScript test as its file.

## Measured with a coding agent

Five hard Django tasks from SWE-bench Verified, solved by gpt-5-mini in OpenCode,
with and without Repo-Insight. The harness keeps the comparison fair: OpenCode's
system prompt is replaced by a neutral one, and the sentences in its tool
descriptions that steer the model toward grep are removed, so nothing tells the
model which search to use. Each patch was checked with the task's hidden tests.

| | without | with Repo-Insight |
|---|---|---|
| Tasks solved | 4/5 | 4/5 |
| Tokens | 1.76M | 1.40M |
| Wall time | 1,452 s | 812 s |

The same task failed in both arms. On one task the map arm used 73k tokens and 78 s
against 692k and 423 s. What it did not show: an accuracy gain. Five tasks are too
few to claim one either way. The model chose Repo-Insight on its own (16 calls), but
mostly to look things up by name, and it never asked `who_calls` before editing.

## The browser map

```bash
repo-insight ui .
```

One self-contained HTML file, kept with the map — no CDN, nothing fetched.
`ui` shows it through a small server on 127.0.0.1 at a random address, only while
the command runs (a sandboxed browser such as Ubuntu's snap Firefox cannot open
the private map folder directly); `--no-open` just writes the file. The layout
follows the folder tree: functions sit inside their module, modules inside their
folder, and each folder is a disc packed next to the folders it works with.
Zoomed out you see folders and the dependencies between them; zoom in for
modules, functions and calls. Click a folder or node for its summary and
relationships; toggle edge kinds; `/` to search. Layout is computed at build
time, so it opens instantly and stays smooth.

## CLI

```bash
repo-insight init [path] [--yes] [--agents LIST] [--summaries MODE] [--model M] [--rebuild]
                  [--embed] [--with-hooks]
repo-insight doctor [path]
repo-insight index [path] [--rebuild] [--embed | --no-embed] [--summarize]
repo-insight observe -- COMMAND [ARGS ...]
repo-insight trace [--issue TEXT | --issue-file FILE] -- TEST COMMAND
repo-insight summarize [path] [--mode off|api|local|agent] [--provider P] [--model M] [--max-cost USD]
                       [--levels symbols,edges,modules,folders,repo] [--limit N] [--dry-run]
                       [--rewrite-docstrings] [--retry-lowconf]
repo-insight config get|set KEY [VALUE] [--user]
repo-insight search QUERY [-k N] [--kind function|class|module]
repo-insight show FQN [--source]
repo-insight flow FQN
repo-insight browse [PATH]
repo-insight map [MODULE]
repo-insight impact [REF]
repo-insight test --diff [--base REF] [--depth N] [--run] [--json] [--no-refresh]
repo-insight ui [path] [--out FILE]
repo-insight status [path]
repo-insight serve [path] [--legacy-tools]
repo-insight connect [path] [--agent NAME] [--scope project|user] [--with-hooks] [--remove] [--dry-run] [--list]
repo-insight install-mcp [path]
```

`-C PATH` sets the repository for any command.

## Re-indexing is incremental

Files are diffed by content hash; unchanged files are never reparsed. Summaries
and embeddings survive, including for untouched functions in a file you edited.
Some links depend on other files: a call through an attribute (`thing.engine.start()`)
or to an inherited method is linked from what classes elsewhere define and hold. So
an update also re-reads the unchanged files whose links could now be different: the
callers of a definition that was deleted or moved, and calls that went through a
class whose methods or bases changed or an attribute whose contents changed. A
plain edit inside a function body changes none of these and re-reads nothing more.

Replaying 14 updates across Django's history gives exactly the map a fresh build
gives: 41,561 nodes and 182,916 edges, no difference. Check any repository the same
way:

```bash
python -m benchmarks.soundness PATH REV1 REV2 ...   # every definition present; updated == fresh
```
The MCP server notices changed files on its own and refreshes in the
background, so agents don't need to call `reindex`.

## Configuration

Everything optional. See `.env.example`.

| Variable | Purpose |
|---|---|
| `REPO_INSIGHT_EMBED_BACKEND` | `auto` (default), `fastembed`, `remote`, `none` |
| `REPO_INSIGHT_EMBED_URL` / `_MODEL` / `_KEY` | OpenAI-compatible embeddings endpoint |
| `REPO_INSIGHT_SUMMARY_MODEL` | summary model, overriding config |
| `REPO_INSIGHT_SUMMARY_URL` / `_KEY` | a local or OpenAI-compatible chat endpoint (implies `local` when no mode is set) |
| `REPO_INSIGHT_SUMMARY_BACKEND` | older switch, still honoured: `anthropic` → `api`, `openai` → `local`, `none` → `off` |
| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | credentials only — they never choose a mode (`ant auth login` works too) |

Settings for one repository live next to its map, outside the repository, and
`~/.config/repo-insight/config.toml` covers every repository; `repo-insight config
get|set` reads and writes them (`--user` for the second). Command-line flags win,
then environment, then this repo's settings, then the user file. API keys are
never written to config.

A repository can carry `.repo-insight/config.toml` for its team, but it arrives
with the code, so only one harmless key is read from it
(`summaries.mode = "off"`); anything that could send code or a key somewhere, run
something or spend money is ignored, with a warning. Write it with
`repo-insight config set --shared`.

### Where the map is kept

Never inside the repository. Each repository's map, settings, logs and
`map.html` go in a private folder (mode 700) under
`~/.local/share/repo-insight/maps/<name>-<hash of the path>/`
(`$XDG_DATA_HOME`, or `$REPO_INSIGHT_DATA_DIR` to choose another place outside
your repositories). Inside the repository a map could be committed, shipped in an
image or archive, or served with the code, and one that came with a clone would
be read as ours. Maps are keyed by path, so a moved checkout is indexed afresh.
A map an older version left in `<repo>/.repo-insight/` is never read;
`repo-insight index` points it out so you can delete it.

```toml
[summaries]
mode = "api"               # off | api | local | agent
max_cost_usd = 5.0
[summaries.api]
provider = "anthropic"     # anthropic | openai | openai-compatible
model = "claude-opus-5"
[summaries.local]
url = "http://localhost:11434/v1"
model = "qwen2.5-coder"
```

## Limits worth knowing

- **Languages**: Python, JavaScript, TypeScript and Go, each an adapter in
  `src/repo_insight/languages/` (grammar, parser, import resolution, call recorder).
  Python resolution is the most complete (star imports, re-exports, aliases); JS/TS
  resolves relative specifiers, `require`, `tsconfig.json` paths and workspace
  packages. TypeScript interfaces, enums, type aliases and abstract classes are kept
  as classes that say what they are, and `implements` links an interface's methods
  to the classes implementing them.
- **Go**: packages are found through `go.mod` (nested modules too); a call is resolved
  when it goes through a package name, the method's receiver, or a parameter or field
  with a declared type, including methods promoted from embedded structs. A struct
  implements the module's interfaces whose methods it has, so calls through them
  dispatch to it. The types of local variables (`r := store.New()`) are not inferred:
  `observe -- go test ./...` records what those calls reach. Imports from outside the
  module stay external.
- **Dynamic dispatch**: reading the code alone, calls through operators,
  registries or `getattr` are not resolved; run `observe` to record them. Overrides
  and constructors are linked (`DISPATCHES`, `INITS`); a call through an attribute
  whose type is unknown is linked by the attribute's name only when the guess is
  narrow, and is labelled `inferred`. Other unresolvable calls are kept as external
  references.
- **observe** covers Python and Node; Node's calls are sampled, and its worker
  threads are not.
- **Type edges** come from annotations. Unannotated code yields no `ACCEPTS` or
  `RETURNS` edges.
- **Summaries are generated text.** They are a map legend, not a specification;
  `inspect_symbol` is one call away.
- **Large files are skipped:** anything over 2 MB (`REPO_INSIGHT_MAX_FILE_BYTES`)
  or named `*.min.*`. The index report names what it skipped.
- **Size on large repositories:** Django indexes in about 20 s without embeddings
  (about 7 minutes with them, on 16 cores) into a map file of roughly 180 MB;
  sympy's is about 270 MB. See `docs/hardening.md`.
- **Migrations** (`*/migrations/*.py`) are not indexed.

## Development

```bash
pytest                      # 924 tests, ~50s, no network, never spends money
pytest -m scale             # timing and memory budgets on generated repositories
pytest -m slow              # a real local model run (needs Ollama or llama.cpp)
pytest -m llm               # a real hosted-API run (needs credentials, costs cents)

python -m benchmarks.corpus                 # clone six pinned real repositories
python -m benchmarks.scale PATH [PATH ...]  # index time, memory, tool response times
python -m benchmarks.agent --help           # agent benchmark: with the map against without
```

`docs/hardening.md` records the security, robustness, memory and performance
findings and their fixes, with measurements on Django, sympy, scikit-learn and
others. `docs/benchmark-plan.md` is the plan for measuring what Repo-Insight is
worth to a coding agent, and describes the harness in `benchmarks/agent/`. That
harness never starts a paid agent run without a spending ceiling on the command
line.

## License

MIT
