> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mengram.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Code Integration

> Memory that survives /clear and auto-compaction — auto-save conversations, auto-recall context on every prompt, and load your profile on session start.

## Overview

Mengram integrates with [Claude Code](https://docs.anthropic.com/en/docs/claude-code) hooks to create a full memory loop that survives `/clear`, **auto-compaction**, machine switches, and team handoffs — the SessionStart hook fires after every compact and re-injects your context:

1. **Session context** — loads your cognitive profile when a session starts, so Claude knows who you are
2. **Auto-recall** — searches relevant memories on every prompt and injects them as context
3. **Auto-save** — captures conversations in the background to build up memory over time

Zero manual effort. One command to install.

## Quick Setup

### Option A — plugin from the marketplace (recommended)

```bash theme={null}
# 1. Save your API key once (free key at https://mengram.io)
mkdir -p ~/.mengram && echo '{"api_key": "om-your-key-here"}' > ~/.mengram/config.json

# 2. Install the plugin
claude plugin marketplace add alibaizhanov/mengram
claude plugin install mengram@mengram
```

The plugin ships the hooks, the MCP server (30 tools), and a skill. Hooks read the key from `~/.mengram/config.json` (an exported `MENGRAM_API_KEY` env var wins if set).

**First-run self-check:** until the plugin verifies one successful API round-trip, failures show a one-line message telling you exactly what's broken. After the first success, failures are silent — an outage never spams you or blocks Claude Code.

### Option B — CLI hooks

```bash theme={null}
pip install mengram-ai
mengram setup
```

This creates your account (if needed), saves your API key, and installs all 3 hooks automatically. Restart Claude Code — done.

## Skip the cold start — import your history

Your past Claude Code sessions are already on disk. Feed them in and memory starts full, not empty:

```bash theme={null}
pip install mengram-ai
mengram import claude-code
```

Secrets (API keys, tokens) are redacted client-side before upload. Then ask Claude: *"what do you know about my projects?"*

## How It Works

### 1. Session Start — Profile Loaded

When you open Claude Code (or after context compaction), the `SessionStart` hook fires:

```
Session starts
  → mengram auto-context runs
  → Loads your Cognitive Profile from Mengram (GET /v1/profile)
  → Prints it to stdout — Claude sees it as context

Claude now knows: your name, preferences, tech stack, current projects
```

### 2. Every Prompt — Relevant Memories Recalled

When you type a prompt, the `UserPromptSubmit` hook fires **before** Claude responds:

```
You type: "how did we deploy to Railway?"
  → mengram auto-recall runs
  → Searches Mengram for relevant memories (POST /v1/search)
  → Returns additionalContext that Claude sees:

  [Mengram Memory — relevant context from past sessions]
  Railway Deployment:
    - Auto-deploys from main branch
    - Uses gunicorn with 1 worker
    - DATABASE_URL uses Session Mode port 5432

Claude responds WITH context from your past sessions
```

### 3. After Response — Conversation Saved

After Claude responds, the `Stop` hook fires asynchronously in the background:

```
Claude finishes responding
  → mengram auto-save runs (background, non-blocking)
  → Every 3rd response, sends [user + assistant] to POST /v1/add
  → API extracts entities, facts, episodes, procedures
  → Memory grows over time
```

### Full Loop

```
┌──────────────────────────────────────────────┐
│  Session starts                              │
│  ↓ SessionStart → profile loaded             │
│                                              │
│  You type a prompt                           │
│  ↓ UserPromptSubmit → relevant memory found  │
│                                              │
│  Claude responds (with memory context)       │
│  ↓ Stop → conversation saved (background)    │
│                                              │
│  Next prompt → recall again...               │
└──────────────────────────────────────────────┘
```

## Commands

### mengram hook install

Installs all 3 hooks into `~/.claude/settings.json`.

```bash theme={null}
mengram hook install                    # default: save every 3rd response
mengram hook install --every 5          # save every 5th response
mengram hook install --user-id myuser   # custom user_id
```

This adds 3 hooks to your Claude Code settings:

```json theme={null}
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [{
          "type": "command",
          "command": "mengram auto-context",
          "timeout": 15
        }]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [{
          "type": "command",
          "command": "mengram auto-recall",
          "timeout": 10
        }]
      }
    ],
    "Stop": [
      {
        "hooks": [{
          "type": "command",
          "command": "mengram auto-save --every 3",
          "timeout": 30,
          "async": true
        }]
      }
    ]
  }
}
```

### mengram hook status

Check status of all hooks.

```bash theme={null}
mengram hook status
```

Output:

```
Mengram Hooks

  Auto-save:      installed (every 3 responses)
  Auto-recall:    installed
  Session context: installed
  API Key:        om-...Kb8 (set)
  API:            connected (free plan)
  Settings:       /Users/you/.claude/settings.json
```

### mengram hook uninstall

Remove all Mengram hooks.

```bash theme={null}
mengram hook uninstall
```

## Configuration

| Option      | Default     | Description                                                         |
| ----------- | ----------- | ------------------------------------------------------------------- |
| `--every N` | 3           | Save every Nth response. Lower = more memories, higher = less noise |
| `--user-id` | `"default"` | Mengram user\_id for multi-user isolation                           |

### Environment Variables

| Variable          | Required | Description                                    |
| ----------------- | -------- | ---------------------------------------------- |
| `MENGRAM_API_KEY` | Yes      | Your Mengram API key (starts with `om-`)       |
| `MENGRAM_URL`     | No       | Custom API URL (default: `https://mengram.io`) |
| `MENGRAM_USER_ID` | No       | Default user\_id (overridden by `--user-id`)   |

## Filtering

**Auto-save** skips:

* Short responses (\< 100 characters) — trivial confirmations
* Interrupted requests
* Responses when no API key is set

**Auto-recall** skips:

* Very short prompts (\< 10 characters)
* Slash commands (`/help`, `/clear`, etc.)
* Simple confirmations (`yes`, `no`, `ok`)

## Quota Limits

When you hit your monthly plan limits, each hook surfaces a clear warning instead of failing silently:

| Hook             | What happens          | Message shown                                                                           |
| ---------------- | --------------------- | --------------------------------------------------------------------------------------- |
| **Auto-recall**  | Search quota exceeded | Claude sees: `[Mengram] Memory search quota exceeded — recall is disabled`              |
| **Auto-context** | Profile load fails    | Session start shows: `[Mengram] Memory profile load failed — quota exceeded`            |
| **Auto-save**    | Save quota exceeded   | Terminal shows: `[Mengram] Memory save failed — Your conversations are NOT being saved` |

All messages include an upgrade link. Claude Code is never blocked — hooks continue gracefully.

Non-quota errors (network timeouts, transient failures) are silently swallowed so they never interrupt your workflow.

To check your current usage: `mengram stats` or visit [mengram.io/dashboard](https://mengram.io/dashboard).

## Debugging: verbose markers and heartbeat

**Verbose markers (CLI hooks):** add `--verbose` to any hook command in your hooks config and every exit path emits a one-line status marker — `[mengram:auto-recall] found 3 memories`, `[mengram:auto-save] throttled (2/3)`. Answers "is it working?" in one session restart. Off by default (byte-for-byte silent).

**Heartbeat (plugin):** set `MENGRAM_HEARTBEAT=25` (env) or `"heartbeat": 25` in `~/.mengram/config.json` and every 25th successful save shows one line: `[mengram] heartbeat: 150 conversations saved to memory so far`. With the heartbeat on, silence means something is wrong.

## Troubleshooting

**Hooks not firing?**

* Restart Claude Code after installing
* Check `mengram hook status` to verify all 3 hooks are installed
* Keys are read from `MENGRAM_API_KEY` env **or** `~/.mengram/config.json` (env wins) — check `cat ~/.mengram/config.json`

**Memories not appearing?**

* Auto-save processes in the background — check after \~30 seconds
* Verify API connectivity: `mengram hook status`
* Check your memories at [mengram.io/dashboard](https://mengram.io/dashboard)

**Recall seems slow?**

* Auto-recall has a 10-second timeout — if the API is slow, it's skipped gracefully
* Claude Code continues normally even if a hook fails

**Seeing quota warnings?**

* You've hit your monthly plan limit — memory is disabled until the limit resets or you upgrade
* Run `mengram stats` to check usage
* Upgrade at [mengram.io/dashboard](https://mengram.io/dashboard)

<Tip>
  Run `mengram setup` to automatically save your API key to your shell profile and install all hooks in one step.
</Tip>
