second-brain-cli 0.1.0

Universal memory layer for AI coding agents — ingest, recall, and sync across Claude Code, Cursor, and more
# second-brain

A universal memory layer for AI coding agents. Ingests conversation history from Claude Code, Cursor, and other tools into a graph-backed knowledge store with vector search, then serves it via MCP (Model Context Protocol) so any AI agent can recall what you've discussed, decided, and built across projects and machines.

## Why

Every AI coding tool keeps its own conversation history locked in its own format. Claude Code stores JSONL in `~/.claude/projects/`, Cursor keeps SQLite in `~/.cursor/`. None of them talk to each other, and none of them let you search across sessions. If you discussed an architecture decision with Claude last week and ask Cursor about it today, you start from zero.

second-brain fixes this by creating a single knowledge graph that ingests from all your AI tools, embeds everything for semantic search, tracks relationships between memories (reinforces, contradicts, supersedes), and exposes it all through MCP so any connected agent can recall context from any previous conversation.

## Architecture

```
┌─────────────┐  ┌─────────────┐
│ Claude Code │  │   Cursor    │  ... more adapters
└──────┬──────┘  └──────┬──────┘
       │                │
       ▼                ▼
┌──────────────────────────────┐
│         Adapters             │  Parse tool-specific formats
└──────────────┬───────────────┘
               ▼
┌──────────────────────────────┐
│           Core               │
│  ┌────────┐  ┌────────────┐  │
│  │ KuzuDB │  │ BGE-small  │  │  Graph DB + 384-dim embeddings
│  │ (graph)│  │ (embeddings)│  │
│  └────────┘  └────────────┘  │
│  ┌────────────────────────┐  │
│  │    QueryEngine         │  │  Weighted scoring:
│  │  vector 0.5 + graph    │  │  vector similarity + graph
│  │  0.3 + recency 0.2    │  │  relevance + temporal decay
│  └────────────────────────┘  │
└──────────────┬───────────────┘
               ▼
┌──────────────────────────────┐
│   MCP Server (stdio)         │  Tools: recall, remember,
│                              │  ingest, associate, forget,
│                              │  context, status
└──────────────────────────────┘
               ▼
┌──────────────────────────────┐
│   Sync (SSH + JSONL)         │  Bidirectional, sequence-
│                              │  numbered change log
└──────────────────────────────┘
```

## Crates

| Crate | Description |
|-------|-------------|
| `second-brain-core` | KuzuDB storage, BGE-small-en-v1.5 embeddings, QueryEngine, schema types |
| `second-brain-adapters` | Parsers for Claude Code JSONL and Cursor SQLite formats |
| `second-brain-sync` | SSH transport, JSONL change log export/import, conflict resolution |
| `second-brain-mcp` | MCP stdio server exposing recall/remember/ingest/associate/forget/context/status |
| `second-brain-cli` | CLI binary (`sb`) for ingest, recall, sync, consolidation |
| `second-brain-api` | HTTP API server (WIP) |

## Install

```bash
cargo install second-brain-cli
```

Or build from source:

```bash
git clone https://github.com/Anyesh/second-brain.git
cd second-brain
cargo build --release
```

Binaries land in `target/release/`: `second-brain-cli`, `second-brain-mcp`, `second-brain-api`.

## Usage

### Ingest conversations

```bash
# Ingest Claude Code history
sb ingest claude-code

# Ingest Cursor history
sb ingest cursor

# Ingest everything
sb ingest all

# Re-ingest from scratch
sb reingest --clean
```

Ingest reads from standard paths (`~/.claude/projects/` for Claude Code, `~/.cursor/` for Cursor), parses conversations, extracts memories with types (episodic, semantic, procedural), generates 384-dim embeddings, and stores everything in KuzuDB with entity extraction and relationship tracking.

### Recall

```bash
sb recall "how does authentication work in the API"
sb recall "what database did we choose and why"
```

