@@ -181,6 +196,11 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agen
Roo Code MCP server
+
+
+Warp
+connect + MCP + skills
+
@@ -413,7 +433,7 @@ Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cl
### 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, 8 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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.
```
@@ -464,7 +484,7 @@ This adds an idempotent block to `~/.codex/hooks.json` referencing absolute path
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 53 memory tools:
{
@@ -489,7 +509,7 @@ 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 53 memory tools:
mcp_servers:
@@ -543,6 +563,7 @@ The agentmemory entry is the **same MCP server block** across every host that us
| **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. |
| **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. |
| **Goose** | Goose MCP settings UI | Same `mcpServers` block. |
| **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. |
@@ -687,7 +708,7 @@ SSH-tunnel pattern for reaching it.
Every coding agent forgets everything when the session ends. You waste the first 5 minutes of every session re-explaining your stack. agentmemory runs in the background and eliminates that entirely.
-```
+```text
Session 1: "Add auth to the API"
Agent writes code, runs tests, fixes bugs
agentmemory silently captures every tool use
@@ -720,7 +741,7 @@ Every AI coding agent ships with built-in memory — Claude Code has `MEMORY.md`
### Memory Pipeline
-```
+```text
PostToolUse hook fires
-> SHA-256 dedup (5min window)
-> Privacy filter (strip secrets, API keys)
diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md
new file mode 100644
index 0000000000..1dc2b525c9
--- /dev/null
+++ b/READMEs/README.de-DE.md
@@ -0,0 +1,1377 @@
+
+
+
+
+
+
+ Ihr Coding-Agent merkt sich alles. Schluss mit dem ständigen Wiederholen.
+ Built on iii engine
+
+ Persistentes Gedächtnis für Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode und jeden MCP-Client.
+
+ Das Gist erweitert Karpathys LLM-Wiki-Muster um Confidence Scoring, Lifecycle, Knowledge Graphs und hybride Suche: agentmemory ist die Implementierung.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+Oder per `npx` (keine Installation):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Achtung — npx cached pro Version. Wenn ein nacktes `npx @agentmemory/agentmemory` eine ältere Version liefert, erzwingen Sie die neueste mit `npx -y @agentmemory/agentmemory@latest` oder leeren Sie den Cache einmalig mit `rm -rf ~/.npm/_npx` (macOS/Linux; unter Windows löschen Sie `%LOCALAPPDATA%\npm-cache\_npx`). Der erste npx-Lauf ab v0.9.16+ fordert eine globale Installation inline an, sodass der nackte Befehl `agentmemory` anschließend überall funktioniert.
+
+Vollständige Optionen unter [Schnellstart](#quick-start). Agentenspezifische Verdrahtung unter [Funktioniert mit jedem Agenten](#works-with-every-agent).
+
+---
+
+
+
+agentmemory funktioniert mit jedem Agenten, der Hooks, MCP oder REST API unterstützt. Alle Agenten teilen sich denselben Memory-Server.
+
+
+
+
+
+Claude Code
+natives Plugin + 12 Hooks + MCP
+
+
+
+Codex CLI
+natives Plugin + 6 Hooks + MCP
+
+
+
+OpenClaw
+natives Plugin + MCP
+
+
+
+Hermes
+natives Plugin + MCP
+
+
+
+pi
+natives Plugin + MCP
+
+
+
+OpenHuman
+natives Memory-trait-Backend
+
+
+
+Cursor
+MCP-Server
+
+
+
+Gemini CLI
+MCP-Server
+
+
+
+
+
+OpenCode
+22 Hooks + MCP + Plugin
+
+
+
+Cline
+MCP-Server
+
+
+
+Goose
+MCP-Server
+
+
+
+Kilo Code
+MCP-Server
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP-Server
+
+
+
+Windsurf
+MCP-Server
+
+
+
+Roo Code
+MCP-Server
+
+
+
+
+
+ Funktioniert mit jedem Agenten, der MCP oder HTTP spricht. Ein Server, gemeinsame Erinnerungen für alle.
+
+
+---
+
+Sie erklären in jeder Session dieselbe Architektur. Sie entdecken dieselben Bugs erneut. Sie bringen dem Agenten dieselben Präferenzen wieder bei. Eingebautes Gedächtnis (CLAUDE.md, .cursorrules) ist bei 200 Zeilen am Ende und veraltet. agentmemory behebt das. Es erfasst stillschweigend, was Ihr Agent tut, komprimiert das Ganze in durchsuchbares Gedächtnis und injiziert beim Start der nächsten Session den passenden Kontext. Ein Befehl. Funktioniert über Agenten hinweg.
+
+**Was sich ändert:** Session 1 richten Sie JWT-Authentifizierung ein. Session 2 fragen Sie nach Rate Limiting. Der Agent weiß bereits, dass Ihre Auth jose-Middleware in `src/middleware/auth.ts` verwendet, dass Ihre Tests Token-Validierung abdecken und dass Sie sich aus Gründen der Edge-Kompatibilität für jose statt jsonwebtoken entschieden haben. Kein Wiederholen. Kein Copy-Paste. Der Agent *weiß es einfach*.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **Neu in v0.9.0** — Landing-Site unter [agent-memory.dev](https://agent-memory.dev), Filesystem-Connector (`@agentmemory/fs-watcher`), das standalone MCP proxyt nun zum laufenden Server, sodass Hooks und Viewer übereinstimmen, Audit-Policy auf jedem Delete-Pfad kodifiziert, der Health-Check meldet `memory_critical` nicht mehr bei kleinen Node-Prozessen. Vollständige Hinweise in [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18).
+
+---
+
+
+
+> Embedding-Modell: `all-MiniLM-L6-v2` (lokal, kostenlos, kein API-Schlüssel). Vollständige Berichte: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Konkurrenzvergleich: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory vs mem0, Letta, Khoj, claude-mem, Hippo.
+
+**Lokal reproduzieren:** [`eval/README.md`](../eval/README.md) — Adapter-pluggable Harness für LongMemEval `_s` (öffentlich, 500 Fragen) + `coding-agent-life-v1` (interner 15-Session-Korpus). Adapter für grep / vector / agentmemory werden direkt verglichen, NDJSON-Ausgabe, veröffentlichte Scorecards landen in [`docs/benchmarks/`](../docs/benchmarks/).
+
+**Funktioniert kombiniert mit [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) und [Graphify](https://github.com/safishamsi/graphify).** Code-Graph-Indizierung, mehragentige Build-Pipelines und breitere Knowledge Graphs über Docs / PDFs / Bilder / Videos. agentmemory merkt sich die Arbeit; diese drei Projekte beleuchten den Rest der Kontextschicht. Rezepte + Frage-Routing-Tabelle: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
Eingebaut (CLAUDE.md)
+
+
+
Typ
+
Memory-Engine + MCP-Server
+
Memory-Layer-API
+
Komplette Agenten-Runtime
+
Statische Datei
+
+
+
Retrieval R@5
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
N/V (grep)
+
+
+
Auto-Erfassung
+
12 Hooks (null manueller Aufwand)
+
Manuelle add()-Aufrufe
+
Agent bearbeitet sich selbst
+
Manuelle Bearbeitung
+
+
+
Suche
+
BM25 + Vector + Graph (RRF-Fusion)
+
Vector + Graph
+
Vector (Archival)
+
Lädt alles in den Kontext
+
+
+
Multi-Agent
+
MCP + REST + Leases + Signals
+
API (keine Koordination)
+
Nur innerhalb der Letta-Runtime
+
Dateien pro Agent
+
+
+
Framework-Lock-in
+
Keiner (jeder MCP-Client)
+
Keiner
+
Hoch (Letta erforderlich)
+
Format pro Agent
+
+
+
Externe Abhängigkeiten
+
Keine (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + Vector-DB
+
Keine
+
+
+
Memory-Lifecycle
+
4-stufige Konsolidierung + Decay + Auto-Forget
+
Passive Extraktion
+
Vom Agenten verwaltet
+
Manuelles Pruning
+
+
+
Token-Effizienz
+
~1.900 Tokens/Session (10 $/Jahr)
+
Je nach Integration unterschiedlich
+
Core Memory im Kontext
+
22K+ Tokens bei 240 Beobachtungen
+
+
+
Echtzeit-Viewer
+
Ja (Port 3113)
+
Cloud-Dashboard
+
Cloud-Dashboard
+
Nein
+
+
+
Self-hosted
+
Ja (Standard)
+
Optional
+
Optional
+
Ja
+
+
+
+---
+
+
+
+Kompatibilität: Diese Version zielt auf stabiles `iii-sdk` `^0.11.0` und iii-engine v0.11.x ab.
+
+### In 30 Sekunden ausprobieren
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo` befüllt 3 realistische Sessions (JWT-Auth, N+1-Query-Fix, Rate Limiting) und führt semantische Suchen darauf aus. Sie sehen, wie „N+1 query fix" gefunden wird, wenn Sie nach „database performance optimization" suchen — Keyword-Matching kann das nicht.
+
+Öffnen Sie `http://localhost:3113`, um das Memory in Echtzeit aufgebaut zu sehen.
+
+### Empfohlen: global installieren
+
+`npx` cached pro Version. Wenn Sie letzte Woche `npx @agentmemory/agentmemory@0.9.14` ausgeführt haben, kann ein nacktes `npx @agentmemory/agentmemory` das veraltete 0.9.14 aus `~/.npm/_npx/` ausliefern und nicht die neueste Version. Einmal installieren, und der nackte Befehl `agentmemory` funktioniert überall:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+Ab v0.9.16 fordert der erste npx-Lauf inline zu einer globalen Installation auf — einmal mit `Y` antworten, fertig. Wenn Sie das überspringen, greifen Sie für einen frischen Fetch auf eine dieser Möglichkeiten zurück:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+Unter Windows / PowerShell lautet das Äquivalent zum Leeren des Caches `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — die plattformübergreifende Option ist `npx -y ...@latest` oben.
+
+### Session-Replay
+
+Jede Session, die agentmemory aufzeichnet, ist abspielbar. Öffnen Sie den Viewer, wählen Sie den Reiter **Replay** und scrubben Sie durch die Timeline: Prompts, Tool-Aufrufe, Tool-Ergebnisse und Antworten werden als diskrete Events mit Play/Pause, Geschwindigkeitssteuerung (0,5×–4×) und Tastenkürzeln (Leertaste zum Umschalten, Pfeile zum Schrittweisen) gerendert.
+
+Haben Sie ältere Claude-Code-JSONL-Transkripte, die Sie übernehmen wollen?
+
+```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
+```
+
+Importierte Sessions tauchen im Replay-Picker neben den nativen auf. Intern routet jeder Eintrag durch die iii-Funktionen `mem::replay::load`, `mem::replay::sessions` und `mem::replay::import-jsonl` — keine Seitenkanal-Server.
+
+### Upgrade / Wartung
+
+Verwenden Sie den Wartungsbefehl, wenn Sie Ihr lokales Runtime bewusst aktualisieren wollen:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Achtung: Dieser Befehl verändert den aktuellen Workspace/Runtime. Er kann JavaScript-Abhängigkeiten aktualisieren, ggf. `cargo install iii-engine --force` ausführen und Docker-Images ziehen.
+
+Implementierungsdetails in `src/cli.ts` (siehe `runUpgrade` rund um den Bereich `src/cli.ts:544-595`).
+
+### Claude Code (ein Block, einfügen)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 ohne Plugin-Installation (MCP-Standalone-Pfad)
+
+Wenn Sie den MCP-Server von agentmemory direkt über `~/.claude.json` verdrahten anstatt über `/plugin install`, löst Claude Code `${CLAUDE_PLUGIN_ROOT}` niemals auf, und Sie müssen Hook-Skripte in `~/.claude/settings.json` auf absolute Pfade zeigen lassen. Diese Pfade enthalten typischerweise die agentmemory-Version (z. B. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), sodass das nächste Upgrade jeden Hook stillschweigend bricht ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Workaround:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Das mischt dieselben Hook-Befehle in `~/.claude/settings.json` ein, mit absoluten Pfaden, die in das mitgelieferte `plugin/`-Verzeichnis des aktuell installierten `@agentmemory/agentmemory`-Pakets auflösen. Führen Sie den Befehl nach einem agentmemory-Upgrade erneut aus, um die Pfade zu aktualisieren. Eigene Einträge in derselben Datei bleiben erhalten; nur frühere agentmemory-Einträge werden ersetzt. Den `/plugin install`-Pfad zu nutzen, bleibt der empfohlene Ansatz.
+Für entfernte oder geschützte Deployments starten Sie Claude Code mit gesetztem `AGENTMEMORY_URL` und `AGENTMEMORY_SECRET`. Das Plugin reicht beide Werte an seinen mitgelieferten MCP-Server weiter; ist `AGENTMEMORY_URL` leer, verwendet das MCP-Shim `http://localhost:3111`.
+
+### Codex CLI (Codex-Plugin-Plattform)
+
+```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
+```
+
+Das Codex-Plugin wird aus demselben `plugin/`-Verzeichnis ausgeliefert wie das Claude-Code-Plugin. Es registriert:
+
+- `@agentmemory/mcp` als MCP-Server (proxyt alle 51 Tools, wenn `AGENTMEMORY_URL` auf einen laufenden agentmemory-Server zeigt; fällt lokal auf 7 Tools zurück, wenn kein Server erreichbar ist)
+- 6 Lifecycle-Hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 Skills: `/recall`, `/remember`, `/session-history`, `/forget`
+
+Codex' Hook-Engine injiziert `CLAUDE_PLUGIN_ROOT` in Hook-Subprozesse (siehe [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), sodass dieselben Hook-Skripte ohne Duplikation auf beiden Hosts laufen. Die Events Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure gibt es nur in Claude Code und werden für Codex nicht registriert.
+
+#### Codex Desktop: Plugin-Hooks derzeit lautlos (Workaround vorhanden)
+
+`CodexHooks` und `PluginHooks` sind beide stabil und standardmäßig aktiviert in [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), aber aktuelle Codex-Desktop-Builds dispatchen die plugin-lokale `hooks.json` nicht ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP-Tools funktionieren weiterhin; nur die Lifecycle-Beobachtungen fehlen.
+
+Solange der Fix upstream nicht gelandet ist, spiegeln Sie dieselben Hook-Befehle in die globale `~/.codex/hooks.json`:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Das fügt einen idempotenten Block zu `~/.codex/hooks.json` hinzu, der absolute Pfade zu den mitgelieferten Skripten referenziert (keine `${CLAUDE_PLUGIN_ROOT}`-Expansion auf Benutzer-Scope nötig). Führen Sie denselben Befehl nach einem agentmemory-Upgrade erneut aus, um die Pfade zu aktualisieren. Eigene Einträge in derselben Datei bleiben erhalten; nur frühere agentmemory-Einträge werden ersetzt.
+
+
+OpenClaw (diesen Prompt einfügen)
+
+```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 51 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`.
+```
+
+Vollständiger Leitfaden: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (diesen Prompt einfügen)
+
+```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 51 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.
+```
+
+Vollständiger Leitfaden: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Andere Agenten
+
+Starten Sie den Memory-Server: `npx @agentmemory/agentmemory`
+
+Der agentmemory-Eintrag ist der **gleiche MCP-Server-Block** für jeden Host, der das `mcpServers`-Format verwendet (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw):
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Fügen Sie diesen Eintrag in das bestehende `mcpServers`-Objekt** in der Konfigurationsdatei des Hosts ein — ersetzen Sie nicht die Datei. Wenn die Datei bereits andere Server enthält, fügen Sie `agentmemory` als zusätzlichen Schlüssel innerhalb von `mcpServers` daneben ein. Fehlt `mcpServers` ganz, fügen Sie den Block innerhalb von `{ "mcpServers": { ... } }` ein. Die `${VAR}`-Platzhalter übernehmen `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` aus der Shell beim Start des MCP-Servers — nicht gesetzte Variablen werden als leere Strings übergeben, und das Shim fällt auf `http://localhost:3111` zurück. Ein einziger verdrahteter Eintrag deckt sowohl lokale als auch entfernte (k8s / reverse-proxied) Deployments ab.
+
+| Agent | Konfigurationsdatei | Hinweise |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | In `mcpServers` einfügen. Ein-Klick-Deeplink auch auf der Website. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | In `mcpServers` einfügen. Claude Desktop nach dem Editieren neu starten. |
+| **Cline / Roo Code / Kilo Code** | Cline-MCP-Einstellungen (Settings UI → MCP Servers → Edit) | Gleicher `mcpServers`-Block. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Gleicher `mcpServers`-Block. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (automatisches Mergen). |
+| **OpenClaw** | OpenClaw-MCP-Konfig | Gleicher `mcpServers`-Block oder das tiefer integrierte [Memory-Plugin](../integrations/openclaw/). |
+| **Codex CLI (nur MCP)** | `.codex/config.toml` | TOML-Form: `codex mcp add agentmemory -- npx -y @agentmemory/mcp` oder `[mcp_servers.agentmemory]` manuell hinzufügen. |
+| **Codex CLI (volles Plugin)** | Codex-Plugin-Marketplace | `codex plugin marketplace add rohitg00/agentmemory`, dann `codex plugin add agentmemory@agentmemory`. Registriert MCP + 6 Lifecycle-Hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 Skills. Auf Codex Desktop zusätzlich `agentmemory connect codex --with-hooks` ausführen, bis [openai/codex#16430](https://github.com/openai/codex/issues/16430) landet — Plugin-Hooks sind dort derzeit lautlos. |
+| **OpenCode (nur MCP)** | `opencode.json` | Anderes Format — `mcp`-Schlüssel auf oberster Ebene, Command als Array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (volles Plugin)** | `plugin/opencode/` | 22 Auto-Capture-Hooks für Session-Lifecycle, Messages, Tools, Fehler. Zwei Slash-Befehle (`/recall`, `/remember`). Kopieren Sie `plugin/opencode/` in Ihren OpenCode-Workspace und fügen Sie den Plugin-Eintrag zu `opencode.json` hinzu. Siehe [`plugin/opencode/README.md`](../plugin/opencode/README.md) für die vollständige Hook-Tabelle + Gap-Analyse. |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | [`integrations/pi`](../integrations/pi/) kopieren und pi neu starten. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Verwenden Sie das tiefer integrierte [Memory-Provider-Plugin](../integrations/hermes/) mit `memory.provider: agentmemory`. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` schreibt den standardmäßigen `mcpServers`-Block. Die Hook-Payload ist feldkompatibel mit Claude Code, sodass die bestehenden 12 Hook-Skripte ohne Änderung funktionieren — verdrahten Sie sie über den Abschnitt `hooks` in derselben `settings.json`. |
+| **Antigravity** (ersetzt Gemini CLI) | `mcp_config.json` (im User-Verzeichnis von Antigravity) | `agentmemory connect antigravity` schreibt den standardmäßigen `mcpServers`-Block. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Nach dem Sunset von Gemini CLI am 2026-06-18 zu nutzen. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` schreibt die Konfig auf Benutzerebene. Workspace-Overrides liegen in `.kiro/settings/mcp.json` neben Ihrem Code. |
+| **Goose** | Goose-MCP-Einstellungen-UI | Gleicher `mcpServers`-Block. |
+| **Aider** | n/v | Sprechen Sie direkt mit der REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Jeder Agent (32+)** | n/v | `npx skillkit install agentmemory` erkennt den Host automatisch und merged. |
+
+**MCP-Clients in Sandboxen** (Flatpak / Snap / restriktive Container), die den `localhost` des Hosts nicht erreichen können: Setzen Sie zusätzlich `"AGENTMEMORY_FORCE_PROXY": "1"` im `env`-Block und lassen Sie `AGENTMEMORY_URL` auf eine Route zeigen, die die Sandbox tatsächlich erreichen kann (z. B. Ihre LAN-IP). Siehe [#234](https://github.com/rohitg00/agentmemory/issues/234) für den Diagnose-Walkthrough.
+
+### Programmatischer Zugriff (Python / Rust / Node)
+
+agentmemory registriert seine Kernoperationen als iii-Funktionen (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Jede Sprache mit einem iii-SDK kann sie direkt über `ws://localhost:49134` aufrufen — kein separater REST-Client pro Sprache nötig.
+
+```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"},
+})
+```
+
+Vollständiges Beispiel: [`examples/python/`](../examples/python/) (Quickstart + Beobachtungs-/Recall-Fluss). REST auf `:3111` bleibt verfügbar für Hosts ohne iii-Runtime.
+
+### Aus den Quellen
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Das startet agentmemory mit einer lokalen `iii-engine`, falls `iii` bereits installiert ist, oder fällt auf Docker Compose zurück, falls Docker vorhanden ist. REST, Streams und der Viewer binden sich standardmäßig an `127.0.0.1`.
+
+`iii-engine` manuell installieren. **agentmemory pinnt `iii-engine` derzeit auf `v0.11.2`** — `v0.11.6` führt ein neues Modell ein, alles per `iii worker add` zu sandboxen, für das agentmemory noch nicht refaktoriert wurde. Der Pin wird aufgehoben, sobald die Refaktorierung erfolgt ist. Überschreiben Sie mit `AGENTMEMORY_III_VERSION=`, wenn Sie manuell auf das Sandbox-Modell migriert sind.
+
+- **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:** `aarch64-apple-darwin` durch `x86_64-apple-darwin` ersetzen
+- **Linux x64:** durch `x86_64-unknown-linux-gnu` ersetzen
+- **Linux arm64:** durch `aarch64-unknown-linux-gnu` ersetzen
+- **Windows:** `iii-x86_64-pc-windows-msvc.zip` von [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) herunterladen, `iii.exe` extrahieren, zum PATH hinzufügen
+
+Oder Docker verwenden (die mitgelieferte `docker-compose.yml` zieht `iiidev/iii:0.11.2`). Vollständige Doku: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory läuft auf Windows 10/11, aber das Node.js-Paket allein genügt nicht — Sie brauchen außerdem das `iii-engine`-Runtime (ein separates natives Binary) als Hintergrundprozess. Der offizielle Upstream-Installer ist ein `sh`-Skript, und es gibt heute weder einen PowerShell-Installer noch ein scoop/winget-Paket, daher haben Windows-Nutzer zwei Wege:
+
+**Option A — Vorgebautes Windows-Binary (empfohlen):**
+
+```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 — Nur Standalone-MCP (ohne Engine):** Wenn Sie nur die MCP-Tools für Ihren Agenten brauchen und weder REST API, Viewer noch Cron-Jobs, überspringen Sie die Engine ganz:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Diagnose unter Windows:** Wenn `npx @agentmemory/agentmemory` fehlschlägt, mit `--verbose` neu starten, um das tatsächliche Engine-stderr zu sehen. Häufige Fehlerbilder:
+
+| Symptom | Lösung |
+|---|---|
+| `iii-engine process started`, dann `did not become ready within 15s` | Engine ist beim Start abgestürzt — mit `--verbose` neu starten, stderr prüfen |
+| `Could not start iii-engine` | Weder `iii.exe` noch Docker installiert. Siehe Option A oder B oben |
+| Port-Konflikt | `netstat -ano \| findstr :3111`, um zu sehen, was gebunden ist, dann beenden oder `--port ` verwenden |
+| Docker-Fallback wird übersprungen, obwohl Docker installiert ist | Stellen Sie sicher, dass Docker Desktop tatsächlich läuft (Taskleisten-Icon) |
+
+> Hinweis: Es gibt kein `cargo install iii-engine` — `iii` ist nicht auf crates.io veröffentlicht. Die einzigen unterstützten Installationsmethoden sind das vorgebaute Binary oben, das Upstream-`sh`-Installationsskript (nur macOS/Linux) und das Docker-Image.
+
+---
+
+
Deployment
+
+Ein-Klick-Vorlagen für gemanagte Hosts. Jede liefert ein autonomes
+Dockerfile aus, das `@agentmemory/agentmemory` aus npm bezieht und das
+iii-engine-Binary aus dem offiziellen `iiidev/iii`-Image vom Docker Hub
+kopiert — keine vorgebaute agentmemory-Image-Erforderlichkeit. Persistenter
+Speicher wird unter `/data` gemountet; der Entrypoint beim ersten Boot
+überschreibt die per npm gelieferte iii-Konfig (die `127.0.0.1` bindet)
+mit einer deploy-tauglichen Variante, die `0.0.0.0` bindet und absolute
+`/data`-Pfade verwendet, generiert das HMAC-Secret und senkt die
+Privilegien von `root` auf `node` via `gosu`, bevor er die agentmemory-CLI
+exec't.
+
+
+
+
+
+
+Der Ein-Klick-Deploy-Button von Render erfordert eine `render.yaml` im Repository-Root, das wir bewusst sauber halten. Verwenden Sie den Render-Blueprint-Fluss, dokumentiert in [`deploy/render/`](./deploy/render/README.md), um manuell auf das im Repo liegende Blueprint zu zeigen.
+
+Vollständige Setup-Details (HMAC-Capture, Viewer-SSH-Tunnel, Rotation, Backup, Kostenuntergrenzen) finden Sie in [`deploy/`](./deploy/README.md):
+
+- [`deploy/fly`](./deploy/fly/README.md) — Einzelmaschine mit
+ `auto_stop_machines = "stop"`; am günstigsten im Leerlauf.
+- [`deploy/railway`](./deploy/railway/README.md) — Hobby-Plan mit Pauschalpreis,
+ Volume im Dashboard.
+- [`deploy/render`](./deploy/render/README.md) — Blueprint-Fluss,
+ automatische Disk-Snapshots auf bezahlten Plänen.
+- [`deploy/coolify`](./deploy/coolify/README.md) — self-hosted auf Ihrem
+ eigenen VPS via [Coolify](https://coolify.io/self-hosted); derselbe
+ Docker-Compose-Stack, Sie besitzen Host und Daten.
+
+Nur Port `3111` wird veröffentlicht. Der Viewer auf `3113` bleibt im
+Container an Loopback gebunden — jedes Template-README dokumentiert
+das SSH-Tunnel-Muster, um ihn zu erreichen.
+
+---
+
+
+
+Jeder Coding-Agent vergisst alles, wenn die Session endet. Sie verschwenden die ersten 5 Minuten jeder Session damit, Ihren Stack erneut zu erklären. agentmemory läuft im Hintergrund und beseitigt das vollständig.
+
+```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. eingebautes Agent-Memory
+
+Jeder KI-Coding-Agent kommt mit eingebautem Memory — Claude Code hat `MEMORY.md`, Cursor hat Notepads, Cline hat Memory Bank. Das funktioniert wie Klebezettel. agentmemory ist die durchsuchbare Datenbank hinter den Klebezetteln.
+
+| | Eingebaut (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Skalierung | 200-Zeilen-Limit | Unbegrenzt |
+| Suche | Lädt alles in den Kontext | BM25 + Vector + Graph (nur Top-K) |
+| Token-Kosten | 22K+ bei 240 Beobachtungen | ~1.900 Tokens (92 % weniger) |
+| Agentenübergreifend | Dateien pro Agent | MCP + REST (jeder Agent) |
+| Koordination | Keine | Leases, Signale, Actions, Routinen |
+| Observability | Dateien manuell lesen | Echtzeit-Viewer auf :3113 |
+
+---
+
+
+
+Triple-Stream-Retrieval, das drei Signale kombiniert:
+
+| Stream | Was es tut | Wann |
+|---|---|---|
+| **BM25** | Gestemmter Keyword-Abgleich mit Synonymerweiterung | Immer aktiv |
+| **Vector** | Cosinus-Ähnlichkeit über dichte Embeddings | Embedding-Provider konfiguriert |
+| **Graph** | Knowledge-Graph-Traversal via Entitäten-Abgleich | Entitäten in der Anfrage erkannt |
+
+Verschmolzen mit Reciprocal Rank Fusion (RRF, k=60) und session-diversifiziert (max. 3 Ergebnisse pro Session).
+
+BM25 tokenisiert Griechisch, Kyrillisch, Hebräisch, Arabisch und akzentuiertes Latein standardmäßig. Für Erinnerungen in Chinesisch / Japanisch / Koreanisch installieren Sie die optionalen Segmentierer (`npm install @node-rs/jieba tiny-segmenter`), um CJK-Folgen in Worttokens aufzuteilen; ohne sie fällt agentmemory weich auf eine Tokenisierung als gesamte Folge zurück und gibt einmalig einen Hinweis auf stderr aus.
+
+### Embedding-Provider
+
+agentmemory erkennt Ihren Provider automatisch. Für die besten Ergebnisse installieren Sie lokale Embeddings (kostenlos):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Provider | Modell | Kosten | Hinweise |
+|---|---|---|---|
+| **Lokal (empfohlen)** | `all-MiniLM-L6-v2` | Kostenlos | Offline, +8 pp Recall gegenüber BM25 allein |
+| Gemini | `gemini-embedding-001` | Free Tier | 100+ Sprachen, 768/1536/3072 Dims (MRL), 2048-Token-Eingabe. Ersetzt `text-embedding-004` ([deprecated, Abschaltung 14. Jan. 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | 0,02 $/1M | Höchste Qualität |
+| Voyage AI | `voyage-code-3` | Kostenpflichtig | Auf Code optimiert |
+| Cohere | `embed-english-v3.0` | Testzugang | Allzweck |
+| OpenRouter | Beliebiges Modell | Variabel | Multi-Modell-Proxy |
+
+---
+
+
+
+53 Tools, 6 Resources, 3 Prompts und 4 Skills — das umfassendste MCP-Memory-Toolkit für jeden Agenten.
+
+> **MCP-Shim vs. voller Server:** Das veröffentlichte `@agentmemory/mcp`-Paket ist ein dünnes Shim. Es legt die volle 51-Tool-Oberfläche **nur dann** offen, wenn es per `AGENTMEMORY_URL` einen laufenden agentmemory-Server erreichen kann (Proxy-Modus). Ohne erreichbaren Server fällt das Shim auf einen lokalen 7-Tool-Satz zurück (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). Die Umgebungsvariable `AGENTMEMORY_TOOLS=core|all` ist ein *serverseitiger* Schalter — sie im `env`-Block des Shims zu setzen hat keinen Effekt. Wenn Sie in Cursor / OpenCode / Gemini CLI nur 7 Tools sehen, starten Sie `npx @agentmemory/agentmemory` (oder den Docker-Stack) und setzen Sie `AGENTMEMORY_URL=http://localhost:3111`.
+
+### 51 Tools
+
+
+Core-Tools (immer verfügbar)
+
+| Tool | Beschreibung |
+|------|-------------|
+| `memory_recall` | Vergangene Beobachtungen durchsuchen |
+| `memory_compress_file` | Markdown-Dateien unter Erhalt der Struktur komprimieren |
+| `memory_save` | Erkenntnis, Entscheidung oder Muster speichern |
+| `memory_patterns` | Wiederkehrende Muster erkennen |
+| `memory_smart_search` | Hybride semantische + Keyword-Suche |
+| `memory_file_history` | Vergangene Beobachtungen zu bestimmten Dateien |
+| `memory_sessions` | Letzte Sessions auflisten |
+| `memory_timeline` | Chronologische Beobachtungen |
+| `memory_profile` | Projektprofil (Konzepte, Dateien, Muster) |
+| `memory_export` | Alle Memory-Daten exportieren |
+| `memory_relations` | Beziehungsgraph abfragen |
+
+
+
+
+Erweiterte Tools (insgesamt 51 — AGENTMEMORY_TOOLS=all setzen)
+
+| Tool | Beschreibung |
+|------|-------------|
+| `memory_patterns` | Wiederkehrende Muster erkennen |
+| `memory_timeline` | Chronologische Beobachtungen |
+| `memory_relations` | Beziehungsgraph abfragen |
+| `memory_graph_query` | Knowledge-Graph-Traversal |
+| `memory_consolidate` | 4-stufige Konsolidierung ausführen |
+| `memory_claude_bridge_sync` | Mit MEMORY.md synchronisieren |
+| `memory_team_share` | Mit Teammitgliedern teilen |
+| `memory_team_feed` | Kürzlich geteilte Einträge |
+| `memory_audit` | Audit-Trail der Operationen |
+| `memory_governance_delete` | Mit Audit-Trail löschen |
+| `memory_snapshot_create` | Git-versionierter Snapshot |
+| `memory_action_create` | Arbeitspakete mit Abhängigkeiten anlegen |
+| `memory_action_update` | Action-Status aktualisieren |
+| `memory_frontier` | Entblockte Actions nach Priorität sortiert |
+| `memory_next` | Einzelne wichtigste nächste Action |
+| `memory_lease` | Exklusive Action-Leases (Multi-Agent) |
+| `memory_routine_run` | Workflow-Routinen instanziieren |
+| `memory_signal_send` | Inter-Agent-Messaging |
+| `memory_signal_read` | Nachrichten mit Empfangsquittungen lesen |
+| `memory_checkpoint` | Externe Bedingungs-Gates |
+| `memory_mesh_sync` | P2P-Sync zwischen Instanzen |
+| `memory_sentinel_create` | Ereignisgesteuerte Watcher |
+| `memory_sentinel_trigger` | Sentinels extern auslösen |
+| `memory_sketch_create` | Ephemere Action-Graphen |
+| `memory_sketch_promote` | In permanent überführen |
+| `memory_crystallize` | Action-Ketten kompaktieren |
+| `memory_diagnose` | Health-Checks |
+| `memory_heal` | Festsitzenden Zustand auto-fixen |
+| `memory_facet_tag` | Dimension:Wert-Tags |
+| `memory_facet_query` | Nach Facetten-Tags abfragen |
+| `memory_verify` | Provenienz nachverfolgen |
+
+
+
+### 6 Resources · 3 Prompts · 4 Skills
+
+| Typ | Name | Beschreibung |
+|------|------|-------------|
+| Resource | `agentmemory://status` | Health, Session-Anzahl, Memory-Anzahl |
+| Resource | `agentmemory://project/{name}/profile` | Projektspezifische Intelligenz |
+| Resource | `agentmemory://memories/latest` | Die 10 neuesten aktiven Erinnerungen |
+| Resource | `agentmemory://graph/stats` | Knowledge-Graph-Statistiken |
+| Prompt | `recall_context` | Suche + Rückgabe von Kontext-Nachrichten |
+| Prompt | `session_handoff` | Handoff-Daten zwischen Agenten |
+| Prompt | `detect_patterns` | Wiederkehrende Muster analysieren |
+| Skill | `/recall` | Memory durchsuchen |
+| Skill | `/remember` | Im Langzeit-Memory speichern |
+| Skill | `/session-history` | Zusammenfassungen letzter Sessions |
+| Skill | `/forget` | Beobachtungen / Sessions löschen |
+
+### Standalone MCP
+
+Ohne den vollen Server laufen lassen — für jeden MCP-Client. Eines der folgenden geht:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+Oder zur MCP-Konfig Ihres Agenten hinzufügen:
+
+Die meisten Agenten (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+Fügen Sie den `agentmemory`-Eintrag in das vorhandene `mcpServers`-Objekt Ihres Hosts ein, statt die Datei zu ersetzen. Für Sandbox-Clients, die den `localhost` des Hosts nicht erreichen können, fügen Sie `"AGENTMEMORY_FORCE_PROXY": "1"` zum env-Block hinzu und lassen `AGENTMEMORY_URL` auf eine Route zeigen, die die Sandbox erreicht.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Plugin-Datei aus dem Repo kopieren:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Startet automatisch auf Port `3113`. Live-Beobachtungs-Stream, Session-Explorer, Memory-Browser, Knowledge-Graph-Visualisierung und Health-Dashboard.
+
+```bash
+open http://localhost:3113
+```
+
+Der Viewer-Server bindet sich standardmäßig an `127.0.0.1`. Der per REST ausgelieferte `/agentmemory/viewer`-Endpunkt folgt den üblichen `AGENTMEMORY_SECRET`-Bearer-Token-Regeln. CSP-Header verwenden eine Skript-Nonce pro Response und deaktivieren Inline-Handler-Attribute (`script-src-attr 'none'`).
+
+---
+
+
+
+Der Viewer auf `:3113` zeigt, was Ihr Agent **gespeichert hat**. Die [iii console](https://iii.dev/docs/console) zeigt, was Ihr Agent **getan hat** — jede Memory-Operation als OpenTelemetry-Trace, jeden KV-Eintrag editierbar, jede Funktion aufrufbar, jeden Stream abgreifbar. Zwei Fenster auf dasselbe Memory: eines produktnah, eines engine-nah.
+
+Sehen Sie, wie ein `memory_smart_search` feuert, und beobachten Sie BM25-Scan → Embedding-Lookup → RRF-Fusion → Reranker als Wasserfall. Editieren Sie einen festsitzenden Konsolidierungs-Timer im KV-Browser. Spielen Sie einen `PostToolUse`-Hook mit angepasster Payload erneut ab. Pinnen Sie den WebSocket-Stream an und sehen Sie Beobachtungen live eintrudeln.
+
+agentmemory liefert das umsonst, weil jede Funktion, jeder Trigger, jeder State-Scope und jeder Stream eine iii-Primitive ist — nichts Eigenes, nichts zu instrumentieren.
+
+
+
+
+ Workers-Seite: jeder verbundene Worker — einschließlich agentmemory selbst — mit PID, Funktionsanzahl, Runtime und last-seen.
+
+
+**Bereits installiert.** Die Console wird mit `iii` ausgeliefert — kein separater Installer.
+
+**Neben agentmemory starten:**
+
+```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
+```
+
+Dann `http://localhost:3114` öffnen. `--enable-flow` ergänzen für die experimentelle Architektur-Graph-Seite.
+
+Engine-Endpunkte nur überschreiben, wenn Sie sie verschoben haben:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Was Sie aus der Console heraus tun können:**
+
+| Seite | Verwenden Sie sie für |
+|------|-----------|
+| **Workers** | Jeden verbundenen Worker und seine Live-Metriken sehen — einschließlich des agentmemory-Workers selbst. |
+| **Functions** | Jede Funktion von agentmemory direkt mit einer JSON-Payload aufrufen — handlich zum Testen von `memory.recall`, `memory.consolidate`, `graph.query` ohne Client zu verdrahten. |
+| **Triggers** | HTTP-, Cron-, Event- und State-Trigger erneut abspielen — den Konsolidierungs-Cron manuell auslösen, eine HTTP-Route wiederholen, einen State-Change emittieren. |
+| **States** | KV-Browser mit vollem CRUD — Sessions, Memory-Slots, Lifecycle-Timer, Embedding-Index — Werte direkt bearbeiten. |
+| **Streams** | Live-WebSocket-Monitor für Memory-Schreibvorgänge, Hook-Events und Beobachtungsupdates, wie sie durch iii-Streams fließen. |
+| **Queues** | Durable Queue-Topics + Dead-Letter-Verwaltung. Fehlgeschlagene Embedding-/Kompressions-Jobs wiederholen oder verwerfen. |
+| **Traces** | OpenTelemetry-Wasserfall- / Flame- / Service-Breakdown-Ansichten. Nach `trace_id` filtern, um exakt zu sehen, welche Funktionen, DB-Calls und Embedding-Anfragen eine einzelne `memory.search` ausgelöst hat. |
+| **Logs** | Strukturierte OTEL-Logs, gefiltert und korreliert mit Trace-/Span-IDs. |
+| **Config** | Runtime-Konfiguration — sehen Sie genau, mit welchen Workern, Providern und Ports Ihre Engine läuft. |
+| **Flow** | (Optional, `--enable-flow`) Interaktiver Architekturgraph jedes Workers, Triggers und Streams. |
+
+
+
+**Traces sind bereits aktiv:**
+
+`iii-config.yaml` wird mit aktiviertem `iii-observability`-Worker ausgeliefert (`exporter: memory`, `sampling_ratio: 1.0`, Metriken + Logs). Keine zusätzliche Konfig nötig — in dem Moment, in dem agentmemory startet, emittiert jede Memory-Operation einen Trace-Span und ein strukturiertes Log, das die Console lesen kann.
+
+Wenn Sie stattdessen zu Jaeger/Honeycomb/Grafana Tempo exportieren wollen, ändern Sie `exporter: memory` zu `exporter: otlp` und setzen den Collector-Endpunkt gemäß der iii-Observability-Doku.
+
+> **Achtung:** Auf der Console selbst wird keine Auth erzwungen — lassen Sie sie an `127.0.0.1` gebunden (Standard) und stellen Sie sie niemals öffentlich bereit.
+
+---
+
+
+
+agentmemory ist **bereits eine laufende [iii](https://iii.dev)-Instanz**. Funktionen, Trigger, KV-State, Streams, OTEL-Traces — alles sind iii-Primitiven. Sie haben weder Postgres noch Redis, Express, pm2 oder Prometheus installiert, weil iii sie ersetzt.
+
+Das bedeutet, ein weiterer Befehl erweitert agentmemory um eine komplett neue Fähigkeit.
+
+### agentmemory mit einem Befehl erweitern
+
+```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
+```
+
+Jedes `iii worker add` registriert neue Funktionen und Trigger im selben Engine, auf dem agentmemory bereits läuft. Viewer und Console übernehmen sie sofort — kein Reload, keine neue Integration, kein neuer Container.
+
+| `iii worker add` | Was Sie zusätzlich zu agentmemory erhalten |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Multi-Instanz-Memory: jedes `remember` fächert auf, jedes `search` liest die Vereinigung |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Geplanter Lifecycle — nächtliche Konsolidierung, wöchentliche Snapshots, Decay nach fester Uhr |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable Retries: fehlgeschlagene Embedding-/Kompressions-Jobs überleben den Neustart, keine verlorenen Beobachtungen |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL-Traces, Metriken, Logs auf jeder Funktion — in `iii-config.yaml` ab dem ersten Tag verdrahtet |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Code, der aus `memory_recall` kommt, läuft in einer wegwerf-VM, nicht in Ihrer Shell |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-gestützter State-Adapter, wenn Sie die In-Memory-KV-Voreinstellungen überwachsen |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | Zusätzliche MCP-Server neben dem von agentmemory aufstellen, die sich denselben Engine teilen |
+
+Volle Registry: [workers.iii.dev](https://workers.iii.dev). Jeder Worker dort komponiert sich über dieselben Primitiven wie agentmemory — und das agentmemory, das Sie bereits haben, ist einer davon.
+
+### Was iii ersetzt
+
+| Traditioneller Stack | agentmemory verwendet |
+|---|---|
+| 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 |
+| Eigene Plugin-Systeme | `iii worker add ` |
+
+**118 Quelldateien · ~21.800 LOC · 950+ Tests · 123 Funktionen · 34 KV-Scopes** — alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst.
+
+---
+
+
+
+### LLM-Provider
+
+agentmemory erkennt aus Ihrer Umgebung automatisch. Standardmäßig werden keine LLM-Aufrufe ausgeführt, solange Sie nicht einen Provider konfigurieren oder dem Claude-Abonnement-Fallback ausdrücklich zustimmen.
+
+| Provider | Konfig | Hinweise |
+|----------|--------|-------|
+| **No-op (Standard)** | Keine Konfig nötig | LLM-gestütztes Compress/Summarize ist DEAKTIVIERT. Synthetische BM25-Kompression + Recall funktionieren weiter. Siehe `AGENTMEMORY_ALLOW_AGENT_SDK` unten, falls Sie früher auf den Claude-Abonnement-Fallback gesetzt haben. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Abrechnung pro Token |
+| MiniMax | `MINIMAX_API_KEY` | Anthropic-kompatibel |
+| Gemini | `GEMINI_API_KEY` | Aktiviert zusätzlich Embeddings |
+| OpenRouter | `OPENROUTER_API_KEY` | Beliebiges Modell |
+| Claude-Abonnement-Fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Nur als Opt-in. Startet `@anthropic-ai/claude-agent-sdk`-Sessions — verursachte früher unbegrenzte Stop-Hook-Rekursion (Folge von #149), daher nicht mehr Standard. |
+
+### Kostenbewusste Modellwahl
+
+Hintergrund-Kompression läuft bei jeder Beobachtung, daher beeinflusst die Modellwahl die monatlichen Kosten spürbar. Erfasste Lastdaten: 635 Requests / 888K Tokens / 35 Stunden aktive Nutzung, gegen drei OpenRouter-Modelle zu den Preisen vom 2026-05-23.
+
+| Stufe | Modell | Eingabe / 1M | Ausgabe / 1M | Kosten für die erfassten 35 h | Hinweise |
+|------|-------|------------|-------------|---------------------------|-------|
+| Empfohlen | `deepseek/deepseek-v4-pro` | 0,435 $ | 0,87 $ | ~0,46 $ | Solide Kompressions-/Summarize-Qualität zu ~10× geringeren Kosten als Sonnet. |
+| Empfohlen | `deepseek/deepseek-chat` | 0,27 $ | 1,10 $ | ~0,40 $ | Älter, aber für reine Kompressions-Workloads weiterhin in Ordnung. |
+| Empfohlen | `qwen/qwen3-coder` | 0,45 $ | 1,80 $ | ~0,55 $ | Starkes Code-Reasoning, wenn Ihre Sessions stark codelastig sind. |
+| Premium | `anthropic/claude-sonnet-4.6` | 3,00 $ | 15,00 $ | ~5,02 $ | Hohe Qualität, aber teuer für dauerhafte Hintergrundarbeit. |
+| Premium | `openai/gpt-4o` | 2,50 $ | 10,00 $ | ~4,20 $ | Ähnliche Stufe wie Sonnet. |
+| Vermeiden | `anthropic/claude-opus-4.6` | 15,00 $ | 75,00 $ | ~25+ $ | Reasoning-Klasse-Modell; massive Überausgabe für Kompression. |
+
+agentmemory gibt eine Runtime-Warnung aus, wenn `OPENROUTER_MODEL` auf ein Premium-Tier-Muster passt. Setzen Sie `AGENTMEMORY_SUPPRESS_COST_WARNING=1`, um sie zum Schweigen zu bringen, sobald Sie eine bewusste Wahl getroffen haben.
+
+Qualitäts-Kosten-Abwägung für Memory-Arbeit: Kompression ist eine Summarize-Aufgabe mit eher lockerer Qualitätsanforderung (der Agent liest die Zusammenfassung erneut, nicht der Benutzer). DeepSeek-V4-Pro / Qwen3-Coder landen bei dieser Aufgabe innerhalb von Rundungsfehlern an Sonnet, bei ~10× weniger Kosten. Heben Sie Premium-Modelle für Anfragen auf, die Sie direkt lesen.
+
+Quellen: [OpenRouter-Preise für Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek-Preis-Hinweise](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Multi-Agent-Memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+In Multi-Agent-Setups, in denen sich mehrere Rollen einen agentmemory-Server teilen (architect / developer / reviewer / researcher / support-agent), markiert `AGENT_ID` jede Schreibaktion mit der Rolle, die sie ausgelöst hat. `AGENTMEMORY_AGENT_SCOPE` steuert, ob der Recall nach diesem Tag filtert.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+Zwei Modi:
+
+| Modus | Schreibvorgänge markieren | Recall filtern | Wann verwenden |
+|------|------------|---------------|-------------|
+| `shared` (Standard) | ja | nein | Agentenübergreifender Kontext mit Audit-Trail. Architect sieht, was Developer notiert hat, aber jede Zeile vermerkt, wer es gesagt hat. |
+| `isolated` | ja | ja | Strikte Trennung. Architect sieht niemals Beobachtungen / Erinnerungen / Sessions von Developer. |
+
+Was getaggt wird, wenn `AGENT_ID` gesetzt ist: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. Die Rolle fließt von `api::session::start` → `mem::observe` → `mem::compress` → KV.
+
+Was im Isolated-Modus gefiltert wird: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Jeder Endpunkt akzeptiert `?agentId=` als Per-Request-Override und `?agentId=*`, um sich komplett aus dem env-Scope auszuklinken. `/memories` akzeptiert zudem `?includeOrphans=true`, um Pre-AGENT_ID-Erinnerungen, deren `agentId` undefiniert ist, sichtbar zu machen.
+
+Per-Call-Override auf SDK-/REST-Ebene: jeder mutierende Endpunkt (`/session/start`, `/remember`) akzeptiert ein `agentId`-Feld im Request-Body, das die env-Variable überschreibt. Nützlich für Runtimes, die viele Rollen durch einen einzelnen Serverprozess routen.
+
+Wenn `AGENT_ID` nicht gesetzt ist, bleibt Memory unscoped (Legacy-Verhalten, keine Tags, keine Filter).
+
+### Ports
+
+agentmemory + iii-engine binden standardmäßig vier Ports. Wenn ein Neustart mit `port in use` fehlschlägt, sagt Ihnen diese Tabelle, nach welchem Prozess Sie suchen müssen.
+
+| Port | Prozess | Zweck | Env-Override |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Interner Streams-Worker (von agentmemory + Viewer verwendet) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Echtzeit-Viewer (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — Worker registrieren sich hier, OTel-Telemetrie fließt darüber | `III_ENGINE_URL` (volle URL, Standard `ws://localhost:49134`) |
+
+Aufräumen veralteter Prozesse, wenn Ports nach einem abgestürzten Lauf gebunden bleiben:
+
+```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` räumt sowohl den Worker als auch das Engine-Pidfile bei einem geordneten Shutdown sauber auf (#640, #474). Das manuelle Cleanup oben ist nur für den Post-Crash-Fall nötig, in dem kein Pidfile zurückbleibt.
+
+### Konfigurationsdatei
+
+Legen Sie die agentmemory-Runtime-Konfiguration in `~/.agentmemory/.env` ab, statt Variablen in jeder Shell zu exportieren. Wenn der Viewer einen Setup-Hinweis wie `export ANTHROPIC_API_KEY=...` zeigt, kopieren Sie ihn als `ANTHROPIC_API_KEY=...` ohne `export`-Präfix in diese Datei und starten Sie agentmemory neu.
+
+Prozess-Umgebungsvariablen funktionieren weiterhin und haben Vorrang vor Werten in der Datei.
+
+Unter Windows liegt dieselbe Datei unter `%USERPROFILE%\.agentmemory\.env`:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+Um mit einem Claude Code Pro/Max-Abonnement statt eines API-Schlüssels zu testen, stimmen Sie explizit zu:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+Aktivieren Sie Graph- oder Konsolidierungs-Features in derselben Datei, falls gewünscht:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Umgebungsvariablen
+
+`~/.agentmemory/.env` anlegen:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**Voraussetzungen:** Node.js >= 20, [iii-engine](https://iii.dev/docs) oder Docker
+
+
+
+ Tu agente de codificación lo recuerda todo. Se acabó volver a explicarlo.
+ Built on iii engine
+
+ Memoria persistente para Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode y cualquier cliente MCP.
+
+ El gist extiende el patrón LLM Wiki de Karpathy con puntuación de confianza, ciclo de vida, grafos de conocimiento y búsqueda híbrida: agentmemory es la implementación.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+O mediante `npx` (sin instalación):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Aviso — npx cachea por versión. Si un simple `npx @agentmemory/agentmemory` sirve una versión antigua, fuerza la última con `npx -y @agentmemory/agentmemory@latest`, o limpia la caché una vez con `rm -rf ~/.npm/_npx` (macOS/Linux; en Windows borra `%LOCALAPPDATA%\npm-cache\_npx`). La primera ejecución vía npx desde la v0.9.16+ pregunta si deseas instalar globalmente, de modo que el comando `agentmemory` quede disponible en cualquier lugar.
+
+Todas las opciones en [Inicio rápido](#quick-start) más abajo. Conexión específica por agente en [Funciona con cualquier agente](#works-with-every-agent).
+
+---
+
+
+
+agentmemory funciona con cualquier agente que soporte hooks, MCP o REST API. Todos los agentes comparten el mismo servidor de memoria.
+
+
+
+
+
+Claude Code
+native plugin + 12 hooks + MCP
+
+
+
+Codex CLI
+native plugin + 6 hooks + MCP
+
+
+
+OpenClaw
+native plugin + MCP
+
+
+
+Hermes
+native plugin + MCP
+
+
+
+pi
+native plugin + MCP
+
+
+
+OpenHuman
+native Memory trait backend
+
+
+
+Cursor
+MCP server
+
+
+
+Gemini CLI
+MCP server
+
+
+
+
+
+OpenCode
+22 hooks + MCP + plugin
+
+
+
+Cline
+MCP server
+
+
+
+Goose
+MCP server
+
+
+
+Kilo Code
+MCP server
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP server
+
+
+
+Windsurf
+MCP server
+
+
+
+Roo Code
+MCP server
+
+
+
+
+
+ Funciona con cualquier agente que hable MCP o HTTP. Un único servidor, memorias compartidas entre todos ellos.
+
+
+---
+
+Vuelves a explicar la misma arquitectura cada sesión. Vuelves a descubrir los mismos bugs. Vuelves a enseñar las mismas preferencias. La memoria integrada (CLAUDE.md, .cursorrules) se topa con un techo de 200 líneas y se queda obsoleta. agentmemory soluciona esto. Captura silenciosamente lo que hace tu agente, lo comprime en una memoria buscable e inyecta el contexto correcto al inicio de la siguiente sesión. Un único comando. Funciona en todos los agentes.
+
+**Qué cambia:** En la sesión 1 configuras autenticación JWT. En la sesión 2 pides rate limiting. El agente ya sabe que tu autenticación usa el middleware jose en `src/middleware/auth.ts`, que tus pruebas cubren la validación de tokens y que elegiste jose en lugar de jsonwebtoken por compatibilidad con Edge. Sin volver a explicar. Sin copiar y pegar. El agente simplemente lo *sabe*.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **Novedad en v0.9.0** — Sitio de aterrizaje en [agent-memory.dev](https://agent-memory.dev), conector de sistema de ficheros (`@agentmemory/fs-watcher`), el MCP standalone ahora hace de proxy al servidor en ejecución, por lo que los hooks y el visor coinciden, política de auditoría codificada en cada ruta de borrado, y health deja de marcar `memory_critical` en procesos Node pequeños. Notas completas en [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18).
+
+---
+
+
+
+
+
+
+
+### Precisión de recuperación
+
+**coding-agent-life-v1** (corpus interno, reproducible en sandbox)
+
+| Adaptador | P@5 | R@5 | Tasa de aciertos top-5 | Latencia p50 |
+|---|---|---|---|---|
+| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms |
+| grep baseline | 0.267 | 0.967 | 15 / 15 | 0 ms |
+
+Tasa de aciertos top-5 del 100%. Precisión **2,2×** mejor que la baseline grep con la misma entrada. Desglose completo por tipo: [`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 preguntas)
+
+| Sistema | R@5 | R@10 | MRR |
+|---|---|---|---|
+| **agentmemory** | **95.2%** | **98.6%** | **88.2%** |
+| BM25-only fallback | 86.2% | 94.6% | 71.5% |
+
+
+
+> Modelo de embedding: `all-MiniLM-L6-v2` (local, gratuito, sin API key). Informes completos: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Comparativa con la competencia: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory frente a mem0, Letta, Khoj, claude-mem, Hippo.
+
+**Reproduce en local:** [`eval/README.md`](../eval/README.md) — un harness con adaptadores intercambiables para LongMemEval `_s` (500-Q públicas) y `coding-agent-life-v1` (corpus interno de 15 sesiones). Los adaptadores grep / vector / agentmemory se puntúan en paralelo, salida NDJSON, y las scorecards publicadas quedan en [`docs/benchmarks/`](../docs/benchmarks/).
+
+**Funciona muy bien con [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) y [Graphify](https://github.com/safishamsi/graphify).** Indexado de grafos de código, pipelines de build multiagente y grafos de conocimiento más amplios sobre documentos / PDFs / imágenes / vídeos. agentmemory recuerda el trabajo; esos tres proyectos iluminan el resto de la capa de contexto. Recetas y tabla de enrutamiento por pregunta: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
Built-in (CLAUDE.md)
+
+
+
Tipo
+
Motor de memoria + servidor MCP
+
API de capa de memoria
+
Runtime de agente completo
+
Fichero estático
+
+
+
Retrieval R@5
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
N/A (grep)
+
+
+
Captura automática
+
12 hooks (esfuerzo manual cero)
+
Llamadas manuales a add()
+
El agente se edita a sí mismo
+
Edición manual
+
+
+
Búsqueda
+
BM25 + Vector + Graph (fusión RRF)
+
Vector + Graph
+
Vector (archival)
+
Carga todo en contexto
+
+
+
Multiagente
+
MCP + REST + leases + signals
+
API (sin coordinación)
+
Solo dentro del runtime de Letta
+
Ficheros por agente
+
+
+
Dependencia de framework
+
Ninguna (cualquier cliente MCP)
+
Ninguna
+
Alta (obliga a usar Letta)
+
Formato por agente
+
+
+
Dependencias externas
+
Ninguna (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + BD vectorial
+
Ninguna
+
+
+
Ciclo de vida de memoria
+
Consolidación de 4 niveles + decaimiento + auto-olvido
+
Extracción pasiva
+
Gestionado por el agente
+
Poda manual
+
+
+
Eficiencia de tokens
+
~1.900 tokens/sesión ($10/año)
+
Varía según la integración
+
Memoria principal en contexto
+
22K+ tokens con 240 obs
+
+
+
Visor en tiempo real
+
Sí (port 3113)
+
Dashboard en la nube
+
Dashboard en la nube
+
No
+
+
+
Self-hosted
+
Sí (por defecto)
+
Opcional
+
Opcional
+
Sí
+
+
+
+---
+
+
+
+Compatibilidad: esta release apunta a `iii-sdk` estable `^0.11.0` e iii-engine v0.11.x.
+
+### Pruébalo en 30 segundos
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo` siembra 3 sesiones realistas (autenticación JWT, corrección de N+1 queries, rate limiting) y ejecuta búsquedas semánticas sobre ellas. Verás cómo encuentra "N+1 query fix" al buscar "database performance optimization" — algo que la coincidencia por palabra clave no puede hacer.
+
+Abre `http://localhost:3113` para ver cómo se construye la memoria en directo.
+
+### Recomendado: instala globalmente
+
+`npx` cachea por versión. Si la semana pasada ejecutaste `npx @agentmemory/agentmemory@0.9.14`, un simple `npx @agentmemory/agentmemory` puede servir la versión obsoleta 0.9.14 desde `~/.npm/_npx/`, y no la última. Instala una vez y el comando `agentmemory` funciona en cualquier sitio:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+A partir de v0.9.16, la primera ejecución vía npx pregunta si deseas instalar globalmente — responde `Y` una vez y listo. Si lo saltas, recurre a cualquiera de estos para un fetch limpio:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+En Windows / PowerShell, el equivalente para limpiar caché es `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — la opción `npx -y ...@latest` de arriba es la alternativa multiplataforma.
+
+### Session Replay
+
+Toda sesión que agentmemory registra es reproducible. Abre el visor, elige la pestaña **Replay** y desplázate por la línea de tiempo: prompts, llamadas a herramientas, resultados y respuestas se renderizan como eventos discretos con play/pause, control de velocidad (0,5×–4×) y atajos de teclado (espacio para alternar, flechas para avanzar paso a paso).
+
+¿Ya tienes transcripciones JSONL antiguas de Claude Code que quieras importar?
+
+```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
+```
+
+Las sesiones importadas aparecen en el selector de Replay junto a las nativas. Por debajo, cada entrada se enruta a través de las funciones iii `mem::replay::load`, `mem::replay::sessions` y `mem::replay::import-jsonl` — sin servidores side-channel.
+
+### Actualización / Mantenimiento
+
+Usa el comando de mantenimiento cuando intencionadamente quieras actualizar tu runtime local:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Aviso: este comando muta el workspace/runtime actual. Puede actualizar dependencias de JavaScript, puede ejecutar `cargo install iii-engine --force`, y puede traer imágenes Docker.
+
+Los detalles de implementación están en `src/cli.ts` (ver `runUpgrade` en torno a la región `src/cli.ts:544-595`).
+
+### Claude Code (un bloque, pégalo)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 sin instalar el plugin (ruta MCP standalone)
+
+Si conectas el servidor MCP de agentmemory directamente vía `~/.claude.json` en lugar de usar `/plugin install`, Claude Code nunca resuelve `${CLAUDE_PLUGIN_ROOT}` y tienes que apuntar los scripts de hook a rutas absolutas en `~/.claude/settings.json`. Esas rutas suelen incluir la versión de agentmemory (p. ej. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), por lo que la siguiente actualización rompe silenciosamente todos los hooks ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Solución:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Esto fusiona los mismos comandos de hook en `~/.claude/settings.json` con rutas absolutas que apuntan al directorio `plugin/` empaquetado del paquete `@agentmemory/agentmemory` actualmente instalado. Vuelve a ejecutar el comando tras actualizar agentmemory para refrescar las rutas. Las entradas de usuario en el mismo fichero se preservan; solo se reemplazan las entradas previas de agentmemory. La ruta vía `/plugin install` sigue siendo la recomendada.
+Para despliegues remotos o protegidos, lanza Claude Code con `AGENTMEMORY_URL` y `AGENTMEMORY_SECRET` definidos. El plugin pasa ambos valores a su servidor MCP empaquetado; cuando `AGENTMEMORY_URL` está vacío, el shim MCP usa `http://localhost:3111`.
+
+### Codex CLI (plataforma de plugins Codex)
+
+```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
+```
+
+El plugin de Codex se sirve desde el mismo directorio `plugin/` que el de Claude Code. Registra:
+
+- `@agentmemory/mcp` como servidor MCP (hace de proxy a las 51 tools cuando `AGENTMEMORY_URL` apunta a un servidor agentmemory en ejecución; cae a 7 tools en local cuando no hay servidor accesible)
+- 6 hooks de ciclo de vida: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skills: `/recall`, `/remember`, `/session-history`, `/forget`
+
+El motor de hooks de Codex inyecta `CLAUDE_PLUGIN_ROOT` en los subprocesos de hook (según [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), por lo que los mismos scripts de hook funcionan en ambos hosts sin duplicación. Los eventos Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure son exclusivos de Claude Code y no se registran para Codex.
+
+#### Codex Desktop: los hooks del plugin están silenciados (con workaround)
+
+`CodexHooks` y `PluginHooks` son estables y están activados por defecto en [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), pero las builds actuales de Codex Desktop no despachan el `hooks.json` local del plugin ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). Las tools MCP siguen funcionando; solo faltan las observaciones del ciclo de vida.
+
+Hasta que se solucione upstream, replica los mismos comandos de hook en el `~/.codex/hooks.json` global:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Esto añade un bloque idempotente a `~/.codex/hooks.json` que referencia rutas absolutas a los scripts empaquetados (no hace falta expandir `${CLAUDE_PLUGIN_ROOT}` en el ámbito de usuario). Vuelve a ejecutar el mismo comando tras actualizar agentmemory para refrescar las rutas. Las entradas de usuario en el mismo fichero se preservan; solo se reemplazan las entradas previas de agentmemory.
+
+
+OpenClaw (pega este 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 51 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`.
+```
+
+Guía completa: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (pega este 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 51 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.
+```
+
+Guía completa: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Otros agentes
+
+Arranca el servidor de memoria: `npx @agentmemory/agentmemory`
+
+La entrada de agentmemory es el **mismo bloque de servidor MCP** en cada host que use la forma `mcpServers` (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw):
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Fusiona esta entrada en el objeto `mcpServers` existente** en el fichero de configuración del host — no reemplaces el fichero. Si el fichero ya contiene otros servidores, añade `agentmemory` junto a ellos como otra clave dentro de `mcpServers`. Si `mcpServers` no existe, pega el bloque dentro de `{ "mcpServers": { ... } }`. Los marcadores `${VAR}` heredan `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` del shell al lanzar el servidor MCP — si no están definidas se pasan como cadena vacía y el shim cae a `http://localhost:3111`. Una sola entrada cubre tanto despliegues locales como remotos (k8s / con reverse-proxy).
+
+| Agente | Fichero de configuración | Notas |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | Fusiona en `mcpServers`. También hay deeplink de un clic en el sitio web. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Fusiona en `mcpServers`. Reinicia Claude Desktop tras editar. |
+| **Cline / Roo Code / Kilo Code** | Ajustes MCP de Cline (Settings UI → MCP Servers → Edit) | Mismo bloque `mcpServers`. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Mismo bloque `mcpServers`. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (fusión automática). |
+| **OpenClaw** | Configuración MCP de OpenClaw | Mismo bloque `mcpServers`, o usa el [memory plugin](../integrations/openclaw/) más profundo. |
+| **Codex CLI (solo MCP)** | `.codex/config.toml` | Forma TOML: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, o añade `[mcp_servers.agentmemory]` a mano. |
+| **Codex CLI (plugin completo)** | Marketplace de plugins Codex | `codex plugin marketplace add rohitg00/agentmemory` y luego `codex plugin add agentmemory@agentmemory`. Registra MCP + 6 hooks de ciclo de vida (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. En Codex Desktop, ejecuta también `agentmemory connect codex --with-hooks` hasta que se mergee [openai/codex#16430](https://github.com/openai/codex/issues/16430) — los hooks de plugin están silenciados allí. |
+| **OpenCode (solo MCP)** | `opencode.json` | Forma distinta — clave `mcp` en el nivel superior, comando como array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (plugin completo)** | `plugin/opencode/` | 22 hooks de captura automática que cubren ciclo de vida de sesión, mensajes, tools y errores. Dos comandos slash (`/recall`, `/remember`). Copia `plugin/opencode/` a tu workspace de OpenCode y añade la entrada del plugin a `opencode.json`. Tabla completa de hooks + análisis de gaps en [`plugin/opencode/README.md`](../plugin/opencode/README.md). |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | Copia [`integrations/pi`](../integrations/pi/) y reinicia pi. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Usa el [memory provider plugin](../integrations/hermes/) más profundo con `memory.provider: agentmemory`. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` escribe el bloque `mcpServers` estándar. El payload de los hooks es compatible a nivel de campo con Claude Code, así que los scripts de los 12 hooks existentes funcionan sin modificación — conéctalos en la sección `hooks` del mismo `settings.json`. |
+| **Antigravity** (sustituye a Gemini CLI) | `mcp_config.json` (en el directorio User de Antigravity) | `agentmemory connect antigravity` escribe el bloque `mcpServers` estándar. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Úsalo tras el sunset de Gemini CLI del 2026-06-18. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` escribe la configuración de nivel usuario. Los overrides por workspace van en `.kiro/settings/mcp.json` junto a tu código. |
+| **Goose** | UI de ajustes MCP de Goose | Mismo bloque `mcpServers`. |
+| **Aider** | n/a | Habla directamente con la REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Cualquier agente (32+)** | n/a | `npx skillkit install agentmemory` auto-detecta el host y fusiona. |
+
+**Clientes MCP en sandbox** (Flatpak / Snap / contenedores restrictivos) que no pueden alcanzar el `localhost` del host: añade también `"AGENTMEMORY_FORCE_PROXY": "1"` al bloque `env`, y apunta `AGENTMEMORY_URL` a una ruta que el sandbox sí pueda alcanzar (p. ej. tu IP de LAN). Consulta [#234](https://github.com/rohitg00/agentmemory/issues/234) para el walkthrough de diagnóstico.
+
+### Acceso programático (Python / Rust / Node)
+
+agentmemory registra sus operaciones principales como funciones iii (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Cualquier lenguaje con un SDK iii puede llamarlas directamente sobre `ws://localhost:49134` — sin un cliente REST separado por lenguaje.
+
+```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"},
+})
+```
+
+Ejemplo trabajado: [`examples/python/`](../examples/python/) (quickstart + flujo de observación/recall). La REST en `:3111` sigue disponible para hosts sin runtime iii.
+
+### Desde el código fuente
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Esto arranca agentmemory con un `iii-engine` local si `iii` ya está instalado, o cae a Docker Compose si hay Docker disponible. REST, streams y el visor se enlazan a `127.0.0.1` por defecto.
+
+Instala `iii-engine` manualmente. **agentmemory actualmente fija `iii-engine` a `v0.11.2`** — `v0.11.6` introduce un nuevo modelo que sandboxea todo vía `iii worker add`, y agentmemory aún no se ha refactorizado para él. La fijación se levantará cuando aterrice el refactor. Sobrescribe con `AGENTMEMORY_III_VERSION=` si has migrado al modelo sandbox manualmente.
+
+- **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:** cambia `aarch64-apple-darwin` por `x86_64-apple-darwin`
+- **Linux x64:** cambia por `x86_64-unknown-linux-gnu`
+- **Linux arm64:** cambia por `aarch64-unknown-linux-gnu`
+- **Windows:** descarga `iii-x86_64-pc-windows-msvc.zip` desde [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extrae `iii.exe`, añádelo al PATH
+
+O usa Docker (el `docker-compose.yml` empaquetado descarga `iiidev/iii:0.11.2`). Documentación completa: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory funciona en Windows 10/11, pero el paquete de Node.js por sí solo no es suficiente — también necesitas el runtime `iii-engine` (un binario nativo aparte) como proceso en segundo plano. El instalador oficial upstream es un script `sh` y hoy no existe un instalador PowerShell ni paquete scoop/winget, así que los usuarios de Windows tienen dos rutas:
+
+**Opción A — Binario Windows preconstruido (recomendado):**
+
+```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
+```
+
+**Opción 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
+```
+
+**Opción C — Solo MCP standalone (sin engine):** si solo necesitas las tools MCP para tu agente y no necesitas la REST API, el visor ni los cron jobs, sáltate el engine por completo:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Diagnóstico para Windows:** si `npx @agentmemory/agentmemory` falla, vuelve a ejecutar con `--verbose` para ver el stderr real del engine. Modos de fallo habituales:
+
+| Síntoma | Solución |
+|---|---|
+| `iii-engine process started` seguido de `did not become ready within 15s` | El engine ha crasheado al arrancar — reejecuta con `--verbose` y revisa stderr |
+| `Could not start iii-engine` | Ni `iii.exe` ni Docker están instalados. Ver Opción A o B |
+| Conflicto de puerto | `netstat -ano \| findstr :3111` para ver qué está vinculado, mátalo o usa `--port ` |
+| Se omite el fallback a Docker aunque Docker esté instalado | Asegúrate de que Docker Desktop esté efectivamente en ejecución (icono en la bandeja del sistema) |
+
+> Nota: no existe `cargo install iii-engine` — `iii` no está publicado en crates.io. Los únicos métodos de instalación soportados son el binario preconstruido de arriba, el script `sh` upstream (solo macOS/Linux) y la imagen Docker.
+
+---
+
+
Deploy
+
+Plantillas de un clic para hosts gestionados. Cada una incluye un
+Dockerfile autocontenido que descarga `@agentmemory/agentmemory` desde npm
+y copia el binario del iii engine desde la imagen oficial `iiidev/iii` de
+Docker Hub — no se requiere una imagen preconstruida de agentmemory. El
+almacenamiento persistente se monta en `/data`; el entrypoint del primer
+arranque sobrescribe la configuración iii empaquetada por npm (que se
+enlaza a `127.0.0.1`) por una afinada para despliegue que se enlaza a
+`0.0.0.0` y usa rutas absolutas `/data`, genera el secreto HMAC y
+baja privilegios de `root` a `node` con `gosu` antes de hacer exec
+del CLI de agentmemory.
+
+
+
+
+
+
+El botón de despliegue de un clic de Render requiere un `render.yaml` en la raíz del repo, que mantenemos limpio a propósito. Usa el flujo Render Blueprint documentado en [`deploy/render/`](../deploy/render/README.md) para apuntar al blueprint del repo manualmente.
+
+Los detalles completos de configuración (captura HMAC, túnel SSH del visor, rotación, backup, mínimos de coste) están en [`deploy/`](../deploy/README.md):
+
+- [`deploy/fly`](../deploy/fly/README.md) — máquina única con `auto_stop_machines = "stop"`; más barato en idle.
+- [`deploy/railway`](../deploy/railway/README.md) — tarifa plana del plan Hobby, volumen en el dashboard.
+- [`deploy/render`](../deploy/render/README.md) — flujo Blueprint, snapshots automáticos de disco en planes de pago.
+- [`deploy/coolify`](../deploy/coolify/README.md) — self-hosted en tu propio VPS vía [Coolify](https://coolify.io/self-hosted); misma stack Docker Compose, tú eres dueño del host y los datos.
+
+Solo se publica el puerto `3111`. El visor en `3113` permanece enlazado a loopback dentro del contenedor — el README de cada plantilla documenta el patrón de túnel SSH para alcanzarlo.
+
+---
+
+
+
+Todo agente de codificación olvida todo al terminar la sesión. Pierdes los primeros 5 minutos de cada sesión re-explicando tu stack. agentmemory corre en segundo plano y lo elimina por completo.
+
+```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.
+```
+
+### Frente a la memoria integrada del agente
+
+Todo agente de codificación con IA viene con memoria integrada — Claude Code tiene `MEMORY.md`, Cursor tiene notepads, Cline tiene memory bank. Funcionan como notas adhesivas. agentmemory es la base de datos buscable que hay detrás de esas notas adhesivas.
+
+| | Integrada (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Escala | tope de 200 líneas | Ilimitado |
+| Búsqueda | Carga todo en contexto | BM25 + vector + graph (solo top-K) |
+| Coste en tokens | 22K+ con 240 observaciones | ~1.900 tokens (92% menos) |
+| Cross-agent | Ficheros por agente | MCP + REST (cualquier agente) |
+| Coordinación | Ninguna | Leases, signals, actions, routines |
+| Observabilidad | Lectura manual de ficheros | Visor en tiempo real en :3113 |
+
+---
+
+
+
+### Pipeline de memoria
+
+```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
+```
+
+### Consolidación de memoria en 4 niveles
+
+Inspirada en cómo el cerebro humano procesa la memoria — no muy diferente de la consolidación del sueño.
+
+| Nivel | Qué | Analogía |
+|------|------|---------|
+| **Working** | Observaciones crudas a partir del uso de tools | Memoria a corto plazo |
+| **Episodic** | Resúmenes de sesión comprimidos | "Qué pasó" |
+| **Semantic** | Hechos y patrones extraídos | "Lo que sé" |
+| **Procedural** | Workflows y patrones de decisión | "Cómo hacerlo" |
+
+Las memorias decaen con el tiempo (curva de Ebbinghaus). Las memorias accedidas con frecuencia se refuerzan. Las memorias obsoletas se evictan automáticamente. Las contradicciones se detectan y resuelven.
+
+### Qué se captura
+
+| Hook | Captura |
+|------|----------|
+| `SessionStart` | Ruta de proyecto, ID de sesión |
+| `UserPromptSubmit` | Prompts del usuario (con filtro de privacidad) |
+| `PreToolUse` | Patrones de acceso a ficheros + contexto enriquecido |
+| `PostToolUse` | Nombre de la tool, entrada, salida |
+| `PostToolUseFailure` | Contexto del error |
+| `PreCompact` | Re-inyecta memoria antes de la compactación |
+| `SubagentStart/Stop` | Ciclo de vida de sub-agentes |
+| `Stop` | Resumen de fin de sesión |
+| `SessionEnd` | Marcador de sesión completa |
+
+### Capacidades clave
+
+| Capacidad | Descripción |
+|---|---|
+| **Captura automática** | Cada uso de tool registrado vía hooks — esfuerzo manual cero |
+| **Búsqueda semántica** | BM25 + vector + grafo de conocimiento con fusión RRF |
+| **Evolución de memoria** | Versionado, supersesión, grafos de relaciones |
+| **Auto-olvido** | Expiración por TTL, detección de contradicciones, evicción por importancia |
+| **Privacy first** | API keys, secretos y etiquetas `` se eliminan antes del almacenado |
+| **Self-healing** | Circuit breaker, cadena de fallback de proveedores, monitorización de salud |
+| **Puente Claude** | Sincronización bidireccional con MEMORY.md |
+| **Grafo de conocimiento** | Extracción de entidades + recorrido BFS |
+| **Memoria de equipo** | Espacios compartidos y privados con namespace por miembro |
+| **Provenance de citas** | Traza cualquier memoria de vuelta a las observaciones origen |
+| **Snapshots de Git** | Versiona, revierte y diffea el estado de memoria |
+
+---
+
+
+
+Recuperación de triple stream combinando tres señales:
+
+| Stream | Qué hace | Cuándo |
+|---|---|---|
+| **BM25** | Coincidencia por palabras con stemming y expansión de sinónimos | Siempre activo |
+| **Vector** | Similitud coseno sobre embeddings densos | Proveedor de embeddings configurado |
+| **Graph** | Recorrido del grafo de conocimiento vía coincidencia de entidades | Entidades detectadas en la consulta |
+
+Fusionado con Reciprocal Rank Fusion (RRF, k=60) y diversificado por sesión (máximo 3 resultados por sesión).
+
+BM25 tokeniza griego, cirílico, hebreo, árabe y latín con tildes de serie. Para memorias en chino / japonés / coreano, instala los segmentadores opcionales (`npm install @node-rs/jieba tiny-segmenter`) para partir los runs CJK en tokens a nivel de palabra; sin ellos, agentmemory hace soft-fallback a tokenización por run completo y muestra una pista única en stderr.
+
+### Proveedores de embedding
+
+agentmemory autodetecta tu proveedor. Para mejores resultados, instala embeddings locales (gratis):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Proveedor | Modelo | Coste | Notas |
+|---|---|---|---|
+| **Local (recomendado)** | `all-MiniLM-L6-v2` | Gratis | Offline, +8pp de recall sobre BM25-only |
+| Gemini | `gemini-embedding-001` | Free tier | 100+ idiomas, 768/1536/3072 dims (MRL), entrada de 2048 tokens. Sustituye a `text-embedding-004` ([deprecado, cierre el 14 ene 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | $0.02/1M | Máxima calidad |
+| Voyage AI | `voyage-code-3` | De pago | Optimizado para código |
+| Cohere | `embed-english-v3.0` | Trial gratis | Uso general |
+| OpenRouter | Cualquier modelo | Varía | Proxy multi-modelo |
+
+---
+
+
+
+53 tools, 6 recursos, 3 prompts y 4 skills — el toolkit MCP de memoria más completo para cualquier agente.
+
+> **Shim MCP vs servidor completo:** el paquete publicado `@agentmemory/mcp` es un shim ligero. Expone la superficie completa de 51 tools **solo cuando puede alcanzar un servidor agentmemory en ejecución** vía `AGENTMEMORY_URL` (modo proxy). Sin servidor accesible, el shim cae a un set local de 7 tools (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). La variable de entorno `AGENTMEMORY_TOOLS=core|all` es un flag *del lado del servidor* — definirla en el bloque `env` del shim no tiene efecto. Si ves solo 7 tools en Cursor / OpenCode / Gemini CLI, arranca `npx @agentmemory/agentmemory` (o la stack Docker) y define `AGENTMEMORY_URL=http://localhost:3111`.
+
+### 51 Tools
+
+
+Tools principales (siempre disponibles)
+
+| Tool | Descripción |
+|------|-------------|
+| `memory_recall` | Busca observaciones pasadas |
+| `memory_compress_file` | Comprime ficheros markdown preservando la estructura |
+| `memory_save` | Guarda un insight, decisión o patrón |
+| `memory_patterns` | Detecta patrones recurrentes |
+| `memory_smart_search` | Búsqueda híbrida semántica + por palabras |
+| `memory_file_history` | Observaciones pasadas sobre ficheros concretos |
+| `memory_sessions` | Lista sesiones recientes |
+| `memory_timeline` | Observaciones cronológicas |
+| `memory_profile` | Perfil de proyecto (conceptos, ficheros, patrones) |
+| `memory_export` | Exporta todos los datos de memoria |
+| `memory_relations` | Consulta el grafo de relaciones |
+
+
+
+
+Tools extendidas (51 en total — define AGENTMEMORY_TOOLS=all)
+
+| Tool | Descripción |
+|------|-------------|
+| `memory_patterns` | Detecta patrones recurrentes |
+| `memory_timeline` | Observaciones cronológicas |
+| `memory_relations` | Consulta el grafo de relaciones |
+| `memory_graph_query` | Recorrido del grafo de conocimiento |
+| `memory_consolidate` | Ejecuta la consolidación de 4 niveles |
+| `memory_claude_bridge_sync` | Sincroniza con MEMORY.md |
+| `memory_team_share` | Comparte con miembros del equipo |
+| `memory_team_feed` | Elementos compartidos recientes |
+| `memory_audit` | Pista de auditoría de operaciones |
+| `memory_governance_delete` | Borrado con pista de auditoría |
+| `memory_snapshot_create` | Snapshot versionado en Git |
+| `memory_action_create` | Crea ítems de trabajo con dependencias |
+| `memory_action_update` | Actualiza estado de una action |
+| `memory_frontier` | Actions desbloqueadas, ordenadas por prioridad |
+| `memory_next` | La única acción más importante a continuación |
+| `memory_lease` | Leases exclusivos de actions (multiagente) |
+| `memory_routine_run` | Instancia rutinas de workflow |
+| `memory_signal_send` | Mensajería entre agentes |
+| `memory_signal_read` | Lee mensajes con acuse de recibo |
+| `memory_checkpoint` | Gates de condiciones externas |
+| `memory_mesh_sync` | Sincronización P2P entre instancias |
+| `memory_sentinel_create` | Watchers dirigidos por eventos |
+| `memory_sentinel_trigger` | Dispara sentinels desde fuera |
+| `memory_sketch_create` | Grafos de actions efímeros |
+| `memory_sketch_promote` | Promociona a permanente |
+| `memory_crystallize` | Compacta cadenas de actions |
+| `memory_diagnose` | Health checks |
+| `memory_heal` | Repara automáticamente estado atascado |
+| `memory_facet_tag` | Tags dimension:value |
+| `memory_facet_query` | Consulta por tags de facet |
+| `memory_verify` | Traza provenance |
+
+
+
+### 6 Recursos · 3 Prompts · 4 Skills
+
+| Tipo | Nombre | Descripción |
+|------|------|-------------|
+| Resource | `agentmemory://status` | Salud, conteo de sesiones, conteo de memorias |
+| Resource | `agentmemory://project/{name}/profile` | Inteligencia por proyecto |
+| Resource | `agentmemory://memories/latest` | Las 10 memorias activas más recientes |
+| Resource | `agentmemory://graph/stats` | Estadísticas del grafo de conocimiento |
+| Prompt | `recall_context` | Búsqueda + devuelve mensajes de contexto |
+| Prompt | `session_handoff` | Datos de traspaso entre agentes |
+| Prompt | `detect_patterns` | Analiza patrones recurrentes |
+| Skill | `/recall` | Busca en memoria |
+| Skill | `/remember` | Guarda en memoria a largo plazo |
+| Skill | `/session-history` | Resúmenes recientes de sesiones |
+| Skill | `/forget` | Borra observaciones/sesiones |
+
+### MCP standalone
+
+Ejecútalo sin el servidor completo — para cualquier cliente MCP. Cualquiera de estos funciona:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+O añádelo a la configuración MCP de tu agente:
+
+La mayoría de los agentes (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+Fusiona la entrada `agentmemory` en el objeto `mcpServers` existente del host en lugar de reemplazar el fichero. Para clientes en sandbox que no pueden alcanzar el `localhost` del host, añade `"AGENTMEMORY_FORCE_PROXY": "1"` al bloque env y define `AGENTMEMORY_URL` a una ruta a la que el sandbox sí pueda llegar.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Copia el fichero del plugin desde el repo:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Se inicia automáticamente en el puerto `3113`. Stream de observaciones en vivo, explorador de sesiones, navegador de memoria, visualización del grafo de conocimiento y dashboard de salud.
+
+```bash
+open http://localhost:3113
+```
+
+El servidor del visor se enlaza a `127.0.0.1` por defecto. El endpoint servido por REST `/agentmemory/viewer` sigue las reglas habituales de bearer-token `AGENTMEMORY_SECRET`. Las cabeceras CSP usan un nonce de script por respuesta y desactivan los atributos handler inline (`script-src-attr 'none'`).
+
+---
+
+
+
+El visor en `:3113` muestra lo que tu agente **recordó**. La [iii console](https://iii.dev/docs/console) muestra lo que tu agente **hizo** — cada operación de memoria como una traza OpenTelemetry, cada entrada KV editable, cada función invocable, cada stream tappable. Dos ventanas sobre la misma memoria: una con forma de producto, otra con forma de motor.
+
+Mira cómo se dispara `memory_smart_search` y observa el escaneo BM25 → consulta de embedding → fusión RRF → reranker como un waterfall. Edita un temporizador de consolidación atascado en el navegador KV. Reproduce un hook `PostToolUse` con un payload ajustado. Fija el stream WebSocket y mira cómo aterrizan las observaciones en vivo.
+
+agentmemory ofrece esto gratis porque cada función, trigger, scope de estado y stream es un primitivo de iii — nada custom, nada que instrumentar.
+
+
+
+
+ Página Workers: cada worker conectado — incluida agentmemory — con PID, conteo de funciones, runtime y last-seen.
+
+
+**Ya instalada.** La console se incluye con `iii` — sin instalador aparte.
+
+**Lánzala junto a 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
+```
+
+Luego abre `http://localhost:3114`. Añade `--enable-flow` para la página experimental de grafo de arquitectura.
+
+Sobrescribe endpoints del engine solo si los has movido:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Qué puedes hacer desde la console:**
+
+| Página | Úsala para |
+|------|-----------|
+| **Workers** | Ver todos los workers conectados y sus métricas en vivo — incluyendo el propio worker de agentmemory. |
+| **Functions** | Invocar cualquier función de agentmemory directamente con un payload JSON — útil para probar `memory.recall`, `memory.consolidate`, `graph.query` sin cablear un cliente. |
+| **Triggers** | Reproducir triggers HTTP, cron, event y state — disparar manualmente el cron de consolidación, reintentar una ruta HTTP, emitir un cambio de estado. |
+| **States** | Navegador KV con CRUD completo — sesiones, slots de memoria, temporizadores del ciclo de vida, índice de embeddings — edita valores in-place. |
+| **Streams** | Monitor WebSocket en vivo para escrituras de memoria, eventos de hooks y actualizaciones de observaciones a medida que fluyen por los streams de iii. |
+| **Queues** | Topics de cola duraderas + gestión de dead-letter. Reproduce o descarta jobs fallidos de embedding / compresión. |
+| **Traces** | Vistas OpenTelemetry waterfall / flame / desglose por servicio. Filtra por `trace_id` para ver exactamente qué funciones, llamadas a BD y peticiones de embedding produjo un único `memory.search`. |
+| **Logs** | Logs OTEL estructurados, filtrados y correlados con trace/span IDs. |
+| **Config** | Configuración de runtime — ve exactamente con qué workers, proveedores y puertos está ejecutando tu engine. |
+| **Flow** | (Opcional, `--enable-flow`) Grafo de arquitectura interactivo de cada worker, trigger y stream. |
+
+
+
+
+ Traces: waterfall / flame / desglose por servicio para cada operación de memoria.
+
+
+**Las trazas ya están activas:**
+
+`iii-config.yaml` se sirve con el worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 1.0`, métricas + logs). No se necesita configuración adicional — desde el momento en que agentmemory arranca, cada operación de memoria emite una traza-span y un log estructurado que la console puede leer.
+
+Si quieres exportar a Jaeger/Honeycomb/Grafana Tempo en su lugar, cambia `exporter: memory` por `exporter: otlp` y define el endpoint del collector según la documentación de observabilidad de iii.
+
+> **Aviso:** la console en sí no impone auth — mantenla enlazada a `127.0.0.1` (por defecto) y nunca la expongas públicamente.
+
+---
+
+
+
+agentmemory **ya es una instancia [iii](https://iii.dev) en ejecución**. Funciones, triggers, estado KV, streams, trazas OTEL — todo son primitivos de iii. No has instalado Postgres, Redis, Express, pm2 ni Prometheus, porque iii los reemplaza.
+
+Eso significa que un comando más extiende agentmemory con una capacidad completamente nueva.
+
+### Extiende agentmemory con un comando
+
+```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
+```
+
+Cada `iii worker add` registra nuevas funciones y triggers en el mismo engine en el que agentmemory ya está corriendo. El visor y la console los detectan al instante — sin recargar, sin nueva integración, sin nuevo contenedor.
+
+| `iii worker add` | Qué obtienes encima de agentmemory |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Memoria multi-instancia: cada `remember` se difunde, cada `search` lee la unión |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Ciclo de vida programado — consolidación nocturna, snapshots semanales, decaimiento en un reloj fijo |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Reintentos duraderos: los jobs de embedding + compresión fallidos sobreviven al reinicio, sin observaciones perdidas |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Trazas OTEL, métricas y logs en cada función — cableado en `iii-config.yaml` desde el primer día |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | El código salido de `memory_recall` corre dentro de una VM desechable, no en tu shell |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptador de estado respaldado por SQL cuando te quedas pequeño con el KV in-memory por defecto |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | Levanta servidores MCP adicionales junto al MCP de agentmemory, compartiendo el mismo engine |
+
+Registro completo: [workers.iii.dev](https://workers.iii.dev). Cada worker allí se compone a través de los mismos primitivos que usa agentmemory — y el agentmemory que ya tienes es uno de ellos.
+
+### Qué reemplaza iii
+
+| Stack tradicional | agentmemory usa |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + índice vectorial in-memory |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | Supervisión de workers del iii engine |
+| Prometheus / Grafana | iii OTEL + monitor de salud |
+| Sistemas de plugins propios | `iii worker add ` |
+
+**118 ficheros de código · ~21.800 LOC · 950+ tests · 123 funciones · 34 scopes KV** — todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo.
+
+---
+
+
+
+### Proveedores de LLM
+
+agentmemory autodetecta desde tu entorno. Por defecto no se hacen llamadas LLM a menos que configures un proveedor o aceptes explícitamente el fallback de suscripción de Claude.
+
+| Proveedor | Configuración | Notas |
+|----------|--------|-------|
+| **No-op (por defecto)** | Sin configuración | Compresión/resumen vía LLM DESACTIVADA. La compresión sintética BM25 + recall siguen funcionando. Mira `AGENTMEMORY_ALLOW_AGENT_SDK` más abajo si dependías del fallback de suscripción de Claude. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Facturación por token |
+| MiniMax | `MINIMAX_API_KEY` | Compatible con Anthropic |
+| Gemini | `GEMINI_API_KEY` | También habilita embeddings |
+| OpenRouter | `OPENROUTER_API_KEY` | Cualquier modelo |
+| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Solo opt-in. Lanza sesiones de `@anthropic-ai/claude-agent-sdk` — solía causar recursión sin límite en el Stop-hook (seguimiento de #149), por eso ya no es el comportamiento por defecto. |
+
+### Selección de modelo con conciencia de coste
+
+La compresión en background corre en cada observación, así que la elección de modelo cambia el gasto mensual de forma significativa. Datos de carga capturados: 635 peticiones / 888K tokens / 35 horas de uso activo, sobre tres modelos de OpenRouter con precios del 2026-05-23.
+
+| Tier | Modelo | Input / 1M | Output / 1M | Coste para las 35h capturadas | Notas |
+|------|-------|------------|-------------|---------------------------|-------|
+| Recomendado | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Calidad de compresión + resumen sólida a ~10× menos coste que Sonnet. |
+| Recomendado | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | Más antiguo pero aún correcto para cargas solo de compresión. |
+| Recomendado | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Buen razonamiento de código si tus sesiones son muy code-centric. |
+| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | Alta calidad pero caro para trabajo de background siempre activo. |
+| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Tier similar a Sonnet. |
+| Evitar | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Modelo de reasoning; sobrecoste enorme para compresión. |
+
+agentmemory imprime un aviso en runtime cuando `OPENROUTER_MODEL` coincide con un patrón de tier premium. Define `AGENTMEMORY_SUPPRESS_COST_WARNING=1` para silenciarlo una vez que hayas tomado una decisión informada.
+
+Trade-off de calidad vs coste en trabajo de memoria: la compresión es una tarea de resumen con un listón de calidad relativamente flexible (quien re-lee el resumen es el agente, no el usuario). DeepSeek-V4-Pro / Qwen3-Coder se quedan dentro del error de redondeo respecto a Sonnet en esta tarea, costando ~10× menos. Reserva los modelos de tier premium para las consultas que leas directamente.
+
+Fuentes: [OpenRouter pricing for Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Memoria multiagente (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+En montajes multiagente donde varios roles comparten un servidor agentmemory (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` etiqueta cada escritura con el rol que la hizo. `AGENTMEMORY_AGENT_SCOPE` controla si el recall filtra por esa etiqueta.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+Dos modos:
+
+| Modo | Etiqueta escrituras | Filtra recall | Cuándo usarlo |
+|------|------------|---------------|-------------|
+| `shared` (por defecto) | sí | no | Contexto cross-agent con pista de auditoría. El architect puede ver lo que el developer apuntó, pero cada fila registra quién lo dijo. |
+| `isolated` | sí | sí | Separación estricta. El architect nunca ve observaciones / memorias / sesiones del developer. |
+
+Qué se etiqueta cuando `AGENT_ID` está definido: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. El rol fluye `api::session::start` → `mem::observe` → `mem::compress` → KV.
+
+Qué se filtra en modo isolated: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Cada endpoint acepta `?agentId=` para sobreescribir por petición, y `?agentId=*` para optar por salir del scope del entorno por completo. `/memories` también acepta `?includeOrphans=true` para sacar memorias previas a AGENT_ID cuyo `agentId` es undefined.
+
+Sobrescritura por llamada en la capa SDK / REST: cada endpoint que muta (`/session/start`, `/remember`) acepta un campo `agentId` en el body que gana frente al entorno. Útil para runtimes que enrutan muchos roles a un único proceso de servidor.
+
+Cuando `AGENT_ID` no está definido, la memoria permanece sin scope (comportamiento legacy, sin etiquetas, sin filtros).
+
+### Puertos
+
+agentmemory + iii-engine enlazan cuatro puertos por defecto. Si un reinicio falla con `port in use`, esta tabla te dice qué proceso buscar.
+
+| Puerto | Proceso | Propósito | Override por env |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Worker de streams interno (consumido por agentmemory + visor) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Visor en tiempo real (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — los workers se registran aquí, la telemetría OTel fluye por encima | `III_ENGINE_URL` (URL completa, por defecto `ws://localhost:49134`) |
+
+Limpieza de procesos zombi cuando los puertos quedan ocupados tras una ejecución crasheada:
+
+```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` recoge limpiamente tanto el worker como el pidfile del engine en un shutdown graceful (#640, #474). La limpieza manual de arriba solo aplica al caso post-crash en el que no queda ningún pidfile.
+
+### Fichero de configuración
+
+Coloca la configuración de runtime de agentmemory en `~/.agentmemory/.env` en lugar de exportar variables en cada shell. Si el visor muestra una pista de setup tipo `export ANTHROPIC_API_KEY=...`, cópiala a este fichero como `ANTHROPIC_API_KEY=...` sin el prefijo `export`, y reinicia agentmemory.
+
+Las variables de entorno del proceso siguen funcionando y tienen prioridad sobre los valores del fichero.
+
+En Windows, el mismo fichero vive en `%USERPROFILE%\.agentmemory\.env`:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+Para probar con una suscripción Claude Code Pro/Max en lugar de una API key, acepta opt-in explícito:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+Activa graph o consolidation en el mismo fichero si las quieres:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Variables de entorno
+
+Crea `~/.agentmemory/.env`:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+124 endpoints en el puerto `3111`. La REST API se enlaza a `127.0.0.1` por defecto. Los endpoints protegidos requieren `Authorization: Bearer ` cuando `AGENTMEMORY_SECRET` está definido, y los endpoints de mesh sync requieren `AGENTMEMORY_SECRET` en ambos peers.
+
+
+Endpoints principales
+
+| Method | Path | Descripción |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | Health check (siempre público) |
+| `POST` | `/agentmemory/session/start` | Inicia sesión + obtiene contexto |
+| `POST` | `/agentmemory/session/end` | Finaliza sesión |
+| `POST` | `/agentmemory/observe` | Captura observación |
+| `POST` | `/agentmemory/smart-search` | Búsqueda híbrida |
+| `POST` | `/agentmemory/context` | Genera contexto |
+| `POST` | `/agentmemory/remember` | Guarda en memoria a largo plazo |
+| `POST` | `/agentmemory/forget` | Borra observaciones |
+| `POST` | `/agentmemory/enrich` | Contexto de fichero + memorias + bugs |
+| `GET` | `/agentmemory/profile` | Perfil de proyecto |
+| `GET` | `/agentmemory/export` | Exporta todos los datos |
+| `POST` | `/agentmemory/import` | Importa desde JSON |
+| `POST` | `/agentmemory/graph/query` | Consulta del grafo de conocimiento |
+| `POST` | `/agentmemory/team/share` | Comparte con el equipo |
+| `GET` | `/agentmemory/audit` | Pista de auditoría |
+
+Lista completa de endpoints: [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**Requisitos previos:** Node.js >= 20, [iii-engine](https://iii.dev/docs) o Docker
+
+
+
+ Votre agent de codage se souvient de tout. Fini de tout réexpliquer.
+ Built on iii engine
+
+ Mémoire persistante pour Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode et tout client MCP.
+
+ Le gist étend le motif LLM Wiki de Karpathy avec scoring de confiance, cycle de vie, graphes de connaissances et recherche hybride : agentmemory en est l'implémentation.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+Ou via `npx` (sans installation) :
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+À noter — npx met en cache par version. Si un simple `npx @agentmemory/agentmemory` sert une version plus ancienne, forcez la dernière avec `npx -y @agentmemory/agentmemory@latest`, ou videz le cache une fois avec `rm -rf ~/.npm/_npx` (macOS/Linux ; sur Windows, supprimez `%LOCALAPPDATA%\npm-cache\_npx`). Depuis v0.9.16+, la première exécution npx propose une installation globale inline pour que la commande `agentmemory` soit ensuite disponible partout.
+
+Toutes les options dans [Démarrage rapide](#quick-start) ci-dessous. Câblage spécifique par agent dans [Compatible avec tous les agents](#works-with-every-agent).
+
+---
+
+
+
+agentmemory fonctionne avec tout agent qui prend en charge les hooks, MCP ou l'API REST. Tous les agents partagent le même serveur de mémoire.
+
+
+
+
+
+Claude Code
+plugin natif + 12 hooks + MCP
+
+
+
+Codex CLI
+plugin natif + 6 hooks + MCP
+
+
+
+OpenClaw
+plugin natif + MCP
+
+
+
+Hermes
+plugin natif + MCP
+
+
+
+pi
+plugin natif + MCP
+
+
+
+OpenHuman
+backend natif trait Memory
+
+
+
+Cursor
+serveur MCP
+
+
+
+Gemini CLI
+serveur MCP
+
+
+
+
+
+OpenCode
+22 hooks + MCP + plugin
+
+
+
+Cline
+serveur MCP
+
+
+
+Goose
+serveur MCP
+
+
+
+Kilo Code
+serveur MCP
+
+
+
+Aider
+API REST
+
+
+
+Claude Desktop
+serveur MCP
+
+
+
+Windsurf
+serveur MCP
+
+
+
+Roo Code
+serveur MCP
+
+
+
+
+
+ Fonctionne avec n'importe quel agent qui parle MCP ou HTTP. Un seul serveur, des mémoires partagées entre tous.
+
+
+---
+
+Vous expliquez la même architecture à chaque session. Vous redécouvrez les mêmes bugs. Vous réenseignez les mêmes préférences. La mémoire intégrée (CLAUDE.md, .cursorrules) plafonne à 200 lignes et devient obsolète. agentmemory règle ce problème. Il capture silencieusement ce que fait votre agent, le compresse dans une mémoire interrogeable, puis injecte le bon contexte au démarrage de la session suivante. Une seule commande. Compatible entre agents.
+
+**Ce qui change :** Session 1, vous mettez en place l'authentification JWT. Session 2, vous demandez une limitation de débit. L'agent sait déjà que votre authentification utilise le middleware jose dans `src/middleware/auth.ts`, que vos tests couvrent la validation des tokens, et que vous avez choisi jose plutôt que jsonwebtoken pour la compatibilité Edge. Pas de réexplication. Pas de copier-coller. L'agent *sait*, point.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **Nouveau en v0.9.0** — Site d'accueil sur [agent-memory.dev](https://agent-memory.dev), connecteur système de fichiers (`@agentmemory/fs-watcher`), le MCP standalone fait désormais proxy vers le serveur en cours d'exécution afin que les hooks et le visualiseur soient cohérents, politique d'audit codifiée sur tous les chemins de suppression, l'état de santé ne signale plus `memory_critical` sur les petits processus Node. Notes complètes dans [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18).
+
+---
+
+
+
+
+
+
+
+### Précision de récupération
+
+**coding-agent-life-v1** (corpus interne, reproductible en sandbox)
+
+| Adaptateur | P@5 | R@5 | Taux de hit top-5 | Latence p50 |
+|---|---|---|---|---|
+| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms |
+| Référence grep | 0.267 | 0.967 | 15 / 15 | 0 ms |
+
+100 % de taux de hit top-5. **2,2×** meilleure précision que la référence grep sur entrée identique. Ventilation complète par type : [`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)
+
+| Système | R@5 | R@10 | MRR |
+|---|---|---|---|
+| **agentmemory** | **95.2%** | **98.6%** | **88.2%** |
+| Repli BM25 seul | 86.2% | 94.6% | 71.5% |
+
+
+
+> Modèle d'embedding : `all-MiniLM-L6-v2` (local, gratuit, aucune clé d'API). Rapports complets : [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Comparaison avec les concurrents : [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory vs mem0, Letta, Khoj, claude-mem, Hippo.
+
+**Reproduire localement :** [`eval/README.md`](../eval/README.md) — harnais à adaptateurs pluggables pour LongMemEval `_s` (public, 500 questions) + `coding-agent-life-v1` (corpus interne de 15 sessions). Les adaptateurs grep / vectoriel / agentmemory sont scorés côte à côte, sortie NDJSON, scorecards publiés dans [`docs/benchmarks/`](../docs/benchmarks/).
+
+**À associer à [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) et [Graphify](https://github.com/safishamsi/graphify).** Indexation de graphe de code, pipelines de build multi-agents et graphes de connaissances étendus sur docs / PDFs / images / vidéos. agentmemory mémorise le travail ; ces trois projets éclairent le reste de la couche de contexte. Recettes et tableau de routage des questions : [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
Intégré (CLAUDE.md)
+
+
+
Type
+
Moteur de mémoire + serveur MCP
+
API de couche mémoire
+
Runtime d'agent complet
+
Fichier statique
+
+
+
R@5 de récupération
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
N/A (grep)
+
+
+
Capture automatique
+
12 hooks (zéro effort manuel)
+
Appels add() manuels
+
L'agent s'édite lui-même
+
Édition manuelle
+
+
+
Recherche
+
BM25 + Vectoriel + Graphe (fusion RRF)
+
Vectoriel + Graphe
+
Vectoriel (archival)
+
Charge tout en contexte
+
+
+
Multi-agents
+
MCP + REST + leases + signaux
+
API (sans coordination)
+
Uniquement dans le runtime Letta
+
Fichiers par agent
+
+
+
Verrouillage framework
+
Aucun (tout client MCP)
+
Aucun
+
Élevé (Letta obligatoire)
+
Format par agent
+
+
+
Dépendances externes
+
Aucune (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + base vectorielle
+
Aucune
+
+
+
Cycle de vie mémoire
+
Consolidation à 4 niveaux + décroissance + oubli automatique
+
Extraction passive
+
Gérée par l'agent
+
Élagage manuel
+
+
+
Efficacité en tokens
+
~1 900 tokens/session (10 $/an)
+
Variable selon l'intégration
+
Mémoire centrale dans le contexte
+
22K+ tokens à 240 observations
+
+
+
Visualiseur temps réel
+
Oui (port 3113)
+
Tableau de bord cloud
+
Tableau de bord cloud
+
Non
+
+
+
Auto-hébergé
+
Oui (par défaut)
+
Optionnel
+
Optionnel
+
Oui
+
+
+
+---
+
+
+
+Compatibilité : cette version cible `iii-sdk` stable `^0.11.0` et iii-engine v0.11.x.
+
+### Essayez en 30 secondes
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo` amorce 3 sessions réalistes (auth JWT, correctif de requêtes N+1, limitation de débit) et lance des recherches sémantiques dessus. Vous verrez le système trouver « N+1 query fix » quand vous cherchez « database performance optimization » — la correspondance par mots-clés en est incapable.
+
+Ouvrez `http://localhost:3113` pour voir la mémoire se construire en direct.
+
+### Recommandé : installation globale
+
+`npx` met en cache par version. Si vous avez lancé `npx @agentmemory/agentmemory@0.9.14` la semaine dernière, un simple `npx @agentmemory/agentmemory` peut servir le 0.9.14 obsolète depuis `~/.npm/_npx/`, pas la dernière version. Installez une fois et la commande `agentmemory` est disponible partout :
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+À partir de v0.9.16, la première exécution npx propose une installation globale inline — répondez `Y` une fois et c'est réglé. Si vous passez l'étape, repliez sur l'une de ces options pour un fetch frais :
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+Sur Windows / PowerShell, l'équivalent pour vider le cache est `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — le `npx -y ...@latest` ci-dessus reste l'option multiplateforme.
+
+### Replay de session
+
+Chaque session enregistrée par agentmemory est rejouable. Ouvrez le visualiseur, choisissez l'onglet **Replay**, et parcourez la chronologie : prompts, appels d'outils, résultats d'outils et réponses s'affichent comme événements discrets avec play/pause, contrôle de vitesse (0,5×–4×) et raccourcis clavier (espace pour basculer, flèches pour avancer).
+
+Vous avez déjà d'anciennes transcriptions JSONL Claude Code à importer ?
+
+```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
+```
+
+Les sessions importées apparaissent dans le sélecteur Replay aux côtés des natives. Sous le capot, chaque entrée passe par les fonctions iii `mem::replay::load`, `mem::replay::sessions` et `mem::replay::import-jsonl` — aucun serveur secondaire.
+
+### Mise à niveau / Maintenance
+
+Utilisez la commande de maintenance lorsque vous voulez intentionnellement mettre à jour votre runtime local :
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Avertissement : cette commande modifie l'espace de travail / runtime courant. Elle peut mettre à jour les dépendances JavaScript, exécuter `cargo install iii-engine --force` et tirer des images Docker.
+
+Détails d'implémentation dans `src/cli.ts` (voir `runUpgrade` autour de la zone `src/cli.ts:544-595`).
+
+### Claude Code (un seul bloc, à coller)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 sans installation du plugin (chemin MCP-standalone)
+
+Si vous câblez le serveur MCP d'agentmemory via `~/.claude.json` directement plutôt que via `/plugin install`, Claude Code ne résout jamais `${CLAUDE_PLUGIN_ROOT}` et vous devez pointer les scripts de hooks vers des chemins absolus dans `~/.claude/settings.json`. Ces chemins embarquent typiquement la version d'agentmemory (par ex. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), si bien que la mise à niveau suivante casse silencieusement tous les hooks ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Contournement :
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Cela fusionne les mêmes commandes de hooks dans `~/.claude/settings.json` avec des chemins absolus résolus vers le répertoire `plugin/` du paquet `@agentmemory/agentmemory` actuellement installé. Relancez la commande après une mise à niveau d'agentmemory pour rafraîchir les chemins. Les entrées de l'utilisateur dans le même fichier sont préservées ; seules les entrées agentmemory précédentes sont remplacées. Utiliser le chemin `/plugin install` reste l'approche recommandée.
+Pour des déploiements distants ou protégés, lancez Claude Code avec `AGENTMEMORY_URL` et `AGENTMEMORY_SECRET` définis. Le plugin transmet les deux valeurs à son serveur MCP intégré ; quand `AGENTMEMORY_URL` est vide, le shim MCP utilise `http://localhost:3111`.
+
+### Codex CLI (plateforme de plugins Codex)
+
+```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
+```
+
+Le plugin Codex est livré depuis le même répertoire `plugin/` que le plugin Claude Code. Il enregistre :
+
+- `@agentmemory/mcp` comme serveur MCP (proxie les 51 outils lorsque `AGENTMEMORY_URL` pointe vers un serveur agentmemory actif ; retombe sur 7 outils en local si aucun serveur n'est accessible)
+- 6 hooks de cycle de vie : `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skills : `/recall`, `/remember`, `/session-history`, `/forget`
+
+Le moteur de hooks de Codex injecte `CLAUDE_PLUGIN_ROOT` dans les sous-processus de hooks (cf. [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), donc les mêmes scripts de hooks fonctionnent sur les deux hôtes sans duplication. Les événements Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure sont propres à Claude Code et ne sont pas enregistrés pour Codex.
+
+#### Codex Desktop : hooks de plugin actuellement silencieux (contournement disponible)
+
+`CodexHooks` et `PluginHooks` sont tous deux stables + activés par défaut dans [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), mais les builds Codex Desktop actuels ne dispatchent pas les `hooks.json` locaux au plugin ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). Les outils MCP fonctionnent toujours ; seules les observations de cycle de vie manquent.
+
+En attendant le correctif amont, dupliquez les mêmes commandes de hooks dans le `~/.codex/hooks.json` global :
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Cela ajoute un bloc idempotent à `~/.codex/hooks.json` qui référence des chemins absolus vers les scripts intégrés (pas besoin d'expansion `${CLAUDE_PLUGIN_ROOT}` au scope utilisateur). Relancez la même commande après une mise à niveau d'agentmemory pour rafraîchir les chemins. Les entrées de l'utilisateur dans le même fichier sont préservées ; seules les entrées agentmemory précédentes sont remplacées.
+
+
+OpenClaw (collez ce 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 51 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`.
+```
+
+Guide complet : [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (collez ce 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 51 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.
+```
+
+Guide complet : [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Autres agents
+
+Démarrez le serveur de mémoire : `npx @agentmemory/agentmemory`
+
+L'entrée agentmemory est le **même bloc serveur MCP** pour tous les hôtes utilisant le format `mcpServers` (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw) :
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Fusionnez cette entrée dans l'objet `mcpServers` existant** du fichier de config de l'hôte — ne remplacez pas le fichier. Si le fichier contient déjà d'autres serveurs, ajoutez `agentmemory` à côté d'eux comme nouvelle clé dans `mcpServers`. Si `mcpServers` est totalement absent, collez le bloc dans `{ "mcpServers": { ... } }`. Les placeholders `${VAR}` héritent de `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` depuis le shell au lancement du serveur MCP — des vars non définies passent des chaînes vides et le shim retombe sur `http://localhost:3111`. Une seule entrée câblée couvre à la fois les déploiements locaux et distants (k8s / reverse-proxy).
+
+| Agent | Fichier de config | Notes |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | Fusionner dans `mcpServers`. Deeplink en un clic également disponible sur le site web. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Fusionner dans `mcpServers`. Redémarrer Claude Desktop après modification. |
+| **Cline / Roo Code / Kilo Code** | Paramètres MCP de Cline (Settings UI → MCP Servers → Edit) | Même bloc `mcpServers`. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Même bloc `mcpServers`. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (fusion automatique). |
+| **OpenClaw** | Config MCP d'OpenClaw | Même bloc `mcpServers`, ou utilisez le [plugin mémoire plus poussé](../integrations/openclaw/). |
+| **Codex CLI (MCP seul)** | `.codex/config.toml` | Format TOML : `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, ou ajoutez `[mcp_servers.agentmemory]` à la main. |
+| **Codex CLI (plugin complet)** | Marketplace de plugins Codex | `codex plugin marketplace add rohitg00/agentmemory` puis `codex plugin add agentmemory@agentmemory`. Enregistre MCP + 6 hooks de cycle de vie (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. Sur Codex Desktop, lancez également `agentmemory connect codex --with-hooks` en attendant que [openai/codex#16430](https://github.com/openai/codex/issues/16430) soit corrigé — les hooks de plugin y sont actuellement silencieux. |
+| **OpenCode (MCP seul)** | `opencode.json` | Format différent — clé `mcp` au niveau racine, commande sous forme de tableau : `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (plugin complet)** | `plugin/opencode/` | 22 hooks de capture automatique couvrant cycle de vie de session, messages, outils, erreurs. Deux commandes slash (`/recall`, `/remember`). Copiez `plugin/opencode/` dans votre workspace OpenCode et ajoutez l'entrée du plugin à `opencode.json`. Voir [`plugin/opencode/README.md`](../plugin/opencode/README.md) pour le tableau complet des hooks et l'analyse des manques. |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | Copiez [`integrations/pi`](../integrations/pi/) et redémarrez pi. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Utilisez le [plugin de fournisseur de mémoire plus poussé](../integrations/hermes/) avec `memory.provider: agentmemory`. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` écrit le bloc `mcpServers` standard. La charge utile des hooks est compatible champ-à-champ avec Claude Code, donc les 12 scripts de hooks existants fonctionnent sans modification — câblez-les via la section `hooks` du même `settings.json`. |
+| **Antigravity** (remplace Gemini CLI) | `mcp_config.json` (dans le répertoire User d'Antigravity) | `agentmemory connect antigravity` écrit le bloc `mcpServers` standard. macOS : `~/Library/Application Support/Antigravity/User/`. Linux : `~/.config/Antigravity/User/`. À utiliser après l'arrêt de Gemini CLI au 2026-06-18. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` écrit la config au niveau utilisateur. Les overrides de workspace vont dans `.kiro/settings/mcp.json` à côté de votre code. |
+| **Goose** | UI des paramètres MCP de Goose | Même bloc `mcpServers`. |
+| **Aider** | n/a | Parlez directement à l'API REST : `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Tout agent (32+)** | n/a | `npx skillkit install agentmemory` détecte l'hôte automatiquement et fusionne. |
+
+**Clients MCP en sandbox** (Flatpak / Snap / conteneurs restrictifs) qui ne peuvent pas joindre le `localhost` de l'hôte : définissez également `"AGENTMEMORY_FORCE_PROXY": "1"` dans le bloc `env` et pointez `AGENTMEMORY_URL` vers une route que la sandbox peut effectivement atteindre (par ex. votre IP LAN). Voir [#234](https://github.com/rohitg00/agentmemory/issues/234) pour la démarche de diagnostic.
+
+### Accès programmatique (Python / Rust / Node)
+
+agentmemory enregistre ses opérations principales en tant que fonctions iii (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). N'importe quel langage doté d'un SDK iii peut les appeler directement sur `ws://localhost:49134` — pas besoin de client REST séparé par langage.
+
+```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"},
+})
+```
+
+Exemple complet : [`examples/python/`](../examples/python/) (quickstart + flux observation/recall). REST sur `:3111` reste disponible pour les hôtes sans runtime iii.
+
+### Depuis les sources
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Cela démarre agentmemory avec un `iii-engine` local si `iii` est déjà installé, ou retombe sur Docker Compose si Docker est disponible. REST, streams et visualiseur se lient à `127.0.0.1` par défaut.
+
+Installer `iii-engine` manuellement. **agentmemory épingle actuellement `iii-engine` à `v0.11.2`** — `v0.11.6` introduit un nouveau modèle de sandboxing systématique via `iii worker add` pour lequel agentmemory n'a pas encore été refactorisé. L'épinglage sera levé une fois la refonte effectuée. Surchargez avec `AGENTMEMORY_III_VERSION=` si vous avez migré au modèle sandbox manuellement.
+
+- **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 :** remplacez `aarch64-apple-darwin` par `x86_64-apple-darwin`
+- **Linux x64 :** remplacez par `x86_64-unknown-linux-gnu`
+- **Linux arm64 :** remplacez par `aarch64-unknown-linux-gnu`
+- **Windows :** téléchargez `iii-x86_64-pc-windows-msvc.zip` depuis [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extrayez `iii.exe`, ajoutez-le au PATH
+
+Ou utilisez Docker (le `docker-compose.yml` fourni tire `iiidev/iii:0.11.2`). Documentation complète : [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory tourne sur Windows 10/11, mais le paquet Node.js seul ne suffit pas — il vous faut aussi le runtime `iii-engine` (un binaire natif séparé) comme processus en arrière-plan. L'installeur amont officiel est un script `sh` et il n'existe à ce jour ni installeur PowerShell ni paquet scoop/winget, donc les utilisateurs Windows ont deux chemins :
+
+**Option A — Binaire Windows précompilé (recommandé) :**
+
+```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 — MCP standalone uniquement (sans moteur) :** si vous n'avez besoin que des outils MCP pour votre agent et pas de l'API REST, du visualiseur ou des jobs cron, sautez le moteur :
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Diagnostics pour Windows :** si `npx @agentmemory/agentmemory` échoue, relancez avec `--verbose` pour voir le stderr réel du moteur. Modes de défaillance courants :
+
+| Symptôme | Correctif |
+|---|---|
+| `iii-engine process started` puis `did not become ready within 15s` | Le moteur a planté au démarrage — relancez avec `--verbose`, vérifiez stderr |
+| `Could not start iii-engine` | Ni `iii.exe` ni Docker installés. Voir les options A ou B ci-dessus |
+| Conflit de port | `netstat -ano \| findstr :3111` pour voir ce qui est lié, puis tuez-le ou utilisez `--port ` |
+| Fallback Docker ignoré bien que Docker soit installé | Assurez-vous que Docker Desktop tourne effectivement (icône de la barre d'état système) |
+
+> Note : il n'y a pas de `cargo install iii-engine` — `iii` n'est pas publié sur crates.io. Les seules méthodes d'installation supportées sont le binaire précompilé ci-dessus, le script d'installation amont en `sh` (macOS/Linux uniquement) et l'image Docker.
+
+---
+
+
Déploiement
+
+Templates en un clic pour les hébergeurs managés. Chacun livre un Dockerfile
+autonome qui récupère `@agentmemory/agentmemory` depuis npm et copie le
+binaire iii engine depuis l'image officielle `iiidev/iii` du Docker
+Hub — pas d'image agentmemory précompilée requise. Le stockage
+persistant se monte sur `/data` ; le point d'entrée au premier
+démarrage réécrit la config iii livrée par npm (qui se lie à
+`127.0.0.1`) par une version réglée pour le déploiement qui se lie à
+`0.0.0.0` et utilise des chemins absolus `/data`, génère le secret HMAC,
+puis abaisse les privilèges de `root` à `node` via `gosu` avant
+d'exec'er la CLI agentmemory.
+
+
+
+
+
+
+Le bouton de déploiement en un clic de Render exige un `render.yaml` à la racine du dépôt, que nous gardons délibérément propre. Utilisez le flux Render Blueprint documenté dans [`deploy/render/`](./deploy/render/README.md) pour pointer manuellement vers le blueprint dans le dépôt.
+
+Détails complets de configuration (capture HMAC, tunnel SSH du visualiseur, rotation, sauvegarde, plafonds de coût) dans [`deploy/`](./deploy/README.md) :
+
+- [`deploy/fly`](./deploy/fly/README.md) — machine unique avec
+ `auto_stop_machines = "stop"` ; le moins cher à l'arrêt.
+- [`deploy/railway`](./deploy/railway/README.md) — forfait Hobby à tarif fixe,
+ volume dans le tableau de bord.
+- [`deploy/render`](./deploy/render/README.md) — flux Blueprint,
+ snapshots disque automatiques sur les forfaits payants.
+- [`deploy/coolify`](./deploy/coolify/README.md) — auto-hébergé sur votre
+ propre VPS via [Coolify](https://coolify.io/self-hosted) ; même stack
+ Docker Compose, vous possédez l'hôte et les données.
+
+Seul le port `3111` est publié. Le visualiseur sur `3113` reste lié à la
+boucle locale dans le conteneur — chaque README de template documente
+le motif tunnel SSH pour y accéder.
+
+---
+
+
+
+Chaque agent de codage oublie tout quand la session se termine. Vous perdez les 5 premières minutes de chaque session à réexpliquer votre stack. agentmemory tourne en arrière-plan et élimine totalement cette perte.
+
+```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 mémoire d'agent intégrée
+
+Chaque agent de codage IA est livré avec une mémoire intégrée — Claude Code a `MEMORY.md`, Cursor a des notepads, Cline a memory bank. Cela fonctionne comme des post-it. agentmemory est la base de données interrogeable derrière les post-it.
+
+| | Intégrée (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Échelle | Plafond de 200 lignes | Illimitée |
+| Recherche | Charge tout en contexte | BM25 + vecteur + graphe (top-K seul) |
+| Coût en tokens | 22K+ à 240 observations | ~1 900 tokens (92 % de moins) |
+| Inter-agents | Fichiers par agent | MCP + REST (n'importe quel agent) |
+| Coordination | Aucune | Leases, signaux, actions, routines |
+| Observabilité | Lire les fichiers à la main | Visualiseur temps réel sur :3113 |
+
+---
+
+
+
+### Pipeline mémoire
+
+```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
+```
+
+### Consolidation mémoire à 4 niveaux
+
+Inspirée de la façon dont le cerveau humain traite la mémoire — pas si éloignée de la consolidation pendant le sommeil.
+
+| Niveau | Quoi | Analogie |
+|------|------|---------|
+| **Working** | Observations brutes issues de l'usage des outils | Mémoire à court terme |
+| **Episodic** | Résumés de session compressés | « Ce qui s'est passé » |
+| **Semantic** | Faits et motifs extraits | « Ce que je sais » |
+| **Procedural** | Workflows et motifs de décision | « Comment faire » |
+
+Les mémoires décroissent dans le temps (courbe d'Ebbinghaus). Les mémoires fréquemment consultées se renforcent. Les mémoires obsolètes sont évincées automatiquement. Les contradictions sont détectées et résolues.
+
+### Ce qui est capturé
+
+| Hook | Capture |
+|------|----------|
+| `SessionStart` | Chemin de projet, ID de session |
+| `UserPromptSubmit` | Prompts utilisateur (filtrés pour la vie privée) |
+| `PreToolUse` | Motifs d'accès fichier + contexte enrichi |
+| `PostToolUse` | Nom de l'outil, entrée, sortie |
+| `PostToolUseFailure` | Contexte d'erreur |
+| `PreCompact` | Réinjecte la mémoire avant compaction |
+| `SubagentStart/Stop` | Cycle de vie des sous-agents |
+| `Stop` | Résumé de fin de session |
+| `SessionEnd` | Marqueur de fin de session |
+
+### Capacités clés
+
+| Capacité | Description |
+|---|---|
+| **Capture automatique** | Chaque usage d'outil enregistré via hooks — zéro effort manuel |
+| **Recherche sémantique** | BM25 + vecteur + graphe de connaissances avec fusion RRF |
+| **Évolution de la mémoire** | Versioning, supersession, graphes de relations |
+| **Oubli automatique** | Expiration TTL, détection de contradictions, éviction par importance |
+| **Vie privée d'abord** | Clés d'API, secrets, balises `` retirés avant stockage |
+| **Auto-réparation** | Circuit breaker, chaîne de repli de fournisseur, surveillance de santé |
+| **Pont Claude** | Synchronisation bidirectionnelle avec MEMORY.md |
+| **Graphe de connaissances** | Extraction d'entités + parcours BFS |
+| **Mémoire d'équipe** | Partagée + privée par namespace entre membres de l'équipe |
+| **Provenance des citations** | Tracer toute mémoire jusqu'aux observations sources |
+| **Snapshots git** | Version, rollback et diff de l'état mémoire |
+
+---
+
+
+
+Récupération triple-flux combinant trois signaux :
+
+| Flux | Ce qu'il fait | Quand |
+|---|---|---|
+| **BM25** | Correspondance par mots-clés racinisés avec expansion par synonymes | Toujours actif |
+| **Vector** | Similarité cosinus sur embeddings denses | Fournisseur d'embedding configuré |
+| **Graph** | Parcours du graphe de connaissances par correspondance d'entités | Entités détectées dans la requête |
+
+Fusionnés par Reciprocal Rank Fusion (RRF, k=60) et diversifiés par session (max 3 résultats par session).
+
+BM25 tokenise nativement le grec, le cyrillique, l'hébreu, l'arabe et le latin accentué. Pour des mémoires en chinois / japonais / coréen, installez les segmenteurs optionnels (`npm install @node-rs/jieba tiny-segmenter`) afin de découper les suites CJK en tokens au niveau du mot ; sans eux, agentmemory retombe doucement sur une tokenisation par suite entière et imprime un message indicatif unique sur stderr.
+
+### Fournisseurs d'embedding
+
+agentmemory détecte automatiquement votre fournisseur. Pour de meilleurs résultats, installez les embeddings locaux (gratuits) :
+
+```bash
+npm install @xenova/transformers
+```
+
+| Fournisseur | Modèle | Coût | Notes |
+|---|---|---|---|
+| **Local (recommandé)** | `all-MiniLM-L6-v2` | Gratuit | Hors-ligne, +8 pp de rappel par rapport à BM25 seul |
+| Gemini | `gemini-embedding-001` | Niveau gratuit | 100+ langues, dimensions 768/1536/3072 (MRL), entrée 2048 tokens. Remplace `text-embedding-004` ([déprécié, arrêt le 14 jan. 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | 0,02 $/1M | Meilleure qualité |
+| Voyage AI | `voyage-code-3` | Payant | Optimisé pour le code |
+| Cohere | `embed-english-v3.0` | Essai gratuit | Polyvalent |
+| OpenRouter | N'importe quel modèle | Variable | Proxy multi-modèles |
+
+---
+
+
+
+53 outils, 6 ressources, 3 prompts et 4 skills — la boîte à outils mémoire MCP la plus complète pour tout agent.
+
+> **Shim MCP vs serveur complet :** le paquet publié `@agentmemory/mcp` est un shim léger. Il expose la surface complète de 51 outils **uniquement quand il peut joindre un serveur agentmemory actif** via `AGENTMEMORY_URL` (mode proxy). Sans serveur joignable, le shim retombe sur un jeu local de 7 outils (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). La variable d'env `AGENTMEMORY_TOOLS=core|all` est un drapeau *côté serveur* — la définir dans le bloc `env` du shim n'a aucun effet. Si vous ne voyez que 7 outils dans Cursor / OpenCode / Gemini CLI, lancez `npx @agentmemory/agentmemory` (ou la stack Docker) et définissez `AGENTMEMORY_URL=http://localhost:3111`.
+
+### 51 outils
+
+
+Outils de base (toujours disponibles)
+
+| Outil | Description |
+|------|-------------|
+| `memory_recall` | Rechercher dans les observations passées |
+| `memory_compress_file` | Compresser des fichiers markdown en préservant la structure |
+| `memory_save` | Sauvegarder un insight, une décision ou un motif |
+| `memory_patterns` | Détecter des motifs récurrents |
+| `memory_smart_search` | Recherche hybride sémantique + mots-clés |
+| `memory_file_history` | Observations passées sur des fichiers spécifiques |
+| `memory_sessions` | Lister les sessions récentes |
+| `memory_timeline` | Observations chronologiques |
+| `memory_profile` | Profil de projet (concepts, fichiers, motifs) |
+| `memory_export` | Exporter toutes les données mémoire |
+| `memory_relations` | Interroger le graphe de relations |
+
+
+
+
+Outils étendus (51 au total — définissez AGENTMEMORY_TOOLS=all)
+
+| Outil | Description |
+|------|-------------|
+| `memory_patterns` | Détecter des motifs récurrents |
+| `memory_timeline` | Observations chronologiques |
+| `memory_relations` | Interroger le graphe de relations |
+| `memory_graph_query` | Parcours du graphe de connaissances |
+| `memory_consolidate` | Lancer la consolidation à 4 niveaux |
+| `memory_claude_bridge_sync` | Synchroniser avec MEMORY.md |
+| `memory_team_share` | Partager avec les membres de l'équipe |
+| `memory_team_feed` | Éléments partagés récemment |
+| `memory_audit` | Piste d'audit des opérations |
+| `memory_governance_delete` | Supprimer avec piste d'audit |
+| `memory_snapshot_create` | Snapshot versionné git |
+| `memory_action_create` | Créer des éléments de travail avec dépendances |
+| `memory_action_update` | Mettre à jour le statut d'une action |
+| `memory_frontier` | Actions débloquées classées par priorité |
+| `memory_next` | Seule action suivante la plus importante |
+| `memory_lease` | Leases d'action exclusifs (multi-agents) |
+| `memory_routine_run` | Instancier des routines de workflow |
+| `memory_signal_send` | Messagerie inter-agents |
+| `memory_signal_read` | Lire des messages avec accusés |
+| `memory_checkpoint` | Portes de condition externes |
+| `memory_mesh_sync` | Sync P2P entre instances |
+| `memory_sentinel_create` | Watchers événementiels |
+| `memory_sentinel_trigger` | Déclencher des sentinelles depuis l'extérieur |
+| `memory_sketch_create` | Graphes d'action éphémères |
+| `memory_sketch_promote` | Promouvoir en permanent |
+| `memory_crystallize` | Compacter les chaînes d'actions |
+| `memory_diagnose` | Vérifications de santé |
+| `memory_heal` | Auto-correction d'état bloqué |
+| `memory_facet_tag` | Tags dimension:valeur |
+| `memory_facet_query` | Interroger par tags de facettes |
+| `memory_verify` | Tracer la provenance |
+
+
+
+### 6 Ressources · 3 Prompts · 4 Skills
+
+| Type | Nom | Description |
+|------|------|-------------|
+| Ressource | `agentmemory://status` | Santé, nombre de sessions, nombre de mémoires |
+| Ressource | `agentmemory://project/{name}/profile` | Intelligence par projet |
+| Ressource | `agentmemory://memories/latest` | 10 dernières mémoires actives |
+| Ressource | `agentmemory://graph/stats` | Statistiques du graphe de connaissances |
+| Prompt | `recall_context` | Recherche + retour de messages de contexte |
+| Prompt | `session_handoff` | Données de passation entre agents |
+| Prompt | `detect_patterns` | Analyser les motifs récurrents |
+| Skill | `/recall` | Rechercher la mémoire |
+| Skill | `/remember` | Sauvegarder en mémoire long-terme |
+| Skill | `/session-history` | Résumés de sessions récentes |
+| Skill | `/forget` | Supprimer observations / sessions |
+
+### MCP autonome
+
+Tourne sans le serveur complet — pour n'importe quel client MCP. L'une ou l'autre marche :
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+Ou ajoutez à la config MCP de votre agent :
+
+La plupart des agents (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI) :
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+Fusionnez l'entrée `agentmemory` dans l'objet `mcpServers` existant de votre hôte plutôt que de remplacer le fichier. Pour des clients en sandbox qui ne peuvent pas joindre le `localhost` de l'hôte, ajoutez `"AGENTMEMORY_FORCE_PROXY": "1"` au bloc env et pointez `AGENTMEMORY_URL` vers une route que la sandbox peut atteindre.
+
+OpenCode (`opencode.json`) :
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Copiez le fichier plugin depuis le dépôt :
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Démarre automatiquement sur le port `3113`. Flux d'observations en direct, explorateur de sessions, navigateur mémoire, visualisation du graphe de connaissances et tableau de bord de santé.
+
+```bash
+open http://localhost:3113
+```
+
+Le serveur du visualiseur se lie à `127.0.0.1` par défaut. Le point d'entrée `/agentmemory/viewer` servi par REST suit les règles normales de bearer-token `AGENTMEMORY_SECRET`. Les en-têtes CSP utilisent un nonce de script par réponse et désactivent les attributs gestionnaires inline (`script-src-attr 'none'`).
+
+---
+
+
+
+Le visualiseur sur `:3113` montre ce que votre agent **a mémorisé**. La [iii console](https://iii.dev/docs/console) montre ce que votre agent **a fait** — chaque op mémoire comme trace OpenTelemetry, chaque entrée KV éditable, chaque fonction invocable, chaque flux taps-able. Deux fenêtres sur la même mémoire : l'une orientée produit, l'autre orientée moteur.
+
+Regardez un `memory_smart_search` se déclencher et voyez le scan BM25 → recherche d'embeddings → fusion RRF → reranker comme un waterfall. Éditez un timer de consolidation bloqué dans le navigateur KV. Rejouez un hook `PostToolUse` avec une charge utile modifiée. Épinglez le flux WebSocket et regardez les observations arriver en direct.
+
+agentmemory livre cela gratuitement parce que chaque fonction, trigger, scope d'état et flux est une primitive iii — rien de personnalisé, rien à instrumenter.
+
+
+
+
+ Page Workers : chaque worker connecté — y compris agentmemory lui-même — avec PID, nombre de fonctions, runtime et last-seen.
+
+
+**Déjà installé.** La console est livrée avec `iii` — pas d'installeur séparé.
+
+**Lancer aux côtés d'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
+```
+
+Puis ouvrez `http://localhost:3114`. Ajoutez `--enable-flow` pour la page expérimentale de graphe d'architecture.
+
+Surchargez les endpoints du moteur uniquement si vous les avez déplacés :
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Ce que vous pouvez faire depuis la console :**
+
+| Page | Pour |
+|------|-----------|
+| **Workers** | Voir chaque worker connecté et ses métriques en direct — y compris le worker agentmemory lui-même. |
+| **Functions** | Invoquer n'importe quelle fonction d'agentmemory avec une charge utile JSON — pratique pour tester `memory.recall`, `memory.consolidate`, `graph.query` sans câbler un client. |
+| **Triggers** | Rejouer les triggers HTTP, cron, event et state — déclencher manuellement le cron de consolidation, retenter une route HTTP, émettre un changement d'état. |
+| **States** | Navigateur KV avec CRUD complet — sessions, slots mémoire, timers de cycle de vie, index d'embeddings — éditer les valeurs sur place. |
+| **Streams** | Moniteur WebSocket en direct pour les écritures mémoire, événements de hooks et mises à jour d'observations à mesure qu'ils circulent dans les iii streams. |
+| **Queues** | Topics de files durables + gestion de la dead-letter. Rejouer ou abandonner les jobs d'embedding / compression échoués. |
+| **Traces** | Vues waterfall / flame / décomposition par service OpenTelemetry. Filtrez par `trace_id` pour voir exactement quelles fonctions, appels DB et requêtes d'embedding une seule `memory.search` a produits. |
+| **Logs** | Logs OTEL structurés filtrés et corrélés aux IDs de trace/span. |
+| **Config** | Configuration runtime — voir exactement quels workers, fournisseurs et ports tourne votre moteur. |
+| **Flow** | (Optionnel, `--enable-flow`) Graphe d'architecture interactif de chaque worker, trigger et flux. |
+
+
+
+
+ Traces : waterfall / flame / décomposition par service pour chaque opération mémoire.
+
+
+**Les traces sont déjà actives :**
+
+`iii-config.yaml` est livré avec le worker `iii-observability` activé (`exporter: memory`, `sampling_ratio: 1.0`, métriques + logs). Aucune config supplémentaire — dès qu'agentmemory démarre, chaque opération mémoire émet un span de trace et un log structuré que la console peut lire.
+
+Si vous voulez exporter vers Jaeger/Honeycomb/Grafana Tempo à la place, changez `exporter: memory` en `exporter: otlp` et définissez l'endpoint du collecteur selon la documentation d'observabilité d'iii.
+
+> **Attention :** aucune auth n'est appliquée sur la console elle-même — gardez-la liée à `127.0.0.1` (par défaut) et ne l'exposez jamais publiquement.
+
+---
+
+
+
+agentmemory est **déjà une instance [iii](https://iii.dev) en cours d'exécution**. Fonctions, triggers, état KV, flux, traces OTEL — tout est primitive iii. Vous n'avez pas installé Postgres, Redis, Express, pm2, ni Prometheus, parce qu'iii les remplace.
+
+Cela signifie qu'une commande supplémentaire étend agentmemory d'une toute nouvelle capacité.
+
+### Étendez agentmemory avec une seule commande
+
+```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
+```
+
+Chaque `iii worker add` enregistre de nouvelles fonctions et triggers dans le même moteur sur lequel agentmemory tourne déjà. Le visualiseur et la console les prennent en compte immédiatement — sans rechargement, sans nouvelle intégration, sans nouveau conteneur.
+
+| `iii worker add` | Ce que vous obtenez en plus d'agentmemory |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Mémoire multi-instances : chaque `remember` se diffuse, chaque `search` lit l'union |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Cycle de vie planifié — consolidation nocturne, snapshots hebdomadaires, décroissance sur horloge fixe |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Retries durables : les jobs d'embedding + compression en échec survivent au redémarrage, aucune observation perdue |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Traces, métriques et logs OTEL sur chaque fonction — câblés dans `iii-config.yaml` dès le premier jour |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Le code issu de `memory_recall` s'exécute dans une VM jetable, pas dans votre shell |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptateur d'état adossé à SQL lorsque vous dépassez les valeurs par défaut KV en mémoire |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | Déployez des serveurs MCP supplémentaires à côté de celui d'agentmemory, partageant le même moteur |
+
+Registre complet : [workers.iii.dev](https://workers.iii.dev). Chaque worker là-bas se compose via les mêmes primitives qu'utilise agentmemory — et l'agentmemory que vous avez déjà en est un.
+
+### Ce qu'iii remplace
+
+| Stack traditionnelle | agentmemory utilise |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + index vectoriel en mémoire |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | Supervision de workers du moteur iii |
+| Prometheus / Grafana | iii OTEL + moniteur de santé |
+| Systèmes de plugins personnalisés | `iii worker add ` |
+
+**118 fichiers sources · ~21 800 LOC · 950+ tests · 123 fonctions · 34 scopes KV** — tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même.
+
+---
+
+
+
+### Fournisseurs LLM
+
+agentmemory détecte automatiquement depuis votre environnement. Par défaut, aucun appel LLM n'est effectué tant que vous n'avez pas configuré de fournisseur ou explicitement opté pour le fallback abonnement Claude.
+
+| Fournisseur | Config | Notes |
+|----------|--------|-------|
+| **No-op (par défaut)** | Aucune config nécessaire | Le compress/summarize adossé à un LLM est DÉSACTIVÉ. La compression et le recall BM25 synthétiques fonctionnent toujours. Voir `AGENTMEMORY_ALLOW_AGENT_SDK` ci-dessous si vous comptiez sur le fallback abonnement Claude. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Facturation au token |
+| MiniMax | `MINIMAX_API_KEY` | Compatible Anthropic |
+| Gemini | `GEMINI_API_KEY` | Active aussi les embeddings |
+| OpenRouter | `OPENROUTER_API_KEY` | N'importe quel modèle |
+| Fallback abonnement Claude | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in seulement. Engendre des sessions `@anthropic-ai/claude-agent-sdk` — provoquait une récursion non bornée du Stop-hook (suite de #149), il n'est plus l'option par défaut. |
+
+### Sélection de modèle attentive au coût
+
+La compression en arrière-plan tourne sur chaque observation, donc le choix du modèle influence sensiblement la dépense mensuelle. Données de charge capturées : 635 requêtes / 888K tokens / 35 heures d'usage actif, exécutées contre trois modèles OpenRouter au tarif du 2026-05-23.
+
+| Niveau | Modèle | Entrée / 1M | Sortie / 1M | Coût pour les 35h capturées | Notes |
+|------|-------|------------|-------------|---------------------------|-------|
+| Recommandé | `deepseek/deepseek-v4-pro` | 0,435 $ | 0,87 $ | ~0,46 $ | Qualité de compression + résumé solide à un coût ~10× moindre que Sonnet. |
+| Recommandé | `deepseek/deepseek-chat` | 0,27 $ | 1,10 $ | ~0,40 $ | Plus ancien mais toujours satisfaisant pour des charges de compression uniquement. |
+| Recommandé | `qwen/qwen3-coder` | 0,45 $ | 1,80 $ | ~0,55 $ | Solide raisonnement code si vos sessions sont fortement code-shaped. |
+| Premium | `anthropic/claude-sonnet-4.6` | 3,00 $ | 15,00 $ | ~5,02 $ | Haute qualité mais coûteux pour du travail de fond permanent. |
+| Premium | `openai/gpt-4o` | 2,50 $ | 10,00 $ | ~4,20 $ | Niveau similaire à Sonnet. |
+| À éviter | `anthropic/claude-opus-4.6` | 15,00 $ | 75,00 $ | ~25+ $ | Modèle classe raisonnement ; surcoût massif pour de la compression. |
+
+agentmemory imprime un avertissement runtime quand `OPENROUTER_MODEL` correspond à un motif de niveau premium. Définissez `AGENTMEMORY_SUPPRESS_COST_WARNING=1` pour le faire taire une fois votre choix éclairé.
+
+Compromis qualité vs coût pour le travail mémoire : la compression est une tâche de résumé avec des exigences de qualité relativement souples (c'est l'agent qui relit le résumé, pas l'utilisateur). DeepSeek-V4-Pro / Qwen3-Coder se situent à la précision d'arrondi près de Sonnet sur cette tâche tout en coûtant ~10× moins. Réservez les modèles premium aux requêtes que vous lisez directement.
+
+Sources : [tarification OpenRouter pour Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [notes de prix DeepSeek](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Mémoire multi-agents (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+Dans des configurations multi-agents où plusieurs rôles partagent un même serveur agentmemory (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` marque chaque écriture avec le rôle qui l'a produite. `AGENTMEMORY_AGENT_SCOPE` contrôle si le recall filtre par ce tag.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+Deux modes :
+
+| Mode | Marquer les écritures | Filtrer le recall | Quand l'utiliser |
+|------|------------|---------------|-------------|
+| `shared` (par défaut) | oui | non | Contexte inter-agents avec piste d'audit. L'architect voit ce que le developer a noté, mais chaque ligne enregistre qui l'a dit. |
+| `isolated` | oui | oui | Séparation stricte. L'architect ne voit jamais les observations / mémoires / sessions du developer. |
+
+Ce qui est marqué quand `AGENT_ID` est défini : `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. Le rôle circule de `api::session::start` → `mem::observe` → `mem::compress` → KV.
+
+Ce qui est filtré en mode isolé : `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Chaque endpoint accepte `?agentId=` pour surcharger par requête, et `?agentId=*` pour se désinscrire entièrement du scope de l'env. `/memories` accepte aussi `?includeOrphans=true` pour faire remonter les mémoires antérieures à AGENT_ID dont `agentId` est indéfini.
+
+Surcharge par appel au niveau SDK / REST : chaque endpoint mutant (`/session/start`, `/remember`) accepte un champ `agentId` dans le corps de la requête qui gagne sur l'env. Utile pour des runtimes qui routent plusieurs rôles à travers un même processus serveur.
+
+Quand `AGENT_ID` n'est pas défini, la mémoire reste non scopée (comportement legacy, sans tags ni filtres).
+
+### Ports
+
+agentmemory + iii-engine se lient à quatre ports par défaut. Si un redémarrage échoue avec `port in use`, ce tableau vous indique le processus à chercher.
+
+| Port | Processus | Usage | Surcharge env |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | API REST + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Worker streams interne (consommé par agentmemory + visualiseur) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Visualiseur temps réel (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — les workers s'y enregistrent, la télémétrie OTel y circule | `III_ENGINE_URL` (URL complète, défaut `ws://localhost:49134`) |
+
+Nettoyage de processus zombies quand des ports restent occupés après un crash :
+
+```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` réclame proprement à la fois le worker et le pidfile du moteur en arrêt gracieux (#640, #474). Le nettoyage manuel ci-dessus n'est nécessaire que pour le cas post-crash où aucun pidfile n'est laissé en place.
+
+### Fichier de configuration
+
+Mettez la configuration runtime d'agentmemory dans `~/.agentmemory/.env` au lieu d'exporter des variables dans chaque shell. Si le visualiseur affiche un indice de setup comme `export ANTHROPIC_API_KEY=...`, recopiez-le dans ce fichier sous la forme `ANTHROPIC_API_KEY=...` sans le préfixe `export`, puis redémarrez agentmemory.
+
+Les variables d'environnement du processus restent valides et prennent le pas sur les valeurs du fichier.
+
+Sur Windows, le même fichier se trouve dans `%USERPROFILE%\.agentmemory\.env` :
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+Pour tester avec un abonnement Claude Code Pro/Max au lieu d'une clé d'API, optez-vous explicitement :
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+Activez les fonctionnalités de graphe ou de consolidation dans le même fichier si vous les voulez :
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Variables d'environnement
+
+Créez `~/.agentmemory/.env` :
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+124 endpoints sur le port `3111`. L'API REST se lie à `127.0.0.1` par défaut. Les endpoints protégés exigent `Authorization: Bearer ` lorsque `AGENTMEMORY_SECRET` est défini, et les endpoints de mesh sync exigent `AGENTMEMORY_SECRET` sur les deux pairs.
+
+
+Endpoints clés
+
+| Méthode | Chemin | Description |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | Vérification de santé (toujours publique) |
+| `POST` | `/agentmemory/session/start` | Démarrer une session + obtenir le contexte |
+| `POST` | `/agentmemory/session/end` | Terminer une session |
+| `POST` | `/agentmemory/observe` | Capturer une observation |
+| `POST` | `/agentmemory/smart-search` | Recherche hybride |
+| `POST` | `/agentmemory/context` | Générer du contexte |
+| `POST` | `/agentmemory/remember` | Sauvegarder en mémoire long-terme |
+| `POST` | `/agentmemory/forget` | Supprimer des observations |
+| `POST` | `/agentmemory/enrich` | Contexte de fichier + mémoires + bugs |
+| `GET` | `/agentmemory/profile` | Profil de projet |
+| `GET` | `/agentmemory/export` | Exporter toutes les données |
+| `POST` | `/agentmemory/import` | Importer depuis JSON |
+| `POST` | `/agentmemory/graph/query` | Requête sur le graphe de connaissances |
+| `POST` | `/agentmemory/team/share` | Partager avec l'équipe |
+| `GET` | `/agentmemory/audit` | Piste d'audit |
+
+Liste complète des endpoints : [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**Prérequis :** Node.js >= 20, [iii-engine](https://iii.dev/docs) ou Docker
+
+
+
+ आपका कोडिंग एजेंट सब कुछ याद रखता है। बार-बार समझाने की ज़रूरत नहीं।
+ Built on iii engine
+
+ Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode, और किसी भी MCP क्लाइंट के लिए स्थायी मेमोरी।
+
+ यह gist Karpathy के LLM Wiki पैटर्न को confidence scoring, lifecycle, knowledge graphs और hybrid search के साथ बढ़ाता है: agentmemory इसका implementation है।
+
+
+---
+
+## इंस्टॉल
+
+```bash
+npm install -g @agentmemory/agentmemory # एक बार — PATH पर `agentmemory` कमांड उपलब्ध
+# अगर macOS/Linux सिस्टम Node इंस्टॉल पर EACCES त्रुटि आती है, तो इसके साथ फिर से चलाएँ:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # :3111 पर मेमोरी सर्वर शुरू करें
+agentmemory demo # नमूना सेशंस सीड करें + recall साबित करें
+agentmemory connect claude-code # अपना एजेंट जोड़ें (अन्य: codex, cursor, gemini-cli, ...)
+```
+
+या `npx` के माध्यम से (इंस्टॉल की ज़रूरत नहीं):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+ध्यान दें — npx प्रति-वर्ज़न कैश करता है। अगर बेयर `npx @agentmemory/agentmemory` कोई पुराना रिलीज़ चला रहा है, तो नवीनतम को `npx -y @agentmemory/agentmemory@latest` से ज़बरदस्ती चलाएँ, या एक बार `rm -rf ~/.npm/_npx` से कैश साफ़ करें (macOS/Linux; Windows पर `%LOCALAPPDATA%\npm-cache\_npx` हटाएँ)। v0.9.16+ के बाद पहली npx रन आपको इनलाइन ग्लोबल इंस्टॉल करने का प्रॉम्प्ट देती है ताकि बेयर `agentmemory` कमांड हर जगह काम करे।
+
+पूर्ण विकल्प नीचे [क्विक स्टार्ट](#quick-start) में हैं। एजेंट-विशिष्ट कॉन्फ़िगरेशन [हर एजेंट के साथ काम करता है](#works-with-every-agent) में।
+
+---
+
+
+
+agentmemory किसी भी ऐसे एजेंट के साथ काम करता है जो hooks, MCP, या REST API सपोर्ट करता है। सभी एजेंट एक ही मेमोरी सर्वर साझा करते हैं।
+
+
+
+
+
+Claude Code
+native plugin + 12 hooks + MCP
+
+
+
+Codex CLI
+native plugin + 6 hooks + MCP
+
+
+
+OpenClaw
+native plugin + MCP
+
+
+
+Hermes
+native plugin + MCP
+
+
+
+pi
+native plugin + MCP
+
+
+
+OpenHuman
+native Memory trait बैकएंड
+
+
+
+Cursor
+MCP सर्वर
+
+
+
+Gemini CLI
+MCP सर्वर
+
+
+
+
+
+OpenCode
+22 hooks + MCP + plugin
+
+
+
+Cline
+MCP सर्वर
+
+
+
+Goose
+MCP सर्वर
+
+
+
+Kilo Code
+MCP सर्वर
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP सर्वर
+
+
+
+Windsurf
+MCP सर्वर
+
+
+
+Roo Code
+MCP सर्वर
+
+
+
+
+
+ MCP या HTTP बोलने वाले किसी भी एजेंट के साथ काम करता है। एक सर्वर, सभी के बीच साझा मेमोरी।
+
+
+---
+
+आप हर सेशन में वही आर्किटेक्चर समझाते हैं। आप वही bugs बार-बार खोजते हैं। आप वही प्राथमिकताएँ फिर से सिखाते हैं। बिल्ट-इन मेमोरी (CLAUDE.md, .cursorrules) 200 लाइनों पर सीमित है और पुरानी हो जाती है। agentmemory इसे ठीक करता है। यह चुपचाप आपके एजेंट की गतिविधियाँ कैप्चर करता है, उन्हें खोज योग्य मेमोरी में संकुचित करता है, और अगला सेशन शुरू होने पर सही संदर्भ इंजेक्ट करता है। एक कमांड। सभी एजेंट्स के साथ काम करता है।
+
+**क्या बदलता है:** सेशन 1 में आप JWT auth सेटअप करते हैं। सेशन 2 में आप rate limiting माँगते हैं। एजेंट को पहले से पता है कि आपकी auth `src/middleware/auth.ts` में jose middleware का उपयोग करती है, आपके tests token validation को कवर करते हैं, और आपने Edge compatibility के लिए jsonwebtoken के बजाय jose चुना है। फिर से समझाना नहीं। कॉपी-पेस्ट नहीं। एजेंट बस *जानता है*।
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **v0.9.0 में नया** — लैंडिंग साइट [agent-memory.dev](https://agent-memory.dev), फाइलसिस्टम कनेक्टर (`@agentmemory/fs-watcher`), स्टैंडअलोन MCP अब चल रहे सर्वर को प्रॉक्सी करता है ताकि hooks और व्यूअर सहमत हों, हर delete path में audit policy कोडिफाई की गई, small Node प्रक्रियाओं पर health अब `memory_critical` फ़्लैग नहीं करता। पूरे नोट्स [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18) में।
+
+---
+
+
+
+> Embedding मॉडल: `all-MiniLM-L6-v2` (local, free, कोई API key नहीं)। पूरी रिपोर्ट्स: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md)। प्रतिस्पर्धी तुलना: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory बनाम mem0, Letta, Khoj, claude-mem, Hippo।
+
+**स्थानीय रूप से reproduce करें:** [`eval/README.md`](../eval/README.md) — LongMemEval `_s` (public 500-Q) + `coding-agent-life-v1` (in-house 15-session corpus) के लिए adapter-pluggable harness। Grep / vector / agentmemory adapters साथ-साथ scored होते हैं, NDJSON output, प्रकाशित scorecards [`docs/benchmarks/`](../docs/benchmarks/) में जाते हैं।
+
+**[codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything), और [Graphify](https://github.com/safishamsi/graphify) के साथ जोड़ता है।** Code-graph indexing, multi-agent build pipelines, और docs / PDFs / images / videos में व्यापक knowledge graphs। agentmemory काम याद रखता है; ये तीन प्रोजेक्ट्स context layer के बाकी हिस्से को रोशन करते हैं। Recipes + question-routing table: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md)।
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
बिल्ट-इन (CLAUDE.md)
+
+
+
प्रकार
+
Memory engine + MCP सर्वर
+
Memory layer API
+
पूर्ण agent runtime
+
Static फाइल
+
+
+
Retrieval R@5
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
N/A (grep)
+
+
+
स्वचालित कैप्चर
+
12 hooks (शून्य मैनुअल प्रयास)
+
मैनुअल add() कॉल
+
एजेंट self-edits
+
मैनुअल editing
+
+
+
खोज
+
BM25 + Vector + Graph (RRF fusion)
+
Vector + Graph
+
Vector (archival)
+
सब कुछ context में लोड करता है
+
+
+
Multi-agent
+
MCP + REST + leases + signals
+
API (कोई coordination नहीं)
+
केवल Letta runtime में
+
प्रति-एजेंट फाइलें
+
+
+
Framework lock-in
+
कोई नहीं (कोई भी MCP क्लाइंट)
+
कोई नहीं
+
उच्च (Letta का उपयोग आवश्यक)
+
प्रति-एजेंट format
+
+
+
बाहरी निर्भरताएँ
+
कोई नहीं (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + vector DB
+
कोई नहीं
+
+
+
Memory lifecycle
+
4-tier consolidation + decay + auto-forget
+
Passive extraction
+
Agent-managed
+
मैनुअल pruning
+
+
+
Token दक्षता
+
~1,900 tokens/session ($10/yr)
+
integration पर निर्भर
+
Core memory context में
+
240 observations पर 22K+ tokens
+
+
+
Real-time व्यूअर
+
हाँ (port 3113)
+
Cloud dashboard
+
Cloud dashboard
+
नहीं
+
+
+
Self-hosted
+
हाँ (default)
+
Optional
+
Optional
+
हाँ
+
+
+
+---
+
+
+
+संगतता: यह रिलीज़ stable `iii-sdk` `^0.11.0` और iii-engine v0.11.x को टार्गेट करता है।
+
+### 30 सेकंड में आज़माएँ
+
+```bash
+# Terminal 1: सर्वर शुरू करें
+npx @agentmemory/agentmemory
+
+# Terminal 2: नमूना डेटा सीड करें और recall को कार्य में देखें
+npx @agentmemory/agentmemory demo
+```
+
+`demo` 3 यथार्थवादी सेशंस सीड करता है (JWT auth, N+1 query fix, rate limiting) और उन पर semantic searches चलाता है। जब आप "database performance optimization" खोजते हैं तो आप देखेंगे कि यह "N+1 query fix" ढूँढ़ लेता है — keyword matching ऐसा नहीं कर सकती।
+
+मेमोरी को लाइव बनते हुए देखने के लिए `http://localhost:3113` खोलें।
+
+### अनुशंसित: globally इंस्टॉल करें
+
+`npx` per-version कैश करता है। अगर आपने पिछले हफ्ते `npx @agentmemory/agentmemory@0.9.14` चलाया था, तो एक बेयर `npx @agentmemory/agentmemory` `~/.npm/_npx/` से stale 0.9.14 दे सकता है, न कि नवीनतम रिलीज़। एक बार इंस्टॉल करें और बेयर `agentmemory` कमांड हर जगह काम करता है:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# अगर macOS/Linux सिस्टम Node इंस्टॉल पर EACCES त्रुटि आती है, इसके साथ फिर से चलाएँ:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # सर्वर शुरू करें (npx form के समान)
+agentmemory stop # बंद करें
+agentmemory remove # हमने जो भी बनाया उसे अनइंस्टॉल करें
+agentmemory connect claude-code # एक एजेंट जोड़ें
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+v0.9.16 के बाद से, पहली npx रन आपको inline globally इंस्टॉल करने का प्रॉम्प्ट देती है — एक बार `Y` जवाब दें और तैयार। अगर आप skip करते हैं, तो ताज़ा fetch के लिए इनमें से किसी पर भी fallback करें:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # npm से नवीनतम को force करता है (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # केवल macOS/Linux (POSIX shell)
+```
+
+Windows / PowerShell पर, समतुल्य cache clear है `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — ऊपर का `npx -y ...@latest` form cross-platform विकल्प है।
+
+### Session Replay
+
+agentmemory द्वारा रिकॉर्ड किया गया हर सेशन replayable है। व्यूअर खोलें, **Replay** टैब चुनें, और timeline scrub करें: prompts, tool calls, tool results, और responses अलग events के रूप में render होते हैं, play/pause, speed control (0.5×–4×), और keyboard shortcuts (space toggle के लिए, arrows step के लिए) के साथ।
+
+क्या आपके पास पहले से पुरानी Claude Code JSONL transcripts हैं जिन्हें आप लाना चाहते हैं?
+
+```bash
+# डिफ़ॉल्ट ~/.claude/projects के तहत सब कुछ import करें
+npx @agentmemory/agentmemory import-jsonl
+
+# या एक अकेली फाइल import करें
+npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl
+```
+
+Imported सेशंस native ones के साथ Replay picker में दिखते हैं। हुड के नीचे प्रत्येक entry `mem::replay::load`, `mem::replay::sessions`, और `mem::replay::import-jsonl` iii functions के माध्यम से रूट होती है — कोई side-channel servers नहीं।
+
+### Upgrade / Maintenance
+
+जब आप जानबूझकर अपने local runtime को update करना चाहते हैं तो maintenance command का उपयोग करें:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+चेतावनी: यह कमांड वर्तमान workspace/runtime को mutate करता है। यह JavaScript निर्भरताएँ update कर सकता है, `cargo install iii-engine --force` चला सकता है, और Docker images खींच सकता है।
+
+Implementation विवरण `src/cli.ts` में हैं (`src/cli.ts:544-595` क्षेत्र के आसपास `runUpgrade` देखें)।
+
+### Claude Code (एक block, paste करें)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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.
+```
+
+#### Plugin install के बिना Claude Code (MCP-standalone path)
+
+अगर आप `/plugin install` का उपयोग करने के बजाय `~/.claude.json` के माध्यम से सीधे agentmemory का MCP सर्वर कनेक्ट करते हैं, तो Claude Code कभी भी `${CLAUDE_PLUGIN_ROOT}` resolve नहीं करता और आपको hook scripts को `~/.claude/settings.json` में absolute paths पर point करना पड़ता है। ये paths आमतौर पर agentmemory version को embed करते हैं (जैसे `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), इसलिए अगला upgrade चुपचाप हर hook को तोड़ देता है ([#508](https://github.com/rohitg00/agentmemory/issues/508))।
+
+Workaround:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+यह वही hook commands को `~/.claude/settings.json` में merge करता है, current installed `@agentmemory/agentmemory` package की bundled `plugin/` directory पर resolve किए गए absolute paths के साथ। agentmemory upgrade करने के बाद paths refresh करने के लिए कमांड फिर से चलाएँ। उसी फाइल में user entries संरक्षित होती हैं; केवल पिछली agentmemory entries replace होती हैं। `/plugin install` path अनुशंसित approach बनी रहती है।
+Remote या protected deployments के लिए, Claude Code को `AGENTMEMORY_URL` और `AGENTMEMORY_SECRET` set के साथ launch करें। Plugin दोनों values को इसके bundled MCP सर्वर के माध्यम से pass करता है; जब `AGENTMEMORY_URL` खाली होता है, तो MCP shim `http://localhost:3111` का उपयोग करता है।
+
+### Codex CLI (Codex plugin platform)
+
+```bash
+# 1. एक अलग terminal में memory सर्वर शुरू करें
+npx @agentmemory/agentmemory
+
+# 2. agentmemory marketplace register करें और plugin install करें
+codex plugin marketplace add rohitg00/agentmemory
+codex plugin add agentmemory@agentmemory
+```
+
+Codex plugin उसी `plugin/` directory से ship होता है जिससे Claude Code plugin। यह register करता है:
+
+- `@agentmemory/mcp` MCP सर्वर के रूप में (जब `AGENTMEMORY_URL` चल रहे agentmemory सर्वर पर point करता है, तो सभी 51 tools proxy करता है; कोई पहुँच योग्य सर्वर न होने पर locally 7 tools पर fallback करता है)
+- 6 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skills: `/recall`, `/remember`, `/session-history`, `/forget`
+
+Codex का hook engine hook subprocesses में `CLAUDE_PLUGIN_ROOT` inject करता है ([`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs) के अनुसार), इसलिए वही hook scripts duplication के बिना दोनों hosts में काम करते हैं। Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events केवल Claude-Code-only हैं और Codex के लिए register नहीं होते।
+
+#### Codex Desktop: plugin hooks वर्तमान में silent हैं (workaround उपलब्ध)
+
+`CodexHooks` और `PluginHooks` दोनों [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs) में stable + default-enabled हैं, लेकिन Codex Desktop builds वर्तमान में plugin-local `hooks.json` dispatch नहीं करते ([openai/codex#16430](https://github.com/openai/codex/issues/16430))। MCP tools अभी भी काम करते हैं; केवल lifecycle observations छूट जाते हैं।
+
+जब तक upstream fix land नहीं करता, वही hook commands को global `~/.codex/hooks.json` में mirror करें:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+यह `~/.codex/hooks.json` में एक idempotent block जोड़ता है जो bundled scripts के absolute paths को reference करता है (user-scope पर `${CLAUDE_PLUGIN_ROOT}` expansion की ज़रूरत नहीं)। agentmemory upgrade के बाद paths refresh करने के लिए वही कमांड फिर से चलाएँ। उसी फाइल में user entries संरक्षित रहती हैं; केवल पिछली agentmemory entries replace होती हैं।
+
+
+OpenClaw (यह prompt paste करें)
+
+```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 51 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`.
+```
+
+पूर्ण गाइड: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (यह prompt paste करें)
+
+```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 51 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.
+```
+
+पूर्ण गाइड: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### अन्य एजेंट्स
+
+मेमोरी सर्वर शुरू करें: `npx @agentmemory/agentmemory`
+
+agentmemory entry `mcpServers` shape का उपयोग करने वाले हर host में **वही MCP server block** है (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw):
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**इस entry को host की config file में मौजूदा `mcpServers` object में merge करें** — file को replace न करें। अगर फाइल में पहले से अन्य servers हैं, तो `mcpServers` के अंदर एक और key के रूप में `agentmemory` को उनके बगल में जोड़ें। अगर `mcpServers` पूरी तरह से missing है, तो block को `{ "mcpServers": { ... } }` के अंदर paste करें। `${VAR}` placeholders MCP-server launch पर shell से `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` inherit करते हैं — unset variables empty strings pass करते हैं और shim `http://localhost:3111` पर fallback होता है। एक wired entry local और remote (k8s / reverse-proxied) दोनों deployments को कवर करती है।
+
+| एजेंट | Config फाइल | नोट्स |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | `mcpServers` में merge करें। Website पर one-click deeplink भी उपलब्ध। |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | `mcpServers` में merge करें। Edit के बाद Claude Desktop restart करें। |
+| **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | वही `mcpServers` block। |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | वही `mcpServers` block। |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges)। |
+| **OpenClaw** | OpenClaw MCP config | वही `mcpServers` block, या गहरे [memory plugin](../integrations/openclaw/) का उपयोग करें। |
+| **Codex CLI (केवल MCP)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, या manually `[mcp_servers.agentmemory]` जोड़ें। |
+| **Codex CLI (पूर्ण plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` फिर `codex plugin add agentmemory@agentmemory`। MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills register करता है। Codex Desktop पर, [openai/codex#16430](https://github.com/openai/codex/issues/16430) land होने तक `agentmemory connect codex --with-hooks` भी चलाएँ — plugin hooks वर्तमान में वहाँ silent हैं। |
+| **OpenCode (केवल MCP)** | `opencode.json` | अलग shape — top-level `mcp` key, command array के रूप में: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`। |
+| **OpenCode (पूर्ण plugin)** | `plugin/opencode/` | Session lifecycle, messages, tools, errors को कवर करने वाले 22 auto-capture hooks। दो slash commands (`/recall`, `/remember`)। `plugin/opencode/` को अपने OpenCode workspace में copy करें और plugin entry को `opencode.json` में जोड़ें। पूरी hook table + gap analysis के लिए [`plugin/opencode/README.md`](../plugin/opencode/README.md) देखें। |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | [`integrations/pi`](../integrations/pi/) copy करें और pi restart करें। |
+| **Hermes Agent** | `~/.hermes/config.yaml` | गहरे [memory provider plugin](../integrations/hermes/) का उपयोग `memory.provider: agentmemory` के साथ करें। |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` standard `mcpServers` block लिखता है। Hook payload Claude Code के साथ field-compatible है, इसलिए मौजूदा 12-hook scripts modification के बिना काम करते हैं — उन्हें उसी `settings.json` के `hooks` section के माध्यम से जोड़ें। |
+| **Antigravity** (Gemini CLI को replace करता है) | `mcp_config.json` (Antigravity की User dir में) | `agentmemory connect antigravity` standard `mcpServers` block लिखता है। macOS: `~/Library/Application Support/Antigravity/User/`। Linux: `~/.config/Antigravity/User/`। 2026-06-18 Gemini CLI sunset के बाद उपयोग करें। |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` user-level config लिखता है। Workspace overrides आपके code के बगल में `.kiro/settings/mcp.json` में जाते हैं। |
+| **Goose** | Goose MCP settings UI | वही `mcpServers` block। |
+| **Aider** | n/a | REST API से सीधे बात करें: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`। |
+| **कोई भी एजेंट (32+)** | n/a | `npx skillkit install agentmemory` host को auto-detect करता है और merge करता है। |
+
+**Sandboxed MCP क्लाइंट्स** (Flatpak / Snap / प्रतिबंधात्मक containers) जो host के `localhost` तक नहीं पहुँच सकते: `env` block में `"AGENTMEMORY_FORCE_PROXY": "1"` भी set करें, और `AGENTMEMORY_URL` को एक ऐसे route पर point करें जिस तक sandbox वास्तव में पहुँच सकता है (जैसे आपका LAN IP)। Diagnostic walkthrough के लिए [#234](https://github.com/rohitg00/agentmemory/issues/234) देखें।
+
+### Programmatic access (Python / Rust / Node)
+
+agentmemory अपने core operations को iii functions के रूप में register करता है (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`)। iii SDK वाली कोई भी भाषा उन्हें `ws://localhost:49134` पर सीधे call कर सकती है — प्रति भाषा अलग REST क्लाइंट नहीं।
+
+```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"},
+})
+```
+
+कार्यशील उदाहरण: [`examples/python/`](../examples/python/) (quickstart + observation/recall flow)। iii runtime के बिना hosts के लिए REST `:3111` पर उपलब्ध रहता है।
+
+### Source से
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+यह agentmemory को local `iii-engine` के साथ शुरू करता है अगर `iii` पहले से installed है, या Docker उपलब्ध होने पर Docker Compose पर fallback करता है। REST, streams, और व्यूअर default रूप से `127.0.0.1` से bind करते हैं।
+
+`iii-engine` मैनुअली इंस्टॉल करें। **agentmemory वर्तमान में `iii-engine` को `v0.11.2` पर pin करता है** — `v0.11.6` एक नया sandbox-everything-via-`iii worker add` model introduce करता है जिसके लिए agentmemory को अभी refactor नहीं किया गया है। Refactor land होने के बाद pin हटा दी जाती है। अगर आपने sandbox model पर मैनुअली migrate किया है तो `AGENTMEMORY_III_VERSION=` से override करें।
+
+- **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:** `aarch64-apple-darwin` को `x86_64-apple-darwin` के साथ बदलें
+- **Linux x64:** `x86_64-unknown-linux-gnu` के साथ बदलें
+- **Linux arm64:** `aarch64-unknown-linux-gnu` के साथ बदलें
+- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2) से `iii-x86_64-pc-windows-msvc.zip` download करें, `iii.exe` extract करें, PATH में जोड़ें
+
+या Docker का उपयोग करें (bundled `docker-compose.yml` `iiidev/iii:0.11.2` खींचता है)। पूर्ण docs: [iii.dev/docs](https://iii.dev/docs)।
+
+### Windows
+
+agentmemory Windows 10/11 पर चलता है, लेकिन केवल Node.js package पर्याप्त नहीं है — आपको एक background process के रूप में `iii-engine` runtime (एक अलग native binary) भी चाहिए। आधिकारिक upstream installer एक `sh` script है और आज कोई PowerShell installer या scoop/winget package नहीं है, इसलिए Windows users के पास दो रास्ते हैं:
+
+**विकल्प A — Prebuilt Windows binary (अनुशंसित):**
+
+```powershell
+# 1. अपने browser में https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 खोलें
+# (हम v0.11.2 पर pin करते हैं जब तक agentmemory नए sandbox
+# model के लिए refactor नहीं हो जाता जो engine v0.11.6+ की आवश्यकता है)
+# 2. iii-x86_64-pc-windows-msvc.zip download करें
+# (या ARM machine पर हैं तो iii-aarch64-pc-windows-msvc.zip)
+# 3. PATH पर कहीं iii.exe extract करें, या यहाँ रखें:
+# %USERPROFILE%\.local\bin\iii.exe
+# (agentmemory उस location को automatically check करता है)
+# 4. Verify करें:
+iii --version
+# Print होना चाहिए: 0.11.2
+
+# 5. फिर agentmemory को सामान्य की तरह चलाएँ:
+npx -y @agentmemory/agentmemory
+```
+
+**विकल्प B — Docker Desktop:**
+
+```powershell
+# 1. Windows के लिए Docker Desktop install करें
+# 2. Docker Desktop शुरू करें और सुनिश्चित करें कि engine चल रहा है
+# 3. agentmemory चलाएँ — यह bundled compose file को auto-start करेगा:
+npx -y @agentmemory/agentmemory
+```
+
+**विकल्प C — केवल standalone MCP (कोई engine नहीं):** अगर आपको केवल अपने agent के लिए MCP tools चाहिए और REST API, व्यूअर, या cron jobs की ज़रूरत नहीं है, तो engine को पूरी तरह से skip करें:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# या shim package के माध्यम से:
+npx -y @agentmemory/mcp
+```
+
+**Windows के लिए diagnostics:** अगर `npx @agentmemory/agentmemory` fail करता है, तो वास्तविक engine stderr देखने के लिए `--verbose` के साथ फिर से चलाएँ। सामान्य failure modes:
+
+| लक्षण | समाधान |
+|---|---|
+| `iii-engine process started` फिर `did not become ready within 15s` | Engine startup पर crashed — `--verbose` के साथ फिर से चलाएँ, stderr check करें |
+| `Could not start iii-engine` | न तो `iii.exe` न ही Docker installed है। ऊपर विकल्प A या B देखें |
+| Port conflict | `netstat -ano \| findstr :3111` से देखें कि क्या bind है, फिर उसे kill करें या `--port ` का उपयोग करें |
+| Docker installed होने पर भी Docker fallback skip हो रहा है | सुनिश्चित करें कि Docker Desktop वास्तव में चल रहा है (system tray icon) |
+
+> नोट: कोई `cargo install iii-engine` नहीं है — `iii` crates.io पर publish नहीं है। केवल समर्थित install methods ऊपर prebuilt binary, upstream `sh` install script (केवल macOS/Linux), और Docker image हैं।
+
+---
+
+
Deploy
+
+Managed hosts के लिए one-click templates। प्रत्येक एक self-contained
+Dockerfile ship करता है जो npm से `@agentmemory/agentmemory` खींचता है
+और आधिकारिक `iiidev/iii` Docker Hub image से iii engine binary को
+copy करता है — pre-built agentmemory image की आवश्यकता नहीं। Persistent
+storage `/data` पर mount होती है; first-boot entrypoint npm-bundled
+iii config (जो `127.0.0.1` से bind करती है) को एक deploy-tuned config
+से overwrite करता है जो `0.0.0.0` से bind करती है और absolute `/data`
+paths का उपयोग करती है, HMAC secret generate करती है, फिर agentmemory
+CLI को exec करने से पहले `gosu` के माध्यम से privileges को `root` से
+`node` पर drop करती है।
+
+
+
+
+
+
+Render का one-click deploy button repository root पर `render.yaml` की आवश्यकता रखता है,
+जिसे हम जानबूझकर साफ़ रखते हैं। In-repo blueprint पर manually point करने के लिए
+[`deploy/render/`](../deploy/render/README.md) में documented Render Blueprint flow का उपयोग करें।
+
+पूर्ण setup विवरण (HMAC capture, viewer SSH tunnel,
+rotation, backup, cost floors) [`deploy/`](../deploy/README.md) में रहते हैं:
+
+- [`deploy/fly`](../deploy/fly/README.md) — `auto_stop_machines = "stop"` के साथ
+ single machine; सबसे सस्ता idle।
+- [`deploy/railway`](../deploy/railway/README.md) — Hobby plan flat fee,
+ dashboard में volume।
+- [`deploy/render`](../deploy/render/README.md) — Blueprint flow,
+ paid plans पर automatic disk snapshots।
+- [`deploy/coolify`](../deploy/coolify/README.md) — अपने स्वयं के VPS पर
+ [Coolify](https://coolify.io/self-hosted) के माध्यम से self-hosted; वही Docker
+ Compose stack, आप host और data के मालिक हैं।
+
+केवल port `3111` publish किया जाता है। `3113` पर viewer container के अंदर
+loopback से bound रहता है — हर template का README उस तक पहुँचने के लिए
+SSH-tunnel pattern को document करता है।
+
+---
+
+
+
+हर coding agent सेशन समाप्त होने पर सब कुछ भूल जाता है। आप हर सेशन के पहले 5 मिनट अपने stack को फिर से समझाने में बर्बाद करते हैं। agentmemory पृष्ठभूमि में चलता है और इसे पूरी तरह से समाप्त कर देता है।
+
+```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.
+```
+
+### बिल्ट-इन agent memory से तुलना
+
+हर AI coding agent बिल्ट-इन memory के साथ ship होता है — Claude Code में `MEMORY.md` है, Cursor में notepads हैं, Cline में memory bank है। ये sticky notes की तरह काम करते हैं। agentmemory उन sticky notes के पीछे का searchable database है।
+
+| | बिल्ट-इन (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Scale | 200-line cap | असीमित |
+| खोज | सब कुछ context में load करता है | BM25 + vector + graph (केवल top-K) |
+| Token cost | 240 observations पर 22K+ | ~1,900 tokens (92% कम) |
+| Cross-agent | प्रति-agent फाइलें | MCP + REST (कोई भी agent) |
+| Coordination | कोई नहीं | Leases, signals, actions, routines |
+| Observability | फाइलें मैनुअल पढ़ें | :3113 पर real-time viewer |
+
+---
+
+
+
+### 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
+
+मानव मस्तिष्क memory को कैसे process करता है उससे प्रेरित — sleep consolidation से बहुत अलग नहीं।
+
+| Tier | क्या | Analogy |
+|------|------|---------|
+| **Working** | Tool use से raw observations | Short-term memory |
+| **Episodic** | संकुचित session summaries | "क्या हुआ" |
+| **Semantic** | निकाले गए facts और patterns | "मैं क्या जानता हूँ" |
+| **Procedural** | Workflows और decision patterns | "कैसे करें" |
+
+Memories समय के साथ decay होती हैं (Ebbinghaus curve)। बार-बार access की जाने वाली memories मज़बूत होती हैं। पुरानी memories auto-evict होती हैं। Contradictions detect और resolve होती हैं।
+
+### क्या Capture होता है
+
+| 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` | Compaction से पहले memory को re-inject करता है |
+| `SubagentStart/Stop` | Sub-agent lifecycle |
+| `Stop` | End-of-session summary |
+| `SessionEnd` | Session complete marker |
+
+### मुख्य क्षमताएँ
+
+| क्षमता | विवरण |
+|---|---|
+| **Automatic capture** | हर tool use hooks के माध्यम से record होता है — शून्य manual effort |
+| **Semantic search** | RRF fusion के साथ BM25 + vector + knowledge graph |
+| **Memory evolution** | Versioning, supersession, relationship graphs |
+| **Auto-forgetting** | TTL expiry, contradiction detection, importance eviction |
+| **Privacy first** | API keys, secrets, `` tags storage से पहले strip होते हैं |
+| **Self-healing** | Circuit breaker, provider fallback chain, health monitoring |
+| **Claude bridge** | MEMORY.md के साथ bi-directional sync |
+| **Knowledge graph** | Entity extraction + BFS traversal |
+| **Team memory** | Team members के बीच namespaced shared + private |
+| **Citation provenance** | किसी भी memory को source observations तक trace करें |
+| **Git snapshots** | Memory state को version, rollback, और diff करें |
+
+---
+
+
+
+तीन signals को combine करने वाला triple-stream retrieval:
+
+| Stream | यह क्या करता है | कब |
+|---|---|---|
+| **BM25** | Synonym expansion के साथ stemmed keyword matching | हमेशा on |
+| **Vector** | Dense embeddings पर cosine similarity | Embedding provider configured |
+| **Graph** | Entity matching के माध्यम से knowledge graph traversal | Query में entities detected |
+
+Reciprocal Rank Fusion (RRF, k=60) के साथ fuse होता है और session-diversified होता है (प्रति session max 3 results)।
+
+BM25 box से बाहर ही Greek, Cyrillic, Hebrew, Arabic, और accented Latin को tokenize करता है। Chinese / Japanese / Korean memories के लिए, CJK runs को word-level tokens में split करने के लिए optional segmenters install करें (`npm install @node-rs/jieba tiny-segmenter`); उनके बिना, agentmemory soft-fall back होकर whole-run tokenization पर जाता है और stderr पर एक-बार hint print करता है।
+
+### Embedding providers
+
+agentmemory आपके provider को auto-detect करता है। सर्वोत्तम परिणामों के लिए, local embeddings install करें (free):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Provider | Model | Cost | नोट्स |
+|---|---|---|---|
+| **Local (अनुशंसित)** | `all-MiniLM-L6-v2` | Free | Offline, BM25-only पर +8pp recall |
+| Gemini | `gemini-embedding-001` | Free tier | 100+ भाषाएँ, 768/1536/3072 dims (MRL), 2048-token input। `text-embedding-004` को replace करता है ([deprecated, 14 जनवरी 2026 को shutdown](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | $0.02/1M | उच्चतम quality |
+| Voyage AI | `voyage-code-3` | Paid | Code के लिए optimized |
+| Cohere | `embed-english-v3.0` | Free trial | General purpose |
+| OpenRouter | कोई भी model | भिन्न | Multi-model proxy |
+
+---
+
+
+
+53 tools, 6 resources, 3 prompts, और 4 skills — किसी भी agent के लिए सबसे व्यापक MCP memory toolkit।
+
+> **MCP shim बनाम full server:** published `@agentmemory/mcp` package एक thin shim है। यह full 51-tool surface को **केवल तभी expose करता है जब यह `AGENTMEMORY_URL` के माध्यम से चल रहे agentmemory server तक पहुँच सके** (proxy mode)। कोई पहुँच योग्य server न होने पर, shim 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`) पर fallback करता है। `AGENTMEMORY_TOOLS=core|all` env var एक *server-side* flag है — shim के `env` block में set करने का कोई असर नहीं। अगर आप Cursor / OpenCode / Gemini CLI में केवल 7 tools देखते हैं, तो `npx @agentmemory/agentmemory` (या Docker stack) शुरू करें और `AGENTMEMORY_URL=http://localhost:3111` set करें।
+
+### 51 Tools
+
+
+Core tools (हमेशा उपलब्ध)
+
+| Tool | विवरण |
+|------|-------------|
+| `memory_recall` | पिछले observations खोजें |
+| `memory_compress_file` | Structure preserve करते हुए markdown files compress करें |
+| `memory_save` | एक insight, decision, या pattern save करें |
+| `memory_patterns` | Recurring patterns detect करें |
+| `memory_smart_search` | Hybrid semantic + keyword search |
+| `memory_file_history` | विशिष्ट files के बारे में पिछले observations |
+| `memory_sessions` | Recent sessions list करें |
+| `memory_timeline` | Chronological observations |
+| `memory_profile` | Project profile (concepts, files, patterns) |
+| `memory_export` | सभी memory data export करें |
+| `memory_relations` | Relationship graph query करें |
+
+
+
+
+Extended tools (कुल 51 — AGENTMEMORY_TOOLS=all set करें)
+
+| Tool | विवरण |
+|------|-------------|
+| `memory_patterns` | Recurring patterns detect करें |
+| `memory_timeline` | Chronological observations |
+| `memory_relations` | Relationship graph query करें |
+| `memory_graph_query` | Knowledge graph traversal |
+| `memory_consolidate` | 4-tier consolidation चलाएँ |
+| `memory_claude_bridge_sync` | MEMORY.md के साथ sync करें |
+| `memory_team_share` | Team members के साथ share करें |
+| `memory_team_feed` | हाल ही में shared items |
+| `memory_audit` | Operations का audit trail |
+| `memory_governance_delete` | Audit trail के साथ delete करें |
+| `memory_snapshot_create` | Git-versioned snapshot |
+| `memory_action_create` | Dependencies के साथ work items create करें |
+| `memory_action_update` | Action status update करें |
+| `memory_frontier` | Priority द्वारा ranked unblocked actions |
+| `memory_next` | Single most important next action |
+| `memory_lease` | Exclusive action leases (multi-agent) |
+| `memory_routine_run` | Workflow routines instantiate करें |
+| `memory_signal_send` | Inter-agent messaging |
+| `memory_signal_read` | Receipts के साथ messages पढ़ें |
+| `memory_checkpoint` | External condition gates |
+| `memory_mesh_sync` | Instances के बीच P2P sync |
+| `memory_sentinel_create` | Event-driven watchers |
+| `memory_sentinel_trigger` | Sentinels externally fire करें |
+| `memory_sketch_create` | Ephemeral action graphs |
+| `memory_sketch_promote` | Permanent पर promote करें |
+| `memory_crystallize` | Action chains compact करें |
+| `memory_diagnose` | Health checks |
+| `memory_heal` | Stuck state को auto-fix करें |
+| `memory_facet_tag` | Dimension:value tags |
+| `memory_facet_query` | Facet tags द्वारा query करें |
+| `memory_verify` | Provenance trace करें |
+
+
+
+### 6 Resources · 3 Prompts · 4 Skills
+
+| प्रकार | नाम | विवरण |
+|------|------|-------------|
+| Resource | `agentmemory://status` | Health, session count, memory count |
+| Resource | `agentmemory://project/{name}/profile` | Per-project intelligence |
+| Resource | `agentmemory://memories/latest` | नवीनतम 10 active memories |
+| Resource | `agentmemory://graph/stats` | Knowledge graph statistics |
+| Prompt | `recall_context` | Search + context messages return करें |
+| Prompt | `session_handoff` | Agents के बीच handoff data |
+| Prompt | `detect_patterns` | Recurring patterns analyze करें |
+| Skill | `/recall` | Memory खोजें |
+| Skill | `/remember` | Long-term memory में save करें |
+| Skill | `/session-history` | हाल के session summaries |
+| Skill | `/forget` | Observations/sessions delete करें |
+
+### Standalone MCP
+
+Full server के बिना चलाएँ — किसी भी MCP client के लिए। इनमें से कोई भी काम करता है:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (हमेशा उपलब्ध)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+या अपने agent की MCP config में जोड़ें:
+
+अधिकांश agents (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+`agentmemory` entry को file को replace करने के बजाय अपने host के मौजूदा `mcpServers` object में merge करें। होस्ट के `localhost` तक नहीं पहुँच सकने वाले sandboxed clients के लिए, env block में `"AGENTMEMORY_FORCE_PROXY": "1"` जोड़ें और `AGENTMEMORY_URL` को एक ऐसे route पर set करें जिस तक sandbox पहुँच सकता है।
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Plugin file को repo से copy करें:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Port `3113` पर auto-start होता है। Live observation stream, session explorer, memory browser, knowledge graph visualization, और health dashboard।
+
+```bash
+open http://localhost:3113
+```
+
+व्यूअर server default रूप से `127.0.0.1` से bind होता है। REST-served `/agentmemory/viewer` endpoint सामान्य `AGENTMEMORY_SECRET` bearer-token नियमों का पालन करता है। CSP headers per-response script nonce का उपयोग करते हैं और inline handler attributes को disable करते हैं (`script-src-attr 'none'`)।
+
+---
+
+
+
+`:3113` पर viewer दिखाता है कि आपके agent ने क्या **याद रखा**। [iii console](https://iii.dev/docs/console) दिखाता है कि आपके agent ने क्या **किया** — हर memory op एक OpenTelemetry trace के रूप में, हर KV entry editable, हर function invocable, हर stream tappable। एक ही memory पर दो windows: एक product-shaped, एक engine-shaped।
+
+`memory_smart_search` को fire होते देखें और BM25 scan → embedding lookup → RRF fusion → reranker को waterfall के रूप में देखें। KV browser में stuck consolidation timer को edit करें। `PostToolUse` hook को tweaked payload के साथ replay करें। WebSocket stream को pin करें और observations को live land होते देखें।
+
+agentmemory इसे free में ship करता है क्योंकि हर function, trigger, state scope, और stream एक iii primitive है — कुछ भी custom नहीं, instrument करने के लिए कुछ नहीं।
+
+
+
+
+ Workers page: हर connected worker — agentmemory स्वयं सहित — PID, function count, runtime, और last-seen के साथ।
+
+
+**पहले से installed।** Console `iii` के साथ ship होता है — कोई अलग installer नहीं।
+
+**agentmemory के साथ launch करें:**
+
+```bash
+# agentmemory viewer port 3113 रखता है, तो console को 3114 पर चलाएँ।
+# Engine REST (3111), WebSocket (3112), और bridge (49134) defaults agentmemory से match करते हैं।
+iii console --port 3114
+```
+
+फिर `http://localhost:3114` खोलें। Experimental architecture-graph page के लिए `--enable-flow` जोड़ें।
+
+केवल तभी engine endpoints override करें जब आपने उन्हें move किया हो:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Console से आप क्या कर सकते हैं:**
+
+| Page | इसके लिए उपयोग करें |
+|------|-----------|
+| **Workers** | हर connected worker और उसके live metrics देखें — agentmemory worker सहित। |
+| **Functions** | agentmemory के किसी भी function को सीधे JSON payload के साथ invoke करें — client जोड़े बिना `memory.recall`, `memory.consolidate`, `graph.query` test करने के लिए उपयोगी। |
+| **Triggers** | HTTP, cron, event, और state triggers replay करें — consolidation cron को manually fire करें, HTTP route retry करें, एक state change emit करें। |
+| **States** | Full CRUD के साथ KV browser — sessions, memory slots, lifecycle timers, embeddings index — values को in place edit करें। |
+| **Streams** | Memory writes, hook events, और observation updates के लिए live WebSocket monitor क्योंकि वे iii streams से बहते हैं। |
+| **Queues** | Durable queue topics + dead-letter management। Failed embedding / compression jobs को replay या drop करें। |
+| **Traces** | OpenTelemetry waterfall / flame / service-breakdown views। `trace_id` से filter करें ताकि देख सकें कि एक `memory.search` ने वास्तव में कौन से functions, DB calls, और embedding requests produce किए। |
+| **Logs** | Trace/span IDs से correlated और filtered structured OTEL logs। |
+| **Config** | Runtime configuration — देखें कि आपका engine किन workers, providers, और ports के साथ चल रहा है। |
+| **Flow** | (Optional, `--enable-flow`) हर worker, trigger, और stream का interactive architecture graph। |
+
+
+
+
+ Traces: हर memory operation के लिए waterfall / flame / service breakdown।
+
+
+**Traces पहले से on हैं:**
+
+`iii-config.yaml` `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs) के साथ ship होता है। कोई extra config की ज़रूरत नहीं — जैसे ही agentmemory शुरू होता है, हर memory operation एक trace span और एक structured log emit करता है जिसे console पढ़ सकता है।
+
+अगर आप इसके बजाय Jaeger/Honeycomb/Grafana Tempo पर export करना चाहते हैं, तो `exporter: memory` को `exporter: otlp` में बदलें और iii के observability docs के अनुसार collector endpoint set करें।
+
+> **ध्यान दें:** console पर कोई auth enforce नहीं है — इसे `127.0.0.1` (default) से bound रखें और इसे कभी publicly expose न करें।
+
+---
+
+
+
+agentmemory **पहले से एक चल रहा [iii](https://iii.dev) instance है**। Functions, triggers, KV state, streams, OTEL traces — यह सब iii primitives हैं। आपने Postgres, Redis, Express, pm2, या Prometheus install नहीं किया, क्योंकि iii उन्हें replace करता है।
+
+इसका मतलब है कि एक और कमांड agentmemory को एक पूरी नई capability के साथ extend करती है।
+
+### एक command के साथ agentmemory को extend करें
+
+```bash
+iii worker add iii-pubsub # memory writes को हर connected instance पर fan out करें
+iii worker add iii-cron # scheduled consolidation, decay sweeps, snapshot rotation
+iii worker add iii-queue # embedding + compression jobs के लिए durable retries
+iii worker add iii-observability # हर memory op पर OTEL traces (default on)
+iii worker add iii-sandbox # recalled code को isolated microVM के अंदर चलाएँ
+iii worker add iii-database # एक SQL-backed state adapter में swap करें
+iii worker add mcp # agentmemory MCP के साथ-साथ generic MCP host
+```
+
+प्रत्येक `iii worker add` उसी engine में नए functions और triggers register करता है जिस पर agentmemory पहले से चल रहा है। Viewer और console उन्हें तुरंत pick करते हैं — कोई reload नहीं, कोई नया integration नहीं, कोई नया container नहीं।
+
+| `iii worker add` | agentmemory के ऊपर आपको क्या मिलता है |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Multi-instance memory: हर `remember` fan out होती है, हर `search` union पढ़ता है |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Scheduled lifecycle — रात की consolidation, साप्ताहिक snapshots, fixed clock पर decay |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable retries: failed embedding + compression jobs restart से बचते हैं, कोई lost observations नहीं |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | हर function पर OTEL traces, metrics, logs — दिन एक से `iii-config.yaml` में wired |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall` से निकला code throwaway VM के अंदर चलता है, आपके shell में नहीं |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | जब आप in-memory KV defaults से बाहर निकलते हैं तो SQL-backed state adapter |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory के साथ-साथ extra MCP servers खड़े करें, वही engine share करें |
+
+Full registry: [workers.iii.dev](https://workers.iii.dev)। वहाँ हर worker उन्हीं primitives के माध्यम से compose करता है जिनका agentmemory उपयोग करता है — और आपके पास पहले से जो agentmemory है, वह उनमें से एक है।
+
+### iii क्या replace करता है
+
+| Traditional stack | agentmemory उपयोग करता है |
+|---|---|
+| 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 ` |
+
+**118 source files · ~21,800 LOC · 950+ tests · 123 functions · 34 KV scopes** — सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है।
+
+---
+
+
+
+### LLM Providers
+
+agentmemory आपके environment से auto-detect करता है। Default रूप से, जब तक आप एक provider configure नहीं करते या Claude subscription fallback में explicitly opt in नहीं करते, कोई LLM calls नहीं की जातीं।
+
+| Provider | Config | नोट्स |
+|----------|--------|-------|
+| **No-op (default)** | कोई config की ज़रूरत नहीं | LLM-backed compress/summarize DISABLED है। Synthetic BM25 compression + recall अभी भी काम करते हैं। अगर आप पहले Claude-subscription fallback पर निर्भर थे तो नीचे `AGENTMEMORY_ALLOW_AGENT_SDK` देखें। |
+| Anthropic API | `ANTHROPIC_API_KEY` | Per-token billing |
+| MiniMax | `MINIMAX_API_KEY` | Anthropic-compatible |
+| Gemini | `GEMINI_API_KEY` | Embeddings भी enable करता है |
+| OpenRouter | `OPENROUTER_API_KEY` | कोई भी model |
+| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | केवल opt-in। `@anthropic-ai/claude-agent-sdk` sessions spawn करता है — पहले unbounded Stop-hook recursion का कारण था (#149 follow-up) तो यह अब default नहीं है। |
+
+### Cost-aware model selection
+
+Background compression हर observation पर चलता है, इसलिए model choice monthly spend को meaningfully बदलता है। Captured workload data: 635 requests / 888K tokens / 35 hours of active use, 2026-05-23 pricing पर तीन OpenRouter models पर चलाया गया।
+
+| Tier | Model | Input / 1M | Output / 1M | Captured 35h के लिए cost | नोट्स |
+|------|-------|------------|-------------|---------------------------|-------|
+| अनुशंसित | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Sonnet से ~10× कम cost पर solid compression + summarization quality। |
+| अनुशंसित | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | पुराना लेकिन केवल-compression workloads के लिए अभी भी ठीक। |
+| अनुशंसित | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | अगर आपके sessions भारी रूप से code-shaped हैं तो strong code reasoning। |
+| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | High quality लेकिन always-on background work के लिए महंगा। |
+| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Sonnet के समान tier। |
+| बचें | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Reasoning-class model; compression के लिए massive overspend। |
+
+जब `OPENROUTER_MODEL` premium-tier pattern से match करता है तो agentmemory एक runtime warning print करता है। जब आप informed choice कर लें तो silence करने के लिए `AGENTMEMORY_SUPPRESS_COST_WARNING=1` set करें।
+
+Memory work के लिए quality बनाम cost tradeoff: compression एक summarization task है जिसमें अपेक्षाकृत loose quality bars हैं (agent summary को re-read करता है, user नहीं)। DeepSeek-V4-Pro / Qwen3-Coder इस task पर Sonnet से rounding error के भीतर land होते हैं जबकि ~10× कम cost में। Premium-tier models को उन queries के लिए save करें जिन्हें आप सीधे पढ़ते हैं।
+
+Sources: [Sonnet 4.6 के लिए OpenRouter pricing](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek pricing नोट्स](https://api-docs.deepseek.com/quick_start/pricing/)।
+
+### Multi-agent memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+Multi-agent setups में जहाँ कई roles एक agentmemory server share करते हैं (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` हर write को उस role से tag करता है जिसने इसे किया। `AGENTMEMORY_AGENT_SCOPE` यह control करता है कि recall उस tag के द्वारा filter करता है या नहीं।
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+दो modes:
+
+| Mode | Writes को tag करें | Recall filter करें | कब उपयोग करें |
+|------|------------|---------------|-------------|
+| `shared` (default) | हाँ | नहीं | Audit trail के साथ cross-agent context। Architect देख सकता है कि developer ने क्या note किया, लेकिन हर row record करती है कि किसने कहा। |
+| `isolated` | हाँ | हाँ | सख्त separation। Architect कभी developer के observations / memories / sessions नहीं देखता। |
+
+जब `AGENT_ID` set होता है तो क्या tagged होता है: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`। Role `api::session::start` → `mem::observe` → `mem::compress` → KV से flow करता है।
+
+Isolated mode में क्या filter होता है: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`। प्रत्येक endpoint per-request override के लिए `?agentId=` और env scope से पूरी तरह से opt out करने के लिए `?agentId=*` accept करता है। `/memories` AGENT_ID से पहले के memories को surface करने के लिए `?includeOrphans=true` भी accept करता है जिनकी `agentId` undefined है।
+
+SDK / REST layer पर per-call override: हर mutating endpoint (`/session/start`, `/remember`) request body में एक `agentId` field accept करता है जो env से जीतता है। एक server process के माध्यम से कई roles को route करने वाले runtimes के लिए उपयोगी।
+
+जब `AGENT_ID` unset होता है, तो memory unscoped रहती है (legacy behavior, कोई tags नहीं, कोई filters नहीं)।
+
+### Ports
+
+agentmemory + iii-engine default रूप से चार ports पर bind होते हैं। अगर एक restart `port in use` के साथ fail होता है, तो यह table बताती है कि किस process को देखना है।
+
+| Port | Process | उद्देश्य | Env override |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Internal streams worker (agentmemory + viewer द्वारा consumed) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Real-time viewer (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — workers यहाँ register होते हैं, OTel telemetry यहाँ से flow होती है | `III_ENGINE_URL` (full URL, default `ws://localhost:49134`) |
+
+Crashed run के बाद ports bound रहने पर stale-process cleanup:
+
+```bash
+# macOS / Linux — हर port पर जो भी है उसे ढूँढ़ें और kill करें
+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` graceful shutdown पर worker और engine pidfile दोनों को साफ़ रूप से reap करता है (#640, #474)। ऊपर का manual cleanup केवल post-crash case के लिए है जहाँ कोई भी pidfile पीछे नहीं छोड़ी गई।
+
+### Config File
+
+हर shell में variables export करने के बजाय agentmemory runtime configuration को `~/.agentmemory/.env` में रखें। अगर viewer `export ANTHROPIC_API_KEY=...` जैसा setup hint दिखाता है, तो इसे `export` prefix के बिना इस file में `ANTHROPIC_API_KEY=...` के रूप में copy करें, फिर agentmemory restart करें।
+
+Process environment variables अभी भी काम करते हैं और file में values पर precedence लेते हैं।
+
+Windows पर, वही file `%USERPROFILE%\.agentmemory\.env` पर रहती है:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+API key के बजाय Claude Code Pro/Max subscription के साथ test करने के लिए, explicitly opt in करें:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+अगर आप graph या consolidation features चाहते हैं तो उसी file में उन्हें on करें:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Environment Variables
+
+`~/.agentmemory/.env` बनाएँ:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+Port `3111` पर 124 endpoints। REST API default रूप से `127.0.0.1` से bind होता है। `AGENTMEMORY_SECRET` set होने पर protected endpoints `Authorization: Bearer ` की आवश्यकता रखते हैं, और mesh sync endpoints दोनों peers पर `AGENTMEMORY_SECRET` की आवश्यकता रखते हैं।
+
+
+मुख्य endpoints
+
+| Method | Path | विवरण |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | Health check (हमेशा public) |
+| `POST` | `/agentmemory/session/start` | Session शुरू करें + context प्राप्त करें |
+| `POST` | `/agentmemory/session/end` | Session समाप्त करें |
+| `POST` | `/agentmemory/observe` | Observation capture करें |
+| `POST` | `/agentmemory/smart-search` | Hybrid search |
+| `POST` | `/agentmemory/context` | Context generate करें |
+| `POST` | `/agentmemory/remember` | Long-term memory में save करें |
+| `POST` | `/agentmemory/forget` | Observations delete करें |
+| `POST` | `/agentmemory/enrich` | File context + memories + bugs |
+| `GET` | `/agentmemory/profile` | Project profile |
+| `GET` | `/agentmemory/export` | सभी data export करें |
+| `POST` | `/agentmemory/import` | JSON से import करें |
+| `POST` | `/agentmemory/graph/query` | Knowledge graph query |
+| `POST` | `/agentmemory/team/share` | Team के साथ share करें |
+| `GET` | `/agentmemory/audit` | Audit trail |
+
+Full endpoint list: [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (running services की आवश्यकता है)
+```
+
+**आवश्यकताएँ:** Node.js >= 20, [iii-engine](https://iii.dev/docs) या Docker
+
+
+
+ コーディングエージェントがすべてを記憶します。もう説明し直す必要はありません。
+ Built on iii engine
+
+ Claude Code、Cursor、Gemini CLI、Codex CLI、Hermes、OpenClaw、pi、OpenCode、そしてあらゆる MCP クライアントのための永続メモリ。
+
+
+ 코딩 에이전트가 모든 것을 기억합니다. 더 이상 다시 설명할 필요가 없습니다.
+ Built on iii engine
+
+ Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode 및 모든 MCP 클라이언트를 위한 영구 메모리입니다.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+또는 `npx`로 설치 없이 실행:
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+참고 — npx는 버전별로 캐싱합니다. 단순한 `npx @agentmemory/agentmemory`가 이전 릴리스를 제공한다면, `npx -y @agentmemory/agentmemory@latest`로 최신 버전을 강제로 가져오거나 `rm -rf ~/.npm/_npx`로 캐시를 한 번 비우십시오(macOS/Linux. Windows에서는 `%LOCALAPPDATA%\npm-cache\_npx`를 삭제). v0.9.16부터의 첫 npx 실행은 전역 설치 여부를 인라인으로 묻기 때문에, 이후에는 어디서나 단순한 `agentmemory` 명령이 동작합니다.
+
+전체 옵션은 아래 [빠른 시작](#quick-start)을 참고하십시오. 에이전트별 연결 방법은 [모든 에이전트와 호환](#works-with-every-agent) 섹션에서 확인할 수 있습니다.
+
+---
+
+
+
+agentmemory는 hooks, MCP, REST API를 지원하는 모든 에이전트와 호환됩니다. 모든 에이전트는 동일한 메모리 서버를 공유합니다.
+
+
+
+
+
+Claude Code
+native plugin + 12 hooks + MCP
+
+
+
+Codex CLI
+native plugin + 6 hooks + MCP
+
+
+
+OpenClaw
+native plugin + MCP
+
+
+
+Hermes
+native plugin + MCP
+
+
+
+pi
+native plugin + MCP
+
+
+
+OpenHuman
+native Memory trait backend
+
+
+
+Cursor
+MCP server
+
+
+
+Gemini CLI
+MCP server
+
+
+
+
+
+OpenCode
+22 hooks + MCP + plugin
+
+
+
+Cline
+MCP server
+
+
+
+Goose
+MCP server
+
+
+
+Kilo Code
+MCP server
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP server
+
+
+
+Windsurf
+MCP server
+
+
+
+Roo Code
+MCP server
+
+
+
+
+
+ MCP 또는 HTTP를 지원하는 모든 에이전트와 호환됩니다. 서버 하나, 모든 에이전트가 메모리를 공유합니다.
+
+
+---
+
+세션마다 같은 아키텍처를 설명하고, 같은 버그를 다시 찾고, 같은 선호 사항을 다시 가르치게 됩니다. 내장 메모리(CLAUDE.md, .cursorrules)는 200줄 한도에서 멈추고 금세 낡습니다. agentmemory가 이 문제를 해결합니다. 에이전트의 동작을 조용히 캡처하여 검색 가능한 메모리로 압축하고, 다음 세션이 시작될 때 적절한 컨텍스트를 주입합니다. 명령 하나면 됩니다. 모든 에이전트에서 동작합니다.
+
+**무엇이 바뀌는가:** 세션 1에서 JWT 인증을 설정합니다. 세션 2에서 rate limiting을 요청합니다. 에이전트는 이미 인증이 `src/middleware/auth.ts`의 jose 미들웨어로 처리된다는 것, 테스트가 토큰 검증을 다룬다는 것, 그리고 Edge 호환성 때문에 jsonwebtoken 대신 jose를 선택했다는 것을 알고 있습니다. 다시 설명할 필요도, 복사·붙여넣기도 필요 없습니다. 에이전트가 그냥 *알고* 있습니다.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **v0.9.0의 새로운 기능** — [agent-memory.dev](https://agent-memory.dev)의 랜딩 사이트, 파일시스템 커넥터(`@agentmemory/fs-watcher`), 독립형 MCP가 이제 실행 중인 서버로 프록시되어 hooks와 뷰어가 일치합니다. 모든 삭제 경로에 감사 정책이 코드로 명문화되었고, 작은 Node 프로세스에서 health가 `memory_critical`로 잘못 표시되지 않습니다. 전체 노트는 [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18)에서 확인할 수 있습니다.
+
+---
+
+
+
+> 임베딩 모델: `all-MiniLM-L6-v2` (로컬, 무료, API 키 불필요). 전체 보고서: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). 경쟁 제품 비교: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory 대 mem0, Letta, Khoj, claude-mem, Hippo.
+
+**로컬 재현 방법:** [`eval/README.md`](../eval/README.md) — LongMemEval `_s`(공개 500-Q)와 `coding-agent-life-v1`(자체 15-세션 코퍼스)을 위한 어댑터 플러그형 하니스. grep / vector / agentmemory 어댑터를 나란히 평가하고, NDJSON으로 출력하며, 게시된 스코어카드는 [`docs/benchmarks/`](../docs/benchmarks/)에 보관됩니다.
+
+**다음과 함께 사용하기 좋습니다: [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything), [Graphify](https://github.com/safishamsi/graphify).** 코드 그래프 인덱싱, 멀티 에이전트 빌드 파이프라인, 그리고 docs/PDF/이미지/비디오에 걸친 더 넓은 지식 그래프. agentmemory는 작업을 기억하고, 이 세 프로젝트는 나머지 컨텍스트 레이어를 밝혀줍니다. 레시피와 질문 라우팅 표: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
내장 메모리 (CLAUDE.md)
+
+
+
유형
+
메모리 엔진 + MCP 서버
+
메모리 레이어 API
+
완전한 에이전트 런타임
+
정적 파일
+
+
+
검색 R@5
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
해당 없음 (grep)
+
+
+
자동 캡처
+
12 hooks (수동 작업 없음)
+
수동 add() 호출
+
에이전트 자체 편집
+
수동 편집
+
+
+
검색
+
BM25 + Vector + Graph (RRF 융합)
+
Vector + Graph
+
Vector (archival)
+
모든 것을 컨텍스트에 로드
+
+
+
멀티 에이전트
+
MCP + REST + leases + signals
+
API (조정 없음)
+
Letta 런타임 내에서만
+
에이전트별 파일
+
+
+
프레임워크 종속성
+
없음 (모든 MCP 클라이언트)
+
없음
+
높음 (Letta 사용 필수)
+
에이전트별 포맷
+
+
+
외부 의존성
+
없음 (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + 벡터 DB
+
없음
+
+
+
메모리 라이프사이클
+
4-tier 통합 + 감쇠 + 자동 망각
+
수동적 추출
+
에이전트 관리
+
수동 정리
+
+
+
토큰 효율
+
세션당 ~1,900 토큰 ($10/년)
+
통합 방식에 따라 다름
+
핵심 메모리는 컨텍스트에 상주
+
관측 240개 기준 22K+ 토큰
+
+
+
실시간 뷰어
+
있음 (port 3113)
+
클라우드 대시보드
+
클라우드 대시보드
+
없음
+
+
+
셀프 호스팅
+
예 (기본)
+
선택 사항
+
선택 사항
+
예
+
+
+
+---
+
+
+
+호환성: 이 릴리스는 안정 버전 `iii-sdk` `^0.11.0`과 iii-engine v0.11.x를 대상으로 합니다.
+
+### 30초 만에 사용해 보기
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo`는 현실적인 세션 3개(JWT 인증, N+1 쿼리 수정, rate limiting)를 시드하고, 그 위에서 시맨틱 검색을 실행합니다. "database performance optimization"으로 검색하면 "N+1 query fix"를 찾는 것을 확인할 수 있는데, 키워드 매칭으로는 불가능한 결과입니다.
+
+`http://localhost:3113`을 열어서 메모리가 실시간으로 쌓이는 것을 지켜보십시오.
+
+### 권장: 전역 설치
+
+`npx`는 버전별로 캐싱합니다. 지난주에 `npx @agentmemory/agentmemory@0.9.14`를 실행했다면, 단순한 `npx @agentmemory/agentmemory`는 최신 릴리스가 아니라 `~/.npm/_npx/`에 캐시된 0.9.14를 제공할 수 있습니다. 한 번 설치하면 단순한 `agentmemory` 명령이 어디서나 동작합니다:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+v0.9.16 이후부터 첫 npx 실행은 인라인으로 전역 설치 여부를 묻습니다 — `Y`로 한 번만 답하면 설정이 끝납니다. 만약 건너뛰었다면, 새로 가져오기 위해 다음 중 하나를 사용하십시오:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+Windows / PowerShell에서 동일한 캐시 비우기는 `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"`입니다 — 위의 `npx -y ...@latest`가 크로스 플랫폼 옵션입니다.
+
+### 세션 리플레이
+
+agentmemory가 기록한 모든 세션은 재생 가능합니다. 뷰어를 열어 **Replay** 탭을 선택하고 타임라인을 스크럽하면 프롬프트, 도구 호출, 도구 결과, 응답이 별개의 이벤트로 렌더링됩니다. 재생/일시정지, 속도 제어(0.5×–4×), 키보드 단축키(space로 토글, 화살표로 단계 이동)를 모두 지원합니다.
+
+가져오고 싶은 기존 Claude Code JSONL 트랜스크립트가 있습니까?
+
+```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
+```
+
+가져온 세션은 네이티브 세션과 함께 Replay 선택기에 표시됩니다. 내부적으로 각 항목은 `mem::replay::load`, `mem::replay::sessions`, `mem::replay::import-jsonl` iii 함수로 라우팅됩니다 — 별도의 사이드 채널 서버 없이.
+
+### 업그레이드 / 유지보수
+
+로컬 런타임을 의도적으로 업데이트할 때는 maintenance 명령을 사용하십시오:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+경고: 이 명령은 현재 workspace/런타임을 변경합니다. JavaScript 의존성을 업데이트할 수 있으며, `cargo install iii-engine --force`를 실행할 수도 있고, Docker 이미지를 pull할 수도 있습니다.
+
+구현 세부 사항은 `src/cli.ts`에 있습니다 (`runUpgrade`는 `src/cli.ts:544-595` 부근 참고).
+
+### Claude Code (블록 한 번, 붙여넣기)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 사용 (MCP-독립형 경로)
+
+`/plugin install` 대신 `~/.claude.json`을 통해 agentmemory의 MCP 서버를 직접 연결한 경우, Claude Code는 `${CLAUDE_PLUGIN_ROOT}`를 해석하지 못하므로 `~/.claude/settings.json`의 hook 스크립트를 절대 경로로 지정해야 합니다. 이 경로들은 일반적으로 agentmemory 버전을 포함하기 때문에 (예: `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), 다음 업그레이드에서 모든 hook이 조용히 깨질 수 있습니다 ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+해결책:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+이 명령은 현재 설치된 `@agentmemory/agentmemory` 패키지의 번들된 `plugin/` 디렉터리로 해석된 절대 경로로 동일한 hook 명령을 `~/.claude/settings.json`에 병합합니다. agentmemory를 업그레이드한 후 동일한 명령을 다시 실행하여 경로를 갱신하십시오. 동일한 파일의 사용자 항목은 보존되며, 이전 agentmemory 항목만 교체됩니다. `/plugin install` 경로를 사용하는 것이 여전히 권장 방식입니다.
+원격 또는 보호된 배포의 경우, `AGENTMEMORY_URL`과 `AGENTMEMORY_SECRET`을 설정한 채로 Claude Code를 실행하십시오. 플러그인은 두 값을 모두 번들된 MCP 서버로 전달합니다. `AGENTMEMORY_URL`이 비어 있을 때는 MCP shim이 `http://localhost:3111`을 사용합니다.
+
+### Codex CLI (Codex 플러그인 플랫폼)
+
+```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
+```
+
+Codex 플러그인은 Claude Code 플러그인과 동일한 `plugin/` 디렉터리에서 제공됩니다. 다음을 등록합니다:
+
+- `@agentmemory/mcp`를 MCP 서버로 등록 (`AGENTMEMORY_URL`이 실행 중인 agentmemory 서버를 가리킬 때 51개 도구 모두 프록시. 도달 가능한 서버가 없으면 로컬에서 7개 도구로 폴백)
+- 6개 라이프사이클 hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4개 skills: `/recall`, `/remember`, `/session-history`, `/forget`
+
+Codex의 hook 엔진은 hook 서브프로세스에 `CLAUDE_PLUGIN_ROOT`를 주입하므로 ([`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs) 참고), 동일한 hook 스크립트가 중복 없이 두 호스트에서 모두 동작합니다. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure 이벤트는 Claude Code 전용이며 Codex에는 등록되지 않습니다.
+
+#### Codex Desktop: 플러그인 hooks가 현재 동작하지 않음 (해결책 있음)
+
+`CodexHooks`와 `PluginHooks`는 [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs)에서 모두 안정 + 기본 활성화 상태이지만, 현재 Codex Desktop 빌드는 플러그인-로컬 `hooks.json`을 디스패치하지 않습니다 ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP 도구는 여전히 동작합니다. 라이프사이클 관측만 누락됩니다.
+
+업스트림 수정이 적용될 때까지 동일한 hook 명령을 전역 `~/.codex/hooks.json`에 미러링하십시오:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+이 명령은 번들된 스크립트의 절대 경로를 참조하는 idempotent 블록을 `~/.codex/hooks.json`에 추가합니다(사용자 스코프에서 `${CLAUDE_PLUGIN_ROOT}` 확장이 필요 없음). agentmemory를 업그레이드한 후 동일한 명령을 다시 실행하여 경로를 갱신하십시오. 동일한 파일의 사용자 항목은 보존되며, 이전 agentmemory 항목만 교체됩니다.
+
+
+OpenClaw (이 프롬프트를 붙여넣으세요)
+
+```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 51 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`.
+```
+
+전체 가이드: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (이 프롬프트를 붙여넣으세요)
+
+```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 51 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.
+```
+
+전체 가이드: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### 다른 에이전트
+
+메모리 서버 시작: `npx @agentmemory/agentmemory`
+
+agentmemory 항목은 `mcpServers` 형태를 사용하는 모든 호스트(Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw)에서 **동일한 MCP 서버 블록**입니다:
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**호스트 설정 파일의 기존 `mcpServers` 객체에 이 항목을 병합하십시오** — 파일 전체를 교체하지 마십시오. 파일에 이미 다른 서버가 있다면, `agentmemory`를 `mcpServers` 안의 또 다른 키로 옆에 추가하십시오. `mcpServers` 자체가 없다면 `{ "mcpServers": { ... } }` 안에 블록을 붙여넣으십시오. `${VAR}` 자리표시자는 MCP 서버 실행 시 셸에서 `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET`을 상속합니다 — 설정되지 않은 변수는 빈 문자열로 전달되며 shim은 `http://localhost:3111`로 폴백합니다. 한 번 연결한 항목으로 로컬과 원격(k8s / 리버스 프록시) 배포를 모두 커버합니다.
+
+| 에이전트 | 설정 파일 | 비고 |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | `mcpServers`에 병합. 웹사이트에서 원클릭 deeplink도 사용 가능. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | `mcpServers`에 병합. 편집 후 Claude Desktop 재시작. |
+| **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | 동일한 `mcpServers` 블록. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | 동일한 `mcpServers` 블록. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (자동 병합). |
+| **OpenClaw** | OpenClaw MCP config | 동일한 `mcpServers` 블록을 사용하거나, 더 깊은 [memory plugin](../integrations/openclaw/)을 사용. |
+| **Codex CLI (MCP only)** | `.codex/config.toml` | TOML 형식: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, 또는 `[mcp_servers.agentmemory]`를 수동으로 추가. |
+| **Codex CLI (full plugin)** | Codex 플러그인 마켓플레이스 | `codex plugin marketplace add rohitg00/agentmemory` 후 `codex plugin add agentmemory@agentmemory`. MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills 등록. Codex Desktop에서는 [openai/codex#16430](https://github.com/openai/codex/issues/16430)이 머지될 때까지 `agentmemory connect codex --with-hooks`도 실행해야 합니다 — 현재 그곳에서는 플러그인 hooks가 동작하지 않습니다. |
+| **OpenCode (MCP only)** | `opencode.json` | 다른 형식 — 최상위 `mcp` 키, 명령은 배열로: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (full plugin)** | `plugin/opencode/` | 세션 라이프사이클, 메시지, 도구, 오류를 다루는 22개의 자동 캡처 hooks. 두 개의 슬래시 명령(`/recall`, `/remember`). `plugin/opencode/`를 OpenCode workspace에 복사한 후 `opencode.json`에 플러그인 항목을 추가하십시오. 전체 hook 표 + gap 분석은 [`plugin/opencode/README.md`](../plugin/opencode/README.md) 참고. |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | [`integrations/pi`](../integrations/pi/)를 복사하고 pi를 재시작. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | `memory.provider: agentmemory`로 더 깊은 [memory provider plugin](../integrations/hermes/) 사용. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen`이 표준 `mcpServers` 블록을 기록. Hook 페이로드는 Claude Code와 필드 호환이므로, 기존 12-hook 스크립트가 수정 없이 동작합니다 — 동일한 `settings.json`의 `hooks` 섹션에서 연결. |
+| **Antigravity** (Gemini CLI 대체) | `mcp_config.json` (Antigravity의 User 디렉터리 내) | `agentmemory connect antigravity`가 표준 `mcpServers` 블록을 기록. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. 2026-06-18 Gemini CLI sunset 이후 사용. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro`가 사용자 레벨 설정을 기록. 워크스페이스 오버라이드는 코드 옆 `.kiro/settings/mcp.json`에. |
+| **Goose** | Goose MCP settings UI | 동일한 `mcpServers` 블록. |
+| **Aider** | n/a | REST API와 직접 통신: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **모든 에이전트 (32+)** | n/a | `npx skillkit install agentmemory`가 호스트를 자동 감지하고 병합. |
+
+**샌드박스된 MCP 클라이언트**(Flatpak / Snap / 제한적인 컨테이너 등)가 호스트의 `localhost`에 도달할 수 없는 경우: `env` 블록에 `"AGENTMEMORY_FORCE_PROXY": "1"`도 설정하고, `AGENTMEMORY_URL`을 샌드박스가 실제로 도달 가능한 경로(예: LAN IP)로 지정하십시오. 진단 가이드는 [#234](https://github.com/rohitg00/agentmemory/issues/234)를 참고하십시오.
+
+### 프로그래매틱 액세스 (Python / Rust / Node)
+
+agentmemory는 핵심 작업을 iii 함수(`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`)로 등록합니다. iii SDK가 있는 모든 언어에서 `ws://localhost:49134`로 직접 호출할 수 있습니다 — 언어별 별도의 REST 클라이언트가 필요하지 않습니다.
+
+```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"},
+})
+```
+
+작동 예제: [`examples/python/`](../examples/python/) (퀵스타트 + 관측/리콜 흐름). iii 런타임이 없는 호스트를 위해 `:3111`의 REST는 그대로 사용 가능합니다.
+
+### 소스에서 빌드
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+`iii`가 이미 설치되어 있으면 로컬 `iii-engine`으로 agentmemory를 시작하고, Docker가 사용 가능하면 Docker Compose로 폴백합니다. REST, 스트림, 뷰어는 기본적으로 `127.0.0.1`에 바인딩됩니다.
+
+`iii-engine`을 수동으로 설치하십시오. **agentmemory는 현재 `iii-engine`을 `v0.11.2`로 고정합니다** — `v0.11.6`은 모든 것을 `iii worker add`를 통해 샌드박스화하는 새 모델을 도입했는데 agentmemory는 아직 이를 위해 리팩터링되지 않았기 때문입니다. 리팩터링이 완료되면 고정이 풀립니다. 수동으로 sandbox 모델로 마이그레이션했다면 `AGENTMEMORY_III_VERSION=`으로 덮어쓰십시오.
+
+- **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:** `aarch64-apple-darwin`을 `x86_64-apple-darwin`으로 교체
+- **Linux x64:** `x86_64-unknown-linux-gnu`로 교체
+- **Linux arm64:** `aarch64-unknown-linux-gnu`로 교체
+- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2)에서 `iii-x86_64-pc-windows-msvc.zip`을 다운로드하고 `iii.exe`를 추출한 후 PATH에 추가
+
+또는 Docker 사용 (번들된 `docker-compose.yml`이 `iiidev/iii:0.11.2`를 pull). 전체 문서: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory는 Windows 10/11에서 실행되지만, Node.js 패키지만으로는 충분하지 않습니다 — 별도의 네이티브 바이너리인 `iii-engine` 런타임이 백그라운드 프로세스로 필요합니다. 공식 업스트림 인스톨러는 `sh` 스크립트이고 PowerShell 인스톨러나 scoop/winget 패키지는 현재 없으므로, Windows 사용자에게는 두 가지 경로가 있습니다:
+
+**옵션 A — 사전 빌드된 Windows 바이너리 (권장):**
+
+```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
+```
+
+**옵션 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
+```
+
+**옵션 C — 독립형 MCP만 사용 (엔진 없음):** 에이전트용 MCP 도구만 필요하고 REST API, 뷰어, cron 작업이 필요하지 않다면 엔진을 완전히 건너뛸 수 있습니다:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Windows 진단:** `npx @agentmemory/agentmemory`가 실패하면 `--verbose`로 다시 실행하여 실제 엔진 stderr를 확인하십시오. 일반적인 실패 모드:
+
+| 증상 | 해결 방법 |
+|---|---|
+| `iii-engine process started`가 표시된 후 `did not become ready within 15s` | 엔진이 시작 시 충돌함 — `--verbose`로 다시 실행하여 stderr 확인 |
+| `Could not start iii-engine` | `iii.exe`도 Docker도 설치되어 있지 않음. 위의 옵션 A 또는 B 참고 |
+| 포트 충돌 | `netstat -ano \| findstr :3111`로 무엇이 바인딩되어 있는지 확인하고 종료하거나 `--port ` 사용 |
+| Docker가 설치되어 있어도 Docker 폴백을 건너뜀 | Docker Desktop이 실제로 실행 중인지 확인 (시스템 트레이 아이콘) |
+
+> 참고: `cargo install iii-engine`는 없습니다 — `iii`는 crates.io에 게시되지 않았습니다. 지원되는 설치 방법은 위의 사전 빌드된 바이너리, 업스트림 `sh` 설치 스크립트(macOS/Linux 전용), Docker 이미지뿐입니다.
+
+---
+
+
배포
+
+매니지드 호스트용 원클릭 템플릿입니다. 각각은 npm에서 `@agentmemory/agentmemory`를 가져오고 공식 `iiidev/iii` Docker Hub 이미지에서 iii 엔진 바이너리를 복사하는 자체 완결형 Dockerfile을 제공합니다 — 사전 빌드된 agentmemory 이미지가 필요 없습니다. 영구 스토리지는 `/data`에 마운트되며, 첫 부팅 진입점은 npm 번들 iii 설정(`127.0.0.1`에 바인딩)을 `0.0.0.0`에 바인딩하고 절대 `/data` 경로를 사용하는 배포 튜닝 설정으로 덮어쓰고, HMAC 시크릿을 생성한 후, `gosu`를 통해 `root`에서 `node`로 권한을 낮춘 다음 agentmemory CLI를 exec합니다.
+
+
+
+
+
+
+Render의 원클릭 배포 버튼은 저장소 루트에 `render.yaml`이 필요한데, 우리는 의도적으로 이를 깨끗하게 유지합니다. [`deploy/render/`](../deploy/render/README.md)에 문서화된 Render Blueprint 플로우를 사용하여 in-repo blueprint를 수동으로 가리키도록 하십시오.
+
+전체 설정 세부 사항(HMAC 캡처, 뷰어 SSH 터널, 로테이션, 백업, 비용 하한)은 [`deploy/`](../deploy/README.md)에 있습니다:
+
+- [`deploy/fly`](../deploy/fly/README.md) — `auto_stop_machines = "stop"`으로 단일 머신; 유휴 비용이 가장 저렴.
+- [`deploy/railway`](../deploy/railway/README.md) — Hobby 플랜 정액제, 볼륨은 대시보드에서.
+- [`deploy/render`](../deploy/render/README.md) — Blueprint 플로우, 유료 플랜에서 자동 디스크 스냅샷.
+- [`deploy/coolify`](../deploy/coolify/README.md) — [Coolify](https://coolify.io/self-hosted)를 통해 자체 VPS에 셀프 호스팅; 동일한 Docker Compose 스택, 호스트와 데이터를 직접 소유.
+
+`3111` 포트만 게시됩니다. `3113`의 뷰어는 컨테이너 내부에서 loopback에 바인딩된 채로 유지됩니다 — 각 템플릿의 README는 그곳에 도달하기 위한 SSH 터널 패턴을 문서화합니다.
+
+---
+
+
+
+모든 코딩 에이전트는 세션이 끝나면 모든 것을 잊습니다. 매 세션의 첫 5분을 스택을 다시 설명하는 데 낭비합니다. agentmemory는 백그라운드에서 실행되어 이를 완전히 제거합니다.
+
+```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.
+```
+
+### 내장 에이전트 메모리와의 비교
+
+모든 AI 코딩 에이전트는 내장 메모리와 함께 제공됩니다 — Claude Code에는 `MEMORY.md`가 있고, Cursor에는 notepad가, Cline에는 memory bank가 있습니다. 이들은 포스트잇처럼 동작합니다. agentmemory는 포스트잇 뒤에 있는 검색 가능한 데이터베이스입니다.
+
+| | 내장 (CLAUDE.md) | agentmemory |
+|---|---|---|
+| 규모 | 200줄 한도 | 무제한 |
+| 검색 | 모든 것을 컨텍스트에 로드 | BM25 + vector + graph (top-K만) |
+| 토큰 비용 | 관측 240개 기준 22K+ | ~1,900 토큰 (92% 적음) |
+| 크로스 에이전트 | 에이전트별 파일 | MCP + REST (모든 에이전트) |
+| 조정 | 없음 | leases, signals, actions, routines |
+| 가시성 | 파일 수동 읽기 | :3113의 실시간 뷰어 |
+
+---
+
+
+
+### 메모리 파이프라인
+
+```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 메모리 통합
+
+인간 뇌가 메모리를 처리하는 방식 — 수면 통합과 크게 다르지 않은 방식 — 에서 영감을 받았습니다.
+
+| Tier | 무엇 | 비유 |
+|------|------|---------|
+| **Working** | 도구 사용에서 나온 원시 관측 | 단기 기억 |
+| **Episodic** | 압축된 세션 요약 | "무슨 일이 있었는가" |
+| **Semantic** | 추출된 사실과 패턴 | "내가 아는 것" |
+| **Procedural** | 워크플로우와 의사 결정 패턴 | "그것을 하는 방법" |
+
+메모리는 시간이 지나면서 감쇠합니다(Ebbinghaus 곡선). 자주 액세스하는 메모리는 강화됩니다. 오래된 메모리는 자동으로 축출됩니다. 모순은 감지되고 해결됩니다.
+
+### 무엇이 캡처되는가
+
+| Hook | 캡처 내용 |
+|------|----------|
+| `SessionStart` | 프로젝트 경로, 세션 ID |
+| `UserPromptSubmit` | 사용자 프롬프트 (개인정보 필터링됨) |
+| `PreToolUse` | 파일 접근 패턴 + 풍부한 컨텍스트 |
+| `PostToolUse` | 도구 이름, 입력, 출력 |
+| `PostToolUseFailure` | 오류 컨텍스트 |
+| `PreCompact` | 컴팩션 전에 메모리 재주입 |
+| `SubagentStart/Stop` | 서브 에이전트 라이프사이클 |
+| `Stop` | 세션 종료 요약 |
+| `SessionEnd` | 세션 완료 마커 |
+
+### 핵심 기능
+
+| 기능 | 설명 |
+|---|---|
+| **자동 캡처** | 모든 도구 사용을 hooks로 기록 — 수동 작업 없음 |
+| **시맨틱 검색** | BM25 + vector + 지식 그래프, RRF 융합 |
+| **메모리 진화** | 버저닝, supersession, 관계 그래프 |
+| **자동 망각** | TTL 만료, 모순 감지, 중요도 기반 축출 |
+| **개인정보 우선** | API 키, 시크릿, `` 태그를 저장 전에 제거 |
+| **자가 치유** | 서킷 브레이커, 프로바이더 폴백 체인, 헬스 모니터링 |
+| **Claude 브리지** | MEMORY.md와의 양방향 동기화 |
+| **지식 그래프** | 엔티티 추출 + BFS 순회 |
+| **팀 메모리** | 팀원 간 namespaced 공유 + 비공개 |
+| **인용 출처 추적** | 모든 메모리를 원본 관측으로 추적 |
+| **Git 스냅샷** | 메모리 상태의 버전 관리, 롤백, 차이 비교 |
+
+---
+
+
+
+세 가지 신호를 결합한 트리플 스트림 검색:
+
+| 스트림 | 무엇을 하는가 | 언제 |
+|---|---|---|
+| **BM25** | 형태소 추출 키워드 매칭 + 동의어 확장 | 항상 활성 |
+| **Vector** | 밀집 임베딩 위의 코사인 유사도 | 임베딩 프로바이더 구성 시 |
+| **Graph** | 엔티티 매칭을 통한 지식 그래프 순회 | 쿼리에서 엔티티 감지 시 |
+
+Reciprocal Rank Fusion(RRF, k=60)으로 융합하고, 세션 다양화(세션당 최대 3개 결과)합니다.
+
+BM25는 기본적으로 그리스어, 키릴 문자, 히브리어, 아랍어, 강세 부호가 있는 라틴 문자를 토크나이즈합니다. 중국어 / 일본어 / 한국어 메모리의 경우 선택적 세그멘터(`npm install @node-rs/jieba tiny-segmenter`)를 설치하여 CJK 런을 단어 수준 토큰으로 분할하십시오. 설치하지 않으면 agentmemory는 전체 런 토크나이제이션으로 soft fallback하고 stderr에 일회성 힌트를 출력합니다.
+
+### 임베딩 프로바이더
+
+agentmemory는 프로바이더를 자동 감지합니다. 최상의 결과를 위해 로컬 임베딩을 설치하십시오 (무료):
+
+```bash
+npm install @xenova/transformers
+```
+
+| 프로바이더 | 모델 | 비용 | 비고 |
+|---|---|---|---|
+| **Local (권장)** | `all-MiniLM-L6-v2` | 무료 | 오프라인, BM25-only 대비 +8pp recall |
+| Gemini | `gemini-embedding-001` | 무료 티어 | 100+ 언어, 768/1536/3072 dims (MRL), 2048-token 입력. `text-embedding-004`를 대체 ([deprecated, 2026년 1월 14일 종료](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | $0.02/1M | 최고 품질 |
+| Voyage AI | `voyage-code-3` | 유료 | 코드 최적화 |
+| Cohere | `embed-english-v3.0` | 무료 평가판 | 범용 |
+| OpenRouter | 모든 모델 | 다양 | 멀티 모델 프록시 |
+
+---
+
+
+
+53개 도구, 6개 리소스, 3개 프롬프트, 4개 skills — 모든 에이전트를 위한 가장 포괄적인 MCP 메모리 툴킷.
+
+> **MCP shim 대 전체 서버:** 게시된 `@agentmemory/mcp` 패키지는 얇은 shim입니다. `AGENTMEMORY_URL`을 통해 실행 중인 agentmemory 서버에 도달할 수 있을 때 **만** 전체 51-도구 표면을 노출합니다(프록시 모드). 도달 가능한 서버가 없으면 shim은 7-도구 로컬 세트(`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`)로 폴백합니다. `AGENTMEMORY_TOOLS=core|all` 환경 변수는 *서버 측* 플래그입니다 — shim의 `env` 블록에 설정해도 효과가 없습니다. Cursor / OpenCode / Gemini CLI에서 도구가 7개만 보인다면 `npx @agentmemory/agentmemory`(또는 Docker 스택)를 시작하고 `AGENTMEMORY_URL=http://localhost:3111`을 설정하십시오.
+
+### 51개 도구
+
+
+핵심 도구 (항상 사용 가능)
+
+| 도구 | 설명 |
+|------|-------------|
+| `memory_recall` | 과거 관측 검색 |
+| `memory_compress_file` | 구조를 유지하면서 markdown 파일 압축 |
+| `memory_save` | 통찰, 결정, 패턴 저장 |
+| `memory_patterns` | 반복 패턴 감지 |
+| `memory_smart_search` | 하이브리드 시맨틱 + 키워드 검색 |
+| `memory_file_history` | 특정 파일에 대한 과거 관측 |
+| `memory_sessions` | 최근 세션 목록 |
+| `memory_timeline` | 시간순 관측 |
+| `memory_profile` | 프로젝트 프로필 (개념, 파일, 패턴) |
+| `memory_export` | 모든 메모리 데이터 내보내기 |
+| `memory_relations` | 관계 그래프 쿼리 |
+
+
+
+
+확장 도구 (총 51개 — AGENTMEMORY_TOOLS=all 설정)
+
+| 도구 | 설명 |
+|------|-------------|
+| `memory_patterns` | 반복 패턴 감지 |
+| `memory_timeline` | 시간순 관측 |
+| `memory_relations` | 관계 그래프 쿼리 |
+| `memory_graph_query` | 지식 그래프 순회 |
+| `memory_consolidate` | 4-tier 통합 실행 |
+| `memory_claude_bridge_sync` | MEMORY.md와 동기화 |
+| `memory_team_share` | 팀원과 공유 |
+| `memory_team_feed` | 최근 공유 항목 |
+| `memory_audit` | 작업 감사 로그 |
+| `memory_governance_delete` | 감사 로그를 남기는 삭제 |
+| `memory_snapshot_create` | Git 버전 관리 스냅샷 |
+| `memory_action_create` | 의존성이 있는 작업 항목 생성 |
+| `memory_action_update` | 작업 상태 업데이트 |
+| `memory_frontier` | 우선순위로 정렬된 차단 해제된 작업 |
+| `memory_next` | 가장 중요한 다음 작업 하나 |
+| `memory_lease` | 독점 작업 leases (멀티 에이전트) |
+| `memory_routine_run` | 워크플로우 루틴 인스턴스화 |
+| `memory_signal_send` | 에이전트 간 메시징 |
+| `memory_signal_read` | 수신 확인이 있는 메시지 읽기 |
+| `memory_checkpoint` | 외부 조건 게이트 |
+| `memory_mesh_sync` | 인스턴스 간 P2P 동기화 |
+| `memory_sentinel_create` | 이벤트 기반 워처 |
+| `memory_sentinel_trigger` | 외부에서 sentinel 발화 |
+| `memory_sketch_create` | 일시적 작업 그래프 |
+| `memory_sketch_promote` | 영구로 승격 |
+| `memory_crystallize` | 작업 체인 압축 |
+| `memory_diagnose` | 헬스 체크 |
+| `memory_heal` | 정체된 상태 자동 수정 |
+| `memory_facet_tag` | dimension:value 태그 |
+| `memory_facet_query` | facet 태그로 쿼리 |
+| `memory_verify` | 출처 추적 |
+
+
+
+### 6 리소스 · 3 프롬프트 · 4 Skills
+
+| 유형 | 이름 | 설명 |
+|------|------|-------------|
+| Resource | `agentmemory://status` | 헬스, 세션 수, 메모리 수 |
+| Resource | `agentmemory://project/{name}/profile` | 프로젝트별 인텔리전스 |
+| Resource | `agentmemory://memories/latest` | 최신 10개 활성 메모리 |
+| Resource | `agentmemory://graph/stats` | 지식 그래프 통계 |
+| Prompt | `recall_context` | 검색 + 컨텍스트 메시지 반환 |
+| Prompt | `session_handoff` | 에이전트 간 핸드오프 데이터 |
+| Prompt | `detect_patterns` | 반복 패턴 분석 |
+| Skill | `/recall` | 메모리 검색 |
+| Skill | `/remember` | 장기 메모리에 저장 |
+| Skill | `/session-history` | 최근 세션 요약 |
+| Skill | `/forget` | 관측/세션 삭제 |
+
+### 독립형 MCP
+
+전체 서버 없이 실행 — 모든 MCP 클라이언트용. 다음 둘 다 동작합니다:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+또는 에이전트의 MCP 설정에 추가:
+
+대부분의 에이전트 (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+파일을 교체하지 말고 호스트의 기존 `mcpServers` 객체에 `agentmemory` 항목을 병합하십시오. 호스트의 `localhost`에 도달할 수 없는 샌드박스 클라이언트의 경우 env 블록에 `"AGENTMEMORY_FORCE_PROXY": "1"`을 추가하고 `AGENTMEMORY_URL`을 샌드박스가 도달할 수 있는 경로로 설정하십시오.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+저장소에서 플러그인 파일을 복사하십시오:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+`3113` 포트에서 자동 시작됩니다. 라이브 관측 스트림, 세션 탐색기, 메모리 브라우저, 지식 그래프 시각화, 헬스 대시보드.
+
+```bash
+open http://localhost:3113
+```
+
+뷰어 서버는 기본적으로 `127.0.0.1`에 바인딩됩니다. REST가 서빙하는 `/agentmemory/viewer` 엔드포인트는 일반 `AGENTMEMORY_SECRET` bearer-token 규칙을 따릅니다. CSP 헤더는 응답별 script nonce를 사용하며 인라인 핸들러 속성을 비활성화합니다 (`script-src-attr 'none'`).
+
+---
+
+
+
+`:3113`의 뷰어는 에이전트가 **기억한 것**을 보여줍니다. [iii console](https://iii.dev/docs/console)은 에이전트가 **무엇을 했는지**를 보여줍니다 — 모든 메모리 작업을 OpenTelemetry 추적으로, 모든 KV 항목을 편집 가능하게, 모든 함수를 호출 가능하게, 모든 스트림을 탭 가능하게. 동일한 메모리에 대한 두 창: 하나는 제품 형태, 하나는 엔진 형태.
+
+`memory_smart_search`가 발화되는 것을 보고 BM25 스캔 → 임베딩 조회 → RRF 융합 → 리랭커를 워터폴로 확인하십시오. KV 브라우저에서 정체된 통합 타이머를 편집하십시오. 조정된 페이로드로 `PostToolUse` hook을 재생하십시오. WebSocket 스트림을 고정하고 관측이 실시간으로 도착하는 것을 지켜보십시오.
+
+agentmemory는 모든 함수, 트리거, 상태 스코프, 스트림이 iii 프리미티브이기 때문에 — 사용자 정의도, 계측할 것도 없기 때문에 — 이를 무료로 제공합니다.
+
+
+
+
+ Workers 페이지: 연결된 모든 워커 — agentmemory 자체 포함 — PID, 함수 수, 런타임, last-seen 표시.
+
+
+**이미 설치됨.** 콘솔은 `iii`와 함께 제공됩니다 — 별도의 인스톨러가 없습니다.
+
+**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
+```
+
+그런 다음 `http://localhost:3114`을 여십시오. 실험적인 architecture-graph 페이지를 위해 `--enable-flow`를 추가하십시오.
+
+엔진 엔드포인트를 옮긴 경우에만 덮어쓰십시오:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**콘솔에서 할 수 있는 일:**
+
+| 페이지 | 용도 |
+|------|-----------|
+| **Workers** | 연결된 모든 워커와 그 라이브 메트릭 확인 — agentmemory 워커 자체 포함. |
+| **Functions** | JSON 페이로드로 agentmemory의 모든 함수를 직접 호출 — 클라이언트를 연결하지 않고 `memory.recall`, `memory.consolidate`, `graph.query`를 테스트하기에 편리. |
+| **Triggers** | HTTP, cron, event, state 트리거를 재생 — 통합 cron을 수동으로 발화, HTTP 라우트를 재시도, state 변경을 발생. |
+| **States** | 전체 CRUD가 가능한 KV 브라우저 — 세션, 메모리 슬롯, 라이프사이클 타이머, 임베딩 인덱스 — 값을 그 자리에서 편집. |
+| **Streams** | iii 스트림을 통해 흐르는 메모리 쓰기, hook 이벤트, 관측 업데이트를 위한 라이브 WebSocket 모니터. |
+| **Queues** | 내구성 있는 큐 토픽 + 데드 레터 관리. 실패한 임베딩 / 압축 작업을 재생하거나 폐기. |
+| **Traces** | OpenTelemetry 워터폴 / 플레임 / 서비스별 분해 뷰. `trace_id`로 필터링하여 단일 `memory.search`가 생성한 함수, DB 호출, 임베딩 요청을 정확히 확인. |
+| **Logs** | trace/span ID에 필터링·상관된 구조화된 OTEL 로그. |
+| **Config** | 런타임 설정 — 엔진이 실행 중인 워커, 프로바이더, 포트를 정확히 확인. |
+| **Flow** | (선택, `--enable-flow`) 모든 워커, 트리거, 스트림의 인터랙티브 architecture graph. |
+
+
+
+
+ Traces: 모든 메모리 작업에 대한 워터폴 / 플레임 / 서비스 분해.
+
+
+**Traces는 이미 켜져 있습니다:**
+
+`iii-config.yaml`은 `iii-observability` 워커가 활성화된 상태로 제공됩니다(`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs). 추가 설정이 필요 없습니다 — agentmemory가 시작되는 순간 모든 메모리 작업이 콘솔이 읽을 수 있는 trace span과 구조화된 로그를 방출합니다.
+
+대신 Jaeger/Honeycomb/Grafana Tempo로 내보내고 싶다면 `exporter: memory`를 `exporter: otlp`로 변경하고 iii의 가시성 문서에 따라 collector 엔드포인트를 설정하십시오.
+
+> **참고:** 콘솔 자체에는 인증이 적용되지 않습니다 — `127.0.0.1`에 바인딩된 채로 두고(기본값) 절대 공개적으로 노출하지 마십시오.
+
+---
+
+
+
+agentmemory는 **이미 실행 중인 [iii](https://iii.dev) 인스턴스**입니다. 함수, 트리거, KV 상태, 스트림, OTEL 추적 — 모두 iii 프리미티브입니다. Postgres, Redis, Express, pm2, Prometheus를 설치하지 않은 이유는 iii가 이들을 대체하기 때문입니다.
+
+그 말은 명령어 하나로 agentmemory에 완전히 새로운 기능을 확장할 수 있다는 뜻입니다.
+
+### 명령어 하나로 agentmemory 확장
+
+```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
+```
+
+각 `iii worker add`는 agentmemory가 이미 실행 중인 동일한 엔진에 새 함수와 트리거를 등록합니다. 뷰어와 콘솔은 즉시 이를 인식합니다 — 재로드도, 새 통합도, 새 컨테이너도 필요 없습니다.
+
+| `iii worker add` | agentmemory 위에 무엇이 추가되는가 |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | 멀티 인스턴스 메모리: 모든 `remember`가 팬아웃, 모든 `search`가 합집합을 읽음 |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | 스케줄링된 라이프사이클 — 야간 통합, 주간 스냅샷, 고정된 시계에 따른 감쇠 |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | 내구성 있는 재시도: 실패한 임베딩 + 압축 작업은 재시작에도 살아남아 관측 손실 없음 |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | 모든 함수에 OTEL traces, metrics, logs — 첫날부터 `iii-config.yaml`에 연결됨 |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall`에서 나온 코드를 셸이 아니라 일회용 VM 안에서 실행 |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | 인메모리 KV 기본값을 넘어설 때 SQL 기반 state adapter |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory의 MCP 옆에 추가 MCP 서버를 세우고 동일한 엔진을 공유 |
+
+전체 레지스트리: [workers.iii.dev](https://workers.iii.dev). 그곳의 모든 워커는 agentmemory가 사용하는 동일한 프리미티브로 구성됩니다 — 그리고 이미 갖고 있는 agentmemory도 그중 하나입니다.
+
+### iii가 무엇을 대체하는가
+
+| 전통적인 스택 | agentmemory에서의 사용 |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + 인메모리 벡터 인덱스 |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | iii engine worker supervision |
+| Prometheus / Grafana | iii OTEL + 헬스 모니터 |
+| 사용자 정의 플러그인 시스템 | `iii worker add ` |
+
+**118개 소스 파일 · ~21,800 LOC · 950+ tests · 123개 함수 · 34개 KV 스코프** — 모두 세 가지 프리미티브 위에. `agentmemory plugin install`이 없습니다. 플러그인 시스템은 iii 자체입니다.
+
+---
+
+
+
+### LLM 프로바이더
+
+agentmemory는 환경에서 자동 감지합니다. 기본적으로 프로바이더를 구성하거나 Claude subscription 폴백에 명시적으로 옵트인하지 않는 한 LLM 호출이 발생하지 않습니다.
+
+| 프로바이더 | 설정 | 비고 |
+|----------|--------|-------|
+| **No-op (기본)** | 설정 불필요 | LLM 기반 압축/요약이 비활성화됨. 합성 BM25 압축 + 리콜은 여전히 동작. 이전에 Claude-subscription 폴백에 의존했다면 아래의 `AGENTMEMORY_ALLOW_AGENT_SDK` 참고. |
+| Anthropic API | `ANTHROPIC_API_KEY` | 토큰당 청구 |
+| MiniMax | `MINIMAX_API_KEY` | Anthropic 호환 |
+| Gemini | `GEMINI_API_KEY` | 임베딩도 활성화 |
+| OpenRouter | `OPENROUTER_API_KEY` | 모든 모델 |
+| Claude subscription 폴백 | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | 옵트인 전용. `@anthropic-ai/claude-agent-sdk` 세션을 스폰 — 무한 Stop-hook 재귀를 일으킨 전력이 있어서(#149 후속) 더 이상 기본값이 아닙니다. |
+
+### 비용 인식 모델 선택
+
+백그라운드 압축은 모든 관측마다 실행되므로 모델 선택이 월별 지출에 의미 있게 영향을 미칩니다. 캡처된 워크로드 데이터: 635 요청 / 888K 토큰 / 35시간의 활성 사용, 2026-05-23 가격으로 세 가지 OpenRouter 모델에 대해 실행.
+
+| 티어 | 모델 | Input / 1M | Output / 1M | 캡처된 35h 비용 | 비고 |
+|------|-------|------------|-------------|---------------------------|-------|
+| 권장 | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | 견고한 압축 + 요약 품질, Sonnet 대비 ~10배 저렴. |
+| 권장 | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | 더 오래되었지만 압축 전용 워크로드에 여전히 적합. |
+| 권장 | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | 세션이 코드 중심이라면 강한 코드 추론. |
+| 프리미엄 | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | 고품질이지만 항시 백그라운드 작업에는 비쌈. |
+| 프리미엄 | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Sonnet과 유사한 티어. |
+| 회피 | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | 추론 클래스 모델; 압축에는 막대한 과지출. |
+
+`OPENROUTER_MODEL`이 프리미엄 티어 패턴과 일치하면 agentmemory가 런타임 경고를 출력합니다. 정보에 기반한 결정을 내렸다면 `AGENTMEMORY_SUPPRESS_COST_WARNING=1`로 한 번에 침묵시키십시오.
+
+메모리 작업에서의 품질 대 비용 트레이드오프: 압축은 비교적 느슨한 품질 기준을 가진 요약 작업입니다(사용자가 아니라 에이전트가 요약을 다시 읽습니다). DeepSeek-V4-Pro / Qwen3-Coder는 이 작업에서 Sonnet과 반올림 오차 내에 들어가면서 ~10배 적은 비용이 듭니다. 프리미엄 티어 모델은 직접 읽는 쿼리에 남겨두십시오.
+
+출처: [OpenRouter pricing for Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### 멀티 에이전트 메모리 (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+여러 역할(architect / developer / reviewer / researcher / support-agent)이 하나의 agentmemory 서버를 공유하는 멀티 에이전트 설정에서, `AGENT_ID`는 모든 쓰기에 그것을 작성한 역할을 태깅합니다. `AGENTMEMORY_AGENT_SCOPE`는 리콜이 그 태그로 필터링되는지 여부를 제어합니다.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+두 가지 모드:
+
+| 모드 | 쓰기 태그 | 리콜 필터링 | 사용 시점 |
+|------|------------|---------------|-------------|
+| `shared` (기본) | 예 | 아니오 | 감사 로그가 있는 크로스 에이전트 컨텍스트. architect는 developer가 기록한 내용을 볼 수 있지만, 모든 행은 누가 말했는지 기록합니다. |
+| `isolated` | 예 | 예 | 엄격한 분리. architect는 developer의 관측 / 메모리 / 세션을 절대 보지 않습니다. |
+
+`AGENT_ID`가 설정되었을 때 태깅되는 것: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. 역할은 `api::session::start` → `mem::observe` → `mem::compress` → KV로 흐릅니다.
+
+isolated 모드에서 필터링되는 것: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. 각 엔드포인트는 요청별로 덮어쓰기 위해 `?agentId=`을 받고, env 스코프를 완전히 옵트아웃하기 위해 `?agentId=*`을 받습니다. `/memories`는 또한 `agentId`가 undefined인 pre-AGENT_ID 메모리를 노출하기 위해 `?includeOrphans=true`를 받습니다.
+
+SDK / REST 레이어에서의 호출별 덮어쓰기: 모든 변형 엔드포인트(`/session/start`, `/remember`)는 env를 이기는 `agentId` 필드를 request body에서 받습니다. 많은 역할을 하나의 서버 프로세스로 라우팅하는 런타임에 유용합니다.
+
+`AGENT_ID`가 설정되지 않았을 때, 메모리는 스코프되지 않은 상태로 유지됩니다(레거시 동작, 태그 없음, 필터 없음).
+
+### 포트
+
+agentmemory + iii-engine은 기본적으로 네 개의 포트에 바인딩합니다. 재시작이 `port in use`로 실패한다면, 이 표가 어떤 프로세스를 찾을지 알려줍니다.
+
+| 포트 | 프로세스 | 용도 | Env 덮어쓰기 |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | 내부 streams 워커 (agentmemory + 뷰어가 소비) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | 실시간 뷰어 (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — 워커가 여기에 등록, OTel 텔레메트리가 이 위로 흐름 | `III_ENGINE_URL` (전체 URL, 기본 `ws://localhost:49134`) |
+
+크래시된 실행 후 포트가 바인딩된 채로 남아 있을 때의 정리:
+
+```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`은 정상 종료 시 워커와 엔진 pidfile을 모두 깔끔하게 회수합니다 (#640, #474). 위의 수동 정리는 어떤 pidfile도 남지 않은 크래시 후 케이스에만 해당됩니다.
+
+### 설정 파일
+
+매 셸에서 변수를 export하는 대신 agentmemory 런타임 설정을 `~/.agentmemory/.env`에 두십시오. 뷰어가 `export ANTHROPIC_API_KEY=...` 같은 setup 힌트를 보여주면, `export` 접두사 없이 `ANTHROPIC_API_KEY=...`로 이 파일에 복사한 후 agentmemory를 재시작하십시오.
+
+프로세스 환경 변수는 여전히 동작하며 파일의 값보다 우선순위가 높습니다.
+
+Windows에서 동일한 파일은 `%USERPROFILE%\.agentmemory\.env`에 있습니다:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+API 키 대신 Claude Code Pro/Max subscription으로 테스트하려면 명시적으로 옵트인하십시오:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+원한다면 동일한 파일에서 graph 또는 consolidation 기능을 활성화하십시오:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### 환경 변수
+
+`~/.agentmemory/.env` 생성:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+`3111` 포트의 124개 엔드포인트. REST API는 기본적으로 `127.0.0.1`에 바인딩됩니다. 보호된 엔드포인트는 `AGENTMEMORY_SECRET`이 설정되었을 때 `Authorization: Bearer `를 요구하며, mesh sync 엔드포인트는 양쪽 피어 모두에서 `AGENTMEMORY_SECRET`을 요구합니다.
+
+
+주요 엔드포인트
+
+| Method | Path | 설명 |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | 헬스 체크 (항상 공개) |
+| `POST` | `/agentmemory/session/start` | 세션 시작 + 컨텍스트 가져오기 |
+| `POST` | `/agentmemory/session/end` | 세션 종료 |
+| `POST` | `/agentmemory/observe` | 관측 캡처 |
+| `POST` | `/agentmemory/smart-search` | 하이브리드 검색 |
+| `POST` | `/agentmemory/context` | 컨텍스트 생성 |
+| `POST` | `/agentmemory/remember` | 장기 메모리에 저장 |
+| `POST` | `/agentmemory/forget` | 관측 삭제 |
+| `POST` | `/agentmemory/enrich` | 파일 컨텍스트 + 메모리 + 버그 |
+| `GET` | `/agentmemory/profile` | 프로젝트 프로필 |
+| `GET` | `/agentmemory/export` | 모든 데이터 내보내기 |
+| `POST` | `/agentmemory/import` | JSON에서 가져오기 |
+| `POST` | `/agentmemory/graph/query` | 지식 그래프 쿼리 |
+| `POST` | `/agentmemory/team/share` | 팀과 공유 |
+| `GET` | `/agentmemory/audit` | 감사 로그 |
+
+전체 엔드포인트 목록: [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**전제 조건:** Node.js >= 20, [iii-engine](https://iii.dev/docs) 또는 Docker
+
+
+
+ Seu agente de codificação lembra de tudo. Chega de re-explicar.
+ Built on iii engine
+
+ Memória persistente para Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode e qualquer cliente MCP.
+
+ O gist estende o padrão LLM Wiki do Karpathy com pontuação de confiança, ciclo de vida, grafos de conhecimento e busca híbrida: agentmemory é a implementação.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+Ou via `npx` (sem instalação):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Atenção — o npx faz cache por versão. Se um simples `npx @agentmemory/agentmemory` servir uma release antiga, force a mais recente com `npx -y @agentmemory/agentmemory@latest`, ou limpe o cache uma vez com `rm -rf ~/.npm/_npx` (macOS/Linux; no Windows apague `%LOCALAPPDATA%\npm-cache\_npx`). A primeira execução via npx a partir da v0.9.16+ pergunta inline se você quer instalar globalmente, de modo que o comando `agentmemory` simples funcione em qualquer lugar depois.
+
+Opções completas em [Início rápido](#quick-start) abaixo. Conexão específica por agente em [Funciona com qualquer agente](#works-with-every-agent).
+
+---
+
+
+
+agentmemory funciona com qualquer agente que suporte hooks, MCP ou REST API. Todos os agentes compartilham o mesmo servidor de memória.
+
+
+
+
+
+Claude Code
+native plugin + 12 hooks + MCP
+
+
+
+Codex CLI
+native plugin + 6 hooks + MCP
+
+
+
+OpenClaw
+native plugin + MCP
+
+
+
+Hermes
+native plugin + MCP
+
+
+
+pi
+native plugin + MCP
+
+
+
+OpenHuman
+native Memory trait backend
+
+
+
+Cursor
+MCP server
+
+
+
+Gemini CLI
+MCP server
+
+
+
+
+
+OpenCode
+22 hooks + MCP + plugin
+
+
+
+Cline
+MCP server
+
+
+
+Goose
+MCP server
+
+
+
+Kilo Code
+MCP server
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP server
+
+
+
+Windsurf
+MCP server
+
+
+
+Roo Code
+MCP server
+
+
+
+
+
+ Funciona com qualquer agente que fale MCP ou HTTP. Um servidor, memórias compartilhadas entre todos eles.
+
+
+---
+
+Você explica a mesma arquitetura toda sessão. Você redescobre os mesmos bugs. Você reensina as mesmas preferências. A memória integrada (CLAUDE.md, .cursorrules) bate no teto das 200 linhas e fica desatualizada. agentmemory resolve isso. Ele captura silenciosamente o que seu agente faz, comprime em memória pesquisável e injeta o contexto certo quando a próxima sessão começa. Um comando. Funciona em todos os agentes.
+
+**O que muda:** Na sessão 1 você configura autenticação JWT. Na sessão 2 você pede rate limiting. O agente já sabe que sua autenticação usa o middleware jose em `src/middleware/auth.ts`, que seus testes cobrem a validação de tokens e que você escolheu jose em vez de jsonwebtoken por compatibilidade com Edge. Sem re-explicar. Sem copiar e colar. O agente simplesmente *sabe*.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **Novidade na v0.9.0** — Landing em [agent-memory.dev](https://agent-memory.dev), conector de filesystem (`@agentmemory/fs-watcher`), MCP standalone agora faz proxy para o servidor em execução, então hooks e viewer combinam, política de auditoria codificada em cada caminho de deleção, e health para de marcar `memory_critical` em processos Node pequenos. Notas completas em [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18).
+
+---
+
+
+
+
+
+
+
+### Precisão de recuperação
+
+**coding-agent-life-v1** (corpus interno, reproduzível em sandbox)
+
+| Adaptador | P@5 | R@5 | Taxa de acerto top-5 | Latência p50 |
+|---|---|---|---|---|
+| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms |
+| grep baseline | 0.267 | 0.967 | 15 / 15 | 0 ms |
+
+Taxa de acerto top-5 de 100%. **2,2×** mais precisão que a baseline grep com a mesma entrada. Detalhamento completo por tipo: [`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 perguntas)
+
+| Sistema | R@5 | R@10 | MRR |
+|---|---|---|---|
+| **agentmemory** | **95.2%** | **98.6%** | **88.2%** |
+| BM25-only fallback | 86.2% | 94.6% | 71.5% |
+
+
+
+> Modelo de embedding: `all-MiniLM-L6-v2` (local, gratuito, sem API key). Relatórios completos: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Comparativo com concorrentes: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory vs mem0, Letta, Khoj, claude-mem, Hippo.
+
+**Reproduza localmente:** [`eval/README.md`](../eval/README.md) — harness com adaptadores plugáveis para LongMemEval `_s` (500-Q públicas) e `coding-agent-life-v1` (corpus interno de 15 sessões). Adaptadores grep / vector / agentmemory são pontuados lado a lado, saída em NDJSON, e as scorecards publicadas ficam em [`docs/benchmarks/`](../docs/benchmarks/).
+
+**Combina com [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) e [Graphify](https://github.com/safishamsi/graphify).** Indexação de grafos de código, pipelines de build multiagente e grafos de conhecimento mais amplos sobre docs / PDFs / imagens / vídeos. agentmemory lembra do trabalho; esses três projetos iluminam o resto da camada de contexto. Recipes e tabela de roteamento por pergunta: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+
+
+
+
agentmemory
+
mem0 (53K ⭐)
+
Letta / MemGPT (22K ⭐)
+
Built-in (CLAUDE.md)
+
+
+
Tipo
+
Engine de memória + servidor MCP
+
API de camada de memória
+
Runtime de agente completo
+
Arquivo estático
+
+
+
Retrieval R@5
+
95.2%
+
68.5% (LoCoMo)
+
83.2% (LoCoMo)
+
N/A (grep)
+
+
+
Captura automática
+
12 hooks (esforço manual zero)
+
Chamadas manuais a add()
+
O agente se autoedita
+
Edição manual
+
+
+
Busca
+
BM25 + Vector + Graph (fusão RRF)
+
Vector + Graph
+
Vector (archival)
+
Carrega tudo no contexto
+
+
+
Multiagente
+
MCP + REST + leases + signals
+
API (sem coordenação)
+
Somente dentro do runtime do Letta
+
Arquivos por agente
+
+
+
Dependência de framework
+
Nenhuma (qualquer cliente MCP)
+
Nenhuma
+
Alta (precisa usar Letta)
+
Formato por agente
+
+
+
Dependências externas
+
Nenhuma (SQLite + iii-engine)
+
Qdrant / pgvector
+
Postgres + BD vetorial
+
Nenhuma
+
+
+
Ciclo de vida da memória
+
Consolidação de 4 níveis + decaimento + auto-esquecimento
+
Extração passiva
+
Gerenciado pelo agente
+
Poda manual
+
+
+
Eficiência de tokens
+
~1.900 tokens/sessão ($10/ano)
+
Varia conforme a integração
+
Memória principal no contexto
+
22K+ tokens com 240 obs
+
+
+
Viewer em tempo real
+
Sim (port 3113)
+
Dashboard na nuvem
+
Dashboard na nuvem
+
Não
+
+
+
Self-hosted
+
Sim (padrão)
+
Opcional
+
Opcional
+
Sim
+
+
+
+---
+
+
+
+Compatibilidade: este release tem como alvo o `iii-sdk` estável `^0.11.0` e o iii-engine v0.11.x.
+
+### Experimente em 30 segundos
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo` semeia 3 sessões realistas (autenticação JWT, correção de N+1 queries, rate limiting) e roda buscas semânticas sobre elas. Você verá que ele encontra "N+1 query fix" ao buscar "database performance optimization" — algo que matching por palavra-chave não consegue fazer.
+
+Abra `http://localhost:3113` para acompanhar a memória sendo construída ao vivo.
+
+### Recomendado: instale globalmente
+
+`npx` faz cache por versão. Se você rodou `npx @agentmemory/agentmemory@0.9.14` semana passada, um simples `npx @agentmemory/agentmemory` pode servir a versão velha 0.9.14 a partir de `~/.npm/_npx/`, e não a mais recente. Instale uma vez e o comando `agentmemory` funciona em qualquer lugar:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+A partir da v0.9.16, a primeira execução via npx pergunta inline se você quer instalar globalmente — responda `Y` uma vez e está pronto. Se pular, recorra a qualquer um destes para um fetch limpo:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+No Windows / PowerShell, o equivalente para limpar cache é `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — a forma `npx -y ...@latest` acima é a opção multiplataforma.
+
+### Session Replay
+
+Toda sessão que o agentmemory grava é reproduzível. Abra o viewer, escolha a aba **Replay** e arraste pela timeline: prompts, chamadas a tools, resultados e respostas renderizam como eventos discretos com play/pause, controle de velocidade (0,5×–4×) e atalhos de teclado (espaço para alternar, setas para avançar passo a passo).
+
+Já tem transcripts antigos JSONL do Claude Code que quer trazer para cá?
+
+```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
+```
+
+As sessões importadas aparecem no seletor de Replay ao lado das nativas. Sob o capô, cada entrada passa pelas funções iii `mem::replay::load`, `mem::replay::sessions` e `mem::replay::import-jsonl` — sem servidores paralelos.
+
+### Atualização / Manutenção
+
+Use o comando de manutenção quando você intencionalmente quiser atualizar seu runtime local:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Aviso: este comando muta o workspace/runtime atual. Pode atualizar dependências JavaScript, pode rodar `cargo install iii-engine --force` e pode puxar imagens Docker.
+
+Detalhes de implementação estão em `src/cli.ts` (veja `runUpgrade` na região `src/cli.ts:544-595`).
+
+### Claude Code (um bloco, cole)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 sem instalar o plugin (caminho MCP standalone)
+
+Se você cabear o servidor MCP do agentmemory via `~/.claude.json` diretamente em vez de usar `/plugin install`, o Claude Code nunca resolve `${CLAUDE_PLUGIN_ROOT}` e você tem que apontar os scripts de hook para caminhos absolutos em `~/.claude/settings.json`. Esses caminhos tipicamente embutem a versão do agentmemory (ex: `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), então a próxima atualização quebra silenciosamente todos os hooks ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Contorno:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Isso mescla os mesmos comandos de hook em `~/.claude/settings.json` com caminhos absolutos resolvidos para o diretório `plugin/` empacotado do pacote `@agentmemory/agentmemory` atualmente instalado. Rode o comando novamente após atualizar o agentmemory para atualizar os caminhos. Entradas de usuário no mesmo arquivo são preservadas; apenas entradas anteriores do agentmemory são substituídas. Usar o caminho `/plugin install` continua sendo a abordagem recomendada.
+Para deploys remotos ou protegidos, inicie o Claude Code com `AGENTMEMORY_URL` e `AGENTMEMORY_SECRET` definidos. O plugin repassa ambos os valores para seu servidor MCP empacotado; quando `AGENTMEMORY_URL` está vazio, o shim MCP usa `http://localhost:3111`.
+
+### Codex CLI (plataforma de plugins do Codex)
+
+```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
+```
+
+O plugin do Codex é servido a partir do mesmo diretório `plugin/` do plugin do Claude Code. Ele registra:
+
+- `@agentmemory/mcp` como servidor MCP (faz proxy de todas as 51 tools quando `AGENTMEMORY_URL` aponta para um servidor agentmemory em execução; cai para 7 tools localmente quando não há servidor acessível)
+- 6 hooks de ciclo de vida: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skills: `/recall`, `/remember`, `/session-history`, `/forget`
+
+A engine de hooks do Codex injeta `CLAUDE_PLUGIN_ROOT` nos subprocessos de hook (conforme [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), então os mesmos scripts de hook funcionam nos dois hosts sem duplicação. Os eventos Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure são exclusivos do Claude Code e não são registrados para o Codex.
+
+#### Codex Desktop: hooks do plugin atualmente silenciosos (com contorno)
+
+`CodexHooks` e `PluginHooks` são estáveis e habilitados por padrão em [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), mas as builds atuais do Codex Desktop não despacham `hooks.json` local de plugin ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). As tools MCP continuam funcionando; só as observações de ciclo de vida estão faltando.
+
+Até que o upstream corrija, espelhe os mesmos comandos de hook no `~/.codex/hooks.json` global:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Isso adiciona um bloco idempotente em `~/.codex/hooks.json` referenciando caminhos absolutos para os scripts empacotados (sem necessidade de expansão de `${CLAUDE_PLUGIN_ROOT}` no escopo de usuário). Rode o mesmo comando novamente após atualizar o agentmemory para atualizar os caminhos. Entradas de usuário no mesmo arquivo são preservadas; só entradas anteriores do agentmemory são substituídas.
+
+
+OpenClaw (cole este 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 51 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`.
+```
+
+Guia completo: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (cole este 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 51 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.
+```
+
+Guia completo: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Outros agentes
+
+Inicie o servidor de memória: `npx @agentmemory/agentmemory`
+
+A entrada do agentmemory é o **mesmo bloco de servidor MCP** em todo host que usa o formato `mcpServers` (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw):
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Mescle esta entrada no objeto `mcpServers` existente** no arquivo de configuração do host — não substitua o arquivo. Se o arquivo já tem outros servidores, adicione `agentmemory` ao lado deles como outra chave dentro de `mcpServers`. Se `mcpServers` não existe, cole o bloco dentro de `{ "mcpServers": { ... } }`. Os placeholders `${VAR}` herdam `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` do shell no momento em que o servidor MCP sobe — variáveis não definidas passam string vazia e o shim cai para `http://localhost:3111`. Uma entrada cabeada cobre deploys tanto locais quanto remotos (k8s / com reverse-proxy).
+
+| Agente | Arquivo de configuração | Notas |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | Mescle em `mcpServers`. Deeplink de um clique também disponível no site. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Mescle em `mcpServers`. Reinicie o Claude Desktop após editar. |
+| **Cline / Roo Code / Kilo Code** | Configurações MCP do Cline (Settings UI → MCP Servers → Edit) | Mesmo bloco `mcpServers`. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Mesmo bloco `mcpServers`. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (mescla automaticamente). |
+| **OpenClaw** | Configuração MCP do OpenClaw | Mesmo bloco `mcpServers`, ou use o [memory plugin](../integrations/openclaw/) mais profundo. |
+| **Codex CLI (somente MCP)** | `.codex/config.toml` | Formato TOML: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, ou adicione `[mcp_servers.agentmemory]` manualmente. |
+| **Codex CLI (plugin completo)** | Marketplace de plugins do Codex | `codex plugin marketplace add rohitg00/agentmemory` e depois `codex plugin add agentmemory@agentmemory`. Registra MCP + 6 hooks de ciclo de vida (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. No Codex Desktop, rode também `agentmemory connect codex --with-hooks` até que [openai/codex#16430](https://github.com/openai/codex/issues/16430) seja mergeado — os hooks de plugin estão silenciosos lá. |
+| **OpenCode (somente MCP)** | `opencode.json` | Formato diferente — chave `mcp` no topo, comando como array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (plugin completo)** | `plugin/opencode/` | 22 hooks de captura automática cobrindo ciclo de vida de sessão, mensagens, tools e erros. Dois comandos slash (`/recall`, `/remember`). Copie `plugin/opencode/` para seu workspace do OpenCode e adicione a entrada do plugin em `opencode.json`. Tabela completa de hooks + análise de gaps em [`plugin/opencode/README.md`](../plugin/opencode/README.md). |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | Copie [`integrations/pi`](../integrations/pi/) e reinicie o pi. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Use o [memory provider plugin](../integrations/hermes/) mais profundo com `memory.provider: agentmemory`. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` escreve o bloco `mcpServers` padrão. O payload dos hooks é compatível em nível de campo com o Claude Code, então os scripts dos 12 hooks existentes funcionam sem modificação — cabê-los na seção `hooks` do mesmo `settings.json`. |
+| **Antigravity** (substitui o Gemini CLI) | `mcp_config.json` (no diretório User do Antigravity) | `agentmemory connect antigravity` escreve o bloco `mcpServers` padrão. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Use após o sunset do Gemini CLI em 2026-06-18. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` escreve a configuração no nível do usuário. Overrides por workspace vão em `.kiro/settings/mcp.json` ao lado do seu código. |
+| **Goose** | UI de configurações MCP do Goose | Mesmo bloco `mcpServers`. |
+| **Aider** | n/a | Fale diretamente com a REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Qualquer agente (32+)** | n/a | `npx skillkit install agentmemory` autodetecta o host e mescla. |
+
+**Clientes MCP em sandbox** (Flatpak / Snap / contêineres restritivos) que não conseguem alcançar o `localhost` do host: também defina `"AGENTMEMORY_FORCE_PROXY": "1"` no bloco `env`, e aponte `AGENTMEMORY_URL` para uma rota que o sandbox realmente alcance (ex: seu IP de LAN). Veja [#234](https://github.com/rohitg00/agentmemory/issues/234) para o passo a passo de diagnóstico.
+
+### Acesso programático (Python / Rust / Node)
+
+agentmemory registra suas operações principais como funções iii (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Qualquer linguagem com um SDK iii pode chamá-las diretamente via `ws://localhost:49134` — sem um cliente REST separado por linguagem.
+
+```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"},
+})
+```
+
+Exemplo prático: [`examples/python/`](../examples/python/) (quickstart + fluxo de observação/recall). A REST em `:3111` continua disponível para hosts sem runtime iii.
+
+### A partir do código-fonte
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Isso inicia o agentmemory com um `iii-engine` local se `iii` já estiver instalado, ou cai para Docker Compose se o Docker estiver disponível. REST, streams e o viewer fazem bind em `127.0.0.1` por padrão.
+
+Instale o `iii-engine` manualmente. **O agentmemory atualmente fixa o `iii-engine` em `v0.11.2`** — `v0.11.6` introduz um novo modelo que faz sandbox de tudo via `iii worker add` que o agentmemory ainda não foi refatorado para usar. O pin sai assim que o refactor cair. Sobrescreva com `AGENTMEMORY_III_VERSION=` se você migrou manualmente para o modelo de sandbox.
+
+- **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:** troque `aarch64-apple-darwin` por `x86_64-apple-darwin`
+- **Linux x64:** troque por `x86_64-unknown-linux-gnu`
+- **Linux arm64:** troque por `aarch64-unknown-linux-gnu`
+- **Windows:** baixe `iii-x86_64-pc-windows-msvc.zip` de [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extraia `iii.exe`, adicione ao PATH
+
+Ou use Docker (o `docker-compose.yml` empacotado puxa `iiidev/iii:0.11.2`). Docs completas: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory roda em Windows 10/11, mas só o pacote Node.js não é suficiente — você também precisa do runtime `iii-engine` (um binário nativo separado) como processo em segundo plano. O instalador oficial upstream é um script `sh` e hoje não há instalador PowerShell nem pacote scoop/winget, então usuários de Windows têm dois caminhos:
+
+**Opção A — Binário Windows pré-compilado (recomendado):**
+
+```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
+```
+
+**Opção 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
+```
+
+**Opção C — apenas MCP standalone (sem engine):** se você só precisa das tools MCP para seu agente e não precisa da REST API, viewer ou cron jobs, pule o engine completamente:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Diagnóstico para Windows:** se `npx @agentmemory/agentmemory` falhar, rode novamente com `--verbose` para ver o stderr real do engine. Modos de falha comuns:
+
+| Sintoma | Correção |
+|---|---|
+| `iii-engine process started` seguido de `did not become ready within 15s` | Engine crashou na inicialização — rode novamente com `--verbose`, verifique stderr |
+| `Could not start iii-engine` | Nem `iii.exe` nem Docker estão instalados. Veja Opção A ou B acima |
+| Conflito de porta | `netstat -ano \| findstr :3111` para ver o que está em bind, mate o processo ou use `--port ` |
+| Fallback do Docker é pulado mesmo com Docker instalado | Confira se o Docker Desktop está de fato rodando (ícone na bandeja do sistema) |
+
+> Nota: não existe `cargo install iii-engine` — `iii` não é publicado no crates.io. Os únicos métodos de instalação suportados são o binário pré-compilado acima, o script de instalação `sh` upstream (somente macOS/Linux) e a imagem Docker.
+
+---
+
+
Deploy
+
+Templates de um clique para hosts gerenciados. Cada um inclui um
+Dockerfile autocontido que puxa `@agentmemory/agentmemory` do npm
+e copia o binário do iii engine da imagem oficial `iiidev/iii` no
+Docker Hub — sem necessidade de imagem pré-compilada do agentmemory.
+Armazenamento persistente monta em `/data`; o entrypoint de primeiro
+boot sobrescreve a configuração iii empacotada pelo npm (que faz
+bind em `127.0.0.1`) por uma ajustada para deploy que faz bind em
+`0.0.0.0` e usa caminhos absolutos `/data`, gera o segredo HMAC e
+depois reduz privilégios de `root` para `node` via `gosu` antes de
+fazer exec do CLI do agentmemory.
+
+
+
+
+
+
+O botão de deploy de um clique do Render exige um `render.yaml` na raiz do repositório, que mantemos limpo de propósito. Use o fluxo Render Blueprint documentado em [`deploy/render/`](../deploy/render/README.md) para apontar para o blueprint do repo manualmente.
+
+Detalhes completos de setup (captura de HMAC, túnel SSH do viewer, rotação, backup, mínimos de custo) ficam em [`deploy/`](../deploy/README.md):
+
+- [`deploy/fly`](../deploy/fly/README.md) — máquina única com `auto_stop_machines = "stop"`; mais barato em idle.
+- [`deploy/railway`](../deploy/railway/README.md) — taxa plana do plano Hobby, volume no dashboard.
+- [`deploy/render`](../deploy/render/README.md) — fluxo Blueprint, snapshots automáticos de disco nos planos pagos.
+- [`deploy/coolify`](../deploy/coolify/README.md) — self-hosted no seu próprio VPS via [Coolify](https://coolify.io/self-hosted); mesma stack Docker Compose, você possui o host e os dados.
+
+Somente a porta `3111` é publicada. O viewer em `3113` fica em bind no loopback dentro do contêiner — o README de cada template documenta o padrão de túnel SSH para alcançá-lo.
+
+---
+
+
+
+Todo agente de codificação esquece tudo quando a sessão termina. Você desperdiça os primeiros 5 minutos de toda sessão re-explicando sua stack. agentmemory roda em segundo plano e elimina isso por completo.
+
+```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 memória integrada do agente
+
+Todo agente de codificação com IA vem com memória integrada — Claude Code tem `MEMORY.md`, Cursor tem notepads, Cline tem memory bank. Funcionam como post-its. agentmemory é o banco de dados pesquisável por trás dos post-its.
+
+| | Integrada (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Escala | teto de 200 linhas | Ilimitado |
+| Busca | Carrega tudo no contexto | BM25 + vector + graph (só top-K) |
+| Custo em tokens | 22K+ com 240 observações | ~1.900 tokens (92% menos) |
+| Cross-agent | Arquivos por agente | MCP + REST (qualquer agente) |
+| Coordenação | Nenhuma | Leases, signals, actions, routines |
+| Observabilidade | Leitura manual de arquivos | Viewer em tempo real em :3113 |
+
+---
+
+
+
+### Pipeline de memória
+
+```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
+```
+
+### Consolidação de memória em 4 níveis
+
+Inspirada em como o cérebro humano processa memória — não muito diferente da consolidação do sono.
+
+| Nível | O quê | Analogia |
+|------|------|---------|
+| **Working** | Observações brutas a partir do uso de tools | Memória de curto prazo |
+| **Episodic** | Resumos de sessão comprimidos | "O que aconteceu" |
+| **Semantic** | Fatos e padrões extraídos | "O que eu sei" |
+| **Procedural** | Workflows e padrões de decisão | "Como fazer" |
+
+As memórias decaem com o tempo (curva de Ebbinghaus). Memórias acessadas com frequência se reforçam. Memórias velhas são evictadas automaticamente. Contradições são detectadas e resolvidas.
+
+### O que é capturado
+
+| Hook | Captura |
+|------|----------|
+| `SessionStart` | Caminho do projeto, ID da sessão |
+| `UserPromptSubmit` | Prompts do usuário (filtrados por privacidade) |
+| `PreToolUse` | Padrões de acesso a arquivos + contexto enriquecido |
+| `PostToolUse` | Nome da tool, entrada, saída |
+| `PostToolUseFailure` | Contexto do erro |
+| `PreCompact` | Reinjeta memória antes da compactação |
+| `SubagentStart/Stop` | Ciclo de vida de sub-agentes |
+| `Stop` | Resumo de fim de sessão |
+| `SessionEnd` | Marcador de sessão completa |
+
+### Principais capacidades
+
+| Capacidade | Descrição |
+|---|---|
+| **Captura automática** | Todo uso de tool registrado via hooks — esforço manual zero |
+| **Busca semântica** | BM25 + vector + grafo de conhecimento com fusão RRF |
+| **Evolução de memória** | Versionamento, supersessão, grafos de relacionamento |
+| **Auto-esquecimento** | Expiração por TTL, detecção de contradição, evicção por importância |
+| **Privacy first** | API keys, segredos e tags `` são removidos antes do armazenamento |
+| **Self-healing** | Circuit breaker, cadeia de fallback de providers, monitoramento de saúde |
+| **Ponte Claude** | Sincronização bidirecional com MEMORY.md |
+| **Grafo de conhecimento** | Extração de entidades + travessia BFS |
+| **Memória de time** | Compartilhado namespaced + privado entre membros do time |
+| **Provenance de citação** | Rastreia qualquer memória de volta às observações originais |
+| **Snapshots Git** | Versiona, faz rollback e diff do estado de memória |
+
+---
+
+
+
+Recuperação triple-stream combinando três sinais:
+
+| Stream | O que faz | Quando |
+|---|---|---|
+| **BM25** | Matching de palavra-chave com stemming + expansão de sinônimos | Sempre ativo |
+| **Vector** | Similaridade de cosseno sobre embeddings densos | Provider de embedding configurado |
+| **Graph** | Travessia do grafo de conhecimento via matching de entidades | Entidades detectadas na query |
+
+Fundidos com Reciprocal Rank Fusion (RRF, k=60) e diversificados por sessão (máximo de 3 resultados por sessão).
+
+BM25 tokeniza grego, cirílico, hebraico, árabe e latim acentuado de fábrica. Para memórias em chinês / japonês / coreano, instale os segmentadores opcionais (`npm install @node-rs/jieba tiny-segmenter`) para quebrar runs CJK em tokens em nível de palavra; sem eles, o agentmemory faz soft-fallback para tokenização por run inteiro e imprime uma dica única no stderr.
+
+### Providers de embedding
+
+agentmemory autodetecta seu provider. Para melhores resultados, instale embeddings locais (gratuito):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Provider | Modelo | Custo | Notas |
+|---|---|---|---|
+| **Local (recomendado)** | `all-MiniLM-L6-v2` | Gratuito | Offline, +8pp de recall sobre BM25-only |
+| Gemini | `gemini-embedding-001` | Free tier | 100+ idiomas, 768/1536/3072 dims (MRL), entrada de 2048 tokens. Substitui `text-embedding-004` ([deprecado, encerramento em 14 de janeiro de 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | $0.02/1M | Maior qualidade |
+| Voyage AI | `voyage-code-3` | Pago | Otimizado para código |
+| Cohere | `embed-english-v3.0` | Trial gratuito | Uso geral |
+| OpenRouter | Qualquer modelo | Varia | Proxy multi-modelo |
+
+---
+
+
+
+53 tools, 6 resources, 3 prompts e 4 skills — o toolkit MCP de memória mais completo para qualquer agente.
+
+> **Shim MCP vs servidor completo:** o pacote publicado `@agentmemory/mcp` é um shim fino. Expõe a superfície completa de 51 tools **apenas quando consegue alcançar um servidor agentmemory em execução** via `AGENTMEMORY_URL` (modo proxy). Sem servidor acessível, o shim cai para um set local de 7 tools (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). A variável de ambiente `AGENTMEMORY_TOOLS=core|all` é uma flag *do lado do servidor* — defini-la no bloco `env` do shim não tem efeito. Se você vê só 7 tools no Cursor / OpenCode / Gemini CLI, inicie `npx @agentmemory/agentmemory` (ou a stack Docker) e defina `AGENTMEMORY_URL=http://localhost:3111`.
+
+### 51 Tools
+
+
+Tools principais (sempre disponíveis)
+
+| Tool | Descrição |
+|------|-------------|
+| `memory_recall` | Busca observações passadas |
+| `memory_compress_file` | Comprime arquivos markdown preservando a estrutura |
+| `memory_save` | Salva um insight, decisão ou padrão |
+| `memory_patterns` | Detecta padrões recorrentes |
+| `memory_smart_search` | Busca híbrida semântica + por palavras |
+| `memory_file_history` | Observações passadas sobre arquivos específicos |
+| `memory_sessions` | Lista sessões recentes |
+| `memory_timeline` | Observações cronológicas |
+| `memory_profile` | Perfil de projeto (conceitos, arquivos, padrões) |
+| `memory_export` | Exporta todos os dados de memória |
+| `memory_relations` | Consulta o grafo de relacionamentos |
+
+
+
+
+Tools estendidas (51 no total — defina AGENTMEMORY_TOOLS=all)
+
+| Tool | Descrição |
+|------|-------------|
+| `memory_patterns` | Detecta padrões recorrentes |
+| `memory_timeline` | Observações cronológicas |
+| `memory_relations` | Consulta o grafo de relacionamentos |
+| `memory_graph_query` | Travessia do grafo de conhecimento |
+| `memory_consolidate` | Executa a consolidação de 4 níveis |
+| `memory_claude_bridge_sync` | Sincroniza com MEMORY.md |
+| `memory_team_share` | Compartilha com membros do time |
+| `memory_team_feed` | Itens compartilhados recentes |
+| `memory_audit` | Trilha de auditoria de operações |
+| `memory_governance_delete` | Deleção com trilha de auditoria |
+| `memory_snapshot_create` | Snapshot versionado no Git |
+| `memory_action_create` | Cria itens de trabalho com dependências |
+| `memory_action_update` | Atualiza status de action |
+| `memory_frontier` | Actions desbloqueadas ranqueadas por prioridade |
+| `memory_next` | A única action mais importante a seguir |
+| `memory_lease` | Leases exclusivos de actions (multiagente) |
+| `memory_routine_run` | Instancia rotinas de workflow |
+| `memory_signal_send` | Mensageria entre agentes |
+| `memory_signal_read` | Lê mensagens com confirmação de recebimento |
+| `memory_checkpoint` | Portões de condições externas |
+| `memory_mesh_sync` | Sincronização P2P entre instâncias |
+| `memory_sentinel_create` | Watchers dirigidos por eventos |
+| `memory_sentinel_trigger` | Dispara sentinels externamente |
+| `memory_sketch_create` | Grafos de actions efêmeros |
+| `memory_sketch_promote` | Promove para permanente |
+| `memory_crystallize` | Compacta cadeias de actions |
+| `memory_diagnose` | Health checks |
+| `memory_heal` | Corrige automaticamente estado travado |
+| `memory_facet_tag` | Tags dimension:value |
+| `memory_facet_query` | Consulta por tags de facet |
+| `memory_verify` | Rastreia provenance |
+
+
+
+### 6 Resources · 3 Prompts · 4 Skills
+
+| Tipo | Nome | Descrição |
+|------|------|-------------|
+| Resource | `agentmemory://status` | Saúde, contagem de sessões, contagem de memórias |
+| Resource | `agentmemory://project/{name}/profile` | Inteligência por projeto |
+| Resource | `agentmemory://memories/latest` | As 10 memórias ativas mais recentes |
+| Resource | `agentmemory://graph/stats` | Estatísticas do grafo de conhecimento |
+| Prompt | `recall_context` | Busca + retorna mensagens de contexto |
+| Prompt | `session_handoff` | Dados de handoff entre agentes |
+| Prompt | `detect_patterns` | Analisa padrões recorrentes |
+| Skill | `/recall` | Busca na memória |
+| Skill | `/remember` | Salva na memória de longo prazo |
+| Skill | `/session-history` | Resumos recentes de sessões |
+| Skill | `/forget` | Deleta observações/sessões |
+
+### MCP standalone
+
+Rode sem o servidor completo — para qualquer cliente MCP. Qualquer um destes funciona:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+Ou adicione à configuração MCP do seu agente:
+
+A maioria dos agentes (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+Mescle a entrada `agentmemory` no objeto `mcpServers` existente do seu host em vez de substituir o arquivo. Para clientes em sandbox que não conseguem alcançar o `localhost` do host, adicione `"AGENTMEMORY_FORCE_PROXY": "1"` ao bloco env e defina `AGENTMEMORY_URL` para uma rota que o sandbox alcance.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Copie o arquivo do plugin do repo:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Sobe automaticamente na porta `3113`. Stream ao vivo de observações, explorador de sessões, navegador de memórias, visualização do grafo de conhecimento e dashboard de saúde.
+
+```bash
+open http://localhost:3113
+```
+
+O servidor do viewer faz bind em `127.0.0.1` por padrão. O endpoint servido por REST `/agentmemory/viewer` segue as regras normais de bearer-token `AGENTMEMORY_SECRET`. Os headers CSP usam um nonce de script por resposta e desabilitam atributos de handler inline (`script-src-attr 'none'`).
+
+---
+
+
+
+O viewer em `:3113` mostra o que seu agente **lembrou**. O [iii console](https://iii.dev/docs/console) mostra o que seu agente **fez** — cada operação de memória como uma trace do OpenTelemetry, cada entrada KV editável, cada função invocável, cada stream observável. Duas janelas sobre a mesma memória: uma em formato de produto, outra em formato de engine.
+
+Veja um `memory_smart_search` disparar e enxergue o scan BM25 → busca de embedding → fusão RRF → reranker como um waterfall. Edite um timer de consolidação travado no navegador KV. Reproduza um hook `PostToolUse` com payload ajustado. Fixe o stream WebSocket e veja as observações chegando ao vivo.
+
+agentmemory oferece isso de graça porque toda função, trigger, escopo de estado e stream é um primitivo iii — nada custom, nada para instrumentar.
+
+
+
+
+ Página Workers: todo worker conectado — incluindo o próprio agentmemory — com PID, contagem de funções, runtime e last-seen.
+
+
+**Já instalado.** O console vem junto com `iii` — sem instalador separado.
+
+**Suba junto com o 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
+```
+
+Depois abra `http://localhost:3114`. Adicione `--enable-flow` para a página experimental de grafo de arquitetura.
+
+Sobrescreva endpoints do engine apenas se você os tiver movido:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**O que você pode fazer pelo console:**
+
+| Página | Use para |
+|------|-----------|
+| **Workers** | Ver todo worker conectado e suas métricas ao vivo — incluindo o próprio worker do agentmemory. |
+| **Functions** | Invocar qualquer função do agentmemory diretamente com um payload JSON — útil para testar `memory.recall`, `memory.consolidate`, `graph.query` sem cabear um cliente. |
+| **Triggers** | Reproduzir triggers HTTP, cron, event e state — disparar o cron de consolidação manualmente, reexecutar uma rota HTTP, emitir uma mudança de estado. |
+| **States** | Navegador KV com CRUD completo — sessões, slots de memória, timers de ciclo de vida, índice de embeddings — edite valores no lugar. |
+| **Streams** | Monitor WebSocket ao vivo para escritas de memória, eventos de hook e atualizações de observação à medida que fluem pelos streams iii. |
+| **Queues** | Tópicos de fila duráveis + gestão de dead-letter. Reproduza ou descarte jobs de embedding / compressão que falharam. |
+| **Traces** | Vistas waterfall / flame / breakdown por serviço do OpenTelemetry. Filtre por `trace_id` para ver exatamente quais funções, chamadas a DB e requisições de embedding um único `memory.search` produziu. |
+| **Logs** | Logs OTEL estruturados filtrados e correlacionados a trace/span IDs. |
+| **Config** | Configuração de runtime — veja exatamente com quais workers, providers e portas seu engine está rodando. |
+| **Flow** | (Opcional, `--enable-flow`) Grafo de arquitetura interativo de todo worker, trigger e stream. |
+
+
+
+
+ Traces: waterfall / flame / breakdown por serviço para toda operação de memória.
+
+
+**Traces já estão ativos:**
+
+`iii-config.yaml` vem com o worker `iii-observability` habilitado (`exporter: memory`, `sampling_ratio: 1.0`, métricas + logs). Sem configuração extra — no momento em que o agentmemory inicia, toda operação de memória emite um trace span e um log estruturado que o console consegue ler.
+
+Se você quiser exportar para Jaeger/Honeycomb/Grafana Tempo, troque `exporter: memory` por `exporter: otlp` e configure o endpoint do collector conforme a documentação de observabilidade do iii.
+
+> **Aviso:** nenhum auth é aplicado no console em si — mantenha-o em bind em `127.0.0.1` (o padrão) e nunca o exponha publicamente.
+
+---
+
+
+
+agentmemory **já é uma instância [iii](https://iii.dev) em execução**. Funções, triggers, estado KV, streams, traces OTEL — tudo são primitivos iii. Você não instalou Postgres, Redis, Express, pm2 ou Prometheus, porque o iii os substitui.
+
+Isso significa que mais um comando estende o agentmemory com uma capacidade totalmente nova.
+
+### Estenda o agentmemory com um comando
+
+```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
+```
+
+Cada `iii worker add` registra novas funções e triggers no mesmo engine onde o agentmemory já está rodando. O viewer e o console os reconhecem na hora — sem reload, sem nova integração, sem novo contêiner.
+
+| `iii worker add` | O que você ganha em cima do agentmemory |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Memória multi-instância: todo `remember` faz fanout, todo `search` lê a união |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Ciclo de vida agendado — consolidação noturna, snapshots semanais, decaimento em relógio fixo |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Retries duráveis: jobs falhos de embedding + compressão sobrevivem a restart, sem observações perdidas |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | Traces OTEL, métricas, logs em toda função — cabeado em `iii-config.yaml` desde o primeiro dia |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Código que veio do `memory_recall` roda dentro de uma VM descartável, não no seu shell |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | Adaptador de estado baseado em SQL quando você ultrapassa o KV in-memory padrão |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | Suba servidores MCP adicionais ao lado do MCP do agentmemory, compartilhando o mesmo engine |
+
+Registry completo: [workers.iii.dev](https://workers.iii.dev). Todo worker lá se compõe pelos mesmos primitivos que o agentmemory usa — e o agentmemory que você já tem é um deles.
+
+### O que o iii substitui
+
+| Stack tradicional | agentmemory usa |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + índice vetorial in-memory |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | Supervisão de workers do iii engine |
+| Prometheus / Grafana | iii OTEL + monitor de saúde |
+| Sistemas de plugin customizados | `iii worker add ` |
+
+**118 arquivos de código · ~21.800 LOC · 950+ tests · 123 funções · 34 escopos KV** — tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii.
+
+---
+
+
+
+### Providers de LLM
+
+agentmemory autodetecta a partir do seu ambiente. Por padrão, nenhuma chamada LLM é feita a menos que você configure um provider ou opte explicitamente pelo fallback de assinatura do Claude.
+
+| Provider | Config | Notas |
+|----------|--------|-------|
+| **No-op (padrão)** | Sem configuração | Compress/summarize via LLM DESATIVADO. Compressão sintética BM25 + recall ainda funcionam. Veja `AGENTMEMORY_ALLOW_AGENT_SDK` abaixo se você dependia do fallback de assinatura do Claude. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Cobrança por token |
+| MiniMax | `MINIMAX_API_KEY` | Compatível com Anthropic |
+| Gemini | `GEMINI_API_KEY` | Também habilita embeddings |
+| OpenRouter | `OPENROUTER_API_KEY` | Qualquer modelo |
+| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Apenas opt-in. Cria sessões de `@anthropic-ai/claude-agent-sdk` — costumava causar recursão sem limite no Stop-hook (seguimento do #149), por isso não é mais o padrão. |
+
+### Seleção de modelo com consciência de custo
+
+A compressão em background roda em toda observação, então a escolha de modelo muda o gasto mensal de forma significativa. Dados de workload capturados: 635 requisições / 888K tokens / 35 horas de uso ativo, executados contra três modelos OpenRouter a preços de 2026-05-23.
+
+| Tier | Modelo | Input / 1M | Output / 1M | Custo para as 35h capturadas | Notas |
+|------|-------|------------|-------------|---------------------------|-------|
+| Recomendado | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Qualidade sólida de compressão + sumarização a um custo ~10× menor que o Sonnet. |
+| Recomendado | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | Mais antigo mas ainda OK para workloads só de compressão. |
+| Recomendado | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Bom raciocínio de código se suas sessões forem muito orientadas a código. |
+| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | Alta qualidade, mas caro para trabalho de background sempre ativo. |
+| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Tier similar ao Sonnet. |
+| Evitar | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Modelo classe reasoning; gasto desproporcional para compressão. |
+
+agentmemory imprime um aviso em runtime quando `OPENROUTER_MODEL` casa com um padrão de tier premium. Defina `AGENTMEMORY_SUPPRESS_COST_WARNING=1` para silenciar depois que você tiver tomado uma decisão informada.
+
+Trade-off qualidade vs custo para trabalho de memória: compressão é uma tarefa de sumarização com critério de qualidade relativamente frouxo (quem relê o resumo é o agente, não o usuário). DeepSeek-V4-Pro / Qwen3-Coder ficam dentro do erro de arredondamento do Sonnet nessa tarefa, custando ~10× menos. Reserve os modelos tier premium para as queries que você lê diretamente.
+
+Fontes: [OpenRouter pricing for Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Memória multiagente (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+Em setups multiagente onde vários papéis compartilham um servidor agentmemory (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` etiqueta cada escrita com o papel que a fez. `AGENTMEMORY_AGENT_SCOPE` controla se o recall filtra por essa tag.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+Dois modos:
+
+| Modo | Etiqueta escritas | Filtra recall | Quando usar |
+|------|------------|---------------|-------------|
+| `shared` (padrão) | sim | não | Contexto cross-agent com trilha de auditoria. O architect pode ver o que o developer anotou, mas toda linha registra quem disse. |
+| `isolated` | sim | sim | Separação estrita. O architect nunca vê observações / memórias / sessões do developer. |
+
+O que é etiquetado quando `AGENT_ID` está definido: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. O papel flui `api::session::start` → `mem::observe` → `mem::compress` → KV.
+
+O que é filtrado no modo isolated: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Cada endpoint aceita `?agentId=` para sobrescrever por requisição, e `?agentId=*` para sair do escopo do env por completo. `/memories` também aceita `?includeOrphans=true` para mostrar memórias pré-AGENT_ID cujo `agentId` é undefined.
+
+Override por chamada na camada SDK / REST: todo endpoint mutador (`/session/start`, `/remember`) aceita um campo `agentId` no body da requisição que vence o env. Útil para runtimes que roteiam muitos papéis por um único processo de servidor.
+
+Quando `AGENT_ID` não está definido, a memória permanece sem escopo (comportamento legado, sem tags, sem filtros).
+
+### Portas
+
+agentmemory + iii-engine fazem bind em quatro portas por padrão. Se um restart falhar com `port in use`, esta tabela diz qual processo procurar.
+
+| Porta | Processo | Propósito | Override por env |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Worker de streams interno (consumido por agentmemory + viewer) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Viewer em tempo real (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — workers se registram aqui, telemetria OTel flui por cima | `III_ENGINE_URL` (URL completa, padrão `ws://localhost:49134`) |
+
+Limpeza de processo travado quando as portas ficam ocupadas após uma execução crashada:
+
+```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` recolhe tanto o worker quanto o pidfile do engine de forma limpa no shutdown graceful (#640, #474). A limpeza manual acima só serve para o caso pós-crash em que nenhum pidfile foi deixado para trás.
+
+### Arquivo de configuração
+
+Coloque a configuração de runtime do agentmemory em `~/.agentmemory/.env` em vez de exportar variáveis em cada shell. Se o viewer mostrar uma dica de setup como `export ANTHROPIC_API_KEY=...`, copie para este arquivo como `ANTHROPIC_API_KEY=...` sem o prefixo `export`, depois reinicie o agentmemory.
+
+Variáveis de ambiente do processo continuam funcionando e têm precedência sobre os valores no arquivo.
+
+No Windows, o mesmo arquivo fica em `%USERPROFILE%\.agentmemory\.env`:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+Para testar com uma assinatura Claude Code Pro/Max em vez de uma API key, faça opt-in explícito:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+Ligue features de graph ou consolidation no mesmo arquivo se quiser:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Variáveis de ambiente
+
+Crie `~/.agentmemory/.env`:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+124 endpoints na porta `3111`. A REST API faz bind em `127.0.0.1` por padrão. Endpoints protegidos exigem `Authorization: Bearer ` quando `AGENTMEMORY_SECRET` está definido, e endpoints de mesh sync exigem `AGENTMEMORY_SECRET` em ambos os peers.
+
+
+Endpoints principais
+
+| Method | Path | Descrição |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | Health check (sempre público) |
+| `POST` | `/agentmemory/session/start` | Inicia sessão + obtém contexto |
+| `POST` | `/agentmemory/session/end` | Encerra sessão |
+| `POST` | `/agentmemory/observe` | Captura observação |
+| `POST` | `/agentmemory/smart-search` | Busca híbrida |
+| `POST` | `/agentmemory/context` | Gera contexto |
+| `POST` | `/agentmemory/remember` | Salva na memória de longo prazo |
+| `POST` | `/agentmemory/forget` | Deleta observações |
+| `POST` | `/agentmemory/enrich` | Contexto de arquivo + memórias + bugs |
+| `GET` | `/agentmemory/profile` | Perfil de projeto |
+| `GET` | `/agentmemory/export` | Exporta todos os dados |
+| `POST` | `/agentmemory/import` | Importa de JSON |
+| `POST` | `/agentmemory/graph/query` | Query do grafo de conhecimento |
+| `POST` | `/agentmemory/team/share` | Compartilha com o time |
+| `GET` | `/agentmemory/audit` | Trilha de auditoria |
+
+Lista completa de endpoints: [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**Pré-requisitos:** Node.js >= 20, [iii-engine](https://iii.dev/docs) ou Docker
+
+
+
+ Ваш агент программирования помнит всё. Больше не нужно объяснять заново.
+ Built on iii engine
+
+ Постоянная память для Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode и любого MCP-клиента.
+
+ Этот gist расширяет шаблон LLM Wiki от Karpathy: confidence-оценкой, жизненным циклом, графами знаний и гибридным поиском — agentmemory является его реализацией.
+
+
+---
+
+## Install
+
+```bash
+npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the memory server on :3111
+agentmemory demo # seed sample sessions + prove recall
+agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)
+```
+
+Или через `npx` (без установки):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Внимание: npx кеширует пакеты по версиям. Если простой `npx @agentmemory/agentmemory` выдаёт более старый релиз, принудительно возьмите свежий через `npx -y @agentmemory/agentmemory@latest` или однократно очистите кеш: `rm -rf ~/.npm/_npx` (macOS/Linux; на Windows удалите `%LOCALAPPDATA%\npm-cache\_npx`). Начиная с v0.9.16+, при первом запуске npx предлагает поставить пакет глобально прямо в строке — после этого простая команда `agentmemory` будет работать повсюду.
+
+Полный список опций — в разделе [Быстрый старт](#quick-start) ниже. Привязка конкретного агента — в разделе [Работает с каждым агентом](#works-with-every-agent).
+
+---
+
+
+
+agentmemory работает с любым агентом, поддерживающим хуки, MCP или REST API. Все агенты используют один и тот же сервер памяти.
+
+
+ Работает с любым агентом, который говорит на MCP или HTTP. Один сервер — общая память для всех.
+
+
+---
+
+Вы заново объясняете архитектуру в каждой сессии. Вы заново находите те же баги. Вы заново обучаете агента тем же предпочтениям. Встроенная память (CLAUDE.md, .cursorrules) упирается в 200 строк и устаревает. agentmemory это решает. Он тихо собирает то, что делает ваш агент, сжимает это в индексируемую память и подмешивает нужный контекст при старте следующей сессии. Одна команда. Работает между агентами.
+
+**Что меняется:** В сессии 1 вы настраиваете JWT-аутентификацию. В сессии 2 просите добавить rate limiting. Агент уже знает, что аутентификация использует middleware jose в `src/middleware/auth.ts`, что ваши тесты покрывают валидацию токенов, и что вы выбрали jose, а не jsonwebtoken, из-за совместимости с Edge. Никаких повторных объяснений. Никакого копирования-вставки. Агент просто *знает*.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **Новое в v0.9.0** — Лендинг по адресу [agent-memory.dev](https://agent-memory.dev), коннектор файловой системы (`@agentmemory/fs-watcher`), автономный MCP теперь проксирует к работающему серверу, поэтому хуки и просмотрщик согласованы, политика аудита кодифицирована для каждого пути удаления, проверка состояния больше не помечает `memory_critical` на маленьких Node-процессах. Полные заметки в [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18).
+
+---
+
+
+
+
+
+
+
+### Точность извлечения
+
+**coding-agent-life-v1** (внутренний корпус, воспроизводимо в sandbox)
+
+| Адаптер | P@5 | R@5 | Top-5 hit rate | p50-задержка |
+|---|---|---|---|---|
+| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 мс |
+| Базовый grep | 0.267 | 0.967 | 15 / 15 | 0 мс |
+
+100 % попаданий в top-5. **2,2×** выше точность, чем у grep-базы, на тех же входах. Полная разбивка по типам: [`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 вопросов)
+
+| Система | R@5 | R@10 | MRR |
+|---|---|---|---|
+| **agentmemory** | **95.2%** | **98.6%** | **88.2%** |
+| Fallback только BM25 | 86.2% | 94.6% | 71.5% |
+
+
+
+
+### Экономия токенов
+
+| Подход | Токенов в год | Стоимость в год |
+|---|---|---|
+| Вставлять весь контекст | 19,5М+ | Невозможно (выходит за окно) |
+| LLM-резюме | ~650K | ~500 $ |
+| **agentmemory** | **~170K** | **~10 $** |
+| agentmemory + локальные эмбеддинги | ~170K | **0 $** |
+
+
+
+
+
+> Модель эмбеддингов: `all-MiniLM-L6-v2` (локальная, бесплатная, без API-ключа). Полные отчёты: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Сравнение с конкурентами: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory против mem0, Letta, Khoj, claude-mem, Hippo.
+
+**Воспроизведите локально:** [`eval/README.md`](../eval/README.md) — harness с подключаемыми адаптерами для LongMemEval `_s` (публичный, 500 вопросов) и `coding-agent-life-v1` (внутренний корпус из 15 сессий). Адаптеры grep / vector / agentmemory сравниваются бок о бок, вывод NDJSON, опубликованные scorecard'ы попадают в [`docs/benchmarks/`](../docs/benchmarks/).
+
+**Хорошо сочетается с [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) и [Graphify](https://github.com/safishamsi/graphify).** Индексация кодового графа, мультиагентные конвейеры сборки и более широкие графы знаний по докам / PDF / изображениям / видео. agentmemory запоминает работу; эти три проекта подсвечивают остальное в слое контекста. Рецепты и таблица маршрутизации вопросов: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+Совместимость: этот релиз нацелен на стабильный `iii-sdk` `^0.11.0` и iii-engine v0.11.x.
+
+### Попробуйте за 30 секунд
+
+```bash
+# Terminal 1: start the server
+npx @agentmemory/agentmemory
+
+# Terminal 2: seed sample data and see recall in action
+npx @agentmemory/agentmemory demo
+```
+
+`demo` заполняет 3 реалистичные сессии (JWT-аутентификация, исправление N+1-запроса, rate limiting) и запускает по ним семантический поиск. Вы увидите, как находится «N+1 query fix», когда вы ищете «database performance optimization» — keyword-сопоставление так не умеет.
+
+Откройте `http://localhost:3113`, чтобы видеть построение памяти в реальном времени.
+
+### Рекомендуется: глобальная установка
+
+`npx` кеширует пакеты по версиям. Если на прошлой неделе вы запускали `npx @agentmemory/agentmemory@0.9.14`, простой `npx @agentmemory/agentmemory` может выдать застаревшую 0.9.14 из `~/.npm/_npx/`, а не последний релиз. Установите один раз — и команда `agentmemory` будет работать везде:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# If you hit EACCES on macOS/Linux system Node installs, retry with:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # start the server (same as the npx form)
+agentmemory stop # tear it down
+agentmemory remove # uninstall everything we created
+agentmemory connect claude-code # wire one agent
+agentmemory doctor # interactive diagnostics + fix prompts
+```
+
+Начиная с v0.9.16, первый запуск npx предлагает установку глобально в той же строке — ответьте `Y` один раз, и готово. Если вы пропустили шаг, воспользуйтесь любым из этих вариантов для свежего скачивания:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell)
+```
+
+В Windows / PowerShell эквивалент очистки кеша — `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"`, а вариант выше `npx -y ...@latest` остаётся кросс-платформенным.
+
+### Воспроизведение сессий
+
+Каждую сессию, которую записывает agentmemory, можно воспроизвести. Откройте просмотрщик, выберите вкладку **Replay** и пролистывайте таймлайн: промпты, вызовы инструментов, результаты вызовов и ответы отображаются как отдельные события с play/pause, регулировкой скорости (0,5×–4×) и горячими клавишами (пробел переключает, стрелки — пошаговое перемещение).
+
+Уже есть старые JSONL-расшифровки Claude Code, которые хотите подгрузить?
+
+```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
+```
+
+Импортированные сессии появятся в Replay-пикере рядом с нативными. Под капотом каждая запись проходит через iii-функции `mem::replay::load`, `mem::replay::sessions` и `mem::replay::import-jsonl` — никаких побочных серверов.
+
+### Обновление / Обслуживание
+
+Используйте команду обслуживания, когда специально хотите обновить локальный runtime:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Внимание: команда меняет текущее рабочее окружение / runtime. Она может обновлять JavaScript-зависимости, может запустить `cargo install iii-engine --force`, может стянуть Docker-образы.
+
+Детали реализации — в `src/cli.ts` (см. `runUpgrade` в районе `src/cli.ts:544-595`).
+
+### Claude Code (один блок, вставьте его)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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 без установки плагина (путь MCP-standalone)
+
+Если подключать MCP-сервер agentmemory через `~/.claude.json` напрямую, минуя `/plugin install`, Claude Code никогда не разрешит `${CLAUDE_PLUGIN_ROOT}`, и в `~/.claude/settings.json` придётся прописывать абсолютные пути к скриптам хуков. Эти пути обычно включают версию agentmemory (например, `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), так что следующее обновление тихо ломает каждый хук ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Обходное решение:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Это вливает те же команды хуков в `~/.claude/settings.json` с абсолютными путями, разрешёнными в каталог `plugin/` текущего установленного пакета `@agentmemory/agentmemory`. После обновления agentmemory запустите команду ещё раз, чтобы освежить пути. Записи пользователя в этом файле сохраняются; заменяются только предыдущие записи agentmemory. Рекомендуемым способом остаётся путь через `/plugin install`.
+Для удалённых или защищённых развертываний запускайте Claude Code с заданными `AGENTMEMORY_URL` и `AGENTMEMORY_SECRET`. Плагин пробрасывает обе переменные во встроенный MCP-сервер; если `AGENTMEMORY_URL` пуст, MCP-shim использует `http://localhost:3111`.
+
+### Codex CLI (платформа плагинов Codex)
+
+```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
+```
+
+Плагин Codex поставляется из того же каталога `plugin/`, что и плагин Claude Code. Он регистрирует:
+
+- `@agentmemory/mcp` как MCP-сервер (проксирует все 51 инструмент, когда `AGENTMEMORY_URL` указывает на работающий сервер agentmemory; локально откатывается к 7 инструментам, если сервер недоступен)
+- 6 хуков жизненного цикла: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skill'а: `/recall`, `/remember`, `/session-history`, `/forget`
+
+Хук-движок Codex подставляет `CLAUDE_PLUGIN_ROOT` в подпроцессы хуков (см. [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), поэтому одни и те же скрипты хуков работают на обоих хостах без дублирования. События Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure доступны только в Claude Code и для Codex не регистрируются.
+
+#### Codex Desktop: хуки плагинов сейчас тихие (есть обходное решение)
+
+`CodexHooks` и `PluginHooks` оба стабильны и включены по умолчанию в [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), но текущие сборки Codex Desktop не диспатчат локальный `hooks.json` плагина ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). Инструменты MCP по-прежнему работают; не хватает только наблюдений жизненного цикла.
+
+Пока upstream не подвезёт фикс, продублируйте те же команды хуков в глобальный `~/.codex/hooks.json`:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Это добавляет идемпотентный блок в `~/.codex/hooks.json` со ссылками на абсолютные пути к встроенным скриптам (раскрывать `${CLAUDE_PLUGIN_ROOT}` на уровне пользователя не нужно). После обновления agentmemory запустите ту же команду ещё раз, чтобы освежить пути. Записи пользователя в этом файле сохраняются; заменяются только предыдущие записи agentmemory.
+
+
+OpenClaw (вставьте этот промпт)
+
+```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 51 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`.
+```
+
+Полное руководство: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (вставьте этот промпт)
+
+```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 51 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.
+```
+
+Полное руководство: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Другие агенты
+
+Запустите сервер памяти: `npx @agentmemory/agentmemory`
+
+Запись agentmemory — это **один и тот же блок MCP-сервера** для всех хостов, использующих формат `mcpServers` (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw):
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Вставьте эту запись в существующий объект `mcpServers`** в файле конфигурации хоста — не заменяйте сам файл. Если там уже есть другие серверы, добавьте `agentmemory` рядом с ними как новый ключ внутри `mcpServers`. Если `mcpServers` отсутствует совсем, вставьте блок внутрь `{ "mcpServers": { ... } }`. Подстановки `${VAR}` наследуют `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` из shell в момент запуска MCP-сервера — незаданные переменные передаются пустыми, и shim откатывается на `http://localhost:3111`. Одна подключённая запись покрывает как локальные, так и удалённые (k8s / reverse-proxied) развертывания.
+
+| Агент | Файл конфигурации | Заметки |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | Добавить в `mcpServers`. Также доступен deeplink в один клик на сайте. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Добавить в `mcpServers`. После правки перезапустить Claude Desktop. |
+| **Cline / Roo Code / Kilo Code** | Настройки MCP в Cline (Settings UI → MCP Servers → Edit) | Тот же блок `mcpServers`. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Тот же блок `mcpServers`. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (автоматическое слияние). |
+| **OpenClaw** | MCP-конфиг OpenClaw | Тот же блок `mcpServers`, либо более глубокий [memory-плагин](../integrations/openclaw/). |
+| **Codex CLI (только MCP)** | `.codex/config.toml` | Формат TOML: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, либо добавьте `[mcp_servers.agentmemory]` вручную. |
+| **Codex CLI (полный плагин)** | Маркетплейс плагинов Codex | `codex plugin marketplace add rohitg00/agentmemory`, затем `codex plugin add agentmemory@agentmemory`. Регистрирует MCP + 6 хуков жизненного цикла (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skill'а. На Codex Desktop дополнительно запустите `agentmemory connect codex --with-hooks`, пока не зарелизят [openai/codex#16430](https://github.com/openai/codex/issues/16430) — хуки плагина там пока тихие. |
+| **OpenCode (только MCP)** | `opencode.json` | Другая форма — корневой ключ `mcp`, команда задаётся массивом: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (полный плагин)** | `plugin/opencode/` | 22 хука авто-захвата по жизненному циклу сессии, сообщениям, инструментам и ошибкам. Две slash-команды (`/recall`, `/remember`). Скопируйте `plugin/opencode/` в свой рабочий каталог OpenCode и добавьте запись плагина в `opencode.json`. Полная таблица хуков и анализ пробелов — в [`plugin/opencode/README.md`](../plugin/opencode/README.md). |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | Скопируйте [`integrations/pi`](../integrations/pi/) и перезапустите pi. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Используйте более глубокий [плагин провайдера памяти](../integrations/hermes/) с `memory.provider: agentmemory`. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` записывает стандартный блок `mcpServers`. Payload хуков по полям совместим с Claude Code, поэтому существующие 12 скриптов хуков работают без изменений — подключите их через секцию `hooks` в том же `settings.json`. |
+| **Antigravity** (заменяет Gemini CLI) | `mcp_config.json` (в каталоге User у Antigravity) | `agentmemory connect antigravity` записывает стандартный блок `mcpServers`. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Использовать после отключения Gemini CLI 2026-06-18. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` записывает конфиг на уровне пользователя. Workspace-переопределения — в `.kiro/settings/mcp.json` рядом с кодом. |
+| **Goose** | UI настроек MCP в Goose | Тот же блок `mcpServers`. |
+| **Aider** | н/д | Разговаривайте напрямую с REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Любой агент (32+)** | н/д | `npx skillkit install agentmemory` сам определит хост и сольёт настройки. |
+
+**MCP-клиенты в sandbox** (Flatpak / Snap / ограничивающие контейнеры), которые не могут добраться до `localhost` хоста: дополнительно установите `"AGENTMEMORY_FORCE_PROXY": "1"` в блоке `env` и укажите `AGENTMEMORY_URL` на маршрут, до которого sandbox действительно может дотянуться (например, IP в локальной сети). См. [#234](https://github.com/rohitg00/agentmemory/issues/234) для пошаговой диагностики.
+
+### Программный доступ (Python / Rust / Node)
+
+agentmemory регистрирует свои основные операции как iii-функции (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Любой язык с SDK для iii может вызывать их напрямую через `ws://localhost:49134` — отдельный REST-клиент на каждый язык не требуется.
+
+```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"},
+})
+```
+
+Рабочий пример: [`examples/python/`](../examples/python/) (быстрый старт + поток наблюдения/извлечения). REST на `:3111` остаётся доступным для хостов без iii-runtime.
+
+### Из исходников
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Это поднимает agentmemory с локальным `iii-engine`, если `iii` уже установлен, либо откатывается к Docker Compose, если есть Docker. REST, стримы и просмотрщик по умолчанию слушают на `127.0.0.1`.
+
+Установите `iii-engine` вручную. **agentmemory сейчас зафиксирован на `iii-engine` `v0.11.2`** — `v0.11.6` вводит новую модель «всё через `iii worker add` в sandbox», под которую agentmemory ещё не отрефакторен. Закрепление снимется, как только рефакторинг будет завершён. Переопределите через `AGENTMEMORY_III_VERSION=`, если вы вручную перешли на sandbox-модель.
+
+- **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:** замените `aarch64-apple-darwin` на `x86_64-apple-darwin`
+- **Linux x64:** замените на `x86_64-unknown-linux-gnu`
+- **Linux arm64:** замените на `aarch64-unknown-linux-gnu`
+- **Windows:** скачайте `iii-x86_64-pc-windows-msvc.zip` из [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), распакуйте `iii.exe`, добавьте в PATH
+
+Либо используйте Docker (входящий в комплект `docker-compose.yml` тянет `iiidev/iii:0.11.2`). Полная документация: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory работает на Windows 10/11, но одного Node.js-пакета мало — также нужен runtime `iii-engine` (отдельный нативный бинарь) как фоновый процесс. Официальный upstream-установщик — это `sh`-скрипт, на сегодня нет ни PowerShell-установщика, ни пакета scoop/winget, поэтому у пользователей Windows два пути:
+
+**Вариант A — Готовый Windows-бинарь (рекомендуется):**
+
+```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
+```
+
+**Вариант 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
+```
+
+**Вариант C — только standalone MCP (без движка):** если вам нужны только MCP-инструменты для агента и не нужны REST API, просмотрщик или cron-задачи, пропустите движок целиком:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# or via the shim package:
+npx -y @agentmemory/mcp
+```
+
+**Диагностика на Windows:** если `npx @agentmemory/agentmemory` падает, перезапустите с `--verbose`, чтобы увидеть реальный stderr движка. Частые сценарии сбоя:
+
+| Симптом | Что делать |
+|---|---|
+| `iii-engine process started`, затем `did not become ready within 15s` | Движок упал при старте — перезапустите с `--verbose`, проверьте stderr |
+| `Could not start iii-engine` | Не установлены ни `iii.exe`, ни Docker. См. варианты A или B выше |
+| Конфликт порта | `netstat -ano \| findstr :3111`, чтобы понять, что занимает порт, затем убить процесс или использовать `--port ` |
+| Откат на Docker пропускается, хотя Docker установлен | Убедитесь, что Docker Desktop действительно запущен (иконка в трее) |
+
+> Примечание: команды `cargo install iii-engine` нет — `iii` не публикуется на crates.io. Поддерживаются только три способа установки: готовый бинарь выше, upstream-`sh`-скрипт (только macOS/Linux) и Docker-образ.
+
+---
+
+
Развёртывание
+
+Шаблоны в один клик для managed-хостов. Каждый поставляет автономный
+Dockerfile, который тянет `@agentmemory/agentmemory` из npm и копирует
+бинарь iii engine из официального образа `iiidev/iii` на Docker
+Hub — собственный преcобранный образ agentmemory не нужен. Постоянное
+хранилище монтируется в `/data`; entrypoint при первом запуске
+перезаписывает поставляемый npm'ом iii-конфиг (который слушает на
+`127.0.0.1`) на deploy-вариант, слушающий на `0.0.0.0` и
+использующий абсолютные пути `/data`, генерирует HMAC-секрет,
+а затем понижает привилегии с `root` до `node` через `gosu`
+перед запуском CLI agentmemory.
+
+
+
+
+
+
+Кнопке Render «деплой в один клик» нужен `render.yaml` в корне репозитория, который мы намеренно держим чистым. Используйте схему через Render Blueprint, описанную в [`deploy/render/`](./deploy/render/README.md), чтобы вручную указать на in-repo blueprint.
+
+Полные детали настройки (захват HMAC, SSH-туннель к просмотрщику, ротация, бэкап, нижние пороги стоимости) — в [`deploy/`](./deploy/README.md):
+
+- [`deploy/fly`](./deploy/fly/README.md) — одна машина с
+ `auto_stop_machines = "stop"`; дешевле всего в простое.
+- [`deploy/railway`](./deploy/railway/README.md) — фиксированный тариф Hobby,
+ том в панели.
+- [`deploy/render`](./deploy/render/README.md) — поток Blueprint,
+ автоматические снапшоты диска на платных тарифах.
+- [`deploy/coolify`](./deploy/coolify/README.md) — self-hosted на собственном
+ VPS через [Coolify](https://coolify.io/self-hosted); тот же Docker
+ Compose-стек, хост и данные у вас.
+
+Публикуется только порт `3111`. Просмотрщик на `3113` остаётся
+привязанным к loopback внутри контейнера — в README каждого шаблона
+описан паттерн SSH-туннеля, чтобы до него достучаться.
+
+---
+
+
+
+Каждый агент программирования забывает всё, когда сессия заканчивается. Вы тратите первые 5 минут каждой сессии на повторное объяснение своего стека. agentmemory работает в фоне и устраняет это полностью.
+
+```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 встроенная память агента
+
+Каждый ИИ-агент программирования поставляется со встроенной памятью — у Claude Code есть `MEMORY.md`, у Cursor — notepad'ы, у Cline — memory bank. Это работает как стикеры. agentmemory — индексируемая база данных за этими стикерами.
+
+| | Встроенная (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Масштаб | Потолок в 200 строк | Без ограничений |
+| Поиск | Загружает всё в контекст | BM25 + векторный + граф (только top-K) |
+| Цена в токенах | 22K+ при 240 наблюдениях | ~1 900 токенов (на 92 % меньше) |
+| Между агентами | Файлы на каждого агента | MCP + REST (любой агент) |
+| Координация | Нет | Lease'ы, сигналы, action'ы, routine'ы |
+| Наблюдаемость | Читать файлы вручную | Просмотрщик в реальном времени на :3113 |
+
+---
+
+
+
+### Конвейер памяти
+
+```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-уровневая консолидация памяти
+
+Вдохновлено тем, как мозг человека обрабатывает воспоминания — похоже на консолидацию во время сна.
+
+| Уровень | Что | Аналогия |
+|------|------|---------|
+| **Working** | Сырые наблюдения от использования инструментов | Кратковременная память |
+| **Episodic** | Сжатые краткие итоги сессий | «Что произошло» |
+| **Semantic** | Извлечённые факты и закономерности | «Что я знаю» |
+| **Procedural** | Workflow'ы и паттерны принятия решений | «Как это сделать» |
+
+Воспоминания затухают со временем (кривая Эббингауза). Часто используемые воспоминания усиливаются. Устаревшие — автоматически вытесняются. Противоречия обнаруживаются и разрешаются.
+
+### Что захватывается
+
+| Хук | Захватывает |
+|------|----------|
+| `SessionStart` | Путь к проекту, идентификатор сессии |
+| `UserPromptSubmit` | Пользовательские промпты (с приватным фильтром) |
+| `PreToolUse` | Паттерны доступа к файлам + обогащённый контекст |
+| `PostToolUse` | Имя инструмента, вход, выход |
+| `PostToolUseFailure` | Контекст ошибки |
+| `PreCompact` | Заново подмешивает память перед компакцией |
+| `SubagentStart/Stop` | Жизненный цикл подагентов |
+| `Stop` | Итог в конце сессии |
+| `SessionEnd` | Маркер завершения сессии |
+
+### Ключевые возможности
+
+| Возможность | Описание |
+|---|---|
+| **Автоматический захват** | Каждое использование инструмента записывается через хуки — никаких ручных усилий |
+| **Семантический поиск** | BM25 + векторный + граф знаний со слиянием RRF |
+| **Эволюция памяти** | Версионирование, supersession, графы связей |
+| **Авто-забывание** | Истечение TTL, обнаружение противоречий, вытеснение по важности |
+| **Privacy first** | API-ключи, секреты, теги `` вырезаются до сохранения |
+| **Самовосстановление** | Circuit breaker, цепочка fallback-провайдеров, мониторинг состояния |
+| **Claude bridge** | Двусторонняя синхронизация с MEMORY.md |
+| **Граф знаний** | Извлечение сущностей + обход BFS |
+| **Командная память** | Отдельные namespace'ы для общего и приватного у участников команды |
+| **Происхождение цитат** | Любую запись памяти можно проследить до исходных наблюдений |
+| **Git-снапшоты** | Версионирование, откат и diff состояния памяти |
+
+---
+
+
+
+Тройной поток извлечения, объединяющий три сигнала:
+
+| Поток | Что делает | Когда |
+|---|---|---|
+| **BM25** | Сопоставление по стеммированным ключевым словам с расширением синонимами | Всегда включён |
+| **Vector** | Косинусное сходство по плотным эмбеддингам | Если настроен embedding-провайдер |
+| **Graph** | Обход графа знаний по сопоставлению сущностей | Если в запросе обнаружены сущности |
+
+Сливаются через Reciprocal Rank Fusion (RRF, k=60) и диверсифицируются по сессиям (не более 3 результатов на сессию).
+
+BM25 «из коробки» токенизирует греческий, кириллицу, иврит, арабский и латиницу с диакритикой. Для записей на китайском / японском / корейском поставьте опциональные сегментаторы (`npm install @node-rs/jieba tiny-segmenter`), чтобы CJK-последовательности разбивались на токены уровня слова; без них agentmemory мягко откатывается к токенизации целых последовательностей и выводит одноразовую подсказку в stderr.
+
+### Провайдеры эмбеддингов
+
+agentmemory автоматически определяет вашего провайдера. Для лучших результатов поставьте локальные эмбеддинги (бесплатно):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Провайдер | Модель | Стоимость | Заметки |
+|---|---|---|---|
+| **Локально (рекомендуется)** | `all-MiniLM-L6-v2` | Бесплатно | Офлайн, +8 пп recall по сравнению только с BM25 |
+| Gemini | `gemini-embedding-001` | Бесплатный тариф | 100+ языков, размерности 768/1536/3072 (MRL), вход 2048 токенов. Заменяет `text-embedding-004` ([устарел, отключение 14 янв. 2026](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | 0,02 $/1M | Высочайшее качество |
+| Voyage AI | `voyage-code-3` | Платно | Оптимизирован под код |
+| Cohere | `embed-english-v3.0` | Бесплатная пробная версия | Общего назначения |
+| OpenRouter | Любая модель | Зависит | Мульти-модельный прокси |
+
+---
+
+
+
+53 инструмента, 6 ресурсов, 3 промпта и 4 skill'а — самый исчерпывающий MCP-набор для памяти любого агента.
+
+> **MCP-shim против полного сервера:** опубликованный пакет `@agentmemory/mcp` — это тонкий shim. Он раскрывает полную поверхность из 51 инструмента **только если может достучаться до работающего сервера agentmemory** через `AGENTMEMORY_URL` (режим прокси). Если сервер недоступен, shim откатывается к локальному набору из 7 инструментов (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). Переменная окружения `AGENTMEMORY_TOOLS=core|all` — *серверный* флаг; задавать её в блоке `env` shim'а бесполезно. Если в Cursor / OpenCode / Gemini CLI видно только 7 инструментов, запустите `npx @agentmemory/agentmemory` (или Docker-стек) и установите `AGENTMEMORY_URL=http://localhost:3111`.
+
+### 51 инструмент
+
+
+Базовые инструменты (всегда доступны)
+
+| Инструмент | Описание |
+|------|-------------|
+| `memory_recall` | Искать в прошлых наблюдениях |
+| `memory_compress_file` | Сжимать markdown-файлы с сохранением структуры |
+| `memory_save` | Сохранить инсайт, решение или паттерн |
+| `memory_patterns` | Выявить повторяющиеся паттерны |
+| `memory_smart_search` | Гибридный семантический + keyword-поиск |
+| `memory_file_history` | Прошлые наблюдения о конкретных файлах |
+| `memory_sessions` | Список последних сессий |
+| `memory_timeline` | Хронологические наблюдения |
+| `memory_profile` | Профиль проекта (концепции, файлы, паттерны) |
+| `memory_export` | Экспортировать все данные памяти |
+| `memory_relations` | Запрос к графу связей |
+
+
+
+
+Расширенные инструменты (всего 51 — задайте AGENTMEMORY_TOOLS=all)
+
+| Инструмент | Описание |
+|------|-------------|
+| `memory_patterns` | Выявить повторяющиеся паттерны |
+| `memory_timeline` | Хронологические наблюдения |
+| `memory_relations` | Запрос к графу связей |
+| `memory_graph_query` | Обход графа знаний |
+| `memory_consolidate` | Запустить 4-уровневую консолидацию |
+| `memory_claude_bridge_sync` | Синхронизация с MEMORY.md |
+| `memory_team_share` | Поделиться с участниками команды |
+| `memory_team_feed` | Недавно расшаренные элементы |
+| `memory_audit` | Аудит-журнал операций |
+| `memory_governance_delete` | Удалить с записью в аудит-журнал |
+| `memory_snapshot_create` | Снапшот, версионированный в git |
+| `memory_action_create` | Создать задачи с зависимостями |
+| `memory_action_update` | Обновить статус action |
+| `memory_frontier` | Разблокированные action'ы, отсортированные по приоритету |
+| `memory_next` | Самый важный следующий action |
+| `memory_lease` | Эксклюзивные lease'ы для action'ов (мультиагентность) |
+| `memory_routine_run` | Инстанцировать workflow-routine'ы |
+| `memory_signal_send` | Межагентный обмен сообщениями |
+| `memory_signal_read` | Чтение сообщений с подтверждениями |
+| `memory_checkpoint` | Внешние условные шлюзы |
+| `memory_mesh_sync` | P2P-синхронизация между инстансами |
+| `memory_sentinel_create` | События-наблюдатели |
+| `memory_sentinel_trigger` | Запустить sentinel'ы извне |
+| `memory_sketch_create` | Эфемерные графы action'ов |
+| `memory_sketch_promote` | Перевести в постоянное состояние |
+| `memory_crystallize` | Сжать цепочки action'ов |
+| `memory_diagnose` | Проверки состояния |
+| `memory_heal` | Авто-исправление зависшего состояния |
+| `memory_facet_tag` | Теги вида измерение:значение |
+| `memory_facet_query` | Запрос по фасет-тегам |
+| `memory_verify` | Трассировка происхождения |
+
+
+
+### 6 ресурсов · 3 промпта · 4 skill'а
+
+| Тип | Имя | Описание |
+|------|------|-------------|
+| Ресурс | `agentmemory://status` | Состояние, число сессий, число записей памяти |
+| Ресурс | `agentmemory://project/{name}/profile` | Интеллект на уровне проекта |
+| Ресурс | `agentmemory://memories/latest` | 10 последних активных записей памяти |
+| Ресурс | `agentmemory://graph/stats` | Статистика графа знаний |
+| Промпт | `recall_context` | Поиск + возврат контекстных сообщений |
+| Промпт | `session_handoff` | Передача данных между агентами |
+| Промпт | `detect_patterns` | Анализ повторяющихся паттернов |
+| Skill | `/recall` | Поиск по памяти |
+| Skill | `/remember` | Сохранение в долговременную память |
+| Skill | `/session-history` | Краткие итоги последних сессий |
+| Skill | `/forget` | Удаление наблюдений / сессий |
+
+### Standalone MCP
+
+Запуск без полного сервера — для любого MCP-клиента. Подойдёт любое:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # canonical (always available)
+npx -y @agentmemory/mcp # shim package alias
+```
+
+Или добавьте в MCP-конфиг своего агента:
+
+Большинство агентов (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+Вставьте запись `agentmemory` в существующий объект `mcpServers` хоста, а не заменяйте файл. Для sandbox-клиентов, которые не могут добраться до `localhost` хоста, добавьте `"AGENTMEMORY_FORCE_PROXY": "1"` в блок env и укажите `AGENTMEMORY_URL` на маршрут, доступный из sandbox.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Скопируйте файл плагина из репозитория:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+Автоматически запускается на порту `3113`. Живой поток наблюдений, обозреватель сессий, браузер по памяти, визуализация графа знаний и панель состояния.
+
+```bash
+open http://localhost:3113
+```
+
+Сервер просмотрщика по умолчанию слушает на `127.0.0.1`. Эндпоинт `/agentmemory/viewer`, отдаваемый REST'ом, подчиняется обычным правилам bearer-токена `AGENTMEMORY_SECRET`. Заголовки CSP используют nonce скрипта на ответ и отключают inline-атрибуты-обработчики (`script-src-attr 'none'`).
+
+---
+
+
+
+Просмотрщик на `:3113` показывает, что ваш агент **запомнил**. [iii console](https://iii.dev/docs/console) показывает, что ваш агент **сделал** — каждая операция памяти как трейс OpenTelemetry, каждая запись KV редактируема, каждая функция вызываема, каждый стрим тэппится. Два окна на одну и ту же память: одно повёрнуто к продукту, другое к движку.
+
+Наблюдайте, как срабатывает `memory_smart_search`, и видите BM25-скан → поиск эмбеддингов → RRF-слияние → reranker в виде waterfall. Отредактируйте зависший таймер консолидации в браузере KV. Воспроизведите хук `PostToolUse` с изменённым payload. Пин WebSocket-стрима — и смотрите, как наблюдения прилетают в реальном времени.
+
+agentmemory отдаёт это бесплатно, потому что каждая функция, триггер, scope состояния и стрим — это примитив iii: ничего самописного, нечего инструментировать.
+
+
+
+
+ Страница Workers: каждый подключённый воркер — включая сам agentmemory — с PID, количеством функций, runtime и временем последнего появления.
+
+
+**Уже установлено.** Console поставляется вместе с `iii` — отдельный установщик не нужен.
+
+**Запускать рядом с 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
+```
+
+Затем откройте `http://localhost:3114`. Добавьте `--enable-flow` для экспериментальной страницы графа архитектуры.
+
+Переопределяйте эндпоинты движка только если вы их перенесли:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Что можно делать из console:**
+
+| Страница | Зачем |
+|------|-----------|
+| **Workers** | Видеть каждый подключённый воркер и его живые метрики — включая сам воркер agentmemory. |
+| **Functions** | Напрямую вызывать любую функцию agentmemory с JSON-payload — удобно для тестов `memory.recall`, `memory.consolidate`, `graph.query` без подключения клиента. |
+| **Triggers** | Воспроизводить HTTP-, cron-, event- и state-триггеры — запустить cron консолидации вручную, повторить HTTP-маршрут, эмитировать изменение состояния. |
+| **States** | KV-браузер с полным CRUD — сессии, слоты памяти, lifecycle-таймеры, индекс эмбеддингов — редактирование значений на месте. |
+| **Streams** | Живой WebSocket-монитор для записей памяти, событий хуков и обновлений наблюдений по мере их прохождения через iii-стримы. |
+| **Queues** | Долговечные топики очередей + управление dead-letter. Повтор или сброс упавших job'ов эмбеддинга / компрессии. |
+| **Traces** | Виды waterfall / flame / разбивка по сервисам в OpenTelemetry. Фильтр по `trace_id` показывает, какие функции, обращения к БД и embedding-запросы породил отдельный `memory.search`. |
+| **Logs** | Структурированные OTEL-логи, фильтруемые и коррелируемые с trace-/span-ID. |
+| **Config** | Конфигурация runtime — какие именно воркеры, провайдеры и порты использует ваш движок. |
+| **Flow** | (Опционально, `--enable-flow`) Интерактивный граф архитектуры из всех воркеров, триггеров и стримов. |
+
+
+
+
+ Traces: waterfall / flame / разбивка по сервисам для каждой операции памяти.
+
+
+**Traces уже включены:**
+
+`iii-config.yaml` поставляется с включённым воркером `iii-observability` (`exporter: memory`, `sampling_ratio: 1.0`, метрики + логи). Дополнительная настройка не нужна — как только agentmemory запускается, каждая операция памяти эмитит trace-span и структурированный лог, который консоль читает.
+
+Если хотите экспортировать в Jaeger/Honeycomb/Grafana Tempo, измените `exporter: memory` на `exporter: otlp` и укажите эндпоинт коллектора согласно документации по observability в iii.
+
+> **Внимание:** на самой console аутентификация не применяется — держите её привязанной к `127.0.0.1` (по умолчанию) и никогда не выставляйте наружу.
+
+---
+
+
+
+agentmemory — это **уже работающий инстанс [iii](https://iii.dev)**. Функции, триггеры, KV-состояние, стримы, OTEL-трейсы — всё это примитивы iii. Вы не ставили Postgres, Redis, Express, pm2 или Prometheus, потому что iii их заменяет.
+
+Это значит, что одна дополнительная команда расширяет agentmemory целой новой возможностью.
+
+### Расширить agentmemory одной командой
+
+```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
+```
+
+Каждый `iii worker add` регистрирует новые функции и триггеры в том же движке, где уже работает agentmemory. Просмотрщик и console подхватывают их мгновенно — без перезагрузки, новой интеграции или нового контейнера.
+
+| `iii worker add` | Что получаете сверху к agentmemory |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Память на множестве инстансов: каждое `remember` разлетается, каждое `search` читает объединение |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Жизненный цикл по расписанию — ночная консолидация, еженедельные снапшоты, decay по фиксированному таймеру |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Надёжные повторы: упавшие job'ы эмбеддинга и компрессии переживают перезапуск, наблюдения не теряются |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL-трейсы, метрики, логи на каждой функции — подключены в `iii-config.yaml` с первого дня |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Код, пришедший из `memory_recall`, исполняется внутри одноразовой VM, а не в вашем shell |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-адаптер состояния, когда дефолтная in-memory KV уже мала |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | Поднять дополнительные MCP-серверы рядом с MCP'ом agentmemory, на одном и том же движке |
+
+Полный реестр: [workers.iii.dev](https://workers.iii.dev). Каждый воркер там собирается из тех же примитивов, что и agentmemory — и тот agentmemory, который у вас уже есть, — один из них.
+
+### Что заменяет iii
+
+| Традиционный стек | agentmemory использует |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + векторный индекс в памяти |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | Супервизия воркеров движка iii |
+| Prometheus / Grafana | iii OTEL + монитор состояния |
+| Самописные плагинные системы | `iii worker add ` |
+
+**118 исходных файлов · ~21 800 LOC · 950+ тестов · 123 функции · 34 KV-scope'а** — всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii.
+
+---
+
+
+
+### LLM-провайдеры
+
+agentmemory автоопределяет провайдера по окружению. По умолчанию никакие вызовы LLM не выполняются, пока вы не настроите провайдера или явно не включите fallback на подписку Claude.
+
+| Провайдер | Конфигурация | Заметки |
+|----------|--------|-------|
+| **No-op (по умолчанию)** | Настройка не нужна | LLM-сжатие/резюме ВЫКЛЮЧЕНО. Синтетическое BM25-сжатие и recall продолжают работать. Если вы раньше полагались на fallback подписки Claude — см. `AGENTMEMORY_ALLOW_AGENT_SDK` ниже. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Поминутная (token-based) оплата |
+| MiniMax | `MINIMAX_API_KEY` | Совместим с Anthropic |
+| Gemini | `GEMINI_API_KEY` | Дополнительно включает эмбеддинги |
+| OpenRouter | `OPENROUTER_API_KEY` | Любая модель |
+| Fallback на подписку Claude | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Только по согласию. Запускает сессии `@anthropic-ai/claude-agent-sdk` — раньше приводил к неограниченной рекурсии Stop-хука (продолжение #149), потому больше не по умолчанию. |
+
+### Выбор модели с учётом стоимости
+
+Фоновое сжатие выполняется на каждом наблюдении, поэтому выбор модели заметно влияет на ежемесячные расходы. Замеренные данные нагрузки: 635 запросов / 888K токенов / 35 часов активного использования, прогон против трёх моделей OpenRouter по ценам на 2026-05-23.
+
+| Уровень | Модель | Вход / 1M | Выход / 1M | Стоимость за зафиксированные 35 ч | Заметки |
+|------|-------|------------|-------------|---------------------------|-------|
+| Рекомендовано | `deepseek/deepseek-v4-pro` | 0,435 $ | 0,87 $ | ~0,46 $ | Хорошее качество сжатия и резюмирования при стоимости ~10× ниже Sonnet. |
+| Рекомендовано | `deepseek/deepseek-chat` | 0,27 $ | 1,10 $ | ~0,40 $ | Постарше, но для рабочих нагрузок только на сжатие по-прежнему годится. |
+| Рекомендовано | `qwen/qwen3-coder` | 0,45 $ | 1,80 $ | ~0,55 $ | Сильное code-reasoning, если ваши сессии сильно завязаны на код. |
+| Premium | `anthropic/claude-sonnet-4.6` | 3,00 $ | 15,00 $ | ~5,02 $ | Высокое качество, но дорого для постоянной фоновой работы. |
+| Premium | `openai/gpt-4o` | 2,50 $ | 10,00 $ | ~4,20 $ | Класс, схожий с Sonnet. |
+| Избегать | `anthropic/claude-opus-4.6` | 15,00 $ | 75,00 $ | ~25+ $ | Модель класса reasoning; колоссальный перерасход на сжатие. |
+
+agentmemory выводит runtime-предупреждение, когда `OPENROUTER_MODEL` совпадает с шаблоном premium-уровня. Установите `AGENTMEMORY_SUPPRESS_COST_WARNING=1`, чтобы заглушить его, как только сделаете осознанный выбор.
+
+Компромисс качество/цена для работы с памятью: сжатие — это задача резюмирования с относительно мягкими требованиями к качеству (резюме перечитывает агент, не пользователь). DeepSeek-V4-Pro / Qwen3-Coder ложатся на этой задаче в пределах погрешности от Sonnet, стоя примерно в 10 раз дешевле. Премиум-модели оставляйте для запросов, которые читаете напрямую.
+
+Источники: [цены OpenRouter на Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [заметки о ценах DeepSeek](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Мультиагентная память (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+В мультиагентных конфигурациях, где несколько ролей делят один сервер agentmemory (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` помечает каждую запись ролью, которая её сделала. `AGENTMEMORY_AGENT_SCOPE` управляет тем, фильтрует ли recall по этому тегу.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"
+```
+
+Два режима:
+
+| Режим | Помечать записи | Фильтровать recall | Когда использовать |
+|------|------------|---------------|-------------|
+| `shared` (по умолчанию) | да | нет | Общий контекст между агентами с аудит-журналом. Architect видит, что отметил developer, но каждая запись фиксирует, кто это сказал. |
+| `isolated` | да | да | Строгое разделение. Architect никогда не увидит наблюдения / записи памяти / сессии developer'а. |
+
+Что помечается, когда `AGENT_ID` задан: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. Роль течёт по `api::session::start` → `mem::observe` → `mem::compress` → KV.
+
+Что фильтруется в режиме `isolated`: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Каждый эндпоинт принимает `?agentId=` для переопределения на конкретный запрос и `?agentId=*`, чтобы полностью выйти из env-scope. `/memories` дополнительно принимает `?includeOrphans=true`, чтобы поднять «доисторические» записи памяти, у которых `agentId` не определён.
+
+Переопределение в самом вызове на уровне SDK / REST: каждый мутирующий эндпоинт (`/session/start`, `/remember`) принимает поле `agentId` в теле запроса, которое выигрывает у env. Полезно для runtime'ов, прогоняющих много ролей через один серверный процесс.
+
+Когда `AGENT_ID` не задан, память остаётся без scope (legacy-поведение: ни тегов, ни фильтров).
+
+### Порты
+
+agentmemory + iii-engine по умолчанию занимают четыре порта. Если перезапуск падает с `port in use`, эта таблица подскажет, какой процесс искать.
+
+| Порт | Процесс | Назначение | Override через env |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Внутренний streams-воркер (используется agentmemory + просмотрщиком) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Просмотрщик в реальном времени (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — воркеры регистрируются здесь, по нему же течёт OTel-телеметрия | `III_ENGINE_URL` (полный URL, по умолчанию `ws://localhost:49134`) |
+
+Очистка зависших процессов, если порты остаются занятыми после падения:
+
+```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` корректно вычищает и воркер, и pidfile движка при штатном завершении (#640, #474). Ручная очистка выше нужна только в посткрэшевом сценарии, когда ни один pidfile не остался.
+
+### Конфигурационный файл
+
+Помещайте runtime-конфигурацию agentmemory в `~/.agentmemory/.env`, а не экспортируйте переменные в каждой сессии shell. Если просмотрщик показывает подсказку настройки вида `export ANTHROPIC_API_KEY=...`, скопируйте её в этот файл как `ANTHROPIC_API_KEY=...` без префикса `export`, затем перезапустите agentmemory.
+
+Переменные окружения процесса по-прежнему работают и имеют приоритет над значениями из файла.
+
+В Windows тот же файл лежит в `%USERPROFILE%\.agentmemory\.env`:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+Чтобы протестировать с подпиской Claude Code Pro/Max вместо API-ключа, включите её явно:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+В этом же файле включите возможности графа или консолидации, если они нужны:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Переменные окружения
+
+Создайте `~/.agentmemory/.env`:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+124 эндпоинта на порту `3111`. REST API по умолчанию слушает на `127.0.0.1`. Защищённые эндпоинты требуют `Authorization: Bearer `, когда установлен `AGENTMEMORY_SECRET`, а эндпоинты mesh-синхронизации требуют `AGENTMEMORY_SECRET` на обоих узлах.
+
+
+Ключевые эндпоинты
+
+| Метод | Путь | Описание |
+|--------|------|-------------|
+| `GET` | `/agentmemory/health` | Проверка состояния (всегда публична) |
+| `POST` | `/agentmemory/session/start` | Запуск сессии + получение контекста |
+| `POST` | `/agentmemory/session/end` | Завершение сессии |
+| `POST` | `/agentmemory/observe` | Захват наблюдения |
+| `POST` | `/agentmemory/smart-search` | Гибридный поиск |
+| `POST` | `/agentmemory/context` | Генерация контекста |
+| `POST` | `/agentmemory/remember` | Сохранить в долговременную память |
+| `POST` | `/agentmemory/forget` | Удалить наблюдения |
+| `POST` | `/agentmemory/enrich` | Контекст файла + записи памяти + баги |
+| `GET` | `/agentmemory/profile` | Профиль проекта |
+| `GET` | `/agentmemory/export` | Экспорт всех данных |
+| `POST` | `/agentmemory/import` | Импорт из JSON |
+| `POST` | `/agentmemory/graph/query` | Запрос к графу знаний |
+| `POST` | `/agentmemory/team/share` | Расшарить в команду |
+| `GET` | `/agentmemory/audit` | Аудит-журнал |
+
+Полный список эндпоинтов: [`src/triggers/api.ts`](../src/triggers/api.ts)
+
+
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ tests
+npm run test:integration # API tests (requires running services)
+```
+
+**Требования:** Node.js >= 20, [iii-engine](https://iii.dev/docs) или Docker
+
+
+
+ Kodlama ajanınız her şeyi hatırlasın. Aynı şeyi bir daha açıklamayın.
+ Built on iii engine
+
+ Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode ve her MCP istemcisi için kalıcı bellek.
+
+ Bu gist, Karpathy'nin LLM Wiki desenini güven puanlaması, yaşam döngüsü, bilgi grafları ve hibrit aramayla genişletir: agentmemory bunun uygulamasıdır.
+
+
+---
+
+## Kurulum
+
+```bash
+npm install -g @agentmemory/agentmemory # bir kez — `agentmemory` PATH'te kullanılabilir
+# macOS/Linux sistem Node kurulumlarında EACCES hatası alırsanız şununla deneyin:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # bellek sunucusunu :3111 üzerinde başlat
+agentmemory demo # örnek oturumlar yükle + recall'u kanıtla
+agentmemory connect claude-code # ajanınızı bağlayın (ayrıca: codex, cursor, gemini-cli, ...)
+```
+
+Veya `npx` ile (kurulum gerekmez):
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Dikkat — npx sürüm bazında önbelleğe alır. Eğer çıplak bir `npx @agentmemory/agentmemory` eski bir sürümü servis ediyorsa, en güncelini `npx -y @agentmemory/agentmemory@latest` ile zorlayın veya önbelleği `rm -rf ~/.npm/_npx` ile bir kez temizleyin (macOS/Linux; Windows'ta `%LOCALAPPDATA%\npm-cache\_npx` dizinini silin). v0.9.16+ sonrası ilk npx çalıştırması, çıplak `agentmemory` komutunun her yerden çalışması için global kurulum yapmanızı satır içi olarak sorar.
+
+Tüm seçenekler aşağıdaki [Hızlı Başlangıç](#quick-start) bölümünde. Ajana özel bağlantılar için [Her ajanla çalışır](#works-with-every-agent) bölümüne bakın.
+
+---
+
+
+
+agentmemory; hook'ları, MCP'yi veya REST API'yi destekleyen her ajanla çalışır. Tüm ajanlar aynı bellek sunucusunu paylaşır.
+
+
+
+
+
+Claude Code
+yerel eklenti + 12 hook + MCP
+
+
+
+Codex CLI
+yerel eklenti + 6 hook + MCP
+
+
+
+OpenClaw
+yerel eklenti + MCP
+
+
+
+Hermes
+yerel eklenti + MCP
+
+
+
+pi
+yerel eklenti + MCP
+
+
+
+OpenHuman
+yerel Memory trait arka uç
+
+
+
+Cursor
+MCP sunucusu
+
+
+
+Gemini CLI
+MCP sunucusu
+
+
+
+
+
+OpenCode
+22 hook + MCP + eklenti
+
+
+
+Cline
+MCP sunucusu
+
+
+
+Goose
+MCP sunucusu
+
+
+
+Kilo Code
+MCP sunucusu
+
+
+
+Aider
+REST API
+
+
+
+Claude Desktop
+MCP sunucusu
+
+
+
+Windsurf
+MCP sunucusu
+
+
+
+Roo Code
+MCP sunucusu
+
+
+
+
+
+ MCP veya HTTP konuşan herhangi bir ajanla çalışır. Tek sunucu, tüm ajanlar arasında paylaşılan bellek.
+
+
+---
+
+Her oturumda aynı mimariyi tekrar tekrar anlatıyorsunuz. Aynı bug'ları yeniden keşfediyorsunuz. Aynı tercihleri yeniden öğretiyorsunuz. Yerleşik bellek (CLAUDE.md, .cursorrules) 200 satırda tıkanır ve eskir. agentmemory bunu düzeltir. Ajanınızın yaptıklarını sessizce yakalar, aranabilir belleğe sıkıştırır ve bir sonraki oturum başladığında doğru bağlamı enjekte eder. Tek komut. Ajanlar arası çalışır.
+
+**Neler değişiyor:** Oturum 1'de JWT kimlik doğrulamasını kuruyorsunuz. Oturum 2'de hız sınırlaması istiyorsunuz. Ajan zaten biliyor: kimlik doğrulamanız `src/middleware/auth.ts` içinde jose middleware kullanıyor, testleriniz token doğrulamasını kapsıyor ve Edge uyumluluğu için jsonwebtoken yerine jose'yi seçtiniz. Yeniden anlatma yok. Kopyala-yapıştır yok. Ajan basitçe *biliyor*.
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+> **v0.9.0'da yeni** — [agent-memory.dev](https://agent-memory.dev) tanıtım sitesi, dosya sistemi bağlayıcısı (`@agentmemory/fs-watcher`), bağımsız MCP artık çalışan sunucuya proxy yapıyor (böylece hook'lar ve görüntüleyici hemfikir), her silme yolunda kodlanmış denetim politikası, küçük Node süreçlerinde sağlık `memory_critical` olarak işaretlenmiyor. Tüm notlar [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18) içinde.
+
+---
+
+
+
+
+
+
+
+### Geri Getirme Doğruluğu
+
+**coding-agent-life-v1** (kurum içi corpus, sandbox-yeniden üretilebilir)
+
+| Adaptör | P@5 | R@5 | Top-5 isabet oranı | p50 gecikme |
+|---|---|---|---|---|
+| **agentmemory hibrit** | **0.578** | **0.967** | **15 / 15** | 14 ms |
+| grep referansı | 0.267 | 0.967 | 15 / 15 | 0 ms |
+
+%100 Top-5 isabet oranı. Aynı girdide grep referansından **2.2×** daha iyi hassasiyet. Tam tip bazında döküm: [`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 soru)
+
+| Sistem | R@5 | R@10 | MRR |
+|---|---|---|---|
+| **agentmemory** | **95.2%** | **98.6%** | **88.2%** |
+| Yalnız BM25 yedeği | 86.2% | 94.6% | 71.5% |
+
+
+
+> Embedding modeli: `all-MiniLM-L6-v2` (yerel, ücretsiz, API anahtarı gerekmez). Tam raporlar: [`benchmark/LONGMEMEVAL.md`](../benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](../benchmark/QUALITY.md), [`benchmark/SCALE.md`](../benchmark/SCALE.md). Rakip karşılaştırması: [`benchmark/COMPARISON.md`](../benchmark/COMPARISON.md) — agentmemory'nin mem0, Letta, Khoj, claude-mem, Hippo ile karşılaştırması.
+
+**Yerel olarak yeniden üretin:** [`eval/README.md`](../eval/README.md) — LongMemEval `_s` (genel 500 soru) + `coding-agent-life-v1` (kurum içi 15 oturum corpus) için adaptör-takılabilir harness. Grep / vektör / agentmemory adaptörleri yan yana puanlanır, NDJSON çıktısı, yayımlanan puan tabloları [`docs/benchmarks/`](../docs/benchmarks/) içine düşer.
+
+**[codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything) ve [Graphify](https://github.com/safishamsi/graphify) ile birlikte çalışır.** Kod-graf indeksleme, çok-ajanlı build pipeline'ları ve doküman / PDF / görsel / video boyunca daha geniş bilgi grafları. agentmemory çalışmayı hatırlar; bu üç proje bağlam katmanının geri kalanını aydınlatır. Tarifler + soru-yönlendirme tablosu: [`docs/recipes/pairings.md`](../docs/recipes/pairings.md).
+
+---
+
+
+
+Uyumluluk: bu sürüm kararlı `iii-sdk` `^0.11.0` ve iii-engine v0.11.x'i hedefler.
+
+### 30 saniyede deneyin
+
+```bash
+# Terminal 1: sunucuyu başlatın
+npx @agentmemory/agentmemory
+
+# Terminal 2: örnek veriyi yükleyin ve geri çağırmayı iş başında görün
+npx @agentmemory/agentmemory demo
+```
+
+`demo`, 3 gerçekçi oturum yükler (JWT auth, N+1 sorgu düzeltmesi, hız sınırlaması) ve bunlar üzerinde anlamsal aramalar çalıştırır. "veritabanı performans optimizasyonu" araması yaptığınızda "N+1 sorgu düzeltmesi"ni bulduğunu göreceksiniz — anahtar kelime eşleştirmesi bunu yapamaz.
+
+Belleğin canlı oluşumunu izlemek için `http://localhost:3113` adresini açın.
+
+### Önerilen: globally kurun
+
+`npx` sürüm bazında önbelleğe alır. Geçen hafta `npx @agentmemory/agentmemory@0.9.14`'ü çalıştırdıysanız, çıplak bir `npx @agentmemory/agentmemory` `~/.npm/_npx/`'ten en son sürümü değil, eski 0.9.14'ü servis edebilir. Bir kez kurun ve çıplak `agentmemory` komutu her yerde çalışsın:
+
+```bash
+npm install -g @agentmemory/agentmemory
+# macOS/Linux sistem Node kurulumlarında EACCES hatası alırsanız şununla deneyin:
+# sudo npm install -g @agentmemory/agentmemory
+agentmemory # sunucuyu başlatın (npx şekliyle aynı)
+agentmemory stop # kapatın
+agentmemory remove # oluşturduğumuz her şeyi kaldırın
+agentmemory connect claude-code # tek bir ajanı bağlayın
+agentmemory doctor # interaktif teşhis + düzeltme istemleri
+```
+
+v0.9.16 ve sonrası ile birlikte, ilk npx çalıştırması global kurmanızı satır içi olarak ister — bir kez `Y` yanıtlayın, hazırsınız. Atlarsanız, taze bir indirme için şunlardan birine geri dönün:
+
+```bash
+npx -y @agentmemory/agentmemory@latest # npm'den en güncelini zorlar (platformlar arası)
+rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # yalnız macOS/Linux (POSIX shell)
+```
+
+Windows / PowerShell'de eşdeğer cache temizleme komutu `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` şeklindedir — yukarıdaki `npx -y ...@latest` formu platformlar arası seçenektir.
+
+### Oturum Tekrar Oynatma (Session Replay)
+
+agentmemory'nin kaydettiği her oturum tekrar oynatılabilir. Görüntüleyiciyi açın, **Replay** sekmesini seçin ve zaman çizelgesini tarayın: istemler, araç çağrıları, araç sonuçları ve yanıtlar; oynat/duraklat, hız kontrolü (0.5×–4×) ve klavye kısayollarıyla (boşluk geçiş, oklar adım atlama) ayrı olaylar olarak görüntülenir.
+
+Halihazırda içeri aktarmak istediğiniz eski Claude Code JSONL kayıtlarınız mı var?
+
+```bash
+# Varsayılan ~/.claude/projects altındaki her şeyi içeri aktar
+npx @agentmemory/agentmemory import-jsonl
+
+# Veya tek bir dosya içeri aktar
+npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl
+```
+
+İçeri aktarılan oturumlar yerli olanların yanında Replay seçicisinde görünür. Arka planda her giriş `mem::replay::load`, `mem::replay::sessions` ve `mem::replay::import-jsonl` iii fonksiyonları üzerinden yönlendirilir — yan kanal sunucu yok.
+
+### Yükseltme / Bakım
+
+Yerel runtime'ınızı bilinçli olarak güncellemek istediğinizde bakım komutunu kullanın:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Uyarı: bu komut mevcut çalışma alanını/runtime'ı değiştirir. JavaScript bağımlılıklarını güncelleyebilir, `cargo install iii-engine --force` çalıştırabilir ve Docker imajlarını çekebilir.
+
+Uygulama detayları `src/cli.ts` içinde (`src/cli.ts:544-595` bölgesi civarında `runUpgrade`'a bakın).
+
+### Claude Code (tek blok, yapıştırın)
+
+```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, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 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.
+```
+
+#### Eklenti kurulumu olmadan Claude Code (MCP-bağımsız yol)
+
+Eğer `/plugin install` kullanmak yerine agentmemory'nin MCP sunucusunu doğrudan `~/.claude.json` üzerinden bağlarsanız, Claude Code `${CLAUDE_PLUGIN_ROOT}`'u asla çözmez ve hook scriptlerini `~/.claude/settings.json` içinde mutlak yollara işaret etmek zorunda kalırsınız. Bu yollar genellikle agentmemory sürümünü gömer (örn. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`), bu yüzden bir sonraki yükseltme her hook'u sessizce kırar ([#508](https://github.com/rohitg00/agentmemory/issues/508)).
+
+Geçici çözüm:
+
+```bash
+agentmemory connect claude-code --with-hooks
+```
+
+Bu, aynı hook komutlarını `~/.claude/settings.json` içine, kurulu `@agentmemory/agentmemory` paketinin paketli `plugin/` dizinine çözülmüş mutlak yollarla birleştirir. agentmemory'yi yükselttikten sonra yolları yenilemek için komutu yeniden çalıştırın. Aynı dosyadaki kullanıcı girdileri korunur; yalnızca önceki agentmemory girdileri değiştirilir. `/plugin install` yolunu kullanmak hâlâ önerilen yaklaşımdır.
+Uzak veya korumalı deployment'lar için Claude Code'u `AGENTMEMORY_URL` ve `AGENTMEMORY_SECRET` ayarlanmış olarak başlatın. Eklenti her iki değeri de paketli MCP sunucusuna geçirir; `AGENTMEMORY_URL` boş olduğunda MCP shim'i `http://localhost:3111`'i kullanır.
+
+### Codex CLI (Codex eklenti platformu)
+
+```bash
+# 1. ayrı bir terminalde bellek sunucusunu başlatın
+npx @agentmemory/agentmemory
+
+# 2. agentmemory marketplace'i kaydedin ve eklentiyi kurun
+codex plugin marketplace add rohitg00/agentmemory
+codex plugin add agentmemory@agentmemory
+```
+
+Codex eklentisi, Claude Code eklentisiyle aynı `plugin/` dizininden gelir. Şunları kaydeder:
+
+- `@agentmemory/mcp` MCP sunucusu olarak (`AGENTMEMORY_URL` çalışan bir agentmemory sunucusuna işaret ettiğinde tüm 51 tool'u proxy yapar; erişilebilir sunucu yoksa yerel olarak 7 tool'a düşer)
+- 6 yaşam döngüsü hook'u: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`
+- 4 skill: `/recall`, `/remember`, `/session-history`, `/forget`
+
+Codex'in hook motoru, hook alt süreçlerine `CLAUDE_PLUGIN_ROOT` enjekte eder (bkz. [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), bu sayede aynı hook scriptleri her iki host'ta da çoğaltma yapmadan çalışır. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure olayları yalnızca Claude Code'a özeldir ve Codex için kaydedilmez.
+
+#### Codex Desktop: eklenti hook'ları şu anda sessiz (geçici çözüm mevcut)
+
+`CodexHooks` ve `PluginHooks` her ikisi de [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs) içinde stable + varsayılan olarak etkin, ancak Codex Desktop sürümleri şu anda eklenti-yerel `hooks.json`'u dağıtmıyor ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP tool'ları hâlâ çalışıyor; yalnızca yaşam döngüsü gözlemleri eksik.
+
+Düzeltme upstream'e iner inmez, aynı hook komutlarını global `~/.codex/hooks.json` içine yansıtın:
+
+```bash
+agentmemory connect codex --with-hooks
+```
+
+Bu, `~/.codex/hooks.json`'a paketli scriptlere mutlak yollarla atıfta bulunan idempotent bir blok ekler (user-scope'ta `${CLAUDE_PLUGIN_ROOT}` genişlemesi gerekmez). agentmemory'yi yükselttikten sonra yolları yenilemek için aynı komutu yeniden çalıştırın. Aynı dosyadaki kullanıcı girdileri korunur; yalnızca önceki agentmemory girdileri değiştirilir.
+
+
+OpenClaw (bu istemi yapıştırın)
+
+```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 51 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`.
+```
+
+Tam kılavuz: [`integrations/openclaw/`](../integrations/openclaw/)
+
+
+
+
+Hermes Agent (bu istemi yapıştırın)
+
+```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 51 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.
+```
+
+Tam kılavuz: [`integrations/hermes/`](../integrations/hermes/)
+
+
+
+### Diğer ajanlar
+
+Bellek sunucusunu başlatın: `npx @agentmemory/agentmemory`
+
+agentmemory girdisi, `mcpServers` şeklini kullanan her host'ta (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw) **aynı MCP sunucu bloğudur**:
+
+```json
+"agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ }
+}
+```
+
+**Bu girdiyi host'un yapılandırma dosyasındaki mevcut `mcpServers` nesnesine birleştirin** — dosyayı değiştirmeyin. Dosyada zaten başka sunucular varsa, `agentmemory`'yi `mcpServers` içindeki başka bir anahtar olarak yanlarına ekleyin. `mcpServers` tamamen eksikse, bloğu `{ "mcpServers": { ... } }` içine yapıştırın. `${VAR}` yer tutucuları, MCP-sunucu lansmanında shell'den `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET`'i miras alır — ayarsız değişkenler boş string geçirir ve shim `http://localhost:3111`'e geri döner. Bir tane bağlı girdi hem yerel hem uzak (k8s / reverse-proxy'li) dağıtımları kapsar.
+
+| Ajan | Yapılandırma dosyası | Notlar |
+|---|---|---|
+| **Cursor** | `~/.cursor/mcp.json` | `mcpServers` içine birleştirin. Web sitesinde tek tıklamayla deeplink de mevcut. |
+| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | `mcpServers` içine birleştirin. Düzenlemeden sonra Claude Desktop'ı yeniden başlatın. |
+| **Cline / Roo Code / Kilo Code** | Cline MCP ayarları (Settings UI → MCP Servers → Edit) | Aynı `mcpServers` bloğu. |
+| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Aynı `mcpServers` bloğu. |
+| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (otomatik birleştirir). |
+| **OpenClaw** | OpenClaw MCP yapılandırması | Aynı `mcpServers` bloğu veya daha derin [bellek eklentisi](../integrations/openclaw/) kullanın. |
+| **Codex CLI (yalnız MCP)** | `.codex/config.toml` | TOML şekli: `codex mcp add agentmemory -- npx -y @agentmemory/mcp` veya manuel olarak `[mcp_servers.agentmemory]` ekleyin. |
+| **Codex CLI (tam eklenti)** | Codex eklenti marketplace | `codex plugin marketplace add rohitg00/agentmemory` ardından `codex plugin add agentmemory@agentmemory`. MCP + 6 yaşam döngüsü hook'u (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skill kaydeder. Codex Desktop'ta, [openai/codex#16430](https://github.com/openai/codex/issues/16430) inene kadar `agentmemory connect codex --with-hooks` da çalıştırın — eklenti hook'ları şu anda orada sessiz. |
+| **OpenCode (yalnız MCP)** | `opencode.json` | Farklı şekil — üst seviye `mcp` anahtarı, komut dizi olarak: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. |
+| **OpenCode (tam eklenti)** | `plugin/opencode/` | Oturum yaşam döngüsü, mesajlar, araçlar, hataları kapsayan 22 otomatik yakalama hook'u. İki slash komut (`/recall`, `/remember`). `plugin/opencode/`'u OpenCode çalışma alanınıza kopyalayın ve eklenti girdisini `opencode.json`'a ekleyin. Tam hook tablosu + gap analizi için [`plugin/opencode/README.md`](../plugin/opencode/README.md) bakın. |
+| **pi** | `~/.pi/agent/extensions/agentmemory` | [`integrations/pi`](../integrations/pi/)'yi kopyalayın ve pi'yi yeniden başlatın. |
+| **Hermes Agent** | `~/.hermes/config.yaml` | Daha derin [bellek sağlayıcı eklentisi](../integrations/hermes/)'ni `memory.provider: agentmemory` ile kullanın. |
+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` standart `mcpServers` bloğunu yazar. Hook yükü Claude Code ile alan-uyumludur, bu yüzden mevcut 12 hook scripti değişiklik yapmadan çalışır — aynı `settings.json`'daki `hooks` bölümü üzerinden bağlayın. |
+| **Antigravity** (Gemini CLI'nin yerini alır) | `mcp_config.json` (Antigravity'nin User dizininde) | `agentmemory connect antigravity` standart `mcpServers` bloğunu yazar. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. 2026-06-18 Gemini CLI sonlandırılması sonrasında kullanın. |
+| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` kullanıcı-seviyesi yapılandırmayı yazar. Çalışma alanı override'ları kodunuzun yanındaki `.kiro/settings/mcp.json`'a gider. |
+| **Goose** | Goose MCP ayarları UI | Aynı `mcpServers` bloğu. |
+| **Aider** | n/a | REST API ile doğrudan konuşun: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. |
+| **Herhangi bir ajan (32+)** | n/a | `npx skillkit install agentmemory` host'u otomatik algılar ve birleştirir. |
+
+**Sandbox'lı MCP istemcileri** (Flatpak / Snap / kısıtlayıcı container'lar) host'un `localhost`'una erişemez: ayrıca `env` bloğunda `"AGENTMEMORY_FORCE_PROXY": "1"` ayarlayın ve `AGENTMEMORY_URL`'i sandbox'ın gerçekten erişebileceği bir rotaya yönlendirin (örn. LAN IP'niz). Teşhis adım adımı için bkz. [#234](https://github.com/rohitg00/agentmemory/issues/234).
+
+### Programatik erişim (Python / Rust / Node)
+
+agentmemory çekirdek işlemlerini iii fonksiyonları olarak kaydeder (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). iii SDK'sı olan herhangi bir dil, bunları doğrudan `ws://localhost:49134` üzerinden çağırabilir — dil başına ayrı bir REST istemcisi yok.
+
+```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"},
+})
+```
+
+Çalışan örnek: [`examples/python/`](../examples/python/) (quickstart + gözlem/recall akışı). iii runtime'ı olmayan host'lar için REST `:3111` üzerinde kullanılmaya devam eder.
+
+### Kaynaktan
+
+```bash
+git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
+npm install && npm run build && npm start
+```
+
+Bu, `iii` zaten kuruluysa yerel bir `iii-engine` ile agentmemory'yi başlatır veya Docker mevcutsa Docker Compose'a düşer. REST, stream'ler ve görüntüleyici varsayılan olarak `127.0.0.1`'e bağlanır.
+
+`iii-engine`'i manuel olarak kurun. **agentmemory şu anda `iii-engine`'i `v0.11.2`'ye sabitliyor** — `v0.11.6`, agentmemory'nin henüz refactor edilmediği yeni bir sandbox-her-şey-üzerinden-`iii worker add` modelini tanıtıyor. Refactor geldiğinde sabitleme kaldırılır. Sandbox modeline manuel olarak geçtiyseniz `AGENTMEMORY_III_VERSION=` ile override edin.
+
+- **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:** `aarch64-apple-darwin`'i `x86_64-apple-darwin` ile değiştirin
+- **Linux x64:** `x86_64-unknown-linux-gnu` ile değiştirin
+- **Linux arm64:** `aarch64-unknown-linux-gnu` ile değiştirin
+- **Windows:** [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2)'den `iii-x86_64-pc-windows-msvc.zip`'i indirin, `iii.exe`'yi çıkarın, PATH'e ekleyin
+
+Veya Docker kullanın (paketli `docker-compose.yml` `iiidev/iii:0.11.2`'yi çeker). Tam dokümanlar: [iii.dev/docs](https://iii.dev/docs).
+
+### Windows
+
+agentmemory Windows 10/11'de çalışır, ancak yalnızca Node.js paketi yeterli değildir — arka planda çalışan bir süreç olarak `iii-engine` runtime'ı (ayrı yerel ikilik) da gerekir. Resmi upstream kurucu bir `sh` scripti ve bugün için PowerShell kurucusu veya scoop/winget paketi yok, bu yüzden Windows kullanıcılarının iki yolu var:
+
+**Seçenek A — Önceden derlenmiş Windows ikiliği (önerilen):**
+
+```powershell
+# 1. Tarayıcınızda https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 açın
+# (engine v0.11.6+'nın gerektirdiği yeni sandbox modeli için
+# agentmemory refactor edilene kadar v0.11.2'ye sabitliyoruz)
+# 2. iii-x86_64-pc-windows-msvc.zip indirin
+# (veya ARM makinedeyseniz iii-aarch64-pc-windows-msvc.zip)
+# 3. iii.exe'yi PATH'te bir yere çıkarın veya şuraya yerleştirin:
+# %USERPROFILE%\.local\bin\iii.exe
+# (agentmemory bu konumu otomatik kontrol eder)
+# 4. Doğrulayın:
+iii --version
+# Şunu yazmalı: 0.11.2
+
+# 5. Ardından agentmemory'yi her zamanki gibi çalıştırın:
+npx -y @agentmemory/agentmemory
+```
+
+**Seçenek B — Docker Desktop:**
+
+```powershell
+# 1. Windows için Docker Desktop kurun
+# 2. Docker Desktop'ı başlatın ve engine'in çalıştığından emin olun
+# 3. agentmemory'yi çalıştırın — paketli compose dosyasını otomatik başlatır:
+npx -y @agentmemory/agentmemory
+```
+
+**Seçenek C — yalnızca bağımsız MCP (engine yok):** yalnızca ajanınız için MCP araçlarına ihtiyacınız varsa ve REST API'sine, görüntüleyiciye veya cron işlerine gerek yoksa engine'i tamamen atlayın:
+
+```powershell
+npx -y @agentmemory/agentmemory mcp
+# veya shim paketi üzerinden:
+npx -y @agentmemory/mcp
+```
+
+**Windows için teşhis:** `npx @agentmemory/agentmemory` başarısız olursa, gerçek engine stderr'ini görmek için `--verbose` ile yeniden çalıştırın. Yaygın hata türleri:
+
+| Belirti | Düzeltme |
+|---|---|
+| `iii-engine process started` ardından `did not become ready within 15s` | Engine başlatma sırasında çöktü — `--verbose` ile yeniden çalıştırın, stderr'i kontrol edin |
+| `Could not start iii-engine` | Ne `iii.exe` ne de Docker kurulu. Yukarıdaki Seçenek A veya B'ye bakın |
+| Port çakışması | `netstat -ano \| findstr :3111` ile neyin bağlı olduğunu görün, ardından öldürün veya `--port ` kullanın |
+| Docker kurulu olsa bile Docker fallback atlanıyor | Docker Desktop'ın gerçekten çalıştığından emin olun (sistem tepsisi simgesi) |
+
+> Not: `cargo install iii-engine` yoktur — `iii` crates.io'da yayımlanmamıştır. Tek desteklenen kurulum yöntemleri yukarıdaki önceden derlenmiş ikilik, upstream `sh` kurulum scripti (yalnızca macOS/Linux) ve Docker imajıdır.
+
+---
+
+
Deploy
+
+Yönetilen host'lar için tek tıklamayla şablonlar. Her biri,
+npm'den `@agentmemory/agentmemory`'yi çeken ve iii engine
+ikilisini resmi `iiidev/iii` Docker Hub imajından kopyalayan
+kendi kendine yeten bir Dockerfile içerir — önceden derlenmiş
+bir agentmemory imajı gerekmez. Kalıcı depolama `/data`'ya
+bağlanır; ilk açılış entrypoint'i, npm-paketli iii yapılandırmasını
+(ki `127.0.0.1`'e bağlanır) `0.0.0.0`'a bağlanan ve mutlak
+`/data` yollarını kullanan deploy-ayarlı bir tanesiyle üzerine
+yazar, HMAC secret'ını üretir, ardından agentmemory CLI'sini
+exec etmeden önce `gosu` aracılığıyla yetkileri `root`'tan
+`node`'a düşürür.
+
+
+
+
+
+
+Render'ın tek-tıklamayla deploy düğmesi, depo kökünde `render.yaml`
+gerektirir; biz bunu bilerek temiz tutuyoruz. Deponun içindeki blueprint'e
+manuel olarak işaret etmek için [`deploy/render/`](../deploy/render/README.md) içinde belgelenen Render Blueprint akışını kullanın.
+
+Tam kurulum detayları (HMAC yakalama, görüntüleyici SSH tüneli,
+döndürme, yedekleme, maliyet alt sınırları) [`deploy/`](../deploy/README.md) içinde:
+
+- [`deploy/fly`](../deploy/fly/README.md) — `auto_stop_machines = "stop"` ile
+ tek makine; en ucuz boşta çalışma.
+- [`deploy/railway`](../deploy/railway/README.md) — Hobby planı sabit ücret,
+ panelden volume.
+- [`deploy/render`](../deploy/render/README.md) — Blueprint akışı,
+ ücretli planlarda otomatik disk snapshot'ları.
+- [`deploy/coolify`](../deploy/coolify/README.md) — kendi VPS'inizde
+ [Coolify](https://coolify.io/self-hosted) üzerinden self-hosted; aynı
+ Docker Compose stack'i, host ve verinin sahibi sizsiniz.
+
+Yalnızca `3111` portu yayımlanır. `3113`'teki görüntüleyici container içinde
+loopback'e bağlı kalır — her şablonun README'si ona ulaşmak için SSH-tünel
+desenini belgeler.
+
+---
+
+
+
+Her kodlama ajanı, oturum sona erdiğinde her şeyi unutur. Her oturumun ilk 5 dakikasını yığınınızı yeniden anlatarak harcarsınız. agentmemory arka planda çalışır ve bunu tamamen ortadan kaldırır.
+
+```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.
+```
+
+### Yerleşik ajan belleğiyle karşılaştırma
+
+Her AI kodlama ajanı yerleşik bellekle gelir — Claude Code'da `MEMORY.md`, Cursor'da notepad, Cline'da memory bank var. Bunlar yapışkan notlar gibi çalışır. agentmemory, o yapışkan notların ardındaki aranabilir veritabanıdır.
+
+| | Yerleşik (CLAUDE.md) | agentmemory |
+|---|---|---|
+| Ölçek | 200 satır sınırı | Sınırsız |
+| Arama | Her şeyi bağlama yükler | BM25 + vektör + graf (yalnız top-K) |
+| Token maliyeti | 240 gözlemde 22K+ | ~1,900 token (%92 daha az) |
+| Ajanlar arası | Ajan başına dosya | MCP + REST (herhangi bir ajan) |
+| Koordinasyon | Yok | Lease'ler, sinyaller, action'lar, routine'ler |
+| Gözlemlenebilirlik | Dosyaları manuel okuma | :3113'te gerçek zamanlı görüntüleyici |
+
+---
+
+
+
+### Bellek 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 Katmanlı Bellek Konsolidasyonu
+
+İnsan beyninin belleği nasıl işlediğinden ilham aldı — uyku konsolidasyonundan çok da farklı değil.
+
+| Katman | Ne | Analoji |
+|------|------|---------|
+| **Working** | Araç kullanımından ham gözlemler | Kısa süreli bellek |
+| **Episodic** | Sıkıştırılmış oturum özetleri | "Ne oldu" |
+| **Semantic** | Çıkarılmış olgular ve desenler | "Ne biliyorum" |
+| **Procedural** | İş akışları ve karar desenleri | "Nasıl yapılır" |
+
+Bellekler zamanla decay olur (Ebbinghaus eğrisi). Sık erişilen bellekler güçlenir. Bayat bellekler otomatik tahliye edilir. Çelişkiler algılanır ve çözülür.
+
+### Ne Yakalanır
+
+| Hook | Yakalar |
+|------|----------|
+| `SessionStart` | Proje yolu, oturum ID |
+| `UserPromptSubmit` | Kullanıcı istemleri (gizlilik-filtrelenmiş) |
+| `PreToolUse` | Dosya erişim desenleri + zenginleştirilmiş bağlam |
+| `PostToolUse` | Tool adı, girdi, çıktı |
+| `PostToolUseFailure` | Hata bağlamı |
+| `PreCompact` | Sıkıştırmadan önce belleği yeniden enjekte eder |
+| `SubagentStart/Stop` | Alt-ajan yaşam döngüsü |
+| `Stop` | Oturum sonu özeti |
+| `SessionEnd` | Oturum tamamlandı işareti |
+
+### Temel Yetenekler
+
+| Yetenek | Açıklama |
+|---|---|
+| **Otomatik yakalama** | Her tool kullanımı hook'lar üzerinden kaydedilir — sıfır manuel çaba |
+| **Anlamsal arama** | RRF füzyonu ile BM25 + vektör + bilgi grafı |
+| **Bellek evrimi** | Sürümleme, supersede, ilişki grafları |
+| **Otomatik unutma** | TTL süresi dolması, çelişki algılama, önem tahliyesi |
+| **Gizlilik öncelikli** | API anahtarları, secret'lar, `` etiketleri depolamadan önce çıkarılır |
+| **Kendini iyileştirme** | Devre kesici, sağlayıcı yedek zinciri, sağlık izleme |
+| **Claude bridge** | MEMORY.md ile çift yönlü sync |
+| **Bilgi grafı** | Entity çıkarımı + BFS gezinti |
+| **Takım belleği** | İsimlendirilmiş paylaşımlı + özel takım üyeleri arasında |
+| **Atıf provenansı** | Herhangi bir belleği kaynak gözlemlere kadar izleyin |
+| **Git snapshot'ları** | Bellek durumunu sürümleyin, geri alın ve diff'leyin |
+
+---
+
+
+
+Üç sinyali birleştiren üçlü-akış geri getirme:
+
+| Akış | Ne yapar | Ne zaman |
+|---|---|---|
+| **BM25** | Eş anlamlı genişletmeli stem'lenmiş anahtar kelime eşleştirme | Her zaman açık |
+| **Vektör** | Yoğun embedding'ler üzerinde kosinüs benzerliği | Embedding sağlayıcı yapılandırılmış |
+| **Graf** | Entity eşleştirme yoluyla bilgi grafı gezintisi | Sorguda entity'ler tespit edildiğinde |
+
+Reciprocal Rank Fusion (RRF, k=60) ile birleştirilir ve oturum-çeşitlendirilir (oturum başına maksimum 3 sonuç).
+
+BM25, Yunanca, Kiril, İbranice, Arapça ve aksanlı Latin'i kutudan çıkar çıkmaz tokenize eder. Çince / Japonca / Korece bellekler için, CJK akışlarını kelime-seviyesinde token'lara bölmek üzere isteğe bağlı segmenter'ları kurun (`npm install @node-rs/jieba tiny-segmenter`); bunlar olmadan agentmemory yumuşak olarak tüm-akış tokenizasyonuna düşer ve stderr'e bir kerelik bir ipucu yazdırır.
+
+### Embedding sağlayıcıları
+
+agentmemory sağlayıcınızı otomatik algılar. En iyi sonuçlar için yerel embedding'leri kurun (ücretsiz):
+
+```bash
+npm install @xenova/transformers
+```
+
+| Sağlayıcı | Model | Maliyet | Notlar |
+|---|---|---|---|
+| **Yerel (önerilen)** | `all-MiniLM-L6-v2` | Ücretsiz | Çevrim dışı, BM25-only üzerinde +8pp recall |
+| Gemini | `gemini-embedding-001` | Ücretsiz katman | 100+ dil, 768/1536/3072 boyut (MRL), 2048-token girdi. `text-embedding-004`'ün yerini alır ([deprecated, 14 Ocak 2026'da kapanış](https://ai.google.dev/gemini-api/docs/deprecations)) |
+| OpenAI | `text-embedding-3-small` | 1M başı $0.02 | En yüksek kalite |
+| Voyage AI | `voyage-code-3` | Ücretli | Kod için optimize edilmiş |
+| Cohere | `embed-english-v3.0` | Ücretsiz deneme | Genel amaçlı |
+| OpenRouter | Herhangi bir model | Değişken | Çok-modelli proxy |
+
+---
+
+
+
+53 tool, 6 kaynak, 3 prompt ve 4 skill — herhangi bir ajan için en kapsamlı MCP bellek toolkit'i.
+
+> **MCP shim vs tam sunucu:** yayımlanan `@agentmemory/mcp` paketi ince bir shim'dir. Tam 51-tool yüzeyini **yalnızca `AGENTMEMORY_URL` üzerinden çalışan bir agentmemory sunucusuna erişebildiğinde** açığa çıkarır (proxy modu). Erişilebilir sunucu yoksa, shim 7-tool yerel sete (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`) düşer. `AGENTMEMORY_TOOLS=core|all` env değişkeni *sunucu tarafı* bir bayraktır — shim'in `env` bloğunda ayarlamak hiçbir etki yapmaz. Cursor / OpenCode / Gemini CLI'da yalnızca 7 tool görüyorsanız, `npx @agentmemory/agentmemory` (veya Docker stack'i) başlatın ve `AGENTMEMORY_URL=http://localhost:3111` ayarlayın.
+
+### 51 Tool
+
+
+Çekirdek tool'lar (her zaman kullanılabilir)
+
+| Tool | Açıklama |
+|------|-------------|
+| `memory_recall` | Geçmiş gözlemleri ara |
+| `memory_compress_file` | Yapıyı koruyarak markdown dosyalarını sıkıştır |
+| `memory_save` | Bir içgörü, karar veya deseni kaydet |
+| `memory_patterns` | Tekrar eden desenleri algıla |
+| `memory_smart_search` | Hibrit anlamsal + anahtar kelime araması |
+| `memory_file_history` | Belirli dosyalar hakkında geçmiş gözlemler |
+| `memory_sessions` | Son oturumları listele |
+| `memory_timeline` | Kronolojik gözlemler |
+| `memory_profile` | Proje profili (kavramlar, dosyalar, desenler) |
+| `memory_export` | Tüm bellek verisini dışa aktar |
+| `memory_relations` | İlişki grafını sorgula |
+
+
+
+
+Genişletilmiş tool'lar (51 toplam — AGENTMEMORY_TOOLS=all ayarla)
+
+| Tool | Açıklama |
+|------|-------------|
+| `memory_patterns` | Tekrar eden desenleri algıla |
+| `memory_timeline` | Kronolojik gözlemler |
+| `memory_relations` | İlişki grafını sorgula |
+| `memory_graph_query` | Bilgi grafı gezintisi |
+| `memory_consolidate` | 4 katmanlı konsolidasyonu çalıştır |
+| `memory_claude_bridge_sync` | MEMORY.md ile sync |
+| `memory_team_share` | Takım üyeleriyle paylaş |
+| `memory_team_feed` | Son paylaşılan öğeler |
+| `memory_audit` | İşlemlerin denetim izi |
+| `memory_governance_delete` | Denetim izi ile sil |
+| `memory_snapshot_create` | Git-sürümlü snapshot |
+| `memory_action_create` | Bağımlılıklarla iş öğesi oluştur |
+| `memory_action_update` | Action durumunu güncelle |
+| `memory_frontier` | Önceliğe göre sıralanmış engellenmemiş action'lar |
+| `memory_next` | Tek en önemli sonraki action |
+| `memory_lease` | Exclusive action lease'leri (çoklu ajan) |
+| `memory_routine_run` | İş akışı routine'lerini örnekle |
+| `memory_signal_send` | Ajanlar arası mesajlaşma |
+| `memory_signal_read` | Onay alındıyla mesajları oku |
+| `memory_checkpoint` | Harici koşul kapıları |
+| `memory_mesh_sync` | Örnekler arasında P2P sync |
+| `memory_sentinel_create` | Event-driven gözcüler |
+| `memory_sentinel_trigger` | Sentinel'leri harici olarak tetikle |
+| `memory_sketch_create` | Ephemeral action grafları |
+| `memory_sketch_promote` | Kalıcıya yükselt |
+| `memory_crystallize` | Action zincirlerini kompakt et |
+| `memory_diagnose` | Sağlık kontrolleri |
+| `memory_heal` | Sıkışmış durumu otomatik düzelt |
+| `memory_facet_tag` | Boyut:değer etiketleri |
+| `memory_facet_query` | Facet etiketlerine göre sorgula |
+| `memory_verify` | Provenansı izle |
+
+
+
+### 6 Kaynak · 3 Prompt · 4 Skill
+
+| Tür | İsim | Açıklama |
+|------|------|-------------|
+| Resource | `agentmemory://status` | Sağlık, oturum sayısı, bellek sayısı |
+| Resource | `agentmemory://project/{name}/profile` | Proje başına zeka |
+| Resource | `agentmemory://memories/latest` | En son 10 aktif bellek |
+| Resource | `agentmemory://graph/stats` | Bilgi grafı istatistikleri |
+| Prompt | `recall_context` | Ara + bağlam mesajları döndür |
+| Prompt | `session_handoff` | Ajanlar arasında handoff verisi |
+| Prompt | `detect_patterns` | Tekrar eden desenleri analiz et |
+| Skill | `/recall` | Belleği ara |
+| Skill | `/remember` | Uzun süreli belleğe kaydet |
+| Skill | `/session-history` | Son oturum özetleri |
+| Skill | `/forget` | Gözlemleri/oturumları sil |
+
+### Bağımsız MCP
+
+Tam sunucu olmadan çalıştır — herhangi bir MCP istemcisi için. Şunlardan herhangi biri çalışır:
+
+```bash
+npx -y @agentmemory/agentmemory mcp # kanonik (her zaman kullanılabilir)
+npx -y @agentmemory/mcp # shim paketi takma adı
+```
+
+Veya ajanınızın MCP yapılandırmasına ekleyin:
+
+Çoğu ajan (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI):
+```json
+{
+ "mcpServers": {
+ "agentmemory": {
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "http://localhost:3111"
+ }
+ }
+ }
+}
+```
+
+`agentmemory` girdisini, dosyayı değiştirmek yerine host'unuzun mevcut `mcpServers` nesnesine birleştirin. Host'un `localhost`'una erişemeyen sandbox'lı istemciler için env bloğuna `"AGENTMEMORY_FORCE_PROXY": "1"` ekleyin ve `AGENTMEMORY_URL`'i sandbox'ın erişebileceği bir rotaya ayarlayın.
+
+OpenCode (`opencode.json`):
+```json
+{
+ "mcp": {
+ "agentmemory": {
+ "type": "local",
+ "command": ["npx", "-y", "@agentmemory/mcp"],
+ "enabled": true
+ }
+ },
+ "plugin": ["./plugins/agentmemory-capture.ts"]
+}
+```
+
+Eklenti dosyasını depodan kopyalayın:
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+cp plugin/opencode/commands/*.md ~/.config/opencode/commands/
+```
+
+---
+
+
+
+`3113` portunda otomatik başlar. Canlı gözlem akışı, oturum gezgini, bellek tarayıcısı, bilgi grafı görselleştirmesi ve sağlık paneli.
+
+```bash
+open http://localhost:3113
+```
+
+Görüntüleyici sunucusu varsayılan olarak `127.0.0.1`'e bağlanır. REST-servisli `/agentmemory/viewer` endpoint'i normal `AGENTMEMORY_SECRET` bearer-token kurallarını izler. CSP başlıkları yanıt başına bir script nonce'ı kullanır ve satır içi handler özniteliklerini devre dışı bırakır (`script-src-attr 'none'`).
+
+---
+
+
+
+`:3113`'teki görüntüleyici ajanınızın **hatırladıklarını** gösterir. [iii konsolu](https://iii.dev/docs/console) ajanınızın **yaptıklarını** gösterir — her bellek op'u bir OpenTelemetry trace'i olarak, her KV girdisi düzenlenebilir, her fonksiyon çağrılabilir, her stream dinlenebilir. Aynı belleğe iki pencere: biri ürün-şekilli, diğeri motor-şekilli.
+
+Bir `memory_smart_search`'ün ateşlenmesini izleyin ve BM25 taramasını → embedding aramasını → RRF füzyonunu → reranker'ı bir şelale olarak görün. Sıkışmış bir konsolidasyon zamanlayıcısını KV tarayıcıda düzenleyin. `PostToolUse` hook'unu değiştirilmiş bir payload ile tekrar oynatın. WebSocket stream'ini sabitleyin ve gözlemlerin canlı olarak indiğini izleyin.
+
+agentmemory bunu ücretsiz dağıtır çünkü her fonksiyon, trigger, durum kapsamı ve stream bir iii primitif'idir — özel hiçbir şey, enstrümante edilecek hiçbir şey yok.
+
+
+
+
+ Workers sayfası: bağlı her worker — agentmemory'nin kendisi dahil — PID, fonksiyon sayısı, runtime ve son-görülme ile birlikte.
+
+
+**Zaten kurulu.** Konsol `iii` ile birlikte gelir — ayrı kurucu yok.
+
+**agentmemory ile birlikte başlat:**
+
+```bash
+# agentmemory görüntüleyicisi 3113 portunu tutar, bu yüzden konsolu 3114'te çalıştırın.
+# Engine REST (3111), WebSocket (3112) ve bridge (49134) varsayılanları agentmemory ile eşleşir.
+iii console --port 3114
+```
+
+Ardından `http://localhost:3114`'ü açın. Deneysel mimari-grafı sayfası için `--enable-flow` ekleyin.
+
+Yalnızca taşıdıysanız engine endpoint'lerini override edin:
+
+```bash
+iii console --port 3114 \
+ --engine-port 3111 \
+ --ws-port 3112 \
+ --bridge-port 49134
+```
+
+**Konsoldan neler yapabilirsiniz:**
+
+| Sayfa | Şunun için kullanın |
+|------|-----------|
+| **Workers** | Bağlı her worker'ı ve canlı metriklerini görün — agentmemory worker'ının kendisi dahil. |
+| **Functions** | agentmemory'nin herhangi bir fonksiyonunu doğrudan JSON payload ile çağırın — bir istemci bağlamadan `memory.recall`, `memory.consolidate`, `graph.query` test etmek için kullanışlı. |
+| **Triggers** | HTTP, cron, event ve state trigger'larını tekrar oynatın — konsolidasyon cron'unu manuel olarak ateşleyin, bir HTTP route'unu yeniden deneyin, bir durum değişikliği yayın. |
+| **States** | Tam CRUD ile KV tarayıcı — oturumlar, bellek slot'ları, yaşam döngüsü zamanlayıcıları, embedding'ler indeksi — değerleri yerinde düzenleyin. |
+| **Streams** | Bellek yazımları, hook olayları ve gözlem güncellemeleri için iii stream'leri üzerinden akarken canlı WebSocket monitörü. |
+| **Queues** | Dayanıklı kuyruk konuları + dead-letter yönetimi. Başarısız embedding / sıkıştırma işlerini tekrar oynatın veya bırakın. |
+| **Traces** | OpenTelemetry şelale / alev / hizmet-dağılımı görünümleri. `trace_id` ile filtreleyerek tek bir `memory.search`'ün hangi fonksiyonları, DB çağrılarını ve embedding isteklerini ürettiğini tam olarak görün. |
+| **Logs** | Trace/span ID'lerine korelasyonlu, yapılandırılmış OTEL logları. |
+| **Config** | Runtime yapılandırması — engine'inizin hangi worker'lar, sağlayıcılar ve portlarla çalıştığını tam olarak görün. |
+| **Flow** | (İsteğe bağlı, `--enable-flow`) Her worker, trigger ve stream'in interaktif mimari grafı. |
+
+
+
+
+ Traces: her bellek işlemi için şelale / alev / hizmet dağılımı.
+
+
+**Trace'ler zaten açık:**
+
+`iii-config.yaml` `iii-observability` worker'ı etkinleştirilmiş olarak gelir (`exporter: memory`, `sampling_ratio: 1.0`, metrikler + log'lar). Ekstra yapılandırma gerekmez — agentmemory başlar başlamaz, her bellek işlemi konsolun okuyabileceği bir trace span'ı ve yapılandırılmış bir log yayar.
+
+Bunun yerine Jaeger/Honeycomb/Grafana Tempo'ya dışa aktarmak isterseniz, `exporter: memory`'yi `exporter: otlp` olarak değiştirin ve collector endpoint'ini iii'nin observability dokümanlarına göre ayarlayın.
+
+> **Dikkat:** konsolun kendisinde hiçbir auth zorlanmaz — `127.0.0.1`'e bağlı tutun (varsayılan) ve asla genel kullanıma açmayın.
+
+---
+
+
+
+agentmemory **zaten çalışan bir [iii](https://iii.dev) örneğidir**. Fonksiyonlar, trigger'lar, KV state, stream'ler, OTEL trace'leri — hepsi iii primitifleridir. Postgres, Redis, Express, pm2 veya Prometheus kurmadınız çünkü iii bunların yerini alıyor.
+
+Bu da, tek bir komutun agentmemory'yi tamamen yeni bir yetenekle genişlettiği anlamına gelir.
+
+### agentmemory'yi tek komutla genişletin
+
+```bash
+iii worker add iii-pubsub # bellek yazımlarını bağlı her örneğe fan-out et
+iii worker add iii-cron # zamanlanmış konsolidasyon, decay süpürmeleri, snapshot rotasyonu
+iii worker add iii-queue # embedding + sıkıştırma işleri için dayanıklı yeniden denemeler
+iii worker add iii-observability # her bellek op'unda OTEL trace'leri (varsayılan açık)
+iii worker add iii-sandbox # hatırlanan kodu izole bir microVM içinde çalıştır
+iii worker add iii-database # SQL destekli bir state adaptörü tak
+iii worker add mcp # agentmemory MCP'sinin yanında genel MCP host'u
+```
+
+Her `iii worker add` agentmemory'nin zaten çalıştığı aynı engine'e yeni fonksiyonlar ve trigger'lar kaydeder. Görüntüleyici ve konsol bunları anında alır — yeniden yükleme yok, yeni entegrasyon yok, yeni container yok.
+
+| `iii worker add` | agentmemory'nin üzerine ne elde edersiniz |
+|---|---|
+| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Çoklu-örnek bellek: her `remember` fan-out olur, her `search` birleşimi okur |
+| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Zamanlanmış yaşam döngüsü — geceleri konsolidasyon, haftalık snapshot'lar, sabit bir saatte decay |
+| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Dayanıklı yeniden denemeler: başarısız embedding + sıkıştırma işleri yeniden başlatmaya dayanır, kayıp gözlem yok |
+| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL trace'leri, metrikleri, log'ları her fonksiyonda — birinci günden itibaren `iii-config.yaml`'da bağlı |
+| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | `memory_recall`'dan çıkan kod, shell'inizde değil, bir kullan-at VM içinde çalışır |
+| [`iii-database`](https://workers.iii.dev/workers/iii-database) | In-memory KV varsayılanlarını aştığınızda SQL destekli state adaptörü |
+| [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory'ninin yanında ekstra MCP sunucuları ayağa kaldırın, aynı engine'i paylaşın |
+
+Tam kayıt defteri: [workers.iii.dev](https://workers.iii.dev). Oradaki her worker, agentmemory'nin kullandığı aynı primitifler aracılığıyla bir araya gelir — ve elinizde olan agentmemory de onlardan biridir.
+
+### iii'nin yerini aldığı şeyler
+
+| Geleneksel stack | agentmemory kullanır |
+|---|---|
+| Express.js / Fastify | iii HTTP Triggers |
+| SQLite / Postgres + pgvector | iii KV State + in-memory vektör indeksi |
+| SSE / Socket.io | iii Streams (WebSocket) |
+| pm2 / systemd | iii engine worker süpervizyonu |
+| Prometheus / Grafana | iii OTEL + sağlık monitörü |
+| Özel eklenti sistemleri | `iii worker add ` |
+
+**118 kaynak dosya · ~21,800 LOC · 950+ test · 123 fonksiyon · 34 KV scope** — hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi iii'nin kendisi.
+
+---
+
+
+
+### LLM Sağlayıcıları
+
+agentmemory ortamınızdan otomatik algılar. Varsayılan olarak, bir sağlayıcı yapılandırmadıkça veya Claude abonelik fallback'ine açıkça opt-in yapmadıkça hiçbir LLM çağrısı yapılmaz.
+
+| Sağlayıcı | Yapılandırma | Notlar |
+|----------|--------|-------|
+| **No-op (varsayılan)** | Yapılandırma gerekmez | LLM destekli compress/summarize DEVRE DIŞI. Sentetik BM25 sıkıştırma + recall hâlâ çalışır. Eskiden Claude-abonelik fallback'ine dayanıyorsanız aşağıdaki `AGENTMEMORY_ALLOW_AGENT_SDK`'ya bakın. |
+| Anthropic API | `ANTHROPIC_API_KEY` | Token başına faturalama |
+| MiniMax | `MINIMAX_API_KEY` | Anthropic-uyumlu |
+| Gemini | `GEMINI_API_KEY` | Embedding'leri de etkinleştirir |
+| OpenRouter | `OPENROUTER_API_KEY` | Herhangi bir model |
+| Claude abonelik fallback'i | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Yalnızca opt-in. `@anthropic-ai/claude-agent-sdk` oturumları doğurur — eskiden sınırsız Stop-hook recursion'ına neden oluyordu (#149 takip), bu yüzden artık varsayılan değil. |
+
+### Maliyet bilincine sahip model seçimi
+
+Arka plan sıkıştırması her gözlemde çalışır, bu yüzden model seçimi aylık harcamayı anlamlı ölçüde değiştirir. Yakalanan iş yükü verisi: 635 istek / 888K token / 35 saatlik aktif kullanım, 2026-05-23 fiyatlandırmasında üç OpenRouter modeline karşı çalıştırıldı.
+
+| Katman | Model | Girdi / 1M | Çıktı / 1M | Yakalanan 35 saat maliyeti | Notlar |
+|------|-------|------------|-------------|---------------------------|-------|
+| Önerilen | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Sonnet'ten ~10× daha düşük maliyetle sağlam sıkıştırma + özetleme kalitesi. |
+| Önerilen | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | Daha eski ama yalnızca-sıkıştırma iş yükleri için hâlâ iyi. |
+| Önerilen | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Oturumlarınız yoğun olarak kod-şekilli ise güçlü kod muhakemesi. |
+| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | Yüksek kalite ancak her zaman açık arka plan çalışması için pahalı. |
+| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Sonnet ile benzer katman. |
+| Kaçının | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Reasoning sınıfı model; sıkıştırma için büyük aşırı harcama. |
+
+`OPENROUTER_MODEL` premium-katman bir desenle eşleştiğinde agentmemory bir runtime uyarısı yazdırır. Bilinçli bir seçim yaptıktan sonra susturmak için `AGENTMEMORY_SUPPRESS_COST_WARNING=1` ayarlayın.
+
+Bellek işi için kalite vs maliyet ödünleşmesi: sıkıştırma görece gevşek kalite çıtaları olan bir özetleme görevidir (özeti tekrar okuyan kullanıcı değil, ajandır). DeepSeek-V4-Pro / Qwen3-Coder bu görevde Sonnet'in yuvarlama hatası içinde kalırken ~10× daha az maliyetlidir. Premium katman modelleri doğrudan okuduğunuz sorgular için saklayın.
+
+Kaynaklar: [Sonnet 4.6 için OpenRouter fiyatlandırması](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek fiyatlandırma notları](https://api-docs.deepseek.com/quick_start/pricing/).
+
+### Çoklu-ajan belleği (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)
+
+Birden fazla rolün tek bir agentmemory sunucusunu paylaştığı çoklu-ajan kurulumlarında (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` her yazıyı onu yapan rolle etiketler. `AGENTMEMORY_AGENT_SCOPE` recall'un bu etikete göre filtreleyip filtrelemeyeceğini kontrol eder.
+
+```env
+TEAM_ID=company
+USER_ID=engineering-team
+AGENT_ID=architect
+AGENTMEMORY_AGENT_SCOPE=isolated # isteğe bağlı; varsayılan "shared"
+```
+
+İki mod:
+
+| Mod | Yazıları etiketle | Recall'u filtrele | Ne zaman kullanılır |
+|------|------------|---------------|-------------|
+| `shared` (varsayılan) | evet | hayır | Denetim iziyle ajanlar arası bağlam. Architect, developer'ın notlarını görebilir ancak her satır kim söylediğini kaydeder. |
+| `isolated` | evet | evet | Katı ayrım. Architect developer'ın gözlemlerini / belleklerini / oturumlarını asla görmez. |
+
+`AGENT_ID` ayarlandığında ne etiketlenir: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. Rol `api::session::start` → `mem::observe` → `mem::compress` → KV boyunca akar.
+
+İzole modda ne filtrelenir: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Her endpoint istek başına override için `?agentId=` ve env kapsamından opt-out etmek için `?agentId=*` kabul eder. `/memories` ayrıca `agentId`'si undefined olan AGENT_ID öncesi belleklerin yüzeylenmesi için `?includeOrphans=true` kabul eder.
+
+SDK / REST katmanında çağrı başına override: her mutasyon endpoint'i (`/session/start`, `/remember`) istek gövdesinde env'i geçen bir `agentId` alanı kabul eder. Tek bir sunucu sürecinden birçok rolü yönlendiren runtime'lar için kullanışlıdır.
+
+`AGENT_ID` ayarlanmadığında bellek kapsam dışı kalır (eski davranış, etiket yok, filtre yok).
+
+### Portlar
+
+agentmemory + iii-engine varsayılan olarak dört port'a bağlanır. Bir yeniden başlatma `port in use` ile başarısız olursa, bu tablo hangi süreci aramanız gerektiğini söyler.
+
+| Port | Süreç | Amaç | Env override |
+|------|---------|---------|--------------|
+| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` |
+| `3112` | iii-engine | Dahili stream'ler worker'ı (agentmemory + görüntüleyici tarafından tüketilir) | `III_STREAMS_PORT` |
+| `3113` | agentmemory | Gerçek zamanlı görüntüleyici (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |
+| `49134` | iii-engine | WebSocket — worker'lar burada kaydolur, OTel telemetri buradan akar | `III_ENGINE_URL` (tam URL, varsayılan `ws://localhost:49134`) |
+
+Çöken bir çalıştırma sonrası portlar bağlı kaldığında bayat-süreç temizliği:
+
+```bash
+# macOS / Linux — her portta ne varsa bulun ve öldürün
+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` graceful shutdown'da hem worker hem de engine pidfile'ını temiz olarak biçer (#640, #474). Yukarıdaki manuel temizlik yalnızca her iki pidfile'ın da geride kalmadığı çökme sonrası durum içindir.
+
+### Yapılandırma Dosyası
+
+agentmemory runtime yapılandırmasını her shell'de değişkenleri export etmek yerine `~/.agentmemory/.env`'a koyun. Görüntüleyici `export ANTHROPIC_API_KEY=...` gibi bir kurulum ipucu gösteriyorsa, `export` ön ekini koymadan bu dosyaya `ANTHROPIC_API_KEY=...` olarak kopyalayın, ardından agentmemory'yi yeniden başlatın.
+
+Süreç ortam değişkenleri hâlâ çalışır ve dosyadaki değerlere göre öncelik kazanır.
+
+Windows'ta aynı dosya `%USERPROFILE%\.agentmemory\.env` konumunda bulunur:
+
+```powershell
+New-Item -ItemType Directory -Force $HOME\.agentmemory
+notepad $HOME\.agentmemory\.env
+```
+
+API anahtarı yerine Claude Code Pro/Max aboneliğiyle test etmek için açıkça opt-in yapın:
+
+```env
+AGENTMEMORY_ALLOW_AGENT_SDK=true
+AGENTMEMORY_AUTO_COMPRESS=true
+```
+
+Graph veya konsolidasyon özelliklerini istiyorsanız aynı dosyada açın:
+
+```env
+GRAPH_EXTRACTION_ENABLED=true
+CONSOLIDATION_ENABLED=true
+```
+
+### Ortam Değişkenleri
+
+`~/.agentmemory/.env` oluşturun:
+
+```env
+# LLM provider (pick one — default is the no-op provider: no LLM calls)
+# ANTHROPIC_API_KEY=sk-ant-...
+# ANTHROPIC_BASE_URL=... # Optional: Anthropic-compatible proxy / Azure
+# GEMINI_API_KEY=...
+# OPENROUTER_API_KEY=...
+# MINIMAX_API_KEY=...
+# OPENAI_API_KEY=*** # NOTE: this same key auto-activates BOTH the
+# # OpenAI LLM provider (here) AND the OpenAI
+# # embedding provider (further below). Set
+# # OPENAI_API_KEY_FOR_LLM=false to scope it
+# # to embeddings only.
+# OPENAI_BASE_URL=https://api.openai.com # Optional: override for Azure / vLLM / LM Studio / proxies
+# # Azure: https://.openai.azure.com/openai/deployments/
+# # Auto-detected from `.openai.azure.com` hostname; uses
+# # api-key header + api-version query param.
+# OPENAI_API_VERSION=2024-08-01-preview # Optional: Azure api-version query param
+# OPENAI_MODEL=gpt-4o-mini # Optional: default model
+# OPENAI_TIMEOUT_MS=60000 # Optional: OpenAI-scoped alias for the outbound fetch
+# # timeout. Takes precedence over AGENTMEMORY_LLM_TIMEOUT_MS
+# # for back-compat with v0.9.17. New configs should
+# # prefer the global AGENTMEMORY_LLM_TIMEOUT_MS below.
+# OPENAI_REASONING_EFFORT=none # Optional: "low" | "medium" | "high" | "none"
+# # Honored only by OpenAI's reasoning models (o1, o3,
+# # gpt-*-reasoning) and providers that mirror that
+# # schema (Ollama Cloud thinking models). Standard
+# # chat models reject this field with 400. Set to
+# # "none" for thinking models that return reasoning
+# # but no content.
+# OPENAI_API_KEY_FOR_LLM=false # Optional: set to false to skip OpenAI auto-detection
+# # for LLM (useful if you only want OpenAI for embeddings)
+# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk);
+# leave OFF unless you understand the Stop-hook recursion risk (#149 follow-up):
+# AGENTMEMORY_ALLOW_AGENT_SDK=true
+
+# Embedding provider (auto-detected, or override)
+# EMBEDDING_PROVIDER=local
+# VOYAGE_API_KEY=...
+# OPENAI_API_KEY=sk-...
+# OPENAI_BASE_URL=https://api.openai.com # Override for Azure / vLLM / LM Studio / proxies
+# OPENAI_EMBEDDING_MODEL=text-embedding-3-small
+# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table
+
+# Outbound LLM / embedding timeout
+# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s). Applies to every
+ # raw-fetch provider (Gemini, OpenRouter, MiniMax,
+ # OpenAI LLM, OpenAI/Cohere/Voyage/OpenRouter
+ # embedding). For the OpenAI LLM path, the
+ # OpenAI-scoped OPENAI_TIMEOUT_MS alias (above)
+ # takes precedence when set, for back-compat
+ # with v0.9.17.
+ # Increase for slow networks or large batch calls;
+ # decrease to fail-fast on rate-limit holds.
+
+# Search tuning
+# BM25_WEIGHT=0.4
+# VECTOR_WEIGHT=0.6
+# TOKEN_BUDGET=2000
+
+# Auth
+# AGENTMEMORY_SECRET=your-secret
+
+# Ports (defaults: 3111 API, 3113 viewer)
+# III_REST_PORT=3111
+
+# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned
+ # memory slots — persona,
+ # user_preferences, tool_guidelines,
+ # project_context, guidance,
+ # pending_items, session_patterns,
+ # self_notes. Size-limited; agent
+ # edits via memory_slot_* tools.
+ # Pinned slots addressable for
+ # SessionStart injection.
+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.
+ # Stop hook fires mem::slot-reflect:
+ # scans recent observations, auto-
+ # appends TODOs to pending_items,
+ # counts patterns in
+ # session_patterns, records touched
+ # files in project_context. Fire-
+ # and-forget; does not block.
+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:
+ # - SessionStart may inject ~1-2K
+ # chars of project context into
+ # the first turn of each session
+ # (this is what actually reaches
+ # the model — Claude Code treats
+ # SessionStart stdout as context)
+ # - PreToolUse fires /agentmemory/enrich
+ # on every file-touching tool call
+ # (resource cleanup, not a token
+ # fix — PreToolUse stdout is debug
+ # log only per Claude Code docs)
+ # Observations are still captured via
+ # PostToolUse regardless of this flag.
+# GRAPH_EXTRACTION_ENABLED=false
+# CONSOLIDATION_ENABLED=true
+# LESSON_DECAY_ENABLED=true
+# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
+# CLAUDE_MEMORY_BRIDGE=false
+# SNAPSHOT_ENABLED=false
+
+# Team
+# TEAM_ID=
+# USER_ID=
+# TEAM_MODE=private
+
+# Tool visibility: "core" (8 tools) or "all" (51 tools)
+# AGENTMEMORY_TOOLS=core
+```
+
+---
+
+
+
+```bash
+npm run dev # Hot reload
+npm run build # Production build
+npm test # 950+ test
+npm run test:integration # API testleri (çalışan servisler gerektirir)
+```
+
+**Ön koşullar:** Node.js >= 20, [iii-engine](https://iii.dev/docs) veya Docker
+
+