# Tribal Memory

> Your AI tools don't share a brain. Tribal Memory gives them one.

One memory store, many agents. Teach Claude Code something — Codex already knows it. That's not just persistence — it's **cross-agent intelligence**.

<p align="center">
  <img src="docs/assets/one-brain-two-agents.gif" alt="One Brain, Two Agents — Claude Code stores memories, Codex recalls them" width="700">
  <br>
  <em>Claude Code stores architecture decisions → Codex recalls them instantly</em>
</p>

[![PyPI](https://img.shields.io/pypi/v/tribalmemory)](https://pypi.org/project/tribalmemory/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)

---

## Why

Every AI coding assistant starts fresh. Claude Code doesn't know what you told Codex. Codex doesn't know what you told Claude. You repeat yourself constantly.

Tribal Memory is a shared memory server that any AI agent can connect to via [MCP](https://modelcontextprotocol.io). Store a memory from one agent, recall it from another. It just works.

---

## Install

```bash
pip install tribalmemory    # or: uv tool install tribalmemory
```

`tribalmemory init` defaults to **FastEmbed** (local ONNX embeddings, zero cloud). If FastEmbed isn't installed, it will offer to install it automatically. For OpenAI or Ollama embeddings, use `--openai` or `--ollama`.

---

## Quick Start

### Option A: FastEmbed (Zero Cloud, Zero Cost) — Default

No API keys. No cloud. No external services. Everything runs on your machine.

```bash
pip install tribalmemory   # or: uv tool install tribalmemory
tribalmemory init          # auto-installs FastEmbed if needed
tribalmemory serve
```

That's it. No config editing required.

> **First run:** FastEmbed downloads a ~130MB ONNX model on first use. After that, embeddings are instant and fully offline.

See [docs/fastembed-quickstart.md](docs/fastembed-quickstart.md) for details.

### Option B: OpenAI Embeddings

```bash
tribalmemory init --openai   # prompts for your API key
tribalmemory serve
```

### Option C: Ollama

If you already have [Ollama](https://ollama.com) running:

```bash
tribalmemory init --ollama
tribalmemory serve
```

See [docs/ollama-quickstart.md](docs/ollama-quickstart.md) for Ollama setup details.

Server runs on `http://localhost:18790`.

### Running as a Service (Optional)

Keep the server running in the background with automatic restarts:

```bash
# Install and start the service (systemd on Linux, launchd on macOS)
tribalmemory service install

# Check status
tribalmemory service status

# View logs
tribalmemory service logs

# Stop and remove
tribalmemory service uninstall
```

User-level services only — no root/sudo required.

---

## Integrations

Tribal Memory connects to AI agents via [MCP (Model Context Protocol)](https://modelcontextprotocol.io). Set up one or more of these:

### Claude Code (CLI)

```bash
# Auto-configure (recommended)
tribalmemory init --claude-code
```

Or manually — add to `~/.claude.json`:

```json
{
  "mcpServers": {
    "tribal-memory": {
      "command": "tribalmemory-mcp"
    }
  }
}
```

Now Claude Code has persistent memory across sessions:

```
You: Remember that the auth service uses JWT with RS256
Claude: ✅ Stored.

--- next session ---

You: How does the auth service work?
Claude: Based on my memory, the auth service uses JWT with RS256...
```

### Claude Desktop

```bash
# Auto-configure (recommended — resolves the full binary path automatically)
tribalmemory init --claude-desktop
```

Claude Desktop doesn't inherit your shell PATH, so the bare command `tribalmemory-mcp` won't work. The init flag resolves the absolute path and writes it to `claude_desktop_config.json` for you.

### Both Claude Apps

```bash
# Configure Claude Code CLI and Claude Desktop together
tribalmemory init --claude-code --claude-desktop
```

### Codex (CLI & Desktop)

The Codex CLI and desktop app share the same config file (`~/.codex/config.toml`), so one command sets up both:

```bash
# Auto-configure (recommended — works for both CLI and desktop app)
tribalmemory init --codex
```

Or manually — add to `~/.codex/config.toml`:

```toml
[mcp_servers.tribal-memory]
command = "tribalmemory-mcp"
```

> **Note:** The init flag resolves the full binary path automatically, so the desktop app finds the command even if it doesn't inherit your shell PATH.

That's it. Codex now shares the same memory store as Claude Code. Memories stored by one are instantly available to the other.

### OpenClaw

Tribal Memory includes a plugin for [OpenClaw](https://github.com/openclaw/openclaw):

```bash
openclaw plugins install ./extensions/memory-tribal
openclaw config set plugins.slots.memory=memory-tribal
```

### Cloud Setup (Coming Soon)

A hosted Tribal Memory service for teams — no server management, automatic syncing across machines. [Star the repo](https://github.com/abbudjoe/TribalMemory) for updates.

---

## Demo

Run the interactive demo to see Tribal Memory in action:

```bash
./demo.sh
```

See [docs/demo-output.md](docs/demo-output.md) for sample output.

---

## Self-Hosted Setup

### Configuration

Generated by `tribalmemory init`. Lives at `~/.tribal-memory/config.yaml`:

```yaml
instance_id: my-agent

embedding:
  provider: fastembed              # or openai
  model: BAAI/bge-small-en-v1.5   # or text-embedding-3-small
  dimensions: 384                  # 384 for fastembed, 1536 for OpenAI

db:
  provider: lancedb
  path: ~/.tribal-memory/lancedb

server:
  host: 127.0.0.1
  port: 18790

search:
  lazy_spacy: true                 # 70x faster ingest (default: true)
```

### Entity Extraction (Optional)

For better recall on personal conversations (finding people, places, dates), install spaCy:

```bash
pip install tribalmemory[spacy]
python -m spacy download en_core_web_sm
```

With **lazy spaCy** (default), entity extraction is blazing fast:
- **Ingest**: Uses fast regex patterns (~2-3 seconds per conversation)
- **Recall**: Runs spaCy NER once on your query for accurate entity matching

This gives you the best of both worlds — fast ingestion AND accurate retrieval for personal conversations.

### Environment Variables

| Variable | Description |
|----------|-------------|
| `OPENAI_API_KEY` | Required for OpenAI embeddings; not needed for FastEmbed/local mode |
| `TRIBAL_MEMORY_CONFIG` | Path to config file (default: `~/.tribal-memory/config.yaml`) |
| `TRIBAL_MEMORY_INSTANCE_ID` | Override instance ID |

### Docker

```bash
# With OpenAI embeddings
OPENAI_API_KEY=sk-... docker compose up -d

# With local Ollama (zero cloud)
docker compose --profile local up -d
```

The Docker setup defaults to OpenAI embeddings. Set `OPENAI_API_KEY` as an environment variable, or use `--profile local` to spin up a bundled Ollama instance instead. Mount a custom `config.yaml` to change embedding provider, model, or dimensions. See `docker-compose.yml` for all options.

---

## Tribal API

### HTTP Endpoints

All endpoints are under the `/v1` prefix.

```bash
# Store a memory
curl -X POST http://localhost:18790/v1/remember \
  -H "Content-Type: application/json" \
  -d '{"content": "The database uses Postgres 16", "tags": ["infra"]}'

# Search memories
curl -X POST http://localhost:18790/v1/recall \
  -H "Content-Type: application/json" \
  -d '{"query": "what database", "limit": 5}'

# Health check
curl http://localhost:18790/v1/health

# Get stats
curl http://localhost:18790/v1/stats
```

### MCP Tools

When connected via MCP, your AI gets these tools:

| Tool | Description |
|------|-------------|
| `tribal_store` | Store a new memory with deduplication |
| `tribal_recall` | Search memories (vector + graph expansion) |
| `tribal_recall_entity` | Query by entity name with hop traversal |
| `tribal_entity_graph` | Explore entity relationships |
| `tribal_correct` | Update/correct an existing memory |
| `tribal_forget` | Delete a memory |
| `tribal_stats` | Get memory statistics |
| `tribal_export` | Export memories to portable JSON |
| `tribal_import` | Import memories from a bundle |
| `tribal_sessions_ingest` | Index conversation transcripts |

### Python API

```python
from tribalmemory.services import create_memory_service

# FastEmbed auto-defaults to BAAI/bge-small-en-v1.5 (384 dims).
# For OpenAI: omit embedding_provider or set to "openai".
service = create_memory_service(
    instance_id="my-agent",
    db_path="./memories",
    embedding_provider="fastembed",
)

# Store
result = await service.remember(
    "User prefers TypeScript for web projects",
    tags=["preference", "coding"]
)

# Recall
results = await service.recall("What language for web?")
for r in results:
    print(f"{r.similarity_score:.2f}: {r.memory.content}")

# Correct
await service.correct(
    original_id=result.memory_id,
    corrected_content="User prefers TypeScript for web, Python for scripts"
)
```

---

## Architecture

```
┌─────────────┐
│  Claude Code │──── MCP ────┐
└─────────────┘              │
┌─────────────┐              ▼
│  Codex CLI   │──── MCP ───► Tribal Memory Server
└─────────────┘              ▲  (localhost:18790)
┌─────────────┐              │
│  OpenClaw    │── plugin ───┘
└─────────────┘
```

The server is the single source of truth. Each agent connects as an instance. Memories are tagged with `source_instance` so you can see *who* learned *what*.

---

## Features

- **Semantic search** — Find memories by meaning, not keywords
- **Cross-agent sharing** — Memories from one agent are available to all
- **Graph search** — Entity extraction + relationship traversal
- **Hybrid retrieval** — Vector + BM25 keyword search combined
- **FastEmbed support** — Local ONNX embeddings, no API keys needed
- **Session indexing** — Index conversation transcripts for search
- **Automatic deduplication** — Won't store the same thing twice
- **Memory corrections** — Update outdated information with audit trail
- **Temporal reasoning** — Date extraction and time-based filtering
- **Import/export** — Portable JSON bundles with embedding metadata
- **Token budgets** — Smart context management to avoid LLM overload
- **MCP server** — Native integration with Claude Code, Codex, and more
- **Benchmark tested** — [100% accuracy on LoCoMo](docs/memorybench-results.md) (1986 questions, all categories)

---

## Privacy

In local mode (FastEmbed + LanceDB), **zero data leaves your machine**:
- Embeddings computed locally (ONNX runtime)
- Memories stored locally in LanceDB
- No API keys, no cloud services, no telemetry

When using OpenAI embeddings, memory content is sent to the OpenAI API for embedding generation. Memories themselves are still stored locally — only the embedding step requires an external call.

---

## Development

```bash
git clone https://github.com/abbudjoe/TribalMemory.git
cd TribalMemory
pip install -e ".[dev]"

# Run tests
PYTHONPATH=src pytest

# Run linting
ruff check .
black --check .
```

---

## License

Apache 2.0 — see [LICENSE](LICENSE)
