Skip to main content
Glama
README.md
# repomem: shared repo memory for every coding agent

**One memory per repo that any agent can write to and every agent can read. Each memory is pinned to the code it describes, and it flags itself when that code changes.**

When Claude Code works out how your repo fits together, that understanding is gone at the end of the session. When you open the same repo in GitHub Copilot or Cursor, the new agent pays again (in tokens, tool calls and minutes) to rediscover the same things. `repomem` is a small [MCP](https://modelcontextprotocol.io) server that keeps what agents learn: conventions, gotchas, architecture and where things live. It hands that knowledge to the next agent, whichever vendor it comes from.

![Claude Code recalls a memory Copilot wrote, checks it against the code and extends it](docs/screenshots/04-claude-updates-copilot-memory.png)

---

## Why this and not a code graph or RAG index?

Agents already index code. Cursor, Copilot and Augment each have their own index, and grep/glob search is fast and always current. What they **don't** share is the *conclusions* an agent reaches after reading the code:

- "Any PATCH sets `manual=1`, and after that sync never touches the stage again."
- "`ghosted` is never stored. It's computed at read time."
- "The comment above the `WHEN` regex is wrong: it doesn't match 'Thu, March 12'."

Those facts are expensive to rediscover and cheap to store. Today they stay locked inside one vendor's session. repomem makes them:

| | |
|---|---|
| **Vendor-neutral** | Plain MCP over stdio. Tested with Claude Code and GitHub Copilot CLI; works with VS Code Copilot Chat, Cursor and any other MCP client. |
| **Code-anchored** | Each memory points at `path` or `path::Symbol` (Python, TypeScript/JS/JSX, Go, Rust, Java, Kotlin, C#, C/C++, Ruby, PHP, …), and a content hash is stored for each anchor. |
| **Self-invalidating** | If the anchored function changes, the memory is marked **stale** and agents are told to check it again. A stale memory is never served as fact. |
| **Attributed** | Each memory records which agent wrote it and every agent that edited it (`claude-code + copilot-cli`). |
| **Deduplicated** | An agent that tries to add a near-copy for the same symbol is told to **merge** into the existing memory with `update_memory`. |
| **Local and small** | One Python file plus SQLite at `~/.repomem/mem.db`. No cloud, no embeddings, no graph database. Code never leaves your machine. |

---

## How it works

```mermaid
flowchart LR
    CC[Claude Code] -- recall / remember / update --> S
    CP[Copilot CLI / VS Code] -- recall / remember / update --> S
    CU[Cursor, any MCP client] -- recall / remember / update --> S
    S[repomem MCP server] --> DB[(SQLite<br/>~/.repomem/mem.db)]
    S -- hash anchors on every recall --> R[(your repo)]
    D[Dashboard :8765] --> DB
    E[export] -- rules + snapshot --> F[AGENTS.md / CLAUDE.md]
    F -. read automatically .-> CC & CP & CU
    H[Stop hook] -. "save what you learned" .-> CC & CP
```

1. **Recall.** Agents call `recall_memory` before exploring. Before answering, repomem hashes every anchor again. If an anchored function's source changed, or the file is gone, the memory comes back as `stale`.
2. **Remember.** Agents save non-obvious facts tied to code. An exact duplicate adds a vote instead. A near-duplicate on the same symbol is refused, and the agent is shown the existing memory so it can merge into it.
3. **Update.** An agent that finds a memory incomplete or wrong rewrites it with `update_memory`, and the editor is recorded.
4. **Making agents actually use it:**
   - `repomem export` writes a short rules block into `AGENTS.md` and `CLAUDE.md`, which agents read on their own. Agents then call `recall_memory` with no prompting.
   - A **Stop hook** stops an agent from finishing once and asks it to save or merge what it learned. It works for both Claude Code and Copilot CLI.

### Symbol anchors

`path::Symbol` hashes **only that definition's source**, so an edit elsewhere in the file leaves the memory active. Qualify a method with its class, impl or receiver type: `Class.method`. An anchor matches when the definition's qualified name equals it or ends with `.Symbol`.

| Language | Parser | Example anchor |
|---|---|---|
| Python | stdlib `ast` (no download) | `app/models.py::User.save` |
| TypeScript / JavaScript / JSX / TSX | tree-sitter | `src/api.ts::Client.get`, `web/App.jsx::useTheme` (arrow functions included) |
| Go | tree-sitter | `pkg/server.go::Server.Run` (qualified by receiver) |
| Rust | tree-sitter | `src/lib.rs::Store.get` (qualified by `impl`) |
| Java, Kotlin, C#, C/C++, Ruby, PHP, Swift, … | tree-sitter | `Foo.java::Foo.bar` |

Tree-sitter grammars come from [`tree-sitter-language-pack`](https://pypi.org/project/tree-sitter-language-pack/). Each grammar downloads on first use and is cached. If tree-sitter isn't installed, the language is unknown, or you're offline, repomem falls back to hashing the whole file, so it still works but staleness is file-level and the symbol name isn't checked.

---

## Quick start

```sh
git clone https://github.com/g-m-b/repo-memory-mcp.git
cd repo-memory-mcp
python3 -m venv .venv && .venv/bin/pip install -e .     # installs the `repomem` command into .venv/bin
for t in tests/test_*.py; do .venv/bin/python $t || break; done
```

Below, `REPOMEM` stands for the absolute path of your clone, for example `~/repo-memory-mcp`. The server command is `REPOMEM/.venv/bin/repomem serve`.

### Connect your agents

The server treats its working directory as the repo. Each client starts it inside your project, or you can set `REPOMEM_REPO`.

**Claude Code** (all projects):
```sh
claude mcp add -s user repomem -- $REPOMEM/.venv/bin/repomem serve
```

**GitHub Copilot CLI**:
```sh
copilot mcp add repomem -- $REPOMEM/.venv/bin/repomem serve
```

**VS Code Copilot Chat**: put this in `.vscode/mcp.json` in your project, then use Chat in **Agent** mode.
```json
{
  "servers": {
    "repomem": {
      "type": "stdio",
      "command": "REPOMEM/.venv/bin/repomem",
      "args": ["serve"],
      "env": { "REPOMEM_REPO": "${workspaceFolder}" }
    }
  }
}
```

**Cursor**: `.cursor/mcp.json`, same shape, with `"mcpServers"` as the top-level key.

### Make agents use it without being asked

```sh
repomem export /path/to/your/project   # writes the rules into AGENTS.md + CLAUDE.md
```

Re-run it any time. It only rewrites its own `<!-- repomem:start/end -->` block. `AGENTS.md` also gets a snapshot of current memories, for agents that don't support MCP.

### Stop hook: make agents save what they learned

`hooks/stop_save.py` blocks an agent's **first** stop in a repo repomem tracks and tells it to save or merge new findings. Its second stop goes through, so it can't loop.

It stays out of the way when it has nothing to do, and never costs you your answer:
- **Already saved:** if the agent called `remember_memory` or `update_memory` this session, it finishes normally. The hook reads the transcript the agent passes in and counts real tool calls only, not the list of available tools.
- **Untracked repo:** repos repomem doesn't track are left alone.
- **`claude -p`** prints only the final message, so the agent is told to repeat its answer verbatim after saving. Your script gets the answer, not "memory is up to date".
- **Interactive sessions, and Copilot CLI in every mode** (`-p` and `-s` print every message): the agent ends with one short line ("Memory already up to date." or what it saved). Without that, Copilot would print `No response was returned`.

**Claude Code**, in `~/.claude/settings.json`:
```json
{ "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "python3 REPOMEM/hooks/stop_save.py", "timeout": 10 } ] } ] } }
```

**Copilot CLI**, in `~/.copilot/hooks/repomem.json`:
```json
{ "version": 1, "hooks": { "Stop": [ { "type": "command", "bash": "python3 REPOMEM/hooks/stop_save.py", "timeoutSec": 10 } ] } }
```

> ⚠️ Use the event name **`Stop`**, not Copilot's own `agentStop`. In testing, `agentStop` ran the hook but ignored `decision: block`, and the agent finished anyway.

---

## MCP tools

| Tool | Purpose |
|---|---|
| `recall_memory(query="")` | Search this repo's memory. Results are ranked by how many query words match. With an empty query, or no matches, you get the repo brief. Stale memories are labelled. |
| `remember_memory(text, kind, anchors, distinct=false)` | Save a fact. `kind` is one of `convention`, `gotcha`, `architecture` or `location`. `anchors` look like `path` or `path::Symbol` in any supported language, and are checked to exist inside the repo. If memories already exist for the same symbol, nothing is saved and they're returned for merging. |
| `update_memory(id, text, anchors=None)` | Extend or correct a memory. Re-pins it to the current code and records the editor. |
| `confirm_memory(id)` | Mark a stale memory as still true after checking it. |
| `forget_memory(id)` | Reject a wrong or obsolete memory. |

## CLI

| Command | |
|---|---|
| `repomem serve` | MCP stdio server |
| `repomem dashboard [port]` | Review UI at `http://127.0.0.1:8765` |
| `repomem import [repo]` | Seed memories from bullet points in `AGENTS.md`, `CLAUDE.md`, `.github/copilot-instructions.md` and `.cursor/rules/` |
| `repomem export [repo]` | Write rules (plus a snapshot) into `AGENTS.md` and `CLAUDE.md` |

Environment variables: `REPOMEM_DB` (default `~/.repomem/mem.db`) and `REPOMEM_REPO` (default: the working directory).

## Dashboard

`repomem dashboard`. It's built on the standard library plus [Pico.css](https://picocss.com), with no build step.

- Counts of active, stale and rejected memories, plus instant search and a status filter.
- Per memory: **confirm**, **reject**, **delete** and **edit**. Edits are attributed to `dashboard`.
- Per repo: **export** to `AGENTS.md` / `CLAUDE.md`, and **delete repo memory**.
- Binds to `127.0.0.1` and answers only requests addressed to `127.0.0.1`/`localhost` (which blocks DNS rebinding), refuses cross-origin POSTs, exports only to repos it already tracks, and HTML-escapes all memory text.

![Dashboard: memory #12 is anchored to the JSX symbol `web/src/App.jsx::useTheme`; #10 was written by Copilot and extended by Claude](docs/screenshots/06-dashboard.png)

---

## Test results

The data below comes from real runs on a public project, [`jobtrail`](https://github.com/g-m-b/jobtrail): a FastAPI and React app with about 10 Python files.

### Unit, Stop-hook and MCP end-to-end tests
![Tests](docs/screenshots/01-tests.png)

### 1. Claude Code learns the repo once
Claude Code explored `jobtrail` and saved 9 anchored memories, in 19 turns and about 60 seconds. The cost is paid once.

### 2. Shared memory cuts cost on broad questions
![Benchmark](docs/screenshots/05-benchmark.png)

| Task | With memory | Cold start |
|---|---|---|
| Narrow ("why is my edited application stuck / ghosted?") | 5 turns · 12 s · $0.25 | 5 turns · 16 s · $0.23 |
| Broad ("add a LinkedIn provider: full data path plus gotchas") | **6 turns · 31 s · $0.31** | 17 turns · 54 s · $0.53 |

Narrow questions are already cheap to answer with grep. The gain shows up on cross-cutting questions: about 65% fewer turns, 43% less time and 42% lower cost, with the same gotchas covered. These are single runs on a small repo, so treat them as directional.

### 3. Copilot reads Claude's memory without being asked
The prompt never mentions repomem. Copilot CLI picks up the rules from `AGENTS.md` and recalls first.

![Copilot recalls unprompted](docs/screenshots/02-copilot-recalls-unprompted.png)

### 4. Copilot writes back, and the Stop hook makes it merge rather than duplicate
Copilot added its `cli.py` finding to memory #2 (originally Claude's). The author field is now `claude-code + copilot-cli`.

![Copilot stop hook merge](docs/screenshots/03-copilot-stop-hook-merges.png)

### 5. Claude checks and extends Copilot's memory
The screenshot at the top of this page: Claude recalls #10 (written by Copilot), checks it against `providers.py`, finds two missing facts and merges them with `update_memory`.

### 6. The Stop hook never costs you the answer in scripted runs
`copilot -s` keeps the answer and ends with one line, with no `No response was returned`. `claude -p` prints only the last message, so after the hook the agent repeats its answer verbatim. Below are both real runs, with each session's event log showing the hook blocking.

![Stop hook in headless runs](docs/screenshots/07-stop-hook-headless.png)

### Summary

| | Reads memory unprompted | Saves/merges findings |
|---|---|---|
| Claude Code | ✅ | ✅ (Stop hook as a safety net) |
| GitHub Copilot CLI | ✅ | ✅ with the Stop hook (❌ without it) |

---

## Code review: LLM as judge

The codebase was reviewed by two independent LLM judges from different vendors, **Claude Code** and **GitHub Copilot CLI**. Both used the same rubric (correctness, README vs. behaviour, security, concurrency, robustness, tests), read-only, with every finding requiring a concrete failure scenario. Each finding was verified with a reproducing test before it was fixed, and the judges then re-checked the fixes:

| Round | Judges reported | Outcome |
|---|---|---|
| 1 | 26 findings | All verified. 25 fixed, nearly all with a regression test; 1 (two agents rewriting the *same* memory at once) deferred and documented below |
| 2 | Both: 24/26 fixed (the rest: the deferred item, plus a cross-repo dashboard that is by design). 11 new findings, several in the round-1 fixes themselves | 10 fixed, 1 deferred |
| 3 | Both: 10/11 fixed (the 11th is the deferred item). 4 new findings | 3 fixed, 1 rejected after checking the real database |

Highlights:
- The server's own instructions named tools that didn't exist.
- Dedup and export silently stopped at 50 memories.
- The dashboard could be reached by DNS rebinding.
- A mid-edit syntax error marked every memory in the file stale.
- Concurrent saves from several agents could lose anchors.

During live verification a further bug turned up that neither judge reported: tool errors reached agents only as "Error executing tool". Messages like "no memory #9 in this repo" are now delivered to the agent.

## Project layout

```
src/repomem/
  __main__.py         CLI: serve | dashboard | import | export   (the `repomem` command)
  server.py           MCP server and its five tools
  store.py            SQLite store: remember / recall / update / status, staleness refresh
  anchors.py          path::Symbol resolution and hashing (Python ast + tree-sitter)
  agent_files.py      import from / export to AGENTS.md, CLAUDE.md, Copilot and Cursor rules
  dashboard.py        local review UI (stdlib http.server)
  templates/          dashboard.html (Pico.css)
hooks/
  stop_save.py        Stop hook for Claude Code and Copilot CLI (stdlib only, runs with any python3)
tests/
  test_core.py        behaviour checks (plain asserts, no framework)
  test_e2e_mcp.py     starts `repomem serve` over stdio and drives it with the real MCP client
  test_stop_hook.py   runs the Stop hook against fake Claude/Copilot transcripts
  test_dashboard.py   dashboard security: escaping, Host/Origin checks, bad bodies, error pages
docs/screenshots/     screenshots of the test runs above
pyproject.toml        package metadata, dependencies, `repomem` entry point
```

## Limitations

- **Tree-sitter grammars download on first use.** Offline, or for languages without a grammar, anchors fall back to file level.
- **Unqualified names match the first definition in the file.** Use `Class.method` when names repeat.
- **Recall is keyword-ranked**, not semantic. That's been enough so far; embeddings can come later if recall starts missing things.
- **The Stop hook costs one extra turn** in sessions that learned something but didn't save it (that turn is the point). `claude -p` detection reads the parent process's arguments.
- **Agent-written facts can be wrong.** Attribution, anchors, stale flags and the dashboard review queue are the safeguards. Agents are told to verify before trusting a memory.
- **Local, single-user.** There's no auth or remote server yet.
- **Two agents rewriting the same memory at the same moment:** the last `update_memory` wins. Every other write is serialized; this one would need a version check in the tool API.
- **The Stop hook counts any `remember_memory`/`update_memory` call as "saved",** even one the server refused. The refusal already tells the agent what to do next.

## Roadmap

- Remote HTTP transport with auth, for team-shared memory
- Cross-repo memories (service A calls service B's API)
- Mining past session transcripts for memories
- Semantic recall when keyword recall misses

## License

[MIT](LICENSE)