Recall uses a weighted scoring function: 50% vector cosine similarity, 30% graph relevance (relation types and counts), 20% recency (exponential decay + access frequency). Results below a 0.59 similarity threshold are filtered out.

### MCP server

Add to your `.mcp.json` or Claude Code settings:

```json
{
  "mcpServers": {
    "second-brain": {
      "command": "/path/to/second-brain-mcp",
      "env": {
        "SECOND_BRAIN_DB": "~/.second-brain/graph.kuzu"
      }
    }
  }
}
```

MCP tools available:

| Tool | Description |
|------|-------------|
| `recall` | Semantic search with graph-boosted scoring |
| `remember` | Store a new memory with embedding |
| `ingest` | Trigger conversation ingestion |
| `associate` | Create explicit relations between memories |
| `forget` | Remove a memory by ID |
| `context` | Get a memory with its graph neighborhood |
| `status` | DB stats: memory count, index health, sync state |

The MCP server also runs a file watcher that auto-ingests new Claude Code conversations as they appear.

### Sync

Bidirectional sync between machines over SSH using a sequence-numbered JSONL change log.

```bash
# Full bidirectional sync with a peer
sb sync user@remote-host

# Manual export/import
sb sync-export --after-seq 0 > changes.jsonl
cat changes.jsonl | sb sync-import

# Check sync state
sb sync-status

# Backfill sync log for data that predates the log
sb sync-backfill
```

Sync resolves conflicts with last-write-wins on memory updates (newer `last_accessed` wins). Conversations, entities, and relations use create-or-skip semantics.

### Consolidation

Distill raw conversation memories into higher-level summaries using a local LLM (Ollama).

```bash
sb consolidate                          # default: 50 memories, gemma4
sb consolidate --limit 200              # process more
sb consolidate --model llama3.2:latest  # different model
sb consolidate --dry-run                # preview without writing
sb consolidate --ollama-url http://gpu-server:11434  # remote Ollama
```

Distilled memories are linked to their sources via `DistilledFrom` relations. Raw data remains the primary source of truth; distilled memories serve as a supplementary index for broad queries.

## Configuration

| Env var | Default | Description |
|---------|---------|-------------|
| `SECOND_BRAIN_DB` | `~/.second-brain/graph.kuzu` | Path to KuzuDB database |
| `RUST_LOG` | - | Tracing filter (e.g. `info`, `second_brain_mcp=debug`) |

## Query scoring

The QueryEngine combines three signals:

- **Vector similarity (weight: 0.5)**: cosine distance between query embedding and memory embedding using BGE-small-en-v1.5 (384 dimensions)
- **Graph relevance (weight: 0.3)**: based on relation types connected to the memory. Reinforces (+0.3), RelatesTo (+0.2 * strength), DistilledFrom (+0.15), Mentions (+0.1), DerivedFrom (+0.05), Contradicts (-0.1), Supersedes (-0.2)
- **Recency (weight: 0.2)**: exponential decay over 30 days plus a logarithmic access frequency boost

Weights are configurable via `QueryEngine::with_weights(vector, graph, recency)`.

## Graph schema

Node types: `Memory`, `Entity`, `Conversation`, `IngestLog`, `ConsolidationLog`, `SyncLog`, `SyncState`

Relation types:
- `RELATES_TO` (Memory -> Memory): semantic relationship with strength
- `REINFORCES` (Memory -> Memory): one memory strengthens another
- `CONTRADICTS` (Memory -> Memory): conflicting information with resolution
- `SUPERSEDES` (Memory -> Memory): newer information replaces older
- `DISTILLED_FROM` (Memory -> Memory): consolidation link
- `DERIVED_FROM` (Memory -> Conversation): provenance tracking
- `MENTIONS` (Memory -> Entity): entity extraction links

## Dependencies

- [KuzuDB]https://kuzudb.com/ 0.11 for the graph database (embedded, single-file)
- [fastembed]https://github.com/Anush008/fastembed-rs 5 for BGE-small-en-v1.5 embeddings (384-dim, runs locally, no API calls)
- Rust 1.85+

## License

MIT