## 1. Project Overview & Quickstart (rohitg00/agentmemory)

## File: README.md

---

## Install

One command:

```bash
npx @agentmemory/agentmemory
```

The first run is an interactive setup: pick the agents to wire (Claude Code, Cursor, Codex, Gemini CLI, OpenCode, ...), pick an LLM provider or stay keyless, and it seeds the config, starts the memory server on `:3111`, and offers to install globally so the bare `agentmemory` command works everywhere afterwards.

Then prove recall works and give your agent its skills:

```bash
agentmemory demo --serve                 # seed sample sessions + watch recall find them
npx skills add rohitg00/agentmemory -y   # 17 native skills so your agent knows when to reach for memory
```

Prefer to let a coding agent do the whole thing? Hand it one instruction:

> Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md

Wire more agents any time with `agentmemory connect <agent>` — 20 adapters listed at [Works with every agent](#works-with-every-agent). Full command reference at [Quick Start](#quick-start).


**Windows**

The fast path is WSL2. Native Windows engine setup is manual (about 10 to 20 minutes) and `agentmemory connect` is currently unsupported there. See the [Windows notes](#windows) for the step-by-step.




**Global install / EACCES**

```bash
npm install @agentmemory/agentmemory
# If you hit EACCES on macOS/Linux system Node installs:
sudo npm install @agentmemory/agentmemory
```




**npx serves an old version**

npx caches per version. Force the latest with `npx -y @agentmemory/agentmemory@latest`, or clear the cache once with `rm -rf ~/.npm/_npx` (macOS/Linux; on Windows delete `%LOCALAPPDATA%\npm-cache\_npx`).




**Already running your own iii engine**

agentmemory pins iii-engine v0.11.2 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.11.2 in `~/.agentmemory/bin`, leaving your own `iii` untouched.



---

<h2 id="works-with-every-agent"></h2>

agentmemory works with any agent that supports hooks, MCP, or REST API. All agents share the same memory server.



| [](https://claude.com/product/claude-code)
**Claude Code**
native plugin + 12 hooks + MCP | [](https://github.com/openai/codex)
**Codex CLI**
native plugin + 6 hooks + MCP | [](https://github.com/features/copilot)
**GitHub Copilot CLI**
MCP + plugin hooks/skills | [](integrations/openclaw/)
**OpenClaw**
native plugin + MCP | [](integrations/hermes/)
**Hermes**
native plugin + MCP | [](integrations/pi/)
**pi**
native plugin + MCP | [](https://github.com/tinyhumansai/openhuman)
**OpenHuman**
native Memory trait backend | [](https://cursor.com)
**Cursor**
native plugin + MCP | [](https://github.com/google-gemini/gemini-cli)
**Gemini CLI**
MCP server |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| [](https://github.com/opencode-ai/opencode)
**OpenCode**
22 hooks + MCP + plugin | [](https://github.com/cline/cline)
**Cline**
MCP server | [](https://github.com/block/goose)
**Goose**
MCP server | [](https://github.com/Kilo-Org/kilocode)
**Kilo Code**
MCP server | [](https://github.com/Aider-AI/aider)
**Aider**
REST API | [](https://claude.ai/download)
**Claude Desktop**
MCP server | [](https://devin.ai)
**Devin**
6 hooks + MCP | [](https://github.com/RooCodeInc/Roo-Code)
**Roo Code**
MCP server |  |
| [](https://www.warp.dev)
**Warp**
connect + MCP + skills |  |  |  |  |  |  |  |  |





---

You explain the same architecture every session. You re-discover the same bugs. You re-teach the same preferences. Built-in memory (CLAUDE.md, .cursorrules) caps out at 200 lines and goes stale. agentmemory fixes this. It silently captures what your agent does, compresses it into searchable memory, and injects the right context when the next session starts. One command. Works across agents.

**What changes:** Session 1 you set up JWT auth. Session 2 you ask for rate limiting. The agent already knows your auth uses jose middleware in `src/middleware/auth.ts`, your tests cover token validation, and you chose jose over jsonwebtoken for Edge compatibility, with no re-explaining and no copy-pasting.

```bash
npx @agentmemory/agentmemory
```

By default, agentmemory stores iii-engine state outside the repository you start it from: `~/Library/Application Support/agentmemory` on macOS, `$XDG_DATA_HOME/agentmemory` or `~/.local/share/agentmemory` on Linux, and `%APPDATA%\agentmemory` on Windows. To choose a location, pass `--data-dir ` or set `AGENTMEMORY_DATA_DIR`:

```bash
npx @agentmemory/agentmemory --data-dir ~/.agentmemory-projects/main
AGENTMEMORY_DATA_DIR=~/.agentmemory-projects/main npx @agentmemory/agentmemory
```

Latest release notes: [CHANGELOG.md](CHANGELOG.md).

---

<h2 id="benchmarks"></h2>



| ### Retrieval Accuracy

**coding-agent-life-v1** (in-house corpus, sandbox-reproducible)

  Adapter   P@5   R@5   Top-5 hit rate   p50 latency  
 --- --- --- --- --- 
  **agentmemory hybrid**   **0.240**   **1.000**   **15 / 15**   14 ms  
  grep baseline   0.227   0.967   15 / 15   0 ms  

100% top-5 hit rate at the **P@5 math ceiling** for this corpus (0.240, see scorecard). Hybrid retrieves every gold session; grep misses 1 of 2 gold on the multi-session temporal query. Lift is **recall + temporal**, not aggregate precision. This benchmark is small and gold-sparse; the larger LongMemEval-S below differentiates better. Full per-type breakdown + correction note: [`docs/benchmarks/2026-05-20-coding-agent-life-v1.md`](docs/benchmarks/2026-05-20-coding-agent-life-v1.md).

**LongMemEval-S** (ICLR 2025, 500 questions)

  System   R@5   R@10   MRR  
 --- --- --- --- 
  **agentmemory**   **95.2%**   **98.6%**   **88.2%**  
  BM25-only fallback   86.2%   94.6%   71.5%   | ### Token Savings

  Approach   Tokens/yr   Cost/yr  
 --- --- --- 
  Paste full context   19.5M+   Impossible (exceeds window)  
  LLM-summarized   ~650K   ~$500  
  **agentmemory**   **~170K**   **~$10**  
  agentmemory + local embeddings   ~170K   **$0**   |
| --- | --- |



> Embedding model: `all-MiniLM-L6-v2` (local, free, no API key). Full reports: [`benchmark/LONGMEMEVAL.md`](benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](benchmark/QUALITY.md), [`benchmark/SCALE.md`](benchmark/SCALE.md). Competitor comparison: [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md) covering agentmemory vs mem0, Letta, Khoj, supermemory, TencentDB Agent Memory, MemPalace, Zep/Graphiti, Cognee, Hippo.

**Reproduce locally:** [`eval/README.md`](eval/README.md), an adapter-pluggable harness for LongMemEval `_s` (public 500-Q) + `coding-agent-life-v1` (in-house 15-session corpus). Grep / vector / agentmemory adapters score side-by-side, NDJSON output, published scorecards land in [`docs/benchmarks/`](docs/benchmarks/).

**Pairs with [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything), and [Graphify](https://github.com/safishamsi/graphify).** Code-graph indexing, multi-agent build pipelines, and broader knowledge graphs across docs / PDFs / images / videos. agentmemory remembers the work; those three projects light up the rest of the context layer. Recipes + question-routing table: [`docs/recipes/pairings.md`](docs/recipes/pairings.md).

---

<h2 id="vs-competitors"></h2>



|  | agentmemory | mem0 (63K ⭐) | Letta / MemGPT (24K ⭐) | Khoj (36K ⭐) | supermemory (29K ⭐) | TencentDB Agent Memory (22K ⭐) | MemPalace (54K ⭐) | oracleagentmemory | Hippo | Built-in (CLAUDE.md) |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **Type** | Memory engine + MCP server | Memory layer API | Full agent runtime | Personal AI | Memory API + app | Team memory hub (LLM proxy) | Vector memory (OSS) | Memory engine (Oracle DB) | Memory system | Static file |
| **Retrieval R@5** | **95.2%** | 68.5% (LoCoMo) | 83.2% (LoCoMo) | N/A | Self-reported | PersonaMem 76% (self-reported) | ~96.6% (self-reported) | 94.4% (self-reported) | N/A | N/A (grep) |
| **Auto-capture** | 12 hooks (zero manual effort) | Manual `add()` calls | Agent self-edits | Manual | API-side extraction | Proxy interception (base-URL swap) | Manual | API extraction | Manual | Manual editing |
| **Search** | BM25 + Vector + Graph (RRF fusion) | Vector + Graph | Vector (archival) | Semantic | Vector + RAG | 4 asset types (Chat / Skill / Wiki / CodeGraph) | Vector-only | Vector + semantic | Decay-weighted | Loads everything into context |
| **Multi-agent** | MCP + REST + leases + signals | API (no coordination) | Within Letta runtime only | No | No | Team roles + shared assets | No | Scoped only | Multi-agent shared | Per-agent files |
| **Framework lock-in** | None (any MCP client) | None | High (must use Letta) | Standalone | None | Proxy fronts every model call | None | Oracle Database | None | Per-agent format |
| **External deps** | None (SQLite + iii-engine) | Qdrant / pgvector | Postgres + vector DB | Multiple | Managed cloud | Docker stack (Core + Hub + Proxy) | Vector store | Oracle AI Database | None | None |
| **Memory lifecycle** | 4-tier consolidation + decay + auto-forget | Passive extraction | Agent-managed | Manual | Auto-forget | Manual review; auto-routing in progress | None | Not stated | Decay + consolidation | Manual pruning |
| **Token efficiency** | ~1,900 tokens/session ($10/yr) | Varies by integration | Core memory in context | Varies | Cloud pricing | Not stated | No token budget | LLM-backed (varies) | Varies | 22K+ tokens at 240 obs |
| **Real-time viewer** | Yes (port 3113) | Cloud dashboard | Cloud dashboard | Web UI | Cloud dashboard | Hub web UI | No | No | No | No |
| **Self-hosted** | Yes (default) | Optional | Optional | Yes | No (cloud-only) | Yes (Docker) | Yes | Yes (Oracle DB) | Yes | Yes |



<sub>Benchmark note: only agentmemory's R@5 is our own measured result (LongMemEval-S, reproducible from [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md)). The mem0 and Letta figures are their published LoCoMo numbers (a different dataset); the MemPalace, supermemory, TencentDB (PersonaMem), and oracleagentmemory figures are vendor self-reported claims we have not independently reproduced (oracleagentmemory's run used GPT-5.5 against an Oracle AI Database). Shown side by side for ballpark only, not a head-to-head on identical data. Star counts are approximate and drift over time.</sub>

**Newer entrants** worth knowing, compared in depth in [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md):

| System | ⭐ | Angle |
|--------|---|-------|
| Zep / Graphiti | 30K | Temporal knowledge graph; strongest published temporal-query results (LongMemEval 63.8%), but graph builds asynchronously so fresh facts can lag |
| Cognee | 30K | Document-to-knowledge-graph ingestion, Python-only, built for structured entity extraction rather than session capture |

None of these auto-capture from coding-agent hooks, ship a local-first viewer, or run keyless — the combination agentmemory is built around.

---

<h2 id="quick-start"></h2>

Compatibility: this release targets stable `iii-sdk` `^0.11.0` and iii-engine v0.11.x.

### Try it in 30 seconds

```bash
# Terminal 1: start the server
npx @agentmemory/agentmemory

# Terminal 2: seed sample data and see recall in action
npx @agentmemory/agentmemory demo
```

`demo` seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs semantic searches against them. You'll see it find "N+1 query fix" when you search "database performance optimization", which keyword matching cannot do.

Open `http://localhost:3113` to watch the memory build live.

### Everyday commands

Install and setup live in [Install](#install) above (the first run walks you through it). Day to day:

```bash
agentmemory                    # start the server
agentmemory stop               # tear it down
agentmemory connect <agent>    # wire another agent
agentmemory doctor             # interactive diagnostics + fix prompts
agentmemory remove             # uninstall everything we created
```

### Session Replay

Every session agentmemory records is replayable. Open the viewer, pick the **Replay** tab, and scrub through the timeline: prompts, tool calls, tool results, and responses render as discrete events with play/pause, speed control (0.5x to 4x), and keyboard shortcuts (space to toggle, arrows to step).

To bring in older Claude Code JSONL transcripts:

```bash
# Import everything under the default ~/.claude/projects
npx @agentmemory/agentmemory import-jsonl

# Or import a single file
npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl
```

Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions, with no side-channel servers. Each imported transcript is indexed for search, stamped with origin channel `import`, and mined for a session crystal and lessons.

> **Heads-up if you rely on `import-jsonl` as your primary capture path:** Claude Code's `cleanupPeriodDays` (in `~/.claude/settings.json`, default **30**) auto-deletes JSONL transcripts older than that window from `~/.claude/projects/`. If you install agentmemory fresh on a months-old Claude Code history, anything older than 30 days is already gone before the first import. Either run `import-jsonl` on a cron, raise `cleanupPeriodDays` to something higher, or wire the auto-capture hooks (the default plugin install path) so each turn lands in agentmemory while the session is live and the JSONL cleanup stops mattering.

### Upgrade / Maintenance

Use the maintenance command when you intentionally want to update your local runtime:

```bash
npx @agentmemory/agentmemory upgrade
```

Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies and pull the pinned `iiidev/iii:0.11.2` Docker image. It never installs an unpinned or newer iii engine.

Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cli.ts:544-595` region).

### Claude Code (one block, paste it)

```text
Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 17 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 54 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113.
```

#### Claude Code without the plugin install (MCP-standalone path)

If you wire agentmemory's MCP server through `~/.claude.json` directly instead of using `/plugin install`, Claude Code never resolves `${CLAUDE_PLUGIN_ROOT}` and you have to point hook scripts at absolute paths in `~/.claude/settings.json`. Those paths typically embed the agentmemory version (e.g. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.22/scripts/…`), so the next upgrade silently breaks every hook.

Workaround:

```bash
agentmemory connect claude-code --with-hooks
```

This merges the same hook commands into `~/.claude/settings.json` with absolute paths resolved to the bundled `plugin/` directory of the currently installed `@agentmemory/agentmemory` package. Re-run the command after upgrading agentmemory to refresh the paths. User entries in the same file are preserved; only previous agentmemory entries are replaced. Using the `/plugin install` path remains the recommended approach.
For remote or protected deployments, launch Claude Code with `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` set. The plugin passes both values through to its bundled MCP server; when `AGENTMEMORY_URL` is empty, the MCP shim uses `http://localhost:3111`.

### Codex CLI (Codex plugin platform)

```bash
# 1. start the memory server in a separate terminal
npx @agentmemory/agentmemory

# 2. register the agentmemory marketplace and install the plugin
codex plugin marketplace add rohitg00/agentmemory
codex plugin add agentmemory@agentmemory
```

The Codex plugin ships from the same `plugin/` directory as the Claude Code plugin. It registers:

- `@agentmemory/mcp` as an MCP server (proxies all 54 tools when `AGENTMEMORY_URL` points at a running agentmemory server; falls back to 7 tools locally when no server is reachable)
- 6 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
- 9 invocable skills: `/recall`, `/remember`, `/session-history`, `/forget`, `/recap`, `/handoff`, `/lesson`, `/commit-context`, `/commit-history`, plus 8 reference skills the agent loads on demand (memory discipline, MCP tools, REST API, config, agents, hooks, architecture, and the skill-authoring guide)

Codex's hook engine injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses (per [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex.

#### Codex Desktop: plugin hooks currently silent (workaround available)

`CodexHooks` and `PluginHooks` are both stable + default-enabled in [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), but Codex Desktop builds currently do not dispatch plugin-local `hooks.json` ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP tools still work; only the lifecycle observations are missing.

Until upstream lands the fix, mirror the same hook commands into the global `~/.codex/hooks.json`:

```bash
agentmemory connect codex --with-hooks
```

This adds an idempotent block to `~/.codex/hooks.json` referencing absolute paths to the bundled scripts (no `${CLAUDE_PLUGIN_ROOT}` expansion needed at user-scope). Re-run the same command after upgrading agentmemory to refresh paths. User entries in the same file are preserved; only previous agentmemory entries are replaced.

### GitHub Copilot CLI

```bash
# MCP-only wiring
agentmemory connect copilot-cli

# Full hooks/skills plugin from the GitHub subdir
copilot plugin install rohitg00/agentmemory:plugin
```

`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. This adapter is Windows-safe even though other `connect` adapters still require manual Windows setup. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience.


**OpenClaw (paste this prompt)**

```text
Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 54 memory tools:

{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"],
      "env": {
        "AGENTMEMORY_URL": "http://localhost:3111"
      }
    }
  }
}

Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper memory-slot integration, copy `integrations/openclaw` to `~/.openclaw/extensions/agentmemory` and enable `plugins.slots.memory = "agentmemory"` in `~/.openclaw/openclaw.json`.
```

Full guide: [`integrations/openclaw/`](integrations/openclaw/)




**Hermes Agent (paste this prompt)**

```text
Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 54 memory tools:

mcp_servers:
  agentmemory:
    command: npx
    args: ["-y", "@agentmemory/mcp"]

memory:
  provider: agentmemory

Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper 6-hook memory provider integration (pre-LLM context injection, turn capture, MEMORY.md mirroring, system prompt block), copy integrations/hermes from the agentmemory repo to ~/.hermes/plugins/agentmemory.
```

Full guide: [`integrations/hermes/`](integrations/hermes/)



### Other agents

Start the memory server: `npx @agentmemory/agentmemory`

#### Native skills via `npx skills add` (50+ agents)

agentmemory ships 17 skills in the Claude-Code-style `<dir>/SKILL.md` format: 9 invocable action skills (`remember`, `recall`, `recap`, `handoff`, `forget`, `lesson`, `commit-context`, `commit-history`, `session-history`) and 8 reference skills the agent loads on demand (`memory-discipline`, `agentmemory-mcp-tools`, `agentmemory-rest-api`, `agentmemory-config`, `agentmemory-agents`, `agentmemory-hooks`, `agentmemory-architecture`, `write-agentmemory-skill`). The reference skills carry data tables generated from source, so they never drift. The [`skills`](https://npmjs.com/package/skills) CLI by vercel-labs auto-installs them into the calling agent's native skill directory across 50+ agents (Claude Code, Cursor, Cline, Continue, Droid, Warp, Codex, Antigravity, Kiro, OpenCode, Goose, Roo, Trae, Windsurf, and more):

```bash
npx skills add rohitg00/agentmemory -y          # auto-detects the calling agent
npx skills add rohitg00/agentmemory -y -a warp  # explicit agent
npx skills add rohitg00/agentmemory -y -a '*'   # install to every installed agent
```

This is **complementary** to `agentmemory connect <agent>`:

- `agentmemory connect <agent>` writes the MCP server config so the tools are available.
- `npx skills add rohitg00/agentmemory` installs the skills so the agent knows when to call them.

For the few agents the skills CLI doesn't cover yet (Zed v1.3.x and below), drop the 17 SKILL.md files under the agent's native skill directory yourself; the same format works everywhere.

#### Standard MCP block

The agentmemory entry is the **same MCP server block** across every host that uses the `mcpServers` shape (Cursor, Claude Desktop, Cline, Roo Code, Gemini CLI, OpenClaw):

```json
"agentmemory": {
  "command": "npx",
  "args": ["-y", "@agentmemory/mcp"],
  "env": {
    "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
    "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
  }
}
```

**Merge this entry into the existing `mcpServers` object** in the host's config file; don't replace the file. If the file already has other servers, add `agentmemory` next to them as another key inside `mcpServers`. If `mcpServers` is missing entirely, paste the block inside `{ "mcpServers": { ... } }`. The `${VAR}` placeholders inherit `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` from the shell at MCP-server launch; unset vars pass empty strings and the shim falls back to `http://localhost:3111`. One wired entry covers both local and remote (k8s / reverse-proxied) deployments.

| Agent | Config file | Notes |
|---|---|---|
| **Cursor (MCP only)** | `~/.cursor/mcp.json` | Merge into `mcpServers`, or `agentmemory connect cursor`. One-click deeplink also available on the website. |
| **Cursor (full plugin)** | `.cursor-plugin/` | Cursor Marketplace listing (submission in review) or Cursor Settings → Plugins → local checkout. Registers 7 auto-capture hooks (sessionStart, beforeSubmitPrompt, preToolUse, postToolUse, postToolUseFailure, stop, sessionEnd) + 17 skills + the MCP server, with `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` managed in Cursor's plugin dashboard. Works in the Cursor IDE and `cursor-agent` CLI; CLI print-mode prompts are backfilled from the session transcript at session end. |
| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Merge into `mcpServers`. Restart Claude Desktop after editing. |
| **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | Same `mcpServers` block. |
| **Devin CLI (MCP + hooks)** | `~/.config/devin/config.json` | `agentmemory connect devin` merges the MCP entry; `--with-hooks` adds six native auto-capture hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SessionEnd) with Devin'"'"'s lowercase tool matchers. Verify with `devin mcp list` and `/hooks` inside devin. |
| **Devin CLI (full plugin)** | `plugin/.devin-plugin/` | `devin plugins install ./plugin` from a checkout registers all 17 skills as `/agentmemory:<skill>` slash commands plus the MCP server. Devin plugin hooks cannot fire `SessionStart`/`SessionEnd`, so pair it with `connect devin --with-hooks` for full session capture. |
| **Devin (cloud)** | Settings → Connections → MCP servers | Add a custom MCP (STDIO): command `npx`, args `-y @agentmemory/mcp@latest`, env `AGENTMEMORY_URL` pointing at a network-reachable agentmemory deployment plus `AGENTMEMORY_SECRET` (cloud sessions cannot reach localhost — see [`deploy/`](deploy/)). Store the secret in Devin Secrets, then use "Test listing tools" to verify all 54 tools appear. |
| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges). |
| **GitHub Copilot CLI (MCP only)** | `~/.copilot/mcp-config.json` | `agentmemory connect copilot-cli` merges `mcpServers.agentmemory`; Copilot picks it up on next launch or `/mcp`. |
| **GitHub Copilot CLI (full plugin)** | Copilot plugin install | `copilot plugin install rohitg00/agentmemory:plugin` for the plugin from the GitHub subdir. |
| **OpenClaw** | OpenClaw MCP config | Same `mcpServers` block. Deeper: `openclaw plugins install ./integrations/openclaw` claims OpenClaw's memory slot (auto-switches from `memory-core`); set `plugins.entries.agentmemory.hooks.allowConversationAccess=true` or turn capture is silently blocked. See [`integrations/openclaw`](integrations/openclaw/). |
| **Codex CLI (MCP only)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, or add `[mcp_servers.agentmemory]` manually. |
| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin add agentmemory@agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 17 skills. On Codex Desktop, also run `agentmemory connect codex --with-hooks` until [openai/codex#16430](https://github.com/openai/codex/issues/16430) lands; plugin hooks are currently silent there. |
| **OpenCode (MCP only)** | `opencode.json` | Different shape: top-level `mcp` key, command as array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
| **OpenCode (full plugin)** | `plugin/opencode/` | 22 auto-capture hooks covering session lifecycle, messages, tools, errors. Project attribution is per-session, so one OpenCode process spanning several repositories files each session under its own project. Two slash commands (`/recall`, `/remember`). Copy `plugin/opencode/` into your OpenCode workspace and add the plugin entry to `opencode.json`. See [`plugin/opencode/README.md`](plugin/opencode/README.md) for the full hook table + gap analysis. |
| **pi** | `~/.pi/agent/extensions/agentmemory` | `agentmemory connect pi` installs the bundled extension into pi's auto-discovery directory (recall on agent start, capture on agent end, `memory_search` / `memory_save` / `memory_health` tools, `/agentmemory-status`). `/reload` in a running pi picks it up. [`integrations/pi`](integrations/pi/) is also a pi package (`pi install ./integrations/pi` from a checkout). |
| **Hermes Agent** | `~/.hermes/config.yaml` | `cp -r integrations/hermes ~/.hermes/plugins/agentmemory` + `memory.provider: agentmemory` gives the 6-hook memory provider (prefetch, turn capture, session end, pre-compress, MEMORY.md mirroring, system prompt block). Validate with `hermes plugins doctor` and `hermes memory status`. See [`integrations/hermes`](integrations/hermes/). |
| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` writes the standard `mcpServers` block. Hook payload is field-compatible with Claude Code, so the existing 12-hook scripts work without modification; wire them via the `hooks` section in the same `settings.json`. |
| **Antigravity** (replaces Gemini CLI) | `mcp_config.json` (in Antigravity's User dir) | `agentmemory connect antigravity` writes the standard `mcpServers` block. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Use after the 2026-06-18 Gemini CLI sunset. |
| **Antigravity CLI** (`agy`) | `~/.gemini/config/mcp_config.json` | `agentmemory connect antigravity-cli`. The `agy` CLI keeps its own config under `~/.gemini/`, separate from the Antigravity IDE above. Pass `--with-hooks` for native auto-capture via `~/.gemini/config/hooks.json`. |
| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` writes the user-level config. Workspace overrides go in `.kiro/settings/mcp.json` next to your code. |
| **Warp** | `~/.warp/.mcp.json` | `agentmemory connect warp` writes the standard `mcpServers` block. Warp also auto-discovers skills from `.claude/skills/`; once the Claude Code plugin is installed the 8 agentmemory skills (`remember`, `recall`, `recap`, `handoff`, `forget`, `commit-context`, `commit-history`, `session-history`) appear natively in Warp's slash-command palette. |
| **Cline (CLI)** | `~/.cline/mcp.json` | `agentmemory connect cline` writes the standard `mcpServers` block. VS Code extension users: paste the same block via Cline Settings → MCP Servers → Edit JSON. |
| **Continue.dev** | `~/.continue/config.yaml` (preferred) or `config.json` (legacy) | `agentmemory connect continue` creates `config.yaml` from scratch when neither exists, or modifies existing `config.json`. **If you already have `config.yaml`** the adapter prints the exact block to paste under `mcpServers:`; it won't silently rewrite your yaml because preserving comments and anchors safely needs a YAML parser the package doesn't ship. Continue uses array form (not object) for `mcpServers`. |
| **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. |
| **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `<repo>/.factory/mcp.json`. Pass `--with-hooks` for native auto-capture. |
| **DeepSeek Harness** | `$DSH_HOME/cordis.patch.yml` | `agentmemory connect dsh` appends an `@deepseek-ai/dsh-mcp-client` row to the home-level patch layer every Harness profile loads; tools register as `mcp__agentmemory__*`. Pass `--with-hooks` to also wire auto-capture: the bundled Claude Code hook scripts run through Harness's first-party `@deepseek-ai/dsh-hooks-claude-code` bridge (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop) via a manifest written to `$DSH_HOME/agentmemory.hooks.json`. Defaults to `~/.dsh` when `DSH_HOME` is unset. |
| **Goose** | Goose MCP settings UI | Same `mcpServers` block; use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). |
| **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
| **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. |

**Sandboxed MCP clients** (Flatpak / Snap / restrictive containers) that can't reach the host's `localhost`: also set `"AGENTMEMORY_FORCE_PROXY": "1"` in the `env` block, and point `AGENTMEMORY_URL` at a route the sandbox can actually reach (e.g. your LAN IP).

### Programmatic access (Python / Rust / Node)

agentmemory registers its core operations as iii functions (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Any language with an iii SDK can call them directly over `ws://localhost:49134`, with no separate REST client per language.

```bash
pip install iii-sdk         # Python
cargo add iii-sdk           # Rust
npm  install iii-sdk        # Node
```

```python
from iii import register_worker

iii = register_worker("ws://localhost:49134")
iii.connect()

iii.trigger({
    "function_id": "mem::smart-search",
    "payload": {"project": "demo", "query": "how do tokens refresh"},
})
```

Worked example: [`examples/python/`](examples/python/) (quickstart + observation/recall flow). REST on `:3111` remains available for hosts without an iii runtime.

### From source

```bash
git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
npm install && npm run build && npm start
```

This starts agentmemory with a local `iii-engine` if `iii` is already installed, or falls back to Docker Compose if Docker is available. REST, streams, and the viewer bind to `127.0.0.1` by default.

Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`**. `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=<version>` if you've migrated to the sandbox model manually.

- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii`
- **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin`
- **Linux x64:** swap for `x86_64-unknown-linux-gnu`
- **Linux arm64:** swap for `aarch64-unknown-linux-gnu`
- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extract `iii.exe`, add to PATH

Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.11.2`). Full docs: [iii.dev/docs](https://iii.dev/docs).

### Windows

agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough; you also need the `iii-engine` runtime (a separate native binary) as a background process. The official upstream installer is a `sh` script and there is no PowerShell installer or scoop/winget package today, so Windows users have two paths:

**Option A: prebuilt Windows binary (recommended)**

```powershell
# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser
#    (we pin to v0.11.2 until agentmemory refactors for the new sandbox
#     model that engine v0.11.6+ requires)
# 2. Download iii-x86_64-pc-windows-msvc.zip
#    (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine)
# 3. Extract iii.exe somewhere on PATH, or place it at:
#    %USERPROFILE%\.local\bin\iii.exe
#    (agentmemory checks that location automatically)
# 4. Verify:
iii --version
# Should print: 0.11.2

# 5. Then run agentmemory as usual:
npx -y @agentmemory/agentmemory
```

**Option B: Docker Desktop**

```powershell
# 1. Install Docker Desktop for Windows
# 2. Start Docker Desktop and make sure the engine is running
# 3. Run agentmemory — it will auto-start the bundled compose file:
npx -y @agentmemory/agentmemory
```

**Option C: standalone MCP only (no engine).** If you only need the MCP tools for your agent and don't need the REST API, viewer, or cron jobs, skip the engine entirely:

```powershell
npx -y @agentmemory/agentmemory mcp
# or via the shim package:
npx -y @agentmemory/mcp
```

**Diagnostics for Windows:** if `npx @agentmemory/agentmemory` fails, re-run with `--verbose` to see the actual engine stderr. Common failure modes:

| Symptom | Fix |
|---|---|
| `iii-engine process started` then `did not become ready within 15s` | Engine crashed on startup; re-run with `--verbose`, check stderr |
| `Could not start iii-engine` | Neither `iii.exe` nor Docker is installed. See Option A or B above |
| Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port <N>` |
| Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) |

> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods, all pinned to v0.11.2: the prebuilt v0.11.2 binary above, the upstream sh install script **with the version pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), and the Docker image `iiidev/iii:0.11.2`. A bare `install.sh | sh` installs the **latest** engine, which agentmemory does not support; always pass `VERSION=0.11.2`. Easiest of all: just run `npx @agentmemory/agentmemory`, which fetches the pinned engine into `~/.agentmemory/bin` for you.

---

<h2 id="deploy">Deploy</h2>

One-click templates for managed hosts. Each one ships a self-contained
Dockerfile that pulls `@agentmemory/agentmemory` from npm and copies
the iii engine binary in from the official `iiidev/iii` Docker Hub
image; no pre-built agentmemory image required. Persistent storage
mounts at `/data`; the first-boot entrypoint overwrites the
npm-bundled iii config (which binds `127.0.0.1`) with a deploy-tuned
one that binds `0.0.0.0` and uses absolute `/data` paths, generates
the HMAC secret, then drops privileges from `root` to `node` via
`gosu` before exec'ing the agentmemory CLI.


  [](https://fly.io/launch?repo=https://github.com/rohitg00/agentmemory&path=deploy/fly)
  [](https://railway.com/new/template?template=https%3A%2F%2Fgithub.com%2Frohitg00%2Fagentmemory&rootDirectory=deploy%2Frailway)


Render's one-click deploy button requires `render.yaml` at the repository root, which we deliberately keep clean. Use the Render Blueprint flow documented in [`deploy/render/`](./deploy/render/README.md) to point at the in-repo blueprint manually.

Full setup details (HMAC capture, viewer SSH tunnel, rotation, backup,
cost floors) live in [`deploy/`](./deploy/README.md):

- [`deploy/fly`](./deploy/fly/README.md): single machine with
  `auto_stop_machines = "stop"`; cheapest idle.
- [`deploy/railway`](./deploy/railway/README.md): Hobby plan flat fee,
  volume in the dashboard.
- [`deploy/render`](./deploy/render/README.md): Blueprint flow,
  automatic disk snapshots on paid plans.
- [`deploy/coolify`](./deploy/coolify/README.md): self-hosted on your
  own VPS via [Coolify](https://coolify.io/self-hosted); same Docker
  Compose stack, you own the host and the data.

Only port `3111` is published. The viewer on `3113` stays bound to
loopback inside the container; every template's README documents the
SSH-tunnel pattern for reaching it.

---

<h2 id="why-agentmemory"></h2>

Every coding agent forgets everything when the session ends, and each new session starts with you re-explaining your stack. agentmemory runs in the background and removes that step.

```text
Session 1: "Add auth to the API"
  Agent writes code, runs tests, fixes bugs
  agentmemory silently captures every tool use
  Session ends -> observations compressed into structured memory

Session 2: "Now add rate limiting"
  Agent already knows:
    - Auth uses JWT middleware in src/middleware/auth.ts
    - Tests in test/auth.test.ts cover token validation
    - You chose jose over jsonwebtoken for Edge compatibility
  Zero re-explaining. Starts working immediately.
```

### vs built-in agent memory

Every AI coding agent ships with built-in memory: Claude Code has `MEMORY.md`, Cursor has notepads, Cline has memory bank. These work like sticky notes. agentmemory is the searchable database behind the sticky notes.

| | Built-in (CLAUDE.md) | agentmemory |
|---|---|---|
| Scale | 200-line cap | Unlimited |
| Search | Loads everything into context | BM25 + vector + graph (top-K only) |
| Token cost | 22K+ at 240 observations | ~1,900 tokens (92% less) |
| Cross-agent | Per-agent files | MCP + REST (any agent) |
| Coordination | None | Leases, signals, actions, routines |
| Observability | Read files manually | Real-time viewer on :3113 |

---

<h2 id="how-it-works"></h2>

### Memory Pipeline

```text
PostToolUse hook fires
  -> SHA-256 dedup (5min window)
  -> Privacy filter (strip secrets, API keys)
  -> Store raw observation
  -> LLM compress -> structured facts + concepts + narrative
  -> Vector embedding (6 providers + local)
  -> Index in BM25 + vector

Stop / SessionEnd hook fires
  -> Summarize session
  -> Knowledge graph extraction (if GRAPH_EXTRACTION_ENABLED=true)
  -> Slot reflection (if SLOT_REFLECT_ENABLED=true)

SessionStart hook fires
  -> Load project profile (top concepts, files, patterns)
  -> Hybrid search (BM25 + vector + graph)
  -> Token budget (default: 2000 tokens)
  -> Inject into conversation
```

### 4-Tier Memory Consolidation

Modeled on how human brains process memory, including sleep consolidation.

| Tier | What | Analogy |
|------|------|---------|
| **Working** | Raw observations from tool use | Short-term memory |
| **Episodic** | Compressed session summaries | "What happened" |
| **Semantic** | Extracted facts and patterns | "What I know" |
| **Procedural** | Workflows and decision patterns | "How to do it" |

Memories decay over time (Ebbinghaus curve). Frequently accessed memories strengthen. Stale memories auto-evict. Contradictions are detected and resolved.

### What Gets Captured

| Hook | Captures |
|------|----------|
| `SessionStart` | Project path, session ID |
| `UserPromptSubmit` | User prompts (privacy-filtered) |
| `PreToolUse` | File access patterns + enriched context |
| `PostToolUse` | Tool name, input, output |
| `PostToolUseFailure` | Error context |
| `PreCompact` | Re-injects memory before compaction |
| `SubagentStart/Stop` | Sub-agent lifecycle |
| `Stop` | End-of-session summary |
| `SessionEnd` | Session complete marker |

### Key Capabilities

| Capability | Description |
|---|---|
| **Automatic capture** | Every tool use recorded via hooks, no manual effort |
| **Semantic search** | BM25 + vector + knowledge graph with RRF fusion |
| **Memory evolution** | Versioning, supersession, relationship graphs |
| **Recall hygiene** | Superseded memory versions leave the search indexes; the version chain in KV keeps full history |
| **Near-duplicate hints** | Saves report an advisory `similarTo` match when new content closely resembles an existing memory |
| **Per-agent scoping** | `agentId` threads through save and recall across REST, MCP, and the search index, in shared or isolated mode |
| **Write-time provenance** | Every observation and memory carries an immutable origin channel (user, agent, tool, import, or shared) stamped at capture, save, and import |
| **Auto-forgetting** | TTL expiry, contradiction detection, importance eviction |
| **Privacy first** | API keys, secrets, `` tags stripped before storage |
| **Self-healing** | Circuit breaker, provider fallback chain, health monitoring |
| **Claude bridge** | Bi-directional sync with MEMORY.md |
| **Knowledge graph** | Entity extraction + BFS traversal |
| **Team memory** | Namespaced shared + private across team members |
| **Citation provenance** | Trace any memory back to source observations |
| **Git snapshots** | Version, rollback, and diff memory state |

---

<h2 id="search"></h2>

Triple-stream retrieval combining three signals:

| Stream | What it does | When |
|---|---|---|
| **BM25** | Stemmed keyword matching with synonym expansion | Always on |
| **Vector** | Cosine similarity over dense embeddings | Embedding provider configured |
| **Graph** | Knowledge graph traversal via entity matching | Entities detected in query |

Fused with Reciprocal Rank Fusion (RRF, k=60) and session-diversified (max 3 results per session).

Hybrid ranking applies to the primary recall path, not just `smart-search`: `mem::search` (behind `memory_recall`) ranks through the same BM25 + vector + graph fusion once the vector index is populated. Lesson recall runs on a dedicated in-memory BM25 index instead of scanning the whole corpus per query. Superseded memory versions are excluded from every recall path; the version chain keeps their history.

BM25 tokenizes Greek, Cyrillic, Hebrew, Arabic, and accented Latin out of the box. For Chinese / Japanese / Korean memories, install the optional segmenters (`npm install @node-rs/jieba tiny-segmenter`) to split CJK runs into word-level tokens; without them, agentmemory soft-falls to whole-run tokenization and prints a one-time hint on stderr.

### Embedding providers

agentmemory auto-detects your provider. For best results, install local embeddings (free):

```bash
npm install @huggingface/transformers
```

| Provider | Model | Cost | Notes |
|---|---|---|---|
| **Local (recommended)** | `all-MiniLM-L6-v2` | Free | Offline, +8pp recall over BM25-only |
| Gemini | `gemini-embedding-001` | Free tier | 100+ languages, 768/1536/3072 dims (MRL), 2048-token input. Replaces `text-embedding-004` ([deprecated, shutdown Jan 14, 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
| OpenAI | `text-embedding-3-small` | $0.02/1M | Highest quality |
| Voyage AI | `voyage-code-3` | Paid | Optimized for code |
| Cohere | `embed-english-v3.0` | Free trial | General purpose |
| OpenRouter | Any model | Varies | Multi-model proxy |

---

<h2 id="mcp-server"></h2>

54 tools, 6 resources, 3 prompts, and 17 skills.

> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 54-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag; setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`.

### 54 Tools

Three tool surfaces, smallest to largest: `AGENTMEMORY_TOOLS=core` trims visibility to 8 essentials (`memory_save`, `memory_recall`, `memory_consolidate`, `memory_smart_search`, `memory_sessions`, `memory_diagnose`, `memory_lesson_save`, `memory_reflect`); the base set below is the registry's 14 foundational tools; the default (`AGENTMEMORY_TOOLS=all`) exposes all 54.


Base tools (14)

| Tool | Description |
|------|-------------|
| `memory_recall` | Search past observations |
| `memory_compress_file` | Compress markdown files while preserving structure |
| `memory_save` | Save an insight, decision, or pattern |
| `memory_file_history` | Past observations about specific files |
| `memory_patterns` | Detect recurring patterns |
| `memory_sessions` | List recent sessions |
| `memory_smart_search` | Hybrid semantic + keyword search |
| `memory_vision_search` | Search image observations |
| `memory_timeline` | Chronological observations |
| `memory_profile` | Project profile (concepts, files, patterns) |
| `memory_export` | Export all memory data |
| `memory_relations` | Query relationship graph |
| `memory_commit_lookup` | Sessions behind a git commit |
| `memory_commits` | Commits recorded for a session |




Extended tools (54 total, the default surface)

| Tool | Description |
|------|-------------|
| `memory_patterns` | Detect recurring patterns |
| `memory_timeline` | Chronological observations |
| `memory_relations` | Query relationship graph |
| `memory_graph_query` | Knowledge graph traversal |
| `memory_consolidate` | Run 4-tier consolidation |
| `memory_claude_bridge_sync` | Sync with MEMORY.md |
| `memory_team_share` | Share with team members |
| `memory_team_feed` | Recent shared items |
| `memory_audit` | Audit trail of operations |
| `memory_governance_delete` | Delete with audit trail |
| `memory_snapshot_create` | Git-versioned snapshot |
| `memory_action_create` | Create work items with dependencies |
| `memory_action_update` | Update action status |
| `memory_frontier` | Unblocked actions ranked by priority |
| `memory_next` | Single most important next action |
| `memory_lease` | Exclusive action leases (multi-agent) |
| `memory_routine_run` | Instantiate workflow routines |
| `memory_signal_send` | Inter-agent messaging |
| `memory_signal_read` | Read messages with receipts |
| `memory_checkpoint` | External condition gates |
| `memory_mesh_sync` | P2P sync between instances |
| `memory_sentinel_create` | Event-driven watchers |
| `memory_sentinel_trigger` | Fire sentinels externally |
| `memory_sketch_create` | Ephemeral action graphs |
| `memory_sketch_promote` | Promote to permanent |
| `memory_crystallize` | Compact action chains |
| `memory_diagnose` | Health checks |
| `memory_heal` | Auto-fix stuck state |
| `memory_facet_tag` | Dimension:value tags |
| `memory_facet_query` | Query by facet tags |
| `memory_verify` | Trace provenance |



### 6 Resources · 3 Prompts · 17 Skills

| Type | Name | Description |
|------|------|-------------|
| Resource | `agentmemory://status` | Health, session count, memory count |
| Resource | `agentmemory://project/{name}/profile` | Per-project intelligence |
| Resource | `agentmemory://project/{name}/recent` | Recent observations for a project |
| Resource | `agentmemory://memories/latest` | Latest 10 active memories |
| Resource | `agentmemory://graph/stats` | Knowledge graph statistics |
| Resource | `agentmemory://team/{id}/profile` | Shared team profile |
| Prompt | `recall_context` | Search + return context messages |
| Prompt | `session_handoff` | Handoff data between agents |
| Prompt | `detect_patterns` | Analyze recurring patterns |
| Skill | `/recall` | Search memory |
| Skill | `/remember` | Save to long-term memory |
| Skill | `/session-history` | Recent session summaries |
| Skill | `/forget` | Delete observations/sessions |

The table shows the four core skills. The full set is 9 invocable skills plus 8 reference skills; see the Native skills section above.

### Standalone MCP

Run without the full server, for any MCP client. Either of these works:

```bash
npx -y @agentmemory/agentmemory mcp   # canonical (always available)
npx -y @agentmemory/mcp                # shim package alias
```

Or add to your agent's MCP config:

Most agents (Cursor, Claude Desktop, Cline, Roo Code, Gemini CLI):
```json
{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"],
      "env": {
        "AGENTMEMORY_URL": "http://localhost:3111"
      }
    }
  }
}
```

Merge the `agentmemory` entry into your host's existing `mcpServers` object rather than replacing the file. For sandboxed clients that can't reach the host's `localhost`, add `"AGENTMEMORY_FORCE_PROXY": "1"` to the env block and set `AGENTMEMORY_URL` to a route the sandbox can reach.

OpenCode (`opencode.json`):
```json
{
  "mcp": {
    "agentmemory": {
      "type": "local",
      "command": ["npx", "-y", "@agentmemory/mcp"],
      "enabled": true
    }
  },
  "plugin": ["./plugins/agentmemory-capture.ts"]
}
```

Copy the plugin file from the repo:
```bash
mkdir -p ~/.config/opencode/plugins
cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
```

---

<h2 id="real-time-viewer"></h2>

Auto-starts on port `3113`. Live observation stream with a stream status indicator, a two-pane session explorer (list beside a sticky detail panel on wide screens), memory and lesson rows that expand to the full stored record including raw JSON and origin provenance, a knowledge graph that clusters nodes by type while relations are sparse, session replay, and a health dashboard.

```bash
open http://localhost:3113
```

The viewer server binds to `127.0.0.1` by default. The REST-served `/agentmemory/viewer` endpoint follows the normal `AGENTMEMORY_SECRET` bearer-token rules. CSP headers use a per-response script nonce and disable inline handler attributes (`script-src-attr 'none'`).

---

<h2 id="iii-console"></h2>

The viewer at `:3113` shows what your agent **remembered**. The [iii console](https://iii.dev/docs/console) shows what your agent **did**: every memory op as an OpenTelemetry trace, every KV entry editable, every function invocable, every stream tappable. Two windows on the same memory: one product-shaped, one engine-shaped.

Watch a `memory_smart_search` fire and see the BM25 scan → embedding lookup → RRF fusion → reranker as a waterfall. Edit a stuck consolidation timer in the KV browser. Replay a `PostToolUse` hook with a tweaked payload. Pin the WebSocket stream and watch observations land live.

agentmemory ships this for free because every function call and trigger fires through iii; nothing custom, nothing to instrument.



**Already installed.** The console ships with `iii`; no separate installer.

**Launch alongside agentmemory:**

```bash
# agentmemory viewer holds port 3113, so run the console on 3114.
# Engine REST (3111), WebSocket (3112), and bridge (49134) defaults match agentmemory.
iii console --port 3114
```

Then open `http://localhost:3114`. Add `--enable-flow` for the experimental architecture-graph page.

Override engine endpoints only if you've moved them:

```bash
iii console --port 3114 \
  --engine-port 3111 \
  --ws-port 3112 \
  --bridge-port 49134
```

**What you can do from the console:**

| Page | Use it to |
|------|-----------|
| **Workers** | See every connected worker and its live metrics, including the agentmemory worker itself. |
| **Functions** | Invoke any of agentmemory's functions directly with a JSON payload; handy for testing `memory.recall`, `memory.consolidate`, `graph.query` without wiring a client. |
| **Triggers** | Replay HTTP, cron, event, and state triggers: fire the consolidation cron manually, retry an HTTP route, emit a state change. |
| **States** | KV browser with full CRUD over sessions, memory slots, lifecycle timers, and the embeddings index; edit values in place. |
| **Streams** | Live WebSocket monitor for memory writes, hook events, and observation updates as they flow through iii streams. |
| **Queues** | Durable queue topics + dead-letter management. Replay or drop failed embedding / compression jobs. |
| **Traces** | OpenTelemetry waterfall / flame / service-breakdown views. Filter by `trace_id` to see exactly which functions, DB calls, and embedding requests a single `memory.search` produced. |
| **Logs** | Structured OTEL logs filtered and correlated to trace/span IDs. |
| **Config** | Runtime configuration: see exactly which workers, providers, and ports your engine is running with. |
| **Flow** | (Optional, `--enable-flow`) Interactive architecture graph of every worker, trigger, and stream. |



**Traces are already on:**

`iii-config.yaml` ships with the `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs). No extra config needed; the moment agentmemory starts, every memory operation emits a trace span and a structured log the console can read.

If you want to export to Jaeger/Honeycomb/Grafana Tempo instead, change `exporter: memory` to `exporter: otlp` and set the collector endpoint per iii's observability docs.

> **Heads-up:** no auth is enforced on the console itself; keep it bound to `127.0.0.1` (the default) and never expose it publicly.

---

<h2 id="powered-by-iii"></h2>

agentmemory is **already a running [iii](https://iii.dev) instance**. Three primitives (worker, function, trigger) compose the runtime; KV state, streams, and OTEL traces come from iii-state, iii-stream, and iii-observability workers that ship with iii. You didn't install Postgres, Redis, Express, pm2, or Prometheus, because iii replaces them.

That means one more command extends agentmemory with an entire new capability.

### Extend agentmemory with one command

```bash
iii worker add iii-pubsub          # fan memory writes out to every connected instance
iii worker add iii-cron            # scheduled consolidation, decay sweeps, snapshot rotation
iii worker add iii-queue           # durable retries for embedding + compression jobs
iii worker add iii-observability   # OTEL traces on every memory op (default on)
iii worker add iii-sandbox         # run recalled code inside an isolated microVM
iii worker add iii-database        # swap in a SQL-backed state adapter
iii worker add mcp                 # generic MCP host alongside the agentmemory MCP
```

Each `iii worker add` registers new functions and triggers into the same engine agentmemory is already running on. The viewer and console pick them up immediately: no reload, no new integration, no new container.

| `iii worker add` | What you get on top of agentmemory |
|---|---|
| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Multi-instance memory: every `remember` fans out, every `search` reads the union |
| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Scheduled lifecycle: nightly consolidation, weekly snapshots, decay on a fixed clock |
| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable retries: failed embedding + compression jobs survive restart, no lost observations |
| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL traces, metrics, logs on every function, wired in `iii-config.yaml` from day one |
| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Code that came out of `memory_recall` runs inside a throwaway VM, not your shell |
| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-backed state adapter when you outgrow the in-memory KV defaults |
| [`mcp`](https://workers.iii.dev/workers/mcp) | Stand up extra MCP servers next to agentmemory's, share the same engine |

Full registry: [workers.iii.dev](https://workers.iii.dev). Every worker there composes through the same primitives agentmemory uses, and the agentmemory you already have is one of them.

### What iii replaces

| Traditional stack | agentmemory uses |
|---|---|
| Express.js / Fastify | iii HTTP Triggers |
| SQLite / Postgres + pgvector | iii KV State + in-memory vector index |
| SSE / Socket.io | iii Streams (WebSocket) |
| pm2 / systemd | iii engine worker supervision |
| Prometheus / Grafana | iii OTEL + health monitor |
| Custom plugin systems | `iii worker add <name>` |

**184 source files · ~42,200 LOC · 1,674 tests · 264 functions · 50 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.

---

<h2 id="configuration"></h2>

### LLM Providers

agentmemory auto-detects from your environment. By default, no LLM calls are made unless you configure a provider or explicitly opt in to the Claude subscription fallback.

| Provider | Config | Notes |
|----------|--------|-------|
| **No-op (default)** | No config needed | LLM-backed compress/summarize is DISABLED. Synthetic BM25 compression + recall still work. See `AGENTMEMORY_ALLOW_AGENT_SDK` below if you used to rely on the Claude-subscription fallback. |
| Anthropic API | `ANTHROPIC_API_KEY` | Per-token billing |
| MiniMax | `MINIMAX_API_KEY` | Anthropic-compatible |
| Gemini | `GEMINI_API_KEY` | Also enables embeddings |
| OpenRouter | `OPENROUTER_API_KEY` | Any model |
| OpenAI API | `OPENAI_API_KEY` | Default `gpt-5.6-luna`, override with `OPENAI_MODEL` |
| **Local (Ollama / LM Studio / vLLM / llama.cpp)** | `OPENAI_API_KEY=local` + `OPENAI_BASE_URL=http://localhost:11434/v1` (Ollama) or `http://localhost:1234/v1` (LM Studio) + `OPENAI_MODEL=<your model>` | Anything OpenAI-API-compatible. Zero cost, runs on your hardware. See [Local models](#local-models-ollama--lm-studio--vllm) below. |
| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions; it used to cause unbounded Stop-hook recursion, so it is no longer the default. |

### Local models (Ollama / LM Studio / vLLM)

agentmemory talks to any OpenAI-API-compatible server, so anything that exposes `/v1/chat/completions` works without code changes. No paid keys, no cloud, no rate limits; runs entirely on your hardware.

**Ollama** (default port `11434`):

```bash
ollama pull qwen3:8b   # or qwen3:4b, gpt-oss:20b, qwen3-coder:30b, etc.
ollama serve
```

```env
# ~/.agentmemory/.env
OPENAI_API_KEY=ollama                          # any non-empty string; Ollama ignores it
OPENAI_BASE_URL=http://localhost:11434/v1
OPENAI_MODEL=qwen3:8b
```

**LM Studio** (default port `1234`):

Open LM Studio → Local Server tab → Start Server. Pick any chat model from the picker (Qwen 3, gpt-oss, DeepSeek R1, etc.).

```env
# ~/.agentmemory/.env
OPENAI_API_KEY=lmstudio                        # any non-empty string; LM Studio ignores it
OPENAI_BASE_URL=http://localhost:1234/v1
OPENAI_MODEL=qwen3-8b                          # match the model name from LM Studio
```

**vLLM / llama.cpp / Text Generation Inference**: same shape. Point `OPENAI_BASE_URL` at whatever URL your server exposes and set `OPENAI_MODEL` to a name your server will accept.

**Model picks for memory work**: compression and summarization are short tasks (<2K tokens in, <500 tokens out) where a 7B instruct model is plenty. Recommendations:

| Model | Size | Why |
|-------|------|-----|
| `qwen3:8b` | ~5.2 GB | Balanced default on a 16 GB machine; strong at extraction and tool-shaped text |
| `qwen3:4b` | ~2.6 GB | Smallest sane option; fine for compression, weaker for graph extraction |
| `qwen3-coder:30b` | ~19 GB | Best local pick for code-shaped sessions (30B MoE, 3.3B active) on 24-32 GB hardware |
| `gpt-oss:20b` | ~14 GB | Strong general model that fits 16 GB RAM |
| `deepseek-r1:8b` | ~5.2 GB | Reasoning distill; slower but cleaner extractions |

Qwen 3 models think by default and can burn the whole token budget on reasoning before any output. Set `AGENTMEMORY_LLM_NOTHINK=1` to append `/no_think` to graph-extraction prompts, and raise `MAX_TOKENS` (16384 works) if extractions come back empty.

Reasoning-class models (`o1`-style with `` blocks) can return empty `content` with a `reasoning` field your local server may not surface. If extractions come back blank, switch to a non-reasoning model first. The `OPENAI_REASONING_EFFORT=none` env can also disable thinking on Ollama Cloud thinking models that mirror the OpenAI reasoning schema.

Local embeddings ship out of the box via `@huggingface/transformers`: `EMBEDDING_PROVIDER=local` (default) gives you `Xenova/all-MiniLM-L6-v2` (384-dim) entirely on-device. No extra config needed.

### Cost-aware model selection

Background compression runs on every observation, so model choice meaningfully changes monthly spend. Captured workload data: 635 requests / 888K tokens / 35 hours of active use, run against three OpenRouter models at 2026-05-23 pricing.

| Tier | Model | Input / 1M | Output / 1M | Cost for the captured 35h | Notes |
|------|-------|------------|-------------|---------------------------|-------|
| Recommended | `deepseek/deepseek-v4-flash-0731` | $0.07 | $0.14 | ~$0.07 (est.) | Latest DeepSeek; cheapest recommended pick for compression workloads. |
| Recommended | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Solid compression + summarization quality at ~10× lower cost than Sonnet. |
| Recommended | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Strong code reasoning if your sessions are heavily code-shaped. |
| Premium | `anthropic/claude-sonnet-5` | $3.00 | $15.00 | ~$5.02 (est.) | Same list price as the measured Sonnet 4.6 run; $2/$10 intro pricing through 2026-08-31. |
| Premium | `openai/gpt-5.6-sol` | $5.00 | $30.00 | ~$9 (est.) | Flagship tier; expensive for always-on background work. |
| Avoid | `anthropic/claude-opus-5` | $5.00 | $25.00 | ~$8.40 (est.) | Flagship-class model; overspend for compression. |

Measured rows come from the captured run; (est.) rows scale the same token mix by each model's list price.

agentmemory prints a runtime warning when `OPENROUTER_MODEL` matches a premium-tier pattern. Set `AGENTMEMORY_SUPPRESS_COST_WARNING=1` to silence once you've made an informed choice.

Quality vs cost tradeoff for memory work: compression is a summarization task with relatively loose quality bars (the agent re-reads the summary, not the user). DeepSeek V4 Flash / V4 Pro / Qwen3-Coder land within rounding error of Sonnet on this task while costing 10-70× less. Save the premium-tier models for queries you read directly.

Sources: [OpenRouter pricing for Claude Sonnet 5](https://openrouter.ai/anthropic/claude-sonnet-5), [DeepSeek V4 Flash](https://openrouter.ai/deepseek/deepseek-v4-flash-0731), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).

### Multi-agent memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)

In multi-agent setups where several roles share one agentmemory server (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` tags every write with the role that made it. `AGENTMEMORY_AGENT_SCOPE` controls whether recall filters by that tag.

```env
TEAM_ID=company
USER_ID=engineering-team
AGENT_ID=architect
AGENTMEMORY_AGENT_SCOPE=isolated  # optional; default "shared"
```

Two modes:

| Mode | Tag writes | Filter recall | When to use |
|------|------------|---------------|-------------|
| `shared` (default) | yes | no | Cross-agent context with audit trail. Architect can see what developer noted, but every row records who said it. |
| `isolated` | yes | yes | Strict separation. Architect never sees developer's observations / memories / sessions. |

What gets tagged when `AGENT_ID` is set: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. The role flows from `api::session::start` → `mem::observe` → `mem::compress` → KV.

What gets filtered in isolated mode: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Each endpoint accepts `?agentId=<role>` to override per-request, and `?agentId=*` to opt out of the env scope entirely. `/memories` also accepts `?includeOrphans=true` to surface pre-AGENT_ID memories whose `agentId` is undefined.

Per-call override at the SDK / REST layer: every mutating endpoint (`/session/start`, `/remember`) accepts an `agentId` field in the request body that wins over the env. Useful for runtimes routing many roles through one server process. The MCP `memory_save` tool exposes the same `agentId` field, the standalone stdio server forwards both `agentId` and `project`, and saved memories carry `agentId` into the search index, so agent-scoped search covers memories as well as observations.

When `AGENT_ID` is unset, memory remains unscoped (legacy behavior, no tags, no filters).

### Ports

agentmemory + iii-engine bind four ports by default. If a restart fails with `port in use`, this table tells you which process to look for.

| Port | Process | Purpose | Env override |
|------|---------|---------|--------------|
| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
| `3112` | iii-engine | Internal streams worker (consumed by agentmemory + viewer) | `III_STREAMS_PORT` |
| `3113` | agentmemory | Real-time viewer (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
| `49134` | iii-engine | WebSocket; workers register here, OTel telemetry flows over it | `III_ENGINE_URL` (full URL, default `ws://localhost:49134`) |

Stale-process cleanup when ports stay bound after a crashed run:

```bash
# macOS / Linux — find whatever is on each port and kill it
lsof -i :3111,3112,3113,49134
pkill -f agentmemory || true
pkill -f 'iii ' || true

# Windows
netstat -ano | findstr ":3111 :3112 :3113 :49134"
taskkill /F /PID 
```

`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful shutdown. In Docker mode it tears down only agentmemory's own compose services and reaps the native worker before the Docker teardown; the CLI also refuses to adopt or signal Docker or VM port holders (Docker backend, vpnkit, colima) as the native engine unless `--force` is passed. The manual cleanup above is only for the post-crash case where neither pidfile is left behind.

### Config File

Put agentmemory runtime configuration in `~/.agentmemory/.env` instead of exporting variables in every shell. If the viewer shows a setup hint like `export ANTHROPIC_API_KEY=...`, copy it into this file as `ANTHROPIC_API_KEY=...` without the `export` prefix, then restart agentmemory.

Process environment variables still work and take precedence over values in the file.

On Windows, the same file lives at `%USERPROFILE%\.agentmemory\.env`:

```powershell
New-Item -ItemType Directory -Force $HOME\.agentmemory
notepad $HOME\.agentmemory\.env
```

To test with a Claude Code Pro/Max subscription instead of an API key, opt in explicitly:

```env
AGENTMEMORY_ALLOW_AGENT_SDK=true
AGENTMEMORY_AUTO_COMPRESS=true
```

Consolidation (graph nodes, lessons, crystals) is on by default whenever an LLM provider is configured. Explicitly opt out with `CONSOLIDATION_ENABLED=false` if you want LLM-free operation. Graph extraction is a separate flag:

```env
GRAPH_EXTRACTION_ENABLED=true
# CONSOLIDATION_ENABLED=false   # opt out of auto-consolidation
```

### Environment Variables

Create `~/.agentmemory/.env`:

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

<h2 id="api"></h2>

130 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.


Key endpoints

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/agentmemory/health` | Health check (always public) |
| `POST` | `/agentmemory/session/start` | Start session + get context |
| `POST` | `/agentmemory/session/end` | End session |
| `POST` | `/agentmemory/observe` | Capture observation |
| `POST` | `/agentmemory/smart-search` | Hybrid search |
| `POST` | `/agentmemory/context` | Generate context |
| `POST` | `/agentmemory/remember` | Save to long-term memory |
| `POST` | `/agentmemory/forget` | Delete observations |
| `POST` | `/agentmemory/enrich` | File context + memories + bugs |
| `GET` | `/agentmemory/profile` | Project profile |
| `GET` | `/agentmemory/export` | Export all data |
| `POST` | `/agentmemory/import` | Import from JSON |
| `POST` | `/agentmemory/graph/query` | Knowledge graph query |
| `POST` | `/agentmemory/team/share` | Share with team |
| `GET` | `/agentmemory/audit` | Audit trail |

Full endpoint list: [`src/triggers/api.ts`](src/triggers/api.ts)



---

<h2 id="development"></h2>

```bash
npm run dev               # Hot reload
npm run build             # Production build
npm test                  # 1,674 tests
npm run test:integration  # API tests (requires running services)
```

**Prerequisites:** Node.js >= 20, [iii-engine](https://iii.dev/docs) or Docker

<h2 id="license"></h2>

[Apache-2.0](LICENSE)

---

## File: benchmark/README.md

# benchmark/

Two kinds of numbers live in this directory:

1. **Quality / retrieval** — `longmemeval-bench.ts`, `quality-eval.ts`,
   `real-embeddings-eval.ts`, `scale-eval.ts`. Recall, precision, token
   savings. Documented in `LONGMEMEVAL.md`, `QUALITY.md`,
   `REAL-EMBEDDINGS.md`, `SCALE.md`.

2. **Load shape** — `load-100k.ts`. p50 / p90 / p99 latency and
   throughput against a running daemon. This is the file you want when
   somebody asks "what's p99 at 100k memories under concurrency 100?".

## load-100k.ts

Hand-rolled, dependency-free load harness. Issues real HTTP against a
local agentmemory daemon at `http://localhost:3111`, records per-request
latency with `performance.now()`, and writes a JSON report per run.

### What it measures

For each cell in the matrix `(N, concurrency, endpoint)` it records:

- `p50_ms`, `p90_ms`, `p99_ms` — nearest-rank percentiles.
- `min_ms`, `max_ms`, `ops`, `errors`.
- `throughput_per_sec` — wall-clock ops / sec for that cell.

Default matrix:

- `N` ∈ {1000, 10000, 100000} — number of memories seeded before the
  cell runs.
- `C` ∈ {1, 10, 100} — concurrent in-flight requests during the cell.
- Endpoints under test:
  - `POST /agentmemory/remember`
  - `POST /agentmemory/smart-search`
  - `GET  /agentmemory/memories?latest=true`

Each cell issues `BENCH_OPS=200` requests by default — enough samples
for stable p99 without dragging a 100k-seed run past tens of minutes.

### Why p99 is the number that matters

p50 tells you the median request feels fast. p90 tells you the bulk of
requests feel fast. **p99 tells you the request your tail user hits when
they really need it feels fast.** Capacity planning lives here — if you
want to size a fleet, scale your daemon, or set an SLO, p99 is the
number to plan against. p50 will lie to you.

### Running it

```bash
# 1. Start the daemon however you normally do (npx, Docker, etc.)
npx @agentmemory/agentmemory

# 2. From the repo root, in another shell:
npm run bench:load
```

To override the matrix:

```bash
BENCH_N=1000 BENCH_C=1,10 BENCH_OPS=100 npm run bench:load
```

To have the harness spawn a daemon for the run (after `npm run build`):

```bash
AGENTMEMORY_BENCH_AUTOSTART=1 npm run bench:load
```

Other env knobs (see the file header for the canonical list):

- `AGENTMEMORY_URL` — base URL of the daemon (default
  `http://localhost:3111`).
- `BENCH_SEED` — seed for the `mulberry32` content RNG. Same seed +
  same daemon build = byte-identical seed corpus.
- `BENCH_OUT_DIR` — where the JSON report lands (default
  `benchmark/results/`).

### Where results land

`benchmark/results/load-100k-<short-git-sha>.json`. The harness
`mkdir -p`s the directory. The file has a `schema_version: 1` field so
future format changes don't silently break consumers.

### Content generation is seedable

Synthetic memory content is built from a small noun / verb / concept
vocabulary fed by a `mulberry32(BENCH_SEED)` PRNG. Same seed + same
build = same corpus. The point isn't "realistic" content (there isn't
one realistic content); the point is **reproducibility** — re-running
the harness against the same git sha should give the same content
mixture going in, so latency variance comes from the daemon and not
from JSON payload jitter.

### Publishing numbers per release

The release flow appends a `## Performance` section to `CHANGELOG.md`
referencing the JSON in `benchmark/results/` for that release's git
sha. p99 is the headline number; the JSON is the receipt.

---

## File: deploy/railway/README.md

# Deploy agentmemory on Railway

This template runs agentmemory on a single Railway service with a
persistent volume mounted at `/data`. The HMAC secret is generated on
first boot and persisted to the volume — you read it once from the
deploy logs and copy it into your client.

## What you get

- A public HTTPS endpoint serving the agentmemory REST API on port 3111
- A persistent Railway Volume at `/data` for memories, BM25 index, and
  stream backlog
- Railway healthcheck against `/agentmemory/livez`
- The HMAC bearer secret is generated on first boot inside the
  container and persisted to `/data/.hmac` (chmod 600); the operator
  copies it from the deploy logs once.
- The deploy uses `requiredMountPath: /data` so Railway refuses to
  start the service if no volume is attached at that path — first
  deploy must create the volume from the dashboard.

## Deploy via Railway dashboard

1. Click **Deploy from GitHub** in the Railway dashboard and pick the
   `rohitg00/agentmemory` repo.
2. Set the **Config-as-Code Path** under the service Settings to
   `deploy/railway/railway.json`. Railway picks up the Dockerfile path
   from there.
3. Open the service's **Volumes** tab and add a volume mounted at
   `/data` (Railway volumes are configured in the dashboard or via
   `railway volume add`, not in `railway.json`).
4. Click **Deploy**.

## Deploy via Railway CLI

```bash
# Install: https://docs.railway.com/guides/cli
railway login
railway init                                            # link a new project
railway up --service agentmemory                        # builds + deploys
railway volume add --service agentmemory --mount /data  # attach persistent volume
railway redeploy                                        # restart with the volume
```

## Capture the HMAC secret

After the first deploy succeeds, open the service's **Deploy Logs**:

```bash
railway logs --service agentmemory | grep AGENTMEMORY_SECRET=
```

You will see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`.
Copy it into your client environment. The secret is never printed again
on subsequent boots.

## Verify the deployment

```bash
curl https://<your-service>.up.railway.app/agentmemory/livez
# {"status":"ok"}
```

For an authenticated call, your client must send `Authorization: Bearer <secret>`.

## Viewer access (port 3113 stays internal)

Railway only exposes the single public port from your service's
`PORT` env var (which we map to 3111). The viewer stays bound to
localhost inside the container. `railway ssh` is an interactive shell
only — it does not support `-L`-style port forwarding, so reach the
viewer with one of the following.

**Quick in-container check:**

```bash
railway ssh --service agentmemory
# inside the container:
curl http://localhost:3113
```

**Browser session — option A (TCP Proxy, recommended):** in the Railway
dashboard, open the service's *Settings → Networking* tab and add a
**TCP Proxy** for container port `3113`. Railway returns a public
host/port pair you can hit directly from your browser. Pair it with the
HMAC bearer-auth header so the viewer is not anonymously reachable.

**Browser session — option B (in-container sshd):** add an `openssh-server`
process to the image and start it from `entrypoint.sh` on a fixed port,
expose that port through a second Railway TCP Proxy, then use a native
`ssh -L 3113:localhost:3113  -p ` from your laptop.
This is the heavier path; option A is what most users will want.

## Rotate the HMAC secret

```bash
railway ssh --service agentmemory
rm /data/.hmac
exit
railway redeploy --service agentmemory
railway logs --service agentmemory | grep AGENTMEMORY_SECRET=
```

Update every client with the new secret. Old tokens stop working
immediately.

## Back up `/data`

```bash
railway ssh --service agentmemory -- "tar czf - /data" > agentmemory-$(date +%Y%m%d).tar.gz
```

To restore on a fresh volume:

```bash
cat agentmemory-YYYYMMDD.tar.gz | railway ssh --service agentmemory -- "tar xzf - -C /"
railway redeploy --service agentmemory
```

## Cost floor and egress

- Hobby plan: $5/month flat, includes $5 of usage.
- agentmemory at idle plus a 1 GB volume typically uses $3–$6 of usage
  per month on the smallest instance, so most users stay near the $5
  floor.
- Egress: $0.10/GB after the bundled allowance.

See <https://railway.com/pricing> for the current rate card.

## Known caveats

- Railway volumes do not auto-snapshot. Take your own backups (above)
  or use the dashboard's manual snapshot feature.
- The Dockerfile builds on Railway's builder on every deploy. First
  deploy is ~2 minutes; cached layers make subsequent rebuilds quick.
  Pin `AGENTMEMORY_VERSION` / `III_VERSION` build args in the
  service's *Variables* tab to lock a specific release.

---

## File: deploy/fly/README.md

# Deploy agentmemory on fly.io

This template runs agentmemory on a single fly.io machine with a 1 GB
persistent volume mounted at `/data`. The HMAC secret is generated on
first boot and persisted to the volume — you capture it from the deploy
logs exactly once.

## What you get

- A public HTTPS endpoint serving the agentmemory REST API on port 3111
- A 1 GB Fly Volume at `/data` for memories, BM25 index, and stream backlog
- `auto_stop_machines = "stop"` and `min_machines_running = 0` — the
  machine sleeps when idle, so cost floor approaches $0 for low traffic
- HTTP healthcheck at `/agentmemory/livez` every 30 s
- The HMAC bearer secret is generated on first boot inside the
  container and persisted to `/data/.hmac` (chmod 600); the operator
  copies it from the deploy logs once.

## One-time setup

Pick a unique Fly app name first — `agentmemory` itself is likely taken.
Every command below references `$APP`, so set it once and the rest of the
flow stays consistent:

```bash
# 1. Install flyctl: https://fly.io/docs/flyctl/install/
# 2. Pick your unique app name (and matching volume name):
export APP="agentmemory-$(whoami)"     # or any other globally-unique name
export VOLUME="${APP//-/_}_data"       # Fly volume names can't contain '-'

# 3. From this directory:
fly launch --copy-config --no-deploy --name "$APP"

# 4. Create the volume in the same region as the app:
fly volumes create "$VOLUME" --region iad --size 1

# 5. Deploy:
fly deploy --app "$APP"
```

If `fly launch` reports the name is taken, pick another value for `$APP`,
re-export, and re-run.

## Capture the HMAC secret

Right after the first deploy succeeds:

```bash
fly logs --app "$APP" | grep -A1 AGENTMEMORY_SECRET=
```

You will see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`.
Copy it into your client environment (`~/.bashrc`, Claude Desktop config,
the viewer unlock prompt, etc.). The secret is never printed again on
subsequent boots.

If the first-boot log line is no longer available, read the persisted
secret from the mounted volume:

```bash
fly ssh console --app "$APP" -C "sh -lc 'cat /data/.hmac'"
```

## Verify the deployment

```bash
curl "https://$APP.fly.dev/agentmemory/livez"
# {"status":"ok"}
```

For an authenticated call, your client must send `Authorization: Bearer <secret>`.

## Viewer access (port 3113 stays internal)

The viewer port is intentionally not exposed publicly. Tunnel to it:

```bash
fly proxy 3113:3113 --app "$APP"
# then open http://localhost:3113
```

`fly proxy` opens an mTLS WireGuard channel to the machine, so the
viewer's bearer token still has to ride a loopback connection on your
laptop — the v0.9.12 plaintext-bearer guard stays satisfied.

The entrypoint sets `AGENTMEMORY_VIEWER_HOST=::` **only when it detects
Fly's runtime variables** (`FLY_APP_NAME` / `FLY_ALLOC_ID`). That makes
the viewer listen on the machine's `fly-local-6pn` WireGuard interface
as well as loopback so `fly proxy` can reach it. The same branch
pre-seeds `VIEWER_ALLOWED_HOSTS=localhost:3113,127.0.0.1:3113,[::1]:3113`,
which are the Host headers `fly proxy 3113:3113` actually emits on
your laptop.

When `AGENTMEMORY_VIEWER_HOST` is non-loopback the viewer enforces two
extra guards: it refuses to start unless `VIEWER_ALLOWED_HOSTS` is
explicitly set, and every request to `/agentmemory/*` must present
`Authorization: Bearer $AGENTMEMORY_SECRET`. Static HTML and the
favicon are still served unauthenticated. If a proxied viewer request
gets a 401, the browser UI prompts for `AGENTMEMORY_SECRET` and stores
it in session storage so subsequent viewer API calls include the bearer.
Use the value printed in the first-boot logs or read `/data/.hmac`
inside the machine.

> **Security warning.** Setting `AGENTMEMORY_VIEWER_HOST=0.0.0.0` or
> `::` turns the viewer into a network-reachable proxy that signs every
> upstream call with `AGENTMEMORY_SECRET`. Never enable that outside a
> network you trust (Fly's WireGuard mesh in this template), and never
> set it in a plain `docker run -p 3113:3113 …` on a shared host — the
> entrypoint deliberately skips the override when Fly env vars are
> absent so a plain Docker pull stays loopback-only.

## Rotate the HMAC secret

```bash
fly ssh console --app "$APP"
rm /data/.hmac
exit
fly machine restart <machine-id>
fly logs --app "$APP" | grep AGENTMEMORY_SECRET=
```

Update every client with the new secret. Old tokens stop working
immediately.

## Back up `/data`

```bash
fly ssh console --app "$APP" -C "tar czf - /data" > "$APP-$(date +%Y%m%d).tar.gz"
```

To restore on a fresh machine:

```bash
cat "$APP-YYYYMMDD.tar.gz" | fly ssh console --app "$APP" -C "tar xzf - -C /"
fly machine restart <machine-id>
```

## Cost floor and egress

- Idle (machine stopped): the volume costs ~$0.15/GB/month. A 1 GB
  volume is roughly $0.15/month.
- Active (machine running on `shared-cpu-1x` with 512 MB): about
  $1.94/month if it ran 24/7; in practice `auto_stop_machines` keeps
  that well under $1.
- Outbound bandwidth: 100 GB/month free on the Hobby plan, then $0.02/GB
  in North America / Europe.

See <https://fly.io/docs/about/pricing/> for the up-to-date rate card.

## Known caveats

- The volume lives in one region. To survive a region outage, create a
  second volume in another region and update `primary_region` after the
  failover, or take snapshots with `fly volumes snapshots create`.
- The Dockerfile builds in the Fly Builder on every deploy — first
  build is ~30 seconds; cached layers shrink rebuilds to under 10
  seconds. Image is ~114 MB.
- First deploy lands on a **shared IPv4 + dedicated IPv6** by default
  (free). If you need a dedicated IPv4 for legacy clients without SNI,
  run `fly ips allocate-v4 --app "$APP"` — costs $2/month.
- Cold-start (from machine launch to passing `/agentmemory/livez`) is
  ~9 seconds measured. `grace_period = "30s"` on the health check
  gives a 3x safety margin.
- Bump `AGENTMEMORY_VERSION` or `III_VERSION` in the Dockerfile to
  upgrade. `fly deploy --build-arg AGENTMEMORY_VERSION=<x>` also works
  for a one-off without editing the file.

---

## File: deploy/coolify/README.md

# Deploy agentmemory on Coolify

[Coolify](https://coolify.io/self-hosted) is an open-source, self-hosted
Heroku/Render alternative that you run on your own VPS. This template
deploys agentmemory as a Coolify *Application* backed by a Docker
Compose stack — Coolify handles TLS termination, persistent volume
provisioning, log aggregation, and the deploy webhook for you.

## What you get

- A public HTTPS endpoint serving the agentmemory REST API behind
  Coolify's built-in Traefik/Caddy proxy. The container port (`3111`)
  is exposed to the proxy network only — never bound to the host — so
  TLS termination and domain routing stay under proxy control.
- A persistent Docker volume backing `/data` for memories, BM25 index,
  and stream backlog. Coolify auto-prefixes the volume name with the
  application's UUID so the data survives redeploys.
- An HTTP health-check at `/agentmemory/livez` declared in the
  Dockerfile (`HEALTHCHECK` directive). Coolify reuses it for
  rolling-deploy decisions.

## One-time setup

1. **Open your Coolify dashboard** and click **+ New → Application**.
2. **Source**: pick *Public Repository*. Paste:
   ```
   https://github.com/rohitg00/agentmemory
   ```
   Branch: `main`.
3. **Build Pack**: select *Docker Compose*.
4. **Base Directory**: `deploy/coolify`
5. **Compose Path**: `docker-compose.yml`
6. Click **Save**, then on the application settings screen set a
   **Domain** in the form `https://<your-fqdn>:3111` (the `:3111`
   suffix tells Coolify's proxy which container port to forward to;
   it still serves over 443/80 publicly).
7. Click **Deploy**.

That's it. Coolify clones the repo, builds the Dockerfile under
`deploy/coolify/`, provisions the `agentmemory-data` named volume on
the host, attaches Traefik (or Caddy) for the public domain, and starts
the service. The container is reachable only through the proxy — there
is no published host port.

## Capture the HMAC secret

Once the deploy logs show the service is up, open the application's
**Logs** tab in Coolify and search for `AGENTMEMORY_SECRET=`. You will
see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`.
Copy it into your client environment (`~/.bashrc`, Claude Desktop
config, etc.). The secret is never printed again on subsequent boots.

## Verify the deployment

```bash
curl "https://<your-coolify-domain>/agentmemory/livez"
# {"status":"ok"}
```

For an authenticated call, your client must send
`Authorization: Bearer <secret>`.

## Viewer access (port 3113 stays internal)

The viewer port is not exposed by the compose file on purpose — it
holds the unauthenticated admin surface in older releases and the
proxied surface in current ones, neither of which belongs on the open
internet. Two paths to reach it:

**Option A — SSH tunnel from the Coolify host.** Coolify gives you SSH
access to the underlying VPS. From your laptop:

```bash
ssh -L 3113:127.0.0.1:3113 @<coolify-host>
# inside the SSH session, find the container:
docker ps --filter name=agentmemory --format "{{.Names}}"
# tunnel into the container's port from the host:
docker exec -it <container-name> sh -c "curl http://localhost:3113"
```

Cleaner version: bind the container's 3113 to the host's loopback by
adding `- "127.0.0.1:3113:3113"` to the `ports:` block in
`docker-compose.yml`, redeploy, then `ssh -L 3113:127.0.0.1:3113
@<host>` is enough.

**Option B — expose 3113 as a second Coolify domain protected by HTTP
basic auth.** Coolify's per-service routing supports adding a second
public endpoint with basic-auth middleware. Useful if you want to
share the viewer with a teammate without giving them SSH.

## Rotate the HMAC secret

```bash
ssh @<coolify-host>
docker exec -it <container-name> sh -c "rm /data/.hmac"
exit
```

Then click **Redeploy** in the Coolify dashboard. The next boot prints
a fresh secret to the logs.

## Back up `/data`

Coolify exposes the named volume on the host filesystem under
`/var/lib/docker/volumes/_agentmemory-data/_data`. Back it
up with your existing host-level snapshot tooling (Restic, Borg,
`rsync`, BTRFS snapshots, etc.) or via Coolify's built-in *Backups*
feature for Docker volumes.

## Cost floor and resources

- **Hardware**: the agentmemory container idles at ~150 MB RSS, climbs
  to ~400 MB under steady traffic. The bundled iii engine adds another
  ~80 MB. A 1 vCPU / 1 GB VPS is comfortably enough for a personal
  install.
- **VPS providers commonly paired with Coolify**: Hetzner CX22
  (~€3.79/month), DigitalOcean Basic Droplet ($6/month), Vultr Cloud
  Compute ($6/month). Coolify itself is free.
- **Volume storage**: tied to whatever block storage the VPS provides;
  typically pennies per GB-month.

## Known caveats

- The Dockerfile builds on the Coolify host on every deploy. First
  deploy takes ~2 minutes; cached layers shrink subsequent rebuilds to
  under 30 seconds. Pin `AGENTMEMORY_VERSION` and `III_VERSION` in
  `docker-compose.yml`'s `build.args` block to lock a specific release.
- Coolify's *Persistent Storage* tab will show `agentmemory-data` as a
  managed volume — do not delete it from the dashboard if you want
  your memories to survive a redeploy.
- arm64 hosts work — the iii binary selection in the Dockerfile uses
  `uname -m` and downloads the matching tarball.

---

## File: deploy/render/README.md

# Deploy agentmemory on Render

This template runs agentmemory on a single Render Web Service with a
persistent disk mounted at `/data`. The HMAC secret is generated on
first boot and persisted to the disk — you capture it from the deploy
logs exactly once.

## What you get

- A public HTTPS endpoint serving the agentmemory REST API on port 3111
  (Render injects `PORT` defaulting to 10000; we override it to 3111
  via `envVars` so the published port matches the container's bind)
- A 1 GB persistent disk at `/data` for memories, BM25 index, and
  stream backlog
- Render healthcheck against `/agentmemory/livez`
- The HMAC bearer secret is generated on first boot inside the
  container and persisted to `/data/.hmac` (chmod 600); the operator
  copies it from the deploy logs once.

## Deploy via Render Blueprint

Render's one-click deploy button only auto-detects `render.yaml` at the
repository root, which the agentmemory repo keeps clean. Use the
dashboard's manual Blueprint flow instead:

1. Push the `deploy/render/` directory to a Git provider Render can
   reach (a fork of `rohitg00/agentmemory` works).
2. In the Render dashboard, click **New +** → **Blueprint**.
3. Point Render at the repo and the path `deploy/render/render.yaml`.
4. Render reads the Blueprint, provisions the disk, builds the
   Dockerfile, and starts the service. The whole flow takes 3–5
   minutes on the first run.

## Deploy via Render Deploy Hook (one-click)

Once the Blueprint exists in your account, generate a Deploy Hook URL
in the service settings. Future deploys are a single curl call:

```bash
curl "https://api.render.com/deploy/srv-XXYYZZ?key=AABBCC"
```

To pin a specific `@agentmemory/agentmemory` release, set the
`AGENTMEMORY_VERSION` build arg in the service's *Environment* tab
before the next deploy. Same for `III_VERSION`.

## Capture the HMAC secret

After the first deploy succeeds, open the service's **Logs** tab and
search for `AGENTMEMORY_SECRET=`. You will see exactly one line of the
form `AGENTMEMORY_SECRET=<64 hex chars>`. Copy it into your client
environment. The secret is never printed again on subsequent boots.

## Verify the deployment

```bash
curl https://agentmemory.onrender.com/agentmemory/livez
# {"status":"ok"}
```

For an authenticated call, your client must send `Authorization: Bearer <secret>`.

## Viewer access (port 3113 stays internal)

Render only exposes one public port per service, and we use it for
3111. The viewer port stays bound to localhost inside the container.
Reach it via Render's SSH:

```bash
# Settings → SSH → enable for your service, copy the connection command
ssh srv-XXYYZZ@ssh.<region>.render.com -L 3113:localhost:3113
# now http://localhost:3113 in your browser hits the in-container viewer
```

## Rotate the HMAC secret

```bash
ssh srv-XXYYZZ@ssh.<region>.render.com
rm /data/.hmac
exit
# trigger a redeploy from the Render dashboard or via the Deploy Hook
```

After the redeploy, grab the new secret from the logs and update every
client. Old tokens stop working immediately.

## Back up `/data`

```bash
ssh srv-XXYYZZ@ssh.<region>.render.com "tar czf - /data" > agentmemory-$(date +%Y%m%d).tar.gz
```

Render also takes daily snapshots of persistent disks automatically on
paid plans — the SSH tarball is a belt-and-braces option you can ship
off-platform.

## Cost floor and egress

- Starter plan web service: $7/month (0.5 CPU, 512 MB RAM).
- 1 GB persistent disk: $0.25/GB/month, so $0.25/month for the default.
- Bandwidth: 100 GB outbound included, then $0.10/GB.

See <https://render.com/pricing> for the current rate card.

## Known caveats

- Render Free tier does not support persistent disks. The Starter plan
  ($7/month) is the minimum.
- Render restarts the service on every deploy. The HMAC secret survives
  because it lives on the disk, but expect a 10–30 s gap of 502s
  during rollouts.
- Render runs amd64 only for web services. The Dockerfile selects the
  matching iii binary automatically via `uname -m`.

---

## File: deploy/README.md

# One-click deploy templates

Stand up agentmemory on managed infrastructure without rolling your own
Docker host. Each template ships a self-contained Dockerfile that pulls
`@agentmemory/agentmemory` from npm at build time and copies the iii
engine binary in from the official `iiidev/iii` image — no pre-built
agentmemory image required. Storage mounts at `/data`; an HMAC secret
is generated by the first-boot entrypoint and persisted to the volume.
The entrypoint overwrites the npm-bundled iii config with a
deploy-tuned one that binds `0.0.0.0` and uses absolute `/data` paths,
then drops privileges from `root` to `node` via `gosu` before
exec'ing the agentmemory CLI.

| Platform | Pitch | Cost floor |
|----------|-------|------------|
| [fly.io](./fly/README.md) | Single machine with auto-stop. Cheapest idle cost on a managed host; cold-start on first request after sleep. | ~$0.15/month at full idle |
| [Railway](./railway/README.md) | Push from GitHub, volume in the dashboard. Easiest managed dashboard flow. | $5/month (Hobby plan flat fee) |
| [Render](./render/README.md) | Blueprint-driven; persistent disk attaches automatically. Most "set it and forget it." | $7.25/month (Starter web + 1 GB disk) |
| [Coolify](./coolify/README.md) | Self-hosted on your own VPS. Same Docker Compose stack, you own the host and the data. | VPS cost only (Hetzner CX22 ~€3.79/month) |

## What every template guarantees

- **Volume mounted at `/data`.** Matches the path the engine has used
  since v0.9.10.
- **HMAC secret generated on first boot** via `openssl rand -hex 32`,
  written to `/data/.hmac` with `chmod 600`, and printed to stdout
  exactly once so the operator can capture it from the deploy logs.
  Subsequent boots load the secret from the file. The secret is never
  committed to a config file or set as a platform env var.
- **Only port 3111 is exposed publicly.** The viewer on port 3113
  stays bound to the container's localhost. Reach it via SSH tunnel
  (see each platform's README).
- **TLS upstream of the container.** Every managed platform terminates
  TLS at its edge proxy; the templates publish a single internal port
  (`3111`) to that proxy, never to the host. Integration plugins
  configured with `AGENTMEMORY_REQUIRE_HTTPS=1` will refuse to send the
  bearer over plaintext HTTP to a non-loopback host, so a
  misconfigured TLS layer fails loud instead of silently leaking the
  secret.

## Pick a platform

- Pick **fly.io** if you want the lowest idle cost and don't mind a
  cold-start latency hit on the first request after sleep.
- Pick **Railway** if you want a clicky dashboard flow and a flat
  monthly bill.
- Pick **Render** if you want the most "set it and forget it"
  Blueprint flow with automatic disk snapshots on paid plans.
- Pick **Coolify** if you already run a VPS and want a self-hosted
  control plane — same Docker Compose stack, no third-party host has
  your memories.

All four give you the same agentmemory API at the same port (3111)
with the same auth model. Migrating between them later is a `tar` of
`/data` and a re-import — see each platform's README for the exact
commands.

## Optional: LLM + embedding provider keys

Every template runs out of the box without any LLM or embedding key —
search falls back to BM25-only mode and synthetic (zero-LLM)
compression keeps memories indexable. To unlock LLM-powered
compression and hybrid (BM25 + vector) recall, add one of the
following to your platform's environment variables (Fly:
`flyctl secrets set`; Railway / Render / Coolify: dashboard
*Variables / Environment* tab):

| Variable                  | Purpose                                                  |
|---------------------------|----------------------------------------------------------|
| `ANTHROPIC_API_KEY`       | LLM-backed compression + summarization                   |
| `GEMINI_API_KEY`          | LLM provider alternative                                 |
| `OPENROUTER_API_KEY`      | LLM provider alternative                                 |
| `OPENAI_API_KEY`          | Embedding provider (text-embedding-3-small by default)   |
| `VOYAGE_API_KEY`          | Embedding provider alternative                           |
| `AGENTMEMORY_AUTO_COMPRESS=true` | Run LLM compression on every observation batch    |
| `AGENTMEMORY_INJECT_CONTEXT=true` | Inject recalled memories back into agent prompts |

The defaults are intentionally conservative: provider keys default to
absent (no third-party calls), `AGENTMEMORY_AUTO_COMPRESS` is off,
and `AGENTMEMORY_INJECT_CONTEXT` is off. Opt in only after you've
confirmed your provider quota can absorb the workload.

## Cold-start budget

Measured against fly.io's `iad` region with a 1 GB volume:

```
machine image prepared :  5.1 s
volume mount + format  :  2.5 s
firecracker boot       :  1.0 s
entrypoint + chown     :  0.5 s
iii-engine ready       :  3.0 s
agentmemory worker reg :  2.0 s
─────────────────────────────────
healthcheck passes     : ~9-10 s
```

Every template's health-check `grace_period` (or compose
`start_period`) is set to 30 s for a 3x safety margin. Tune lower
once you've measured your own platform's image-pull characteristics.

---

## File: examples/python/README.md

# Python usage via `iii-sdk`

agentmemory registers its core operations as iii functions (`mem::remember`,
`mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Any
language with an iii SDK can call them directly over the WebSocket transport
on `ws://localhost:49134` — no separate REST client needed.

This example uses the official Python SDK.

## Install

```bash
pip install iii-sdk
```

## Quickstart

Start the agentmemory daemon (defaults to `ws://localhost:49134`, REST on
`:3111`):

```bash
npx -y @agentmemory/agentmemory
```

Then from Python:

```python
from iii import register_worker

iii = register_worker("ws://localhost:49134")
iii.connect()

iii.trigger({
    "function_id": "mem::remember",
    "payload": {
        "project": "demo",
        "title": "auth-stack",
        "content": "Service uses HMAC bearer tokens; refresh every 24h.",
        "concepts": ["auth", "hmac", "refresh"],
    },
})

hits = iii.trigger({
    "function_id": "mem::smart-search",
    "payload": {"project": "demo", "query": "how do tokens refresh", "limit": 5},
})
print(hits)
```

## Functions exposed

| Function id | Purpose | Required payload |
|---|---|---|
| `mem::remember` | Save a memory | `project`, `title`, `content` |
| `mem::observe` | Hook-driven observation ingest | `hookType`, `sessionId`, `project`, `cwd`, `timestamp` |
| `mem::context` | Render context for a session under a token budget | `sessionId`, `project`, optional `budget` |
| `mem::smart-search` | Hybrid BM25 + vector + concept recall | `project`, `query`, optional `limit` |
| `mem::forget` | Delete a memory by id | `id` |

The HTTP-trigger wrappers under `api::*` (callable via REST on `:3111`) exist
for the same operations if you need to reach the daemon from a host without an
iii runtime. Inside the iii ecosystem, calling the `mem::*` functions directly
is lower latency.

## Files

- `quickstart.py` — minimal save-then-search loop.
- `observe_and_recall.py` — observation ingest + context rendering at a token
  budget.

Both scripts assume the daemon is already running.

---

## File: integrations/pi/README.md

<h1 align="center">
  &nbsp;agentmemory for pi
</h1>



---

## Quick setup

Start the agentmemory server in a separate terminal:

```bash
npx @agentmemory/agentmemory
```

Copy this folder into pi's global extensions directory:

```bash
mkdir -p ~/.pi/agent/extensions/agentmemory
cp integrations/pi/index.ts ~/.pi/agent/extensions/agentmemory/index.ts
```

Then enable it in `~/.pi/agent/settings.json` if you prefer explicit loading:

```json
{
  "extensions": ["~/.pi/agent/extensions/agentmemory"]
}
```

If you place it under `~/.pi/agent/extensions/agentmemory/`, pi will also auto-discover it and `/reload` can hot-reload it.

## What it adds

- `memory_health` — confirm the shared memory server is reachable
- `memory_search` — search prior decisions, bugs, workflows, and preferences
- `memory_save` — write durable facts back to long-term memory
- `/agentmemory-status` — check health from inside pi
- `before_agent_start` recall — injects relevant memories into the prompt
- `agent_end` capture — saves completed conversation turns back to agentmemory

## Environment variables

| Variable | Default | Description |
|---|---|---|
| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL |
| `AGENTMEMORY_SECRET` | (none) | Bearer token for protected instances |
| `AGENTMEMORY_REQUIRE_HTTPS` | (off) | When set to `1`, refuse to send a bearer token over plaintext HTTP to a non-loopback host. Sends the token only when `AGENTMEMORY_URL` is `https://...` or points at `localhost`/`127.0.0.1`/`::1`. With this off, the plugin warns once but still sends. |

## Smoke test

Run pi and ask it to use the `memory_health` tool, or call the command directly:

```text
/agentmemory-status
```

You should see `agentmemory healthy` and a footer status like `🧠 agentmemory`.

## Notes

- This extension uses pi's extension API, not MCP, so it can hook directly into the agent lifecycle.
- One local agentmemory server can be shared across pi, pi2, Hermes, OpenClaw, Claude Code, Codex CLI, and Gemini CLI.

## See also

- [agentmemory main README](../../README.md)
- [Hermes integration](../hermes/README.md)
- [OpenClaw integration](../openclaw/README.md)

---

## File: integrations/openclaw/README.md

<h1 align="center">
  
  &nbsp;agentmemory for OpenClaw
</h1>





---

## Install it in 30 seconds

**Paste this prompt into OpenClaw** and it does the whole setup for you:

```text
Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111.

For zero-code setup, add this MCP server so OpenClaw gets all 43 memory tools:

{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"]
    }
  }
}

For deeper memory integration, copy `integrations/openclaw` from the agentmemory repo to `~/.openclaw/extensions/agentmemory`, then enable it in `~/.openclaw/openclaw.json`:

{
  "plugins": {
    "slots": {
      "memory": "agentmemory"
    },
    "entries": {
      "agentmemory": {
        "enabled": true,
        "config": {
          "base_url": "http://localhost:3111",
          "token_budget": 2000,
          "min_confidence": 0.5,
          "fallback_on_error": true,
          "timeout_ms": 5000
        }
      }
    }
  }
}

Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer.
```

That's it. OpenClaw handles the rest.

## Option 1: MCP server (zero code)

Start the agentmemory server in a separate terminal:

```bash
npx @agentmemory/agentmemory
```

Then add to your OpenClaw MCP config:

```json
{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"]
    }
  }
}
```

OpenClaw now has access to all 43 MCP tools including `memory_recall`, `memory_save`, `memory_smart_search`, `memory_timeline`, `memory_profile`, and more.

## Option 2: OpenClaw memory plugin (deeper integration)

Copy this folder into OpenClaw's extension directory:

```bash
mkdir -p ~/.openclaw/extensions
cp -r integrations/openclaw ~/.openclaw/extensions/agentmemory
```

Then enable it in `~/.openclaw/openclaw.json`:

```json
{
  "plugins": {
    "slots": {
      "memory": "agentmemory"
    },
    "entries": {
      "agentmemory": {
        "enabled": true,
        "config": {
          "base_url": "http://localhost:3111",
          "token_budget": 2000,
          "min_confidence": 0.5,
          "fallback_on_error": true,
          "timeout_ms": 5000
        }
      }
    }
  }
}
```

What the plugin does:

- claims the `plugins.slots.memory = "agentmemory"` slot via `api.registerMemoryCapability({ promptBuilder })` so OpenClaw recognises it as the active memory plugin
- recalls relevant long-term memory before the agent starts (via the `before_agent_start` hook)
- captures completed conversation turns after the agent finishes (via the `agent_end` hook)

OpenClaw blocks conversation-reading hooks from non-bundled plugins by default. Allow it once in `openclaw.json` so turn capture works:

```json
{
  "plugins": {
    "allow": ["agentmemory"],
    "entries": { "agentmemory": { "hooks": { "allowConversationAccess": true } } }
  }
}
```
- shares the same backend with Claude Code, Codex CLI, Gemini CLI, Hermes, pi, and other agents

### Memory runtime (current scope)

The plugin currently registers a `promptBuilder` only — not a full `MemoryPluginRuntime` adapter. OpenClaw's `MemoryRuntimeBackendConfig` type today is `{ backend: "builtin" }` or `{ backend: "qmd" }`; both are openclaw-internal backends that don't fit agentmemory's external REST shape. The hook-driven recall + capture flow above is the working integration path. If you need OpenClaw's in-process memory-runtime APIs (e.g. `getMemorySearchManager`) backed by agentmemory, file an upstream request against `openclaw` for an `"external"` backend type and we'll wire `runtime` here once the contract supports it.

## Troubleshooting

**Plugin validates but does not load** — make sure the folder contains `package.json`, `openclaw.plugin.json`, and `plugin.mjs`, and that `plugins.slots.memory` is set to `agentmemory`.

**`plugins.slots.memory = "agentmemory"` reports `unavailable`** — upgrade to v0.9.11+. Older versions of this plugin registered hooks but never called `api.registerMemoryCapability(...)`, so the memory-slot machinery did not consider the slot claimed. The current plugin registers a memory capability (prompt builder) at startup, which is the documented OpenClaw API for occupying the slot.

**Connection refused on port 3111** — the agentmemory server is not running. Start it with `npx @agentmemory/agentmemory`.

**No memories returned** — open `http://localhost:3113` and verify observations are being captured.

## See also

- [agentmemory main README](../../README.md)
- [Hermes integration](../hermes/README.md)
- [pi integration](../pi/README.md)

## License

Apache-2.0 (same as agentmemory)

## 2. Official Technical Reference & Guides (rohitg00/docs)

# Mintlify Starter Kit

Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including

- Guide pages
- Navigation
- Customizations
- API Reference pages
- Use of popular components

### Development

Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command

```
npm i mintlify
```

Run the following command at the root of your documentation (where mint.json is)

```
mintlify dev
```

### Publishing Changes

Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. 

#### Troubleshooting

- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies.
- Page loads as a 404 - Make sure you are running in a folder with `mint.json`