diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000000000000000000000000000000000000..4db7b4a83afa70de6c85bf1c4c8e1673ae49b1fa --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "agentmemory", + "owner": { + "name": "Rohit Ghumare", + "github": "rohitg00" + }, + "plugins": [ + { + "name": "agentmemory", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions", + "source": "./plugin" + } + ] +} diff --git a/.codex-plugin/marketplace.json b/.codex-plugin/marketplace.json new file mode 100644 index 0000000000000000000000000000000000000000..65ec86ced05e1995c9f08e6d34e7ec3c2ec75de6 --- /dev/null +++ b/.codex-plugin/marketplace.json @@ -0,0 +1,22 @@ +{ + "name": "agentmemory", + "interface": { + "displayName": "agentmemory" + }, + "plugins": [ + { + "name": "agentmemory", + "source": { + "source": "git-subdir", + "url": "https://github.com/rohitg00/agentmemory.git", + "path": "./plugin", + "ref": "main" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Memory" + } + ] +} diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..77ca0f3a38d62e9448781c37c3741f27eb6a7c82 --- /dev/null +++ b/.env.example @@ -0,0 +1,175 @@ +# ============================================================================= +# agentmemory configuration +# ============================================================================= +# +# Copy this file to `~/.agentmemory/.env` (or to your project root if you +# prefer scoped config) and uncomment the lines you want to override. +# +# Every line is OFF by default — `agentmemory` runs out of the box with no +# LLM key, no embedding key, and no API auth. Set keys here only when you +# want to enable the corresponding feature. +# +# Run `npx @agentmemory/agentmemory init` to copy this file into place +# automatically. Run `npx @agentmemory/agentmemory doctor` to verify that +# the daemon reads the env you expect. +# +# Defaults shown in comments. Listed in priority order — the first key +# present wins on the LLM detection path (see src/config.ts::detectProvider). + +# ----------------------------------------------------------------------------- +# 1. LLM provider — pick ONE +# ----------------------------------------------------------------------------- +# +# Without a provider key, agentmemory runs in noop mode: observations are +# indexed via zero-LLM synthetic compression, hybrid search still works, +# but LLM-backed summarisation / reflection / consolidation are disabled. +# The detection order is OPENAI_API_KEY → MINIMAX_API_KEY → ANTHROPIC_API_KEY +# → GEMINI_API_KEY → OPENROUTER_API_KEY → noop. + +# OPENAI_API_KEY=sk-... # Used for OpenAI-compatible embeddings today. PR #307 will extend this to chat completions (DeepSeek, SiliconFlow, vLLM, LM Studio, Ollama via `/v1`). +# OPENAI_BASE_URL=https://api.openai.com # Override for OpenAI-compatible providers + +# ANTHROPIC_API_KEY=sk-ant-... +# ANTHROPIC_MODEL=claude-sonnet-4-20250514 # Default Anthropic model +# ANTHROPIC_BASE_URL=https://api.anthropic.com # Override for Anthropic-compatible proxies / Azure AI Foundry + +# GEMINI_API_KEY=... # Either env name works; GEMINI_API_KEY takes precedence +# GOOGLE_API_KEY=... # Alias for GEMINI_API_KEY when set alone (emits a one-time stderr hint) +# GEMINI_MODEL=gemini-2.5-flash # Default Gemini model (auto-detected GA model) + +# OPENROUTER_API_KEY=sk-or-... +# OPENROUTER_MODEL=anthropic/claude-sonnet-4-20250514 + +# MINIMAX_API_KEY=... +# MINIMAX_MODEL=MiniMax-M2.7 + +# MAX_TOKENS=4096 # Cap LLM completion tokens for compression / summarise calls + +# Outbound LLM / embedding timeout — shared across every raw-fetch provider +# (Gemini, OpenRouter, MiniMax, OpenAI LLM, and OpenAI/Cohere/Voyage/OpenRouter +# embedding). The OpenAI LLM path also honours the OpenAI-scoped +# OPENAI_TIMEOUT_MS alias for back-compat with v0.9.17 (precedence). +# AGENTMEMORY_LLM_TIMEOUT_MS=60000 # Default: 60 000 ms (60 s) + +# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk +# child sessions). Off by default — the agent-sdk fallback can trigger +# Stop-hook recursion (#149 follow-up) when invoked from inside Claude Code. +# AGENTMEMORY_ALLOW_AGENT_SDK=true + +# FALLBACK_PROVIDERS=anthropic,gemini # Comma-separated chain tried after the primary provider returns an error (e.g. rate limit) + +# ----------------------------------------------------------------------------- +# 2. Embedding provider — auto-detected, override via EMBEDDING_PROVIDER +# ----------------------------------------------------------------------------- +# +# Without an embedding key, agentmemory runs in BM25-only mode for hybrid +# search. Detection order: EMBEDDING_PROVIDER override → GEMINI_API_KEY → +# OPENAI_API_KEY → VOYAGE_API_KEY → COHERE_API_KEY → OPENROUTER_API_KEY → +# local (Xenova/all-MiniLM-L6-v2, 384-dim). + +# EMBEDDING_PROVIDER=local # local | openai | voyage | cohere | gemini | openrouter + +# VOYAGE_API_KEY=pa-... # Optimised for code embeddings + +# COHERE_API_KEY=... # General-purpose embeddings + +# Reuses OPENAI_API_KEY / OPENAI_BASE_URL above when EMBEDDING_PROVIDER=openai. +# OPENAI_EMBEDDING_MODEL=text-embedding-3-small # Embedding model when EMBEDDING_PROVIDER=openai +# OPENAI_EMBEDDING_DIMENSIONS=1536 # Required when the model is not in the known-models table + +# OPENROUTER_EMBEDDING_MODEL=openai/text-embedding-3-small # When EMBEDDING_PROVIDER=openrouter + +# ----------------------------------------------------------------------------- +# 3. Auth & security +# ----------------------------------------------------------------------------- +# +# Bearer-token auth for the REST API + viewer + all integration plugins. +# Without a secret, REST endpoints are open on loopback. Set this when +# you expose the daemon beyond loopback or run behind a reverse proxy. + +# AGENTMEMORY_SECRET=your-secret-here + +# ----------------------------------------------------------------------------- +# 4. Search tuning +# ----------------------------------------------------------------------------- + +# BM25_WEIGHT=0.4 # Hybrid search weight for BM25 leg +# VECTOR_WEIGHT=0.6 # Hybrid search weight for vector leg +# AGENTMEMORY_GRAPH_WEIGHT=0.2 # Graph traversal bonus on smart-search ranking +# TOKEN_BUDGET=2000 # Max tokens injected via mem::context per session +# MAX_OBS_PER_SESSION=500 # Per-session observation cap before consolidation kicks in +# SUMMARIZE_CHUNK_SIZE=400 # When mem::summarize sees a session larger than this, it chunks observations and map-reduces (chunk-summarize → reduce-merge) to stay within the LLM's context window. Default 400 ≈ 50k tokens per chunk at ~110 tok/obs. Native sessions are capped by MAX_OBS_PER_SESSION; chunking primarily matters for bulk-imported jsonl sessions, which bypass that cap. +# SUMMARIZE_CHUNK_CONCURRENCY=6 # Parallel chunk LLM calls during chunked summarize. Default 6 fits ~100-chunk sessions under iii's 180s function-invocation timeout at typical ~8s/call. High-throughput providers (Novita, DeepInfra, DeepSeek) commonly allow 100+ concurrent — bump this for very large imported sessions. + +# ----------------------------------------------------------------------------- +# 5. Behaviour flags +# ----------------------------------------------------------------------------- + +# AGENTMEMORY_AUTO_COMPRESS=true # Run LLM compression on every observation batch (requires a provider key). Default off — synthetic compression handles most cases. +# AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories back into agent prompts (#143). Default off — hooks capture observations but do not modify conversation. +# CONSOLIDATION_ENABLED=true # Run the 4-tier consolidation pipeline (memories → semantic → procedural). Default off — opt in once you've measured the LLM cost. +# CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation +# GRAPH_EXTRACTION_ENABLED=true # Extract concept-graph edges on remember; powers the graph-traversal recall path +# GRAPH_EXTRACTION_BATCH_SIZE=8 # Memories per graph-extraction batch +# AGENTMEMORY_REFLECT=true # Periodically auto-synthesize lessons from memories +# AGENTMEMORY_DROP_STALE_INDEX=true # Drop on-disk BM25 / vector index on startup if dim guard fires (#248). Recovery toggle for stuck-state debugging. +# AGENTMEMORY_IMAGE_EMBEDDINGS=true # Enable image embeddings when an image provider is present (experimental). + +# ----------------------------------------------------------------------------- +# 6. CLI / runtime knobs +# ----------------------------------------------------------------------------- + +# AGENTMEMORY_TOOLS=all # core (7 tools, default) | all (51 tools) — surface exposed to MCP clients +# AGENTMEMORY_SLOTS=memory # Comma-separated plugin slot names the CLI should claim +# AGENTMEMORY_DEBUG=1 # Trace MCP shim probe + standalone fallback decisions to stderr +# AGENTMEMORY_FORCE_PROXY=1 # Skip the MCP shim livez probe and trust AGENTMEMORY_URL (for sandboxed MCP clients that can't reach localhost) +# AGENTMEMORY_PROBE_TIMEOUT_MS=2000 # MCP shim livez probe timeout +# AGENTMEMORY_URL=http://localhost:3111 # REST base URL — honored by status, doctor, MCP shim +# AGENTMEMORY_VIEWER_URL=http://localhost:3113 # Override the viewer URL printed by `agentmemory status` +# AGENTMEMORY_EXPORT_ROOT=~/agentmemory-backup # Default destination for `agentmemory export` + +# STANDALONE_MCP=1 # MCP shim only — bypass the worker and run @agentmemory/mcp in-process +# STANDALONE_PERSIST_PATH=~/.agentmemory/local.db # Path used by the standalone MCP shim's local fallback store + +# Snapshot exporter — periodic snapshots of state_store + stream_store. +# SNAPSHOT_ENABLED=true +# SNAPSHOT_DIR=~/.agentmemory/snapshots +# SNAPSHOT_INTERVAL=3600 # Seconds between snapshots + +# Team sharing — when set, memories are scoped to (TEAM_ID, USER_ID) tuples. +# TEAM_MODE=shared +# TEAM_ID=acme +# USER_ID=rohit + +# ----------------------------------------------------------------------------- +# 7. Ports +# ----------------------------------------------------------------------------- + +# III_REST_PORT=3111 # REST API port (also affects viewer at +2) +# III_STREAMS_PORT=3112 # Streams API port +# III_ENGINE_URL=ws://localhost:49134 # iii-engine WebSocket URL (used by the worker) + +# ----------------------------------------------------------------------------- +# 8. iii engine pin +# ----------------------------------------------------------------------------- +# +# agentmemory currently pins iii-engine to v0.11.2 — v0.11.6 introduces a +# new sandbox-everything-via-`iii worker add` model that agentmemory +# hasn't been refactored for yet. Override with AGENTMEMORY_III_VERSION +# only after migrating to the sandbox model manually. + +# AGENTMEMORY_III_VERSION=0.11.2 + +# ----------------------------------------------------------------------------- +# 9. Claude Code bridge (opt-in) +# ----------------------------------------------------------------------------- + +# CLAUDE_MEMORY_BRIDGE=true # Mirror compressed memories into Claude Code's CLAUDE.md +# CLAUDE_PROJECT_PATH=/path/to/your/project # Required when CLAUDE_MEMORY_BRIDGE=true +# CLAUDE_MEMORY_LINE_BUDGET=200 # Lines of memory CLAUDE.md should hold + +# ----------------------------------------------------------------------------- +# 10. Obsidian export (opt-in) +# ----------------------------------------------------------------------------- + +# OBSIDIAN_AUTO_EXPORT=true # Auto-export memories to an Obsidian vault on every consolidation diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..a2f5e0c58d6e7b7c9b3d1605a8af8fdfcc234293 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [rohitg00] diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0a74e99e993c9b1b0842debc2e2a7756ba4f752 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,110 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 10 + labels: + - dependencies + - npm + commit-message: + prefix: deps + include: scope + groups: + minor-and-patch: + update-types: + - minor + - patch + + - package-ecosystem: npm + directory: /website + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 10 + labels: + - dependencies + - npm + - website + commit-message: + prefix: deps(website) + include: scope + groups: + minor-and-patch: + update-types: + - minor + - patch + + - package-ecosystem: npm + directory: /integrations/openclaw + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 5 + labels: + - dependencies + - npm + - integrations + commit-message: + prefix: deps(openclaw) + include: scope + + - package-ecosystem: npm + directory: /integrations/pi + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 5 + labels: + - dependencies + - npm + - integrations + commit-message: + prefix: deps(pi) + include: scope + + - package-ecosystem: npm + directory: /integrations/filesystem-watcher + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 5 + labels: + - dependencies + - npm + - integrations + commit-message: + prefix: deps(fs-watcher) + include: scope + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + time: "06:00" + timezone: Etc/UTC + open-pull-requests-limit: 5 + labels: + - dependencies + - github-actions + commit-message: + prefix: ci(deps) + include: scope + groups: + minor-and-patch: + update-types: + - minor + - patch diff --git a/.github/security-advisories/01-viewer-xss.md b/.github/security-advisories/01-viewer-xss.md new file mode 100644 index 0000000000000000000000000000000000000000..046c28627909f0726b1d72a03f89dfc4ad9c978d --- /dev/null +++ b/.github/security-advisories/01-viewer-xss.md @@ -0,0 +1,46 @@ +# GHSA Draft: Stored XSS in agentmemory real-time viewer + +**Severity:** Critical · **CVSS 3.1:** 9.6 (`AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:L`) +**CWE:** [CWE-79 — Improper Neutralization of Input During Web Page Generation](https://cwe.mitre.org/data/definitions/79.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +agentmemory's real-time viewer (default port 3113) rendered user-controlled data — tool outputs, file paths, memory titles, observation content — into HTML using inline `onclick=` event handlers. The viewer's Content Security Policy simultaneously allowed `script-src 'unsafe-inline'`, meaning injected JavaScript would execute in the reader's browser context. + +## Impact + +Any data captured by agentmemory hooks — which includes tool output from Claude Code, Cursor, or any other agent — becomes an XSS vector when the user opens the viewer. An attacker with the ability to influence any captured observation (e.g., by sending a crafted file contents to be read by an agent, or by planting a malicious commit message in a repository) could: + +- Exfiltrate the entire memory store via authenticated requests from the browser +- Read `AGENTMEMORY_SECRET` if the viewer was configured with auth +- Make requests to arbitrary endpoints on behalf of the viewer user +- Modify the DOM to mislead the developer +- Pivot to other localhost services on the developer's machine + +The viewer runs on localhost by default but is **reachable from the browser**, so standard same-origin protections don't help. + +## Patches + +Fixed in **0.8.2**: + +- All inline `on*=` handlers removed from `src/viewer/index.html` +- Replaced with delegated `data-action` event handling +- CSP switched to a **per-response script nonce** (`script-src 'nonce-'`) +- Added `script-src-attr 'none'` to block any inline handler attributes even if injected +- Viewer HTML now rendered through `src/viewer/document.ts` which generates a fresh nonce per request + +## Workarounds + +**None.** Users on affected versions should upgrade to 0.8.2 immediately. Do not open `http://localhost:3113` in a browser on affected versions if you suspect any of your captured observations may contain attacker-controlled content. + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) +- Reporter: @eng-pf + +## Credit + +@eng-pf submitted PR #108 with fixes for this and 5 other vulnerabilities. diff --git a/.github/security-advisories/02-curl-sh-rce.md b/.github/security-advisories/02-curl-sh-rce.md new file mode 100644 index 0000000000000000000000000000000000000000..f32a3e8174464dab1a4984c47d483085c398c29c --- /dev/null +++ b/.github/security-advisories/02-curl-sh-rce.md @@ -0,0 +1,57 @@ +# GHSA Draft: Remote shell script execution in agentmemory CLI startup + +**Severity:** Critical · **CVSS 3.1:** 9.8 (`AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H`) +**CWE:** [CWE-494 — Download of Code Without Integrity Check](https://cwe.mitre.org/data/definitions/494.html), [CWE-829 — Inclusion of Functionality from Untrusted Control Sphere](https://cwe.mitre.org/data/definitions/829.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +The agentmemory CLI (`npx @agentmemory/agentmemory`) auto-installed the iii-engine binary by piping a remote shell script into `sh`: + +```ts +execSync("curl -fsSL https://install.iii.dev/iii/main/install.sh | sh") +``` + +This happened automatically on first run if `iii` was not found in `$PATH`. The script was fetched over HTTPS and executed with the permissions of the user running `npx agentmemory`. No checksum verification, no pinned version, no signature check. + +## Impact + +If `install.iii.dev` were ever compromised — via DNS hijack, domain takeover, expired certificate + MITM on an untrusted network, BGP attack, or any other supply chain attack — **every new agentmemory user would execute attacker-controlled shell code** as their own user. + +This is the canonical "curl | sh" supply chain anti-pattern. It affected: +- Developers running `npx @agentmemory/agentmemory` for the first time +- CI/CD pipelines that installed agentmemory fresh +- Docker builds that installed agentmemory as part of an image + +## Patches + +Fixed in **0.8.2**: + +- Removed `execSync` call entirely from `src/cli.ts` +- CLI now uses an existing local `iii` binary if present in `$PATH` +- Falls back to Docker Compose (`docker compose up -d`) if Docker is available +- Shows manual install instructions if neither iii nor Docker is found: + - `cargo install iii-engine` + - `docker pull iiidev/iii:latest` + - Docs link: https://iii.dev/docs + +## Workarounds + +Users on affected versions should **install iii-engine manually** and run `agentmemory --no-engine` until upgraded: + +```bash +cargo install iii-engine +npx @agentmemory/agentmemory@0.8.1 --no-engine +``` + +Then upgrade to 0.8.2 at the earliest opportunity. + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) + +## Credit + +@eng-pf diff --git a/.github/security-advisories/03-default-bind-0000.md b/.github/security-advisories/03-default-bind-0000.md new file mode 100644 index 0000000000000000000000000000000000000000..f244e5d3848a45f5891e607e113d6e207b0a1055 --- /dev/null +++ b/.github/security-advisories/03-default-bind-0000.md @@ -0,0 +1,62 @@ +# GHSA Draft: agentmemory REST and stream services bound to 0.0.0.0 by default + +**Severity:** High · **CVSS 3.1:** 8.1 (`AV:A/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:L`) +**CWE:** [CWE-668 — Exposure of Resource to Wrong Sphere](https://cwe.mitre.org/data/definitions/668.html), [CWE-306 — Missing Authentication for Critical Function](https://cwe.mitre.org/data/definitions/306.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +The default `iii-config.yaml` bound both the REST API (port 3111) and the streams server (port 3112) to `0.0.0.0`, exposing them on every network interface the host could reach. Combined with the fact that `AGENTMEMORY_SECRET` is **unset by default**, this meant any device on the same local network as a running agentmemory instance could read the entire memory store without authentication. + +Affected endpoints included: +- `GET /agentmemory/export` — full dump of every captured observation, memory, session, and audit entry +- `GET /agentmemory/sessions` — session list +- `POST /agentmemory/smart-search` — arbitrary search over all captured content +- `POST /agentmemory/observe` — ability to **inject** fake observations +- `POST /agentmemory/remember` — ability to plant arbitrary memories +- All 109 other REST endpoints + +## Impact + +A developer running agentmemory on a laptop in a coffee shop, office, or conference WiFi effectively published their entire memory store — including captured API keys, file contents, prompts, decisions, and project context — to anyone on the same network. + +Attackers on the same network could: + +1. **Exfiltrate secrets.** `curl http://:3111/agentmemory/export` downloads everything. Depending on the incompleteness of the secret redaction (see advisory #06), this could include API keys and tokens. +2. **Inject memories.** An attacker could `POST /agentmemory/observe` or `/remember` with fake observations, poisoning the memory store so future sessions retrieve attacker-controlled context. +3. **Pivot to other services.** The mesh sync endpoint (before the auth fix in advisory #04) accepted peer data from any source. + +## Patches + +Fixed in **0.8.2**: + +- `iii-config.yaml` now binds REST, streams to `127.0.0.1` +- Viewer server already bound to `127.0.0.1` +- New `iii-config.docker.yaml` for Docker deployments: containers bind to `0.0.0.0` internally (required for Docker networking) but host port mapping is restricted to `127.0.0.1:port` in `docker-compose.yml` +- README and API section documentation updated to note 127.0.0.1 as the default + +## Workarounds + +Users on affected versions should manually edit their `iii-config.yaml` and change the REST and streams `host` values to `127.0.0.1`: + +```yaml +modules: + - class: modules::api::RestApiModule + config: + host: 127.0.0.1 # was 0.0.0.0 + - class: modules::stream::StreamModule + config: + host: 127.0.0.1 # was 0.0.0.0 +``` + +And set `AGENTMEMORY_SECRET` to a strong random value to protect endpoints even if network exposure is needed. + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) + +## Credit + +@eng-pf diff --git a/.github/security-advisories/04-mesh-unauth.md b/.github/security-advisories/04-mesh-unauth.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ffe2eb8e4812a5c5d335b614f5e7ac0f15cf3d --- /dev/null +++ b/.github/security-advisories/04-mesh-unauth.md @@ -0,0 +1,47 @@ +# GHSA Draft: Unauthenticated mesh sync in agentmemory + +**Severity:** High · **CVSS 3.1:** 7.4 (`AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N`) +**CWE:** [CWE-306 — Missing Authentication for Critical Function](https://cwe.mitre.org/data/definitions/306.html), [CWE-862 — Missing Authorization](https://cwe.mitre.org/data/definitions/862.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +agentmemory's mesh federation feature (P2P sync between instances) accepted push/pull requests on its `/agentmemory/mesh/*` endpoints without requiring authentication. The mesh sync function also did not send any `Authorization` header when calling peer instances, meaning the federation protocol was entirely unauthenticated. + +## Impact + +Any attacker who could reach a mesh-enabled agentmemory instance could: + +1. **Push fake memories** via `POST /agentmemory/mesh/receive` — inject attacker-controlled observations, actions, semantic memories, and relations into the target's memory store. This poisons future retrievals and could be used to manipulate what the target's AI agent sees. +2. **Pull the entire memory store** via `GET /agentmemory/mesh/export` — download all memories, actions, and graph data marked as mesh-shareable. +3. **Chain with advisory #03** — combined with the default `0.0.0.0` binding, mesh endpoints were reachable from any device on the local network without any authentication. + +Mesh is opt-in (requires an explicit peer registration), so this affected only users who had enabled federation. But those users had no authentication at all. + +## Patches + +Fixed in **0.8.2**: + +- All 5 mesh REST endpoints (`mesh-register`, `mesh-list`, `mesh-sync`, `mesh-receive`, `mesh-export`) now return 503 with `"mesh requires AGENTMEMORY_SECRET"` if the secret is not configured +- The `mem::mesh-sync` function now accepts a `meshAuthToken` parameter and **refuses to sync at all** if the token is missing +- Outgoing push/pull requests include `Authorization: Bearer ` headers +- Server-side, all mesh endpoints check bearer auth via the existing `checkAuth` helper + +## Workarounds + +Users on affected versions who have mesh federation enabled should: +1. Set `AGENTMEMORY_SECRET` to a strong random value on **both** peers +2. Restart the server +3. Upgrade to 0.8.2 at the earliest opportunity + +Users who have **not** enabled mesh federation are not affected by this specific issue, but should still upgrade for the other 5 fixes. + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) + +## Credit + +@eng-pf diff --git a/.github/security-advisories/05-obsidian-export-traversal.md b/.github/security-advisories/05-obsidian-export-traversal.md new file mode 100644 index 0000000000000000000000000000000000000000..13c4b8e96c548bc80f538c80883b0ab90c7441f3 --- /dev/null +++ b/.github/security-advisories/05-obsidian-export-traversal.md @@ -0,0 +1,61 @@ +# GHSA Draft: Arbitrary filesystem write via Obsidian export in agentmemory + +**Severity:** Medium · **CVSS 3.1:** 6.5 (`AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L`) +**CWE:** [CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')](https://cwe.mitre.org/data/definitions/22.html), [CWE-73 — External Control of File Name or Path](https://cwe.mitre.org/data/definitions/73.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +The `POST /agentmemory/obsidian/export` endpoint accepted a `vaultDir` parameter and passed it directly to `mkdir` and `writeFile` calls without any containment check. A caller could set `vaultDir` to any absolute path on the filesystem and agentmemory would create directories and write Markdown files there with the permissions of the process running the server. + +```bash +# Example exploit payload (affected versions only) +curl -X POST http://localhost:3111/agentmemory/obsidian/export \ + -H "Content-Type: application/json" \ + -d '{"vaultDir": "/etc/cron.d"}' +``` + +The content written would be agentmemory's exported memories in Markdown format, but an attacker could craft specific memory content beforehand to plant arbitrary files. + +## Impact + +When chained with advisory #03 (default `0.0.0.0` binding) or advisory #04 (unauthenticated mesh), an attacker on the local network could write arbitrary files to any filesystem location the agentmemory process had write access to. + +Possible exploitation paths: +- Write to `~/.ssh/authorized_keys` — SSH key injection +- Write to `/etc/cron.d/*` — cron job injection (if running as root) +- Write to `~/.bashrc` or shell rc files — code execution on next shell +- Overwrite any file the process could write to + +## Patches + +Fixed in **0.8.2**: + +- New `AGENTMEMORY_EXPORT_ROOT` environment variable (default: `~/.agentmemory`) +- `vaultDir` now goes through `resolveVaultDir()` in `src/functions/obsidian-export.ts`: + - Resolves the path with `path.resolve` + - Checks `resolved === root || resolved.startsWith(root + path.sep)` + - Returns `null` if the check fails, and the endpoint returns `{ success: false, error: "vaultDir must be inside AGENTMEMORY_EXPORT_ROOT" }` +- Default export is confined to `~/.agentmemory/vault` +- Tests added in `test/obsidian-export.test.ts` for both the custom-but-valid case and the rejection case + +## Known limitations + +`resolveVaultDir()` performs lexical containment only — it does not call `fs.realpathSync` / `fs.lstatSync`. A pre-existing symlink under `AGENTMEMORY_EXPORT_ROOT` that points outside the root can still be written through. Users who allow untrusted processes to create files inside `AGENTMEMORY_EXPORT_ROOT` should additionally run agentmemory inside a sandbox that forbids symlink creation, or file a follow-up issue requesting symlink-aware containment. + +## Workarounds + +Users on affected versions should: +1. **Disable the Obsidian export endpoint** by setting `OBSIDIAN_AUTO_EXPORT=false` (and avoid calling `/agentmemory/obsidian/export` manually) +2. Set `AGENTMEMORY_SECRET` so the endpoint requires bearer auth +3. Upgrade to 0.8.2 + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) + +## Credit + +@eng-pf diff --git a/.github/security-advisories/06-privacy-redaction-incomplete.md b/.github/security-advisories/06-privacy-redaction-incomplete.md new file mode 100644 index 0000000000000000000000000000000000000000..50c35d4b148d765f428112b510981428a2be8e6e --- /dev/null +++ b/.github/security-advisories/06-privacy-redaction-incomplete.md @@ -0,0 +1,60 @@ +# GHSA Draft: Incomplete secret redaction in agentmemory privacy filter + +**Severity:** Medium · **CVSS 3.1:** 6.2 (`AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N`) +**CWE:** [CWE-532 — Insertion of Sensitive Information into Log File](https://cwe.mitre.org/data/definitions/532.html), [CWE-200 — Exposure of Sensitive Information to an Unauthorized Actor](https://cwe.mitre.org/data/definitions/200.html) +**Affected versions:** `< 0.8.2` +**Patched version:** `0.8.2` + +## Summary + +agentmemory's privacy filter (`src/functions/privacy.ts`) is supposed to strip API keys, secrets, and bearer tokens from captured observations before they are stored. The filter used regex patterns to detect common token formats. Three modern token formats were missing from the patterns: + +1. **Bearer tokens** — `Authorization: Bearer ` headers were not matched, so any captured HTTP request or response that included an Authorization header flowed into the memory store verbatim. +2. **OpenAI project keys** — `sk-proj-*` (the dominant OpenAI API key format since mid-2024) was not matched. The existing `sk-[A-Za-z0-9]{20,}` pattern only caught the legacy format. +3. **GitHub fine-grained service/user tokens** — `ghs_*` and `ghu_*` were not matched. The existing `ghp_[A-Za-z0-9]{36}` pattern only caught personal access tokens. + +## Impact + +agentmemory's README explicitly claimed "Privacy first — API keys, secrets, and `` tags are stripped before anything is stored." That claim was **false** for three common token formats. + +Users relying on the privacy filter to protect their captured observations had a false sense of security. Tokens matching these three patterns would: + +1. Be captured by `PostToolUse` hooks alongside the rest of the tool output +2. Pass through `stripPrivateData()` unmodified +3. Be LLM-compressed and stored in the memory KV +4. Be exposed to any attacker who could reach the `/agentmemory/export` or `/agentmemory/smart-search` endpoints +5. Be included in Obsidian exports, mesh syncs, and CLAUDE.md bridge writes + +When chained with advisory #03 (default `0.0.0.0` binding), this meant network-adjacent attackers could retrieve captured Bearer tokens, OpenAI keys, and GitHub service tokens from the memory store. + +## Patches + +Fixed in **0.8.2**: + +New regex patterns added to `SECRET_PATTERN_SOURCES` in `src/functions/privacy.ts`: + +```ts +/Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi, +/sk-proj-[A-Za-z0-9\-_]{20,}/g, +/(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}/g, +/gh[pus]_[A-Za-z0-9]{36,}/g, +``` + +Three new unit tests in `test/privacy.test.ts` verify each format is now stripped. + +## Workarounds + +Users on affected versions should: +1. Avoid having agents read files or API responses containing these token formats +2. Use the `` tag around any block containing secrets — that filter was not affected +3. Set `AGENTMEMORY_SECRET` to restrict API access +4. Upgrade to 0.8.2 + +## References + +- Fix PR: [#108](https://github.com/rohitg00/agentmemory/pull/108) +- Commit: [`cbaaf4f`](https://github.com/rohitg00/agentmemory/commit/cbaaf4f) + +## Credit + +@eng-pf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..ed53c6da9470b353258f94db3d7d9e5d7141730a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,70 @@ +name: CI + +# `paths-ignore` keeps doc-only / website / README / CHANGELOG churn from +# burning runner minutes. Source / config / workflow changes always run. +# `workflow_dispatch` gives a manual re-run button for flake debugging. +on: + push: + branches: [main] + paths-ignore: + - "README.md" + - "CHANGELOG.md" + - "AGENTS.md" + - "ROADMAP.md" + - "website/**" + - "docs/**" + - "assets/**" + - "deploy/**/README.md" + - "**/*.md" + - "**/*.mdx" + pull_request: + branches: [main] + paths-ignore: + - "README.md" + - "CHANGELOG.md" + - "AGENTS.md" + - "ROADMAP.md" + - "website/**" + - "docs/**" + - "assets/**" + - "deploy/**/README.md" + - "**/*.md" + - "**/*.mdx" + workflow_dispatch: + +# Cancel in-flight PR runs when a force-push lands. Keep push runs to +# protect against partial state on main. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + # Don't bail the whole matrix on one cell's failure — we want to + # see whether the same failure reproduces across OSes (e.g. + # whether a flake is platform-specific or universal). + fail-fast: false + matrix: + # Windows held back: test/obsidian-export.test.ts has hardcoded + # POSIX paths (`/tmp/...`) that fail on D:\ drive runners. + # src/functions/obsidian-export.ts needs os.tmpdir() + path.join + # rework before Windows can be added back. Tracked as follow-up. + os: [ubuntu-latest, macos-latest] + node-version: [20, 22] + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-node@v6 + with: + node-version: ${{ matrix.node-version }} + # Two-step install: generate a lockfile in-runner with + # --package-lock-only, then install from it with `npm ci`. + # Lockfiles are gitignored at the repo level. + - run: npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund + - run: npm ci --legacy-peer-deps --no-audit --no-fund + - run: npm run build + - run: npm run skills:check + - run: npm test diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..000033998d0bd8f8bb5550fba0cfc1d4839773f0 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,124 @@ +name: Publish to npm + +on: + release: + types: [published] + workflow_dispatch: + inputs: + packages: + description: "Packages to publish (comma-separated: agentmemory,mcp,fs-watcher)" + required: false + default: "agentmemory,mcp,fs-watcher" + +# Workflow-level permissions stay minimal — only `contents: read` +# is required to check out the repo. `id-token: write` is granted on +# the publish job for npm's --provenance Sigstore OIDC mint. +permissions: + contents: read + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v6 + with: + # Don't persist the GITHUB_TOKEN to .git/config — the + # publish steps don't push back to the repo, so the token + # only needs to live in memory for this checkout. + persist-credentials: false + + - uses: actions/setup-node@v6 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + # Two-step install: generate a lockfile in-runner with + # --package-lock-only, then install from it with `npm ci`. Gives a + # single deterministic dep graph across build / test / publish + # within one job — important because publish uses `--provenance`. + # Lockfiles are gitignored at the repo level. + - run: npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund + - run: npm ci --legacy-peer-deps --no-audit --no-fund + - run: npm run build + - run: npm test + + - name: Publish @agentmemory/agentmemory + run: | + if npm view "@agentmemory/agentmemory@$(node -p "require('./package.json').version")" version >/dev/null 2>&1; then + echo "Version already published, skipping" + else + npm publish --provenance --access public + fi + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Wait for npm registry propagation + run: | + VERSION=$(node -p "require('./package.json').version") + for i in $(seq 1 24); do + if npm view "@agentmemory/agentmemory@$VERSION" version >/dev/null 2>&1; then + echo "Registry propagated after ${i} attempt(s)" + exit 0 + fi + echo "Attempt $i: not yet available, sleeping 5s..." + sleep 5 + done + echo "ERROR: registry never propagated after 2 minutes" >&2 + exit 1 + + - name: Publish @agentmemory/mcp shim + working-directory: packages/mcp + run: | + SHIM_VERSION=$(node -p "require('./package.json').version") + if npm view "@agentmemory/mcp@$SHIM_VERSION" version >/dev/null 2>&1; then + echo "Shim version already published, skipping" + else + npm publish --provenance --access public + fi + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Wait for @agentmemory/mcp registry propagation + working-directory: packages/mcp + run: | + SHIM_VERSION=$(node -p "require('./package.json').version") + for i in $(seq 1 24); do + if npm view "@agentmemory/mcp@$SHIM_VERSION" version >/dev/null 2>&1; then + echo "Shim propagated after ${i} attempt(s)" + exit 0 + fi + echo "Attempt $i: not yet available, sleeping 5s..." + sleep 5 + done + echo "ERROR: shim never propagated after 2 minutes" >&2 + exit 1 + + - name: Publish @agentmemory/fs-watcher connector + working-directory: integrations/filesystem-watcher + run: | + FSW_VERSION=$(node -p "require('./package.json').version") + if npm view "@agentmemory/fs-watcher@$FSW_VERSION" version >/dev/null 2>&1; then + echo "fs-watcher version already published, skipping" + else + npm publish --provenance --access public + fi + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Wait for @agentmemory/fs-watcher registry propagation + working-directory: integrations/filesystem-watcher + run: | + FSW_VERSION=$(node -p "require('./package.json').version") + for i in $(seq 1 24); do + if npm view "@agentmemory/fs-watcher@$FSW_VERSION" version >/dev/null 2>&1; then + echo "fs-watcher propagated after ${i} attempt(s)" + exit 0 + fi + echo "Attempt $i: not yet available, sleeping 5s..." + sleep 5 + done + echo "ERROR: fs-watcher never propagated after 2 minutes" >&2 + exit 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c995e1dd91e7f364780ac483371603797bbca507 --- /dev/null +++ b/.gitignore @@ -0,0 +1,53 @@ +node_modules/ +dist/ +*.tsbuildinfo + +.env +.env.* +!.env.example + +*.log +.DS_Store +.claude/ + +plugin/scripts/*.map +plugin/scripts/*.d.mts +data/ +!eval/data/ +!eval/data/** +data-*/ +agentmemory-debug/ +.gstack/ + +# Lock files — never commit (see feedback_no_lockfiles memory) +package-lock.json +pnpm-lock.yaml +yarn.lock +integrations/hermes/__pycache__/ + +# Eval reports (transient; published scorecards live in docs/benchmarks/) +eval/reports/ +# LongMemEval download is 278MB; fetched on demand +eval/data/longmemeval/ + +# Python virtual environment and caches +.venv/ +venv/ +ENV/ +__pycache__/ +*.pyc +*.pyo +*.pyd +.pytest_cache/ +.mypy_cache/ + +# Large files +assets/ +*.mp4 +*.png +*.gif +*.jpg +*.jpeg + + + diff --git a/.playwright-mcp/page-2026-06-08T23-28-16-016Z.yml b/.playwright-mcp/page-2026-06-08T23-28-16-016Z.yml new file mode 100644 index 0000000000000000000000000000000000000000..fe39bf84427870d742584781c4ee8c75082e080c --- /dev/null +++ b/.playwright-mcp/page-2026-06-08T23-28-16-016Z.yml @@ -0,0 +1,35 @@ +- generic [active] [ref=e1]: + - generic [ref=e2]: + - link "Open dashboard" [ref=e3] [cursor=pointer]: + - /url: "#dashboard" + - heading "agentmemory" [level=1] [ref=e4] + - generic [ref=e5]: v0.9.8 + - generic [ref=e6]: + - generic [ref=e7]: Tue, Jun 9, 2026 + - button "DARK" [ref=e8] [cursor=pointer] + - generic [ref=e9]: live updates off + - generic [ref=e10]: + - button "Dashboard" [ref=e11] [cursor=pointer] + - button "Graph" [ref=e12] [cursor=pointer] + - button "Memories" [ref=e13] [cursor=pointer] + - button "Timeline" [ref=e14] [cursor=pointer] + - button "Sessions" [ref=e15] [cursor=pointer] + - button "Lessons" [ref=e16] [cursor=pointer] + - button "Actions" [ref=e17] [cursor=pointer] + - button "Crystals" [ref=e18] [cursor=pointer] + - button "Audit" [ref=e19] [cursor=pointer] + - button "Activity" [ref=e20] [cursor=pointer] + - button "Profile" [ref=e21] [cursor=pointer] + - button "Replay" [ref=e22] [cursor=pointer] + - generic [ref=e24]: Loading dashboard... + - contentinfo [ref=e25]: + - generic [ref=e26]: agentmemory viewer · loading... + - generic [ref=e27]: · + - link "github" [ref=e28] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory + - generic [ref=e29]: · + - link "docs" [ref=e30] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory#readme + - generic [ref=e31]: · + - link "report issue →" [ref=e32] [cursor=pointer]: + - /url: "#" \ No newline at end of file diff --git a/.playwright-mcp/page-2026-06-08T23-35-49-143Z.yml b/.playwright-mcp/page-2026-06-08T23-35-49-143Z.yml new file mode 100644 index 0000000000000000000000000000000000000000..ee70aacb0423bbae7448f9c7f6095f0027f647f4 --- /dev/null +++ b/.playwright-mcp/page-2026-06-08T23-35-49-143Z.yml @@ -0,0 +1,40 @@ +- generic [active] [ref=e1]: + - generic [ref=e2]: + - link "Open dashboard" [ref=e3] [cursor=pointer]: + - /url: "#dashboard" + - heading "agentmemory" [level=1] [ref=e4] + - generic [ref=e5]: v0.9.8 + - generic [ref=e6]: + - generic [ref=e7]: Tue, Jun 9, 2026 + - button "DARK" [ref=e8] [cursor=pointer] + - generic [ref=e9]: live updates off + - generic [ref=e10]: + - button "Dashboard" [ref=e11] [cursor=pointer] + - button "Graph" [ref=e12] [cursor=pointer] + - button "Memories" [ref=e13] [cursor=pointer] + - button "Timeline" [ref=e14] [cursor=pointer] + - button "Sessions" [ref=e15] [cursor=pointer] + - button "Lessons" [ref=e16] [cursor=pointer] + - button "Actions" [ref=e17] [cursor=pointer] + - button "Crystals" [ref=e18] [cursor=pointer] + - button "Audit" [ref=e19] [cursor=pointer] + - button "Activity" [ref=e20] [cursor=pointer] + - button "Profile" [ref=e21] [cursor=pointer] + - button "Replay" [ref=e22] [cursor=pointer] + - button "1 off Feature flags — click to expand" [ref=e24] [cursor=pointer]: + - generic [ref=e25]: 1 off + - generic [ref=e26]: Feature flags + - generic [ref=e27]: — click to expand + - generic [ref=e28]: ▼ + - generic [ref=e30]: Loading dashboard... + - contentinfo [ref=e31]: + - generic [ref=e32]: agentmemory viewer · v0.9.8 + - generic [ref=e33]: · + - link "github" [ref=e34] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory + - generic [ref=e35]: · + - link "docs" [ref=e36] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory#readme + - generic [ref=e37]: · + - link "report issue →" [ref=e38] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory/issues/new?title=%5Bviewer%5D%20&body=**Version%3A**%200.9.8%0A**Provider%3A**%20llm%0A**Embedding%3A**%20gemini%0A**Flags%3A**%20GRAPH_EXTRACTION_ENABLED%3Don%2C%20CONSOLIDATION_ENABLED%3Don%2C%20AGENTMEMORY_AUTO_COMPRESS%3Doff%0A**User%20agent%3A**%20Mozilla%2F5.0%20(Windows%20NT%2010.0%3B%20Win64%3B%20x64)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F149.0.0.0%20Safari%2F537.36%0A%0A%23%23%23%20What%20went%20wrong%0A%0A(describe%20the%20issue)%0A%0A%23%23%23%20Steps%20to%20reproduce%0A%0A1.%20%0A2.%20%0A3.%20%0A \ No newline at end of file diff --git a/.playwright-mcp/page-2026-06-09T00-16-38-317Z.yml b/.playwright-mcp/page-2026-06-09T00-16-38-317Z.yml new file mode 100644 index 0000000000000000000000000000000000000000..ee70aacb0423bbae7448f9c7f6095f0027f647f4 --- /dev/null +++ b/.playwright-mcp/page-2026-06-09T00-16-38-317Z.yml @@ -0,0 +1,40 @@ +- generic [active] [ref=e1]: + - generic [ref=e2]: + - link "Open dashboard" [ref=e3] [cursor=pointer]: + - /url: "#dashboard" + - heading "agentmemory" [level=1] [ref=e4] + - generic [ref=e5]: v0.9.8 + - generic [ref=e6]: + - generic [ref=e7]: Tue, Jun 9, 2026 + - button "DARK" [ref=e8] [cursor=pointer] + - generic [ref=e9]: live updates off + - generic [ref=e10]: + - button "Dashboard" [ref=e11] [cursor=pointer] + - button "Graph" [ref=e12] [cursor=pointer] + - button "Memories" [ref=e13] [cursor=pointer] + - button "Timeline" [ref=e14] [cursor=pointer] + - button "Sessions" [ref=e15] [cursor=pointer] + - button "Lessons" [ref=e16] [cursor=pointer] + - button "Actions" [ref=e17] [cursor=pointer] + - button "Crystals" [ref=e18] [cursor=pointer] + - button "Audit" [ref=e19] [cursor=pointer] + - button "Activity" [ref=e20] [cursor=pointer] + - button "Profile" [ref=e21] [cursor=pointer] + - button "Replay" [ref=e22] [cursor=pointer] + - button "1 off Feature flags — click to expand" [ref=e24] [cursor=pointer]: + - generic [ref=e25]: 1 off + - generic [ref=e26]: Feature flags + - generic [ref=e27]: — click to expand + - generic [ref=e28]: ▼ + - generic [ref=e30]: Loading dashboard... + - contentinfo [ref=e31]: + - generic [ref=e32]: agentmemory viewer · v0.9.8 + - generic [ref=e33]: · + - link "github" [ref=e34] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory + - generic [ref=e35]: · + - link "docs" [ref=e36] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory#readme + - generic [ref=e37]: · + - link "report issue →" [ref=e38] [cursor=pointer]: + - /url: https://github.com/rohitg00/agentmemory/issues/new?title=%5Bviewer%5D%20&body=**Version%3A**%200.9.8%0A**Provider%3A**%20llm%0A**Embedding%3A**%20gemini%0A**Flags%3A**%20GRAPH_EXTRACTION_ENABLED%3Don%2C%20CONSOLIDATION_ENABLED%3Don%2C%20AGENTMEMORY_AUTO_COMPRESS%3Doff%0A**User%20agent%3A**%20Mozilla%2F5.0%20(Windows%20NT%2010.0%3B%20Win64%3B%20x64)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F149.0.0.0%20Safari%2F537.36%0A%0A%23%23%23%20What%20went%20wrong%0A%0A(describe%20the%20issue)%0A%0A%23%23%23%20Steps%20to%20reproduce%0A%0A1.%20%0A2.%20%0A3.%20%0A \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..a5e3633a6c9f15c632e32004c440fb3706aa652f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,124 @@ +# agentmemory — Agent Instructions + +## Architecture + +agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` — never bypass iii-engine with standalone SQLite or in-process alternatives. + +- **Engine**: iii-sdk (WebSocket to iii-engine on port 49134) +- **State**: File-based SQLite via iii-engine's StateModule (`./data/state_store.db`) +- **Build**: TypeScript → ESM via tsdown, output to `dist/` +- **Test**: vitest (`npm test` excludes integration tests) + +## Consistency Rules + +**When adding or removing MCP tools, you MUST update ALL of the following:** +1. `src/mcp/tools-registry.ts` — tool definition + `getAllTools()` array +2. `src/mcp/server.ts` — handler case in the `mcp::tools::call` switch +3. `src/triggers/api.ts` — REST endpoint registration +4. `src/index.ts` — function registration + endpoint count in the log line +5. `test/mcp-standalone.test.ts` — tool count assertion +6. `README.md` — tool counts (search for "MCP tools") +7. `plugin/.claude-plugin/plugin.json` — tool count in description +8. `plugin/plugin.json` and `plugin/.mcp.copilot.json` (when present) — tool count or MCP exposure + +**When adding REST endpoints, you MUST update:** +1. `src/triggers/api.ts` — endpoint registration +2. `src/index.ts` — endpoint count in the log line +3. `README.md` — endpoint count (search for "REST endpoints" and "endpoints on port") + +**When bumping version, you MUST update ALL of the following:** +1. `package.json` — version field +2. `src/version.ts` — VERSION constant and type union +3. `src/types.ts` — ExportData version union +4. `src/functions/export-import.ts` — supportedVersions set +5. `test/export-import.test.ts` — version assertion +6. `plugin/.claude-plugin/plugin.json` — version field +7. `plugin/plugin.json` (when present) — version field + +**When adding new KV scopes:** +1. `src/state/schema.ts` — add to the KV object +2. `src/types.ts` — add the corresponding interface + +**When adding new audit operations:** +1. `src/types.ts` — add to AuditEntry.operation union type + +## Code Patterns + +### Function Registration +```typescript +sdk.registerFunction( + "mem::your-function", + async (data: { ... }) => { + // validate inputs + // do work via kv.get/kv.set/kv.list + // record audit via recordAudit() + return { success: true, ... }; + }, +); +``` + +### REST Endpoint Registration +```typescript +sdk.registerFunction("api::your-endpoint", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record; + // validate + whitelist fields (never pass raw body to sdk.trigger) + const result = await sdk.trigger({ + function_id: "mem::your-function", + payload: { ... }, + }); + return { status_code: 200, body: result }; +}); +sdk.registerTrigger({ + type: "http", + function_id: "api::your-endpoint", + config: { api_path: "/agentmemory/your-path", http_method: "POST" }, +}); +``` + +### MCP Tool Handler +```typescript +case "memory_your_tool": { + // validate args with typeof checks + // parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean) + const result = await sdk.trigger({ + function_id: "mem::your-function", + payload: { ... }, + }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; +} +``` + +### Hook Scripts +Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout: + +- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time. +- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix. + +## Coding Standards + +- TypeScript, ESM only (`"type": "module"`) +- No code comments explaining WHAT — use clear naming instead +- Use `fingerprintId()` for content-addressable dedup, `generateId()` for unique IDs +- Parallel operations where possible (`Promise.all` for independent kv writes/reads) +- Input validation at system boundaries (MCP handlers, REST endpoints) +- REST endpoints must whitelist fields — never pass raw request body to `sdk.trigger()` +- Use `recordAudit()` for state-changing operations +- Timestamps: capture once with `new Date().toISOString()` and reuse + +## Testing + +- All tests must pass before PR: `npm test` (950+ tests) +- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list` +- Test files go in `test/` with `.test.ts` extension +- Follow existing patterns in `test/crystallize.test.ts` for function tests + +## Current Stats (v0.9.16) + +- 53 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) +- 128 REST endpoints +- 6 MCP resources, 3 MCP prompts +- 12 hooks, 4 skills +- 50+ iii functions +- 950+ tests diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..3b5188fa98a007fbb30fe7d26bd220087c722668 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,1119 @@ +# Changelog + +All notable changes to agentmemory will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.9.27] — 2026-06-07 + +Wave release closing several breaking regressions reported against v0.9.26, plus an agent-scope isolation security fix, an iii version-pin audit fix, and a benchmark scorecard correction. No breaking changes; drop-in upgrade. + +### Security + +- **`AGENTMEMORY_AGENT_SCOPE=isolated` not enforced on `mem::search` / `POST /agentmemory/search` / `memory_recall` / `recall_context`** ([#817](https://github.com/rohitg00/agentmemory/issues/817)). PR #654's isolation work covered smart-search, `/memories`, `/observations`, and `/sessions` but missed the BM25-only recall path. An isolated worker booted with `AGENT_ID=B` could read agent A's memories via the standard MCP `memory_recall` tool. `mem::search` now applies the same filter as smart-search (wildcard `agentId: "*"` bypasses, explicit `agentId` pins, isolated mode falls back to env `AGENT_ID`). `recall_context` prompt also filters its kv.list memory feed by active agent. Fail-closed: if isolated mode is on and no agent id resolves from any source, the call throws rather than dropping the filter. + +### Fixed + +- **`/graph/query` and `/graph/stats` timed out with `"Invocation stopped"` on large existing corpora** ([#814](https://github.com/rohitg00/agentmemory/issues/814), [PR #816](https://github.com/rohitg00/agentmemory/pull/816)). The v0.9.25 fix from #753 paginated the response but the unbounded `kv.list` + `kv.list` pair still ran on every call. At 75K+ nodes the response payload exceeded the iii heartbeat budget and the worker was declared dead before the new wall-clock timer could fire. Refactored `mem::graph-extract` to maintain three side-indexes (`graphNameIndex`, `graphEdgeKey`, `graphNodeDegree`) so every extract path is O(1), never O(n). The hot path now reads exclusively from a precomputed top-degree snapshot updated inline on every extract. Same `kv.list` bottleneck was also blocking `mem::graph-extract` on every observation capture, so the fix immediately speeds up the observation pipeline too. +- **All data lost on `agentmemory stop` followed by restart** ([#843](https://github.com/rohitg00/agentmemory/issues/843)). `runStop()` killed the iii engine first, then the worker. The worker's shutdown handler flushes BM25/vector snapshots and audit rows via `indexPersistence.save() -> kv.set() -> state::set`, which all routed through an iii engine that was already dead. Stop order inverted: worker first with a bumped 5s SIGTERM grace (gives a large index a real chance to commit), engine second. The "Memories persisted to disk" message now reflects actual disk state. +- **`mem::graph-snapshot-rebuild` and `mem::graph-reset` heartbeat-crashed on legacy >25K-node corpora** ([#825](https://github.com/rohitg00/agentmemory/issues/825)). Both endpoints called `kv.list` up front. At 75K nodes the response payload blocks the event loop in `JSON.parse` and the iii heartbeat starves before any wall-clock budget timer can fire. `mem::graph-snapshot-rebuild` now refuses pre-flight when no prior snapshot exists, returning `{ legacyCorpus: true }` with operator guidance unless an explicit `force: true` flag is set. `mem::graph-reset` no longer enumerates anything: it writes an empty snapshot stamped with `resetAt` and returns. Legacy rows stay as on-disk orphans but post-reset `mem::graph-extract` calls compare each name-index hit's `createdAt` against `resetAt`, so older rows are treated as not-found and a fresh node is written instead of silently reconnecting to a pre-reset orphan. +- **Multi-instance port collisions on one host** ([#750](https://github.com/rohitg00/agentmemory/issues/750), [PR #815](https://github.com/rohitg00/agentmemory/pull/815)). `--port N` only relocated REST + viewer; streams (3112) and iii engine (49134) stayed hardcoded so a second daemon collided on those WS ports regardless of `--port`. `loadConfig()` now derives streams = REST+1 and engine = REST+46023 (so the canonical 3111 → 3112/49134 default is unchanged, and `--port 3211` → 3212/49234). New `--instance N` shortcut picks a 100-port block: `--instance 1` → 3211/3212/3213/49234. Per-port env overrides (`III_STREAM_PORT`, `III_ENGINE_PORT`, `III_ENGINE_URL`) still win. +- **iii console install pulled latest engine instead of the pinned v0.11.2** (audit). `III_CONSOLE_INSTALL_CMD` ran `curl -fsSL https://install.iii.dev/iii/main/install.sh | sh` with no version pin. A fresh first-run prompt could install a console build that talks a different protocol than the engine agentmemory pins. The install script reads a `VERSION` env var (`engine_version="${VERSION:-}"` in install.sh), so the command now passes `VERSION=${IIPINNED_VERSION}`. Render path is platform-aware too: Windows users get a PowerShell-friendly hint instead of a POSIX command they can't run. Mismatch error text updated from "reinstall the latest binary" to reference the pinned version explicitly. + +### Docs + +- **Corrected coding-agent-life-v1 P@5 numbers in the published scorecard** ([#796](https://github.com/rohitg00/agentmemory/issues/796), [PR #805](https://github.com/rohitg00/agentmemory/pull/805)). The original scorecard reported P@5 = 0.578 / 0.267, generated before [PR #562](https://github.com/rohitg00/agentmemory/pull/562) changed the P@K denominator from `topK.length` to `k`. On the current formula those numbers are mathematically impossible (math ceiling at K=5 on this corpus is 0.240). Re-scored on v0.9.26: hybrid 0.240 / R@5 1.000, grep 0.227 / R@5 0.967. Reframed lift as recall + temporal not aggregate precision; aggregate P@5 saturates on a small / single-gold corpus and can't differentiate top-tier adapters. +- **README refresh** ([PR #807](https://github.com/rohitg00/agentmemory/pull/807)). Stats line bumped to 174 files / 1,390+ tests / 258 functions. Corrected hero P@5 numbers. "New in vX.Y.Z" callout block removed since that pattern went stale every release; latest release notes link points at CHANGELOG.md. +- **`import-jsonl` users warned about Claude Code's `cleanupPeriodDays`.** Default 30-day auto-deletion of `~/.claude/projects/*.jsonl` doesn't affect hook-wired installs (each turn lands in iii state while the session is live), but fresh installs on months-old Claude Code histories silently lost anything older than 30 days. README now flags this with three workarounds: cron the import, raise `cleanupPeriodDays`, or wire hooks. + +### Added + +- **`POST /agentmemory/graph/snapshot-rebuild`** — pays the full enumeration cost once on corpora ≤ 25K nodes, persists a top-degree subgraph + aggregate counts, refuses with `{ success: false, tooLarge: true, totalNodes, ceiling }` above the safe ceiling instead of killing the worker. Strict `force: true` boolean check bypasses the legacy-corpus pre-flight refusal. +- **`POST /agentmemory/graph/reset`** — clean-restart escape hatch for legacy corpora. Enumeration-free: writes empty snapshot with `resetAt` epoch marker. Future extracts treat any pre-`resetAt` row as orphan via `createdAt` comparison. +- **`--instance N` CLI flag** — multi-daemon convenience. Picks a 100-port block off the 3111 base. Max N=50. +- **`GraphSnapshot.topDegrees`** — synchronous degree lookup keyed by nodeId so re-ranking after edge writes runs sync over numbers instead of async kv.get inside the sort comparator. +- **`GraphSnapshot.resetAt`** — ISO timestamp set by `mem::graph-reset`. Drives post-reset orphan detection in extract. +- **`GraphQueryResult.fromSnapshot`** + **`GraphQueryResult.warning`** — response fields the viewer can use to surface "served from cache" or "rebuild needed" banners instead of opaque 500s. + +### Changed + +- **REST endpoint count: 126 → 128**. `POST /agentmemory/graph/snapshot-rebuild` and `POST /agentmemory/graph/reset` added. +- **`mem::graph-stats`** now reads exclusively from the snapshot. Returns `{ ..., fromSnapshot, warning }` envelope when snapshot is absent; never returns a 500. +- **`mem::graph-query` empty-body / nodeType-only path** reads exclusively from the snapshot. `startNodeId` / `query` paths keep the live enumeration behind a 6s budget with snapshot-backed fallback on rejection. +- **`mem::search` over-fetch** triggers when agentId filtering is active (not just project/cwd). Without it, isolated-mode pages were silently underfilled when same-agent matches ranked below cross-agent ones. + +### Known limitations + +- `mem::graph-query` BFS (`startNodeId`) and text-search (`query`) paths still call `kv.list` and degrade past ~25K nodes on fresh corpora ([#828](https://github.com/rohitg00/agentmemory/issues/828)). The hot path stays safe (snapshot-only). A per-node adjacency index is the right next fix; deferred to the structured graph migration milestone ([#309](https://github.com/rohitg00/agentmemory/issues/309)). +- `/agentmemory:forget` skill still calls `memory_governance_delete` which only touches `KV.memories` and never observations ([#833](https://github.com/rohitg00/agentmemory/issues/833)). Skill rewrite + new `memory_forget` MCP tool tracked separately. +- `crypto.randomUUID()` global-only on Node <19 ([#715](https://github.com/rohitg00/agentmemory/issues/715)). Drop-in import fix tracked. + +[0.9.27]: https://github.com/rohitg00/agentmemory/compare/v0.9.26...v0.9.27 + +## [0.9.26] — 2026-06-03 + +Hotfix on top of v0.9.25. The first-run boot crashed for users without a persisted index because the load path didn't handle `undefined` returns from iii-state adapters. + +### Fixed + +- **First boot crash: `TypeError: Cannot read properties of undefined (reading 'v')`** ([#797](https://github.com/rohitg00/agentmemory/issues/797)). The sharded index load path (`loadShardedData`) checked `manifest.value !== null` before forwarding to `loadManifestData`. Some iii-state adapters return `undefined` (not `null`) for a missing key, so `undefined !== null` was true and `loadManifestData(undefined, ...)` immediately threw on `manifest.v`. Now treats both `null` and `undefined` (plus non-object values) as "no manifest" and falls through to the legacy load path. Self-healing: the next debounced save rebuilds a fresh manifest, so the crash was already cosmetic for ongoing operation — but it scared every fresh upgrader. Tests cover both undefined and wrong-shape manifest rows. + +[0.9.26]: https://github.com/rohitg00/agentmemory/compare/v0.9.25...v0.9.26 + +## [0.9.25] — 2026-06-03 + +Bug-fix wave closing every breaking regression reported against 0.9.24, plus a feature lane (graph pagination + smart-search followup diagnostic + obsidian-export hardening + sharded index persistence). Eleven issues closed. No breaking changes; drop-in upgrade. + +### Fixed + +- **Cross-provider fallback always 404'd and tripped the circuit breaker** ([#778](https://github.com/rohitg00/agentmemory/issues/778), [PR #791](https://github.com/rohitg00/agentmemory/pull/791)). `createFallbackProvider` copied the primary provider's `model` into every fallback config. With OpenAI primary + Gemini fallback, Gemini was called with `gpt-4o-mini` and 404'd on every call, tripping the circuit breaker and blocking downstream LLM ops. Each fallback now resolves its own env-driven default (`OPENAI_MODEL` / `GEMINI_MODEL` / `ANTHROPIC_MODEL` / `MINIMAX_MODEL` / `OPENROUTER_MODEL`). +- **`import-jsonl` aborted entire batch on legacy session row missing `id`** ([#775](https://github.com/rohitg00/agentmemory/issues/775), [PR #791](https://github.com/rohitg00/agentmemory/pull/791)). Existing-session branch re-keyed on `existing.id` which could be undefined for older rows. `JSON.stringify` dropped the key from the `state::set` payload, the engine returned `missing field \`key\``, and the rejection aborted the whole handler. Now re-keys on `parsed.sessionId` and backfills `existing.id`. +- **`parseSummaryXml` silently dropped summaries wrapped in markdown fences** ([#783](https://github.com/rohitg00/agentmemory/issues/783), [PR #791](https://github.com/rohitg00/agentmemory/pull/791)). DeepSeek / GPT / occasionally Anthropic responses wrap structured XML in ` ```xml ... ``` ` fences with optional conversational text. The raw payload went straight to the tag regex and returned `parse_failed`. New `stripXmlWrappers()` peels markdown fences + pre/postamble; final-merge parse path retries once on failure (matching chunk-level behavior). +- **`sdk.triggerVoid is not a function` on iii-sdk 0.11.2** ([#758](https://github.com/rohitg00/agentmemory/issues/758), [#726](https://github.com/rohitg00/agentmemory/issues/726), [PR #773](https://github.com/rohitg00/agentmemory/pull/773)). iii-sdk 0.11.2 removed `triggerVoid` in favor of `trigger({ action: TriggerAction.Void() })`. Nine call sites still used the removed API; six ran without try/catch and threw `TypeError`, breaking image lifecycle, disk-quota cleanup, vision embeddings, and observation write paths. +- **pi integration recorded every observation as "No content provided"** ([#759](https://github.com/rohitg00/agentmemory/issues/759), [PR #772](https://github.com/rohitg00/agentmemory/pull/772)). pi sent `data.input` / `data.output` but `observe.ts` reads `data.tool_input` / `data.tool_output`. Field-name mismatch left `raw.toolInput` / `raw.toolOutput` undefined; the compress pipeline produced empty observations. +- **Fresh global install refused to boot when PATH iii didn't match the runtime pin** ([#752](https://github.com/rohitg00/agentmemory/issues/752), [PR #774](https://github.com/rohitg00/agentmemory/pull/774)). The hard-pin enforcer told users to overwrite their global iii with v0.11.2, but the v0.11.2 release ships only `iii` (not `iii-init` / `iii-worker`) on some platforms. agentmemory now installs to `~/.agentmemory/bin/` and auto-falls-back to it when PATH iii mismatches the pin. User's existing iii install stays untouched. +- **`mem::obsidian-export` HTTP 500 `[object Object]` on any record missing `id`** ([#729](https://github.com/rohitg00/agentmemory/issues/729), [PR #780](https://github.com/rohitg00/agentmemory/pull/780)). `sanitize(undefined.id)` threw outside the per-record try and escaped the whole handler. Four-layer hardening: id filter, safe-array / safe-string / safe-timestamp normalizers, outer try/catch, fail-safe session sort. +- **Concurrent agent-sdk summarize chunks failed with `too_many_chunks_skipped`** ([#781](https://github.com/rohitg00/agentmemory/issues/781), [PR #782](https://github.com/rohitg00/agentmemory/pull/782)). `AGENTMEMORY_SDK_CHILD` recursion guard mutated `process.env` globally; concurrent chunks under `Promise.all` saw the marker and returned empty. Recursion guard now scoped to `AsyncLocalStorage`; the `process.env` marker stays for cross-process hook inheritance, reference-counted so overlapping calls don't race. +- **Viewer #graph tab blank on large graphs** ([#753](https://github.com/rohitg00/agentmemory/issues/753), [PR #789](https://github.com/rohitg00/agentmemory/pull/789)). `POST /agentmemory/graph/query` with `{}` on an 11k+ node corpus returned HTTP 500 `Invocation stopped`. `graph/query` now accepts `limit` / `offset`, applies a default cap (500) ranked by node degree, restricts page edges to in-page endpoints, and returns `totalNodes` / `totalEdges` / `truncated`. The viewer issues a bounded initial query, distinguishes server-error from empty-corpus, renders an actionable error banner with Retry. + +### Added + +- **Sharded BM25/vector index persistence with manifest commit/rollback** ([#762](https://github.com/rohitg00/agentmemory/issues/762), [PR #764](https://github.com/rohitg00/agentmemory/pull/764), contributed by [@Rokurolize](https://github.com/Rokurolize)). Large BM25/vector snapshots used to save as monolithic strings and failed past the iii state size ceiling. Each snapshot now writes as bounded shards under a generation-scoped prefix, with a manifest published only after all shards commit. Rollback on shard-write failure, fail-closed on length mismatch, legacy snapshot load preserved for downgrade compat. 957 LOC + 25 tests covering rollback / partial-commit / fail-closed paths. +- **Smart-search followup-rate diagnostic** ([#771](https://github.com/rohitg00/agentmemory/issues/771), [PR #786](https://github.com/rohitg00/agentmemory/pull/786)). Disambiguates retrieval bugs from reader bugs. When an agent issues a second `smart-search` within `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS` (default 30s) and the new result set has zero overlap with the prior one, counts as a directional "first results didn't satisfy" signal. OTEL counter `agentmemory.smart_search.followup_within_window_total`, `GET /agentmemory/diagnostics/followup` REST endpoint, `agentmemory status` surface, viewer-source exclusion via `X-Agentmemory-Source: viewer` header. + +### Changed + +- **Dependency bumps + zero `npm audit` vulnerabilities** ([PR #779](https://github.com/rohitg00/agentmemory/pull/779)). `@anthropic-ai/sdk` 0.93 → 0.100.1, `tsdown` 0.20.3 → 0.21.10 (stays on Node 20 floor), `@types/node` 25.7 → 25.9, website `next` 16.2.6 → 16.2.7 + React 19.2.7. `iii-sdk` stays pinned at 0.11.2. Transitive vulns closed via overrides: `qs ^6.15.2`, `ws ^8.21.0`, `protobufjs ^7.5.8`. `npm audit` root + website: 8 → **0**. +- **REST endpoint count: 125 → 126** (new `/agentmemory/diagnostics/followup`). + +### Infrastructure + +- 1379 tests passing (up from 1314 in v0.9.24). 13 new test files covering the regressions + features above. +- Removed `website/package-lock.json` from git tracking; root `.gitignore` already forbade lockfiles. + +[0.9.25]: https://github.com/rohitg00/agentmemory/compare/v0.9.24...v0.9.25 + +## [0.9.24] — 2026-05-29 + +Hotfix on top of v0.9.23. Two bugs surfaced in the first hour after v0.9.23 hit npm: + +### Fixed + +- **`agentmemory --version` silently launched the server instead of printing the version string**. `-v` flag was reserved by `--verbose`, and no `--version` literal was handled — falling through to the default `start` command. Now `--version` (and `-V` capital, per POSIX convention) prints `VERSION` and exits 0 before any side effects (engine boot, dir mkdir, env loading). +- **iii-engine version pin was warn-only, not enforced**. When the engine on `PATH` didn't match agentmemory's pinned version (currently `v0.11.2`), the worker still booted against the mismatched engine and crashed at runtime with cryptic `state::list not found` (v0.13.0) or sandbox-everything traps (v0.11.6). `warnIfEngineVersionMismatch` renamed to `enforceEngineVersionPin` — now `p.log.error`s with the downgrade command and `process.exit(1)`. Override escape hatch via `AGENTMEMORY_III_VERSION=` env unchanged (already redefines `IIPINNED_VERSION` upstream so the comparison passes for users who knowingly run against a different engine). + +[0.9.24]: https://github.com/rohitg00/agentmemory/compare/v0.9.23...v0.9.24 + +## [0.9.23] — 2026-05-28 + +Bug-fix + integration wave. GitHub Copilot CLI joins the supported agent matrix with plugin + hooks + MCP coverage. Three silent DX bugs fixed end-to-end: graph extraction never fired on session end, `agentmemory status` reported zero memories, consolidation defaulted off even with an LLM provider configured. Five additional adapters and a clearer local-LLM story for Ollama / LM Studio users. `agentmemory connect` now points users at `npx skills add` for the native-skills install path (50+ agents). + +### Added + +- **GitHub Copilot CLI** ([PR #534](https://github.com/rohitg00/agentmemory/pull/534)). Full first-class support: `plugin/plugin.json` manifest, `hooks.copilot.json` lifecycle hooks for all 11 Copilot events with camelCase payload normalization, `agentmemory connect copilot-cli` MCP path, first-run onboarding default-select via `COPILOT_CLI` / `COPILOT_AGENT_SESSION_ID` env detection, Windows-safe `cmd.exe /d /s /c npx` wrapper. Standalone MCP transport now speaks LSP-style `Content-Length` framed JSON-RPC alongside the existing newline-delimited form so Copilot's stdio init handshake works. +- **Five new MCP adapters** ([PR #677](https://github.com/rohitg00/agentmemory/pull/677)). Warp, Cline, Continue, Zed, and Droid. `createJsonMcpAdapter` extended with `wrapperKey` (Zed uses `context_servers` instead of `mcpServers`) and `extraEntryFields` (Droid requires `type: "stdio"`). `ADAPTERS` count: 11 → 17. +- **`/agentmemory/graph/build` endpoint** ([PR #698](https://github.com/rohitg00/agentmemory/pull/698)). Backfills the knowledge graph from existing compressed observations across every session in configurable batches. Wires up the viewer's "Build Graph" button that previously returned 404. +- **11 README translations + language picker** ([PR #675](https://github.com/rohitg00/agentmemory/pull/675)). zh-CN, zh-TW, ja-JP, ko-KR, es-ES, pt-BR, fr-FR, de-DE, ru-RU, tr-TR, hi-IN. +- **`npx skills add` hint in connect output** ([PR #709](https://github.com/rohitg00/agentmemory/pull/709)). After a successful `agentmemory connect `, the CLI now prints the matching `npx skills add rohitg00/agentmemory -y` command so users get the native-skills install alongside MCP wiring. The [`skills`](https://npmjs.com/package/skills) CLI covers 50+ agents including the 5 added in PR #677. README "Other agents" section gains a dedicated subsection explaining the two-step pattern (`connect` writes MCP config, `skills add` installs the 8 SKILL.md files into the agent's native skill directory). + +### Changed + +- **Consolidation auto-enables when an LLM provider is configured** ([PR #696](https://github.com/rohitg00/agentmemory/pull/696), closes [#612](https://github.com/rohitg00/agentmemory/discussions/612)). `CONSOLIDATION_ENABLED` defaulted to `false`, so users with a working provider got compression + summarization but zero graph nodes / crystals / lessons. Now defaults `true` whenever any of `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `OPENROUTER_API_KEY` / `GEMINI_API_KEY` / `GOOGLE_API_KEY` / `MINIMAX_API_KEY` / `OPENAI_BASE_URL` is set, or `AGENTMEMORY_PROVIDER=agent-sdk`. Explicit `=false` / `AGENTMEMORY_PROVIDER=noop` still opt out. `OPENAI_API_KEY_FOR_LLM=false` honored (key scoped to embeddings). +- **Fire-and-forget telemetry hooks** ([PR #688](https://github.com/rohitg00/agentmemory/pull/688), closes [#573](https://github.com/rohitg00/agentmemory/issues/573)). Nine telemetry-only hooks (notification, post-tool-failure, post-tool-use, prompt-submit, stop, session-end, subagent-start, subagent-stop, task-completed) switched to unawaited `fetch(...).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()` (1500ms for the multi-fetch `stop` + `session-end` hooks). No longer blocks Claude Code's next-prompt boundary on every assistant turn. +- **Observability defaults tamed** ([PR #686](https://github.com/rohitg00/agentmemory/pull/686), closes [#519](https://github.com/rohitg00/agentmemory/issues/519)). `iii-config.yaml` defaults: `sampling_ratio: 0.1`, `logs_console_output: false`. `findIiiConfig()` precedence reversed so `AGENTMEMORY_III_CONFIG` env > cwd > `~/.agentmemory/iii-config.yaml` > bundled. + +### Fixed + +- **Graph extraction never fires automatically** ([PR #698](https://github.com/rohitg00/agentmemory/pull/698), closes [#666](https://github.com/rohitg00/agentmemory/issues/666)). `event::session::stopped` listens on `agentmemory.session.stopped` but nothing in the codebase ever published that topic. `api::session::end` now directly calls `sdk.triggerVoid("event::session::stopped", { sessionId })` (try/catch guarded so a fan-out error doesn't fail the HTTP response). Knowledge graphs now materialize automatically when sessions end. +- **`agentmemory status` shows Memories/Observations = 0** ([PR #698](https://github.com/rohitg00/agentmemory/pull/698), closes [#666](https://github.com/rohitg00/agentmemory/issues/666)). CLI fetched `/agentmemory/export` for counts but that endpoint times out (>5s) on iii-engine's file-based KV under concurrent `kv.list()`. Switched to `/memories?count=true` (count-only, constant-time) + sum of `sessions[].observationCount`. +- **Hooks send full filesystem path as `project` instead of repo basename** ([PR #687](https://github.com/rohitg00/agentmemory/pull/687), closes [#474](https://github.com/rohitg00/agentmemory/issues/474)). Native sessions, replay-import, and `memory_lesson_save` all use repo basename — the path/basename mismatch silently filtered out the bulk of relevant lessons from auto-injected context. New `resolveProject(cwd?)` helper: `AGENTMEMORY_PROJECT_NAME` env > `git rev-parse --show-toplevel` basename > `basename(cwd)`. Applied to 9 hooks. +- **Cross-project memory leakage** ([PR #662](https://github.com/rohitg00/agentmemory/pull/662)). Memories created in one project leaking into recall on another. Wildcard guard pattern `(!project || !m.project || m.project === project)` preserves backward-compat for legacy unscoped memories while scoping new ones strictly. +- **Graph parser tolerates reordered XML attributes** ([PR #685](https://github.com/rohitg00/agentmemory/pull/685), closes [#635](https://github.com/rohitg00/agentmemory/issues/635)). Order-dependent regex replaced with order-independent `parseAttrs` helper. Self-closing trailing-`/` handling preserved. +- **Defensive null guards on `Memory.sessionIds`** ([PR #684](https://github.com/rohitg00/agentmemory/pull/684)). Older exports + hand-edited dumps can omit this field; now treated as empty array on read. +- **Vector index Buffer slice metadata round-trip** ([PR #683](https://github.com/rohitg00/agentmemory/pull/683), closes [#587](https://github.com/rohitg00/agentmemory/issues/587), [#584](https://github.com/rohitg00/agentmemory/issues/584)). `byteOffset` + `byteLength` preserved on `Buffer.from` and `Float32Array` construction so base64 round-trips don't corrupt vectors stored as slices. +- **Slots HTTP triggers return 503 not 500** ([PR #682](https://github.com/rohitg00/agentmemory/pull/682), closes [#678](https://github.com/rohitg00/agentmemory/issues/678)). Feature-flag-disabled responses now use the documented 503 shape with `enableHow` + `docsHref`. `.env` propagation fixed (now reads via `getEnvVar()` not raw `process.env`). +- **`agentmemory doctor` points to correct iii install URL** ([PR #681](https://github.com/rohitg00/agentmemory/pull/681)). +- **Separate `OPENAI_EMBEDDING_BASE_URL` + `OPENAI_EMBEDDING_API_KEY`** ([PR #503](https://github.com/rohitg00/agentmemory/pull/503)). Lets users route embeddings and LLM calls to different OpenAI-compatible endpoints (e.g. cloud OpenAI for embeddings + local LM Studio for LLM, or vice versa). +- **Viewer Memories tab sorts newest first** ([PR #701](https://github.com/rohitg00/agentmemory/pull/701), closes [#674](https://github.com/rohitg00/agentmemory/issues/674)). Memories list rendered in KV-insertion order, hiding just-saved entries at the bottom of long lists. `loadMemories()` now sorts on `createdAt` desc (fallback `updatedAt`) before items reach state — matches the `localeCompare` pattern Sessions / Metrics tabs already use. + +### Docs + +- **Local-LLM section in README** ([PR #697](https://github.com/rohitg00/agentmemory/pull/697), closes [#671](https://github.com/rohitg00/agentmemory/discussions/671)). Dedicated "Local models (Ollama / LM Studio / vLLM)" subsection with copy-paste configs, model-pick table (qwen2.5-coder:7b, llama3.2:3b, mistral:7b-instruct, deepseek-r1:7b), and reasoning-model empty-content callout. Existing OpenAI-compatible support was buried in a one-line env comment. +- **Three pipeline layers, not three primitives** ([PR #690](https://github.com/rohitg00/agentmemory/pull/690)). Website + README copy: the three primitives are worker / function / trigger (iii). HOOKS / RECALL / CONSOLIDATE are pipeline layers. Section anchor renamed `#primitives` → `#stack` to match the nav label. + +### Infrastructure + +- Hook scripts now bundle per-entry instead of sharing chunks, so `plugin/scripts/_project-*.mjs` hashed artifacts no longer churn the diff on every build. +- `AGENTS.md` "Hook Scripts" section documents the two patterns (context-injecting vs telemetry-only) and the 500ms / 1500ms exit-delay rule for single vs multi-fetch hooks. +- Test suite: 1271 → 1291 (+20 new tests covering project basename resolver, fire-and-forget wiring, consolidation default behavior, session-end → graph extraction, the graph-build endpoint, and the viewer memories sort). + +[0.9.23]: https://github.com/rohitg00/agentmemory/compare/v0.9.22...v0.9.23 + +## [0.9.22] — 2026-05-26 + +Stability + ecosystem wave. Three install-broken bugs (`npm install` ERESOLVE, non-OpenAI base URLs, broken Claude bridge path) closed. Six runtime bugs from active users fixed end-to-end. Three new agent integrations (Qwen Code, Antigravity, Kiro). New `AGENT_ID` scope for multi-agent setups. Port mapping documented. + +### Fixed + +- **`npm install` ERESOLVE on fresh install** ([PR #649](https://github.com/rohitg00/agentmemory/pull/649), closes [#631](https://github.com/rohitg00/agentmemory/issues/631)). `@anthropic-ai/sdk` bumped from `^0.39.0` to `^0.93.0` so `claude-agent-sdk`'s peer is satisfied. Verified clean install with only the published `dependencies` block. + +- **Non-OpenAI base URLs silent-404** ([PR #649](https://github.com/rohitg00/agentmemory/pull/649), closes [#646](https://github.com/rohitg00/agentmemory/issues/646), [#628](https://github.com/rohitg00/agentmemory/issues/628)). `buildChatUrl` + `buildEmbeddingUrl` no longer blindly prepend `/v1/`. DeepSeek, SiliconFlow, Zhipu (`/api/paas/v4`), vLLM, LM Studio, Ollama all resolve correctly. + +- **`CLAUDE_MEMORY_BRIDGE` writes to a path Claude Code reads** ([PR #649](https://github.com/rohitg00/agentmemory/pull/649), closes [#625](https://github.com/rohitg00/agentmemory/issues/625)). Slug now preserves the leading `-` on POSIX absolute paths and drops the spurious `/memory/` subdir, matching `~/.claude/projects//MEMORY.md`. + +- **OpenAI provider reads `reasoning_content` for thinking models** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#627](https://github.com/rohitg00/agentmemory/issues/627)). DeepSeek V4 / Qwen3 / GLM / Kimi return `message.reasoning_content`. Previously only `message.reasoning` was checked — compress silently failed every call and tripped the circuit breaker. + +- **`agentmemory stop` reaps the worker process** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#640](https://github.com/rohitg00/agentmemory/issues/640), [#474](https://github.com/rohitg00/agentmemory/issues/474)). Worker pid is written to `~/.agentmemory/worker.pid` on boot; `stop` signals both engine + worker. + +- **OpenCode plugin implicit-creates the session on first observation** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#638](https://github.com/rohitg00/agentmemory/issues/638)). `mem::observe` creates the session row when one doesn't exist. No more orphan observations or `Session not found for summarize`. + +- **OpenCode plugin zero-config auto-context injection** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#431](https://github.com/rohitg00/agentmemory/issues/431)). `POST /session/start` context is cached per-session; the existing `experimental.chat.system.transform` hook reads from the cache. + +- **Viewer graph settles on 1000+ node graphs** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#563](https://github.com/rohitg00/agentmemory/issues/563)). Tick-decayed damping, per-node velocity cap, raf park on quiescence. Mousedown / wheel / zoom / recenter re-wake the parked loop. + +- **`/memories` + `/export` paginate** ([PR #648](https://github.com/rohitg00/agentmemory/pull/648), closes [#544](https://github.com/rohitg00/agentmemory/issues/544)). New `?count=true` and `?limit=N&offset=M` on `/memories`. `/export` forwards `?maxSessions` + `?offset`. Stops large corpora (8K+ memories) from timing out at the iii-engine invocation boundary. + +- **Claude Code drops the MCP server silently** ([PR #650](https://github.com/rohitg00/agentmemory/pull/650), closes [#510](https://github.com/rohitg00/agentmemory/issues/510)). `plugin/.mcp.json` env block uses `${VAR:-default}` form. Unset required vars no longer fail config parse. + +- **Full 51-tool MCP surface by default** ([PR #650](https://github.com/rohitg00/agentmemory/pull/650), closes [#553](https://github.com/rohitg00/agentmemory/issues/553)). `getVisibleTools()` default flipped from `core` (8) to `all` (51) to match what every plugin manifest advertises. `AGENTMEMORY_TOOLS=core` still gives the lean set. + +- **Connect adapters write `${VAR:-default}` env block** ([PR #650](https://github.com/rohitg00/agentmemory/pull/650)). `agentmemory connect` for Claude Code / Cursor / Gemini CLI / Windsurf writes the same default form. + +- **Hermes `memory status` no longer reports the plugin as Missing** ([PR #643](https://github.com/rohitg00/agentmemory/pull/643), closes [#520](https://github.com/rohitg00/agentmemory/issues/520)). Hermes plugin seeds `AGENTMEMORY_URL` to `http://localhost:3111` at import. Works for systemd-managed agentmemory where the env file is loaded via `EnvironmentFile=` and never reaches the interactive shell. + +- **Deleted memories cleared from BM25 + vector indices** ([PR #636](https://github.com/rohitg00/agentmemory/pull/636) by [@abhinav-m22](https://github.com/abhinav-m22), closes [#632](https://github.com/rohitg00/agentmemory/issues/632)). `SearchIndex.remove()` added and called from every delete path. Snapshot flushed synchronously so a SIGKILL between mutation + debounce can't resurrect deleted entries. + +- **PostToolUse hook reads `tool_response`, falls back to `tool_output`** ([PR #561](https://github.com/rohitg00/agentmemory/pull/561) by [@faraz152](https://github.com/faraz152), closes [#539](https://github.com/rohitg00/agentmemory/issues/539)). Claude Code's PostToolUse payload uses `tool_response`. Now reads `tool_response ?? tool_output` so legacy integrations keep working. + +- **iii-sdk pinned to exact `0.11.2`** ([PR #567](https://github.com/rohitg00/agentmemory/pull/567), closes [#555](https://github.com/rohitg00/agentmemory/issues/555)). `iii-sdk@0.11.6` introduced a routing regression where every `/agentmemory/*` route returned 404. Pin removes the caret. + +- **OpenAI provider sends explicit `stream: false`** ([PR #526](https://github.com/rohitg00/agentmemory/pull/526) by [@Ptah-CT](https://github.com/Ptah-CT)). Some OpenAI-compatible proxies default to `text/event-stream` when `stream` is absent. + +- **Viewer search uses NFKC normalisation for CJK / fullwidth input** ([PR #542](https://github.com/rohitg00/agentmemory/pull/542) by [@kaushalrog](https://github.com/kaushalrog)). + +- **Viewer splash shows actual bound viewer port** ([PR #560](https://github.com/rohitg00/agentmemory/pull/560) by [@Tanmay-008](https://github.com/Tanmay-008), closes [#521](https://github.com/rohitg00/agentmemory/issues/521)). `/agentmemory/livez` now returns `viewerPort` + `viewerSkipped`. + +- **Viewer tab bar height stable across tab switches** ([PR #325](https://github.com/rohitg00/agentmemory/pull/325) by [@hungtd119](https://github.com/hungtd119), closes [#324](https://github.com/rohitg00/agentmemory/issues/324)). + +- **Graph parser accepts self-closing `` tags** ([PR #494](https://github.com/rohitg00/agentmemory/pull/494) by [@Rex57](https://github.com/Rex57), closes [#492](https://github.com/rohitg00/agentmemory/issues/492)). + +- **Plugin MCP server inherits remote/auth env** ([PR #386](https://github.com/rohitg00/agentmemory/pull/386) by [@LaplaceYoung](https://github.com/LaplaceYoung), closes [#375](https://github.com/rohitg00/agentmemory/issues/375)). + +- **`@agentmemory/mcp` rejects literal `${VAR}` placeholders**. Any `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` value of the form `${...}` is treated as unset and falls back to `http://localhost:3111`. + +- **Codex `stop` hook closes session** ([PR #579](https://github.com/rohitg00/agentmemory/pull/579), closes [#493](https://github.com/rohitg00/agentmemory/issues/493)). `Stop` was missing from the Codex bundle; session never got marked completed. + +- **Claude Code `--with-hooks` works for MCP-standalone users** ([PR #581](https://github.com/rohitg00/agentmemory/pull/581), closes [#508](https://github.com/rohitg00/agentmemory/issues/508)). + +### Added + +- **`AGENT_ID` multi-agent memory isolation** ([PR #654](https://github.com/rohitg00/agentmemory/pull/654), closes [#554](https://github.com/rohitg00/agentmemory/issues/554)). Optional `AGENT_ID` env tags every Session / RawObservation / CompressedObservation / Memory. `AGENTMEMORY_AGENT_SCOPE=isolated` (opt-in; `shared` default) also filters every recall path (`mem::smart-search`, `/memories`, `/observations`, `/sessions`). Per-call overrides via request body + `?agentId=` / `?agentId=*` query params. `?includeOrphans=true` surfaces pre-tag rows. + +- **Qwen Code connect adapter** ([PR #651](https://github.com/rohitg00/agentmemory/pull/651), closes [#647](https://github.com/rohitg00/agentmemory/issues/647)). `agentmemory connect qwen` writes the standard `mcpServers` block to `~/.qwen/settings.json`. + +- **Antigravity connect adapter** ([PR #651](https://github.com/rohitg00/agentmemory/pull/651), closes [#614](https://github.com/rohitg00/agentmemory/issues/614)). Replacement for Gemini CLI (sunset 2026-06-18). Writes `mcp_config.json` to the platform-specific User dir. + +- **Kiro connect adapter** ([PR #651](https://github.com/rohitg00/agentmemory/pull/651), closes [#618](https://github.com/rohitg00/agentmemory/issues/618)). Writes user-level `~/.kiro/settings/mcp.json`. + +- **Cost-aware model selection** ([PR #654](https://github.com/rohitg00/agentmemory/pull/654), closes [#613](https://github.com/rohitg00/agentmemory/issues/613)). Runtime warning when `OPENROUTER_MODEL` matches the premium pattern. README cost-tier table with measured workload data. Suppress via `AGENTMEMORY_SUPPRESS_COST_WARNING=1`. + +- **Pluggable benchmark harness** ([PR #562](https://github.com/rohitg00/agentmemory/pull/562)). New `eval/` directory with the `coding-agent-life-v1` corpus (15 sessions + 15 graded queries) and three adapters (grep, OpenAI embeddings + cosine, agentmemory hybrid). LongMemEval support. Sandboxed agentmemory + iii-engine on alt ports via `eval/scripts/sandbox.sh`. Dev-only — no runtime impact. + +- **`agentmemory connect codex --with-hooks` opt-in flag** ([PR #564](https://github.com/rohitg00/agentmemory/pull/564), closes [#509](https://github.com/rohitg00/agentmemory/issues/509)). Workaround for [openai/codex#16430](https://github.com/openai/codex/issues/16430). + +- **Cross-platform CI matrix** ([PR #556](https://github.com/rohitg00/agentmemory/pull/556)). Ubuntu + macOS × Node 20 + 22, `paths-ignore`, per-branch concurrency cancellation. + +### Docs + +- **Port mapping table** ([PR #651](https://github.com/rohitg00/agentmemory/pull/651), closes [#629](https://github.com/rohitg00/agentmemory/issues/629)). `3111` REST / `3112` streams / `3113` viewer / `49134` engine WS + env overrides + stale-process cleanup recipe. + +- **Pairings recipe** ([PR #641](https://github.com/rohitg00/agentmemory/pull/641)). `docs/recipes/pairings.md` covers stacking agentmemory with codegraph, Understand Anything, and Graphify. + +- **Multi-agent README section** ([PR #654](https://github.com/rohitg00/agentmemory/pull/654)). `AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE` semantics, per-endpoint behavior table. + +- **Supply-chain policy in SECURITY.md** ([PR #654](https://github.com/rohitg00/agentmemory/pull/654), closes [#540](https://github.com/rohitg00/agentmemory/issues/540)). Explains why no lockfile is committed (`dist/` ships pre-built) and what monitoring exists. + +- **README "Config File" section + Windows path** ([PR #321](https://github.com/rohitg00/agentmemory/pull/321) by [@aqilaziz](https://github.com/aqilaziz), closes [#293](https://github.com/rohitg00/agentmemory/issues/293)). + +- **README sudo install hint for `EACCES`** ([PR #454](https://github.com/rohitg00/agentmemory/pull/454) by [@kedar-1](https://github.com/kedar-1)). + +### Infrastructure + +- 108 test files, **1171 tests pass**. +- Agent count: 8 → 11 (claude-code, codex, cursor, gemini-cli, qwen, antigravity, kiro, openclaw, hermes, pi, openhuman). + +## [0.9.21] — 2026-05-19 + +Quality + integration wave. Headline: native OpenCode plugin with full Claude Code hook parity ([#237](https://github.com/rohitg00/agentmemory/pull/237) by [@cl0ckt0wer](https://github.com/cl0ckt0wer)). Ten more PRs alongside: `memory_recall` returning the wrong shape, env-file `AGENTMEMORY_DROP_STALE_INDEX` silently ignored, hook scripts crashing on Windows usernames with spaces, viewer search inputs interrupting CJK IME composition, large sessions silently failing at the LLM context limit, lessons invisible to smart-search, Hermes plugin manifest missing hooks, cli onboarding crashing in non-TTY contexts, rebuildIndex blocking boot on large corpora, 25h embed-loop bottleneck during rebuild, and the v0.9.19 iii-console installer workaround can come out now that upstream is fixed. + +### Added + +- **OpenCode plugin with 22 auto-capture hooks** ([PR #237](https://github.com/rohitg00/agentmemory/pull/237) by [@cl0ckt0wer](https://github.com/cl0ckt0wer), closes [#236](https://github.com/rohitg00/agentmemory/issues/236) + [#244](https://github.com/rohitg00/agentmemory/issues/244)). Complete OpenCode plugin in `plugin/opencode/` matching Claude Code hook parity. Covers session lifecycle (8 hooks), messages (3), tool lifecycle (2), part tracking, permissions, task tracking, plus a two-layer enrichment pipeline (memory context on first turn, file enrichment on subsequent turns) and two slash commands (`/recall`, `/remember`). Full gap analysis in `plugin/opencode/README.md`. + +### Fixed + +- **`memory_recall` endpoint + format/token_budget forwarding** ([PR #516](https://github.com/rohitg00/agentmemory/pull/516) by [@serhiizghama](https://github.com/serhiizghama), closes [#507](https://github.com/rohitg00/agentmemory/issues/507) + [#440](https://github.com/rohitg00/agentmemory/issues/440)). MCP `memory_recall` always returned compact mode and dropped `format` + `token_budget` params. Two root causes fixed: standalone shim routed through `/agentmemory/smart-search` instead of `/agentmemory/search`, and the local-fallback path didn't read either param. Now routes correctly, forwards both params end-to-end, defaults `format` to `"full"` matching the MCP schema. + +- **env-file `AGENTMEMORY_DROP_STALE_INDEX` flag now honored** ([PR #461](https://github.com/rohitg00/agentmemory/pull/461) by [@honor2030](https://github.com/honor2030), closes [#456](https://github.com/rohitg00/agentmemory/issues/456)). Setting the flag in `~/.agentmemory/.env` was silently ignored because the boot path read `process.env` directly. New `isDropStaleIndexEnabled()` helper reads merged env. Combined with [#455](https://github.com/rohitg00/agentmemory/issues/455) + [#469](https://github.com/rohitg00/agentmemory/issues/469) reports, this is the unblock path for the stale-index server-crash recovery loop. + +- **Windows hook scripts quote plugin paths correctly** ([PR #487](https://github.com/rohitg00/agentmemory/pull/487) by [@honor2030](https://github.com/honor2030), closes [#477](https://github.com/rohitg00/agentmemory/issues/477)). Hook command strings referenced `${CLAUDE_PLUGIN_ROOT}/scripts/*.mjs` without quotes — Windows users with spaces in their username had every hook crash. Quotes added + regression test. + +- **Viewer search inputs honor IME composition** ([PR #517](https://github.com/rohitg00/agentmemory/pull/517) by [@jonathanzhan1975](https://github.com/jonathanzhan1975)). CJK users typing in the viewer's search inputs hit mid-character interruption — every keystroke fired the `oninput=` re-render handler, breaking IME composition mid-syllable. New `bindImeSafeSearch` helper defers re-render until `compositionend`. + +- **Chunk large sessions to fit LLM context window** ([PR #472](https://github.com/rohitg00/agentmemory/pull/472) by [@efenex](https://github.com/efenex)). Sessions with >7000 observations silently failed at the LLM provider's context limit — the consolidation pipeline silently skipped the session. New chunking splits oversized sessions across multiple compress calls + restitches the narrative via a `REDUCE_SYSTEM` prompt. Legacy single-call path preserved when obs count is under the chunk size. Backfill script under `scripts/` for users hitting the pre-fix bug. + +- **Surface lessons in smart-search + diagnose tally** ([PR #473](https://github.com/rohitg00/agentmemory/pull/473) by [@efenex](https://github.com/efenex)). Closes the lesson round-trip with [#458](https://github.com/rohitg00/agentmemory/pull/458) (lessons auto-injected into `mem::context`): lessons are now also returned alongside hybrid search results in a separate `lessons` field on `smart-search`, and the `diagnose` health surface tallies per-store counts so the trust-shock pattern (save succeeds, recall empty, diagnose says 0) goes away. + +- **Declare all Hermes plugin hooks** ([PR #486](https://github.com/rohitg00/agentmemory/pull/486) by [@honor2030](https://github.com/honor2030)). The Hermes `plugin.yaml` manifest only declared 3 of the 6 implemented hooks. All 6 now declared (`prefetch`, `sync_turn`, `on_session_end`, `on_pre_compress`, `on_memory_write`, `system_prompt_block`). + +- **`rebuildIndex` non-blocking on boot** ([PR #500](https://github.com/rohitg00/agentmemory/pull/500) by [@efenex](https://github.com/efenex)). Boot path previously `await`-ed `rebuildIndex(kv)`, so the viewer + later boot steps stalled — on large corpora this was 25h+ of blocked startup. Replaced with `void rebuildIndex(kv).then(...).catch(...)` so the rebuild runs in the background. + +- **Batched embed calls in `rebuildIndex` (25h → 3h on large corpora)** ([PR #504](https://github.com/rohitg00/agentmemory/pull/504) by [@efenex](https://github.com/efenex)). The rebuild loop made one embed call per observation, paying full HTTP RTT per item. New `vectorIndexAddBatchGuarded` helper batches embeds (default 32, configurable via `REBUILD_EMBED_BATCH_SIZE`) and try/catches per-item failures. Measured 25h → 3h on a 250k-observation corpus. + +- **CLI skips onboarding prompts without a tty** ([PR #491](https://github.com/rohitg00/agentmemory/pull/491) by [@honor2030](https://github.com/honor2030)). Onboarding prompts crashed in non-interactive contexts (CI, `docker run -d`, piped input). New guard short-circuits with sensible defaults when stdin/stdout aren't TTYs or `CI=1`. + +### Changed + +- **Drop iii-console installer `--next` workaround** ([PR #546](https://github.com/rohitg00/agentmemory/pull/546)). v0.9.19 routed first-run iii-console install through `bash -s -- --next` to dodge an upstream tag-prefix bug at [iii-hq/iii#1652](https://github.com/iii-hq/iii/issues/1652). Upstream [iii-hq/iii#1660](https://github.com/iii-hq/iii/pull/1660) shipped 2026-05-19; `install.iii.dev/console/main/install.sh` is a CDN proxy serving upstream main HEAD so the fix is live without an iii release tag. Reverted to canonical bare `curl ... | sh`. + +### Infrastructure + +- 95 test files (was 92), **1067 tests pass** (was 1038) on `chore(release): v0.9.21`. +- Bundles 11 PRs: 1 contributor feature + 9 bug fixes across MCP / hooks / viewer / summarize / lessons / Hermes / rebuildIndex / CLI + 1 upstream-installer revert. +- New contributors landing first PRs this release: [@cl0ckt0wer](https://github.com/cl0ckt0wer), [@serhiizghama](https://github.com/serhiizghama), [@jonathanzhan1975](https://github.com/jonathanzhan1975). + +[0.9.21]: https://github.com/rohitg00/agentmemory/compare/v0.9.20...v0.9.21 + +## [0.9.20] — 2026-05-18 + +Hotfix: revert the Codex Stop → session-end chain shipped in v0.9.19. + +### Fixed + +- **Revert Codex Stop hook session-end chain** ([PR #501](https://github.com/rohitg00/agentmemory/pull/501) by [@Rex57](https://github.com/Rex57), reverts v0.9.19's [#495](https://github.com/rohitg00/agentmemory/pull/495), re-opens [#493](https://github.com/rohitg00/agentmemory/issues/493)). Post-merge field-testing surfaced the underlying issue: Codex `Stop` fires before the overall conversation is truly finished — multiple Stops bracket each assistant turn within one session. Chaining `session-end.mjs` from Stop marked sessions completed too early, with later observations still arriving against an `endedAt`-stamped record. Restored to summarize-only Stop; the SessionEnd-shaped solution stays open as [#493](https://github.com/rohitg00/agentmemory/issues/493). + +[0.9.20]: https://github.com/rohitg00/agentmemory/compare/v0.9.19...v0.9.20 + +## [0.9.19] — 2026-05-18 + +Feature + hardening wave. Sessions now link to the git commits they shipped (forward + reverse lookup, REST + MCP surfaces). OpenAI provider transport collapses into one shared module with auto-detected Azure URL style (legacy `/openai/deployments/` and v1 `/openai/v1` both supported). Graph retrieval switches from BFS to Dijkstra over the weighted edge graph. Codex Stop hook chains session-end. Plugin MCP server inherits `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` from the shell. Point fix routes the bundled iii-console installer around an upstream tag-prefix bug. 1007+ tests pass. + +### Added + +- **Session-to-commit linking** ([PR #498](https://github.com/rohitg00/agentmemory/pull/498)). New `KV.commits` namespace keyed by full SHA holds `CommitLink` records (sha, shortSha, branch, repo, message, author, authoredAt, files, sessionIds). `Session.commitShas[]` provides the forward back-reference. REST: `POST /agentmemory/session/commit` upserts links (merges `sessionIds` on re-link, preserves `linkedAt`); `GET /agentmemory/commits/:sha` and `GET /agentmemory/commits` round-trip. MCP: `memory_commit_lookup` and `memory_commits` tools. Post-commit hook auto-captures the link on every commit in the working directory. Closes the loop on "what session wrote this code" / "what commits did this session ship" without leaving agentmemory. + +- **Azure OpenAI v1 URL pattern auto-detection** ([PR #462](https://github.com/rohitg00/agentmemory/pull/462), closes [#371](https://github.com/rohitg00/agentmemory/issues/371)). Both the LLM and embedding providers now route through `_openai-shared.ts` and auto-detect Azure URL style: + - `OPENAI_BASE_URL=https://r.openai.azure.com/openai/deployments/` → legacy URL pattern, `api-version` query param via `OPENAI_API_VERSION` (default `2024-08-01-preview`). + - `OPENAI_BASE_URL=https://r.openai.azure.com` (bare host, or `/openai`, or `/openai/v1`) → v1 GA pattern, `/openai/v1/`, deployment name carried in the request body as `model`. + - Net effect: Azure embeddings work for the first time (LLM-side Azure shipped in v0.9.17; embedding was still hardcoded to `/v1/embeddings` + Bearer). Closes [#199](https://github.com/rohitg00/agentmemory/issues/199) (consolidation) as superseded. + +### Changed + +- **Graph retrieval: BFS → Dijkstra over weighted edges** ([PR #463](https://github.com/rohitg00/agentmemory/pull/463), closes [#328](https://github.com/rohitg00/agentmemory/issues/328) filed by [@Tanmay-008](https://github.com/Tanmay-008) with benchmark numbers showing the BFS edge-count semantics + O(n) `Array.shift()` profile). Memory graph edges carry weights 0.1–1.0; BFS visited by edge-count regardless, so a one-hop weak edge ranked the same as a two-hop strong chain. Dijkstra over `cost = 1/max(weight, 0.01)` selects weight-optimal paths instead. Adjacency map built once in O(V+E) and min-heap dequeue at O(log V) replace the prior O(V·E) + O(n) `Array.shift()` profile. `maxDepth` semantics preserved (still edge-count bound). The `startNode` path is excluded from returned paths so the dedicated `score=1.0` fallback loop in `searchByEntities` fires as designed (regression catch from the inline review). + +- **Codex Stop hook chains session-end** ([PR #495](https://github.com/rohitg00/agentmemory/pull/495) by [@Rex57](https://github.com/Rex57), fixes [#493](https://github.com/rohitg00/agentmemory/issues/493) also filed by [@Rex57](https://github.com/Rex57)). `hooks.codex.json` Stop now runs `stop.mjs` followed by `session-end.mjs`. Codex doesn't ship a separate `SessionEnd` lifecycle event, so the session would otherwise stay open after the user terminated the Codex session. Tests assert both commands appear in the Stop chain. + +- **Plugin MCP entry inherits shell env via passthrough** ([PR #460](https://github.com/rohitg00/agentmemory/pull/460), closes [#375](https://github.com/rohitg00/agentmemory/issues/375) filed by [@anthony-spruyt](https://github.com/anthony-spruyt)). `plugin/.mcp.json` and `AGENTMEMORY_MCP_BLOCK` (the template `agentmemory connect ` writes into `~/.claude.json`, `~/.cursor/mcp.json`, etc.) now declare `env: { AGENTMEMORY_URL: "${AGENTMEMORY_URL}", AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}" }`. The MCP host substitutes shell values at server launch. When the vars are unset, the host passes empty strings; the standalone shim's `process.env["AGENTMEMORY_URL"] || "http://localhost:3111"` falls back to localhost. One wired entry now covers both local and remote (k8s / reverse-proxied) deployments without `/doctor` "duplicate server" warnings. + +### Fixed + +- **`ensureIiiConsole()` install path** (`src/cli.ts`). The upstream `install.iii.dev/console/main/install.sh` script's jq predicate filters releases with `startswith("v")` while `iii-hq/iii` tags as `iii/v0.12.0`. The script bails with `no stable iii release found` on every fresh install. Switched the install command to `curl ... | bash -s -- --next` until upstream patches the script — the `--next` codepath uses a regex on `-next.` without the buggy `startswith` constraint, so it succeeds against the same tag set. Inline comment documents the upstream bug + revert condition. + +### Infrastructure + +- 91 test files, 1007 tests pass on `chore(release): v0.9.19`. +- Bundles five PRs ([#460](https://github.com/rohitg00/agentmemory/pull/460), [#462](https://github.com/rohitg00/agentmemory/pull/462), [#463](https://github.com/rohitg00/agentmemory/pull/463), [#495](https://github.com/rohitg00/agentmemory/pull/495), [#498](https://github.com/rohitg00/agentmemory/pull/498)) plus the inline iii-console installer workaround into one patch release. + +[0.9.19]: https://github.com/rohitg00/agentmemory/compare/v0.9.18...v0.9.19 + +## [0.9.18] — 2026-05-17 + +Hardening + DX wave. Five fixes land together: lessons now flow into the auto-inject context payload (closes a half-finished loop from earlier releases — see #381 / #457), the viewer drops `data:` from its `img-src` CSP by self-hosting its favicon, the filesystem watcher redacts PEM private-key blocks and standalone JWTs before transport, the mcp-standalone livez probe gets a dependency-injection seam that kills a flaky test, and the OpenAI timeout precedence is documented + tightened (strict integer parse, `OPENAI_TIMEOUT_MS` keeps its v0.9.17 meaning as an alias of the global `AGENTMEMORY_LLM_TIMEOUT_MS`). 1007/1007 tests pass. + +### Added + +- **Lessons auto-injected into `mem::context` payload** ([PR #458](https://github.com/rohitg00/agentmemory/pull/458), closes [#457](https://github.com/rohitg00/agentmemory/issues/457), surfaced in discussion [#381](https://github.com/rohitg00/agentmemory/discussions/381)). Lessons were generated + stored but only retrievable via an explicit `memory_lesson_recall` MCP call — agents rarely thought to invoke it, so the loop was half-done. `mem::context` now reads `KV.lessons` alongside slots + profile, ranks by `(project-relevance × confidence)` (project-scoped lessons get a 1.5× boost), filters tombstoned + cross-project entries, caps at top-10, and emits a `## Lessons Learned` block competing fairly for the token budget. Block recency tracks the most-recent `lastReinforcedAt || updatedAt`, so hot lessons survive when budget tightens. + +- **Self-hosted viewer favicon** ([PR #452](https://github.com/rohitg00/agentmemory/pull/452), closes [#447](https://github.com/rohitg00/agentmemory/issues/447)). The viewer's inline-SVG `data:` favicon (added in #313) required `data:` in `img-src` — a broader allowance than the viewer actually needed. The favicon now lives at `/favicon.svg` served by the viewer with `Content-Type: image/svg+xml` and `Cache-Control: public, max-age=3600`; build script copies the asset into `dist/viewer/` alongside `index.html`. CSP reverts to bare `img-src 'self'`. + +### Changed + +- **`OPENAI_TIMEOUT_MS` is now an alias of `AGENTMEMORY_LLM_TIMEOUT_MS`** ([PR #453](https://github.com/rohitg00/agentmemory/pull/453), closes [#446](https://github.com/rohitg00/agentmemory/issues/446)). v0.9.17 shipped `OPENAI_TIMEOUT_MS` as the OpenAI-scoped knob, then [PR #379](https://github.com/rohitg00/agentmemory/pull/379) introduced the global `AGENTMEMORY_LLM_TIMEOUT_MS` shared across all raw-fetch providers. The OpenAI provider now resolves them in precedence order: `OPENAI_TIMEOUT_MS` → `AGENTMEMORY_LLM_TIMEOUT_MS` → `60_000ms` default. v0.9.17 configs keep working unchanged; new configs should prefer the global. The provider's request also moved onto the shared `fetchWithTimeout` helper that owns AbortController + `clearTimeout` cleanup for every raw-fetch path (minimax, openrouter, gemini, embedding providers). + +- **Strict integer parse for timeout env vars** (PR #453, CodeRabbit catch). `parsePositiveInt` rejects values like `"30ms"`, `"1_000"`, `"60s"`, `"30abc"`, `"-30"`, `"0"` via `/^\d+$/` (after trim) instead of letting `parseInt`'s lenience silently swallow trailing units / underscores / signs as a number. Malformed values fall back to the 60s default with no surprise truncation. + +### Fixed + +- **Filesystem watcher redacts PEM private-key blocks + standalone JWTs in previews** ([PR #450](https://github.com/rohitg00/agentmemory/pull/450), closes [#448](https://github.com/rohitg00/agentmemory/issues/448)). Continues the redaction surface opened in [PR #332](https://github.com/rohitg00/agentmemory/pull/332). PEM blocks (`-----BEGIN ... PRIVATE KEY-----` through `-----END ... PRIVATE KEY-----`, including encrypted, RSA, EC, DSA, OpenSSH, PGP variants) get a state-machine pass that replaces the whole block with a single `[REDACTED ... PRIVATE KEY]` marker; standalone JWT-shaped tokens (three base64url segments separated by dots, length ≥ ~32 chars) are masked to their last 4 chars. Both run before any transport-layer write. + +- **mcp-standalone livez probe DI seam kills the test flake** ([PR #451](https://github.com/rohitg00/agentmemory/pull/451), closes [#449](https://github.com/rohitg00/agentmemory/issues/449)). The standalone shim's livez probe used a fixed `fetch` against `localhost:3111` which made the test suite depend on no other agentmemory instance running on the host. New `setLivezProbe()` injection seam lets tests provide a deterministic probe; default behaviour for production users is unchanged. + +### Infrastructure + +- 91 test files (was 90), 1007 tests (was 992). New `test/context-lessons.test.ts` (8 cases) covers lessons-auto-inject inclusion, empty-state no-op, project ranking, cross-project isolation, soft-delete skip, top-10 cap, confidence rendering, optional `context` string append. + +- Bundled the four follow-up issues filed during the v0.9.17 audit wave ([#446](https://github.com/rohitg00/agentmemory/issues/446), [#447](https://github.com/rohitg00/agentmemory/issues/447), [#448](https://github.com/rohitg00/agentmemory/issues/448), [#449](https://github.com/rohitg00/agentmemory/issues/449)) plus the cross-project lesson-injection gap surfaced in discussion [#381](https://github.com/rohitg00/agentmemory/discussions/381) into a single patch release — no behaviour changes for existing users beyond the hardening above. + +[0.9.18]: https://github.com/rohitg00/agentmemory/compare/v0.9.17...v0.9.18 + +## [0.9.17] — 2026-05-16 + +OpenAI-compatible LLM provider lands the universal-adapter shape (one provider config covers OpenAI, Azure OpenAI auto-detected by hostname, DeepSeek, SiliconFlow, vLLM, LM Studio, Ollama via `/v1`, plus any future endpoint that mirrors `POST /v1/chat/completions`). Worker registration now pins a stable `project_name` for engine telemetry so attribution reads cleanly across hosts. Comparison section on agent-memory.dev no longer wraps awkwardly after the v0.9.16 refresh. + +### Added + +- **OpenAI-compatible LLM provider** ([PR #307](https://github.com/rohitg00/agentmemory/pull/307), by @fatinghenji). Six providers behind one config: `OPENAI_API_KEY` + `OPENAI_BASE_URL` + `OPENAI_MODEL`. Closes [#185](https://github.com/rohitg00/agentmemory/issues/185), [#232](https://github.com/rohitg00/agentmemory/issues/232) (Ollama works via `OPENAI_BASE_URL=http://localhost:11434/v1`), [#312](https://github.com/rohitg00/agentmemory/issues/312), and [#240](https://github.com/rohitg00/agentmemory/pull/240) (superseded). + +- **Azure OpenAI auto-detection**. `OpenAIProvider` detects `.openai.azure.com` hostnames in the configured base URL at construction time and switches the request shape automatically: drops the `/v1` path prefix (deployment is in the URL), uses `api-key: ` header instead of `Authorization: Bearer`, appends `api-version=` query param. Default api-version is `2024-08-01-preview`; override via `OPENAI_API_VERSION`. Closes the gap with [PR #219](https://github.com/rohitg00/agentmemory/pull/219). + +- **`OPENAI_TIMEOUT_MS` env var** (PR #307). Outbound fetch timeout on the new provider, default 60s, AbortController-bounded with a clear timeout error message that points at the env var. The other raw-fetch providers (anthropic / gemini / openrouter / minimax) share the same gap tracked in [#373](https://github.com/rohitg00/agentmemory/issues/373). + +- **`OPENAI_REASONING_EFFORT` passthrough** (PR #307). Forwarded as `reasoning_effort` on the request body for OpenAI reasoning models (`o1`, `o3`, `gpt-*-reasoning`) and providers that mirror that schema (Ollama Cloud thinking models). Standard chat models reject this field with 400 — README documents the caveat. Set to `"none"` for thinking models that return reasoning but no content. The provider also falls back to `message.reasoning` when `message.content` is empty, covering the Ollama Cloud thinking-model shape. + +### Changed + +- **Worker `telemetry.project_name` pinned to `"agentmemory"`** ([PR #426](https://github.com/rohitg00/agentmemory/pull/426)). `iii-sdk`'s `InitOptions.telemetry.project_name` auto-detects when omitted — falls through cwd → package.json basename → hostname, which produces inconsistent identifiers per host (`agentmemory`, `node`, `npm`, occasionally the user's home dir basename when launched via npx). Pinning the value gives every install the same stable project identifier in the engine's metrics + traces output. Also pins `language: "node"` and `framework: "iii-sdk"` for the same reason. + +- **`OPENAI_API_KEY_FOR_LLM=false` opt-out gate** (PR #307, fix pushed via maintainer edit). `detectLlmProviderKind()` now mirrors `detectProvider()`'s existing gate — users who set `OPENAI_API_KEY` only for embeddings (via the `OPENAI_BASE_URL` + `OPENAI_EMBEDDING_MODEL` flow from #186) won't see the LLM auto-activate. The README's `.env` template now leads with an explicit shared-use callout above the LLM section pointing at the opt-out. + +- **Compare section on agent-memory.dev** ([PR #427](https://github.com/rohitg00/agentmemory/pull/427)). `AGENTMEMORY VS. THE FIELD.` title → `VS. THE FIELD.` (the eyebrow already reads VS., so the longer version was redundant + wrapped ugly). Added `text-wrap: balance` to `.section-title` globally so any wrapping title breaks at a balanced point. `NATIVE PLUGINS` cell value `6 (Claude/Codex/OpenClaw/Hermes/pi/OpenHuman)` → `6` (agent names already visible in the Agents grid two sections above). Row grid rebalanced (label 1.4fr / agentmemory 1.3fr / competitors 1fr each), added `word-break: break-word` + 24px row padding so cells like `YES (APACHE-2.0)` and `2 (Qdrant, Neo4j)` have breathing room. + +### Infrastructure + +- Provider factory at `src/providers/index.ts` now dispatches `"openai"` through `createBaseProvider`; type union extended in `src/types.ts:132`. `VALID_PROVIDERS` set in `src/config.ts` includes the new entry so the fallback-chain config accepts it. + +[0.9.17]: https://github.com/rohitg00/agentmemory/compare/v0.9.16...v0.9.17 + +## [0.9.16] — 2026-05-15 + +Two parallel waves landed back-to-back. (1) DevEx polish on top of v0.9.15's foundation: 5-port ready panel that shows REST/Viewer/Streams/Engine/iii-console in one boxed note, iii-console install probe + auto-install on first run, interactive global-install prompt that replaces the passive npx hint (so `agentmemory stop` actually works in new shells), onboarding wizard now wires every selected agent inline via the same `agentmemory connect` adapter the CLI exposes, plus a memory-share callout so users understand a single server feeds every wired agent. (2) Marketing site refresh against the v0.9.15 surface: new `AS FEATURED IN` bar (AlphaSignal · Agentic AI Foundation · Trendshift), six first-party agents in the featured grid (added pi + OpenHuman), MCP messaging reworded as opt-in surface so REST reads as the primary protocol. + +### Added + +- **5-port ready panel** ([PR #410](https://github.com/rohitg00/agentmemory/pull/410)). Replaces the single-line `Memory ready on :3111 · viewer on :3113 · try: agentmemory demo` hint with a clack `p.note` panel listing all live endpoints — REST API, Viewer, Streams, Engine, iii console — each derived from the configured env vars (`AGENTMEMORY_URL`, `III_REST_PORT`, `III_VIEWER_PORT`, `III_STREAM_PORT`, `III_ENGINE_URL`) so a remote-bind setup reads correctly, not as hardcoded localhost. + +- **iii console install probe + auto-install** (PR #410). New `ensureIiiConsole()` checks for the iii-console binary on PATH or in `~/.local/bin`; if missing, prompts interactively to run `curl -fsSL https://install.iii.dev/console/main/install.sh | sh`. Console is first-class — not optional. On install acceptance the ready panel includes the binary's resolved path and a runnable launch hint (` -p `); on decline the panel surfaces the install one-liner. + +- **Interactive global-install prompt** (PR #410). Replaces the passive `p.log.info` npx hint with a `p.confirm` on first npx run that runs `npm install -g @agentmemory/agentmemory@` inline. Suppressible via `preferences.skipGlobalInstall` so we never ask twice. Closes the v0.9.15-era footgun where users typed `agentmemory stop` in a new shell and hit `command not found`. + +- **Onboarding wires selected agents inline** ([PR #408](https://github.com/rohitg00/agentmemory/pull/408)). After the multi-select agents step in `runOnboarding`, asks `Run \`agentmemory connect \` for each selected agent now? [Y/n]` and dispatches each through the existing `runAdapter` path used by the explicit `agentmemory connect` command. Successes + failures get bucketed in a summary block (`Wired: claude-code, codex, cursor · Skipped/failed: hermes (manual install required)`). Cancellation prints the explicit per-agent commands for the user to run later. + +- **Memory-share callout** (PR #408). Between the agents multi-select and the provider single-select the wizard now prints a verbatim note: `All selected agents share the same memory at :3111. A memory saved by Claude Code is visible to Codex + Cursor instantly.` Closes the most common confusion ("does the same memory work across agents?") we were getting on the v0.9.15 install path. + +- **AS FEATURED IN bar on agent-memory.dev**. New `FeaturedIn` component between Hero and Stats. Three cards with real brand marks: AlphaSignal (github.com/Alpha-Signal avatar, links to the AlphaSignal Substack deep-dive), Agentic AI Foundation (self-hosted wordmark, inverted to white-on-dark for the brutalist palette), Trendshift (their official badge endpoint at `trendshift.io/api/badge/repositories/25123` which bakes the live rank + star count into the image). 3-column grid on desktop, 1-column stack on mobile, keyboard-accessible (`:focus-visible` outline). + +### Changed + +- **MCP messaging reworded as opt-in surface** ([PR #409](https://github.com/rohitg00/agentmemory/pull/409)). The endpoints summary line in `src/index.ts` was foregrounding MCP equally with REST — `Endpoints: 107 REST + 51 MCP tools + 6 MCP resources + 3 MCP prompts`. Users kept reading MCP as compulsory. Now: `REST API: 121 endpoints at http://localhost:/agentmemory/*` (primary), plus a second line `MCP surface (opt-in via \`npx @agentmemory/mcp\`): 51 tools · 6 resources · 3 prompts`. Each `connect` adapter additionally prints a protocol-note line above its install summary so the user sees which surface they're wiring (native hooks vs MCP vs both). + +- **CLI `--help` mcp subcommand description** (PR #409). Was `Start standalone MCP server (no engine required)`. Now: `Start standalone MCP shim — opt-in surface for MCP-only clients (Cursor, Gemini CLI, etc). REST always available at :3111.` + +- **Engine version-mismatch warning copy** (PR #410). The warning that fires when iii on PATH doesn't match `IIPINNED_VERSION` previously said `agentmemory v0.9.14+ pins v0.11.2`. Now reads `agentmemory v${VERSION} pins v${IIPINNED_VERSION}` so the string never lies post-release. + +- **CommandCenter — iii console messaging** (PR #415). `iii CONSOLE · OPTIONAL` → `iii CONSOLE · FIRST-CLASS`. Section lede now mentions both UIs (viewer + console) are first-class and installed inline by the CLI on first run. Bullet counts updated: dropped stale `33 functions` and `49 triggers` → `121 HTTP endpoints` (matches `generated-meta.json`). + +- **Compare table refreshed** (PR #415). MCP TOOLS row our column 44 → 51. New REST ENDPOINTS row (121) and NATIVE PLUGINS row (6: Claude/Codex/OpenClaw/Hermes/pi/OpenHuman). + +- **Agents grid refresh** (PR #415). Featured row expanded from 4 to 6 — added pi and OpenHuman. Codex CLI sub line updated to `NATIVE PLUGIN` (has 6 hooks now, not MCP-only). Section title `FOUR FIRST-PARTY` → `SIX FIRST-PARTY`. Lede mentions `agentmemory connect `. + +- **Hero CTA** (PR #415). `START IN 60 SECONDS` → `START IN 30 SECONDS`. Cold install + engine spawn measured 8-12s on v0.9.15 via the native binary path; 60s was the v0.9.0-era Docker-first claim. + +### Fixed + +- **CLI no longer kills its own parent process** (PR #410 follow-up via #411). `lsof -i :PORT -t` returns every PID with an active TCP connection — including the CLI's own keep-alive `fetch()` from `isEngineRunning()`. Now restricts to `-sTCP:LISTEN` and filters `process.pid` from the candidate set. The bug used to surface as exit code 137 with state files left stranded. + +- **Splash banner ASCII** ([PR #411](https://github.com/rohitg00/agentmemory/pull/411)). The hand-drawn block-art "agentmemory" wordmark in `src/cli/splash.ts` had broken middle glyphs (`_ _` instead of `_ __` around the 'n', merged 'tm/me' segments). Replaced with verified `figlet agentmemory` standard-font output. All 6 rows render at exactly 70 cols, regenerable. + +- **README install hoisted to top** (PR #411). Install section was buried at line 306 below benchmarks and comparison tables. Moved a 4-line install block right under the nav anchors at the top with the bare `agentmemory` command leading. Quick-start kept below for the in-depth walkthrough. Adds an npx-cache caveat with three workarounds (`npm install -g`, `npx -y @latest`, manual `rm -rf ~/.npm/_npx` annotated as POSIX-only). + +### Infrastructure + +- New modules: `src/cli/connect/{index,types,claude-code,codex,cursor,gemini-cli,openclaw,hermes,pi,openhuman,json-mcp-adapter}.ts`, `src/cli/doctor-diagnostics.ts`, `src/cli/remove-plan.ts`, `src/cli/splash.ts`, `src/cli/preferences.ts`, `src/cli/onboarding.ts`, `src/logger.ts` (bootLog shim) — actually shipped in v0.9.15; relisted here only to call out that v0.9.16 keeps every module backward-compatible (no signature breaks on `runOnboarding`, no field removals from `Prefs`). +- New tests: existing CLI test suites continue at 944+ passing. mcp-standalone pre-existing failures unrelated. +- Website: new `FeaturedIn` component (~150 LOC across `.tsx` + `.module.css`); `next.config.ts` adds `aaif.io`, `trendshift.io`, `raw.githubusercontent.com` to `remotePatterns`. + +[0.9.16]: https://github.com/rohitg00/agentmemory/compare/v0.9.15...v0.9.16 + +## [0.9.15] — 2026-05-15 + +DevEx overhaul. Four PRs landed simultaneously rebuilding the first-run experience to SkillKit-grade polish: splash banner + interactive agent grid + provider picker + smart-defaults preferences, `agentmemory connect ` to automate native-plugin install for 8 agents, interactive `doctor` v2 with Fix/Skip/More/Quit prompts and a `--all` auto-fix flag, `agentmemory remove` for clean uninstall with destruction-plan confirmation, plus five silent-killer fixes around viewer port collisions, engine version-mismatch detection, `stop --force` override, adopt-on-attach state recording, and an npx-to-global-install hint. + +### Added + +- **Splash banner + onboarding wizard** ([PR #403](https://github.com/rohitg00/agentmemory/pull/403)). Terminal-width-aware ASCII (full at ≥120 cols, compact at 80–119, single-line below 80), `NO_COLOR`-aware. First-run flow: multi-select 8 native-plugin agents + 8 MCP-server agents (`⟁ Claude Code`, `◫ Cursor`, `◎ Codex`, `✦ Gemini CLI`, `⬡ OpenCode`, etc), single-select LLM provider (Anthropic / OpenAI / Gemini / OpenRouter / MiniMax / BM25-only), seeds `~/.agentmemory/.env` with the chosen provider's `*_API_KEY=` line commented. Subsequent runs skip the splash. + +- **`~/.agentmemory/preferences.json`** (PR #403). Schema-versioned JSON with `{ lastAgent, lastAgents, lastProvider, skipSplash, skipNpxHint, firstRunAt }`. Atomic write via `.tmp` + rename, graceful defaults on read failure. Exports `isFirstRun()`, `readPrefs()`, `writePrefs()`, `resetPrefs()`. + +- **`agentmemory connect ` command** ([PR #402](https://github.com/rohitg00/agentmemory/pull/402)). Automates native-plugin install for `claude-code`, `codex`, `cursor`, `gemini-cli`, `openclaw` (end-to-end working) plus stubs for `hermes`, `pi`, `openhuman` (which print manual-install hints until deeper YAML/TS adapters land). Each adapter: detect → backup the agent's existing config to `~/.agentmemory/backups/-.` → merge → re-read & verify → idempotent on re-run. Supports `--dry-run`, `--force`, `--all`. Interactive picker when run without an agent argument. + +- **`agentmemory remove` command** ([PR #406](https://github.com/rohitg00/agentmemory/pull/406)). Tears down everything agentmemory installed: pidfile + state file + preferences + backups + `~/.local/bin/iii` (only when it matches the version we installed) + any agent connections. Asks separately for `.env` (holds API keys) and for the memory data dir. Requires two confirmations by default. Supports `--force`, `--keep-data`. + +- **`agentmemory doctor` v2** (PR #406). Replaces the passive reporter with an interactive fixer. Each diagnostic prints problem + cause + fix-preview, then offers Fix / Skip / More / Quit. Checks: missing `.env`, missing LLM key, engine version mismatch, viewer port unreachable, stale pidfile, empty API keys, iii on PATH outside `~/.local/bin/iii`. New flags: `--all` (apply every fix, for CI), `--dry-run` (show plan only). + +- **`agentmemory stop --force`** ([PR #405](https://github.com/rohitg00/agentmemory/pull/405)). Bypasses the Docker-compose heuristic refusal so engines started before v0.9.14 (which had no state file) can be torn down without a hand-rolled `lsof | xargs kill -9`. + +- **`--reset` flag**. Wipes preferences and re-runs the onboarding wizard (PR #403). + +- **`--verbose` / `AGENTMEMORY_VERBOSE=1`**. Restores the pre-v0.9.15 25-line `[agentmemory] X` engine-boot log stream for debugging (PR #403). Default is muted to a single ready-line. + +### Changed + +- **First-run output trimmed from 30+ lines to ~10**. The `[agentmemory] Worker v0.9.x` boot log stream is now buffered behind a `bootLog` shim (`src/logger.ts`) and only surfaces when `--verbose` is passed. The default surface is the splash banner, the onboarding prompts (first run only), a single engine spinner, and a one-line ready hint: `Memory ready on :3111 · viewer on http://localhost:3113 · try: agentmemory demo`. + +- **`isEngineRunning()` short-circuit now adopts the engine** ([PR #405](https://github.com/rohitg00/agentmemory/pull/405)). When the CLI finds an existing engine on `:3111`, it now writes `~/.agentmemory/iii.pid` (resolved via `lsof -i :PORT -sTCP:LISTEN -t`) and `~/.agentmemory/engine-state.json` (`{kind:"native", configPath, attached:true}`) if neither exists. Closes the migration gap where pre-v0.9.14 engines could not be stopped via `agentmemory stop` because no state file was written by the older code. + +- **Viewer port auto-bump** (PR #405). When `:3113` is taken, the viewer now retries 3114 → 3115 → … up to 3122 before failing loud. Pre-fix behaviour was a silent `Viewer port 3113 already in use, skipping viewer.` which left users staring at the previous run's stale viewer. + +- **Engine version-mismatch warning** (PR #405). When the iii binary on PATH (or attached engine) is not the pinned `IIPINNED_VERSION` (currently v0.11.2), the CLI now prints a clearly-labelled `p.log.warn` with the override path (`AGENTMEMORY_III_VERSION=...` env var or downgrade curl one-liner). Pre-fix was silent acceptance — v0.11.6 on PATH led to undebuggable EPIPE loops. + +- **npx PATH hint** (PR #405). After the engine is ready, runs invoked via `npx` get one extra line: `Tip: install globally for the bare \`agentmemory\` command: npm install -g @agentmemory/agentmemory`. Suppressible via `preferences.skipNpxHint`. + +### Fixed + +- `lsof -i :PORT -t` was returning client PIDs alongside the LISTEN-socket owner (already fixed in v0.9.14 via the `-sTCP:LISTEN` flag + `process.pid` filter; called out here so anyone bisecting the wave knows the LISTEN flag is what stopped the CLI from killing itself). + +### Infrastructure + +- New modules: `src/cli/splash.ts`, `src/cli/preferences.ts`, `src/cli/onboarding.ts`, `src/cli/connect/{index,types,claude-code,codex,cursor,gemini-cli,openclaw,hermes,pi,openhuman,json-mcp-adapter}.ts`, `src/cli/doctor-diagnostics.ts`, `src/cli/remove-plan.ts`, `src/logger.ts` (bootLog shim). +- New tests: `test/preferences.test.ts` (7), `test/cli-connect.test.ts` (13), `test/cli-doctor-fixes.test.ts` (18), `test/cli-remove.test.ts` (13). 944 tests passing, 10 pre-existing `mcp-standalone.test.ts` failures unrelated to this wave. + +[0.9.15]: https://github.com/rohitg00/agentmemory/compare/v0.9.14...v0.9.15 + +## [0.9.14] — 2026-05-15 + +CLI bootstrap rework so `npx @agentmemory/agentmemory` stops failing on Rancher Desktop and other Docker-shim daemons. The native iii-engine binary is now the first-class start path; Docker becomes opt-in. Also ships `agentmemory stop` so engines started in the background can be torn down without `lsof | xargs kill`. README agents grid reorders OpenHuman next to the other native-integration agents. + +### Added + +- **`agentmemory stop` command** ([PR #396](https://github.com/rohitg00/agentmemory/pull/396)). Reads `~/.agentmemory/iii.pid` first, falls back to `lsof -i :PORT -sTCP:LISTEN -t`, sends `SIGTERM`, waits 3s, escalates to `SIGKILL`. iii-engine doesn't currently handle `SIGTERM` cleanly so the SIGKILL escalation is what actually frees the port. State file (`~/.agentmemory/engine-state.json`) records whether the engine was started natively or via `docker compose up -d`, so `stop` runs `docker compose -f down` for Docker engines instead of signaling the host's Docker socket proxy by accident. + +- **`AGENTMEMORY_USE_DOCKER=1` env var**. Opt-in path for users who want the bundled `docker-compose.yml` to keep handling iii-engine lifecycle. Without it, the CLI prefers the native binary in `~/.local/bin/iii`. Documented in `npx @agentmemory/agentmemory --help`. + +### Changed + +- **`startEngine()` fallback order rewritten** ([PR #396](https://github.com/rohitg00/agentmemory/pull/396)). New tier order: (1) `iii` on PATH, (2) `~/.local/bin/iii` or other fallback paths, (3) interactive clack `p.select` with three choices — auto-install the pinned v0.11.2 binary, use Docker compose, or print manual install instructions and exit, (4) Docker compose only via explicit opt-in or the post-install failure fallback, (5) fail-loud with install instructions. CI / non-TTY environments auto-pick install. The Docker fallback was tier 2 and silently fired on every cold start; on Rancher Desktop `docker compose up -d` returns 0 even when the daemon's pull silently fails, which is what produced the "engine started but REST never responded" misdiagnoses we've been seeing this week. + +- **Installer logic extracted from `runUpgrade` into `runIiiInstaller()`**. Both first-run and `agentmemory upgrade` now share the same pinned-v0.11.2 curl-and-tar path. The pre-v0.9.14 installer only ran on `npx @agentmemory/agentmemory upgrade`, so first-time users never auto-installed. + +- **`installInstructions()` copy reordered**. The curl one-liner now leads (path A), Docker is path B with the `AGENTMEMORY_USE_DOCKER=1` env-var hint. The historical "Why pinned" rationale moved out of the failure note (it's still in the source comment for anyone debugging the pin choice). + +- **README agents grid reordered** ([PR #397](https://github.com/rohitg00/agentmemory/pull/397)). Row 1 is now Claude Code → Codex CLI → OpenClaw → Hermes → pi → OpenHuman → Cursor → Gemini CLI. OpenHuman moved from slot 3 to slot 6 so the native-Memory-trait callout reads cleanly alongside the other native-integration agents. + +### Fixed + +- **CLI no longer kills its own parent process**. `lsof -i :PORT -t` returns every PID with an active TCP connection to the port, including the CLI's own keep-alive `fetch()` from `isEngineRunning()`. Without a LISTEN filter, `agentmemory stop` would SIGKILL itself — exit code 137, state files never cleaned up. Now filters to `-sTCP:LISTEN` and drops `process.pid` from the candidate set. + +- **`agentmemory stop` no longer clears the pidfile when a stale process holds the port**. The HTTP probe can fail while the engine is hung, paused, or in a half-closed state. The pre-fix behaviour cleared the pidfile and printed "Nothing to stop" — the next run would silently start a second engine on a port that the first engine still owns. Now preserves the pidfile and surfaces the live PIDs with `ps -p` + `lsof` hints so the operator can investigate before manual cleanup. + +- **Docker-started engines stop safely**. The pre-fix code called `findEnginePidsByPort` and signaled whatever held :3111. When the engine was started via `docker compose up -d`, that's the host's Docker socket proxy (`com.docker.backend`, `vmnetd`), not the engine — killing it took down Docker Desktop networking for every other container. The new state file lets `runStop` detect Docker-managed engines and run `docker compose down` instead. + +### Infrastructure + +- Engine process now writes both `~/.agentmemory/iii.pid` and `~/.agentmemory/engine-state.json` at spawn. State file is cleared on clean shutdown or abnormal exit; pidfile is preserved when stale PIDs hold the port so the operator can investigate. + +[0.9.14]: https://github.com/rohitg00/agentmemory/compare/v0.9.13...v0.9.14 + +## [0.9.13] — 2026-05-15 + +Six PRs landed since v0.9.12 — `.env.example` discovery shipped (#372), CJK BM25 tokenizer landed (#344 / PR #362), `benchmark/load-100k.ts` load harness landed (#346 / PR #363), one-click deploy templates for fly.io / Railway / Render / Coolify added (#343 / PR #361), Gemini provider defaults moved to current GA models (#246 + #368 / PR #370), and the in-tree Python ecosystem story switched from a duplicate REST client to a one-page `iii-sdk` example (#342 / PR #364). Plus 14 Dependabot security advisories closed via Next.js + PostCSS bumps. + +### Added + +- **`.env.example` at repo root + bundled in the npm tarball** ([#372](https://github.com/rohitg00/agentmemory/issues/372), closes [#47](https://github.com/rohitg00/agentmemory/issues/47), [#293](https://github.com/rohitg00/agentmemory/issues/293), partial [#233](https://github.com/rohitg00/agentmemory/issues/233)). Every env var actually read by `src/` is now documented in one place, grouped by surface (LLM provider, embedding provider, auth, search tuning, behaviour flags, CLI runtime, ports, iii engine pin, Claude Code bridge, Obsidian export). Every line is commented out by default so the file ships as a config template, not a config. The npm package now lists `.env.example` in its `files` field so `npm i -g @agentmemory/agentmemory` carries it. + +- **`agentmemory init` command**. Copies the bundled `.env.example` to `~/.agentmemory/.env` if that file doesn't already exist; refuses to overwrite an existing config and prints a diff command pointing at the latest template. Wired into the CLI help block alongside `status` / `doctor` / `demo` / `upgrade` / `mcp` / `import-jsonl`. + +- **CI sync-checker for `.env.example`** (`scripts/check-env-example.mjs`). Walks every `.ts` / `.mts` / `.mjs` / `.js` file under `src/`, extracts `process.env["KEY"]` / `env["KEY"]` / `getMergedEnv()["KEY"]` / `getEnvVar("KEY")` references, and fails CI when `src/` reads an env var the template doesn't document (or vice versa). Plugged into `.github/workflows/ci.yml` after `npm test`. Initial bootstrap: 60 keys in sync. + +- **CJK tokenizer for BM25 search** ([#344](https://github.com/rohitg00/agentmemory/issues/344), PR [#362](https://github.com/rohitg00/agentmemory/pull/362)). New `src/state/cjk-segmenter.ts` detects CJK input by Unicode block and routes to `@node-rs/jieba` (Chinese, native, no model download), `tiny-segmenter` (Japanese, pure JS, ~25 KB), or rule-based syllable-block split (Korean). Both segmenters declared in `optionalDependencies` so the base install stays lean; soft-fail with a one-time stderr hint when the dep is missing. Order-preserving single-pass tokenization across mixed CJK + non-CJK runs (regression test for `"abc 메모리 def 项目 ghi"` returns `["abc","메모리","def","项目","ghi"]`). + +- **`benchmark/load-100k.ts` load harness** ([#346](https://github.com/rohitg00/agentmemory/issues/346), PR [#363](https://github.com/rohitg00/agentmemory/pull/363)). Hand-rolled, dependency-free harness that seeds N synthetic memories against a local daemon at `http://localhost:3111` and records p50 / p90 / p99 latency + throughput for `POST /agentmemory/remember`, `POST /agentmemory/smart-search`, and `GET /agentmemory/memories?latest=true` across the matrix N ∈ {1k, 10k, 100k} × concurrency C ∈ {1, 10, 100}. Content drawn from a seedable `mulberry32` PRNG so re-running against the same build produces the same seed corpus. Results land in `benchmark/results/load-100k-.json`. Wired as `npm run bench:load`. + +- **One-click deploy templates** for fly.io, Railway, Render, and Coolify ([#343](https://github.com/rohitg00/agentmemory/issues/343), PR [#361](https://github.com/rohitg00/agentmemory/pull/361)). Each template under `deploy//` ships a multi-stage Dockerfile that `COPY --from=iiidev/iii:0.11.2`s the engine binary into a `node:22-slim` runtime, npm-installs `@agentmemory/agentmemory` under `/opt/agentmemory` with `iii-sdk` pinned via `package.json` overrides (avoids the caret-resolves-to-0.11.6 drift), and runs an entrypoint that rewrites the bundled `iii-config.yaml` to bind `0.0.0.0` + use absolute `/data` paths, chowns the platform-mounted volume to `node:node` via `gosu`, generates a first-boot HMAC secret, and exec's the agentmemory CLI as the unprivileged `node` user under `tini` (with `TINI_SUBREAPER=1`). Verified end-to-end on fly.io (machine in `iad`, 1 GB volume, healthcheck passing). + +- **`examples/python/`** quickstart + observation/recall flow showing `iii-sdk` (Python) calling `mem::remember` / `mem::smart-search` / `mem::context` directly over `ws://localhost:49134` ([#342](https://github.com/rohitg00/agentmemory/issues/342), PR [#364](https://github.com/rohitg00/agentmemory/pull/364)). Replaces a duplicate-transport Python REST client (initial PR #360, closed) with a single-SDK story — the same `iii-sdk` install (`pip install iii-sdk` / `cargo add iii-sdk` / `npm install iii-sdk`) talks to every agentmemory function from any language. + +### Changed + +- **Gemini provider defaults bumped to current GA models** (PR [#370](https://github.com/rohitg00/agentmemory/pull/370), closes [#368](https://github.com/rohitg00/agentmemory/pull/368), [#246](https://github.com/rohitg00/agentmemory/pull/246)). LLM default `gemini-2.0-flash` → `gemini-2.5-flash` (the moving `gemini-flash-latest` alias was rejected — release behaviour should be deterministic). Embedding default `text-embedding-004` → `gemini-embedding-001` (the previous default is deprecated and shuts down 2026-01-14 per `ai.google.dev/gemini-api/docs/deprecations`). Three implementation details ride along: (1) URL path `:batchEmbedContent` → `:batchEmbedContents`, (2) every request now sends `outputDimensionality: 768` so the returned vectors match `GeminiEmbeddingProvider.dimensions = 768` and the index-restore dim guard from #248 — no reindex needed, (3) returned vectors are L2-normalized before the result-array push because `gemini-embedding-001` does **not** normalize by default unlike `text-embedding-004` and without this the downstream cosine-similarity math silently collapses recall. `l2Normalize` warns once on a zero-norm embedding so operators can correlate index quality dips with upstream regressions. + +### Security + +- **14 open Dependabot advisories closed via Next.js + PostCSS bumps** (PR [#348](https://github.com/rohitg00/agentmemory/pull/348)). Closed: 13 Next.js advisories (middleware/proxy bypass + SSRF on WebSocket upgrades + DoS via connection exhaustion + CSP-nonce XSS + image-opt DoS + RSC cache poisoning + beforeInteractive XSS + segment-prefetch routes) by bumping the website's Next.js to `^16.2.6`. Plus the PostCSS XSS-via-unescaped-`` advisory closed by pinning to `^8.5.10` via `overrides` in `website/package.json`. Verified `npm audit --omit=dev` returns 0 and `npm run build` clean on Next 16.2.6. Dependabot now runs weekly against six update streams (npm × 5 paths + github-actions) per the new `.github/dependabot.yml`. + +### Contributors + +External contributors landed this release: + +- [@fatinghenji](https://github.com/fatinghenji) — pre-cleanup work on the OpenAI-compatible LLM provider (PR #240 / PR #307); the universal-adapter shape will land in the next minor once branch maintenance catches up. +- [@AmmarSaleh50](https://github.com/AmmarSaleh50) — Gemini embedding migration with L2-norm + 768-dim plumbing (PR #246, folded into #370). +- [@yut304](https://github.com/yut304) — Gemini LLM default deprecation fix (PR #368, folded into #370). + +Thanks also to the issue reporters whose precise repros drove the search-quality + viewer + config-template work this cycle. + +## [0.9.12] — 2026-05-13 + +Four landed PRs since v0.9.11 — one type-correctness fix, one search-quality fix (BM25 unicode + vector-index live-write), one viewer hardening (CSP-clean fonts + load-error surface), and one integrations security hardening (bearer token over plaintext HTTP). + +### Fixed + +- **BM25 tokenizer now indexes non-ASCII (Greek, accented Latin, Hebrew, Arabic) and the vector index is actually populated at runtime** ([#327](https://github.com/rohitg00/agentmemory/pull/327), closes [#295](https://github.com/rohitg00/agentmemory/issues/295)). `src/state/search-index.ts` previously stripped every non-ASCII character via `\w` (JS `\w` is ASCII-only), so non-English search returned empty results across the board. Regex replaced with `/[^\p{L}\p{N}\s/.\\-_]/gu` — keeps Unicode letters/numbers, preserves underscore (matters for `memory_recall`-style identifiers), keeps existing path/separator handling. Separately, `VectorIndex.add()` had **zero callers** anywhere in `src/` — the vector index was loaded from disk at startup and never updated at runtime, so hybrid search returned stale results forever. New `vectorIndexAddGuarded()` helper in `src/functions/search.ts` wires `vectorIndex.add()` into `remember.ts`, `observe.ts` synthetic-compression branch, `compress.ts` post-LLM compression, and the cold-start `rebuildIndex()` walk — with a per-write dimension guard (symmetric to the persistence-load guard from #248), 16k-char input clipping (so an oversized memory can't 400 the embed call), and consistent stderr logging that no longer swallows embed failures. `migrateVectorIndex()` utility re-embeds every memory + per-session observation against a new provider when dimensions change; per-session try/catch isolation so one bad session can't abort the whole migration; structured `failedSessions[]` result with a `""` sentinel that distinguishes a catastrophic list-failure from per-session failures. Soft-fail throughout: a downed embedder never breaks an upstream save. Live-tested end-to-end against Greek fixtures (thanks @nik1t7n for the original repro on Cyrillic content; test fixtures swapped to Greek before merge). + + **CJK caveat preserved**: this fix recovers Greek, Cyrillic, accented Latin, Hebrew, Arabic, and other space-delimited scripts. CJK languages without spaces between characters still tokenize as a single sentence-long token — separate concern, needs a segmenter (PR #224 area). + +- **`@agentmemory/mcp` standalone shim's `RetentionScore` type no longer declares `source` twice** ([#326](https://github.com/rohitg00/agentmemory/pull/326), closes [#277](https://github.com/rohitg00/agentmemory/issues/277)). `src/types.ts:835` and `:842` both declared `source?: "episodic" | "semantic"` on `RetentionScore`. TypeScript silently accepts duplicate property declarations when the types are identical, so the build never errored — but the documented JSDoc on the first declaration (the #124 back-compat note explaining `undefined` should probe both scopes) was effectively shadowed by the duplicate. Removed the second declaration; grep confirmed no caller writes `source` twice on the same `RetentionScore` row, so the cleanup is a pure type-correctness fix with no runtime change. Thanks @cl0ckt0wer for the precise file:line trace. + +- **Viewer dashboard no longer sticks on "Loading dashboard…" when the page loads** ([#335](https://github.com/rohitg00/agentmemory/pull/335), closes [#323](https://github.com/rohitg00/agentmemory/issues/323)). Two narrow fixes from @hem57's Windows repro: (1) removed the `` to `fonts.googleapis.com` — the viewer's strict CSP (`default-src 'none'`, `style-src 'unsafe-inline'`, `font-src 'self'`) blocks external stylesheet origins by design, so every page load logged a CSP violation for the font CSS and another for each blocked font file; system-font fallbacks were already declared on every `--font-*` CSS variable so dropping the external `` is a clean swap. (2) Wrapped `loadDashboard()` body in a `try/catch` that renders the error inline ("Dashboard failed to load: ") instead of leaving the placeholder text up forever — future "stuck Loading" reports now come with concrete error messages instead of just a screenshot of the placeholder. + +- **Integrations (hermes / openclaw / pi) now warn when sending the bearer token over plaintext HTTP to a non-loopback host** ([#315](https://github.com/rohitg00/agentmemory/pull/315), closes [#275](https://github.com/rohitg00/agentmemory/issues/275)). Symmetric guard across all three plugin runtimes (Python / mjs / TypeScript): a request that would attach `Authorization: Bearer ` to a `http://:port` URL now logs a one-time stderr warning telling the operator the token is observable on the wire. Loopback hosts (`localhost`, `127.0.0.1`, `::1`) and `https://` URLs are exempt. New env knob `AGENTMEMORY_REQUIRE_HTTPS=1` escalates the warning to a hard refusal — the plugin throws before any request is sent, so a misconfigured deployment can fail loudly instead of leaking the bearer once. Edge cases verified by 13 tests: IPv6 `[::1]` loopback, RFC1918 LAN IPs (`192.168.x.x` / `10.x.x.x` warn — NOT loopback), lookalike hostnames (`localhost.evil.com` warns), no-secret short-circuit (guard never fires when no bearer would be sent), https-with-secret silent. Thanks [@mvanhorn](https://github.com/mvanhorn) for the cross-runtime implementation. + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.11 → 0.9.12 to lockstep with the main package. + +## [0.9.11] — 2026-05-13 + +Three additions on top of v0.9.10: OpenAI Codex got a plugin platform and agentmemory now ships a Codex manifest + marketplace alongside the existing Claude Code one (so `codex plugin marketplace add rohitg00/agentmemory` installs MCP + 6 hooks + 4 skills in one step); the OpenClaw integration now actually claims the `plugins.slots.memory` slot via `registerMemoryCapability` (older builds advertised the slot via manifest `kind` but never declared the capability so the slot reported `unavailable`); and the marketing website's hero CTA row now ships a live "Star on GitHub" button. + +### Added + +- **Codex plugin support** ([#311](https://github.com/rohitg00/agentmemory/pull/311)). `plugin/.codex-plugin/plugin.json` Codex manifest pointing at the same shared `.mcp.json` + `skills/` directory the Claude Code manifest uses, plus a Codex-shaped `plugin/hooks/hooks.codex.json` that registers exactly the events Codex's hook engine supports (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`) and drops the Claude-Code-only ones (`SubagentStart`, `SubagentStop`, `SessionEnd`, `Notification`, `TaskCompleted`, `PostToolUseFailure`). Verified against `codex-rs/hooks/src/engine/discovery.rs` that Codex injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses for OOTB compat with existing Claude Code plugin scripts — so the same `${CLAUDE_PLUGIN_ROOT}/scripts/...` references work on both hosts. `.codex-plugin/marketplace.json` at the repo root publishes the plugin via the Codex marketplace API (`git-subdir` source pointing at `./plugin`), so end users run `codex plugin marketplace add rohitg00/agentmemory && codex plugin install agentmemory` once and get MCP + lifecycle hooks + 4 skills (`/recall`, `/remember`, `/session-history`, `/forget`). + +- **`Star on GitHub` button in the website hero CTA row** ([#316](https://github.com/rohitg00/agentmemory/pull/316)). Adds a ghost-style `GitHubStarButton` component next to `START IN 60 SECONDS` and `SEE IT MOVE` with inline SVG star icon, `STAR` label, and a live stargazer count fetched once on mount from `api.github.com/repos/rohitg00/agentmemory`. Count is cached in `localStorage` for 30 minutes per repo. Graceful degradation: if the API is unreachable / rate-limited / blocked, the button still renders without the count. No new dependencies. + +### Fixed + +- **OpenClaw `plugins.slots.memory = "agentmemory"` now reports as available, not `unavailable`** ([#310](https://github.com/rohitg00/agentmemory/pull/310)). On OpenClaw `2026.4.9+`, the integration declared `"kind": "memory"` in its manifest and wired `before_agent_start` / `agent_end` hooks but **never called `api.registerMemoryCapability(...)`** — so OpenClaw's memory-slot machinery saw no claim on the slot even though the hooks and REST API worked end-to-end. The fix lands `api.registerMemoryCapability({ promptBuilder })` at register time when the host exposes it, with the `promptBuilder` accepting the documented `{ availableTools, citationsMode? }` params and emitting a three-line block identifying agentmemory as the active provider. Older OpenClaw builds without the capability API still load via the existing hook-only path (`typeof api.registerMemoryCapability === "function"` guard). The PR does **not** ship a `MemoryPluginRuntime` adapter because OpenClaw's current `MemoryRuntimeBackendConfig` type is exactly `{ backend: "builtin" } | { backend: "qmd"; ... }` — both in-process backends that don't fit an external REST shape. Verified against `openclaw@2026.5.7`'s `plugin-sdk/src/plugins/types.d.ts` and `memory-state.d.ts` declarations directly. (closes the bug premise originally surfaced in the closed PR #302, which had attempted the same goal but with an import path that wasn't in the package's `exports` map and a symbol that didn't exist in any released openclaw version.) + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.10 → 0.9.11 to lockstep with the main package. +- README now distinguishes **Codex CLI (MCP only)** from **Codex CLI (full plugin)** in the per-host install table and lists the marketplace install command for the latter. + +## [0.9.10] — 2026-05-12 + +Three deployment-shape fixes reported live by [@flamerged](https://github.com/flamerged) ([#299](https://github.com/rohitg00/agentmemory/issues/299), [#301](https://github.com/rohitg00/agentmemory/issues/301)): the v0.9.7 docker-compose persistence fix was incomplete because the distroless engine runs as UID 65532 but `docker volume create` initializes the named volume mountpoint as `root:root mode 755`; the viewer's port-detection JS hardcoded `'3113'` so any reverse-proxy fronting on port 80/443 returned an empty dashboard; and the `mem::context` budget loop short-circuited the entire selection on the first oversized block — pinning a large slot could starve all other context blocks even when smaller ones would have fit. + +### Fixed + +- **`docker-compose.yml` now chowns the named volume to UID 65532 before the engine starts.** The `iiidev/iii` image is distroless and runs as UID 65532; docker initializes named volumes as `root:root mode 755`; the engine has no `sh` / `chown` to self-heal at startup, so writes to `/data/state_store.db` and `/data/stream_store` returned `Permission denied (os error 13)`. The engine silently buffered in RAM, the API kept reporting `success: true`, and state evaporated on every container restart — the exact symptom v0.9.7's working-directory fix set out to solve. The compose file now ships an `iii-init` one-shot service (`busybox:1.36`, ~4 MB, exits in <100 ms) that runs `chown -R 65532:65532 /data && chmod 755 /data` once at compose-up, plus a `user: "65532:65532"` directive on the `iii-engine` service and a `depends_on.iii-init.condition: service_completed_successfully` gate so the engine never starts before the volume is owner-correct. Existing deployments that already hit the bug should run `docker compose down && docker compose up -d` after upgrading — the init container will fix the volume in place on the first run. (#301, closes [#301](https://github.com/rohitg00/agentmemory/issues/301) — thanks [@flamerged](https://github.com/flamerged) for the precise UID + mountpoint trace and the chown workaround that confirmed the fix shape) + +- **Viewer dashboard now works behind any reverse proxy on standard ports (80 / 443).** `src/viewer/index.html`'s port-detection JS resolved the REST base URL through `params.get('port') || window.location.port || '3113'` — when the page was served on port 80 or 443, `window.location.port` was the empty string and the fallback hardcoded `':3113'`, so every browser-side `/agentmemory/*` fetch missed the proxied origin and went to `:3113` (typically loopback-only on these deployments, so unreachable from outside). The viewer rendered cleanly but every panel showed the empty "first run" state — even though `curl /agentmemory/sessions` (no explicit port) returned correct data. The fix uses `window.location.origin` as the REST base when neither `?port=` nor `window.location.port` is set, and constructs the WebSocket URL from `window.location.host` (with whatever port the page was served on) so the same-origin path works for both REST and live updates. Behaviour with an explicit `?port=N` or non-default `window.location.port` is unchanged. (#299, closes [#299](https://github.com/rohitg00/agentmemory/issues/299) — thanks [@flamerged](https://github.com/flamerged) for the deployment context + the lines-927–930 trace) + +- **`mem::context` budget loop no longer bails the entire selection on the first oversized block.** The selection loop in `src/functions/context.ts` used `break` when `usedTokens + block.tokens > budget`, so a single oversized block at the top of the sorted list — most commonly a fat pinned slot under #288's new injection path — cut off every smaller block that would have fit. Switched to `continue`, so smaller blocks downstream of an oversized one can still slip into the remaining budget. Net effect: pinned-slot priority semantic is preserved (pinned blocks still sort first via `recency: Date.now()`), but the worst case no longer starves the entire context. Total tokens still bounded by `tokenBudget` (default 2000); only the composition under contention changes. + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.9 → 0.9.10 to lockstep with the main package. + +## [0.9.9] — 2026-05-11 + +Two field-reported regressions closed: pinned memory slots never reached SessionStart context (the `renderPinnedContext` and `listPinnedSlots` helpers shipped in v0.7 had no callers), and the MiniMax compression provider read its base URL straight off `process.env`, missing `~/.agentmemory/.env` values that the rest of agentmemory loads through the shared merged-env path. + +### Fixed + +- **Pinned memory slots are now actually injected into SessionStart context.** [@wyh0626](https://github.com/wyh0626) traced ([#286](https://github.com/rohitg00/agentmemory/issues/286)) that `renderPinnedContext` (`src/functions/slots.ts:182`) and `listPinnedSlots` (`src/functions/slots.ts:169`) — introduced in [#182](https://github.com/rohitg00/agentmemory/pull/182) — had zero callers in `src/`. `mem::context` (the function `/agentmemory/session/start` invokes and that `session-start.mjs` reads back into Claude Code) read profile / sessions / summaries / observations but never slots, so anything an agent wrote into a pinned slot via `mem::slot-replace` / `mem::slot-append` / `mem::slot-reflect` sat in KV and never reached the next session. The `mem::slot-reflect` writer fires on the Stop hook when `AGENTMEMORY_REFLECT=true` and persists into `pending_items` / `session_patterns` / `project_context` — the reflect → next-session loop was open. The fix wires `listPinnedSlots` → `renderPinnedContext` into `mem::context` behind `isSlotsEnabled()`, matching the existing `isGraphExtractionEnabled()` gate convention. Pinned slot content lands as a `type: "memory"` block with `recency: Date.now()` so it sorts to the top of the budget-bounded selection. `AGENTMEMORY_SLOTS=false` (the default) keeps the existing behaviour untouched. (#288, closes [#286](https://github.com/rohitg00/agentmemory/issues/286) — thanks [@wyh0626](https://github.com/wyh0626) for the precise zero-callers trace and the six-case regression suite covering global / multi-sort / unpinned-skip / empty-skip / project-shadows-global / gate-off) + +- **MiniMax provider now honors `MINIMAX_BASE_URL` from `~/.agentmemory/.env`, with the default pointed at the current Anthropic-compatible host.** [@rager306](https://github.com/rager306) reported ([#285](https://github.com/rohitg00/agentmemory/issues/285)) v0.9.8 MiniMax compression failing `MiniMax API error 401: invalid api key` against a verified-good key. Direct `curl https://api.minimax.io/anthropic/v1/messages` with the same key succeeded; the control call against `https://api.minimaxi.com/anthropic` returned 401. The 401 was the *stale fallback host* answering — the key was fine. Root cause: split-brain env source. `src/config.ts` (provider detection + API-key load) reads `~/.agentmemory/.env` through the merged `getMergedEnv()` loader; `src/providers/minimax.ts` read `MINIMAX_BASE_URL` straight off `process.env`. Deployments that kept MiniMax config in `~/.agentmemory/.env` only (systemd / launchd / `--env-file` not exported into the worker shell) got the key loaded but the base URL fell through to the stale default. The provider now resolves `MINIMAX_BASE_URL` via `getEnvVar()` (same merged loader the rest of agentmemory uses), and the default is bumped from `api.minimaxi.com` to `api.minimax.io/anthropic` per [MiniMax's current Anthropic-compatible docs](https://platform.minimax.io/docs/api-reference/text-anthropic-api). (#289, closes [#285](https://github.com/rohitg00/agentmemory/issues/285) — thanks [@rager306](https://github.com/rager306) for the precise repro and the local-patch verification) + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.8 → 0.9.9 to lockstep with the main package. + +## [0.9.8] — 2026-05-11 + +Single-line follow-up to v0.9.7's MCP shim work. v0.9.7 surfaced probe failures, added an `AGENTMEMORY_FORCE_PROXY=1` escape hatch, and shipped `AGENTMEMORY_DEBUG=1` — but the *local-mode* `tools/list` branch was still returning only 4 tools when an agentmemory server was unreachable, not the documented 7-tool `IMPLEMENTED_TOOLS` set the shim's `InMemoryKV` actually backs. v0.9.8 fixes that. + +### Fixed + +- **`@agentmemory/mcp` local-mode `tools/list` now exposes all 7 `IMPLEMENTED_TOOLS`, not the 4-tool intersection with `ESSENTIAL_TOOLS`.** The local-fallback branch in `src/mcp/standalone.ts` filtered `getVisibleTools()` through `IMPLEMENTED_TOOLS`, but `getVisibleTools()` honors the shim process's own `AGENTMEMORY_TOOLS` env var (unset → "core" → 8 `ESSENTIAL_TOOLS`). The intersection of `ESSENTIAL_TOOLS` (8) and `IMPLEMENTED_TOOLS` (7) is exactly 4 tools: `memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`. Those four were the only ones MCP clients saw when no agentmemory server was reachable — even though the shim's `InMemoryKV` implements all seven (the four above plus `memory_export`, `memory_audit`, `memory_governance_delete`). The filter source was wrong: the shim dispatches by `IMPLEMENTED_TOOLS`, not by `ESSENTIAL_TOOLS`, so a server-tier env var should never have shaped the shim's local-fallback list. Switched to `getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name))`, which picks the same 7 names from the unfiltered universe regardless of `AGENTMEMORY_TOOLS`. Refactored the `tools/list` handler into an exported `handleToolsList()` for direct testability, and added a regression test asserting the local-fallback path returns exactly the 7 names under both unset and `core` modes. Verified live via stdio against a downed server: shim now returns 7 names (was 4). (#283, closes [#234](https://github.com/rohitg00/agentmemory/issues/234)) + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.7 → 0.9.8 to lockstep with the main package. + +## [0.9.7] — 2026-05-11 + +Four follow-up fixes to v0.9.6 reported live by [@jcalfee](https://github.com/jcalfee) ([#234](https://github.com/rohitg00/agentmemory/issues/234)) and [@satabd](https://github.com/satabd) ([#278](https://github.com/rohitg00/agentmemory/issues/278)): the `@agentmemory/mcp` shim gained probe diagnostics and an escape hatch for clients that can reach the server via a non-default route, the Docker compose stack now persists state across `docker compose down` (the volume binding was unused due to a working-directory mismatch in the engine config), a cosmetic `which iii` stderr leak was suppressed, and the engine container's log output is now bounded so a crash/restart spam loop can no longer fill the host disk. + +### Fixed + +- **`@agentmemory/mcp` standalone shim now surfaces probe failures and ships an escape hatch and a debug-trace knob.** The `livez` probe in `src/mcp/rest-proxy.ts` used a 500 ms timeout and silently swallowed every failure: when the probe failed, the shim fell back to the 7-tool `IMPLEMENTED_TOOLS` set with no log line explaining why. The probe now writes the URL, HTTP status (or thrown reason), and the active timeout to `stderr` on every failure; the default timeout is raised to 2000 ms; `AGENTMEMORY_PROBE_TIMEOUT_MS` overrides it for slow loopbacks; `AGENTMEMORY_FORCE_PROXY=1` skips the probe entirely and trusts `AGENTMEMORY_URL` outright (the right escape hatch when the shim can reach the server via a known route but not the host's `localhost`); and `AGENTMEMORY_DEBUG=1` traces `tools/list` end-to-end (`handle.mode`, response shape, returned tool count, local-fallback contents) so MCP integrations have first-class visibility into what the shim is actually returning over the wire. The shim verified end-to-end via stdio against an `AGENTMEMORY_TOOLS=all` server: `tools/list` returns all 51 tools. (closes [#234](https://github.com/rohitg00/agentmemory/issues/234), thanks [@jcalfee](https://github.com/jcalfee) for the host-vs-sandboxed-client repro and detailed log captures) + +- **Docker compose stack no longer loses state on `docker compose down`.** `iii-config.docker.yaml` configured `iii-state` and `iii-stream` with relative `file_path: ./data/...`, which the engine resolves against its container `WORKDIR=/home/nonroot` — not the `/data` mount where the named `iii-data` volume lives. State and stream stores were written to the ephemeral container layer and discarded on every container restart, so memories, BM25 index, and stream backlog vanished. Both paths are now absolute (`/data/state_store.db` and `/data/stream_store`), routing writes through the named volume as the compose file always intended. Existing users need a one-time `docker compose down -v` to clear the old empty volume layout before the upgrade. + +- **CLI banner no longer leaks `which: no iii in $PATH` when iii isn't installed.** `whichBinary()` in `src/cli.ts` called `execFileSync("which", ["iii"])` with default stdio, which inherits the child's `stderr` to the parent process — and GNU `which` writes "no iii in (...)" to `stderr` (with exit 1) on miss. The catch swallowed the throw but the stderr line had already drained into the user's terminal between the `agentmemory` banner and the "iii-engine ready" line. `stdio: ["ignore", "pipe", "pipe"]` now captures both streams. Pure cosmetic, no behavior change. + +- **Docker compose stack now caps engine container log size at 30 MB total.** [@satabd](https://github.com/satabd) reported the `iiidev/iii:0.11.2` engine container filling a host disk with a 129 GB `-json.log` when the engine fell into a crash/restart spam loop ([#278](https://github.com/rohitg00/agentmemory/issues/278)). The compose service now sets `logging.driver: json-file` with `max-size: 10m` and `max-file: 3`, so unbounded engine stdout/stderr can no longer eat the host's disk. The upstream engine spam itself is filed against `iiidev/iii` — this is the compose-side guardrail. + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.6 → 0.9.7 to lockstep with the main package. + +## [0.9.6] — 2026-05-10 + +Three reliability fixes that close field-reported regressions in v0.9.5: search/recall returns saved memories again, the standalone MCP shim no longer caps non-Claude clients at a 7-tool subset, and the Claude Code session/subagent hooks no longer block agent startup for up to five seconds against a slow or unreachable REST server. + +### Fixed + +- **`memory_smart_search` and `memory_recall` surface memories saved via `memory_save` again.** v0.9.5 indexed memories into BM25 (#258), so search ranked them correctly — but the result-enrichment step on both retrieval paths still queried `KV.observations(sessionId, obsId)`. Memories live in `KV.memories` under a synthetic sessionId, so every hit was silently dropped and clients saw `results: []`. Both `HybridSearch.enrichResults` (which powers `/smart-search`) and `mem::search`'s observation map (which powers `/search` / `memory_recall`) now fall back to `KV.memories` when the observation lookup misses, coercing the `Memory` record into a `CompressedObservation` via a new shared `memoryToObservation` helper in `src/state/memory-utils.ts`. Verified live end-to-end against an iii-engine 0.11.2 stack: pre-fix both endpoints returned `[]` for a saved memory; post-fix the memory surfaces with `score > 0` on both. (#269, closes [#265](https://github.com/rohitg00/agentmemory/issues/265)) + +- **`@agentmemory/mcp` standalone shim now exposes the server's full tool surface to non-Claude clients.** With `AGENTMEMORY_TOOLS=all` on the server, OpenCode / Cursor / Gemini CLI / Cline users expected 51 tools; the shim filtered the response through a hardcoded 7-tool `IMPLEMENTED_TOOLS` set baked in for the local InMemoryKV fallback, so they got 4 (default) or 7 (with the env var). The shim now delegates `tools/list` to `GET /agentmemory/mcp/tools` when an agentmemory server is reachable, and forwards any non-essential tool to `POST /agentmemory/mcp/call` for server-side validation. The local InMemoryKV fallback is unchanged — it still implements only the 7 essential tools, with a clearer error pointing to `AGENTMEMORY_URL` when no server is reachable. Verified live end-to-end via stdio JSON-RPC driver: pre-fix `tools/list` returned 4 tools and `memory_lesson_save` raised "Unknown tool"; post-fix `tools/list` returned 51 and `memory_lesson_save` created a lesson. (#270, closes [#234](https://github.com/rohitg00/agentmemory/issues/234)) + +- **Claude Code session/subagent hooks no longer block agent startup waiting for a slow agentmemory.** `session-start.ts` awaited a 5000 ms POST and discarded the response whenever `AGENTMEMORY_INJECT_CONTEXT=false` (the default since 0.8.10) — pure latency. `subagent-start.ts` had a `// fire and forget` comment but the code awaited a 2000 ms POST. Under fan-out (Slack-bot orchestrators, multi-agent harnesses, fanned `claude -p` jobs) the awaited timeouts stack and feed back into the engine; the reporter hit a positive feedback loop that OOM-killed iii-engine. `session-start` now fire-and-forgets on the telemetry path and caps the inject path at 1500 ms (down from 5000 ms). `subagent-start` actually fire-and-forgets, capped at 800 ms. Verified live against a black-hole TCP listener (accepts, never replies): session-start (no inject) 5.05 s → 0.85 s, session-start (inject=true) 5.05 s → 1.55 s, subagent-start 2.05 s → 0.87 s. (#271, closes [#221](https://github.com/rohitg00/agentmemory/issues/221)) + +### Changed + +- `@agentmemory/mcp` package version bumped from 0.9.4 → 0.9.6 to lockstep with the main package, fixing a release-flow miss in v0.9.5. + +## [0.9.5] — 2026-05-09 + +Bug-fix patch focused on **search recall correctness** and **plugin compatibility**. Pins `iii-engine` to v0.11.2 because v0.11.6 introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet — pin lifts once that refactor lands. Adds a hard guard against silent vector-index corruption, fixes BM25 indexing for memories saved via `memory_save`, and lands four Hermes plugin fixes that make the memory provider actually usable end-to-end. + +If you've been seeing `memory_smart_search` return empty results for memories you just saved, this release fixes that. If you've been hitting `hermes memory status` reporting "not available" against a healthy systemd-managed install, this release fixes that too. + +### Fixed + +- **BM25 search now indexes memories saved via `memory_save`.** `mem::remember` was writing to `KV.memories` but never calling `getSearchIndex().add()`, so `memory_smart_search` and `memory_recall` returned empty for everything saved through that path — for **every** version since v0.9.0. Synthesizes a `CompressedObservation` from the saved Memory (title + content + concepts + files) and adds it to BM25 right after the durable write. `rebuildIndex()` now walks `KV.memories` so a fresh rebuild covers the full corpus, and a startup backfill retroactively indexes pre-existing memories on first start after upgrade — no manual reindex required. New `SearchIndex.has(id)` is the idempotency gate. (#258, closes [#257](https://github.com/rohitg00/agentmemory/issues/257) — thanks @Nizar-BenHamida for the precise repro and log capture) + +- **Embedding providers no longer silently corrupt the vector index when an API returns wrong-dimension vectors.** `cosineSimilarity` returns `0` on length mismatch instead of throwing, so a wrong-size vector got stored, never matched anything, and the corresponding memory became invisible without a single log line. `withDimensionGuard()` now wraps every embedding provider at the factory boundary in `src/providers/embedding/index.ts` — `embed()`, `embedBatch()` (per-vector, indexed errors like `embedBatch[3]`), and `embedImage()` all throw a descriptive error when the returned `Float32Array` length doesn't match `provider.dimensions`. The persistence-restore path got the same defense: `IndexPersistence.load()` now refuses to start when persisted vectors mismatch the active provider, with an actionable error spelling out the recovery paths (re-embed / `AGENTMEMORY_DROP_STALE_INDEX=true` / switch back). (#248, closes [#247](https://github.com/rohitg00/agentmemory/issues/247) and [#256](https://github.com/rohitg00/agentmemory/issues/256) — thanks @AmmarSaleh50 for the issue analysis, the fix PR, and the test coverage) + +- **Hermes plugin: `handle_tool_call` now returns JSON strings, not raw Python dicts.** Hermes stores the return value as the tool result `content` field in session history. Anthropic-protocol providers reject non-string content with a 400 on the next request — once triggered, every subsequent request in the affected session 400s until the session JSON is hand-cleaned. Wrapped all four return paths (`memory_recall`, `memory_save`, `memory_search`, unknown-tool) in `json.dumps()` and tightened the return-type annotation `Any → str` on both the abstract base and the concrete class. Matches the contract that `src/mcp/standalone.ts` already honors. (#255, closes [#254](https://github.com/rohitg00/agentmemory/issues/254) — thanks @KyoMio for the Anthropic-protocol-specific repro) + +- **Hermes plugin: `hermes memory status` now reflects the real service state on systemd / launchd installs.** When agentmemory runs as an external service whose runtime config lives in `~/.agentmemory/.env`, those values never reach the Hermes CLI shell. Hermes status reads `os.environ` against `get_config_schema()`'s `env_var` keys, finds them unset, and reports the plugin as "not available" — even though the service is healthy. The plugin now preloads `~/.agentmemory/.env` at import time using `os.environ.setdefault`, bridging the agentmemory-managed and Hermes-managed config source-of-truths. Anything explicitly exported in the shell still wins. Best-effort: malformed / absent file is silently skipped. Both `~/.agentmemory/.env` and `$XDG_CONFIG_HOME/agentmemory/.env` are checked. (#253, closes [#250](https://github.com/rohitg00/agentmemory/issues/250) — thanks @OptionalCoin for the systemd repro and tracing it to env-source divergence) + +- **Hermes plugin: memory provider hooks accept passthrough kwargs.** Hermes calls memory provider hooks with extra context kwargs (e.g. `session_id`) at runtime that the existing strict signatures rejected with `sync_turn() got an unexpected keyword argument 'session_id'`. Hooks "succeeded" from Hermes's perspective but every conversation turn silently failed sync. Added `**kwargs: Any` to `sync_turn`, `on_session_end`, `on_pre_compress`, `on_memory_write`, `prefetch`, `queue_prefetch`, and `shutdown`. Where Hermes passes `session_id`, the patch prefers it over the cached `self._session_id` so multi-session gateway contexts route to the right session. Same change applied to the abstract `MemoryProvider` fallback for the import-error path. (#252, closes [#249](https://github.com/rohitg00/agentmemory/issues/249) — thanks @OptionalCoin for the precise log analysis) + +- **`agentmemory demo` now actually seeds observations.** `seedDemoSession` posted to `/agentmemory/observe` without `project` and `cwd`, which the API requires as non-empty strings, so every observation 400'd and the demo silently reported "Seeded 0 observations across 3 sessions". Two-line fix: re-stage `project` + `cwd` into the observe payload alongside `sessionId`. The smart-search queries the demo prints will now return real hits. (#251, closes [#229](https://github.com/rohitg00/agentmemory/issues/229) — thanks @seishonagon for the precise root-cause analysis) + +- **LLM compression / summarization timeouts increased.** Larger sessions were hitting the 120s consolidation timeout under heavier workloads, leaving partial state. Bumped per-step ceilings to give slow providers (esp. local models) room to finish. (#213 — thanks @xuli500177) + +- **`pi` / OpenClaw / Hermes integration fixes.** Tested round-trip fixes across the three integration plugins to keep them aligned with the latest hooks contract. (#230 — thanks @deepmroot) + +### Changed + +- **`iii-engine` pinned to v0.11.2 across every install path.** v0.11.6 introduces a new architecture where workers run inside sandboxed microVMs registered via `iii worker add`. agentmemory still uses the older `iii-exec watch + node dist/index.mjs` worker model from `iii-config.yaml`, which doesn't pass the new engine's stricter trigger validation cleanly — the worker drops into an EPIPE reconnect loop and recall stops working. Pinning to v0.11.2 (the last engine that runs agentmemory's current architecture cleanly) until we refactor agentmemory to register itself via `iii worker add` and run inside the new sandbox model. + - `src/cli.ts` auto-installer downloads `github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-.tar.gz` directly. Per-arch coverage: darwin arm64/x64, linux x64/arm64/armv7, win32 x64/arm64. + - Docker fallback pulls `iiidev/iii:0.11.2` instead of `:latest`. + - `docker-compose.yml` uses `image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.11.2}` so the override env var actually takes effect for compose users. + - Install instructions and Windows guide updated to point at the v0.11.2 release page. + - **Escape hatch:** `AGENTMEMORY_III_VERSION=` overrides the pin for users who've moved to the sandbox model manually. + - Windows ZIP path detection in `runUpgrade` so the auto-installer doesn't try to pipe a `.zip` through `tar -xz`. (#260) + - **Follow-up tracked separately:** refactor agentmemory to register as a sandboxed worker via `iii worker add` so the pin can be lifted. + +- **README documents how to extend agentmemory with `iii worker add`.** New "Powered by iii" section maps each `iii worker add ` to a concrete agentmemory capability — multi-instance memory, scheduled consolidation, durable retries on embeddings, sandboxed code exec, SQL state, extra MCP host. Lists only workers actually published to [workers.iii.dev](https://workers.iii.dev) with direct links. (#242) + +- **README iii Console section corrected.** The console ships with `iii` as a subcommand; there's no separate installer. Replaced the bogus `curl install.iii.dev/console/main/install.sh` line, simplified the launch command to `iii console --port 3114`, and added the missing console pages to the capability table (Workers, Queues, Config, Flow). Replaced the dashboard screenshot with the Workers page so users see real agentmemory instances connected. (#243) + +### Notes + +If you're upgrading from <0.9.5 and have an existing vector index on disk, the new dim-guard will refuse to load if your active embedding provider declares a different dimension than what's persisted. This is the intended safe default — set `AGENTMEMORY_DROP_STALE_INDEX=true` to discard and rebuild from live observations, or re-embed against the new provider before starting. + +If you've been on `iii-engine` v0.11.6 and noticed search returning empty after save, install agentmemory 0.9.5 fresh (or run `npx @agentmemory/agentmemory upgrade`) to pull pinned engine v0.11.2. v0.11.6 brings a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet — that work is tracked as a follow-up; this release just keeps existing users unblocked. + +[0.9.6]: https://github.com/rohitg00/agentmemory/compare/v0.9.5...v0.9.6 +[0.9.5]: https://github.com/rohitg00/agentmemory/compare/v0.9.4...v0.9.5 + +## [0.9.4] — 2026-04-29 + +Bug-fix patch. Fixes a silent gap where the knowledge graph never auto-populated despite `GRAPH_EXTRACTION_ENABLED=true`, and adds a doctor check that detects when Claude Code fails to load plugin hooks. + +### Fixed + +- **`mem::graph-extract` now auto-fires at session end.** When `GRAPH_EXTRACTION_ENABLED=true`, the function was registered and the REST endpoint was live, but no internal caller invoked it — the graph KV stayed empty unless users manually `POST`ed to `/agentmemory/graph/extract`. `event::session::stopped` now triggers it (fire-and-forget, idempotent via existing node/edge merge keys), so enabling the flag actually populates the graph. README pipeline diagram updated to show graph extraction at the Stop/SessionEnd phase rather than implying it runs per PostToolUse. (#210) + +### Added + +- **`agentmemory doctor` detects Claude Code plugin-hook load state.** Scans `~/.claude/debug/latest` for the `Loaded hooks from standard location for plugin agentmemory` line. Surfaces the silent failure mode where the plugin is enabled but Claude Code never registered the hooks — users previously got no signal, hooks just silently did nothing. Hint points at reinstall + session restart and the CC version floor (>= 2.1.x). Skips silently when `~/.claude/debug` is absent. (refs #212) + +[0.9.4]: https://github.com/rohitg00/agentmemory/compare/v0.9.3...v0.9.4 + +## [0.9.3] — 2026-04-24 + +Developer-experience patch. Every disabled feature flag is now visible in the viewer, the CLI, and REST error responses, so devs no longer hit empty tabs wondering whether the install is broken or just opt-in. Adds a `doctor` command that diagnoses the whole stack in one shot and a first-run hero in the viewer that points at the magical-moment `demo` command. + +### Added + +- **`agentmemory doctor` command.** Runs 10 diagnostic checks in one shot: server reachability, health status, viewer port, LLM provider, embedding provider, four feature flag states, and whether the knowledge graph has data. Every failing check includes a concrete hint with the exact env var or command to fix it. Mirrors the shape of the new viewer feature-flag banners. +- **`/agentmemory/config/flags` REST endpoint.** Returns `{ version, provider, embeddingProvider, flags[] }` with per-flag `{ key, label, enabled, default, affects, needsLlm, description, enableHow, docsHref }`. Used by the viewer banner, CLI status/doctor, and anyone who wants to introspect config without parsing logs. +- **Viewer feature-flag banner system.** Compact collapsible summary row at the top of every tab (`⚠ 3 off · ⚙ 1 note · Feature flags — click to expand`). Expanded view shows per-flag card with description, exact enable command, docs link, and dismiss button. Dismissed state persists per-flag in localStorage so banners stay out of the way once acknowledged. Banners filter by the current tab's `affects` list. +- **Viewer first-run hero card.** When `sessions.length === 0`, dashboard renders an orange-accent card titled "First run → magical moment in 10 seconds" with `npx @agentmemory/agentmemory demo` as the next step. Removes the dead-empty dashboard that used to greet fresh installs. +- **Viewer footer with preset issue report.** `agentmemory viewer · v{version} · github · docs · report issue →`. The feedback link opens a GitHub issue pre-filled with version, provider name, embedding provider, flag state, and user-agent — so the first message on an issue already contains the diagnostic context that used to take three back-and-forths. +- **Richer empty states on Actions, Memories, Lessons, Crystals tabs.** Each now has a titled lead explaining what the tab is for, why it's empty, three concrete ways to populate it (MCP tool, curl, hook), and a docs link. The old one-liners ("No actions yet. Create actions via memory_action_create MCP tool") assumed too much context. +- **`status` command shows flag state.** New section in the output block lists provider (`✓ llm` / `✗ noop`), embedding provider (`✓ embeddings` / `bm25-only`), and each flag with a tick/cross. Parity with the viewer banner. +- **`AGENTMEMORY_URL` environment variable honored by CLI.** `status`, `doctor`, and related health checks now respect `AGENTMEMORY_URL=http://host:port` and extract the port from it. Previously documented but silently ignored; `--port N` was the only way to override. +- **Website install section promotes `demo` to step 2.** `npx @agentmemory/agentmemory demo` now appears between "start server" and "open viewer" on agent-memory.dev. The magical-moment command is on the critical path of the three-step install, not tucked into the README. +- **Website version auto-derived from repo package.json.** `gen-meta.mjs` picks up `src/version.ts` on `prebuild` and writes `website/lib/generated-meta.json`. Removes the stale-version drift that showed `v0.9.1` on the landing page after `v0.9.2` shipped. + +### Changed + +- **REST "feature not enabled" errors now return structured bodies.** Graph extraction (3 endpoints) and consolidation pipeline (1 endpoint) used to return `{ error: "Knowledge graph not enabled" }`. Now return `{ error, flag, enableHow, docsHref }` matching the viewer banner contract. Curl users get the same fix guidance as UI users. +- **Website install title: `THREE STEPS` → `THREE COMMANDS`.** Matches the new three-command install (`npx agentmemory`, `agentmemory demo`, `open viewer`). + +### Fixed + +- **Viewer banner scroll blocker.** Initial banner implementation rendered four full-height banner cards stacked above the dashboard, pushing all stats off-screen. Replaced with compact collapsible summary that takes ~40px of vertical space by default and only expands on click. + +[0.9.3]: https://github.com/rohitg00/agentmemory/compare/v0.9.2...v0.9.3 + +## [0.9.2] — 2026-04-22 + +Safety + import-pipeline patch. Kills the infinite Stop-hook recursion loop that burned Claude Pro tokens on unkeyed installs, repairs every empty viewer tab after `import-jsonl`, derives lessons and crystals automatically from imported sessions, and opens up OpenAI-compatible embedding endpoints. + +### Security + +- **Stop-hook recursion loop** ([#187](https://github.com/rohitg00/agentmemory/pull/187), follow-up to [#149](https://github.com/rohitg00/agentmemory/issues/149)). A user with no provider key and `AGENTMEMORY_AUTO_COMPRESS=false` could still trigger unbounded recursion: Stop hook → `/summarize` → `provider.summarize()` → agent-sdk provider spawned a Claude Agent SDK child session that inherited the same plugin hooks, whose own Stop fired, spawning another child, etc. ~579 ghost `entrypoint: sdk-ts` sessions could accumulate in minutes, draining the Claude Pro subscription. Fixed at five layers in defense-in-depth: + 1. `detectProvider()` treats empty-string keys (`ANTHROPIC_API_KEY=`) as unset and returns the noop provider by default. The agent-sdk fallback now requires explicit `AGENTMEMORY_ALLOW_AGENT_SDK=true` opt-in with a second loud warning. + 2. New `NoopProvider` returns empty strings for compress/summarize; callers detect `.name === "noop"` and short-circuit. + 3. `agent-sdk` provider sets `AGENTMEMORY_SDK_CHILD=1` before spawning `query()` and restores the previous value in `finally` so later calls in the same parent process are not mis-classified. + 4. All 12 hook scripts inline a shared `isSdkChildContext(payload)` guard that checks both the env marker and `payload.entrypoint === "sdk-ts"`, and bail early. + 5. `/summarize` short-circuits with `{ success: false, error: "no_provider" }` when `provider.name === "noop"` instead of calling through. Empty provider responses are now logged and recorded as failures on the metrics store. + +### Added + +- **`OPENAI_BASE_URL` / `OPENAI_EMBEDDING_MODEL`** ([#186](https://github.com/rohitg00/agentmemory/pull/186), thanks @Edison-A-N). The `OpenAIEmbeddingProvider` now accepts a base URL override and a configurable model name, mirroring the `MINIMAX_BASE_URL` pattern. Unlocks Azure OpenAI, vLLM, LM Studio, and other OpenAI-compatible proxies for embeddings with zero breakage — defaults are preserved. +- **`OPENAI_EMBEDDING_DIMENSIONS`** ([#189](https://github.com/rohitg00/agentmemory/pull/189)). Follow-up: `dimensions` is now derived from the model via a `MODEL_DIMENSIONS` lookup (3-small=1536, 3-large=3072, ada-002=1536) and falls back to 1536 for unknown models. Custom or self-hosted OpenAI-compatible models should set this env var explicitly; non-positive values are rejected at construction. +- **Auto-derived lessons and crystals on `import-jsonl`** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Each imported session now produces one crystal (narrative, tool outcomes, files, lessons) and up to 20 heuristic lessons from instructional patterns (`always`/`never`/`don't`/`prefer`/`avoid`/`caveat`/`note`/`warning`). Lessons are keyed by `fingerprintId("lesson", content.toLowerCase())` so re-importing the same file bumps `reinforcements` on existing lessons instead of duplicating rows. Crystals are keyed by `fingerprintId("crystal", sessionId)` and preserve `createdAt` on upsert. +- **Session preview on the sessions list** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). `Session` gained `firstPrompt` / `summary` fields; both `import-jsonl` and the live `mem::observe` path populate `firstPrompt` from the first real user prompt they see, and the viewer renders it as a 140-char preview row under each session. +- **Richer session detail + crystals viz + lessons tab explainers** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Clicking a session now fetches its observations and renders a 4-stat grid (observations / tools / files / duration), top-10 tool bar chart, activity breakdown, and file list. Crystals cards show resolved lesson content instead of raw IDs. Lessons tab has a header explainer card for the rule + confidence + decay model. + +### Changed + +- **`detectProvider()` default is now `noop`** (see Security). Users who had no API key and relied on the implicit Claude-subscription fallback must set `AGENTMEMORY_ALLOW_AGENT_SDK=true` to restore old behavior — and should read the warning about Stop-hook recursion first. +- **`/agentmemory/audit` response shape** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Now returns `{ entries, success }` instead of a bare array to match the viewer's expected shape. The viewer was rendering empty despite populated data. +- **`/agentmemory/replay/sessions` path** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Calls `kv.list` directly instead of `sdk.trigger → mem::replay::sessions`. Sub-50ms on 600+ sessions instead of timing out at 10s+. +- **Viewer WebSocket connect timeout** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). 5-second timeout around `new WebSocket(...)`. If the socket is still CONNECTING after that, it is force-closed so the `onclose` retry / polling-fallback chain kicks in. Previously the banner stuck on `CONNECTING…` forever when the iii-stream port accepted TCP but never completed the upgrade handshake. +- **`import-jsonl` now runs synthetic compression + BM25 indexing** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Imported observations go through the same `buildSyntheticCompression` + `getSearchIndex().add()` path as live `mem::observe`. Previously the raw shape was written directly to KV and the search index never saw it — consolidation reported "fewer than 5 summaries" and semantic/procedural/memory tabs stayed empty. +- **Viewer strength gauge** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). Memory tab showed `700%` on `strength: 7` because the scale was treated as 0–1. Now handles both 0–1 and 0–10 and clamps at 100%. + +### Fixed + +- **`npm ci` on fork PRs** ([#187](https://github.com/rohitg00/agentmemory/pull/187), [#188](https://github.com/rohitg00/agentmemory/pull/188)). CI failed because lockfiles are gitignored at the repo level. `.github/workflows/ci.yml` + `publish.yml` now run a two-step install: `npm install --package-lock-only` to produce a lockfile in the runner workspace, then `npm ci` to install deterministically from it. Gives a single resolved dependency graph across build + test + publish within one job run — important because publish uses `--provenance`. +- **`image-quota-cleanup` fail-closed on refCount read errors** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). When `getImageRefCount` threw, the code fell through to `deleteImage` with `refCount === 0`, risking deletion of still-referenced images on transient KV errors. Fail-closed: log + return from the `withKeyedLock` callback, never reach `deleteImage` without a confirmed zero refcount. +- **`raw.userPrompt` type guard** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). `mem::observe` now runtime-checks `typeof raw.userPrompt === "string"` before calling `.replace` / `.trim` / `.slice`. Non-string truthy values from malformed hook payloads no longer crash the handler. +- **Viewer Actions frontier field** ([#188](https://github.com/rohitg00/agentmemory/pull/188)). The tab was reading `results[1].actions` but `/frontier` returns `{ frontier: [...] }`. Fixed the read path; preserves actions/frontier unification. +- **Hardcoded `maxTokens: 4096` in the agent-sdk branch of `detectProvider`** ([#188](https://github.com/rohitg00/agentmemory/pull/188), [#190](https://github.com/rohitg00/agentmemory/pull/190)). Ignored the `maxTokens` variable computed from `env["MAX_TOKENS"]`. Every other branch already used the computed value; agent-sdk now matches. + +### Infrastructure + +- `StateScope` interface in `types.ts` documents the `KV.state` scope shape (`system:currentDiskSize: number`); `disk-size-manager` uses `StateScope[typeof DISK_SIZE_KEY]` generics instead of ad-hoc ``. +- `onnxruntime-node` + `onnxruntime-web` moved to `optionalDependencies` alongside `@xenova/transformers` to make their lazy/transitive nature explicit; still externalized in `tsdown.config.ts` because bundling breaks the native `.node` binding paths. +- `FALLBACK_PROVIDERS` parsing now honors the same `AGENTMEMORY_ALLOW_AGENT_SDK` gate as `detectProvider`, filtering out `agent-sdk` from the fallback chain unless explicitly opted in. +- README provider table + env block updated: no-op is the new default, Claude-subscription fallback moved to a separate opt-in row, OpenAI env vars documented. +- Hero stat badge refreshed from 654 → 827 tests (both dark + light variants). +- `VERSION` / `ExportData.version` union / `supportedVersions` Set / `test/export-import.test.ts` / `@agentmemory/mcp` shim version all bumped in lockstep. +- Test count: 827 (up from 812 in v0.9.1). + +[0.9.2]: https://github.com/rohitg00/agentmemory/compare/v0.9.1...v0.9.2 + +## [0.9.1] — 2026-04-21 + +Trust-the-CLI patch. Three bugs that surfaced in real testing of v0.9.0: the dashboard viewer showed zeros for half its cards, the `import-jsonl` command crashed on anything but a perfect response, and `upgrade` hard-aborted on a cargo registry that never had the crate. + +### Fixed + +- **Viewer dashboard list endpoints** ([#172](https://github.com/rohitg00/agentmemory/pull/172)). `GET /agentmemory/semantic` and `GET /agentmemory/procedural` were never registered, and `GET /agentmemory/relations` returned 405 because only the POST trigger existed. The dashboard's `Promise.all` fan-out silently received null for those cards even when semantic, procedural, or relation data was present. Added `api::semantic-list`, `api::procedural-list`, and `api::relations-list` handlers next to `api::memories` in `src/triggers/api.ts`, each returning the shape the viewer already parses. +- **CLI version drift** ([#173](https://github.com/rohitg00/agentmemory/pull/173)). The viewer brand badge hardcoded `v0.7.0` and the README "New in" banner still said `v0.8.2`. Replaced the viewer string with a `__AGENTMEMORY_VERSION__` placeholder substituted at render time by `document.ts` (same mechanism as the CSP nonce). Collapsed `src/version.ts` from a literal union of every historical release back to a single `VERSION` constant — the import-compat contract is the `supportedVersions` Set in `export-import.ts`, not the type. +- **`import-jsonl` crashed with `Unexpected end of JSON input`** ([#174](https://github.com/rohitg00/agentmemory/pull/174)). The livez probe used fetch throws as the only failure signal — any stray service on port 3111 passed silently, then `res.json()` blew up when the real POST returned an empty body or HTML error. Probe now captures `probe.status` + body snippet on non-OK responses and the exception message on network failure, so the error distinguishes `unreachable (...)` from `reachable but unhealthy (HTTP 503: ...)`. The POST reads body as text, parses only if non-empty, requires `json.success === true`, and maps 401 → "set AGENTMEMORY_SECRET" and 404 → "upgrade server to v0.8.13+". +- **`upgrade` aborted on `cargo install iii-engine`** ([#174](https://github.com/rohitg00/agentmemory/pull/174)). The crate was never published — the old flow called `requireSuccess`, which exited before the Docker pull ran. Swapped to the official installer used throughout the README and demo command: `curl -fsSL https://install.iii.dev/iii/main/install.sh | sh`. Installer failure is optional; a warn points at `iiidev/iii:latest` and the releases page at `iii-hq/iii`. + +### Infrastructure + +- Three integration tests cover the new list endpoints. +- `VERSION` / `ExportData.version` union / `supportedVersions` / `test/export-import.test.ts` all bumped in lockstep. + +[0.9.1]: https://github.com/rohitg00/agentmemory/compare/v0.9.0...v0.9.1 + +## [0.9.0] — 2026-04-18 + +Visibility + correctness release. Landing site, filesystem connector, MCP standalone now actually talks to the running server, health logic stops crying wolf, audit trail closes its last gap, and every memory path has a clear policy. + +### Added +- **Website** ([#164](https://github.com/rohitg00/agentmemory/pull/164)). Next.js 16 App Router landing page at `website/` — Lamborghini-inspired dark canvas, live GitHub stars pill, agents marquee with real brand logos, command-center tab showcase (viewer · iii console · state · traces), 12-tile feature grid, 10-agent MCP install selector, universal MCP JSON + one-click Cursor/VS Code deeplinks. Deploys to Vercel with Root Directory = `website/`. +- **Filesystem connector** — new `@agentmemory/fs-watcher` package under `integrations/filesystem-watcher/` ([#163](https://github.com/rohitg00/agentmemory/pull/163), closes [#62](https://github.com/rohitg00/agentmemory/issues/62)). Node `fs.watch` based, no native deps. Emits valid `HookPayload` observations for every file change and delete, with debounce, default ignore list, text-file preview, bearer auth, and env-driven config. +- **Security advisory drafts** for v0.8.2 CVEs ([#118](https://github.com/rohitg00/agentmemory/pull/118)). Six markdown drafts under `.github/security-advisories/` covering viewer XSS, curl-sh RCE, default 0.0.0.0 bind, unauthenticated mesh sync, Obsidian export traversal, and incomplete secret redaction. Also documents the symlink-traversal limitation of the Obsidian export fix. +- **iii console documentation** in the README ([#157](https://github.com/rohitg00/agentmemory/pull/157)). How to launch the iii console alongside the viewer, what each page gives you for agentmemory, and the `iii-observability` config that ships turned on. + +### Changed +- **Audit policy codified** ([#162](https://github.com/rohitg00/agentmemory/pull/162), closes [#125](https://github.com/rohitg00/agentmemory/issues/125)). `src/functions/audit.ts` gains a top-of-file policy block: every structural deletion emits a `recordAudit` row, scoped deletions (`governance-delete`, `forget`) write one row per call, bulk sweeps (`retention-evict`, `evict`, `auto-forget`) write one batched row per invocation. `mem::forget` no longer deletes silently — it writes a single audit row with target ids, session id, and per-type counts. +- **Standalone MCP talks to the running server** ([#161](https://github.com/rohitg00/agentmemory/pull/161), closes [#159](https://github.com/rohitg00/agentmemory/issues/159)). `@agentmemory/mcp` now probes `GET /agentmemory/livez` at `AGENTMEMORY_URL` (defaults to `http://localhost:3111`) on first tool call. If the server is up, every tool (sessions, smart-search, recall, save, governance-delete, export, audit) routes through REST and sees exactly what hooks and the viewer see. If the probe fails, falls back to the local `InMemoryKV` so pure-standalone setups keep working. Bearer `AGENTMEMORY_SECRET` attached automatically. Handle cache invalidates on proxy failure with a 30s TTL so a later server start is picked up. Response shapes are now consistent across proxy and local branches. +- **Retention eviction targets the right store** ([#132](https://github.com/rohitg00/agentmemory/pull/132)). `mem::retention-evict` now routes deletes to `mem:memories` or `mem:semantic` based on the candidate's `source` field, probing both namespaces when the field is missing (legacy rows). Emits a single batched audit row per sweep with `evictedIds`, `evictedEpisodic`, `evictedSemantic`, and the threshold. Retention scores gain a `source` field persisted to the store. + +### Fixed +- **Health stops flagging `memory_critical` on tiny Node processes** ([#160](https://github.com/rohitg00/agentmemory/pull/160), closes [#158](https://github.com/rohitg00/agentmemory/issues/158)). Memory severity no longer escalates from heap ratio alone. Both warn and critical bands now require RSS above `memoryRssFloorBytes` (default 512 MB). When heap is tight but RSS is below the floor, a non-alerting `memory_heap_tight_NN%_rssMMmb` note is attached to the snapshot — visibility without the false positive. +- **iii console screenshots vendored** in the README so the docs don't depend on CDN signed URLs. + +### Infrastructure +- `VERSION` union extended to `0.9.0`; `ExportData.version`, `supportedVersions`, and `test/export-import.test.ts` bumped in lockstep. +- `@agentmemory/mcp` dependency pinned at `~0.9.0` to match. +- Tests: 777 passing (+ 14 skipped), up from 769. + +[0.9.0]: https://github.com/rohitg00/agentmemory/compare/v0.8.12...v0.9.0 + +## [0.8.13] — 2026-04-17 + +### Added + +- Session replay: new "Replay" tab in the viewer that plays any stored session as a scrubbable timeline with prompt, response, tool-call, and tool-result events. Keyboard bindings: space to play/pause, arrow keys to step, speed selector (0.5×–4×). +- JSONL transcript import via `agentmemory import-jsonl [path]` CLI subcommand and `POST /agentmemory/replay/import-jsonl`. Default path `~/.claude/projects`, or pass an explicit file/directory. Imports are recorded in the audit log. +- New iii functions `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl`, each routed through the same HMAC-authed API trigger as other endpoints. + +### Security + +- JSONL import rejects symlinks, paths containing sensitive terms (`secret`, `credential`, `.env`, etc.), and skips malformed lines without aborting the batch. + +## [0.8.12] — 2026-04-16 + +### Added + +- Added token-efficient `memory_recall` output modes: + - `format: "full"` (default) + - `format: "compact"` (returns compact observation rows) + - `format: "narrative"` (title + narrative text for low-token recall) +- Added `token_budget` support to `memory_recall` / `mem::search` to trim results to a target budget and return `tokens_used`, `tokens_budget`, and `truncated` metadata. +- Added new MCP + REST tool `memory_compress_file` (`mem::compress-file` / `/agentmemory/compress-file`) to compress markdown files while preserving headings, URLs, and fenced code blocks. + +### Changed + +- Updated MCP tool count to 44 and REST endpoint count to 104. +- Updated docs and plugin metadata for new tool/endpoint counts. +- Added test coverage for search formats, token budget behavior, and file compression validation. + +## [0.8.11] — 2026-04-15 + +**Fix**: `node dist/index.mjs` crashed on first import after the iii-sdk v0.11 migration (#116) merged. iii-sdk v0.11 dropped `getContext()`, but 32 `src/functions/*.ts` files still imported and called it. Added `src/logger.ts` (thin stderr shim with the same `.info/.warn/.error` signature) and mechanically replaced every `ctx.logger.*` call. Updated all 45 test mock blocks. Fixed `search.ts` `registerFunction` call to use the v0.11 string-ID API. + +### Fixed + +- **iii-sdk v0.11 getContext crash** ([#116](https://github.com/rohitg00/agentmemory/issues/116)) — `SyntaxError: The requested module 'iii-sdk' does not provide an export named 'getContext'` on startup. Removed all `getContext` imports from 32 function files, added `src/logger.ts` shim, updated 45 test mock blocks. + +### Changed + +- Upgraded `iii-sdk` dependency from `^0.11.0-next.8` to stable `^0.11.0`. +- Aligned stream send payloads with v0.11 wire format by using `type` for `stream::send` events in observe/compress/session-activity paths. +- Updated migration guidance/examples and diagnostics plugin registration snippets to v0.11 function registration and trigger request shapes. +## [0.8.10] — 2026-04-15 + +**Behavior change**: the PreToolUse and SessionStart hooks no longer run enrichment by default. SessionStart saves ~1-2K input tokens per session you start (the only path that was actually reaching the model, per the [Claude Code hook docs](https://code.claude.com/docs/en/hooks.md)). PreToolUse stops spawning a Node process and POSTing to `/agentmemory/enrich` on every file-touching tool call — a pure resource cleanup, not a token fix. If you were relying on either path, set `AGENTMEMORY_INJECT_CONTEXT=true` in `~/.agentmemory/.env` and restart. Observations are still captured via PostToolUse regardless. + +### Fixed + +- **Gate SessionStart context injection** ([#143](https://github.com/rohitg00/agentmemory/issues/143), thanks [@adrianricardo](https://github.com/adrianricardo)) — `src/hooks/session-start.ts` previously wrote ~1-2K chars of project context to stdout at every session start. Per the [Claude Code hook docs](https://code.claude.com/docs/en/hooks.md), `SessionStart` stdout is explicitly injected into the model's context ("where stdout is added as context that Claude can see and act on"), so this was adding real tokens to the first turn of every new session. Now gated behind `AGENTMEMORY_INJECT_CONTEXT`, default off. The session still gets registered for observation tracking — only the stdout echo is skipped. +- **Skip the PreToolUse enrichment round-trip when disabled** ([#143](https://github.com/rohitg00/agentmemory/issues/143)) — `src/hooks/pre-tool-use.ts` was POSTing `/agentmemory/enrich` on every `Edit`/`Write`/`Read`/`Glob`/`Grep` tool call and piping up to 4000 chars to stdout. The Claude Code docs make clear that PreToolUse stdout goes to the debug log, not the model context, so this was **not** burning user tokens — but it was spawning a Node process + full HTTP round-trip ~20x per user message with no effect on the conversation. Gating it makes the disabled hot path a ~15ms no-op Node startup instead of a ~100-300ms REST round-trip. **This is a resource cleanup, not a token fix**; leaving the gate in place protects forward in case Claude Code ever changes PreToolUse to inject stdout like SessionStart does. +- **`mem::retention-evict` no longer leaks semantic memories** ([#124](https://github.com/rohitg00/agentmemory/issues/124)) — the eviction loop was unconditionally calling `kv.delete(KV.memories, id)` for every below-threshold candidate, but retention scores are computed for both episodic (`KV.memories`) and semantic (`KV.semantic`) memories. When a candidate came from `KV.semantic`, the delete silently became a no-op (key wasn't in `mem:memories` to begin with) and the semantic row stayed alive forever with a sub-threshold score. Semantic memories could not be evicted by this path at all. Fix: add a `source: "episodic" | "semantic"` discriminator to `RetentionScore`, tag it at score creation, and branch the delete on `candidate.source`. For pre-0.8.10 rows with no `source` field (including semantic retention rows written by the old scorer), the loop probes both namespaces to find where the `memoryId` actually lives, so upgraded stores get their stranded semantic memories evicted without needing to re-score first. The response shape now also includes `evictedEpisodic` and `evictedSemantic` counts for observability. +- **`mem::retention-evict` now emits an audit record per sweep** ([#124](https://github.com/rohitg00/agentmemory/issues/124)) — retention eviction performs structural deletes (memories, retention scores, access logs) but was not calling `recordAudit()`, which made evictions invisible to audit consumers. Now batched one audit row per non-zero sweep, with `operation: "delete"`, `functionId: "mem::retention-evict"`, `targetIds` containing every evicted id, and `details.evicted` / `evictedEpisodic` / `evictedSemantic` / `threshold` for context. Zero-eviction sweeps intentionally do not write an audit row. + +### Honest note on #143 + +My initial diagnosis on the #143 thread pattern-matched too quickly to #138 and overclaimed that PreToolUse stdout was the smoking gun behind "Claude Pro burned in 4 messages". It wasn't — per the docs, PreToolUse stdout is debug-log only. The actual background cause is that [Claude Pro's Claude Code quotas are documented as tight](https://www.theregister.com/2026/03/31/anthropic_claude_code_limits/) and Anthropic has publicly confirmed "people are hitting usage limits in Claude Code way faster than expected." agentmemory contributes ~1-2K tokens per session via SessionStart, and that contribution is worth eliminating, but this release does not and cannot make Claude Pro's base quotas roomier. Users on heavy tool-call workloads should consider Max 5x or Team tiers regardless of whether agentmemory is installed. + +0.8.8's #138 fix (opt-in `mem::compress` via `AGENTMEMORY_AUTO_COMPRESS`) remains the correct fix for users with `ANTHROPIC_API_KEY` set — that path was a real per-observation Claude API burn and is unrelated to the Claude Code hook pipeline. + +### Added + +- **`AGENTMEMORY_INJECT_CONTEXT` env var** — default `false`. When `true`, restores the old SessionStart stdout write and the old PreToolUse `/enrich` round-trip. Startup banner prints a loud warning when it's on, mirroring the `AGENTMEMORY_AUTO_COMPRESS` warning from 0.8.8. +- **`isContextInjectionEnabled()`** helper in `src/config.ts` — single source of truth for the flag. The hooks read the env var directly (they're spawned as standalone `.mjs` files by Claude Code and don't bootstrap through `src/index.ts`), so the helper is there for the startup banner and future code paths. +- **5 subprocess regression tests** in `test/context-injection.test.ts` — spawns the compiled `pre-tool-use.mjs` and `session-start.mjs` hooks with real stdin/stdout pipes and asserts that stdout is empty when the env var is unset, when it's explicitly `false`, and that the disabled PreToolUse path exits under 1 second. Also asserts that the opt-in path with an unreachable backend still exits cleanly. Full suite: **724 passing** (was 719 + 5 new). + +### Infrastructure + +- **Startup banner** (`src/index.ts`) now prints `Context injection: OFF (default, #143)` on normal startup and a prominent WARNING when opt-in is enabled, so the mode is never silent. +- **Migration note**: if you were relying on the old SessionStart project-context injection or the old PreToolUse enrichment round-trip, add to `~/.agentmemory/.env`: + ```env + AGENTMEMORY_INJECT_CONTEXT=true + ``` + and restart Claude Code. You'll see the startup warning in the engine logs confirming it's active. + +[0.8.10]: https://github.com/rohitg00/agentmemory/compare/v0.8.9...v0.8.10 +[0.8.12]: https://github.com/rohitg00/agentmemory/compare/v0.8.11...v0.8.12 + +## [0.8.9] — 2026-04-14 + +Two UX fixes for the Claude Code plugin install path, both reported in [#139](https://github.com/rohitg00/agentmemory/issues/139) by [@stefanfaur](https://github.com/stefanfaur). + +### Fixed + +- **Claude Code plugin now auto-wires the `@agentmemory/mcp` stdio server** ([#139](https://github.com/rohitg00/agentmemory/issues/139)) — the plugin previously only shipped hooks and skills, and the README told Claude Code users to wire up the MCP server manually. A new `plugin/.mcp.json` declares the MCP server so `/plugin install agentmemory@agentmemory` auto-starts it when the plugin is enabled. No extra config step. +- **Skills no longer fail under Claude Code's sandbox with "Contains expansion"** ([#139](https://github.com/rohitg00/agentmemory/issues/139)) — the `recall` and `session-history` skills used pre-execution bash with `$(...)` / `${VAR:-default}` shell expansion, which Claude Code's sandbox rejects by pattern match. All four plugin skills (`recall`, `remember`, `forget`, `session-history`) are now rewritten as pure prompts that tell Claude to use the MCP tools directly. No bash, no sandbox issues, no shell escaping — and the skills run faster because they no longer fork a curl subprocess on every invocation. + +### Added + +- **Standalone MCP shim now implements `memory_smart_search` and `memory_governance_delete`** — the `@agentmemory/mcp` stdio server only exposed 5 tools (`memory_save`, `memory_recall`, `memory_sessions`, `memory_export`, `memory_audit`), so the rewritten plugin skills would have failed at runtime referencing tools the standalone didn't know about. Now ships 7 tools. `memory_smart_search` falls back to the same substring filter as `memory_recall` since the standalone shim doesn't have BM25/vector/graph without the full engine. `memory_governance_delete` takes `memoryIds` as an array or comma-separated string and returns `{deleted, requested, reason}`. +- **`memory_save` accepts `concepts`/`files` as arrays or comma-separated strings** — the old standalone only accepted CSV strings, which would silently drop array inputs. New `normalizeList()` helper handles both. +- **`memory_sessions` honours a `limit` arg** (default 20) — previously returned every session. +- **8 regression tests** in `test/mcp-standalone.test.ts` covering array/CSV inputs for `memory_save`, `memory_smart_search` substring fallback, `memory_sessions` limit, `memory_governance_delete` happy path + unknown-id skip + validation. Full suite: 715 passing. + +### Changed + +- **README Claude Code install snippet** — now explicitly notes that `/plugin install agentmemory` registers hooks + skills AND auto-wires the MCP server via `.mcp.json`, with no extra step. + +[0.8.9]: https://github.com/rohitg00/agentmemory/compare/v0.8.8...v0.8.9 + +## [0.8.8] — 2026-04-14 + +**Behavior change**: per-observation LLM compression is now opt-in. If you were relying on LLM-generated summaries (the old default), set `AGENTMEMORY_AUTO_COMPRESS=true` in `~/.agentmemory/.env` and restart. + +### Fixed + +- **Stop silently burning Claude API tokens on every tool invocation** ([#138](https://github.com/rohitg00/agentmemory/issues/138), thanks [@olcor1](https://github.com/olcor1)) — the old `mem::observe` path fired `mem::compress` unconditionally on every PostToolUse hook, which called Claude via the user's `ANTHROPIC_API_KEY` to turn each raw observation into a structured summary. An active coding session (50-200 tool calls/hour) could run through hundreds of thousands of tokens in minutes, which is the exact opposite of what a memory tool should do. The new default path skips the LLM call and uses a zero-token **synthetic compression** step that derives `type`, `title`, `narrative`, and `files` from the raw tool name, tool input, and tool output directly. Recall and BM25 search still work — you just lose the LLM-generated summaries unless you opt in. + +### Added + +- **`AGENTMEMORY_AUTO_COMPRESS` env var** — default `false`. When `true`, restores the old per-observation LLM compression path. The engine startup banner now prints a loud warning when it's on, reminding you that it spends tokens proportional to your session tool-use frequency. +- **`src/functions/compress-synthetic.ts`** — the new zero-LLM compression helper. `buildSyntheticCompression(raw)` maps tool names to `ObservationType` (via camelCase-aware substring matching for `Read`/`Write`/`Edit`/`Bash`/`Grep`/`WebFetch`/`Task`/etc.), pulls file paths out of `tool_input.file_path` / `pattern` / etc., and truncates narratives to 400 chars so one huge tool output can't blow up the BM25 index. +- **Regression test** `test/auto-compress.test.ts` — 8 cases covering the default path (no `mem::compress` trigger, synthetic observation stored in KV), explicit opt-in, tool-name-to-type mapping, file-path extraction, narrative truncation, and the `post_tool_failure` → `error` path. Full suite: 707 passing. + +### Infrastructure + +- **Startup banner** (`src/index.ts:171`) now prints either `Auto-compress: OFF (default, #138)` or a prominent warning when opt-in is enabled, so the mode is never silent. +- **Migration note**: if you were running 0.8.7 or earlier with `ANTHROPIC_API_KEY` set, your token usage will drop sharply on upgrade. Search quality may also drop slightly because narratives are now derived from raw tool I/O instead of Claude-generated summaries. If you want the old behavior: + ```env + # ~/.agentmemory/.env + AGENTMEMORY_AUTO_COMPRESS=true + ``` + and restart. Existing compressed observations in `~/.agentmemory/` are untouched. + +[0.8.8]: https://github.com/rohitg00/agentmemory/compare/v0.8.7...v0.8.8 + +## [0.8.7] — 2026-04-14 + +One-line fix for a brown-paper-bag bug reported in [#136](https://github.com/rohitg00/agentmemory/issues/136). + +### Fixed + +- **`npx @agentmemory/agentmemory` no longer crashes with "`/app/config.yaml` is a directory"** ([#136](https://github.com/rohitg00/agentmemory/issues/136), thanks [@stefano-medapps](https://github.com/stefano-medapps)) — the published tarball shipped `docker-compose.yml` but **not** `iii-config.docker.yaml`, even though the compose file mounts `./iii-config.docker.yaml:/app/config.yaml:ro`. Docker resolves missing host-path bind sources by silently creating them as empty directories, so the iii-engine container mounted an empty dir at `/app/config.yaml` and crashed with `Error: Failed to read config file '/app/config.yaml': Is a directory (os error 21)`. The `files` array in `package.json` now includes `iii-config.docker.yaml` alongside the regular `iii-config.yaml`. + +### Infrastructure + +- New regression test in `test/consistency.test.ts` parses every `./:` bind mount in `docker-compose.yml` and asserts the source file is shipped via the `files` array. Catches the class of bug where a new bind mount is added to compose without a corresponding entry in `files`. + +[0.8.7]: https://github.com/rohitg00/agentmemory/compare/v0.8.6...v0.8.7 + +## [0.8.6] — 2026-04-13 + +Finishes the `npx ` story from #120 by moving the standalone package under the `@agentmemory` scope. + +### Changed + +- **Standalone MCP shim is now `@agentmemory/mcp`** — the 0.8.5 publish attempted to push `agentmemory-mcp` as an unscoped package, but npm's name-similarity policy rejects it because of an unrelated third-party package called `agent-memory-mcp`. The shim now lives under the scope we already own, so `npx -y @agentmemory/mcp` works on the live registry. All README/integration/CLI-help snippets, the OpenClaw and Hermes guides, and the Claude-Desktop/Cursor/Codex/OpenCode MCP config examples have been updated to use the scoped name. The unscoped `agentmemory-mcp` command line (in the main package's `bin` field) was never published and has been removed from the docs. +- **Package directory renamed** `packages/agentmemory-mcp/` → `packages/mcp/`. The `.github/workflows/publish.yml` publish step points at the new path and `npm view @agentmemory/mcp` for the propagation check. +- **Log prefix** in `src/mcp/standalone.ts` and `src/mcp/in-memory-kv.ts` changed from `[agentmemory-mcp]` to `[@agentmemory/mcp]` so stderr output matches the package users install. + +### Fixed + +- **Shim version bump was missed in 0.8.5** — `packages/agentmemory-mcp/package.json` (now `packages/mcp/package.json`) was still pinned at `0.8.4` because the release bump script only touched the 8 files in the main package. The shim now tracks the main package and depends on `@agentmemory/agentmemory: ~0.8.6`. + +[0.8.6]: https://github.com/rohitg00/agentmemory/compare/v0.8.5...v0.8.6 + +## [0.8.5] — 2026-04-13 + +Compatibility fix for stricter JSON-RPC clients, plus a spec cleanup CodeRabbit caught during review. + +### Fixed + +- **MCP server works with Codex CLI and any strict JSON-RPC 2.0 client** ([#129](https://github.com/rohitg00/agentmemory/issues/129)) — the stdio transport was responding to JSON-RPC **notifications** (messages without an `id` field, e.g. `notifications/initialized`), which violates JSON-RPC 2.0 §4.1 and caused stricter clients like Codex CLI v0.120.0 to close the transport with "Transport closed". Notifications are now detected by the missing/null `id` field, the handler still runs for side effects, but no response is written. Handler errors on notifications are logged to stderr instead of sent back to the client. Claude Code and other clients that tolerated the spurious responses continue to work unchanged. +- **Request `id` type validation per JSON-RPC 2.0 §4** — the transport previously only checked `id != null`, so a malformed request with `id: {}` or `id: [1,2]` could get echoed back with that non-primitive id, and valid-shape requests with bad id types fell through to the handler and produced a response carrying a bogus non-JSON-RPC id. `isValidId()` now enforces `string | number | null | undefined`, and bad-id requests get `-32600 Invalid Request` with `id: null` before the handler runs. Caught by CodeRabbit on PR [#131](https://github.com/rohitg00/agentmemory/pull/131). + +### Infrastructure + +- 14 tests in `test/mcp-transport.test.ts` covering the request path, notification path (#129), malformed input, and id-type validation (object/array/boolean). Full suite: 698 passing. + +[0.8.5]: https://github.com/rohitg00/agentmemory/compare/v0.8.4...v0.8.5 + +## [0.8.4] — 2026-04-13 + +Two community contributions land on top of 0.8.3 and close out the #120 npm story for real. + +### Fixed + +- **Memories saved via the standalone MCP server now survive SIGKILL** ([#122](https://github.com/rohitg00/agentmemory/pull/122), thanks [@JasonLandbridge](https://github.com/JasonLandbridge)) — `memory_save` previously only flushed to `~/.agentmemory/standalone.json` on `SIGINT`/`SIGTERM`. If the MCP server process was killed forcefully (e.g. when an agent session ended), every memory saved during that session was lost. The save handler now persists to disk immediately after every `memory_save` call, so data survives unexpected termination. Also switched to the shared `generateId("mem")` helper and a single `isoNow` shared by `createdAt`/`updatedAt` so they can't drift. +- **OpenCode MCP config format corrected** ([#121](https://github.com/rohitg00/agentmemory/pull/121), thanks [@JasonLandbridge](https://github.com/JasonLandbridge)) — the README previously told OpenCode users to edit `.opencode/config.json` with an `mcpServers` object, but OpenCode actually uses `opencode.json` with an `mcp` object, `type: "local"`, and a `command` array. The agents table row and a new dedicated OpenCode block in the Standalone MCP section now document the correct format. + +## [0.8.3] — 2026-04-13 + +Two bug fixes reported in the public issue tracker. + +### Fixed + +- **Retention score now reflects real agent-side reads** ([#119](https://github.com/rohitg00/agentmemory/issues/119)) — `mem::retention-score` previously hardcoded `accessCount = 0` and `accessTimestamps = []` for episodic memories, and only used a single-sample `lastAccessedAt` for semantic memories. Reads from `mem::search`, `mem::smart-search`, `mem::context`, `mem::timeline`, `mem::file-context`, and the matching MCP tools (`memory_recall`, `memory_smart_search`, `memory_timeline`, `memory_file_history`) were never recorded, so the time-frequency decay formula was a dead path. The reinforcement boost is now driven by a real per-memory access log persisted at `mem:access`, written by every read endpoint (fire-and-forget, so reads never block on tracker writes), with a bounded ring buffer of the last 20 access timestamps. Pre-0.8.3 semantic memories that only have the legacy `lastAccessedAt` field still score correctly via a backwards-compat fallback. +- **`npx agentmemory-mcp` 404** ([#120](https://github.com/rohitg00/agentmemory/issues/120)) — the README told users to run `npx agentmemory-mcp` for MCP client setup, but `agentmemory-mcp` was only a `bin` entry inside `@agentmemory/agentmemory`, not a real package, so `npx` returned 404 from the npm registry. Two fixes: + - Published a new sibling package `agentmemory-mcp` (in `packages/agentmemory-mcp/`) that is a thin shim over `@agentmemory/agentmemory/dist/standalone.mjs`. `npx agentmemory-mcp` now works as documented. + - Added a canonical `npx @agentmemory/agentmemory mcp` subcommand to the main CLI for users who already have `@agentmemory/agentmemory` installed and don't want a second package on disk. Both commands do the same thing. + - README install snippets now use `npx -y agentmemory-mcp` so first-time users skip the install confirmation prompt. + +### Added + +- **Concurrent access tracking is race-safe** — the access log RMW is wrapped in the existing `withKeyedLock` keyed mutex, so two parallel reads of the same memory don't lose increments. `recordAccessBatch` uses `Promise.allSettled` so a slow keyed-lock acquisition on one id doesn't block the rest of the batch. +- **`mem::export` / `mem::import` now round-trip the access log** — the new `mem:access` namespace is included in dumps and restored on import, so backup/restore cycles no longer silently zero out reinforcement signals. +- **`exports` field in `package.json`** — explicitly exposes `./dist/standalone.mjs` as a subpath so the shim package and external consumers have a stable contract. +- **CI publishes both packages on release** — `.github/workflows/publish.yml` now publishes `@agentmemory/agentmemory` first, then the `agentmemory-mcp` shim from `packages/agentmemory-mcp/` so `npx agentmemory-mcp` works on the live release. + +## [0.8.2] — 2026-04-12 + +This release ships 6 security fixes, growth features, and a visual redesign of the README. Users on v0.8.1 should upgrade as soon as possible — the security fixes address vulnerabilities in default deployments. + +### Security + +Six vulnerabilities fixed, originally introduced before v0.8.1: + +- **[CRITICAL] Stored XSS in the real-time viewer** — viewer HTML used inline `onclick=` handlers while the CSP allowed `script-src 'unsafe-inline'`. User-controlled tool outputs could execute JavaScript in the reader's browser. Fixed by removing all inline event handlers, adding delegated `data-action` handling, switching to a per-response nonce-based CSP, and adding `script-src-attr 'none'`. +- **[CRITICAL] `curl | sh` in CLI startup** — the CLI auto-installed iii-engine via `execSync("curl -fsSL https://install.iii.dev/iii/main/install.sh | sh")`. Removed entirely. The CLI now uses an existing local `iii` binary if available, or falls back to Docker Compose. Users install iii-engine manually via `cargo install iii-engine` or Docker. +- **[HIGH] Default `0.0.0.0` binding** — `iii-config.yaml` bound REST (3111) and streams (3112) to all interfaces, exposing the memory store to anyone on the local network. Now binds to `127.0.0.1` by default. A separate `iii-config.docker.yaml` handles the Docker case with host port mapping restricted to `127.0.0.1:port`. +- **[HIGH] Unauthenticated mesh sync** — mesh push/pull endpoints accepted requests without an `Authorization` header. Mesh endpoints now require `AGENTMEMORY_SECRET`, and outgoing mesh sync requests send `Authorization: Bearer `. +- **[MEDIUM] Path traversal in Obsidian export** — the `vaultDir` parameter was passed directly to `mkdir`/`writeFile`, allowing writes to any filesystem path (e.g., `/etc/cron.d`). Exports are now confined to `AGENTMEMORY_EXPORT_ROOT` (default `~/.agentmemory`) via `path.resolve` + `startsWith` containment check. +- **[MEDIUM] Incomplete secret redaction** — the privacy filter missed `Bearer ...` tokens, OpenAI project keys (`sk-proj-*`), and GitHub fine-grained service tokens (`ghs_`, `ghu_`). Added regex coverage for all three formats. + +See GitHub Security Advisories for CVSS scores and affected version ranges. + +### Added + +- **`agentmemory demo` CLI command** — seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs smart-search queries against them. Shows semantic search finding "N+1 query fix" when you search "database performance optimization" — the kind of result keyword matching can't produce. Zero config, 30 seconds, no integration needed. +- **`benchmark/COMPARISON.md`** — head-to-head comparison vs mem0 (53K⭐), Letta/MemGPT (22K⭐), Khoj (34K⭐), claude-mem (46K⭐), and Hippo. 18-dimension feature matrix, honest LongMemEval vs LoCoMo caveats, token efficiency table. +- **`integrations/openclaw/`** — OpenClaw gateway plugin with 4 lifecycle hooks (`onSessionStart`, `onPreLlmCall`, `onPostToolUse`, `onSessionEnd`). Same pattern as the existing Hermes integration. Includes README with paste-this-prompt block, `plugin.yaml`, and `plugin.mjs`. +- **Token savings dashboard** — `agentmemory status` now shows cumulative token savings and dollar cost saved (`$0.30/1K tokens` rate). Same card added to the real-time viewer on port 3113. +- **Paste-this-prompt blocks** — main README and both integration READMEs now open with a copy-pasteable text block users drop into their agent. The agent handles the entire setup (start server, update MCP config, verify health, open viewer). +- **60 custom SVG tags** — 30 dark-bg + 30 light-bg variants under `assets/tags/` and `assets/tags/light/`. Covers 14 section headers, 6 stat cards, 8 pill tags, and utility badges. GitHub README uses `` elements to auto-swap based on reader theme (dark theme → light-bg SVGs, light theme → dark-bg SVGs). +- **Real agent logos** in the Supported Agents grid — 16 agents with clickable brand logos (Claude Code, OpenClaw, Hermes, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Goose, Kilo Code, Aider, Claude Desktop, Windsurf, Roo Code, Claude SDK, plus "any MCP client"). + +### Changed + +- README redesigned from plain markdown headers to SVG-tagged sections matching the agentmemory brand palette (orange `#FF6B35 → #FF8F5E` accent on dark `#1A1A1A` background). +- Hero stat row replaced with 6 custom SVG stat cards showing 95.2% R@5, 92% fewer tokens, 43 MCP tools, 12 auto hooks, 0 external DBs, 654 tests passing. +- Supported Agents grid reordered: Claude Code, OpenClaw, and Hermes now lead the first row (the 3 agents with first-class integrations in `integrations/`). +- Viewer token savings card now shows dollar cost saved alongside raw token count. +- Default configuration files updated: `iii-config.yaml` binds to `127.0.0.1`, new `iii-config.docker.yaml` for Docker deployments. + +### Fixed + +- **Viewer cost calculation was 100x under-reporting** — the formula `tokensSaved / 1000 * 0.3` returns dollars but was treated as cents. Now computes `costDollars` first, then `costCents = Math.round(costDollars * 100)`. 100K tokens now correctly displays `$30.00` instead of `30ct`. +- **`ObservationType` union missing `"image"`** — `VALID_TYPES` in `compress.ts` included `"image"` but the TypeScript union in `types.ts` didn't, breaking exhaustive checks. +- **Dynamic imports inside eviction loops** — `auto-forget.ts` and `evict.ts` called `await import("../utils/image-store.js")` inside nested loops. Hoisted once at the top of each function. +- **OpenClaw `/agentmemory/context` payload** — plugin was sending `{ tokenBudget, query, minConfidence }` but the endpoint expects `{ sessionId, project, budget? }`. Fixed to match the server contract. +- **Cursor cell in README grid** was missing its `Cursor` label. +- Codex CLI logo URL returned 404 from simple-icons CDN. Switched to GitHub org avatars for all logos for maximum reliability. + +### Infrastructure + +- 654 tests (up from 646 in v0.8.1), including 8 new tests covering viewer security, mesh auth, privacy redaction, and export confinement. +- All 60 custom SVGs validated with `xmllint` in CI-ready fashion. +- README consistency check updated to match new tool counts. + +--- + +## [0.8.1] — 2026-04-09 + +- Fix viewer not found when installed via npx (#109) + +## [0.8.0] — 2026-04-09 + +- Initial 0.8.x release + +--- + +[0.8.4]: https://github.com/rohitg00/agentmemory/compare/v0.8.3...v0.8.4 +[0.8.3]: https://github.com/rohitg00/agentmemory/compare/v0.8.2...v0.8.3 +[0.8.2]: https://github.com/rohitg00/agentmemory/compare/v0.8.1...v0.8.2 +[0.8.1]: https://github.com/rohitg00/agentmemory/compare/v0.8.0...v0.8.1 +[0.8.0]: https://github.com/rohitg00/agentmemory/releases/tag/v0.8.0 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..83441738647267f17f984b73de935be3ecab06ab --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,103 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## What This Is + +Python reimplementation of the agentmemory persistent memory server. Exposes a REST API + WebSocket stream + MCP tools endpoint that AI coding agents use to store and retrieve session observations, long-term memories, lessons, and pinned memory slots. Backed by a Dolt SQL Server (MySQL-compatible). + +## Running + +**Prerequisite**: Dolt SQL Server must be running on `127.0.0.1:3306` with a database named `agentmemory`. Config is read from `~/.agentmemory/.env` at startup. + +```bash +# Start the memory API server and built-in viewer (port 3111) +python src/app.py +``` + +The built-in HTML dashboard is accessible at: +- `http://localhost:3111/viewer` or `http://localhost:3111/` + +No build step. No test runner is configured yet. + +## Key Environment Variables + +Set in `~/.agentmemory/.env` or as system env vars: + +| Variable | Default | Purpose | +|---|---|---| +| `III_REST_PORT` / `PORT` | `3111` | API server port | +| `DOLT_HOST/PORT/USER/PASSWORD/DATABASE` | `127.0.0.1/3306/root//"agentmemory"` | Dolt connection | +| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | — | Enables 768-dim vector search; without it, BM25-only | +| `AGENTMEMORY_SECRET` | — | Enables Bearer token auth on all endpoints | +| `AGENT_ID` | — | Default agent ID for scope isolation | +| `AGENTMEMORY_AGENT_SCOPE=isolated` | — | Filters sessions/obs to current `AGENT_ID` | +| `DOLT_AUTO_COMMIT=false` | auto-commit | Disable Dolt versioning commits per write | +| `MAX_OBS_PER_SESSION` | `500` | Hard cap on observations per session | +| `TOKEN_BUDGET` | `2000` | Max tokens in compiled context response | +| `GRAPH_EXTRACTION_ENABLED=true` | `false` | Knowledge graph extraction (requires LLM) — **disabled by default** | +| `CONSOLIDATION_ENABLED=true` | `false` | Memory consolidation (requires LLM) — **disabled by default** | +| `AGENTMEMORY_AUTO_COMPRESS=true` | `false` | LLM-powered observation compression | + +## Architecture + +### `src/db.py` — Storage Layer +`StateKV` wraps a single Dolt table `kv_store(scope VARCHAR, key VARCHAR, value LONGTEXT)`. All data is JSON-serialized. Scopes are namespaced strings (e.g. `mem:sessions`, `mem:obs:{session_id}`). Dolt versioning is triggered via `CALL dolt_add('-A')` + `CALL dolt_commit(...)` stored procedures — this is what makes the store git-versioned. + +### `src/functions.py` — Business Logic +All core operations live here. Important globals: +- `_bm25_index` / `_vector_index` — in-memory search indexes (rebuilt from DB on startup if empty) +- `_hybrid_search` — combines BM25 + vector search; only initialized when embedding provider is set +- `_stream_broadcaster` — WebSocket broadcast callback injected by `app.py` + +Key scopes are defined in the `KV` class. Dynamic scopes: `KV.observations(session_id)` → `mem:obs:{session_id}`. + +**Observation pipeline**: raw payload → `strip_private_data()` → `build_synthetic_compression()` → stored + BM25-indexed + vector-indexed + Dolt-committed + WebSocket-broadcast. + +**Memory versioning**: `remember()` checks Jaccard similarity against existing memories; if > 0.7 match found, the new memory supersedes the old one (`isLatest=False` on old, `parentId` set on new). + +**Context compilation** (`context()`): assembles pinned slots → project profile → lessons (scored by confidence × project match) → past session summaries, capped at `TOKEN_BUDGET` tokens (estimated at `len/3`). + +**Lessons**: fingerprinted by SHA-256 of content. Duplicate saves strengthen confidence (`+0.1 × (1 - conf)`). Weekly decay sweep reduces confidence by `decayRate × weeks`; soft-deleted at ≤ 0.1 confidence with 0 reinforcements. + +### `src/search.py` — Search Indexes +- `SearchIndex`: BM25 with custom Porter stemmer. Persisted to Dolt in sharded 2MB chunks via `IndexPersistence`. +- `VectorIndex`: cosine similarity over Gemini 768-dim embeddings stored as base64-encoded float32 arrays. +- `HybridSearch`: fuses BM25 + vector scores with RRF (reciprocal rank fusion). + +### `src/app.py` — Flask API +Initializes DB → embedding provider → index persistence → rebuilds index if empty (background thread). All endpoints check `AGENTMEMORY_SECRET` via timing-safe Bearer token comparison. WebSocket at `/stream/mem-live/viewer` broadcasts raw + compressed observations to connected viewers. + +MCP tools are served at `GET /agentmemory/mcp/tools` (schema list) and `POST /agentmemory/mcp/tools` (tool call dispatch). + +### `src/viewer/index.html` — Built-in HTML Dashboard +Interactive web dashboard served directly by the Flask server. Provides real-time view of active sessions, timelines, memories with search, slots editor, and DB migration panel. Connects to the Flask backend via REST and live WebSockets. Imports legacy TypeScript `.bin` files via `src/import_data.py`. + +## API Surface + +Base path: `/agentmemory/` + +- `GET /livez` — health/liveness (no auth) +- `POST /observe` — ingest a hook event observation +- `POST /agent/observe` — simplified observe for direct agent use +- `POST /remember` / `POST /agent/remember` — save long-term memory +- `POST /forget` — delete memory/session/observations +- `POST /context` — compile context for a session+project +- `POST /search` — hybrid BM25+vector search +- `POST/GET /lessons` — lessons CRUD + `/lessons/search`, `/lessons/strengthen` +- `GET/POST /slots`, `GET/POST/DELETE /slot` — memory slots CRUD +- `POST /slot/reflect` — auto-populate slots from session observations +- `POST/GET /session/start|end|commit` — session lifecycle +- `GET /sessions`, `GET /observations` — list data +- `GET/POST /relations` — knowledge graph edges +- `POST /evolve` — create new memory version +- `POST /timeline` — chronological observation window +- `GET /profile` — project profile (top concepts/files); no `?project` → returns list of all known projects +- `GET /actions` — list actions (`?limit`, `?status`) +- `POST /actions` — create action +- `PATCH /actions/` — update action status/fields +- `GET /frontier` — pending+active actions sorted by priority +- `GET /insights` — list insights (`?limit`) +- `GET /replay/sessions` — sessions list for replay tab +- `GET /replay/load?sessionId=` — full session + observations for replay +- `GET/POST /mcp/tools` — MCP protocol adapter diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..026795a7c5dd662e8c8cc83f27ce5f9ca7227eda --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,48 @@ +# Code of Conduct + +agentmemory follows the [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). + +The short version: + +- Be kind. Assume good faith. +- Disagree on the idea, not the person. +- Harassment — in issues, PRs, discussions, or any other project space — is not tolerated. +- Unwelcome behavior gets moderated first by reminder, then by time-out, then by removal. + +## Enforcement + +Reports go to **ghumare64@gmail.com** with subject `agentmemory CoC`. All reports are confidential. + +Responses follow the Covenant's enforcement ladder — correction, warning, temporary ban, permanent ban — and are decided by the project Maintainers listed in [MAINTAINERS.md](./MAINTAINERS.md). Where a Maintainer is a party to the report, that Maintainer recuses. + +### Escalation when no impartial Maintainer is available + +If every listed Maintainer recuses, or if the project is operating with a single Maintainer and the report concerns that Maintainer, the report is forwarded to an external neutral contact for independent adjudication. The current fallback chain, in order: + +1. **Contributor Covenant community ombudsperson** — email `ombudsperson@contributor-covenant.org` (see ). +2. **Hosting foundation abuse channel** — when agentmemory is accepted into a foundation (see `GOVERNANCE.md`), reports can be routed to that foundation's conduct committee instead. The current contact will be published here at that time. +3. **GitHub Trust & Safety** — for conduct that occurs inside GitHub spaces, the report can also be filed through . + +The external contact receives the original report verbatim (redacted only of third-party PII unrelated to the incident) and decides the enforcement step. The Maintainer body executes whatever enforcement action the external contact recommends. This ensures no report can dead-end because every internal reviewer is conflicted. + +## Scope + +This applies to every project space: + +- GitHub issues, PRs, discussions, and reviews on this repo. +- Any official chat channel that gets set up (currently none). +- Public representation of the project at conferences, meetups, and on social media. + +## Full text + +Reproduced verbatim from the Contributor Covenant 2.1 for convenience: + +> We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. +> +> We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +Full Covenant v2.1 text: + +## Attribution + +Contributor Covenant is licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..39d38d6fc5603099b82bd0ebef14bb1ef36647a2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,115 @@ +# Contributing to agentmemory + +Thanks for taking an interest. This file is the short path from "I have an idea" to "it's in main." + +## Ground rules + +- Apache-2.0 license applies to every contribution. +- Sign-off is required on every commit (see [DCO](#developer-certificate-of-origin) below). +- Be civil. [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) applies. +- No attribution headers ("Generated with Claude Code", "Co-Authored-By: Claude", etc.) in commits or PR descriptions. + +## Before you open an issue + +Search existing issues first: + +- [open issues](https://github.com/rohitg00/agentmemory/issues?q=is%3Aissue+is%3Aopen) +- [closed issues](https://github.com/rohitg00/agentmemory/issues?q=is%3Aissue+is%3Aclosed) + +If it's a bug: provide the repro steps, your Node version, OS, agentmemory version (`npm view @agentmemory/agentmemory version`), and what you expected vs. what you saw. + +If it's a feature: describe the user problem before the implementation. "I couldn't X because Y" beats "please add X." + +## Before you open a PR + +1. Fork the repo and create a branch off `main`: + - `feat/` for features + - `fix/-` for bug fixes + - `docs/`, `refactor/`, `chore/` for the rest +2. `npm install` — you need Node >=20. +3. `npm run build` — TypeScript must compile clean. +4. `npm test` — the full test suite must pass. The one integration test under `test/integration.test.ts` needs a live server on `:3111` and is fine to skip locally. +5. Commit with sign-off. Rebase over tiny fixup commits so the history stays readable. + +## Pull request flow + +- Keep PRs small and focused. One logical change per PR. +- Write a clear description: what it does, why, and how to verify. +- Link the issue the PR resolves (`Fixes #NNN` / `Closes #NNN`). +- Expect CodeRabbit to review automatically. Address its comments before asking a human. +- Address review feedback in new commits (do not force-push to the same branch). Maintainers may squash on merge. +- A maintainer will merge when tests pass, CodeRabbit is green, and any review comments are addressed. + +## Developer Certificate of Origin + +Every commit must carry a `Signed-off-by` trailer stating you have the right to submit the contribution under Apache-2.0. The full text of the DCO is at . + +Add it automatically: + +```bash +git commit -s -m "feat: your message" +``` + +PRs with commits lacking sign-off will not merge. + +## Coding style + +- TypeScript strict mode. No `any` unless justified in a comment. +- Prettier-compatible formatting (editor on save is fine; no repo-wide hook). +- No code comments that restate what the code does. Only write a comment when the *why* is non-obvious — a hidden constraint, an invariant, a workaround for a specific bug. +- No dead code, no commented-out imports. +- Tests live next to the feature in `test/.test.ts`. Name the test after the behavior, not the implementation. + +## Subsystems at a glance + +| Directory | What lives here | +|-|-| +| `src/triggers/api.ts` | Every HTTP endpoint under `/agentmemory/*`. Adding an MCP tool? Add the REST twin here too. | +| `src/mcp/` | Standalone MCP server (`@agentmemory/mcp`), tools registry, transport, in-memory KV. | +| `src/functions/` | Core memory operations — observe, compress, consolidate, retention, forget, graph, smart-search, export-import, governance. | +| `src/hooks/` | The 12 auto-hooks that capture sessions in agents. | +| `src/health/` | Liveness + readiness + alert thresholds. | +| `src/state/` | KV schema, keyed mutex, access log. | +| `integrations/` | First-party plugins: `hermes/`, `openclaw/`, `filesystem-watcher/`. | +| `plugin/` | Claude Code plugin (`agentmemory@agentmemory`). | +| `website/` | Marketing site (Next.js 16). | +| `test/` | Vitest test suite. | + +## Adding an MCP tool + +1. Register the function in `src/functions/.ts`. +2. Register the HTTP trigger in `src/triggers/api.ts` with a matching `api_path`. +3. Add the tool entry in `src/mcp/tools-registry.ts`. +4. Implement in `src/mcp/standalone.ts` if the standalone MCP package should also expose it. +5. Write a test under `test/`. +6. No CHANGELOG touch in the PR itself — release PRs are the only place CHANGELOG changes. + +## Adding an auto-hook + +1. Add the new `HookType` string to the union in `src/types.ts`. +2. Wire the handler in `src/hooks/.ts`. +3. Add a Vitest case that fires the hook and asserts the observation gets written. + +## Release process + +Maintainers cut releases. Every bump touches 8 files in lockstep: + +1. `package.json` +2. `package-lock.json` (top + `packages[""].version`) +3. `plugin/.claude-plugin/plugin.json` +4. `packages/mcp/package.json` (self + `~x.y.z` pin on the main package) +5. `src/version.ts` (extend the union, assign) +6. `src/types.ts` (`ExportData.version` union) +7. `src/functions/export-import.ts` (`supportedVersions` Set) +8. `test/export-import.test.ts` (assertion) + +Then: CHANGELOG section, PR, merge, tag, GitHub release. The `Publish to npm` workflow picks up the release trigger and publishes `@agentmemory/agentmemory`, `@agentmemory/mcp`, and `@agentmemory/fs-watcher` to npm with provenance. + +## Security issues + +Do not open a public issue for a security report. See [SECURITY.md](./SECURITY.md). + +## Questions + +- Implementation questions: open a GitHub Discussion. +- Governance questions: open an issue labeled `governance`. See [GOVERNANCE.md](./GOVERNANCE.md). diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000000000000000000000000000000000000..dde04a1aee939e942b8b93ecf386cd61af209e42 --- /dev/null +++ b/Caddyfile @@ -0,0 +1,26 @@ +:7860 { + # Route WebSocket streams (iii-stream on 3112) + # Keep full path — iii-stream expects /stream/mem-live/viewer + handle /stream/* { + reverse_proxy localhost:3112 { + header_up Host localhost:3112 + header_up Authorization "Bearer {env.AGENTMEMORY_SECRET}" + } + } + + # Route REST API endpoints (iii-http on 3111) + # Caddy injects the secret so the dashboard viewer works without exposing it to the browser + handle /agentmemory/* { + reverse_proxy localhost:3111 { + header_up Host localhost:3111 + header_up Authorization "Bearer {env.AGENTMEMORY_SECRET}" + } + } + + # Route Viewer dashboard (on 3113) + handle { + reverse_proxy localhost:3113 { + header_up Host localhost:3113 + } + } +} diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000000000000000000000000000000000000..aa9b12f1bac4c041525d704d00e5abb059cdd8dd --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,288 @@ +# Design System Inspired by Lamborghini + +## 1. Visual Theme & Atmosphere + +Lamborghini's website is a cathedral of darkness — a digital stage where jet-black surfaces stretch infinitely and every element emerges from the void like a machine under a spotlight. The page is almost entirely black. Not dark gray, not near-black — true, uncompromising black (`#000000`) that saturates the viewport and refuses to yield. Into this abyss, white type and Lamborghini Gold (`#FFC000`) are deployed with surgical precision, creating a visual language that feels like walking through a nighttime motorsport event where every surface absorbs light except the things that matter. + +The hero is a full-viewport video — dark, cinematic, immersive — showing event footage or vehicle reveals with the Lamborghini bull logo floating ethereally above. The navigation is minimal: a centered bull logo, a "MENU" hamburger on the left, and search/bookmark icons on the right, all rendered in white against the black canvas. There are no borders, no visible nav containers, no background color on the header — just white marks floating in darkness. The overall mood is nocturnal luxury: exclusive, theatrical, and deliberately intimidating. Each section transition is a scroll through darkness into the next revelation. + +Typography is the voice of this darkness. LamboType — a custom Neo-Grotesk typeface created by Character Type and design agency Strichpunkt — is used for everything from 120px uppercase display headlines to 10px micro labels. Its distinctive 12° angled terminals are inspired by the aerodynamic lines of Lamborghini's super sports cars, and its proportions range from Normal to Ultracompressed width. Headlines SHOUT in uppercase at enormous scales with tight line-heights (0.92 at 120px), creating dense blocks of text that feel stamped from steel. The typeface carries hexagonal geometric DNA — constructed from hexagons, three-armed stars, and circles — that echoes throughout the interface in the hexagonal pause button and UI icons. Built on Bootstrap grid with 68 Element Plus/UI components, the technical infrastructure is substantial beneath the theatrical surface. + +**Key Characteristics:** +- True black (`#000000`) dominant surfaces with white and gold as the only relief colors +- LamboType custom Neo-Grotesk font with 12° angled terminals inspired by aerodynamic car lines +- Lamborghini Gold (`#FFC000`) as the sole accent color — used exclusively for primary CTA buttons +- All-uppercase display typography at extreme scales (120px, 80px, 54px) with tight line-heights +- Full-viewport video heroes with cinematic event/vehicle content +- Zero border-radius on buttons — sharp, angular, uncompromising rectangles +- Hexagonal motifs in UI elements (pause button, icon system) echoing brand geometry +- Bootstrap grid system + Element Plus/UI 68 components underneath +- Transparent ghost buttons with white borders at 50% opacity as the secondary CTA pattern + +## 2. Color Palette & Roles + +### Primary +- **Lamborghini Gold** (`#FFC000`): The signature accent color — a warm, saturated amber-gold (rgb 255, 192, 0) used exclusively for primary action buttons ("Discover More", "Tickets", "Start Configuration"). The only chromatic color in the entire interface, it ignites against the black canvas like a headlight cutting through night +- **Pure White** (`#FFFFFF`): Primary text color on dark surfaces, logo rendering, nav elements, and light-mode button fills — the voice that speaks from the darkness + +### Secondary & Accent +- **Dark Gold** (`#917300`): Hover/pressed state for gold buttons — a deep amber (rgb 145, 115, 0) that darkens the gold to signal interaction +- **Gold Text** (`#FFCE3E`): Slightly lighter gold variant (rgb 255, 206, 62) used for inline text accents and highlighted labels +- **Cyan Pulse** (`#29ABE2`): Electric blue-cyan (rgb 41, 171, 226) appearing as an informational accent and interactive element highlight +- **Link Blue** (`#3860BE`): Medium blue (rgb 56, 96, 190) used universally for link hover states across all text colors + +### Surface & Background +- **Absolute Black** (`#000000`): The dominant surface color — used for page background, hero sections, header, footer, and most containers +- **Charcoal** (`#202020`): Elevated dark surface (rgb 32, 32, 32) — the primary "dark gray" for cards, panels, and text containers sitting above the black canvas +- **Dark Iron** (`#181818`): Subtle surface variant (rgb 24, 24, 24) — barely distinguishable from black, used for footer and deep sections +- **Overlay Black** (`rgba(0,0,0,0.7)`): Semi-transparent overlay for modals and video dimming +- **Near White** (`#F8F8F8`): Rare light surface (rgb 248, 248, 248) for content blocks in white-mode sections +- **Mist** (`#E6E6E6`): Light gray surface for secondary light-mode containers + +### Neutrals & Text +- **Pure White** (`#FFFFFF`): Primary text on dark backgrounds — headlines, body, nav labels +- **Smoke** (`#F5F5F5`): Secondary text on dark surfaces — slightly softer than pure white +- **Graphite** (`#494949`): Dark gray text on light surfaces (rgb 73, 73, 73) +- **Ash** (`#7D7D7D`): Mid-range gray for muted text, timestamps, and metadata (rgb 125, 125, 125) +- **Steel** (`#969696`): Lighter gray for disabled text and subtle labels (rgb 150, 150, 150) +- **Slate** (`#666666`): Alternative mid-gray for secondary content +- **Iron** (`#555555`): Dark mid-gray for body text variants +- **Shadow** (`#313131`): Very dark gray for text on dark surfaces where white is too strong + +### Semantic & Accent +- **Cyan Pulse** (`#29ABE2`): Used for informational highlights and interactive feedback +- **Link Blue** (`#3860BE`): Universal hover state for all hyperlinks +- **Teal Action** (`#1EAEDB`): Button hover background for transparent/ghost variants (rgb 30, 174, 219) + +### Gradient System +- No explicit gradients in the color palette — the dark-to-light progression is achieved through surface layering: `#000000` → `#181818` → `#202020` → `#494949` → `#7D7D7D` +- Video heroes use natural atmospheric gradients from the content itself +- Top-of-page gradient: subtle dark-to-darker fade at the edges of full-bleed imagery + +## 3. Typography Rules + +### Font Family +- **Display & UI**: `LamboType`, Roboto, Helvetica Neue, Arial — custom Neo-Grotesk typeface by Character Type for Lamborghini's 2024 brand refresh. Available in widths from Normal to Ultracompressed and weights from Light (300) to Black. Features 12° angled terminals inspired by aerodynamic car geometry, hexagonal construction logic, and support for 200+ languages including Latin, Cyrillic, and Greek +- **Fallback/UI**: `Open Sans` — used for some button/form contexts as system fallback +- **No italic variants** observed on the marketing site — the brand voice is always upright + +### Hierarchy + +| Role | Size | Weight | Line Height | Letter Spacing | Notes | +|------|------|--------|-------------|----------------|-------| +| Hero Display | 120px (7.50rem) | 400 | 0.92 | normal | LamboType, uppercase, maximum impact | +| Display 2 | 80px (5.00rem) | 400 | 1.13 | normal | LamboType, uppercase, major section titles | +| Section Title | 54px (3.38rem) | 400 | 1.19 | normal | LamboType, uppercase | +| Sub-section | 40px (2.50rem) | 400 | 1.15 | normal | LamboType, uppercase | +| Feature Heading | 27px (1.69rem) | 400 | 1.37 | normal | LamboType, uppercase | +| Card Title | 24px (1.50rem) | 400 | — | normal | LamboType | +| Body Large | 18px (1.13rem) | 400 | 1.56 | normal | LamboType, mixed case and uppercase variants | +| Body / UI | 16px (1.00rem) | 400/700 | 1.50 | normal/0.16px | LamboType, primary body text | +| Button Large | 16px (1.00rem) | 400 | 1.50 | normal | Gold CTA buttons | +| Button Standard | 14.4px (0.90rem) | 300/700 | 1.00 | 0.14–0.2px | LamboType, uppercase, ghost buttons | +| Button Small | 13px (0.81rem) | 300/500 | 1.20 | 0.13–0.2px | LamboType, compact button variant | +| Caption | 14px (0.88rem) | 600/700 | 1.14–1.50 | -0.42px | LamboType, uppercase, negative tracking | +| Label | 12px (0.75rem) | 400/500 | 1.83 | 0.96px | LamboType, uppercase badges and micro labels | +| Micro | 10px (0.63rem) | 400 | 1.00–2.00 | 0.225px | LamboType, uppercase, smallest text | + +### Principles +- **ALL-CAPS is the default voice**: Display and feature headings are universally uppercase. This creates a shouting, commanding tone that matches the brand's aggression +- **Extreme scale range**: From 120px heroes to 10px micro labels — a 12:1 ratio that creates dramatic visual hierarchy +- **Tight line-heights at scale**: Display sizes use 0.92-1.19 line-height, creating dense, compressed blocks of type that feel stamped rather than typeset +- **Weight 400 dominates**: Unlike many design systems that use bold for emphasis, Lamborghini's regular weight carries the headlines — the typeface itself is so distinctive it doesn't need weight variation +- **Negative tracking on captions**: -0.42px letter-spacing on 14px captions creates a compressed, technical aesthetic +- **Positive tracking on micro text**: +0.225px at 10px ensures legibility at the smallest sizes +- **Single typeface discipline**: LamboType handles everything — the 12° angled terminals and hexagonal geometry provide visual coherence across all sizes + +## 4. Component Stylings + +### Buttons +All buttons use **zero border-radius** — sharp, angular rectangles that echo the aggressive lines of Lamborghini vehicles. + +**Gold Accent CTA** — The primary action: +- Default: bg `#FFC000` (Lamborghini Gold), text `#000000`, padding 24px, fontSize 16px, fontWeight 400, borderRadius 0px, no border +- Hover: bg `#917300` (Dark Gold), darkens significantly +- Class: `btn-accent btn-large` +- Used for: "Discover More", "Tickets", "Start Configuration" + +**Transparent Ghost** — The secondary action on dark backgrounds: +- Default: bg transparent, text `#FFFFFF`, border 1px solid `#FFFFFF`, padding 16px, opacity 0.5 +- Hover: bg `#1EAEDB` (Teal Action), text white, opacity 0.7 +- Focus: bg `#1EAEDB`, border 1px solid `#000000`, outline 2px solid `#000000` +- Used for: secondary CTAs on hero sections and dark panels + +**White Filled** — Light-mode primary: +- Default: bg `#FFFFFF`, text `#202020`, no border +- Used for: CTAs on dark sections where gold isn't appropriate + +**Black Filled** — Dark filled variant: +- Default: bg `#000000`, text `#202020` +- Used for: Inverted CTA on light sections + +**Gray Neutral** — Subtle action: +- Default: bg `#969696`, text `#202020` +- Used for: secondary/tertiary actions, badge-like buttons + +### Cards & Containers +- Background: `#202020` (Charcoal) on black canvas, or `#000000` on lighter sections +- Border: `0px 1px solid #202020` bottom borders for section dividers +- Border-radius: 0px (completely sharp corners) +- Shadow: minimal, uses overlay opacity for depth +- Content: full-bleed photography + overlaid text in white + +### Inputs & Forms +- Minimal form presence on the marketing site +- Switch elements: border-radius 20px (the only rounded element), border 1px solid `#DDDDDD` +- Cookie banner input style: white text on black with `#7D7D7D` borders + +### Navigation +- **Desktop**: Centered bull logo, "MENU" hamburger with icon on left, search icon + bookmarks icon on right +- **Background**: Transparent (inherits black page background) +- **Sticky**: Fixed to top, floats above content +- **No visible borders or shadows** — elements float in the darkness +- **"MENU" label**: White text at 14px weight 400, uppercase, accompanies hamburger icon +- **Hexagonal motifs**: Pause button on hero sections uses hexagonal outline shape + +### Image Treatment +- **Hero**: Full-viewport video sections (100vh) with cinematic event/vehicle footage +- **Event photography**: Full-bleed aerial shots of Lamborghini Arena events +- **Vehicle imagery**: High-contrast studio shots on dark backgrounds, full-width +- **Aspect ratios**: Predominantly 16:9 and wider for cinematic feel +- **Dark gradient overlays**: Subtle darkening at top/bottom edges of video to ensure text legibility + +### Distinctive Components +- **Hexagonal Pause Button**: Video control uses a hexagonal outline (matching the brand's geometric DNA from the typeface), positioned bottom-right of hero sections +- **Progress Bar**: Thin white line at bottom of hero sections indicating video/slide progress +- **Badge/Tag**: bg `#969696`, text white, padding 8px, fontSize 10px, borderRadius 2px — tiny metallic pills + +## 5. Layout Principles + +### Spacing System +- **Base unit**: 8px +- **Full scale**: 2px, 4px, 5px, 8px, 10px, 12px, 15px, 16px, 20px, 24px, 32px, 40px, 48px, 56px +- **Button padding**: 16px (ghost), 24px (gold accent) +- **Section padding**: 48–56px vertical, 40px horizontal +- **Small spacing**: 2–5px for fine adjustments (badge padding, border spacing) + +### Grid & Container +- **Framework**: Bootstrap grid system (container + row + col) +- **Max width**: 1440px (largest breakpoint) +- **Columns**: Standard 12-column Bootstrap grid +- **Full-bleed**: Hero sections break out of grid to fill viewport edge-to-edge +- **Content areas**: Centered within 1200px max-width containers + +### Whitespace Philosophy +Lamborghini uses darkness as whitespace. The generous black expanses between content blocks serve the same function as white space in a light design — creating breathing room that elevates each element to the status of exhibit. A model name floating in the middle of a black viewport has the same visual weight as a gallery piece on a white wall. The absence of color IS the design. + +### Border Radius Scale +| Value | Context | +|-------|---------| +| 0px | Default for everything — buttons, cards, containers, images | +| 1px | Subtle span elements | +| 2px | Badges, close buttons, cookie elements — barely perceptible | +| 20px | Toggle switches only — the sole rounded element | + +## 6. Depth & Elevation + +| Level | Treatment | Use | +|-------|-----------|-----| +| Level 0 (Abyss) | `#000000` flat | Page background, deepest layer | +| Level 1 (Surface) | `#181818` or `#202020` | Cards, content panels, elevated sections | +| Level 2 (Overlay) | `rgba(0,0,0,0.7)` | Modal backdrops, video dimming | +| Level 3 (Fog) | `rgba(0,0,0,0.5)` | Lighter overlays, hover states | +| Level 4 (Mist) | `rgba(0,0,0,0.25)` | Subtle depth hints | + +### Shadow Philosophy +Lamborghini achieves depth through surface color layering rather than shadows. On a black canvas, traditional drop shadows are invisible — instead, the system creates elevation by shifting from absolute black to progressively lighter dark grays: `#000000` → `#181818` → `#202020` → `#494949`. This "darkness gradient" approach means that elevated elements are literally lighter than their surroundings, inverting the traditional shadow model. + +### Decorative Depth +- Full-bleed video provides atmospheric depth through cinematic lighting +- The hexagonal pause button floats with a thin white outline stroke +- Progress bars at hero section bottoms create a subtle horizon line +- No gradients, glows, or blur effects on UI elements — the photography provides all visual richness + +## 7. Do's and Don'ts + +### Do +- Use absolute black (`#000000`) as the primary background — never dark gray as a substitute +- Apply Lamborghini Gold (`#FFC000`) exclusively for primary CTA buttons — never for decorative purposes +- Set all display headings in uppercase with LamboType — the brand voice is always SHOUTING +- Use zero border-radius on buttons and cards — sharp angles are non-negotiable +- Maintain tight line-heights (0.92–1.19) on display type to create dense, architectural text blocks +- Use the transparent ghost button (white border, 50% opacity) as the secondary CTA on dark backgrounds +- Let full-viewport video/photography carry emotional weight — UI is infrastructure, not decoration +- Reserve hexagonal geometry for UI icons and the video control button +- Use weight 400 (regular) for headlines — the typeface is distinctive enough without bold emphasis +- Keep the gray palette achromatic — all neutrals are pure gray without color tinting + +### Don't +- Introduce additional accent colors beyond gold — the monochrome-plus-gold system is sacred +- Apply border-radius to buttons or cards — curved edges contradict the angular vehicle aesthetic +- Use LamboType in italic or decorative styles — the brand is always upright and direct +- Add gradients to buttons or surfaces — depth comes from surface layering, not blending +- Use light backgrounds as the primary canvas — darkness is the default state, light is the exception +- Mix lowercase into display headings — the uppercase convention communicates authority and power +- Add hover animations with scale or translate — interactions should be color-only (background/opacity shifts) +- Use Open Sans for display text — LamboType must handle all visible typography +- Create busy layouts with many small elements — Lamborghini's design is about singular, bold statements +- Apply shadows to elements — on a black canvas, shadows are meaningless; use surface color shifts instead + +## 8. Responsive Behavior + +### Breakpoints +| Name | Width | Key Changes | +|------|-------|-------------| +| Mobile Small | <425px | Single column, reduced type scale, stacked buttons | +| Mobile | 425-576px | Single column, hamburger nav, hero text ~40px | +| Tablet Small | 576-768px | 2-column grid begins, padding adjusts | +| Tablet | 768-1024px | 2-column layout, expanded hero, vehicle cards side-by-side | +| Desktop | 1024-1280px | Full navigation, 3+ column grids, display text at 80px | +| Desktop Large | 1280-1440px | Full layout, hero at 120px display, max-width containers | +| Wide | >1440px | Content centered, margins expand, hero fills viewport | + +### Touch Targets +- Gold CTA buttons: 48px+ minimum height with 24px padding (exceeds WCAG 44×44px) +- Ghost buttons: 48px+ with 16px padding +- Hamburger menu: large touch target (~48px square) +- Hexagonal pause button: approximately 48px diameter + +### Collapsing Strategy +- **Navigation**: Always hamburger-based ("MENU" + icon) — no horizontal nav expansion on any breakpoint +- **Hero video**: Maintains full-viewport height across all breakpoints, adjusting object-fit +- **Display type**: Scales from 120px (desktop) → 80px (tablet) → 54px/40px (mobile) +- **Button layout**: Side-by-side on desktop, stacks vertically on mobile +- **Grid columns**: 3-column → 2-column → 1-column progression +- **Section spacing**: Reduces from 56px → 40px → 24px vertical padding + +### Image Behavior +- Hero videos use `object-fit: cover` to maintain cinematic framing at all sizes +- Vehicle images scale within their containers with maintained aspect ratios +- Event photography crops to viewport width on narrow screens +- Background images darken at edges to maintain text contrast on all viewports + +## 9. Agent Prompt Guide + +### Quick Color Reference +- Primary CTA: "Lamborghini Gold (#FFC000)" +- Background: "Absolute Black (#000000)" +- Surface: "Charcoal (#202020)" +- Heading text: "Pure White (#FFFFFF)" +- Body text: "Ash (#7D7D7D)" +- Link hover: "Link Blue (#3860BE)" +- Accent: "Cyan Pulse (#29ABE2)" +- Border: "Pure White (#FFFFFF) at 50% opacity" + +### Example Component Prompts +- "Create a hero section with a full-viewport black background, the model name 'TEMERARIO' in LamboType at 120px uppercase weight 400 white text with 0.92 line-height, centered vertically, with a Lamborghini Gold (#FFC000) 'Discover More' button below — sharp corners, 0px radius, 24px padding, black text" +- "Design a transparent ghost button with 1px solid white border at 50% opacity, white text at 14.4px uppercase with 0.2px letter-spacing, padding 16px, on a black background — hover state changes to Teal Action (#1EAEDB) background with 70% opacity" +- "Build a navigation bar with zero visible background on absolute black, a centered bull logo, 'MENU' text label with hamburger icon on the left, and search + bookmark icons on the right — all in white, sticky position" +- "Create a news card grid on charcoal (#202020) background with white headlines at 27px uppercase, body text in #7D7D7D at 16px, and a white underlined 'Read More' link that turns #3860BE on hover" +- "Design a section divider using a 1px solid bottom border in #202020 on a black canvas — the elevation difference is purely through surface color shift, not shadow" + +### Iteration Guide +When refining existing screens generated with this design system: +1. Focus on ONE component at a time — Lamborghini's system is extreme and every element must feel aggressive +2. Reference specific color names and hex codes from this document — the palette has only about 5 active colors +3. Use natural language descriptions, not CSS values — "sharp-cut golden rectangle" not "border-radius: 0px; background: #FFC000" +4. Describe the desired "feel" alongside specific measurements — "floating in total darkness" communicates the black canvas better than "background: #000000" +5. Remember that UPPERCASE IS THE DEFAULT — if text isn't uppercase at display sizes, it probably should be diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..062f827a2b94914a0dddb292e8f62396c0f9aafb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +FROM python:3.11-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + git \ + openssl \ + ca-certificates \ + tini \ + && rm -rf /var/lib/apt/lists/* + +# Install Dolt +RUN curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash + +# Set up HF Spaces user (uid 1000 required) +RUN useradd -m -u 1000 user + +# Set up workdir +WORKDIR /app + +# Copy python dependencies and install +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt + +# Copy application files +COPY --chown=user:user src /app/src +COPY --chown=user:user start.sh /app/start.sh +COPY --chown=user:user sync.py /app/sync.py + +# Give permissions +RUN chmod +x /app/start.sh && chown -R user:user /app /home/user + +# Switch to the non-root user +USER user + +# Set environment +ENV HOME=/home/user + +# Expose the standard HF port +EXPOSE 7860 + +ENTRYPOINT ["/usr/bin/tini", "--", "/app/start.sh"] diff --git a/GOVERNANCE.md b/GOVERNANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..16f505cf45b8894295c072ed9574e4e4013e719d --- /dev/null +++ b/GOVERNANCE.md @@ -0,0 +1,88 @@ +# Governance + +This document describes how decisions are made in the agentmemory project. + +The model here is a near-copy of the [Linux Foundation Minimum Viable Governance (MVG)](https://github.com/todogroup/ospolog/blob/main/governance/minimum-viable-governance.md) pattern, scoped to the project's current single-maintainer reality with a concrete plan to diversify maintainership over the next two release cycles. + +## Mission + +Ship a persistent, local-first memory runtime for AI coding agents that: + +- Requires zero external databases. +- Runs under any MCP-compatible client. +- Stays compatible with the open [Model Context Protocol](https://modelcontextprotocol.io). +- Keeps every user's data on the user's machine by default. + +## Roles + +### Users + +Anyone who runs agentmemory. No process obligation beyond the license. Feedback via [GitHub issues](https://github.com/rohitg00/agentmemory/issues) and [discussions](https://github.com/rohitg00/agentmemory/discussions) is the input channel. + +### Contributors + +Anyone who opens an issue, comments on an issue, opens a pull request, or otherwise helps the project. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the how-to. + +### Maintainers + +A Maintainer has commit access to the repository, responsibility for reviewing PRs, and a vote on project-level decisions. The current list is tracked in [MAINTAINERS.md](./MAINTAINERS.md). + +A Maintainer is expected to: + +- Respond to PRs they are review-owner for within a reasonable window (goal: 3 working days for first comment). +- Uphold the [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md). +- Avoid merging their own non-trivial PRs without a second reviewer once the maintainer count is greater than one. +- Disclose conflicts of interest (employer, paid relationships to users). + +### Maintainer acceptance process + +A Contributor becomes a Maintainer by: + +1. Sustained, high-signal contributions over the prior 6 months (multiple merged PRs across more than one subsystem, plus review comments on others' PRs). +2. A Maintainer nominates the Contributor in a public PR editing `MAINTAINERS.md`. +3. The PR stays open for 7 calendar days to collect objections. +4. If no standing objection from an existing Maintainer, the PR merges and the new Maintainer is added. + +A Maintainer steps down by opening a PR that moves their entry to the `Emeritus` section. This is always accepted. + +## Decision-making + +### Default: lazy consensus on PRs + +Most decisions happen inside pull requests. A PR merges when any Maintainer approves it and no other Maintainer blocks it. Silence is assent after 72 hours of no objection. + +### Non-PR decisions + +Anything that is not a normal code change — charter changes, governance edits, maintainer additions/removals, project scope, breaking API changes, relicensing — happens in a GitHub Issue labeled `governance` with a proposal in the first comment. + +- Minor scope decisions: rough consensus in the issue thread, captured by a Maintainer in a summary comment. +- Formal votes: Maintainers react `+1` / `-1` / `0` to the summary comment. Simple majority of Maintainers with a minimum of two distinct voters carries. If only one Maintainer exists, a 7-day public comment window substitutes for a vote. + +### Breaking changes + +A breaking change to the REST / MCP surface requires: + +1. A tracking issue labeled `breaking` opened at least one minor release cycle ahead of the change. +2. A deprecation path in the codebase (warning log, feature flag, or adapter) for at least one minor release. +3. The change landing in the CHANGELOG under a clearly marked `Breaking` sub-section. + +## Release process + +Releases follow [Semantic Versioning](https://semver.org). See the [release process](./CONTRIBUTING.md#release-process) in `CONTRIBUTING.md` and the automated `.github/workflows/publish.yml` pipeline for the mechanics. + +## Conflicts of interest + +Maintainers employed by a company that sells a product competing with agentmemory, or by a company whose business depends on agentmemory's roadmap, should disclose that relationship in `MAINTAINERS.md` next to their name. Nothing prohibits such maintainership; transparency is the requirement. + +## Amending this document + +This document changes by PR. Edits follow the Non-PR decisions path above: open a `governance` issue, collect feedback, then open the PR citing the issue. + +## Related documents + +- [LICENSE](./LICENSE) — Apache-2.0 +- [CONTRIBUTING.md](./CONTRIBUTING.md) — how to contribute +- [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) — community behavior +- [SECURITY.md](./SECURITY.md) — how to report a vulnerability +- [MAINTAINERS.md](./MAINTAINERS.md) — who has commit access +- [ROADMAP.md](./ROADMAP.md) — where the project is heading diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..b7df565653d59f18774b69bab7a27a0269993171 --- /dev/null +++ b/INSTALL_FOR_AGENTS.md @@ -0,0 +1,163 @@ +# Install agentmemory (agent runbook) + +You are a coding agent. Follow this runbook top to bottom to install agentmemory, wire it into yourself, and verify that persistent memory works. Run each command, check the result against the "Expect" note, then move on. If a step fails, jump to Troubleshooting, and if it still fails, stop and report the step, the exact command, and the error output. + +## What you are installing + +agentmemory is a local memory server for coding agents. It runs on your machine, exposes a REST API on port 3111 and an MCP server, and stores memories on disk under `~/.agentmemory`. It is built on the iii engine, which agentmemory downloads and manages for you as a pinned binary under `~/.agentmemory/bin`. You do not install iii separately. + +Default mode needs no API key and no cloud account. Out of the box it runs hybrid retrieval (BM25 keyword search plus local on-device embeddings), so a full install proves real semantic recall with zero credentials. An LLM provider key is optional and only unlocks richer summaries and auto-injection (see "Optional: richer features"). + +## Prerequisites + +- Node.js >= 20 and npm. Check with `node -v`. +- macOS or Linux for the one-command path. On Windows, use WSL2; native Windows engine setup is manual and `agentmemory connect` is not supported there. +- Ports 3111 (REST), 3112 (streams), 3113 (viewer), and 49134 (engine) free. Override the whole block with `--port ` or `--instance ` if any are taken. + +## Running non-interactively + +Several commands prompt on a TTY (for example the first-run "install globally?" question). As an agent you usually want no prompts. Either set `CI=1` in the environment for the commands below, or rely on the fact that agentmemory skips all prompts automatically when stdin/stdout are not a TTY. Prompts are also never-nag: once answered they persist and are not asked again. Re-run onboarding any time with `agentmemory --reset`. + +## 1. Install globally + +```bash +npm install -g @agentmemory/agentmemory +``` + +If you hit `EACCES` on a system Node install (macOS/Linux), retry with `sudo npm install -g @agentmemory/agentmemory`. + +No-install alternative: skip this step and run the server with `npx -y @agentmemory/agentmemory@latest` everywhere this runbook says `agentmemory`. The `@latest` and `-y` flags matter because npx caches per version and a bare `npx @agentmemory/agentmemory` can serve a stale release. + +Expect: the install completes without errors. + +## 2. Verify the install + +```bash +agentmemory --version +``` + +Expect: a version string is printed. If `command not found`, the global bin is not on `PATH`; use the `npx -y @agentmemory/agentmemory@latest` form instead. + +## 3. Start the server + +The server listens on port 3111 and auto-starts its pinned iii engine on first run (this can take a few seconds the first time while the engine binary is fetched into `~/.agentmemory/bin`). Run it in the background or in a separate terminal so the rest of the runbook can talk to it. + +```bash +agentmemory & +``` + +Or in a dedicated terminal, run `agentmemory` in the foreground. To run a second isolated instance, use `agentmemory --instance 1` (relocates the whole port block to 3211/3212/3213/49234). + +Wait until it is reachable, then continue: + +```bash +curl -fsS http://localhost:3111/agentmemory/livez +``` + +Expect: a `200` response. Retry for up to ~15 seconds on first run while the engine warms up. + +## 4. Prove recall in one command + +```bash +agentmemory demo --serve +``` + +`--serve` boots the server, seeds three realistic sessions (JWT auth, an N+1 query fix, rate limiting), runs semantic searches against them, prints the results, and tears everything down. No second terminal needed. + +Expect: the demo finds the "N+1 query fix" memory when it searches for "database performance optimization", which keyword matching alone cannot do. Open `http://localhost:3113` while it runs to watch the memory build live. + +## 5. Wire MCP into the calling agent + +Detect which agent is running this runbook, then wire its MCP config: + +```bash +agentmemory connect +``` + +`connect` merges agentmemory into that agent's MCP config and preserves any existing servers. Supported agent names: + +`claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`. + +If you cannot tell which agent you are, default to `claude-code`. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. + +Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 53 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach a server, see Troubleshooting. + +## 6. Install native skills + +```bash +npx skills add rohitg00/agentmemory -y +``` + +This installs the native skills so the agent knows when to call the memory tools, not just that they exist. `connect` makes the tools available; skills teach the agent when to use them. + +Expect: the skills are installed for the detected agent. + +## 7. Verify a save and recall round-trip + +Confirm health first: + +```bash +curl -fsS http://localhost:3111/agentmemory/health +``` + +Expect: a JSON body with an ok status. + +Now write a memory and read it back. If MCP is wired, call the `memory_save` tool followed by `memory_smart_search`. Otherwise use REST directly (note: these are the REST paths, which differ from the MCP tool names): + +```bash +curl -X POST http://localhost:3111/agentmemory/remember \ + -H "Content-Type: application/json" \ + -d '{"content":"agentmemory install verification probe","concepts":["install-check"]}' + +curl -X POST http://localhost:3111/agentmemory/smart-search \ + -H "Content-Type: application/json" \ + -d '{"query":"install verification probe","limit":5}' +``` + +Expect: the first call returns `201`, the second returns `200` with results that include the probe memory you just saved. + +If `AGENTMEMORY_SECRET` is set in the environment, the REST API requires it. Add `-H "Authorization: Bearer $AGENTMEMORY_SECRET"` to both calls. By default no secret is set and localhost is open. + +## Optional: richer features + +These are off by default because they spend tokens. Enable them only if the user wants them. Put configuration in `~/.agentmemory/.env` (no `export` prefix), then restart the server. + +- `AGENTMEMORY_INJECT_CONTEXT=true` makes the SessionStart and PreToolUse hooks inject past memory into the agent's context automatically. Cost: spends session tokens proportional to tool-call frequency. +- `AGENTMEMORY_AUTO_COMPRESS=true` sends each observation to your LLM provider for a richer summary. Cost: spends API tokens proportional to tool-use frequency. Requires a provider key. +- Provider key: set one of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, and similar, in the same file. Without a key, agentmemory stays in zero-LLM mode and still indexes and recalls via BM25 plus local embeddings. + +## Tool surface + +The MCP server exposes 53 tools by default (`--tools all`). Use `--tools core` (or `AGENTMEMORY_TOOLS=core`) for a lean 8-tool set on hosts with tight tool limits. The 8 core tools cover save, recall, smart search, sessions, export, audit, and governance delete. + +## Lifecycle commands + +- `agentmemory status` shows server and engine state. +- `agentmemory doctor` runs diagnostics and reports what is misconfigured. +- `agentmemory stop` stops the engine this CLI started (`stop --force` bypasses the Docker guard). +- `agentmemory upgrade` upgrades agentmemory and the iii runtime, best effort. +- `agentmemory --reset` wipes onboarding preferences and re-runs the wizard. +- `agentmemory import-jsonl ` imports prior Claude Code session logs as memories. + +## Troubleshooting + +- `command not found: agentmemory`: the global bin is not on `PATH`. Use `npx -y @agentmemory/agentmemory@latest`. +- `EACCES` during global install: retry with `sudo`, or use the npx form. +- Stale npx version: run `npx -y @agentmemory/agentmemory@latest`, or clear the cache with `rm -rf ~/.npm/_npx` (macOS/Linux). +- Port already in use: another instance or process holds 3111. Stop it, or relocate with `agentmemory --instance 1`. +- Server starts but `livez` never returns 200: re-run with `agentmemory --verbose` to see engine stderr. +- Engine version warning on start: harmless. agentmemory uses its own pinned engine in `~/.agentmemory/bin` regardless of any `iii` on `PATH`. Set `AGENTMEMORY_III_VERSION` only to override deliberately. +- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx @agentmemory/agentmemory` and ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. +- Windows: use WSL2 for the path above. Native Windows runs the server but `connect` and the automated engine install are not supported. + +## Report success + +Report back to the user: + +- agentmemory installed, version, and the server running on port 3111 +- which agent was wired via `agentmemory connect`, and the tool count the agent now sees +- the save and recall round-trip returned the probe memory +- the viewer is available at `http://localhost:3113` +- whether any optional features were enabled + +If any step failed, report which step, the exact command, and the error output. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cb13c72881997c8ad1662ec42c1484cc15859147 --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Rohit Ghumare + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000000000000000000000000000000000000..c6ee2e653b01d2f3f0479cba40486be602796685 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,21 @@ +# Maintainers + +The authoritative list of people with commit access. See [GOVERNANCE.md](./GOVERNANCE.md) for what a Maintainer is, what they do, and how someone becomes one. + +## Active + +| Name | GitHub | Affiliation | Area of focus | Since | +|-|-|-|-|-| +| Rohit Ghumare | [@rohitg00](https://github.com/rohitg00) | Independent | Project lead, all subsystems | 2026-01 | + +## Emeritus + +_None yet._ + +## Maintainer recruitment + +agentmemory is actively looking to diversify maintainership. The growth plan in [ROADMAP.md](./ROADMAP.md) commits to adding at least one additional Maintainer from a different organization by the end of the current growth cycle. + +If you have a sustained contribution track record and would like to be considered, open an issue tagged `governance`. + +The complete contributor graph, with commit counts and recent activity, lives at . diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9881689045a5df60f178a430cb94da0d1df094f8 --- /dev/null +++ b/README.md @@ -0,0 +1,1532 @@ +

+ agentmemory — Persistent memory for AI coding agents +

+ +

+ + Your coding agent remembers everything. No more re-explaining. + Built on iii engine +
+ Persistent memory for Claude Code, GitHub Copilot CLI, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode, and any MCP client. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1.3k stars / 182 forks on the gist +

+ +

+ The gist extends Karpathy's LLM Wiki pattern with confidence scoring, lifecycle, knowledge graphs, and hybrid search: agentmemory is the implementation. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 1,423+ tests passing +

+ +

+ agentmemory demo +

+ +

+ Install • + Quick Start • + Benchmarks • + vs Competitors • + Agents • + How It Works • + MCP • + Viewer • + iii Console • + Powered by iii • + Config • + API +

+ +--- + +## Install + +Fastest path if you use a coding agent: hand it this one instruction and it installs, wires, and verifies agentmemory end to end. + +> Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md + +On Windows the fast path is WSL2. Native Windows engine setup is manual (about 10 to 20 minutes) and `agentmemory connect` is currently unsupported there. See the [Windows notes](#windows) below for the step-by-step. + +```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 demo --serve # one command: boot server, run demo, tear down (no second terminal) +agentmemory connect claude-code # wire MCP into your agent (also: copilot-cli, codex, cursor, gemini-cli, ...) +npx skills add rohitg00/agentmemory -y # install 15 native skills (8 you can invoke, 7 reference) so your agent knows when to use the tools +``` + +Or via `npx` (no install): + +```bash +npx @agentmemory/agentmemory +``` + +Heads-up — npx caches per version. If a bare `npx @agentmemory/agentmemory` serves an older release, force the latest with `npx -y @agentmemory/agentmemory@latest`, or clear the cache once with `rm -rf ~/.npm/_npx` (macOS/Linux; on Windows delete `%LOCALAPPDATA%\npm-cache\_npx`). The first npx run from v0.9.16+ prompts to install globally inline so the bare `agentmemory` command works everywhere afterwards. + +Full options at [Quick Start](#quick-start) below. Agent-specific wiring at [Works with every agent](#works-with-every-agent). + +--- + +

Works with every agent

+ +agentmemory works with any agent that supports hooks, MCP, or REST API. All agents share the same memory server. + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+native plugin + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+native plugin + 6 hooks + MCP +
+GitHub Copilot CLI
+GitHub Copilot CLI
+MCP + plugin hooks/skills +
+OpenClaw
+OpenClaw
+native plugin + MCP +
+Hermes
+Hermes
+native plugin + MCP +
+pi
+pi
+native plugin + MCP +
+OpenHuman
+OpenHuman
+native Memory trait backend +
+Cursor
+Cursor
+MCP server +
+Gemini CLI
+Gemini CLI
+MCP server +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+MCP server +
+Goose
+Goose
+MCP server +
+Kilo Code
+Kilo Code
+MCP server +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP server +
+Windsurf
+Windsurf
+MCP server +
+Roo Code
+Roo Code
+MCP server +
+Warp
+Warp
+connect + MCP + skills +
+ +

+ Works with any agent that speaks MCP or HTTP. One server, memories shared across all of them. +

+ +--- + +You explain the same architecture every session. You re-discover the same bugs. You re-teach the same preferences. Built-in memory (CLAUDE.md, .cursorrules) caps out at 200 lines and goes stale. agentmemory fixes this. It silently captures what your agent does, compresses it into searchable memory, and injects the right context when the next session starts. One command. Works across agents. + +**What changes:** Session 1 you set up JWT auth. Session 2 you ask for rate limiting. The agent already knows your auth uses jose middleware in `src/middleware/auth.ts`, your tests cover token validation, and you chose jose over jsonwebtoken for Edge compatibility. No re-explaining. No copy-pasting. The agent just *knows*. + +```bash +npx @agentmemory/agentmemory +``` + +Latest release notes: [CHANGELOG.md](CHANGELOG.md). + +--- + +

Benchmarks

+ + + + + + +
+ +### Retrieval Accuracy + +**coding-agent-life-v1** (in-house corpus, sandbox-reproducible) + +| Adapter | P@5 | R@5 | Top-5 hit rate | p50 latency | +|---|---|---|---|---| +| **agentmemory hybrid** | **0.240** | **1.000** | **15 / 15** | 14 ms | +| grep baseline | 0.227 | 0.967 | 15 / 15 | 0 ms | + +100% top-5 hit rate at the **P@5 math ceiling** for this corpus (0.240, see scorecard). Hybrid retrieves every gold session; grep misses 1 of 2 gold on the multi-session temporal query. Lift is **recall + temporal**, not aggregate precision — this benchmark is small + gold-sparse, the larger LongMemEval-S below differentiates better. Full per-type breakdown + correction note: [`docs/benchmarks/2026-05-20-coding-agent-life-v1.md`](docs/benchmarks/2026-05-20-coding-agent-life-v1.md). + +**LongMemEval-S** (ICLR 2025, 500 questions) + +| System | R@5 | R@10 | MRR | +|---|---|---|---| +| **agentmemory** | **95.2%** | **98.6%** | **88.2%** | +| BM25-only fallback | 86.2% | 94.6% | 71.5% | + + + +### Token Savings + +| Approach | Tokens/yr | Cost/yr | +|---|---|---| +| Paste full context | 19.5M+ | Impossible (exceeds window) | +| LLM-summarized | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + local embeddings | ~170K | **$0** | + +
+ +> Embedding model: `all-MiniLM-L6-v2` (local, free, no API key). Full reports: [`benchmark/LONGMEMEVAL.md`](benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](benchmark/QUALITY.md), [`benchmark/SCALE.md`](benchmark/SCALE.md). Competitor comparison: [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md) covering agentmemory vs mem0, Letta, Khoj, supermemory, MemPalace, Hippo. + +**Reproduce locally:** [`eval/README.md`](eval/README.md) — adapter-pluggable harness for LongMemEval `_s` (public 500-Q) + `coding-agent-life-v1` (in-house 15-session corpus). Grep / vector / agentmemory adapters score side-by-side, NDJSON output, published scorecards land in [`docs/benchmarks/`](docs/benchmarks/). + +**Pairs with [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything), and [Graphify](https://github.com/safishamsi/graphify).** Code-graph indexing, multi-agent build pipelines, and broader knowledge graphs across docs / PDFs / images / videos. agentmemory remembers the work; those three projects light up the rest of the context layer. Recipes + question-routing table: [`docs/recipes/pairings.md`](docs/recipes/pairings.md). + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (58K ⭐)Letta / MemGPT (23K ⭐)Khoj (35K ⭐)supermemory (26K ⭐)MemPalace (54K ⭐)HippoBuilt-in (CLAUDE.md)
TypeMemory engine + MCP serverMemory layer APIFull agent runtimePersonal AIMemory API + appVector memory (OSS)Memory systemStatic file
Retrieval R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/ASelf-reported~96.6% (self-reported)N/AN/A (grep)
Auto-capture12 hooks (zero manual effort)Manual add() callsAgent self-editsManualAPI-side extractionManualManualManual editing
SearchBM25 + Vector + Graph (RRF fusion)Vector + GraphVector (archival)SemanticVector + RAGVector-onlyDecay-weightedLoads everything into context
Multi-agentMCP + REST + leases + signalsAPI (no coordination)Within Letta runtime onlyNoNoNoMulti-agent sharedPer-agent files
Framework lock-inNone (any MCP client)NoneHigh (must use Letta)StandaloneNoneNoneNonePer-agent format
External depsNone (SQLite + iii-engine)Qdrant / pgvectorPostgres + vector DBMultipleManaged cloudVector storeNoneNone
Memory lifecycle4-tier consolidation + decay + auto-forgetPassive extractionAgent-managedManualAuto-forgetNoneDecay + consolidationManual pruning
Token efficiency~1,900 tokens/session ($10/yr)Varies by integrationCore memory in contextVariesCloud pricingNo token budgetVaries22K+ tokens at 240 obs
Real-time viewerYes (built-in at :3111)Cloud dashboardCloud dashboardWeb UICloud dashboardNoNoNo
Self-hostedYes (default)OptionalOptionalYesNo (cloud-only)YesYesYes
+ +Benchmark note: only agentmemory's R@5 is our own measured result (LongMemEval-S, reproducible from benchmark/COMPARISON.md). The mem0 and Letta figures are their published LoCoMo numbers (a different dataset); the MemPalace and supermemory figures are vendor self-reported claims we have not independently reproduced. Shown side by side for ballpark only, not a head-to-head on identical data. Star counts are approximate and drift over time. + +--- + +

Quick Start

+ +Compatibility: this release targets stable `iii-sdk` `^0.11.0` and iii-engine v0.11.x. + +### Try it in 30 seconds + +```bash +# Terminal 1: start the server +npx @agentmemory/agentmemory + +# Terminal 2: seed sample data and see recall in action +npx @agentmemory/agentmemory demo +``` + +`demo` seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs semantic searches against them. You'll see it find "N+1 query fix" when you search "database performance optimization" — keyword matching can't do that. + +Open `http://localhost:3111/viewer` to watch the memory build live. + +### Recommended: install globally + +`npx` caches per-version. If you ran `npx @agentmemory/agentmemory@0.9.14` last week, a bare `npx @agentmemory/agentmemory` may serve the stale 0.9.14 from `~/.npm/_npx/`, not the latest release. Install once and the bare `agentmemory` command works everywhere: + +```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 +``` + +From v0.9.16 onward, the first npx run prompts you to install globally inline — answer `Y` once and you're set. If you skip, fall back to either of these for a fresh fetch: + +```bash +npx -y @agentmemory/agentmemory@latest # forces latest from npm (cross-platform) +rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux only (POSIX shell) +``` + +On Windows / PowerShell, the equivalent cache clear is `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — the `npx -y ...@latest` form above is the cross-platform option. + +### Session Replay + +Every session agentmemory records is replayable. Open the viewer, pick the **Replay** tab, and scrub through the timeline: prompts, tool calls, tool results, and responses render as discrete events with play/pause, speed control (0.5×–4×), and keyboard shortcuts (space to toggle, arrows to step). + +Already have older Claude Code JSONL transcripts you want to bring in? + +```bash +# Import everything under the default ~/.claude/projects +npx @agentmemory/agentmemory import-jsonl + +# Or import a single file +npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl +``` + +Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions — no side-channel servers. + +> **Heads-up if you rely on `import-jsonl` as your primary capture path:** Claude Code's `cleanupPeriodDays` (in `~/.claude/settings.json`, default **30**) auto-deletes JSONL transcripts older than that window from `~/.claude/projects/`. If you install agentmemory fresh on a months-old Claude Code history, anything older than 30 days is already gone before the first import. Either run `import-jsonl` on a cron, raise `cleanupPeriodDays` to something higher, or wire the auto-capture hooks (the default plugin install path) so each turn lands in agentmemory while the session is live and the JSONL cleanup stops mattering. + +### Upgrade / Maintenance + +Use the maintenance command when you intentionally want to update your local runtime: + +```bash +npx @agentmemory/agentmemory upgrade +``` + +Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies, may run `cargo install iii-engine --force`, and may pull Docker images. + +Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cli.ts:544-595` region). + +### Claude Code (one block, paste it) + +```text +Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 15 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:3111/viewer. +``` + +#### Claude Code without the plugin install (MCP-standalone path) + +If you wire agentmemory's MCP server through `~/.claude.json` directly instead of using `/plugin install`, Claude Code never resolves `${CLAUDE_PLUGIN_ROOT}` and you have to point hook scripts at absolute paths in `~/.claude/settings.json`. Those paths typically embed the agentmemory version (e.g. `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.22/scripts/…`), so the next upgrade silently breaks every hook ([#508](https://github.com/rohitg00/agentmemory/issues/508)). + +Workaround: + +```bash +agentmemory connect claude-code --with-hooks +``` + +This merges the same hook commands into `~/.claude/settings.json` with absolute paths resolved to the bundled `plugin/` directory of the currently installed `@agentmemory/agentmemory` package. Re-run the command after upgrading agentmemory to refresh the paths. User entries in the same file are preserved; only previous agentmemory entries are replaced. Using the `/plugin install` path remains the recommended approach. +For remote or protected deployments, launch Claude Code with `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` set. The plugin passes both values through to its bundled MCP server; when `AGENTMEMORY_URL` is empty, the MCP shim uses `http://localhost:3111`. + +### Codex CLI (Codex plugin platform) + +```bash +# 1. start the memory server in a separate terminal +npx @agentmemory/agentmemory + +# 2. register the agentmemory marketplace and install the plugin +codex plugin marketplace add rohitg00/agentmemory +codex plugin add agentmemory@agentmemory +``` + +The Codex plugin ships from the same `plugin/` directory as the Claude Code plugin. It registers: + +- `@agentmemory/mcp` as an MCP server (proxies all 53 tools when `AGENTMEMORY_URL` points at a running agentmemory server; falls back to 7 tools locally when no server is reachable) +- 6 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop` +- 8 invocable skills: `/recall`, `/remember`, `/session-history`, `/forget`, `/recap`, `/handoff`, `/commit-context`, `/commit-history`, plus 7 reference skills the agent loads on demand (MCP tools, REST API, config, agents, hooks, architecture, and the skill-authoring guide) + +Codex's hook engine injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses (per [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex. + +#### Codex Desktop: plugin hooks currently silent (workaround available) + +`CodexHooks` and `PluginHooks` are both stable + default-enabled in [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), but Codex Desktop builds currently do not dispatch plugin-local `hooks.json` ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP tools still work; only the lifecycle observations are missing. + +Until upstream lands the fix, mirror the same hook commands into the global `~/.codex/hooks.json`: + +```bash +agentmemory connect codex --with-hooks +``` + +This adds an idempotent block to `~/.codex/hooks.json` referencing absolute paths to the bundled scripts (no `${CLAUDE_PLUGIN_ROOT}` expansion needed at user-scope). Re-run the same command after upgrading agentmemory to refresh paths. User entries in the same file are preserved; only previous agentmemory entries are replaced. + +### GitHub Copilot CLI + +```bash +# MCP-only wiring +agentmemory connect copilot-cli + +# Full hooks/skills plugin from the GitHub subdir +copilot plugin install rohitg00/agentmemory:plugin +``` + +`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. This adapter is Windows-safe even though other `connect` adapters still require manual Windows setup. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience. + +
+OpenClaw (paste this prompt) + +```text +Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 53 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:3111/viewer for the real-time viewer. For deeper memory-slot integration, copy `integrations/openclaw` to `~/.openclaw/extensions/agentmemory` and enable `plugins.slots.memory = "agentmemory"` in `~/.openclaw/openclaw.json`. +``` + +Full guide: [`integrations/openclaw/`](integrations/openclaw/) + +
+ +
+Hermes Agent (paste this prompt) + +```text +Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 53 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:3111/viewer for the real-time viewer. For deeper 6-hook memory provider integration (pre-LLM context injection, turn capture, MEMORY.md mirroring, system prompt block), copy integrations/hermes from the agentmemory repo to ~/.hermes/plugins/agentmemory. +``` + +Full guide: [`integrations/hermes/`](integrations/hermes/) + +
+ +### Other agents + +Start the memory server: `npx @agentmemory/agentmemory` + +#### Native skills via `npx skills add` (50+ agents) + +agentmemory ships 15 skills in the Claude-Code-style `/SKILL.md` format: 8 invocable action skills (`remember`, `recall`, `recap`, `handoff`, `forget`, `commit-context`, `commit-history`, `session-history`) and 7 reference skills the agent loads on demand (`agentmemory-mcp-tools`, `agentmemory-rest-api`, `agentmemory-config`, `agentmemory-agents`, `agentmemory-hooks`, `agentmemory-architecture`, `write-agentmemory-skill`). The reference skills carry data tables generated from source, so they never drift. The [`skills`](https://npmjs.com/package/skills) CLI by vercel-labs auto-installs them into the calling agent's native skill directory across 50+ agents (Claude Code, Cursor, Cline, Continue, Droid, Warp, Codex, Antigravity, Kiro, OpenCode, Goose, Roo, Trae, Windsurf, and more): + +```bash +npx skills add rohitg00/agentmemory -y # auto-detects the calling agent +npx skills add rohitg00/agentmemory -y -a warp # explicit agent +npx skills add rohitg00/agentmemory -y -a '*' # install to every installed agent +``` + +This is **complementary** to `agentmemory connect `: + +- `agentmemory connect ` writes the MCP server config so the tools are available. +- `npx skills add rohitg00/agentmemory` installs the skills so the agent knows when to call them. + +For the few agents the skills CLI doesn't cover yet (Zed v1.3.x and below), drop the 15 SKILL.md files under the agent's native skill directory yourself — same format works everywhere. + +#### Standard MCP block + +The agentmemory entry is the **same MCP server block** across every host that uses the `mcpServers` shape (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI, OpenClaw): + +```json +"agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}" + } +} +``` + +**Merge this entry into the existing `mcpServers` object** in the host's config file — don't replace the file. If the file already has other servers, add `agentmemory` next to them as another key inside `mcpServers`. If `mcpServers` is missing entirely, paste the block inside `{ "mcpServers": { ... } }`. The `${VAR}` placeholders inherit `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` from the shell at MCP-server launch — unset vars pass empty strings and the shim falls back to `http://localhost:3111`. One wired entry covers both local and remote (k8s / reverse-proxied) deployments. + +| Agent | Config file | Notes | +|---|---|---| +| **Cursor** | `~/.cursor/mcp.json` | Merge into `mcpServers`. One-click deeplink also available on the website. | +| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Merge into `mcpServers`. Restart Claude Desktop after editing. | +| **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | Same `mcpServers` block. | +| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Same `mcpServers` block. | +| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges). | +| **GitHub Copilot CLI (MCP only)** | `~/.copilot/mcp-config.json` | `agentmemory connect copilot-cli` merges `mcpServers.agentmemory`; Copilot picks it up on next launch or `/mcp`. | +| **GitHub Copilot CLI (full plugin)** | Copilot plugin install | `copilot plugin install rohitg00/agentmemory:plugin` for the plugin from the GitHub subdir. | +| **OpenClaw** | OpenClaw MCP config | Same `mcpServers` block, or use the deeper [memory plugin](integrations/openclaw/). | +| **Codex CLI (MCP only)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, or add `[mcp_servers.agentmemory]` manually. | +| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin add agentmemory@agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 15 skills. On Codex Desktop, also run `agentmemory connect codex --with-hooks` until [openai/codex#16430](https://github.com/openai/codex/issues/16430) lands — plugin hooks are currently silent there. | +| **OpenCode (MCP only)** | `opencode.json` | Different shape — top-level `mcp` key, command as array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. | +| **OpenCode (full plugin)** | `plugin/opencode/` | 22 auto-capture hooks covering session lifecycle, messages, tools, errors. Two slash commands (`/recall`, `/remember`). Copy `plugin/opencode/` into your OpenCode workspace and add the plugin entry to `opencode.json`. See [`plugin/opencode/README.md`](plugin/opencode/README.md) for the full hook table + gap analysis. | +| **pi** | `~/.pi/agent/extensions/agentmemory` | Copy [`integrations/pi`](integrations/pi/) and restart pi. | +| **Hermes Agent** | `~/.hermes/config.yaml` | Use the deeper [memory provider plugin](integrations/hermes/) with `memory.provider: agentmemory`. | +| **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. | +| **Cline (CLI)** | `~/.cline/mcp.json` | `agentmemory connect cline` writes the standard `mcpServers` block. VS Code extension users: paste the same block via Cline Settings → MCP Servers → Edit JSON. | +| **Continue.dev** | `~/.continue/config.yaml` (preferred) or `config.json` (legacy) | `agentmemory connect continue` creates `config.yaml` from scratch when neither exists, or modifies existing `config.json`. **If you already have `config.yaml`** the adapter prints the exact block to paste under `mcpServers:` — it won't silently rewrite your yaml because preserving comments and anchors safely needs a YAML parser the package doesn't ship. Continue uses array form (not object) for `mcpServers`. | +| **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. | +| **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. The `/mcp` slash command inside droid lists configured servers. | +| **Goose** | Goose MCP settings UI | Same `mcpServers` block — use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). | +| **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. | +| **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. | + +**Sandboxed MCP clients** (Flatpak / Snap / restrictive containers) that can't reach the host's `localhost`: also set `"AGENTMEMORY_FORCE_PROXY": "1"` in the `env` block, and point `AGENTMEMORY_URL` at a route the sandbox can actually reach (e.g. your LAN IP). See [#234](https://github.com/rohitg00/agentmemory/issues/234) for the diagnostic walkthrough. + +### Programmatic access (Python / Rust / Node) + +agentmemory registers its core operations as iii functions (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Any language with an iii SDK can call them directly over `ws://localhost:49134` — no separate REST client per language. + +```bash +pip install iii-sdk # Python +cargo add iii-sdk # Rust +npm install iii-sdk # Node +``` + +```python +from iii import register_worker + +iii = register_worker("ws://localhost:49134") +iii.connect() + +iii.trigger({ + "function_id": "mem::smart-search", + "payload": {"project": "demo", "query": "how do tokens refresh"}, +}) +``` + +Worked example: [`examples/python/`](examples/python/) (quickstart + observation/recall flow). REST on `:3111` remains available for hosts without an iii runtime. + +### From source + +```bash +git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory +npm install && npm run build && npm start +``` + +This starts agentmemory with a local `iii-engine` if `iii` is already installed, or falls back to Docker Compose if Docker is available. REST, streams, and the viewer bind to `127.0.0.1` by default. + +Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`** — `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=` if you've migrated to the sandbox model manually. + +- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii` +- **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin` +- **Linux x64:** swap for `x86_64-unknown-linux-gnu` +- **Linux arm64:** swap for `aarch64-unknown-linux-gnu` +- **Windows:** download `iii-x86_64-pc-windows-msvc.zip` from [iii-hq/iii releases v0.11.2](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2), extract `iii.exe`, add to PATH + +Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.11.2`). Full docs: [iii.dev/docs](https://iii.dev/docs). + +### Windows + +agentmemory runs on Windows 10/11, but the Node.js package alone isn't enough — you also need the `iii-engine` runtime (a separate native binary) as a background process. The official upstream installer is a `sh` script and there is no PowerShell installer or scoop/winget package today, so Windows users have two paths: + +**Option A — Prebuilt Windows binary (recommended):** + +```powershell +# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser +# (we pin to v0.11.2 until agentmemory refactors for the new sandbox +# model that engine v0.11.6+ requires) +# 2. Download iii-x86_64-pc-windows-msvc.zip +# (or iii-aarch64-pc-windows-msvc.zip if you're on an ARM machine) +# 3. Extract iii.exe somewhere on PATH, or place it at: +# %USERPROFILE%\.local\bin\iii.exe +# (agentmemory checks that location automatically) +# 4. Verify: +iii --version +# Should print: 0.11.2 + +# 5. Then run agentmemory as usual: +npx -y @agentmemory/agentmemory +``` + +**Option B — Docker Desktop:** + +```powershell +# 1. Install Docker Desktop for Windows +# 2. Start Docker Desktop and make sure the engine is running +# 3. Run agentmemory — it will auto-start the bundled compose file: +npx -y @agentmemory/agentmemory +``` + +**Option C — standalone MCP only (no engine):** if you only need the MCP tools for your agent and don't need the REST API, viewer, or cron jobs, skip the engine entirely: + +```powershell +npx -y @agentmemory/agentmemory mcp +# or via the shim package: +npx -y @agentmemory/mcp +``` + +**Diagnostics for Windows:** if `npx @agentmemory/agentmemory` fails, re-run with `--verbose` to see the actual engine stderr. Common failure modes: + +| Symptom | Fix | +|---|---| +| `iii-engine process started` then `did not become ready within 15s` | Engine crashed on startup — re-run with `--verbose`, check stderr | +| `Could not start iii-engine` | Neither `iii.exe` nor Docker is installed. See Option A or B above | +| Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port ` | +| Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) | + +> Note: there is no `cargo install iii-engine` — `iii` is not published to crates.io. The only supported install methods are the prebuilt binary above, the upstream `sh` install script (macOS/Linux only), and the Docker image. + +--- + +

Deploy

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

+ Deploy to fly.io + Deploy to Railway +

+ +Render's one-click deploy button requires `render.yaml` at the repository root, which we deliberately keep clean. Use the Render Blueprint flow documented in [`deploy/render/`](./deploy/render/README.md) to point at the in-repo blueprint manually. + +Full setup details (HMAC capture, viewer SSH tunnel, rotation, backup, +cost floors) live in [`deploy/`](./deploy/README.md): + +- [`deploy/fly`](./deploy/fly/README.md) — single machine with + `auto_stop_machines = "stop"`; cheapest idle. +- [`deploy/railway`](./deploy/railway/README.md) — Hobby plan flat fee, + volume in the dashboard. +- [`deploy/render`](./deploy/render/README.md) — Blueprint flow, + automatic disk snapshots on paid plans. +- [`deploy/coolify`](./deploy/coolify/README.md) — self-hosted on your + own VPS via [Coolify](https://coolify.io/self-hosted); same Docker + Compose stack, you own the host and the data. + +Port `3111` serves both the API and the built-in HTML viewer. — every template's README documents the +SSH-tunnel pattern for reaching it. + +--- + +

Why agentmemory

+ +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 + Session ends -> observations compressed into structured memory + +Session 2: "Now add rate limiting" + Agent already knows: + - Auth uses JWT middleware in src/middleware/auth.ts + - Tests in test/auth.test.ts cover token validation + - You chose jose over jsonwebtoken for Edge compatibility + Zero re-explaining. Starts working immediately. +``` + +### vs built-in agent memory + +Every AI coding agent ships with built-in memory — Claude Code has `MEMORY.md`, Cursor has notepads, Cline has memory bank. These work like sticky notes. agentmemory is the searchable database behind the sticky notes. + +| | Built-in (CLAUDE.md) | agentmemory | +|---|---|---| +| Scale | 200-line cap | Unlimited | +| Search | Loads everything into context | BM25 + vector + graph (top-K only) | +| Token cost | 22K+ at 240 observations | ~1,900 tokens (92% less) | +| Cross-agent | Per-agent files | MCP + REST (any agent) | +| Coordination | None | Leases, signals, actions, routines | +| Observability | Read files manually | Real-time viewer on :3111 | + +--- + +

How It Works

+ +### 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 + +Inspired by how human brains process memory — not unlike sleep consolidation. + +| Tier | What | Analogy | +|------|------|---------| +| **Working** | Raw observations from tool use | Short-term memory | +| **Episodic** | Compressed session summaries | "What happened" | +| **Semantic** | Extracted facts and patterns | "What I know" | +| **Procedural** | Workflows and decision patterns | "How to do it" | + +Memories decay over time (Ebbinghaus curve). Frequently accessed memories strengthen. Stale memories auto-evict. Contradictions are detected and resolved. + +### What Gets Captured + +| Hook | Captures | +|------|----------| +| `SessionStart` | Project path, session ID | +| `UserPromptSubmit` | User prompts (privacy-filtered) | +| `PreToolUse` | File access patterns + enriched context | +| `PostToolUse` | Tool name, input, output | +| `PostToolUseFailure` | Error context | +| `PreCompact` | Re-injects memory before compaction | +| `SubagentStart/Stop` | Sub-agent lifecycle | +| `Stop` | End-of-session summary | +| `SessionEnd` | Session complete marker | + +### Key Capabilities + +| Capability | Description | +|---|---| +| **Automatic capture** | Every tool use recorded via hooks — zero manual effort | +| **Semantic search** | BM25 + vector + knowledge graph with RRF fusion | +| **Memory evolution** | Versioning, supersession, relationship graphs | +| **Auto-forgetting** | TTL expiry, contradiction detection, importance eviction | +| **Privacy first** | API keys, secrets, `` tags stripped before storage | +| **Self-healing** | Circuit breaker, provider fallback chain, health monitoring | +| **Claude bridge** | Bi-directional sync with MEMORY.md | +| **Knowledge graph** | Entity extraction + BFS traversal | +| **Team memory** | Namespaced shared + private across team members | +| **Citation provenance** | Trace any memory back to source observations | +| **Git snapshots** | Version, rollback, and diff memory state | + +--- + + + +Triple-stream retrieval combining three signals: + +| Stream | What it does | When | +|---|---|---| +| **BM25** | Stemmed keyword matching with synonym expansion | Always on | +| **Vector** | Cosine similarity over dense embeddings | Embedding provider configured | +| **Graph** | Knowledge graph traversal via entity matching | Entities detected in query | + +Fused with Reciprocal Rank Fusion (RRF, k=60) and session-diversified (max 3 results per session). + +BM25 tokenizes Greek, Cyrillic, Hebrew, Arabic, and accented Latin out of the box. For Chinese / Japanese / Korean memories, install the optional segmenters (`npm install @node-rs/jieba tiny-segmenter`) to split CJK runs into word-level tokens; without them, agentmemory soft-falls to whole-run tokenization and prints a one-time hint on stderr. + +### Embedding providers + +agentmemory auto-detects your provider. For best results, install local embeddings (free): + +```bash +npm install @xenova/transformers +``` + +| Provider | Model | Cost | Notes | +|---|---|---|---| +| **Local (recommended)** | `all-MiniLM-L6-v2` | Free | Offline, +8pp recall over BM25-only | +| Gemini | `gemini-embedding-001` | Free tier | 100+ languages, 768/1536/3072 dims (MRL), 2048-token input. Replaces `text-embedding-004` ([deprecated, shutdown Jan 14, 2026](https://ai.google.dev/gemini-api/docs/deprecations)) | +| OpenAI | `text-embedding-3-small` | $0.02/1M | Highest quality | +| Voyage AI | `voyage-code-3` | Paid | Optimized for code | +| Cohere | `embed-english-v3.0` | Free trial | General purpose | +| OpenRouter | Any model | Varies | Multi-model proxy | + +--- + +

MCP Server

+ +53 tools, 6 resources, 3 prompts, and 15 skills, the most comprehensive MCP memory toolkit for any agent. + +> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 53-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag — setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. + +### 53 Tools + +
+Core tools (always available) + +| Tool | Description | +|------|-------------| +| `memory_recall` | Search past observations | +| `memory_compress_file` | Compress markdown files while preserving structure | +| `memory_save` | Save an insight, decision, or pattern | +| `memory_patterns` | Detect recurring patterns | +| `memory_smart_search` | Hybrid semantic + keyword search | +| `memory_file_history` | Past observations about specific files | +| `memory_sessions` | List recent sessions | +| `memory_timeline` | Chronological observations | +| `memory_profile` | Project profile (concepts, files, patterns) | +| `memory_export` | Export all memory data | +| `memory_relations` | Query relationship graph | + +
+ +
+Extended tools (53 total — set AGENTMEMORY_TOOLS=all) + +| Tool | Description | +|------|-------------| +| `memory_patterns` | Detect recurring patterns | +| `memory_timeline` | Chronological observations | +| `memory_relations` | Query relationship graph | +| `memory_graph_query` | Knowledge graph traversal | +| `memory_consolidate` | Run 4-tier consolidation | +| `memory_claude_bridge_sync` | Sync with MEMORY.md | +| `memory_team_share` | Share with team members | +| `memory_team_feed` | Recent shared items | +| `memory_audit` | Audit trail of operations | +| `memory_governance_delete` | Delete with audit trail | +| `memory_snapshot_create` | Git-versioned snapshot | +| `memory_action_create` | Create work items with dependencies | +| `memory_action_update` | Update action status | +| `memory_frontier` | Unblocked actions ranked by priority | +| `memory_next` | Single most important next action | +| `memory_lease` | Exclusive action leases (multi-agent) | +| `memory_routine_run` | Instantiate workflow routines | +| `memory_signal_send` | Inter-agent messaging | +| `memory_signal_read` | Read messages with receipts | +| `memory_checkpoint` | External condition gates | +| `memory_mesh_sync` | P2P sync between instances | +| `memory_sentinel_create` | Event-driven watchers | +| `memory_sentinel_trigger` | Fire sentinels externally | +| `memory_sketch_create` | Ephemeral action graphs | +| `memory_sketch_promote` | Promote to permanent | +| `memory_crystallize` | Compact action chains | +| `memory_diagnose` | Health checks | +| `memory_heal` | Auto-fix stuck state | +| `memory_facet_tag` | Dimension:value tags | +| `memory_facet_query` | Query by facet tags | +| `memory_verify` | Trace provenance | + +
+ +### 6 Resources · 3 Prompts · 4 Skills + +| Type | Name | Description | +|------|------|-------------| +| Resource | `agentmemory://status` | Health, session count, memory count | +| Resource | `agentmemory://project/{name}/profile` | Per-project intelligence | +| Resource | `agentmemory://memories/latest` | Latest 10 active memories | +| Resource | `agentmemory://graph/stats` | Knowledge graph statistics | +| Prompt | `recall_context` | Search + return context messages | +| Prompt | `session_handoff` | Handoff data between agents | +| Prompt | `detect_patterns` | Analyze recurring patterns | +| Skill | `/recall` | Search memory | +| Skill | `/remember` | Save to long-term memory | +| Skill | `/session-history` | Recent session summaries | +| Skill | `/forget` | Delete observations/sessions | + +### Standalone MCP + +Run without the full server — for any MCP client. Either of these works: + +```bash +npx -y @agentmemory/agentmemory mcp # canonical (always available) +npx -y @agentmemory/mcp # shim package alias +``` + +Or add to your agent's MCP config: + +Most agents (Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Gemini CLI): +```json +{ + "mcpServers": { + "agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "http://localhost:3111" + } + } + } +} +``` + +Merge the `agentmemory` entry into your host's existing `mcpServers` object rather than replacing the file. For sandboxed clients that can't reach the host's `localhost`, add `"AGENTMEMORY_FORCE_PROXY": "1"` to the env block and set `AGENTMEMORY_URL` to a route the sandbox can reach. + +OpenCode (`opencode.json`): +```json +{ + "mcp": { + "agentmemory": { + "type": "local", + "command": ["npx", "-y", "@agentmemory/mcp"], + "enabled": true + } + }, + "plugin": ["./plugins/agentmemory-capture.ts"] +} +``` + +Copy the plugin file from the repo: +```bash +mkdir -p ~/.config/opencode/plugins +cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/ +cp plugin/opencode/commands/*.md ~/.config/opencode/commands/ +``` + +--- + +

Real-Time Viewer

+ +Built-in on port `3111`. Live observation stream, session explorer, memory browser, knowledge graph visualization, and health dashboard. + +```bash +open http://localhost:3111/viewer +``` + +The viewer server binds to `127.0.0.1` by default. The REST-served `/agentmemory/viewer` endpoint follows the normal `AGENTMEMORY_SECRET` bearer-token rules. CSP headers use a per-response script nonce and disable inline handler attributes (`script-src-attr 'none'`). + +--- + +

iii Console

+ +The viewer at `:3111` shows what your agent **remembered**. The [iii console](https://iii.dev/docs/console) shows what your agent **did** — every memory op as an OpenTelemetry trace, every KV entry editable, every function invocable, every stream tappable. Two windows on the same memory: one product-shaped, one engine-shaped. + +Watch a `memory_smart_search` fire and see the BM25 scan → embedding lookup → RRF fusion → reranker as a waterfall. Edit a stuck consolidation timer in the KV browser. Replay a `PostToolUse` hook with a tweaked payload. Pin the WebSocket stream and watch observations land live. + +agentmemory ships this for free because every function call and trigger fires through iii — nothing custom, nothing to instrument. + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ Workers page: every connected worker — including agentmemory itself — with PID, function count, runtime, and last-seen. +

+ +**Already installed.** The console ships with `iii` — no separate installer. + +**Launch alongside agentmemory:** + +```bash +# agentmemory holds port 3111, so run other services on other ports. +# Engine REST (3111), WebSocket (3112), and bridge (49134) defaults match agentmemory. +iii console --port 3114 +``` + +Then open `http://localhost:3114`. Add `--enable-flow` for the experimental architecture-graph page. + +Override engine endpoints only if you've moved them: + +```bash +iii console --port 3114 \ + --engine-port 3111 \ + --ws-port 3112 \ + --bridge-port 49134 +``` + +**What you can do from the console:** + +| Page | Use it to | +|------|-----------| +| **Workers** | See every connected worker and its live metrics — including the agentmemory worker itself. | +| **Functions** | Invoke any of agentmemory's functions directly with a JSON payload — handy for testing `memory.recall`, `memory.consolidate`, `graph.query` without wiring a client. | +| **Triggers** | Replay HTTP, cron, event, and state triggers — fire the consolidation cron manually, retry an HTTP route, emit a state change. | +| **States** | KV browser with full CRUD — sessions, memory slots, lifecycle timers, embeddings index — edit values in place. | +| **Streams** | Live WebSocket monitor for memory writes, hook events, and observation updates as they flow through iii streams. | +| **Queues** | Durable queue topics + dead-letter management. Replay or drop failed embedding / compression jobs. | +| **Traces** | OpenTelemetry waterfall / flame / service-breakdown views. Filter by `trace_id` to see exactly which functions, DB calls, and embedding requests a single `memory.search` produced. | +| **Logs** | Structured OTEL logs filtered and correlated to trace/span IDs. | +| **Config** | Runtime configuration — see exactly which workers, providers, and ports your engine is running with. | +| **Flow** | (Optional, `--enable-flow`) Interactive architecture graph of every worker, trigger, and stream. | + +

+ iii console trace waterfall view showing per-span duration +
+ Traces: waterfall / flame / service breakdown for every memory operation. +

+ +**Traces are already on:** + +`iii-config.yaml` ships with the `iii-observability` worker enabled (`exporter: memory`, `sampling_ratio: 1.0`, metrics + logs). No extra config needed — the moment agentmemory starts, every memory operation emits a trace span and a structured log the console can read. + +If you want to export to Jaeger/Honeycomb/Grafana Tempo instead, change `exporter: memory` to `exporter: otlp` and set the collector endpoint per iii's observability docs. + +> **Heads-up:** no auth is enforced on the console itself — keep it bound to `127.0.0.1` (the default) and never expose it publicly. + +--- + +

Powered by iii

+ +agentmemory is **already a running [iii](https://iii.dev) instance**. Three primitives — worker, function, trigger — compose the runtime; KV state, streams, and OTEL traces come from iii-state, iii-stream, and iii-observability workers that ship with iii. You didn't install Postgres, Redis, Express, pm2, or Prometheus, because iii replaces them. + +That means one more command extends agentmemory with an entire new capability. + +### Extend agentmemory with one command + +```bash +iii worker add iii-pubsub # fan memory writes out to every connected instance +iii worker add iii-cron # scheduled consolidation, decay sweeps, snapshot rotation +iii worker add iii-queue # durable retries for embedding + compression jobs +iii worker add iii-observability # OTEL traces on every memory op (default on) +iii worker add iii-sandbox # run recalled code inside an isolated microVM +iii worker add iii-database # swap in a SQL-backed state adapter +iii worker add mcp # generic MCP host alongside the agentmemory MCP +``` + +Each `iii worker add` registers new functions and triggers into the same engine agentmemory is already running on. The viewer and console pick them up immediately — no reload, no new integration, no new container. + +| `iii worker add` | What you get on top of agentmemory | +|---|---| +| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | Multi-instance memory: every `remember` fans out, every `search` reads the union | +| [`iii-cron`](https://workers.iii.dev/workers/iii-cron) | Scheduled lifecycle — nightly consolidation, weekly snapshots, decay on a fixed clock | +| [`iii-queue`](https://workers.iii.dev/workers/iii-queue) | Durable retries: failed embedding + compression jobs survive restart, no lost observations | +| [`iii-observability`](https://workers.iii.dev/workers/iii-observability) | OTEL traces, metrics, logs on every function — wired in `iii-config.yaml` from day one | +| [`iii-sandbox`](https://workers.iii.dev/workers/iii-sandbox) | Code that came out of `memory_recall` runs inside a throwaway VM, not your shell | +| [`iii-database`](https://workers.iii.dev/workers/iii-database) | SQL-backed state adapter when you outgrow the in-memory KV defaults | +| [`mcp`](https://workers.iii.dev/workers/mcp) | Stand up extra MCP servers next to agentmemory's, share the same engine | + +Full registry: [workers.iii.dev](https://workers.iii.dev). Every worker there composes through the same primitives agentmemory uses — and the agentmemory you already have is one of them. + +### What iii replaces + +| Traditional stack | agentmemory uses | +|---|---| +| Express.js / Fastify | iii HTTP Triggers | +| SQLite / Postgres + pgvector | iii KV State + in-memory vector index | +| SSE / Socket.io | iii Streams (WebSocket) | +| pm2 / systemd | iii engine worker supervision | +| Prometheus / Grafana | iii OTEL + health monitor | +| Custom plugin systems | `iii worker add ` | + +**174 source files · ~37,800 LOC · 1,423+ tests · 258 functions · 44 KV scopes** — all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself. + +--- + +

Configuration

+ +### LLM Providers + +agentmemory auto-detects from your environment. By default, no LLM calls are made unless you configure a provider or explicitly opt in to the Claude subscription fallback. + +| Provider | Config | Notes | +|----------|--------|-------| +| **No-op (default)** | No config needed | LLM-backed compress/summarize is DISABLED. Synthetic BM25 compression + recall still work. See `AGENTMEMORY_ALLOW_AGENT_SDK` below if you used to rely on the Claude-subscription fallback. | +| Anthropic API | `ANTHROPIC_API_KEY` | Per-token billing | +| MiniMax | `MINIMAX_API_KEY` | Anthropic-compatible | +| Gemini | `GEMINI_API_KEY` | Also enables embeddings | +| OpenRouter | `OPENROUTER_API_KEY` | Any model | +| OpenAI API | `OPENAI_API_KEY` | Default `gpt-4o-mini`, override with `OPENAI_MODEL` | +| **Local (Ollama / LM Studio / vLLM / llama.cpp)** | `OPENAI_API_KEY=local` + `OPENAI_BASE_URL=http://localhost:11434/v1` (Ollama) or `http://localhost:1234/v1` (LM Studio) + `OPENAI_MODEL=` | Anything OpenAI-API-compatible. Zero cost, runs on your hardware. See [Local models](#local-models-ollama-lm-studio-vllm) below. | +| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions — used to cause unbounded Stop-hook recursion (#149 follow-up) so it is no longer the default. | + +### Local models (Ollama / LM Studio / vLLM) + +agentmemory talks to any OpenAI-API-compatible server, so anything that exposes `/v1/chat/completions` works without code changes. No paid keys, no cloud, no rate limits — runs entirely on your hardware. + +**Ollama** (default port `11434`): + +```bash +ollama pull qwen2.5-coder:7b # or llama3.2:3b, mistral:7b, etc. +ollama serve +``` + +```env +# ~/.agentmemory/.env +OPENAI_API_KEY=ollama # any non-empty string; Ollama ignores it +OPENAI_BASE_URL=http://localhost:11434/v1 +OPENAI_MODEL=qwen2.5-coder:7b +``` + +**LM Studio** (default port `1234`): + +Open LM Studio → Local Server tab → Start Server. Pick any chat model from the picker (Qwen 2.5 Coder, Llama 3.2, DeepSeek, etc.). + +```env +# ~/.agentmemory/.env +OPENAI_API_KEY=lmstudio # any non-empty string; LM Studio ignores it +OPENAI_BASE_URL=http://localhost:1234/v1 +OPENAI_MODEL=qwen2.5-coder-7b-instruct # match the model name from LM Studio +``` + +**vLLM / llama.cpp / Text Generation Inference**: same shape — point `OPENAI_BASE_URL` at whatever URL your server exposes, set `OPENAI_MODEL` to a name your server will accept. + +**Model picks for memory work**: compression and summarization are short tasks (<2K tokens in, <500 tokens out) where a 7B instruct model is plenty. Recommendations: + +| Model | Size | Why | +|-------|------|-----| +| `qwen2.5-coder:7b` | ~4.7 GB | Best at code-shaped sessions; trained on programming + tool-use traces | +| `llama3.2:3b` | ~2 GB | Smallest sane option — fine for compression, weaker for graph extraction | +| `mistral:7b-instruct` | ~4.4 GB | Good general-purpose baseline if you don't want code-specific | +| `deepseek-r1:7b` | ~4.7 GB | Reasoning-tier quality at 7B; slower but cleaner extractions | + +Reasoning-class models (`o1`-style with `` blocks) can return empty `content` with a `reasoning` field your local server may not surface. If extractions come back blank, switch to a non-reasoning model first. The `OPENAI_REASONING_EFFORT=none` env can also disable thinking on Ollama Cloud thinking models that mirror the OpenAI reasoning schema. + +Local embeddings ship out of the box via `@xenova/transformers` — `EMBEDDING_PROVIDER=local` (default) gives you BGE-small entirely on-device. No extra config needed. + +### Cost-aware model selection + +Background compression runs on every observation, so model choice meaningfully changes monthly spend. Captured workload data: 635 requests / 888K tokens / 35 hours of active use, run against three OpenRouter models at 2026-05-23 pricing. + +| Tier | Model | Input / 1M | Output / 1M | Cost for the captured 35h | Notes | +|------|-------|------------|-------------|---------------------------|-------| +| Recommended | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Solid compression + summarization quality at ~10× lower cost than Sonnet. | +| Recommended | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | Older but still fine for compression-only workloads. | +| Recommended | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Strong code reasoning if your sessions are heavily code-shaped. | +| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | High quality but expensive for always-on background work. | +| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Similar tier to Sonnet. | +| Avoid | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Reasoning-class model; massive overspend for compression. | + +agentmemory prints a runtime warning when `OPENROUTER_MODEL` matches a premium-tier pattern. Set `AGENTMEMORY_SUPPRESS_COST_WARNING=1` to silence once you've made an informed choice. + +Quality vs cost tradeoff for memory work: compression is a summarization task with relatively loose quality bars (the agent re-reads the summary, not the user). DeepSeek-V4-Pro / Qwen3-Coder land within rounding error of Sonnet on this task while costing ~10× less. Save the premium-tier models for queries you read directly. + +Sources: [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/). + +### Multi-agent memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`) + +In multi-agent setups where several roles share one agentmemory server (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` tags every write with the role that made it. `AGENTMEMORY_AGENT_SCOPE` controls whether recall filters by that tag. + +```env +TEAM_ID=company +USER_ID=engineering-team +AGENT_ID=architect +AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared" +``` + +Two modes: + +| Mode | Tag writes | Filter recall | When to use | +|------|------------|---------------|-------------| +| `shared` (default) | yes | no | Cross-agent context with audit trail. Architect can see what developer noted, but every row records who said it. | +| `isolated` | yes | yes | Strict separation. Architect never sees developer's observations / memories / sessions. | + +What gets tagged when `AGENT_ID` is set: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. The role flows from `api::session::start` → `mem::observe` → `mem::compress` → KV. + +What gets filtered in isolated mode: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Each endpoint accepts `?agentId=` to override per-request, and `?agentId=*` to opt out of the env scope entirely. `/memories` also accepts `?includeOrphans=true` to surface pre-AGENT_ID memories whose `agentId` is undefined. + +Per-call override at the SDK / REST layer: every mutating endpoint (`/session/start`, `/remember`) accepts an `agentId` field in the request body that wins over the env. Useful for runtimes routing many roles through one server process. + +When `AGENT_ID` is unset, memory remains unscoped (legacy behavior, no tags, no filters). + +### Ports + +agentmemory + iii-engine bind four ports by default. If a restart fails with `port in use`, this table tells you which process to look for. + +| Port | Process | Purpose | Env override | +|------|---------|---------|--------------| +| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` | +| `3112` | iii-engine | Internal streams worker (consumed by agentmemory + viewer) | `III_STREAMS_PORT` | +| `3113` | agentmemory | Real-time viewer (`http://localhost:3111/viewer`) | `AGENTMEMORY_VIEWER_PORT` | +| `49134` | iii-engine | WebSocket — workers register here, OTel telemetry flows over it | `III_ENGINE_URL` (full URL, default `ws://localhost:49134`) | + +Stale-process cleanup when ports stay bound after a crashed run: + +```bash +# macOS / Linux — find whatever is on each port and kill it +lsof -i :3111 +pkill -f agentmemory || true +pkill -f 'iii ' || true + +# Windows +netstat -ano | findstr ":3111" +taskkill /F /PID +``` + +`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful shutdown (#640, #474). The manual cleanup above is only for the post-crash case where neither pidfile is left behind. + +### Config File + +Put agentmemory runtime configuration in `~/.agentmemory/.env` instead of exporting variables in every shell. If the viewer shows a setup hint like `export ANTHROPIC_API_KEY=...`, copy it into this file as `ANTHROPIC_API_KEY=...` without the `export` prefix, then restart agentmemory. + +Process environment variables still work and take precedence over values in the file. + +On Windows, the same file lives at `%USERPROFILE%\.agentmemory\.env`: + +```powershell +New-Item -ItemType Directory -Force $HOME\.agentmemory +notepad $HOME\.agentmemory\.env +``` + +To test with a Claude Code Pro/Max subscription instead of an API key, opt in explicitly: + +```env +AGENTMEMORY_ALLOW_AGENT_SDK=true +AGENTMEMORY_AUTO_COMPRESS=true +``` + +Consolidation (graph nodes, lessons, crystals) is on by default whenever an LLM provider is configured. Explicitly opt out with `CONSOLIDATION_ENABLED=false` if you want LLM-free operation. Graph extraction is a separate flag: + +```env +GRAPH_EXTRACTION_ENABLED=true +# CONSOLIDATION_ENABLED=false # opt out of auto-consolidation +``` + +### Environment Variables + +Create `~/.agentmemory/.env`: + +```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 (default: 3111 API/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=false # on by default when an LLM provider is configured +# 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, lean fallback) or "all" (53 tools) +# AGENTMEMORY_TOOLS=core +``` + +--- + +

API

+ +128 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer ` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers. + +
+Key endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `GET` | `/agentmemory/health` | Health check (always public) | +| `POST` | `/agentmemory/session/start` | Start session + get context | +| `POST` | `/agentmemory/session/end` | End session | +| `POST` | `/agentmemory/observe` | Capture observation | +| `POST` | `/agentmemory/smart-search` | Hybrid search | +| `POST` | `/agentmemory/context` | Generate context | +| `POST` | `/agentmemory/remember` | Save to long-term memory | +| `POST` | `/agentmemory/forget` | Delete observations | +| `POST` | `/agentmemory/enrich` | File context + memories + bugs | +| `GET` | `/agentmemory/profile` | Project profile | +| `GET` | `/agentmemory/export` | Export all data | +| `POST` | `/agentmemory/import` | Import from JSON | +| `POST` | `/agentmemory/graph/query` | Knowledge graph query | +| `POST` | `/agentmemory/team/share` | Share with team | +| `GET` | `/agentmemory/audit` | Audit trail | + +Full endpoint list: [`src/triggers/api.ts`](src/triggers/api.ts) + +
+ +--- + +

Development

+ +```bash +npm run dev # Hot reload +npm run build # Production build +npm test # 1,423+ tests +npm run test:integration # API tests (requires running services) +``` + +**Prerequisites:** Node.js >= 20, [iii-engine](https://iii.dev/docs) or Docker + +

License

+ +[Apache-2.0](LICENSE) diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md new file mode 100644 index 0000000000000000000000000000000000000000..1dc2b525c98f438d34034a05e07999a8851fd6c8 --- /dev/null +++ b/READMEs/README.de-DE.md @@ -0,0 +1,1377 @@ +

+ agentmemory — Persistentes Gedächtnis für KI-Coding-Agenten +

+ +

+ + 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. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design-Dokument: 1200 stars / 172 forks im Gist +

+ +

+ Das Gist erweitert Karpathys LLM-Wiki-Muster um Confidence Scoring, Lifecycle, Knowledge Graphs und hybride Suche: agentmemory ist die Implementierung. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory-Demo +

+ +

+ Installation • + Schnellstart • + Benchmarks • + Vergleich • + Agenten • + Funktionsweise • + MCP • + Viewer • + iii Console • + Powered by iii • + Konfiguration • + API +

+ +--- + +## 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). Agenten­spezifische Verdrahtung unter [Funktioniert mit jedem Agenten](#works-with-every-agent). + +--- + +

Funktioniert mit jedem Agenten

+ +agentmemory funktioniert mit jedem Agenten, der Hooks, MCP oder REST API unterstützt. Alle Agenten teilen sich denselben Memory-Server. + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+natives Plugin + 12 Hooks + MCP +
+Codex CLI
+Codex CLI
+natives Plugin + 6 Hooks + MCP +
+OpenClaw
+OpenClaw
+natives Plugin + MCP +
+Hermes
+Hermes
+natives Plugin + MCP +
+pi
+pi
+natives Plugin + MCP +
+OpenHuman
+OpenHuman
+natives Memory-trait-Backend +
+Cursor
+Cursor
+MCP-Server +
+Gemini CLI
+Gemini CLI
+MCP-Server +
+OpenCode
+OpenCode
+22 Hooks + MCP + Plugin +
+Cline
+Cline
+MCP-Server +
+Goose
+Goose
+MCP-Server +
+Kilo Code
+Kilo Code
+MCP-Server +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP-Server +
+Windsurf
+Windsurf
+MCP-Server +
+Roo Code
+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). + +--- + +

Benchmarks

+ + + + + + +
+ +### Retrieval-Genauigkeit + +**coding-agent-life-v1** (interner Korpus, Sandbox-reproduzierbar) + +| Adapter | P@5 | R@5 | Top-5-Trefferquote | p50-Latenz | +|---|---|---|---|---| +| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep-Baseline | 0.267 | 0.967 | 15 / 15 | 0 ms | + +100 % Top-5-Trefferquote. **2,2×** bessere Präzision als die grep-Baseline bei identischer Eingabe. Volle Aufschlüsselung pro Typ: [`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 Fragen) + +| System | R@5 | R@10 | MRR | +|---|---|---|---| +| **agentmemory** | **95.2%** | **98.6%** | **88.2%** | +| BM25-only Fallback | 86.2% | 94.6% | 71.5% | + + + +### Token-Einsparungen + +| Ansatz | Tokens/Jahr | Kosten/Jahr | +|---|---|---| +| Vollständigen Kontext einfügen | 19,5M+ | Unmöglich (überschreitet das Fenster) | +| LLM-zusammengefasst | ~650K | ~500 $ | +| **agentmemory** | **~170K** | **~10 $** | +| agentmemory + lokale Embeddings | ~170K | **0 $** | + +
+ +> 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). + +--- + +

Vergleich mit der Konkurrenz

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Eingebaut (CLAUDE.md)
TypMemory-Engine + MCP-ServerMemory-Layer-APIKomplette Agenten-RuntimeStatische Datei
Retrieval R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/V (grep)
Auto-Erfassung12 Hooks (null manueller Aufwand)Manuelle add()-AufrufeAgent bearbeitet sich selbstManuelle Bearbeitung
SucheBM25 + Vector + Graph (RRF-Fusion)Vector + GraphVector (Archival)Lädt alles in den Kontext
Multi-AgentMCP + REST + Leases + SignalsAPI (keine Koordination)Nur innerhalb der Letta-RuntimeDateien pro Agent
Framework-Lock-inKeiner (jeder MCP-Client)KeinerHoch (Letta erforderlich)Format pro Agent
Externe AbhängigkeitenKeine (SQLite + iii-engine)Qdrant / pgvectorPostgres + Vector-DBKeine
Memory-Lifecycle4-stufige Konsolidierung + Decay + Auto-ForgetPassive ExtraktionVom Agenten verwaltetManuelles Pruning
Token-Effizienz~1.900 Tokens/Session (10 $/Jahr)Je nach Integration unterschiedlichCore Memory im Kontext22K+ Tokens bei 240 Beobachtungen
Echtzeit-ViewerJa (Port 3113)Cloud-DashboardCloud-DashboardNein
Self-hostedJa (Standard)OptionalOptionalJa
+ +--- + +

Schnellstart

+ +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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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. + +--- + +

Warum agentmemory

+ +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 | + +--- + +

Funktionsweise

+ +### 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-stufige Memory-Konsolidierung + +Inspiriert davon, wie menschliche Gehirne Erinnerungen verarbeiten — nicht unähnlich der Schlafkonsolidierung. + +| Stufe | Was | Analogie | +|------|------|---------| +| **Working** | Rohbeobachtungen aus Tool-Nutzung | Kurzzeitgedächtnis | +| **Episodic** | Komprimierte Session-Zusammenfassungen | „Was passiert ist" | +| **Semantic** | Extrahierte Fakten und Muster | „Was ich weiß" | +| **Procedural** | Workflows und Entscheidungsmuster | „Wie es geht" | + +Erinnerungen klingen mit der Zeit ab (Ebbinghaus-Kurve). Häufig abgerufene Erinnerungen werden verstärkt. Veraltete Erinnerungen werden automatisch evakuiert. Widersprüche werden erkannt und aufgelöst. + +### Was erfasst wird + +| Hook | Erfasst | +|------|----------| +| `SessionStart` | Projektpfad, Session-ID | +| `UserPromptSubmit` | Benutzer-Prompts (Privacy-gefiltert) | +| `PreToolUse` | Datei-Zugriffsmuster + angereicherter Kontext | +| `PostToolUse` | Tool-Name, Eingabe, Ausgabe | +| `PostToolUseFailure` | Fehlerkontext | +| `PreCompact` | Re-injiziert Memory vor der Kompaktierung | +| `SubagentStart/Stop` | Sub-Agent-Lifecycle | +| `Stop` | Zusammenfassung am Session-Ende | +| `SessionEnd` | Session-Abschluss-Marker | + +### Kernfähigkeiten + +| Fähigkeit | Beschreibung | +|---|---| +| **Automatische Erfassung** | Jede Tool-Nutzung via Hooks aufgezeichnet — null manueller Aufwand | +| **Semantische Suche** | BM25 + Vector + Knowledge Graph mit RRF-Fusion | +| **Memory-Evolution** | Versionierung, Supersession, Beziehungsgraphen | +| **Auto-Vergessen** | TTL-Ablauf, Widerspruchserkennung, Wichtigkeits-Eviction | +| **Privacy first** | API-Keys, Secrets, ``-Tags vor Speicherung entfernt | +| **Selbstheilung** | Circuit Breaker, Provider-Fallback-Kette, Health-Monitoring | +| **Claude-Bridge** | Bidirektionale Synchronisierung mit MEMORY.md | +| **Knowledge Graph** | Entitäten-Extraktion + BFS-Traversal | +| **Team-Memory** | Namensraum-getrennt geteilt + privat über Teammitglieder hinweg | +| **Zitations-Provenienz** | Jedes Memory bis zu Ursprungsbeobachtungen zurückverfolgen | +| **Git-Snapshots** | Memory-Stand versionieren, zurückrollen und diffen | + +--- + + + +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 | + +--- + +

MCP-Server

+ +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/ +``` + +--- + +

Echtzeit-Viewer

+ +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'`). + +--- + +

iii Console

+ +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. + +

+ iii console Workers-Seite — verbundene Worker, einschließlich agentmemory-Instanzen mit Live-Funktionszahlen und Runtime-Metadaten +
+ 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. | + +

+ iii console Trace-Wasserfall-Ansicht mit Span-Dauer +
+ Traces: Wasserfall / Flame / Service-Breakdown für jede Memory-Operation. +

+ +**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. + +--- + +

Powered by iii

+ +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. + +--- + +

Konfiguration

+ +### 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 +``` + +--- + +

API

+ +124 Endpunkte auf Port `3111`. Die REST API bindet sich standardmäßig an `127.0.0.1`. Geschützte Endpunkte verlangen `Authorization: Bearer `, wenn `AGENTMEMORY_SECRET` gesetzt ist, und Mesh-Sync-Endpunkte erfordern `AGENTMEMORY_SECRET` auf beiden Peers. + +
+Wichtige Endpunkte + +| Methode | Pfad | Beschreibung | +|--------|------|-------------| +| `GET` | `/agentmemory/health` | Health-Check (immer öffentlich) | +| `POST` | `/agentmemory/session/start` | Session starten + Kontext holen | +| `POST` | `/agentmemory/session/end` | Session beenden | +| `POST` | `/agentmemory/observe` | Beobachtung erfassen | +| `POST` | `/agentmemory/smart-search` | Hybride Suche | +| `POST` | `/agentmemory/context` | Kontext erzeugen | +| `POST` | `/agentmemory/remember` | In Langzeit-Memory speichern | +| `POST` | `/agentmemory/forget` | Beobachtungen löschen | +| `POST` | `/agentmemory/enrich` | Dateikontext + Erinnerungen + Bugs | +| `GET` | `/agentmemory/profile` | Projektprofil | +| `GET` | `/agentmemory/export` | Alle Daten exportieren | +| `POST` | `/agentmemory/import` | Aus JSON importieren | +| `POST` | `/agentmemory/graph/query` | Knowledge-Graph-Anfrage | +| `POST` | `/agentmemory/team/share` | Mit Team teilen | +| `GET` | `/agentmemory/audit` | Audit-Trail | + +Volle Endpunktliste: [`src/triggers/api.ts`](../src/triggers/api.ts) + +
+ +--- + +

Entwicklung

+ +```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 + +

Lizenz

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md new file mode 100644 index 0000000000000000000000000000000000000000..ff780cbe14d8ff9f9b6ba539c74b2d4fff26e6f7 --- /dev/null +++ b/READMEs/README.es-ES.md @@ -0,0 +1,1370 @@ +

+ agentmemory — Memoria persistente para agentes de codificación con IA +

+ +

+ + 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. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Documento de diseño: 1200 stars / 172 forks en el gist +

+ +

+ 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. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ Demostración de agentmemory +

+ +

+ Instalación • + Inicio rápido • + Benchmarks • + Comparativa • + Agentes • + Cómo funciona • + MCP • + Visor • + iii Console • + Powered by iii • + Configuración • + API +

+ +--- + +## 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). + +--- + +

Funciona con cualquier agente

+ +agentmemory funciona con cualquier agente que soporte hooks, MCP o REST API. Todos los agentes comparten el mismo servidor de memoria. + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+native plugin + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+native plugin + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+native plugin + MCP +
+Hermes
+Hermes
+native plugin + MCP +
+pi
+pi
+native plugin + MCP +
+OpenHuman
+OpenHuman
+native Memory trait backend +
+Cursor
+Cursor
+MCP server +
+Gemini CLI
+Gemini CLI
+MCP server +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+MCP server +
+Goose
+Goose
+MCP server +
+Kilo Code
+Kilo Code
+MCP server +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP server +
+Windsurf
+Windsurf
+MCP server +
+Roo Code
+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). + +--- + +

Benchmarks

+ + + + + + +
+ +### 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% | + + + +### Ahorro de tokens + +| Enfoque | Tokens/año | Coste/año | +|---|---|---| +| Pegar todo el contexto | 19.5M+ | Imposible (excede la ventana) | +| Resumido por LLM | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + embeddings locales | ~170K | **$0** | + +
+ +> 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). + +--- + +

Comparativa

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Built-in (CLAUDE.md)
TipoMotor de memoria + servidor MCPAPI de capa de memoriaRuntime de agente completoFichero estático
Retrieval R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
Captura automática12 hooks (esfuerzo manual cero)Llamadas manuales a add()El agente se edita a sí mismoEdición manual
BúsquedaBM25 + Vector + Graph (fusión RRF)Vector + GraphVector (archival)Carga todo en contexto
MultiagenteMCP + REST + leases + signalsAPI (sin coordinación)Solo dentro del runtime de LettaFicheros por agente
Dependencia de frameworkNinguna (cualquier cliente MCP)NingunaAlta (obliga a usar Letta)Formato por agente
Dependencias externasNinguna (SQLite + iii-engine)Qdrant / pgvectorPostgres + BD vectorialNinguna
Ciclo de vida de memoriaConsolidación de 4 niveles + decaimiento + auto-olvidoExtracción pasivaGestionado por el agentePoda manual
Eficiencia de tokens~1.900 tokens/sesión ($10/año)Varía según la integraciónMemoria principal en contexto22K+ tokens con 240 obs
Visor en tiempo realSí (port 3113)Dashboard en la nubeDashboard en la nubeNo
Self-hostedSí (por defecto)OpcionalOpcionalSí
+ +--- + +

Inicio rápido

+ +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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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. + +--- + +

Por qué agentmemory

+ +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 | + +--- + +

Cómo funciona

+ +### 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 | + +--- + +

Servidor MCP

+ +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/ +``` + +--- + +

Visor en tiempo real

+ +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'`). + +--- + +

iii Console

+ +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 de iii console — workers conectados incluyendo instancias de agentmemory con conteo de funciones en vivo y metadatos de runtime +
+ 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. | + +

+ Vista de waterfall de trazas de iii console mostrando duración por span +
+ 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. + +--- + +

Powered by iii

+ +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. + +--- + +

Configuración

+ +### 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 +``` + +--- + +

API

+ +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) + +
+ +--- + +

Desarrollo

+ +```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 + +

Licencia

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md new file mode 100644 index 0000000000000000000000000000000000000000..c2b464ecc2ef39a1ea8f06ab275073584bc5a9e1 --- /dev/null +++ b/READMEs/README.fr-FR.md @@ -0,0 +1,1377 @@ +

+ agentmemory — Mémoire persistante pour les agents de codage IA +

+ +

+ + 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. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Document de conception : 1200 stars / 172 forks sur le gist +

+ +

+ 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. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ Démo agentmemory +

+ +

+ Installation • + Démarrage rapide • + Benchmarks • + vs Concurrents • + Agents • + Fonctionnement • + MCP • + Visualiseur • + iii Console • + Powered by iii • + Configuration • + API +

+ +--- + +## 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). + +--- + +

Compatible avec tous les agents

+ +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
+Claude Code
+plugin natif + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+plugin natif + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+plugin natif + MCP +
+Hermes
+Hermes
+plugin natif + MCP +
+pi
+pi
+plugin natif + MCP +
+OpenHuman
+OpenHuman
+backend natif trait Memory +
+Cursor
+Cursor
+serveur MCP +
+Gemini CLI
+Gemini CLI
+serveur MCP +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+serveur MCP +
+Goose
+Goose
+serveur MCP +
+Kilo Code
+Kilo Code
+serveur MCP +
+Aider
+Aider
+API REST +
+Claude Desktop
+Claude Desktop
+serveur MCP +
+Windsurf
+Windsurf
+serveur MCP +
+Roo Code
+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). + +--- + +

Benchmarks

+ + + + + + +
+ +### 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% | + + + +### Économies de tokens + +| Approche | Tokens/an | Coût/an | +|---|---|---| +| Coller le contexte complet | 19,5M+ | Impossible (dépasse la fenêtre) | +| Résumé par LLM | ~650K | ~500 $ | +| **agentmemory** | **~170K** | **~10 $** | +| agentmemory + embeddings locaux | ~170K | **0 $** | + +
+ +> 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). + +--- + +

vs Concurrents

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Intégré (CLAUDE.md)
TypeMoteur de mémoire + serveur MCPAPI de couche mémoireRuntime d'agent completFichier statique
R@5 de récupération95.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
Capture automatique12 hooks (zéro effort manuel)Appels add() manuelsL'agent s'édite lui-mêmeÉdition manuelle
RechercheBM25 + Vectoriel + Graphe (fusion RRF)Vectoriel + GrapheVectoriel (archival)Charge tout en contexte
Multi-agentsMCP + REST + leases + signauxAPI (sans coordination)Uniquement dans le runtime LettaFichiers par agent
Verrouillage frameworkAucun (tout client MCP)AucunÉlevé (Letta obligatoire)Format par agent
Dépendances externesAucune (SQLite + iii-engine)Qdrant / pgvectorPostgres + base vectorielleAucune
Cycle de vie mémoireConsolidation à 4 niveaux + décroissance + oubli automatiqueExtraction passiveGérée par l'agentÉlagage manuel
Efficacité en tokens~1 900 tokens/session (10 $/an)Variable selon l'intégrationMémoire centrale dans le contexte22K+ tokens à 240 observations
Visualiseur temps réelOui (port 3113)Tableau de bord cloudTableau de bord cloudNon
Auto-hébergéOui (par défaut)OptionnelOptionnelOui
+ +--- + +

Démarrage rapide

+ +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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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. + +--- + +

Pourquoi agentmemory

+ +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 | + +--- + +

Fonctionnement

+ +### 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 | + +--- + +

Serveur MCP

+ +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/ +``` + +--- + +

Visualiseur temps réel

+ +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'`). + +--- + +

iii Console

+ +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. + +

+ iii console — page Workers montrant les workers connectés, dont les instances agentmemory avec compteurs de fonctions en direct et métadonnées de runtime +
+ 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. | + +

+ vue waterfall de traces dans iii console montrant la durée par span +
+ 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. + +--- + +

Powered by iii

+ +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. + +--- + +

Configuration

+ +### 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 +``` + +--- + +

API

+ +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) + +
+ +--- + +

Développement

+ +```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 + +

Licence

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md new file mode 100644 index 0000000000000000000000000000000000000000..412e6f844725e8e28aa25020b6b65851e6d3a0d1 --- /dev/null +++ b/READMEs/README.hi-IN.md @@ -0,0 +1,1380 @@ +

+ agentmemory — AI कोडिंग एजेंट्स के लिए स्थायी मेमोरी +

+ +

+ + आपका कोडिंग एजेंट सब कुछ याद रखता है। बार-बार समझाने की ज़रूरत नहीं। + Built on iii engine +
+ Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode, और किसी भी MCP क्लाइंट के लिए स्थायी मेमोरी। +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1200 stars / 172 forks on the gist +

+ +

+ यह gist Karpathy के LLM Wiki पैटर्न को confidence scoring, lifecycle, knowledge graphs और hybrid search के साथ बढ़ाता है: agentmemory इसका implementation है। +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory demo +

+ +

+ इंस्टॉल • + क्विक स्टार्ट • + बेंचमार्क्स • + प्रतिस्पर्धियों से तुलना • + एजेंट्स • + यह कैसे काम करता है • + MCP • + व्यूअर • + iii कंसोल • + iii द्वारा संचालित • + कॉन्फ़िग • + API +

+ +--- + +## इंस्टॉल + +```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) में। + +--- + +

Works with every agent

+ +agentmemory किसी भी ऐसे एजेंट के साथ काम करता है जो hooks, MCP, या REST API सपोर्ट करता है। सभी एजेंट एक ही मेमोरी सर्वर साझा करते हैं। + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+native plugin + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+native plugin + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+native plugin + MCP +
+Hermes
+Hermes
+native plugin + MCP +
+pi
+pi
+native plugin + MCP +
+OpenHuman
+OpenHuman
+native Memory trait बैकएंड +
+Cursor
+Cursor
+MCP सर्वर +
+Gemini CLI
+Gemini CLI
+MCP सर्वर +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+MCP सर्वर +
+Goose
+Goose
+MCP सर्वर +
+Kilo Code
+Kilo Code
+MCP सर्वर +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP सर्वर +
+Windsurf
+Windsurf
+MCP सर्वर +
+Roo Code
+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) में। + +--- + +

Benchmarks

+ + + + + + +
+ +### Retrieval सटीकता + +**coding-agent-life-v1** (in-house corpus, sandbox-reproducible) + +| Adapter | P@5 | R@5 | Top-5 hit rate | p50 latency | +|---|---|---|---|---| +| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep baseline | 0.267 | 0.967 | 15 / 15 | 0 ms | + +100% top-5 hit rate। समान input पर grep baseline से **2.2×** बेहतर precision। पूरी प्रकार-वार breakdown: [`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 प्रश्न) + +| System | R@5 | R@10 | MRR | +|---|---|---|---| +| **agentmemory** | **95.2%** | **98.6%** | **88.2%** | +| BM25-only fallback | 86.2% | 94.6% | 71.5% | + + + +### Token बचत + +| दृष्टिकोण | Tokens/yr | Cost/yr | +|---|---|---| +| पूरा context paste करें | 19.5M+ | असंभव (window से अधिक) | +| LLM-summarized | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + local embeddings | ~170K | **$0** | + +
+ +> 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)। + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)बिल्ट-इन (CLAUDE.md)
प्रकारMemory engine + MCP सर्वरMemory layer APIपूर्ण agent runtimeStatic फाइल
Retrieval R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
स्वचालित कैप्चर12 hooks (शून्य मैनुअल प्रयास)मैनुअल add() कॉलएजेंट self-editsमैनुअल editing
खोजBM25 + Vector + Graph (RRF fusion)Vector + GraphVector (archival)सब कुछ context में लोड करता है
Multi-agentMCP + REST + leases + signalsAPI (कोई coordination नहीं)केवल Letta runtime मेंप्रति-एजेंट फाइलें
Framework lock-inकोई नहीं (कोई भी MCP क्लाइंट)कोई नहींउच्च (Letta का उपयोग आवश्यक)प्रति-एजेंट format
बाहरी निर्भरताएँकोई नहीं (SQLite + iii-engine)Qdrant / pgvectorPostgres + vector DBकोई नहीं
Memory lifecycle4-tier consolidation + decay + auto-forgetPassive extractionAgent-managedमैनुअल pruning
Token दक्षता~1,900 tokens/session ($10/yr)integration पर निर्भरCore memory context में240 observations पर 22K+ tokens
Real-time व्यूअरहाँ (port 3113)Cloud dashboardCloud dashboardनहीं
Self-hostedहाँ (default)OptionalOptionalहाँ
+ +--- + +

Quick Start

+ +संगतता: यह रिलीज़ 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 करती है। + +

+ Deploy to fly.io + Deploy to Railway +

+ +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 करता है। + +--- + +

Why agentmemory

+ +हर 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 | + +--- + +

How It Works

+ +### 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 | + +--- + +

MCP Server

+ +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/ +``` + +--- + +

Real-Time Viewer

+ +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'`)। + +--- + +

iii Console

+ +`: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 करने के लिए कुछ नहीं। + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ 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। | + +

+ iii console trace waterfall view showing per-span duration +
+ 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 न करें। + +--- + +

Powered by iii

+ +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 स्वयं है। + +--- + +

Configuration

+ +### 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 +``` + +--- + +

API

+ +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) + +
+ +--- + +

Development

+ +```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 + +

License

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md new file mode 100644 index 0000000000000000000000000000000000000000..a117b2257e285a81b2f4ee7557e992fb410d225d --- /dev/null +++ b/READMEs/README.ja-JP.md @@ -0,0 +1,1380 @@ +

+ agentmemory — AI コーディングエージェントのための永続メモリ +

+ +

+ + コーディングエージェントがすべてを記憶します。もう説明し直す必要はありません。 + Built on iii engine +
+ Claude Code、Cursor、Gemini CLI、Codex CLI、Hermes、OpenClaw、pi、OpenCode、そしてあらゆる MCP クライアントのための永続メモリ。 +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1200 stars / 172 forks on the gist +

+ +

+ この gist は Karpathy の LLM Wiki パターンを信頼度スコア、ライフサイクル管理、ナレッジグラフ、ハイブリッド検索で拡張します。agentmemory はその実装です。 +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory demo +

+ +

+ インストール • + クイックスタート • + ベンチマーク • + 競合比較 • + エージェント • + 仕組み • + MCP • + ビューワー • + iii コンソール • + Powered by iii • + 設定 • + API +

+ +--- + +## インストール + +```bash +npm install -g @agentmemory/agentmemory # 一度のインストール — PATH 上に `agentmemory` が使えるようになる +# macOS/Linux のシステム Node で EACCES が出る場合は次を試してください: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # :3111 でメモリサーバーを起動 +agentmemory demo # サンプルセッションを投入してリコールを実証 +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)を参照。 + +--- + +

Works with every agent

+ +agentmemory は hooks、MCP、REST API をサポートするあらゆるエージェントで動作します。すべてのエージェントが同じメモリサーバーを共有します。 + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+ネイティブプラグイン + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+ネイティブプラグイン + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+ネイティブプラグイン + MCP +
+Hermes
+Hermes
+ネイティブプラグイン + MCP +
+pi
+pi
+ネイティブプラグイン + MCP +
+OpenHuman
+OpenHuman
+ネイティブ Memory trait バックエンド +
+Cursor
+Cursor
+MCP サーバー +
+Gemini CLI
+Gemini CLI
+MCP サーバー +
+OpenCode
+OpenCode
+22 hooks + MCP + プラグイン +
+Cline
+Cline
+MCP サーバー +
+Goose
+Goose
+MCP サーバー +
+Kilo Code
+Kilo Code
+MCP サーバー +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP サーバー +
+Windsurf
+Windsurf
+MCP サーバー +
+Roo Code
+Roo Code
+MCP サーバー +
+ +

+ MCP または HTTP を話すあらゆるエージェントで動作。サーバー 1 つで、すべてのエージェントがメモリを共有。 +

+ +--- + +あなたは毎セッション、同じアーキテクチャを説明し直している。同じバグを何度も発見する。同じ好みを繰り返し教える。組み込みのメモリ(CLAUDE.md、.cursorrules)は 200 行で打ち止め、しかも古びていく。agentmemory がこれを解決します。バックグラウンドで静かにエージェントの動きを捕捉し、検索可能なメモリに圧縮し、次のセッションが始まるときに適切なコンテキストを注入します。コマンド 1 つ。エージェント間で動作します。 + +**何が変わるか:** セッション 1 で JWT 認証をセットアップ。セッション 2 でレート制限を依頼する。エージェントは既に、あなたの認証が `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 プロセスで `memory_critical` を誤検知しなくなりました。詳細は [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18) を参照。 + +--- + +

Benchmarks

+ + + + + + +
+ +### 検索精度 + +**coding-agent-life-v1**(社内コーパス、サンドボックスで再現可能) + +| アダプタ | P@5 | R@5 | Top-5 ヒット率 | p50 レイテンシ | +|---|---|---|---|---| +| **agentmemory ハイブリッド** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep ベースライン | 0.267 | 0.967 | 15 / 15 | 0 ms | + +100% Top-5 ヒット率。同じ入力で grep ベースラインより **2.2×** 高い精度。タイプ別の詳細は [`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%** | +| BM25 のみのフォールバック | 86.2% | 94.6% | 71.5% | + + + +### トークン削減 + +| 方式 | トークン/年 | コスト/年 | +|---|---|---| +| フルコンテキスト貼付 | 19.5M+ | 不可能(コンテキストウィンドウ超過) | +| 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 vs mem0、Letta、Khoj、claude-mem、Hippo。 + +**ローカルで再現:** [`eval/README.md`](../eval/README.md) — LongMemEval `_s`(公開 500 問)+ `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) と組み合わせて使えます。** コードグラフのインデックス、マルチエージェントビルドパイプライン、ドキュメント / PDF / 画像 / 動画にまたがる広範なナレッジグラフ。agentmemory が作業を覚え、これら 3 つのプロジェクトがコンテキストレイヤーの残りを照らします。レシピと質問ルーティング表:[`docs/recipes/pairings.md`](../docs/recipes/pairings.md)。 + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)組み込み (CLAUDE.md)
種別メモリエンジン + MCP サーバーメモリレイヤー APIフルエージェントランタイム静的ファイル
検索 R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
自動キャプチャ12 hooks(手動作業ゼロ)手動の add() 呼び出しエージェントが自分で編集手動編集
検索BM25 + ベクトル + グラフ(RRF 融合)ベクトル + グラフベクトル(アーカイブ)すべてをコンテキストにロード
マルチエージェントMCP + REST + リース + シグナルAPI(調整なし)Letta ランタイム内のみエージェントごとにファイル
フレームワークロックインなし(任意の MCP クライアント)なし高(Letta 必須)エージェントごとのフォーマット
外部依存なし(SQLite + iii-engine)Qdrant / pgvectorPostgres + ベクトル DBなし
メモリライフサイクル4 層統合 + 減衰 + 自動忘却受動的抽出エージェント管理手動プルーニング
トークン効率~1,900 tokens/セッション ($10/年)統合方法によるコアメモリがコンテキスト内240 観測で 22K+ tokens
リアルタイムビューワーあり(ポート 3113)クラウドダッシュボードクラウドダッシュボードなし
セルフホストあり(デフォルト)オプションオプションあり
+ +--- + +

Quick Start

+ +互換性:このリリースは安定版の `iii-sdk` `^0.11.0` と iii-engine v0.11.x を対象とします。 + +### 30 秒で試す + +```bash +# ターミナル 1: サーバーを起動 +npx @agentmemory/agentmemory + +# ターミナル 2: サンプルデータを投入してリコールを確認 +npx @agentmemory/agentmemory demo +``` + +`demo` は 3 つの現実的なセッション(JWT 認証、N+1 クエリ修正、レート制限)を投入し、セマンティック検索を実行します。「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 +# macOS/Linux のシステム Node で EACCES が出る場合は次を試してください: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # サーバー起動(npx 形式と同じ) +agentmemory stop # 停止 +agentmemory remove # 作成したものをすべてアンインストール +agentmemory connect claude-code # エージェントを 1 つ接続 +agentmemory doctor # 対話型診断 + 修正プロンプト +``` + +v0.9.16 以降、初回 npx 実行時にインラインでグローバルインストールを促されます — 一度 `Y` と答えれば完了です。スキップした場合、以下のいずれかで最新を取得できます: + +```bash +npx -y @agentmemory/agentmemory@latest # npm から最新を強制(クロスプラットフォーム) +rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # macOS/Linux のみ (POSIX shell) +``` + +Windows / PowerShell では、同等のキャッシュクリアは `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` です — 上記の `npx -y ...@latest` 形式がクロスプラットフォームの選択肢になります。 + +### セッションリプレイ + +agentmemory が記録するすべてのセッションは再生可能です。ビューワーを開き、**Replay** タブを選択し、タイムラインをスクラブしてください: プロンプト、ツール呼び出し、ツール結果、応答が個別のイベントとして表示され、再生/一時停止、速度コントロール(0.5×–4×)、キーボードショートカット(スペースで切り替え、矢印でステップ)が使えます。 + +古い Claude Code の JSONL トランスクリプトを取り込みたい? + +```bash +# デフォルトの ~/.claude/projects 配下を一括インポート +npx @agentmemory/agentmemory import-jsonl + +# あるいは単一ファイルをインポート +npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl +``` + +インポートしたセッションはネイティブのセッションと並んで Replay ピッカーに表示されます。内部では各エントリが `mem::replay::load`、`mem::replay::sessions`、`mem::replay::import-jsonl` の iii functions を経由します — サイドチャネルサーバーはありません。 + +### アップグレード / メンテナンス + +意図的にローカルランタイムを更新したいときは、メンテナンスコマンドを使ってください: + +```bash +npx @agentmemory/agentmemory upgrade +``` + +警告: このコマンドは現在のワークスペース/ランタイムを変更します。JavaScript 依存を更新したり、`cargo install iii-engine --force` を実行したり、Docker イメージを pull したりすることがあります。 + +実装の詳細は `src/cli.ts` を参照(`src/cli.ts:544-595` 付近の `runUpgrade`)。 + +### Claude Code(1 ブロックそのまま貼り付け) + +```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}` を解決しないため、hook スクリプトを `~/.claude/settings.json` の絶対パスに向ける必要があります。これらのパスには通常 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 +``` + +同じ hook コマンドを `~/.claude/settings.json` にマージし、現在インストールされている `@agentmemory/agentmemory` パッケージの `plugin/` ディレクトリに解決された絶対パスを書き込みます。agentmemory をアップグレードしたら、このコマンドを再実行してパスを更新してください。同じファイル内のユーザーエントリは保持され、以前の agentmemory エントリだけが置き換えられます。`/plugin install` の経路が推奨アプローチであることに変わりはありません。 + +リモートや保護されたデプロイでは、`AGENTMEMORY_URL` と `AGENTMEMORY_SECRET` を設定して Claude Code を起動します。プラグインはこの両方の値を同梱の MCP サーバーに渡します。`AGENTMEMORY_URL` が空の場合、MCP shim は `http://localhost:3111` にフォールバックします。 + +### Codex CLI(Codex プラグインプラットフォーム) + +```bash +# 1. 別ターミナルでメモリサーバーを起動 +npx @agentmemory/agentmemory + +# 2. agentmemory マーケットプレイスを登録してプラグインをインストール +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 +``` + +これは同梱スクリプトへの絶対パスを参照する冪等なブロックを `~/.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` + +`mcpServers` シェイプを使うホスト(Cursor、Claude Desktop、Cline、Roo Code、Windsurf、Gemini CLI、OpenClaw)では、agentmemory エントリは**同じ MCP サーバーブロック**です: + +```json +"agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}" + } +} +``` + +**このエントリをホストの設定ファイルにある既存の `mcpServers` オブジェクトにマージしてください** — ファイル全体を置き換えないでください。ファイルに既に他のサーバーがある場合は、`agentmemory` をその隣にもう 1 つのキーとして追加します。`mcpServers` が完全に欠落している場合は、ブロックを `{ "mcpServers": { ... } }` の中に貼り付けてください。`${VAR}` プレースホルダーは MCP サーバー起動時にシェルから `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` を継承します — 未設定の変数は空文字列を渡し、shim は `http://localhost:3111` にフォールバックします。1 つの接続済みエントリでローカルとリモート(k8s / リバースプロキシ)両方のデプロイに対応します。 + +| エージェント | 設定ファイル | 備考 | +|---|---|---| +| **Cursor** | `~/.cursor/mcp.json` | `mcpServers` にマージ。ウェブサイトでワンクリックディープリンクも利用可能。 | +| **Claude Desktop** | `claude_desktop_config.json`(Application Support) | `mcpServers` にマージ。編集後 Claude Desktop を再起動。 | +| **Cline / Roo Code / Kilo Code** | Cline MCP 設定(設定 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 設定 | 同じ `mcpServers` ブロック、または[より深いメモリプラグイン](../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 つのライフサイクル 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 のみ)** | `opencode.json` | 異なるシェイプ — トップレベルの `mcp` キー、command は配列: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`。 | +| **OpenCode(フルプラグイン)** | `plugin/opencode/` | 22 個の自動キャプチャ hooks がセッションライフサイクル、メッセージ、ツール、エラーをカバー。2 つのスラッシュコマンド(`/recall`、`/remember`)。`plugin/opencode/` を OpenCode ワークスペースにコピーし、プラグインエントリを `opencode.json` に追加。完全な hook 表とギャップ分析は [`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` ブロックを書き込みます。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 終了後に使用。 | +| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` がユーザーレベル設定を書き込みます。ワークスペースのオーバーライドはコードの横にある `.kiro/settings/mcp.json` に。 | +| **Goose** | Goose MCP 設定 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 functions(`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 はまだそれ向けにリファクタリングされていません。リファクタが完了次第ピンは解除されます。サンドボックスモデルへ手動移行済みなら `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 ユーザーには 2 つの経路があります: + +**選択肢 A — ビルド済み Windows バイナリ(推奨):** + +```powershell +# 1. ブラウザで https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 を開く +# (engine v0.11.6+ が要求する新しいサンドボックスモデルへ +# agentmemory がリファクタリングされるまで v0.11.2 にピン留め) +# 2. iii-x86_64-pc-windows-msvc.zip をダウンロード +# (ARM マシンの場合は iii-aarch64-pc-windows-msvc.zip) +# 3. iii.exe を PATH 上のどこかに展開、または以下に配置: +# %USERPROFILE%\.local\bin\iii.exe +# (agentmemory はこの場所を自動でチェックします) +# 4. 確認: +iii --version +# 出力: 0.11.2 + +# 5. その後 agentmemory を通常通り起動: +npx -y @agentmemory/agentmemory +``` + +**選択肢 B — Docker Desktop:** + +```powershell +# 1. Docker Desktop for Windows をインストール +# 2. Docker Desktop を起動し、エンジンが動作中であることを確認 +# 3. agentmemory を実行 — 同梱の compose ファイルが自動起動します: +npx -y @agentmemory/agentmemory +``` + +**選択肢 C — スタンドアロン MCP のみ(エンジンなし):** エージェント用に MCP ツールだけが必要で、REST API、ビューワー、cron ジョブが不要なら、エンジンを完全にスキップ: + +```powershell +npx -y @agentmemory/agentmemory mcp +# あるいは shim パッケージ経由: +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` でバインドを確認、kill するか `--port ` を使用 | +| Docker をインストール済みなのにフォールバックがスキップされる | Docker Desktop が実際に動作している(システムトレイアイコン)ことを確認 | + +> 注意: `cargo install iii-engine` は存在しません — `iii` は crates.io に公開されていません。サポートされるインストール方法は、上記のビルド済みバイナリ、上流の `sh` インストールスクリプト(macOS/Linux のみ)、Docker イメージのみです。 + +--- + +

デプロイ

+ +マネージドホスト向けのワンクリックテンプレート。それぞれが +自己完結した Dockerfile を提供し、npm から +`@agentmemory/agentmemory` を pull して公式の `iiidev/iii` +Docker Hub イメージから iii engine バイナリをコピーします — 事前に +ビルドした agentmemory イメージは不要です。永続ストレージは +`/data` にマウントされます。初回起動の entrypoint は npm 同梱の +iii 設定(`127.0.0.1` をバインド)をデプロイ向けに調整した +設定(`0.0.0.0` をバインドし絶対 `/data` パスを使用)で上書きし、 +HMAC シークレットを生成、そして `gosu` で `root` から `node` +に権限を落としてから agentmemory CLI を exec します。 + +

+ Deploy to fly.io + Deploy to Railway +

+ +Render のワンクリックデプロイボタンはリポジトリルートに `render.yaml` を要求しますが、ルートをあえて綺麗に保っています。[`deploy/render/`](../deploy/render/README.md) にドキュメント化された Render 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` のビューワーは +コンテナ内でループバックにバインドされ続けます — 各テンプレートの +README にそこへ到達する SSH トンネルパターンが記載されています。 + +--- + +

Why agentmemory

+ +すべてのコーディングエージェントはセッションが終わるとすべてを忘れます。毎セッションの最初の 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 + ベクトル + グラフ(top-K のみ) | +| トークンコスト | 240 観測で 22K+ | ~1,900 tokens(92% 削減) | +| クロスエージェント | エージェントごとのファイル | MCP + REST(任意のエージェント) | +| 調整 | なし | リース、シグナル、アクション、ルーチン | +| 可観測性 | 手動でファイルを読む | ポート 3113 のリアルタイムビューワー | + +--- + +

How It Works

+ +### メモリパイプライン + +```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(手続き記憶)** | ワークフローと意思決定パターン | 「どうやるか」 | + +記憶は時間とともに減衰(エビングハウス曲線)。頻繁にアクセスされる記憶は強化されます。古い記憶は自動退避。矛盾は検出され解決されます。 + +### 何をキャプチャするか + +| Hook | キャプチャ内容 | +|------|----------| +| `SessionStart` | プロジェクトパス、セッション ID | +| `UserPromptSubmit` | ユーザープロンプト(プライバシーフィルタ済み) | +| `PreToolUse` | ファイルアクセスパターン + コンテキスト富化 | +| `PostToolUse` | ツール名、入力、出力 | +| `PostToolUseFailure` | エラーコンテキスト | +| `PreCompact` | コンパクション前にメモリを再注入 | +| `SubagentStart/Stop` | サブエージェントのライフサイクル | +| `Stop` | セッション終了時の要約 | +| `SessionEnd` | セッション完了マーカー | + +### 主な機能 + +| 機能 | 説明 | +|---|---| +| **自動キャプチャ** | hooks で毎ツール使用を記録 — 手動作業ゼロ | +| **セマンティック検索** | BM25 + ベクトル + ナレッジグラフ、RRF 融合 | +| **メモリ進化** | バージョン管理、上書き、関係グラフ | +| **自動忘却** | TTL 期限切れ、矛盾検出、重要度退避 | +| **プライバシー優先** | API キー、シークレット、`` タグは保存前に除去 | +| **自己修復** | サーキットブレーカー、プロバイダーフォールバックチェーン、ヘルスモニタ | +| **Claude ブリッジ** | MEMORY.md と双方向同期 | +| **ナレッジグラフ** | エンティティ抽出 + BFS 探索 | +| **チームメモリ** | チームメンバー間で名前空間化された共有 + プライベート | +| **引用の出所追跡** | あらゆるメモリを元の観測まで遡れる | +| **Git スナップショット** | メモリ状態のバージョン、ロールバック、diff | + +--- + + + +3 つのシグナルを組み合わせるトリプルストリーム検索: + +| ストリーム | 役割 | 起動条件 | +|---|---|---| +| **BM25** | ステミング付きキーワード一致と類義語拡張 | 常時有効 | +| **Vector(ベクトル)** | 密埋め込みのコサイン類似度 | 埋め込みプロバイダー設定時 | +| **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` | 無料 | オフライン、BM25 単独より召集率 +8pp | +| Gemini | `gemini-embedding-001` | 無料枠 | 100+ 言語、768/1536/3072 次元 (MRL)、2048 トークン入力。`text-embedding-004` の後継([非推奨、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 | 任意のモデル | 場合による | マルチモデルプロキシ | + +--- + +

MCP Server

+ +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 層統合を実行 | +| `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` | 次に最も重要なアクション 1 つ | +| `memory_lease` | 排他的アクションリース(マルチエージェント) | +| `memory_routine_run` | ワークフロー ルーチンをインスタンス化 | +| `memory_signal_send` | エージェント間メッセージング | +| `memory_signal_read` | 受領確認付きでメッセージを読む | +| `memory_checkpoint` | 外部条件ゲート | +| `memory_mesh_sync` | インスタンス間 P2P 同期 | +| `memory_sentinel_create` | イベント駆動ウォッチャー | +| `memory_sentinel_trigger` | 外部からセンチネルを発火 | +| `memory_sketch_create` | 一時的なアクショングラフ | +| `memory_sketch_promote` | 永続化に昇格 | +| `memory_crystallize` | アクションチェーンをコンパクト化 | +| `memory_diagnose` | ヘルスチェック | +| `memory_heal` | 詰まった状態を自動修復 | +| `memory_facet_tag` | 次元:値タグ | +| `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 # 正規(常時利用可能) +npx -y @agentmemory/mcp # shim パッケージのエイリアス +``` + +またはエージェントの 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` オブジェクトにマージし、ファイル全体を置き換えないでください。ホストの `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/ +``` + +--- + +

Real-Time Viewer

+ +ポート `3113` で自動起動。ライブ観測ストリーム、セッションエクスプローラ、メモリブラウザ、ナレッジグラフの可視化、ヘルスダッシュボード。 + +```bash +open http://localhost:3113 +``` + +ビューワーサーバーはデフォルトで `127.0.0.1` にバインドします。REST 経由の `/agentmemory/viewer` エンドポイントは通常の `AGENTMEMORY_SECRET` ベアラートークン規則に従います。CSP ヘッダーはレスポンスごとのスクリプト nonce を使い、インラインハンドラ属性は無効化(`script-src-attr 'none'`)。 + +--- + +

iii Console

+ +`:3113` のビューワーはエージェントが**覚えた**ことを見せます。[iii コンソール](https://iii.dev/docs/console)はエージェントが**やった**ことを見せます — 各メモリ操作は OpenTelemetry トレース、各 KV エントリは編集可能、各 function は呼び出し可能、各ストリームは tap 可能。同じメモリへの 2 つの窓: 一方はプロダクト形、もう一方はエンジン形。 + +`memory_smart_search` の発火を眺め、BM25 スキャン → 埋め込み参照 → RRF 融合 → リランカーをウォーターフォールで見ます。KV ブラウザで詰まった統合タイマーを編集します。調整したペイロードで `PostToolUse` hook を再生します。WebSocket ストリームをピンして観測がライブで着地するのを眺めます。 + +agentmemory はこれを無料で提供します。すべての function、トリガー、ステートスコープ、ストリームが iii プリミティブだからです — カスタム実装も計装も必要ありません。 + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ Workers ページ: agentmemory 自身を含む、接続中のすべての worker と PID、function 数、ランタイム、最終応答時刻。 +

+ +**インストール済みです。** コンソールは `iii` に同梱 — 別途インストーラはありません。 + +**agentmemory と並行して起動:** + +```bash +# agentmemory ビューワーがポート 3113 を握っているので、コンソールは 3114 で実行します。 +# エンジン REST (3111)、WebSocket (3112)、bridge (49134) のデフォルトは agentmemory と一致します。 +iii console --port 3114 +``` + +その後 `http://localhost:3114` を開きます。`--enable-flow` で実験的なアーキテクチャグラフページを有効化します。 + +エンジンエンドポイントを移動した場合のみ上書き: + +```bash +iii console --port 3114 \ + --engine-port 3111 \ + --ws-port 3112 \ + --bridge-port 49134 +``` + +**コンソールでできること:** + +| ページ | 用途 | +|------|-----------| +| **Workers** | agentmemory worker 自身を含む、接続中の各 worker とライブメトリクスを表示。 | +| **Functions** | JSON ペイロードを与えて agentmemory の任意の function を直接呼び出し — クライアントを配線せずに `memory.recall`、`memory.consolidate`、`graph.query` をテストできて便利。 | +| **Triggers** | HTTP、cron、イベント、ステートのトリガーを再生 — 統合 cron を手動で発火、HTTP ルートを再試行、ステート変更を発行。 | +| **States** | フル CRUD の KV ブラウザ — セッション、メモリスロット、ライフサイクルタイマー、埋め込みインデックス — その場で値を編集。 | +| **Streams** | メモリ書き込み、hook イベント、観測更新が iii ストリームを流れる様子をライブで監視する WebSocket モニタ。 | +| **Queues** | 永続キューのトピック + デッドレター管理。失敗した埋め込み / 圧縮ジョブを再生または破棄。 | +| **Traces** | OpenTelemetry のウォーターフォール / フレーム / サービスブレークダウン。`trace_id` でフィルタすれば、単一の `memory.search` がどの function、DB 呼び出し、埋め込みリクエストを生んだか正確にわかります。 | +| **Logs** | 構造化 OTEL ログをフィルタし、trace/span ID と相関付け。 | +| **Config** | ランタイム設定 — エンジンがどの worker、プロバイダー、ポートで動いているか確認。 | +| **Flow** | (オプション、`--enable-flow`)各 worker、トリガー、ストリームの対話型アーキテクチャグラフ。 | + +

+ iii console trace waterfall view showing per-span duration +
+ Traces: すべてのメモリ操作についてウォーターフォール / フレーム / サービスブレークダウン。 +

+ +**Traces は既にオン:** + +`iii-config.yaml` は出荷時から `iii-observability` worker を有効化(`exporter: memory`、`sampling_ratio: 1.0`、メトリクス + ログ)。追加設定不要 — agentmemory が起動した瞬間に、すべてのメモリ操作がトレーススパンとコンソールが読み取れる構造化ログを出します。 + +代わりに Jaeger / Honeycomb / Grafana Tempo へエクスポートしたい場合は、`exporter: memory` を `exporter: otlp` に変更し、iii の可観測性ドキュメントに従ってコレクタエンドポイントを設定してください。 + +> **注意:** コンソール自身に認証は強制されていません — デフォルトの `127.0.0.1` バインドのままにし、決して公開しないでください。 + +--- + +

Powered by iii

+ +agentmemory は**それ自体が稼働中の [iii](https://iii.dev) インスタンス**です。function、トリガー、KV ステート、ストリーム、OTEL トレース — すべてが iii プリミティブです。Postgres、Redis、Express、pm2、Prometheus をインストールしなかったのは、iii がそれらを置き換えるからです。 + +つまり、もう 1 つのコマンドで agentmemory にまったく新しい機能を拡張できます。 + +### 1 つのコマンドで agentmemory を拡張 + +```bash +iii worker add iii-pubsub # メモリ書き込みを接続中のすべてのインスタンスに fan-out +iii worker add iii-cron # スケジュール統合、減衰スイープ、スナップショットローテーション +iii worker add iii-queue # 埋め込み + 圧縮ジョブの永続リトライ +iii worker add iii-observability # すべてのメモリ操作に OTEL トレース(デフォルト オン) +iii worker add iii-sandbox # リコールしたコードを隔離 microVM 内で実行 +iii worker add iii-database # SQL バックエンドのステートアダプタに切り替え +iii worker add mcp # agentmemory MCP の横に汎用 MCP ホストを立てる +``` + +各 `iii worker add` は新しい function とトリガーを、agentmemory が既に動いているのと同じエンジンに登録します。ビューワーとコンソールがすぐに拾い上げます — リロード不要、新しい統合不要、新しいコンテナ不要。 + +| `iii worker add` | agentmemory の上に得られるもの | +|---|---| +| [`iii-pubsub`](https://workers.iii.dev/workers/iii-pubsub) | マルチインスタンスメモリ: すべての `remember` が fan-out、すべての `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) | すべての function に OTEL トレース、メトリクス、ログ — 初日から `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 バックエンドのステートアダプタ | +| [`mcp`](https://workers.iii.dev/workers/mcp) | agentmemory の隣に追加の MCP サーバーを立て、同じエンジンを共有 | + +完全なレジストリ:[workers.iii.dev](https://workers.iii.dev)。そこにあるすべての worker は agentmemory が使っているのと同じプリミティブで組み立てられています — そして既に手元にある agentmemory もその 1 つです。 + +### 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 監視 | +| Prometheus / Grafana | iii OTEL + ヘルスモニタ | +| カスタムプラグインシステム | `iii worker add ` | + +**118 ソースファイル · ~21,800 LOC · 950+ テスト · 123 functions · 34 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。 + +--- + +

Configuration

+ +### LLM プロバイダー + +agentmemory は環境から自動検出します。デフォルトでは、プロバイダーを設定するか Claude 購読フォールバックに明示的にオプトインしない限り、LLM 呼び出しは行いません。 + +| プロバイダー | 設定 | 備考 | +|----------|--------|-------| +| **No-op(デフォルト)** | 設定不要 | LLM 駆動の compress/summarize は無効。合成 BM25 圧縮 + リコールは引き続き動作。以前 Claude 購読フォールバックに依存していた場合は、下記の `AGENTMEMORY_ALLOW_AGENT_SDK` を参照。 | +| Anthropic API | `ANTHROPIC_API_KEY` | トークン単位課金 | +| MiniMax | `MINIMAX_API_KEY` | Anthropic 互換 | +| Gemini | `GEMINI_API_KEY` | 埋め込みも有効化 | +| OpenRouter | `OPENROUTER_API_KEY` | 任意のモデル | +| Claude 購読フォールバック | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | オプトインのみ。`@anthropic-ai/claude-agent-sdk` セッションを生成 — 過去に無限の Stop-hook 再帰(#149 のフォローアップ)を引き起こしたため、もはやデフォルトではありません。 | + +### コストを意識したモデル選択 + +バックグラウンド圧縮は観測のたびに走るため、モデル選択は月額支出に大きく効きます。記録されたワークロード: 635 リクエスト / 888K トークン / 35 時間のアクティブ使用、2026-05-23 時点の OpenRouter 価格で 3 モデルを比較。 + +| 階層 | モデル | 入力 / 1M | 出力 / 1M | 35 時間のワークロードでのコスト | 備考 | +|------|-------|------------|-------------|---------------------------|-------| +| 推奨 | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | 圧縮 + 要約品質が手堅く、Sonnet の約 10 分の 1 のコスト。 | +| 推奨 | `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+ | 推論クラスのモデル。圧縮には大幅な過剰支出。 | + +agentmemory は `OPENROUTER_MODEL` がプレミアム階層パターンと一致するときランタイム警告を表示します。納得して選んだあとは `AGENTMEMORY_SUPPRESS_COST_WARNING=1` で消音できます。 + +メモリ作業における品質対コストのトレードオフ: 圧縮は品質のハードルが比較的緩い要約タスクです(要約を読み返すのはエージェントであってユーザーではありません)。DeepSeek-V4-Pro / Qwen3-Coder はこのタスクで Sonnet と誤差範囲に収まる一方、コストは約 10 分の 1 です。プレミアム階層のモデルは、あなたが直接読むクエリに取っておきましょう。 + +出典:[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`) + +複数のロール(architect / developer / reviewer / researcher / support-agent)が 1 つの agentmemory サーバーを共有するマルチエージェント構成では、`AGENT_ID` がすべての書き込みに発信したロールのタグを付けます。`AGENTMEMORY_AGENT_SCOPE` はリコールがそのタグでフィルタするかどうかを制御します。 + +```env +TEAM_ID=company +USER_ID=engineering-team +AGENT_ID=architect +AGENTMEMORY_AGENT_SCOPE=isolated # 任意、デフォルトは "shared" +``` + +2 つのモード: + +| モード | 書き込みにタグ | リコールでフィルタ | 使いどころ | +|------|------------|---------------|-------------| +| `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=*` で環境スコープから完全にオプトアウトできます。`/memories` はさらに `?includeOrphans=true` を受け付け、`agentId` が undefined の AGENT_ID 導入前のメモリを浮上させます。 + +SDK / REST 層での呼び出し単位オーバーライド: すべての変更系エンドポイント(`/session/start`、`/remember`)はリクエストボディに `agentId` フィールドを受け付け、環境変数より優先されます。1 つのサーバープロセス経由で多数のロールをルーティングするランタイムに便利です。 + +`AGENT_ID` が未設定の場合、メモリはスコープなしのまま(従来の挙動、タグなし・フィルタなし)。 + +### ポート + +agentmemory + iii-engine はデフォルトで 4 つのポートをバインドします。再起動が `port in use` で失敗する場合、この表でどのプロセスを探せばよいか分かります。 + +| ポート | プロセス | 用途 | 環境変数で上書き | +|------|---------|---------|--------------| +| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` | +| `3112` | iii-engine | 内部ストリーム worker(agentmemory + ビューワーが消費) | `III_STREAMS_PORT` | +| `3113` | agentmemory | リアルタイムビューワー(`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` | +| `49134` | iii-engine | WebSocket — worker はここに登録、OTel テレメトリもここを流れる | `III_ENGINE_URL`(完全 URL、デフォルト `ws://localhost:49134`) | + +クラッシュ後にポートが解放されないときの古いプロセス整理: + +```bash +# macOS / Linux — 各ポートで動いているものを探して 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` は正常終了時に worker と engine の pidfile を綺麗に回収します(#640、#474)。上の手動クリーンアップは、どちらの pidfile も残っていないクラッシュ後の状態を対象とします。 + +### 設定ファイル + +agentmemory のランタイム設定は、各シェルで変数を export するのではなく `~/.agentmemory/.env` に置いてください。ビューワーが `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 +``` + +API キーの代わりに Claude Code Pro/Max 購読でテストするには、明示的にオプトイン: + +```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 +``` + +--- + +

API

+ +ポート `3111` 上の 124 エンドポイント。REST API はデフォルトで `127.0.0.1` にバインドします。`AGENTMEMORY_SECRET` が設定されている場合、保護されたエンドポイントは `Authorization: Bearer ` を要求し、mesh sync エンドポイントは両ピアで `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` | ファイルコンテキスト + メモリ + bug | +| `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) + +
+ +--- + +

Development

+ +```bash +npm run dev # ホットリロード +npm run build # 本番ビルド +npm test # 950+ テスト +npm run test:integration # API テスト(サービス起動が必要) +``` + +**前提:** Node.js >= 20、[iii-engine](https://iii.dev/docs) または Docker + +

License

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md new file mode 100644 index 0000000000000000000000000000000000000000..76bcc1d7b12b7f2d8f2fc1a90a925951997b7786 --- /dev/null +++ b/READMEs/README.ko-KR.md @@ -0,0 +1,1361 @@ +

+ agentmemory — AI 코딩 에이전트를 위한 영구 메모리 +

+ +

+ + 코딩 에이전트가 모든 것을 기억합니다. 더 이상 다시 설명할 필요가 없습니다. + Built on iii engine +
+ Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode 및 모든 MCP 클라이언트를 위한 영구 메모리입니다. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ 설계 문서: gist 기준 1200 stars / 172 forks +

+ +

+ 이 gist는 Karpathy의 LLM Wiki 패턴을 신뢰도 점수, 라이프사이클, 지식 그래프, 하이브리드 검색으로 확장한 것입니다. agentmemory는 그 구현체입니다. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory 데모 +

+ +

+ 설치 • + 빠른 시작 • + 벤치마크 • + 경쟁 제품 비교 • + 에이전트 • + 동작 방식 • + MCP • + 뷰어 • + iii Console • + Powered by iii • + 설정 • + API +

+ +--- + +## 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
+Claude Code
+native plugin + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+native plugin + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+native plugin + MCP +
+Hermes
+Hermes
+native plugin + MCP +
+pi
+pi
+native plugin + MCP +
+OpenHuman
+OpenHuman
+native Memory trait backend +
+Cursor
+Cursor
+MCP server +
+Gemini CLI
+Gemini CLI
+MCP server +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+MCP server +
+Goose
+Goose
+MCP server +
+Kilo Code
+Kilo Code
+MCP server +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP server +
+Windsurf
+Windsurf
+MCP server +
+Roo Code
+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)에서 확인할 수 있습니다. + +--- + +

벤치마크

+ + + + + + +
+ +### 검색 정확도 + +**coding-agent-life-v1** (자체 코퍼스, 샌드박스 재현 가능) + +| 어댑터 | P@5 | R@5 | Top-5 적중률 | p50 지연 | +|---|---|---|---|---| +| **agentmemory hybrid** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep baseline | 0.267 | 0.967 | 15 / 15 | 0 ms | + +Top-5 적중률 100%. 동일한 입력에서 grep 기준선 대비 정밀도가 **2.2배** 더 높습니다. 유형별 전체 분석은 다음에서 확인할 수 있습니다: [`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%** | +| BM25-only fallback | 86.2% | 94.6% | 71.5% | + + + +### 토큰 절감 + +| 방식 | 연간 토큰 | 연간 비용 | +|---|---|---| +| 전체 컨텍스트를 매번 붙여넣기 | 19.5M+ | 불가능(컨텍스트 윈도우 초과) | +| 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) — 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). + +--- + +

경쟁 제품 비교

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)내장 메모리 (CLAUDE.md)
유형메모리 엔진 + MCP 서버메모리 레이어 API완전한 에이전트 런타임정적 파일
검색 R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)해당 없음 (grep)
자동 캡처12 hooks (수동 작업 없음)수동 add() 호출에이전트 자체 편집수동 편집
검색BM25 + Vector + Graph (RRF 융합)Vector + GraphVector (archival)모든 것을 컨텍스트에 로드
멀티 에이전트MCP + REST + leases + signalsAPI (조정 없음)Letta 런타임 내에서만에이전트별 파일
프레임워크 종속성없음 (모든 MCP 클라이언트)없음높음 (Letta 사용 필수)에이전트별 포맷
외부 의존성없음 (SQLite + iii-engine)Qdrant / pgvectorPostgres + 벡터 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합니다. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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 터널 패턴을 문서화합니다. + +--- + +

왜 agentmemory인가

+ +모든 코딩 에이전트는 세션이 끝나면 모든 것을 잊습니다. 매 세션의 첫 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 | 모든 모델 | 다양 | 멀티 모델 프록시 | + +--- + +

MCP 서버

+ +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'`). + +--- + +

iii Console

+ +`:3113`의 뷰어는 에이전트가 **기억한 것**을 보여줍니다. [iii console](https://iii.dev/docs/console)은 에이전트가 **무엇을 했는지**를 보여줍니다 — 모든 메모리 작업을 OpenTelemetry 추적으로, 모든 KV 항목을 편집 가능하게, 모든 함수를 호출 가능하게, 모든 스트림을 탭 가능하게. 동일한 메모리에 대한 두 창: 하나는 제품 형태, 하나는 엔진 형태. + +`memory_smart_search`가 발화되는 것을 보고 BM25 스캔 → 임베딩 조회 → RRF 융합 → 리랭커를 워터폴로 확인하십시오. KV 브라우저에서 정체된 통합 타이머를 편집하십시오. 조정된 페이로드로 `PostToolUse` hook을 재생하십시오. WebSocket 스트림을 고정하고 관측이 실시간으로 도착하는 것을 지켜보십시오. + +agentmemory는 모든 함수, 트리거, 상태 스코프, 스트림이 iii 프리미티브이기 때문에 — 사용자 정의도, 계측할 것도 없기 때문에 — 이를 무료로 제공합니다. + +

+ iii console Workers 페이지 — 연결된 워커들, 라이브 함수 수와 런타임 메타데이터가 표시된 agentmemory 인스턴스 포함 +
+ 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. | + +

+ span별 지속 시간을 보여주는 iii console trace waterfall view +
+ 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`에 바인딩된 채로 두고(기본값) 절대 공개적으로 노출하지 마십시오. + +--- + +

Powered by iii

+ +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 +``` + +--- + +

API

+ +`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 + +

라이선스

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md new file mode 100644 index 0000000000000000000000000000000000000000..bd3777a90058742e4fcf4ac38ffbf54726213973 --- /dev/null +++ b/READMEs/README.pt-BR.md @@ -0,0 +1,1370 @@ +

+ agentmemory — Memória persistente para agentes de codificação com IA +

+ +

+ + 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. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Documento de design: 1200 stars / 172 forks no gist +

+ +

+ 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. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ Demonstração do agentmemory +

+ +

+ Instalação • + Início rápido • + Benchmarks • + Comparativo • + Agentes • + Como funciona • + MCP • + Viewer • + iii Console • + Powered by iii • + Configuração • + API +

+ +--- + +## 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). + +--- + +

Funciona com qualquer agente

+ +agentmemory funciona com qualquer agente que suporte hooks, MCP ou REST API. Todos os agentes compartilham o mesmo servidor de memória. + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+native plugin + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+native plugin + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+native plugin + MCP +
+Hermes
+Hermes
+native plugin + MCP +
+pi
+pi
+native plugin + MCP +
+OpenHuman
+OpenHuman
+native Memory trait backend +
+Cursor
+Cursor
+MCP server +
+Gemini CLI
+Gemini CLI
+MCP server +
+OpenCode
+OpenCode
+22 hooks + MCP + plugin +
+Cline
+Cline
+MCP server +
+Goose
+Goose
+MCP server +
+Kilo Code
+Kilo Code
+MCP server +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP server +
+Windsurf
+Windsurf
+MCP server +
+Roo Code
+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). + +--- + +

Benchmarks

+ + + + + + +
+ +### 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% | + + + +### Economia de tokens + +| Abordagem | Tokens/ano | Custo/ano | +|---|---|---| +| Colar contexto completo | 19.5M+ | Impossível (excede a janela) | +| Resumido por LLM | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + embeddings locais | ~170K | **$0** | + +
+ +> 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). + +--- + +

Comparativo

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Built-in (CLAUDE.md)
TipoEngine de memória + servidor MCPAPI de camada de memóriaRuntime de agente completoArquivo estático
Retrieval R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
Captura automática12 hooks (esforço manual zero)Chamadas manuais a add()O agente se autoeditaEdição manual
BuscaBM25 + Vector + Graph (fusão RRF)Vector + GraphVector (archival)Carrega tudo no contexto
MultiagenteMCP + REST + leases + signalsAPI (sem coordenação)Somente dentro do runtime do LettaArquivos por agente
Dependência de frameworkNenhuma (qualquer cliente MCP)NenhumaAlta (precisa usar Letta)Formato por agente
Dependências externasNenhuma (SQLite + iii-engine)Qdrant / pgvectorPostgres + BD vetorialNenhuma
Ciclo de vida da memóriaConsolidação de 4 níveis + decaimento + auto-esquecimentoExtração passivaGerenciado pelo agentePoda manual
Eficiência de tokens~1.900 tokens/sessão ($10/ano)Varia conforme a integraçãoMemória principal no contexto22K+ tokens com 240 obs
Viewer em tempo realSim (port 3113)Dashboard na nuvemDashboard na nuvemNão
Self-hostedSim (padrão)OpcionalOpcionalSim
+ +--- + +

Início rápido

+ +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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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. + +--- + +

Por que agentmemory

+ +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 | + +--- + +

Como funciona

+ +### 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 | + +--- + +

Servidor MCP

+ +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/ +``` + +--- + +

Viewer em tempo real

+ +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'`). + +--- + +

iii Console

+ +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 do iii console — workers conectados incluindo instâncias do agentmemory com contagem de funções ao vivo e metadados de runtime +
+ 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. | + +

+ Visão waterfall de trace do iii console mostrando duração por span +
+ 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. + +--- + +

Powered by iii

+ +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. + +--- + +

Configuração

+ +### 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 +``` + +--- + +

API

+ +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) + +
+ +--- + +

Desenvolvimento

+ +```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 + +

Licença

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md new file mode 100644 index 0000000000000000000000000000000000000000..2bd6596822b0d697ab60ace792326f18e830704c --- /dev/null +++ b/READMEs/README.ru-RU.md @@ -0,0 +1,1377 @@ +

+ agentmemory — Постоянная память для ИИ-агентов программирования +

+ +

+ + Ваш агент программирования помнит всё. Больше не нужно объяснять заново. + Built on iii engine +
+ Постоянная память для Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode и любого MCP-клиента. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Документ проекта: 1200 звёзд / 172 форка в гисте +

+ +

+ Этот gist расширяет шаблон LLM Wiki от Karpathy: confidence-оценкой, жизненным циклом, графами знаний и гибридным поиском — agentmemory является его реализацией. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ Демо agentmemory +

+ +

+ Установка • + Быстрый старт • + Бенчмарки • + Сравнение • + Агенты • + Как это работает • + MCP • + Просмотрщик • + iii Console • + Powered by iii • + Конфигурация • + API +

+ +--- + +## 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. Все агенты используют один и тот же сервер памяти. + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+нативный плагин + 12 хуков + MCP +
+Codex CLI
+Codex CLI
+нативный плагин + 6 хуков + MCP +
+OpenClaw
+OpenClaw
+нативный плагин + MCP +
+Hermes
+Hermes
+нативный плагин + MCP +
+pi
+pi
+нативный плагин + MCP +
+OpenHuman
+OpenHuman
+нативный бэкенд трейта Memory +
+Cursor
+Cursor
+MCP-сервер +
+Gemini CLI
+Gemini CLI
+MCP-сервер +
+OpenCode
+OpenCode
+22 хука + MCP + плагин +
+Cline
+Cline
+MCP-сервер +
+Goose
+Goose
+MCP-сервер +
+Kilo Code
+Kilo Code
+MCP-сервер +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP-сервер +
+Windsurf
+Windsurf
+MCP-сервер +
+Roo Code
+Roo Code
+MCP-сервер +
+ +

+ Работает с любым агентом, который говорит на 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). + +--- + +

Сравнение с конкурентами

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Встроенное (CLAUDE.md)
ТипДвижок памяти + MCP-серверAPI уровня памятиПолноценный агентский runtimeСтатический файл
R@5 при извлечении95.2%68.5% (LoCoMo)83.2% (LoCoMo)Н/Д (grep)
Авто-захват12 хуков (никаких ручных усилий)Ручные вызовы add()Агент сам редактируетРучное редактирование
ПоискBM25 + векторный + граф (RRF-слияние)Векторный + графВекторный (архивный)Загружает всё в контекст
МультиагентностьMCP + REST + lease'ы + сигналыAPI (без координации)Только внутри runtime LettaОтдельные файлы на агента
Привязка к фреймворкуНет (любой MCP-клиент)НетВысокая (нужен Letta)Формат на агента
Внешние зависимостиНет (SQLite + iii-engine)Qdrant / pgvectorPostgres + векторная БДНет
Жизненный цикл памяти4-уровневая консолидация + затухание + авто-забываниеПассивное извлечениеУправляется агентомРучное усечение
Эффективность по токенам~1 900 токенов/сессия (10 $/год)Зависит от интеграцииCore memory в контексте22K+ токенов при 240 наблюдениях
Просмотрщик в реальном времениДа (порт 3113)Облачная панельОблачная панельНет
Self-hostedДа (по умолчанию)ОпциональноОпциональноДа
+ +--- + +

Быстрый старт

+ +Совместимость: этот релиз нацелен на стабильный `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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +Кнопке 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-туннеля, чтобы до него достучаться. + +--- + +

Зачем agentmemory

+ +Каждый агент программирования забывает всё, когда сессия заканчивается. Вы тратите первые 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 | Любая модель | Зависит | Мульти-модельный прокси | + +--- + +

MCP-сервер

+ +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'`). + +--- + +

iii Console

+ +Просмотрщик на `: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 в iii console — подключённые воркеры, включая инстансы agentmemory, с живым числом функций и метаданными runtime +
+ Страница 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`) Интерактивный граф архитектуры из всех воркеров, триггеров и стримов. | + +

+ Просмотр trace-waterfall в iii console с длительностью каждого span +
+ 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` (по умолчанию) и никогда не выставляйте наружу. + +--- + +

Powered by iii

+ +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 +``` + +--- + +

API

+ +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 + +

Лицензия

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md new file mode 100644 index 0000000000000000000000000000000000000000..c97249acd21ad4e529b4f1318b038f3dc98b4363 --- /dev/null +++ b/READMEs/README.tr-TR.md @@ -0,0 +1,1381 @@ +

+ agentmemory — AI kodlama ajanları için kalıcı bellek +

+ +

+ + 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. +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1200 stars / 172 forks on the gist +

+ +

+ 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. +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory demo +

+ +

+ Kurulum • + Hızlı Başlangıç • + Kıyaslamalar • + Rakiplerle Karşılaştırma • + Ajanlar • + Nasıl Çalışır • + MCP • + Görüntüleyici • + iii Konsolu • + iii ile çalışır • + Yapılandırma • + API +

+ +--- + +## 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. + +--- + +

Works with every agent

+ +agentmemory; hook'ları, MCP'yi veya REST API'yi destekleyen her ajanla çalışır. Tüm ajanlar aynı bellek sunucusunu paylaşır. + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+yerel eklenti + 12 hook + MCP +
+Codex CLI
+Codex CLI
+yerel eklenti + 6 hook + MCP +
+OpenClaw
+OpenClaw
+yerel eklenti + MCP +
+Hermes
+Hermes
+yerel eklenti + MCP +
+pi
+pi
+yerel eklenti + MCP +
+OpenHuman
+OpenHuman
+yerel Memory trait arka uç +
+Cursor
+Cursor
+MCP sunucusu +
+Gemini CLI
+Gemini CLI
+MCP sunucusu +
+OpenCode
+OpenCode
+22 hook + MCP + eklenti +
+Cline
+Cline
+MCP sunucusu +
+Goose
+Goose
+MCP sunucusu +
+Kilo Code
+Kilo Code
+MCP sunucusu +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP sunucusu +
+Windsurf
+Windsurf
+MCP sunucusu +
+Roo Code
+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. + +--- + +

Benchmarks

+ + + + + + +
+ +### 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% | + + + +### Token Tasarrufu + +| Yaklaşım | Token/yıl | Maliyet/yıl | +|---|---|---| +| Tam bağlamı yapıştır | 19.5M+ | İmkansız (pencereyi aşar) | +| LLM-özetlenmiş | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + yerel embedding | ~170K | **$0** | + +
+ +> 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). + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)Yerleşik (CLAUDE.md)
TürBellek motoru + MCP sunucusuBellek katmanı API'siTam ajan runtime'ıStatik dosya
Geri getirme R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
Otomatik yakalama12 hook (sıfır manuel çaba)Manuel add() çağrılarıAjan kendi düzenlerManuel düzenleme
AramaBM25 + Vektör + Graf (RRF füzyonu)Vektör + GrafVektör (arşiv)Her şeyi bağlama yükler
Çoklu ajanMCP + REST + lease'ler + sinyallerAPI (koordinasyon yok)Yalnızca Letta runtime'ı içindeAjan başına dosya
Framework bağımlılığıYok (herhangi bir MCP istemcisi)YokYüksek (Letta kullanılmalı)Ajan başına format
Harici bağımlılıklarYok (SQLite + iii-engine)Qdrant / pgvectorPostgres + vektör DBYok
Bellek yaşam döngüsü4 katmanlı konsolidasyon + decay + otomatik-unutmaPasif çıkarımAjan-yönetimliManuel ayıklama
Token verimliliği~1,900 token/oturum ($10/yıl)Entegrasyona göre değişirÇekirdek bellek bağlamda240 gözlemde 22K+ token
Gerçek zamanlı görüntüleyiciVar (port 3113)Bulut panelBulut panelYok
Self-hostedEvet (varsayılan)İsteğe bağlıİsteğe bağlıEvet
+ +--- + +

Quick Start

+ +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. + +

+ Deploy to fly.io + Deploy to Railway +

+ +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. + +--- + +

Why agentmemory

+ +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 | + +--- + +

How It Works

+ +### 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 | + +--- + +

MCP Server

+ +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/ +``` + +--- + +

Real-Time Viewer

+ +`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'`). + +--- + +

iii Console

+ +`: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. + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ 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ı. | + +

+ iii console trace waterfall view showing per-span duration +
+ 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. + +--- + +

Powered by iii

+ +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. + +--- + +

Configuration

+ +### 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 +``` + +--- + +

API

+ +`3111` portunda 124 endpoint. REST API varsayılan olarak `127.0.0.1`'e bağlanır. `AGENTMEMORY_SECRET` ayarlandığında korumalı endpoint'ler `Authorization: Bearer ` gerektirir ve mesh sync endpoint'leri her iki eşte de `AGENTMEMORY_SECRET` gerektirir. + +
+Önemli endpoint'ler + +| Method | Path | Açıklama | +|--------|------|-------------| +| `GET` | `/agentmemory/health` | Sağlık kontrolü (her zaman public) | +| `POST` | `/agentmemory/session/start` | Oturum başlat + bağlam al | +| `POST` | `/agentmemory/session/end` | Oturumu bitir | +| `POST` | `/agentmemory/observe` | Gözlem yakala | +| `POST` | `/agentmemory/smart-search` | Hibrit arama | +| `POST` | `/agentmemory/context` | Bağlam üret | +| `POST` | `/agentmemory/remember` | Uzun süreli belleğe kaydet | +| `POST` | `/agentmemory/forget` | Gözlemleri sil | +| `POST` | `/agentmemory/enrich` | Dosya bağlamı + bellekler + bug'lar | +| `GET` | `/agentmemory/profile` | Proje profili | +| `GET` | `/agentmemory/export` | Tüm veriyi dışa aktar | +| `POST` | `/agentmemory/import` | JSON'dan içeri aktar | +| `POST` | `/agentmemory/graph/query` | Bilgi grafı sorgusu | +| `POST` | `/agentmemory/team/share` | Takımla paylaş | +| `GET` | `/agentmemory/audit` | Denetim izi | + +Tam endpoint listesi: [`src/triggers/api.ts`](../src/triggers/api.ts) + +
+ +--- + +

Development

+ +```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 + +

License

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..cc9a01a155ec4232ae18022c43fc73af93105149 --- /dev/null +++ b/READMEs/README.zh-CN.md @@ -0,0 +1,1378 @@ +

+ agentmemory — 为 AI 编码代理提供持久化记忆 +

+ +

+ + 让你的编码代理记住一切。不再重复解释。 + Built on iii engine +
+ 为 Claude Code、Cursor、Gemini CLI、Codex CLI、Hermes、OpenClaw、pi、OpenCode 以及任何 MCP 客户端提供持久化记忆。 +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1200 stars / 172 forks on the gist +

+ +

+ 这份 gist 以置信度评分、生命周期管理、知识图谱和混合搜索扩展了 Karpathy 的 LLM Wiki 模式:agentmemory 就是其实现。 +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory demo +

+ +

+ 安装 • + 快速开始 • + 基准测试 • + 对比竞品 • + 代理 • + 工作原理 • + MCP • + 查看器 • + iii 控制台 • + 由 iii 驱动 • + 配置 • + API +

+ +--- + +## 安装 + +```bash +npm install -g @agentmemory/agentmemory # 一次安装 — 全局可用 `agentmemory` 命令 +# 如果在 macOS/Linux 的系统 Node 上遇到 EACCES,请重试: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # 在 :3111 启动记忆服务器 +agentmemory demo # 注入示例会话并验证召回 +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)。 + +--- + +

Works with every agent

+ +agentmemory 兼容任何支持 hooks、MCP 或 REST API 的代理。所有代理共享同一个记忆服务器。 + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+原生插件 + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+原生插件 + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+原生插件 + MCP +
+Hermes
+Hermes
+原生插件 + MCP +
+pi
+pi
+原生插件 + MCP +
+OpenHuman
+OpenHuman
+原生 Memory trait 后端 +
+Cursor
+Cursor
+MCP 服务器 +
+Gemini CLI
+Gemini CLI
+MCP 服务器 +
+OpenCode
+OpenCode
+22 hooks + MCP + 插件 +
+Cline
+Cline
+MCP 服务器 +
+Goose
+Goose
+MCP 服务器 +
+Kilo Code
+Kilo Code
+MCP 服务器 +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP 服务器 +
+Windsurf
+Windsurf
+MCP 服务器 +
+Roo Code
+Roo Code
+MCP 服务器 +
+ +

+ 兼容任何使用 MCP 或 HTTP 的代理。一个服务器,所有代理共享记忆。 +

+ +--- + +你每次会话都在重复解释同样的架构。你反复发现同样的 bug。你重复教同样的偏好。内建的记忆(CLAUDE.md、.cursorrules)上限是 200 行而且会过时。agentmemory 解决了这个问题。它在后台静默捕获代理的行为,将其压缩为可搜索的记忆,并在下次会话开始时注入正确的上下文。一条命令。跨代理工作。 + +**改变了什么:** 会话 1 你设置了 JWT 鉴权。会话 2 你要求限流。代理已经知道你的鉴权使用 `src/middleware/auth.ts` 中的 jose 中间件,测试覆盖了 token 校验,你选择 jose 而非 jsonwebtoken 是为了 Edge 兼容性。无需重新解释。无需复制粘贴。代理就是*知道*。 + +```bash +npx @agentmemory/agentmemory +``` + +> **v0.9.0 新功能** — 落地页 [agent-memory.dev](https://agent-memory.dev) 上线,文件系统连接器(`@agentmemory/fs-watcher`),独立 MCP 现在代理至正在运行的服务器,使 hooks 和查看器保持一致,审计策略在所有删除路径上得到统一,健康状态在小型 Node 进程上不再误报 `memory_critical`。完整变更见 [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18)。 + +--- + +

Benchmarks

+ + + + + + +
+ +### 检索准确率 + +**coding-agent-life-v1** (内部语料库,沙盒可复现) + +| 适配器 | P@5 | R@5 | Top-5 命中率 | p50 延迟 | +|---|---|---|---|---| +| **agentmemory 混合** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep 基线 | 0.267 | 0.967 | 15 / 15 | 0 ms | + +100% Top-5 命中率。在同一输入下,精度比 grep 基线高 **2.2×**。完整按类型分解:[`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%** | +| 仅 BM25 回退 | 86.2% | 94.6% | 71.5% | + + + +### Token 节省 + +| 方法 | Token/年 | 成本/年 | +|---|---|---| +| 粘贴全部上下文 | 19.5M+ | 不可能(超出窗口) | +| LLM 摘要 | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + 本地嵌入 | ~170K | **$0** | + +
+ +> 嵌入模型:`all-MiniLM-L6-v2` (本地、免费、无需 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。 + +**本地复现:** [`eval/README.md`](../eval/README.md) — 适配器可插拔的 harness,支持 LongMemEval `_s`(公开 500 问)+ `coding-agent-life-v1`(内部 15 会话语料)。Grep / 向量 / 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) 使用。** 代码图索引、多代理构建流水线,以及跨文档 / PDF / 图像 / 视频的更广泛知识图谱。agentmemory 记住工作内容;这三个项目点亮上下文层的其余部分。组合配方和问题路由表:[`docs/recipes/pairings.md`](../docs/recipes/pairings.md)。 + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)内建 (CLAUDE.md)
类型记忆引擎 + MCP 服务器记忆层 API完整代理运行时静态文件
检索 R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
自动捕获12 hooks (零人工)手动调用 add()代理自编辑手动编辑
搜索BM25 + 向量 + 图 (RRF 融合)向量 + 图向量 (归档)将所有内容加载到上下文
多代理MCP + REST + 租约 + 信号API (无协调)仅在 Letta 运行时内部每代理一个文件
框架锁定无 (任何 MCP 客户端)无高 (必须使用 Letta)每代理格式
外部依赖无 (SQLite + iii-engine)Qdrant / pgvectorPostgres + 向量数据库无
记忆生命周期4 层整合 + 衰减 + 自动遗忘被动提取代理管理手动清理
Token 效率~1,900 tokens/会话 ($10/年)依集成方式不同核心记忆位于上下文240 条观测达 22K+ tokens
实时查看器是 (端口 3113)云端仪表板云端仪表板无
自托管是 (默认)可选可选是
+ +--- + +

Quick Start

+ +兼容性:此版本面向稳定的 `iii-sdk` `^0.11.0` 和 iii-engine v0.11.x。 + +### 30 秒体验 + +```bash +# 终端 1:启动服务器 +npx @agentmemory/agentmemory + +# 终端 2:注入示例数据并查看召回 +npx @agentmemory/agentmemory demo +``` + +`demo` 会注入 3 个真实会话(JWT 鉴权、N+1 查询修复、限流)并对它们执行语义搜索。你将看到搜索「数据库性能优化」时找到「N+1 查询修复」 — 关键词匹配做不到这一点。 + +打开 `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 +# 如果在 macOS/Linux 的系统 Node 上遇到 EACCES,请重试: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # 启动服务器(等同于 npx 形式) +agentmemory stop # 停止 +agentmemory remove # 卸载所有创建的内容 +agentmemory connect claude-code # 连接一个代理 +agentmemory doctor # 交互式诊断 + 修复提示 +``` + +从 v0.9.16 开始,首次 npx 运行会内联提示你全局安装 — 回答一次 `Y` 即可。如果你跳过,可使用以下任一方式获取最新版: + +```bash +npx -y @agentmemory/agentmemory@latest # 强制从 npm 拉取最新(跨平台) +rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # 仅 macOS/Linux (POSIX shell) +``` + +在 Windows / PowerShell 上,等价的缓存清除命令是 `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — 上面的 `npx -y ...@latest` 形式是跨平台选项。 + +### 会话回放 + +agentmemory 记录的每个会话都可回放。打开查看器,选择 **Replay** 标签,在时间线上拖动:提示词、工具调用、工具结果和响应都作为离散事件呈现,支持播放/暂停、速度控制(0.5×–4×)和键盘快捷键(空格切换,箭头单步)。 + +已有旧的 Claude Code JSONL 记录想导入? + +```bash +# 导入默认 ~/.claude/projects 下的全部内容 +npx @agentmemory/agentmemory import-jsonl + +# 或导入单个文件 +npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl +``` + +导入的会话与原生会话一起出现在 Replay 选择器中。底层每个条目都通过 `mem::replay::load`、`mem::replay::sessions`、`mem::replay::import-jsonl` 这些 iii 函数路由 — 没有侧通道服务器。 + +### 升级 / 维护 + +当你确实想更新本地运行时时,使用维护命令: + +```bash +npx @agentmemory/agentmemory upgrade +``` + +警告:此命令会变更当前工作空间/运行时。它可能更新 JavaScript 依赖,可能运行 `cargo install iii-engine --force`,也可能拉取 Docker 镜像。 + +实现细节见 `src/cli.ts`(参考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 + +### 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 路径) + +如果你直接通过 `~/.claude.json` 连接 agentmemory 的 MCP 服务器而不使用 `/plugin install`,Claude Code 永远不会解析 `${CLAUDE_PLUGIN_ROOT}`,你必须把 hook 脚本指向 `~/.claude/settings.json` 中的绝对路径。这些路径通常会嵌入 agentmemory 版本号(例如 `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`),因此下次升级会静默破坏所有 hooks([#508](https://github.com/rohitg00/agentmemory/issues/508))。 + +变通方法: + +```bash +agentmemory connect claude-code --with-hooks +``` + +这会将同样的 hook 命令合并到 `~/.claude/settings.json`,绝对路径解析到当前安装的 `@agentmemory/agentmemory` 包的 `plugin/` 目录。升级 agentmemory 后重新运行该命令以刷新路径。同一文件中的用户条目会被保留;只替换之前的 agentmemory 条目。仍然推荐使用 `/plugin install` 路径。 + +对于远程或受保护的部署,启动 Claude Code 时设置 `AGENTMEMORY_URL` 和 `AGENTMEMORY_SECRET`。插件会将两个值传递给其捆绑的 MCP 服务器;当 `AGENTMEMORY_URL` 为空时,MCP shim 默认使用 `http://localhost:3111`。 + +### Codex CLI(Codex 插件平台) + +```bash +# 1. 在单独终端启动记忆服务器 +npx @agentmemory/agentmemory + +# 2. 注册 agentmemory 市场并安装插件 +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 引擎会将 `CLAUDE_PLUGIN_ROOT` 注入 hook 子进程(参见 [`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 +``` + +这会在 `~/.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` + +在使用 `mcpServers` 结构的每个宿主(Cursor、Claude Desktop、Cline、Roo Code、Windsurf、Gemini CLI、OpenClaw)中,agentmemory 条目是**相同的 MCP 服务器块**: + +```json +"agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}" + } +} +``` + +**将此条目合并到宿主配置文件的现有 `mcpServers` 对象中** — 不要替换整个文件。如果文件已经有其他服务器,把 `agentmemory` 作为另一个 key 加在它们旁边。如果完全缺少 `mcpServers`,把整块粘贴到 `{ "mcpServers": { ... } }` 里。`${VAR}` 占位符会在 MCP 服务器启动时从 shell 继承 `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` — 未设置的变量传空字符串,shim 回退到 `http://localhost:3111`。一个接好的条目同时覆盖本地和远程(k8s / 反代)部署。 + +| 代理 | 配置文件 | 备注 | +|---|---|---| +| **Cursor** | `~/.cursor/mcp.json` | 合并到 `mcpServers`。网站上也提供一键深链。 | +| **Claude Desktop** | `claude_desktop_config.json` (Application Support) | 合并到 `mcpServers`。编辑后重启 Claude Desktop。 | +| **Cline / Roo Code / Kilo Code** | Cline MCP 设置 (设置 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 配置 | 同样的 `mcpServers` 块,或使用更深的[记忆插件](../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 个生命周期 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)** | `opencode.json` | 不同结构 — 顶层 `mcp` key,command 是数组:`{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`。 | +| **OpenCode (完整插件)** | `plugin/opencode/` | 22 个自动捕获 hooks,覆盖会话生命周期、消息、工具、错误。两个斜杠命令(`/recall`、`/remember`)。将 `plugin/opencode/` 复制到你的 OpenCode 工作空间并把插件条目添加到 `opencode.json`。完整 hook 表和差异分析见 [`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` 块。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 停服后使用。 | +| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` 写入用户级配置。工作空间覆盖放在你的代码旁的 `.kiro/settings/mcp.json` 中。 | +| **Goose** | Goose MCP 设置 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/)(快速开始 + 观测/召回流程)。`:3111` 上的 REST 对没有 iii 运行时的宿主仍然可用。 + +### 从源码构建 + +```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 尚未为此重构。重构落地后即解除固定。如果你已经手动迁移到沙盒模型,可用 `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`)。完整文档:[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. 在浏览器打开 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 +# (我们固定在 v0.11.2,直到 agentmemory 为 v0.11.6+ 引擎要求的 +# 新沙盒模型完成重构) +# 2. 下载 iii-x86_64-pc-windows-msvc.zip +# (如果是 ARM 机器则下载 iii-aarch64-pc-windows-msvc.zip) +# 3. 把 iii.exe 解压到 PATH 上的某处,或放在: +# %USERPROFILE%\.local\bin\iii.exe +# (agentmemory 会自动检查该位置) +# 4. 验证: +iii --version +# 应输出:0.11.2 + +# 5. 然后照常运行 agentmemory: +npx -y @agentmemory/agentmemory +``` + +**选项 B — Docker Desktop:** + +```powershell +# 1. 安装 Docker Desktop for Windows +# 2. 启动 Docker Desktop 并确保引擎运行中 +# 3. 运行 agentmemory — 它会自动启动捆绑的 compose 文件: +npx -y @agentmemory/agentmemory +``` + +**选项 C — 仅独立 MCP(无引擎):** 如果你只需要 MCP 工具供代理使用,不需要 REST API、查看器或定时任务,则完全跳过引擎: + +```powershell +npx -y @agentmemory/agentmemory mcp +# 或通过 shim 包: +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` 查看占用,然后 kill 或用 `--port ` | +| Docker 已安装但仍跳过回退 | 确保 Docker Desktop 确实在运行(系统托盘图标) | + +> 注意:没有 `cargo install iii-engine` — `iii` 未发布到 crates.io。唯一受支持的安装方式是上面的预构建二进制、上游 `sh` 安装脚本(仅 macOS/Linux)和 Docker 镜像。 + +--- + +

部署

+ +托管主机的一键模板。每个模板都附带自包含的 +Dockerfile,从 npm 拉取 `@agentmemory/agentmemory` 并从官方 +`iiidev/iii` Docker Hub 镜像复制 iii 引擎二进制 — 无需 +预构建 agentmemory 镜像。持久存储挂载在 +`/data`;首次启动 entrypoint 用面向部署调优的配置 +覆盖 npm 捆绑的 iii 配置(原配置绑定 `127.0.0.1`), +让其绑定 `0.0.0.0` 并使用绝对 `/data` 路径,生成 +HMAC secret,然后通过 `gosu` 从 `root` 降权到 `node` +再 exec agentmemory CLI。 + +

+ Deploy to fly.io + Deploy to Railway +

+ +Render 的一键部署按钮要求仓库根有 `render.yaml`,我们刻意保持根目录整洁。使用 [`deploy/render/`](../deploy/render/README.md) 中文档化的 Render 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 隧道模式。 + +--- + +

Why agentmemory

+ +每个编码代理在会话结束时都会忘记一切。你每次会话的前 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 + 向量 + 图 (仅 top-K) | +| Token 成本 | 240 条观测达 22K+ | ~1,900 tokens(少 92%) | +| 跨代理 | 每代理一个文件 | MCP + REST(任何代理) | +| 协调 | 无 | 租约、信号、动作、例程 | +| 可观测性 | 手动读文件 | 端口 3113 实时查看器 | + +--- + +

How It Works

+ +### 记忆流水线 + +```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(程序记忆)** | 工作流与决策模式 | 「怎么做」 | + +记忆随时间衰减(Ebbinghaus 曲线)。频繁访问的记忆会强化。陈旧记忆会自动清除。矛盾会被检测并解决。 + +### 捕获了什么 + +| Hook | 捕获内容 | +|------|----------| +| `SessionStart` | 项目路径、会话 ID | +| `UserPromptSubmit` | 用户提示词(隐私过滤) | +| `PreToolUse` | 文件访问模式 + 富化上下文 | +| `PostToolUse` | 工具名、输入、输出 | +| `PostToolUseFailure` | 错误上下文 | +| `PreCompact` | 在压缩前重新注入记忆 | +| `SubagentStart/Stop` | 子代理生命周期 | +| `Stop` | 会话结束摘要 | +| `SessionEnd` | 会话完成标记 | + +### 关键能力 + +| 能力 | 描述 | +|---|---| +| **自动捕获** | 每次工具使用都通过 hooks 记录 — 零人工 | +| **语义搜索** | BM25 + 向量 + 知识图谱,RRF 融合 | +| **记忆演化** | 版本控制、覆盖关系、关系图 | +| **自动遗忘** | TTL 过期、矛盾检测、重要性驱逐 | +| **隐私优先** | API key、secret、`` 标签存储前被剥离 | +| **自愈** | 熔断器、提供者回退链、健康监控 | +| **Claude 桥接** | 与 MEMORY.md 双向同步 | +| **知识图谱** | 实体抽取 + BFS 遍历 | +| **团队记忆** | 团队成员之间的命名空间共享 + 私有 | +| **引用溯源** | 任意记忆追溯到源观测 | +| **Git 快照** | 记忆状态的版本、回滚、diff | + +--- + + + +三路检索结合三种信号: + +| 流 | 作用 | 何时启用 | +|---|---|---| +| **BM25** | 词干化关键词匹配 + 同义词扩展 | 始终启用 | +| **Vector(向量)** | 稠密嵌入上的余弦相似度 | 配置了嵌入提供者 | +| **Graph(图)** | 通过实体匹配进行知识图谱遍历 | 查询中检测到实体 | + +通过 Reciprocal Rank Fusion (RRF, k=60) 融合,并按会话多样化(每会话最多 3 个结果)。 + +BM25 开箱即用支持希腊语、西里尔语、希伯来语、阿拉伯语和带音标的拉丁文分词。对于中文/日语/韩语记忆,安装可选分词器(`npm install @node-rs/jieba tiny-segmenter`)以把 CJK 串切分为词级 token;不安装的话,agentmemory 会软回退到整串分词并在 stderr 打印一次性提示。 + +### 嵌入提供者 + +agentmemory 自动检测你的提供者。为获得最佳效果,安装本地嵌入(免费): + +```bash +npm install @xenova/transformers +``` + +| 提供者 | 模型 | 成本 | 备注 | +|---|---|---|---| +| **本地 (推荐)** | `all-MiniLM-L6-v2` | 免费 | 离线,比仅 BM25 召回率高 +8pp | +| Gemini | `gemini-embedding-001` | 免费层 | 100+ 语言,768/1536/3072 维 (MRL),2048-token 输入。替换 `text-embedding-004`([已弃用,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 | 任意模型 | 视而定 | 多模型代理 | + +--- + +

MCP Server

+ +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 层整合 | +| `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` | 独占动作租约(多代理) | +| `memory_routine_run` | 实例化工作流例程 | +| `memory_signal_send` | 代理间消息 | +| `memory_signal_read` | 带回执读取消息 | +| `memory_checkpoint` | 外部条件门 | +| `memory_mesh_sync` | 实例间 P2P 同步 | +| `memory_sentinel_create` | 事件驱动监视器 | +| `memory_sentinel_trigger` | 外部触发哨兵 | +| `memory_sketch_create` | 临时动作图 | +| `memory_sketch_promote` | 提升为永久 | +| `memory_crystallize` | 紧凑化动作链 | +| `memory_diagnose` | 健康检查 | +| `memory_heal` | 自动修复卡住的状态 | +| `memory_facet_tag` | 维度:值 标签 | +| `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 # 规范命令(始终可用) +npx -y @agentmemory/mcp # shim 包别名 +``` + +或添加到你的代理的 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` 对象中,而非替换文件。对于无法访问宿主 `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/ +``` + +--- + +

Real-Time Viewer

+ +在端口 `3113` 自动启动。实时观测流、会话浏览器、记忆浏览器、知识图谱可视化和健康仪表板。 + +```bash +open http://localhost:3113 +``` + +查看器服务器默认绑定 `127.0.0.1`。REST 提供的 `/agentmemory/viewer` 端点遵循正常的 `AGENTMEMORY_SECRET` bearer-token 规则。CSP 头使用每响应 script nonce 并禁用内联处理器属性(`script-src-attr 'none'`)。 + +--- + +

iii Console

+ +`:3113` 上的查看器展示你的代理**记住了什么**。[iii 控制台](https://iii.dev/docs/console) 展示你的代理**做了什么** — 每个记忆操作都是 OpenTelemetry trace,每个 KV 条目都可编辑,每个函数都可调用,每个流都可挂载。同一记忆的两个窗口:一个面向产品,一个面向引擎。 + +观察一次 `memory_smart_search` 触发,在瀑布图中看到 BM25 扫描 → 嵌入查找 → RRF 融合 → 重排器。在 KV 浏览器中编辑卡住的整合计时器。用调整后的负载重放一个 `PostToolUse` hook。固定 WebSocket 流,实时观察观测落地。 + +agentmemory 免费提供这一切,因为每个函数、触发器、状态作用域、流都是 iii 原语 — 没有定制,没有需要插桩的地方。 + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ Workers 页面:每个已连接的 worker — 包括 agentmemory 本身 — 显示 PID、函数数、运行时和最后在线时间。 +

+ +**已经装好了。** 控制台随 `iii` 一同发布 — 无需单独安装器。 + +**与 agentmemory 并行启动:** + +```bash +# agentmemory 查看器占用端口 3113,所以在 3114 运行控制台。 +# 引擎 REST (3111)、WebSocket (3112)、bridge (49134) 默认值与 agentmemory 匹配。 +iii console --port 3114 +``` + +然后打开 `http://localhost:3114`。加 `--enable-flow` 开启实验性架构图页面。 + +仅在你移动了引擎端点时才覆盖: + +```bash +iii console --port 3114 \ + --engine-port 3111 \ + --ws-port 3112 \ + --bridge-port 49134 +``` + +**控制台能做什么:** + +| 页面 | 用途 | +|------|-----------| +| **Workers** | 查看每个已连接 worker 及其实时指标 — 包括 agentmemory worker 本身。 | +| **Functions** | 直接用 JSON 负载调用 agentmemory 的任何函数 — 测试 `memory.recall`、`memory.consolidate`、`graph.query` 无需接入客户端。 | +| **Triggers** | 重放 HTTP、cron、事件和状态触发器 — 手动触发整合 cron、重试 HTTP 路由、发出状态变化。 | +| **States** | 完整 CRUD 的 KV 浏览器 — 会话、记忆槽位、生命周期计时器、嵌入索引 — 就地编辑值。 | +| **Streams** | 记忆写入、hook 事件和观测更新流经 iii 流时的实时 WebSocket 监视器。 | +| **Queues** | 持久队列主题 + 死信管理。重放或丢弃失败的嵌入/压缩任务。 | +| **Traces** | OpenTelemetry 瀑布/火焰/服务分解视图。按 `trace_id` 过滤,精确查看单次 `memory.search` 产生了哪些函数、DB 调用和嵌入请求。 | +| **Logs** | 结构化 OTEL 日志,过滤并与 trace/span ID 关联。 | +| **Config** | 运行时配置 — 看到引擎正在使用的 workers、提供者和端口。 | +| **Flow** | (可选,`--enable-flow`) 每个 worker、触发器和流的交互式架构图。 | + +

+ iii console trace waterfall view showing per-span duration +
+ Traces:每个记忆操作的瀑布/火焰/服务分解。 +

+ +**Traces 已开启:** + +`iii-config.yaml` 出厂启用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 1.0`、指标 + 日志)。无需额外配置 — agentmemory 启动那一刻,每个记忆操作都会发出一个 trace span 和一个控制台可读的结构化日志。 + +如果你想改为导出到 Jaeger/Honeycomb/Grafana Tempo,把 `exporter: memory` 改为 `exporter: otlp` 并按 iii 的可观测性文档设置收集器端点。 + +> **提醒:** 控制台本身未强制鉴权 — 保持其绑定 `127.0.0.1`(默认)并永远不要对外暴露。 + +--- + +

Powered by iii

+ +agentmemory **本身就是一个运行中的 [iii](https://iii.dev) 实例**。函数、触发器、KV 状态、流、OTEL traces — 全部都是 iii 原语。你没有安装 Postgres、Redis、Express、pm2 或 Prometheus,因为 iii 替代了它们。 + +这意味着多一条命令就能为 agentmemory 增加一整套新能力。 + +### 一条命令扩展 agentmemory + +```bash +iii worker add iii-pubsub # 把记忆写入扇出到每个连接的实例 +iii worker add iii-cron # 定时整合、衰减扫描、快照轮换 +iii worker add iii-queue # 嵌入 + 压缩任务的持久重试 +iii worker add iii-observability # 每个记忆操作的 OTEL traces(默认开启) +iii worker add iii-sandbox # 在隔离 microVM 内运行召回到的代码 +iii worker add iii-database # 切换 SQL 后端的状态适配器 +iii worker add mcp # 在 agentmemory 的 MCP 旁开通用 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、指标、日志 — 从第一天起就接入 `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) | 当默认的内存 KV 不够用时,SQL 后端状态适配器 | +| [`mcp`](https://workers.iii.dev/workers/mcp) | 在 agentmemory 的旁边架设额外 MCP 服务器,共享同一引擎 | + +完整注册表:[workers.iii.dev](https://workers.iii.dev)。那里的每个 worker 都通过 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 监管 | +| Prometheus / Grafana | iii OTEL + 健康监控 | +| 自定义插件系统 | `iii worker add ` | + +**118 个源文件 · ~21,800 行代码 · 950+ 测试 · 123 个函数 · 34 个 KV 作用域** — 全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。 + +--- + +

Configuration

+ +### LLM 提供者 + +agentmemory 从你的环境自动检测。默认情况下,除非你配置提供者或显式启用 Claude 订阅回退,否则不会发起 LLM 调用。 + +| 提供者 | 配置 | 备注 | +|----------|--------|-------| +| **No-op(默认)** | 无需配置 | LLM 驱动的 compress/summarize 被禁用。合成 BM25 压缩 + 召回仍可用。如果你以前依赖 Claude 订阅回退,请见下面的 `AGENTMEMORY_ALLOW_AGENT_SDK`。 | +| Anthropic API | `ANTHROPIC_API_KEY` | 按 token 计费 | +| MiniMax | `MINIMAX_API_KEY` | Anthropic 兼容 | +| Gemini | `GEMINI_API_KEY` | 同时启用嵌入 | +| OpenRouter | `OPENROUTER_API_KEY` | 任意模型 | +| Claude 订阅回退 | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | 仅按需启用。会派生 `@anthropic-ai/claude-agent-sdk` 会话 — 曾导致无限 Stop-hook 递归(#149 后续)故不再默认。 | + +### 成本感知的模型选择 + +后台压缩在每次观测时运行,模型选择会显著影响月度支出。捕获的工作负载数据:635 次请求 / 888K tokens / 35 小时活跃使用,基于 2026-05-23 OpenRouter 定价对三个模型评测。 + +| 等级 | 模型 | 输入 / 1M | 输出 / 1M | 35 小时捕获工作负载成本 | 备注 | +|------|-------|------------|-------------|---------------------------|-------| +| 推荐 | `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 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` 控制召回是否按该标签过滤。 + +```env +TEAM_ID=company +USER_ID=engineering-team +AGENT_ID=architect +AGENTMEMORY_AGENT_SCOPE=isolated # 可选;默认 "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=` 来按请求覆盖,以及 `?agentId=*` 来完全跳过环境作用域。`/memories` 还接受 `?includeOrphans=true` 来浮现 `agentId` 为 undefined 的预-AGENT_ID 记忆。 + +SDK / REST 层的按调用覆盖:每个修改端点(`/session/start`、`/remember`)都接受请求体中的 `agentId` 字段,胜过环境变量。对于在一个服务器进程中路由多角色的运行时很有用。 + +当 `AGENT_ID` 未设置时,记忆保持无作用域(遗留行为,无标签、无过滤)。 + +### 端口 + +agentmemory + iii-engine 默认绑定四个端口。如果重启失败并显示 `port in use`,这张表告诉你该查找什么进程。 + +| 端口 | 进程 | 用途 | 环境覆盖 | +|------|---------|---------|--------------| +| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` | +| `3112` | iii-engine | 内部流 worker(由 agentmemory + 查看器消费) | `III_STREAMS_PORT` | +| `3113` | agentmemory | 实时查看器(`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` | +| `49134` | iii-engine | WebSocket — workers 在此注册,OTel 遥测在此流过 | `III_ENGINE_URL`(完整 URL,默认 `ws://localhost:49134`) | + +崩溃后端口仍被占用时的陈旧进程清理: + +```bash +# macOS / Linux — 查找每个端口上的进程并杀掉 +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` 在优雅关闭时干净地回收 worker 和 engine pidfile(#640、#474)。上面的手动清理仅针对崩溃后两个 pidfile 都未留下的情况。 + +### 配置文件 + +把 agentmemory 运行时配置放到 `~/.agentmemory/.env`,而不是在每个 shell 中 export 变量。如果查看器显示像 `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 key 测试,显式启用: + +```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 +``` + +--- + +

API

+ +端口 `3111` 上的 124 个端点。REST API 默认绑定 `127.0.0.1`。当 `AGENTMEMORY_SECRET` 已设置时,受保护端点需要 `Authorization: Bearer `,网状同步端点要求两端都设置 `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` | 文件上下文 + 记忆 + bugs | +| `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) + +
+ +--- + +

Development

+ +```bash +npm run dev # 热重载 +npm run build # 生产构建 +npm test # 950+ 测试 +npm run test:integration # API 测试(需要服务运行中) +``` + +**先决条件:** Node.js >= 20、[iii-engine](https://iii.dev/docs) 或 Docker + +

License

+ +[Apache-2.0](../LICENSE) diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md new file mode 100644 index 0000000000000000000000000000000000000000..ace349b7e03dc6966068cb41071284d19fdee0a5 --- /dev/null +++ b/READMEs/README.zh-TW.md @@ -0,0 +1,1378 @@ +

+ agentmemory — 為 AI 編碼代理提供持久化記憶 +

+ +

+ + 讓你的編碼代理記住一切。不再重複解釋。 + Built on iii engine +
+ 為 Claude Code、Cursor、Gemini CLI、Codex CLI、Hermes、OpenClaw、pi、OpenCode 以及任何 MCP 用戶端提供持久化記憶。 +

+ +

+ English | + 简体中文 | + 繁體中文 | + 日本語 | + 한국어 | + Español | + Türkçe | + Русский | + हिन्दी | + Português | + Français | + Deutsch +

+ +

+ rohitg00/agentmemory | Trendshift +

+ +

+ + + + + Star History Chart + + +

+ +

+ Design doc: 1200 stars / 172 forks on the gist +

+ +

+ 這份 gist 以信心評分、生命週期管理、知識圖譜和混合搜尋擴展了 Karpathy 的 LLM Wiki 模式:agentmemory 就是其實作。 +

+ +

+ npm version + npm downloads + CI + License + Stars +

+ +

+ 95.2% retrieval R@5 + 92% fewer tokens + 53 MCP tools + 12 auto hooks + 0 external DBs + 950+ tests passing +

+ +

+ agentmemory demo +

+ +

+ 安裝 • + 快速開始 • + 基準測試 • + 對比競品 • + 代理 • + 運作原理 • + MCP • + 檢視器 • + iii 主控台 • + 由 iii 驅動 • + 設定 • + API +

+ +--- + +## 安裝 + +```bash +npm install -g @agentmemory/agentmemory # 一次安裝 — 全域可用 `agentmemory` 指令 +# 如果在 macOS/Linux 的系統 Node 上遇到 EACCES,請重試: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # 在 :3111 啟動記憶伺服器 +agentmemory demo # 注入範例會話並驗證召回 +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)。 + +--- + +

Works with every agent

+ +agentmemory 相容任何支援 hooks、MCP 或 REST API 的代理。所有代理共享同一個記憶伺服器。 + + + + + + + + + + + + + + + + + + + + + + +
+Claude Code
+Claude Code
+原生外掛 + 12 hooks + MCP +
+Codex CLI
+Codex CLI
+原生外掛 + 6 hooks + MCP +
+OpenClaw
+OpenClaw
+原生外掛 + MCP +
+Hermes
+Hermes
+原生外掛 + MCP +
+pi
+pi
+原生外掛 + MCP +
+OpenHuman
+OpenHuman
+原生 Memory trait 後端 +
+Cursor
+Cursor
+MCP 伺服器 +
+Gemini CLI
+Gemini CLI
+MCP 伺服器 +
+OpenCode
+OpenCode
+22 hooks + MCP + 外掛 +
+Cline
+Cline
+MCP 伺服器 +
+Goose
+Goose
+MCP 伺服器 +
+Kilo Code
+Kilo Code
+MCP 伺服器 +
+Aider
+Aider
+REST API +
+Claude Desktop
+Claude Desktop
+MCP 伺服器 +
+Windsurf
+Windsurf
+MCP 伺服器 +
+Roo Code
+Roo Code
+MCP 伺服器 +
+ +

+ 相容任何使用 MCP 或 HTTP 的代理。一個伺服器,所有代理共享記憶。 +

+ +--- + +你每次會話都在重複解釋同樣的架構。你反覆發現同樣的 bug。你重複教同樣的偏好。內建的記憶(CLAUDE.md、.cursorrules)上限是 200 行而且會過期。agentmemory 解決了這個問題。它在背景靜默捕捉代理的行為,將其壓縮為可搜尋的記憶,並在下次會話開始時注入正確的上下文。一條指令。跨代理工作。 + +**改變了什麼:** 會話 1 你設定了 JWT 驗證。會話 2 你要求限流。代理已經知道你的驗證使用 `src/middleware/auth.ts` 中的 jose middleware,測試覆蓋了 token 驗證,你選擇 jose 而非 jsonwebtoken 是為了 Edge 相容性。無需重新解釋。無需複製貼上。代理就是*知道*。 + +```bash +npx @agentmemory/agentmemory +``` + +> **v0.9.0 新功能** — 著陸頁 [agent-memory.dev](https://agent-memory.dev) 上線,檔案系統連接器(`@agentmemory/fs-watcher`),獨立 MCP 現在代理至執行中的伺服器,使 hooks 和檢視器保持一致,稽核策略在所有刪除路徑上得到統一,健康狀態在小型 Node 行程上不再誤報 `memory_critical`。完整變更見 [CHANGELOG.md](../CHANGELOG.md#090--2026-04-18)。 + +--- + +

Benchmarks

+ + + + + + +
+ +### 檢索準確率 + +**coding-agent-life-v1** (內部語料庫,沙盒可重現) + +| 適配器 | P@5 | R@5 | Top-5 命中率 | p50 延遲 | +|---|---|---|---|---| +| **agentmemory 混合** | **0.578** | **0.967** | **15 / 15** | 14 ms | +| grep 基線 | 0.267 | 0.967 | 15 / 15 | 0 ms | + +100% Top-5 命中率。在相同輸入下,精確度比 grep 基線高 **2.2×**。完整依類型分解:[`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%** | +| 僅 BM25 回退 | 86.2% | 94.6% | 71.5% | + + + +### Token 節省 + +| 方法 | Token/年 | 成本/年 | +|---|---|---| +| 貼上完整上下文 | 19.5M+ | 不可能(超出窗口) | +| LLM 摘要 | ~650K | ~$500 | +| **agentmemory** | **~170K** | **~$10** | +| agentmemory + 本地嵌入 | ~170K | **$0** | + +
+ +> 嵌入模型:`all-MiniLM-L6-v2`(本地、免費、無需 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。 + +**在地重現:** [`eval/README.md`](../eval/README.md) — 適配器可插拔的 harness,支援 LongMemEval `_s`(公開 500 問)+ `coding-agent-life-v1`(內部 15 會話語料)。Grep / 向量 / 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) 使用。** 程式碼圖索引、多代理建置流水線,以及跨文件 / PDF / 圖片 / 影片的更廣泛知識圖譜。agentmemory 記住工作內容;這三個專案點亮上下文層其餘部分。組合配方與問題路由表:[`docs/recipes/pairings.md`](../docs/recipes/pairings.md)。 + +--- + +

vs Competitors

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
agentmemorymem0 (53K ⭐)Letta / MemGPT (22K ⭐)內建 (CLAUDE.md)
類型記憶引擎 + MCP 伺服器記憶層 API完整代理執行階段靜態檔案
檢索 R@595.2%68.5% (LoCoMo)83.2% (LoCoMo)N/A (grep)
自動捕捉12 hooks(零人工)手動呼叫 add()代理自編輯手動編輯
搜尋BM25 + 向量 + 圖(RRF 融合)向量 + 圖向量(歸檔)把所有內容載入上下文
多代理MCP + REST + 租約 + 訊號API(無協調)僅在 Letta 執行階段內部每個代理一個檔案
框架鎖定無(任何 MCP 用戶端)無高(必須使用 Letta)每個代理格式
外部相依無(SQLite + iii-engine)Qdrant / pgvectorPostgres + 向量資料庫無
記憶生命週期4 層整合 + 衰減 + 自動遺忘被動擷取代理管理手動清理
Token 效率~1,900 tokens/會話 ($10/年)依整合方式不同核心記憶位於上下文240 條觀測達 22K+ tokens
即時檢視器是(連接埠 3113)雲端儀表板雲端儀表板無
自架是(預設)選用選用是
+ +--- + +

Quick Start

+ +相容性:此版本面向穩定的 `iii-sdk` `^0.11.0` 和 iii-engine v0.11.x。 + +### 30 秒體驗 + +```bash +# 終端 1:啟動伺服器 +npx @agentmemory/agentmemory + +# 終端 2:注入範例資料並查看召回 +npx @agentmemory/agentmemory demo +``` + +`demo` 會注入 3 個真實會話(JWT 驗證、N+1 查詢修正、限流)並對它們執行語義搜尋。你將看到搜尋「資料庫效能最佳化」時找到「N+1 查詢修正」 — 關鍵字比對做不到這一點。 + +打開 `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 +# 如果在 macOS/Linux 的系統 Node 上遇到 EACCES,請重試: +# sudo npm install -g @agentmemory/agentmemory +agentmemory # 啟動伺服器(等同 npx 形式) +agentmemory stop # 停止 +agentmemory remove # 解除安裝所有建立的內容 +agentmemory connect claude-code # 連接一個代理 +agentmemory doctor # 互動式診斷 + 修復提示 +``` + +從 v0.9.16 開始,首次 npx 執行會以行內方式提示你全域安裝 — 回答一次 `Y` 即可。若你跳過,可使用以下任一方式取得最新版本: + +```bash +npx -y @agentmemory/agentmemory@latest # 強制從 npm 拉取最新(跨平台) +rm -rf ~/.npm/_npx && npx @agentmemory/agentmemory # 僅 macOS/Linux (POSIX shell) +``` + +在 Windows / PowerShell 上,等價的快取清除指令是 `Remove-Item -Recurse -Force "$env:LOCALAPPDATA\npm-cache\_npx"` — 上面的 `npx -y ...@latest` 形式是跨平台選項。 + +### 會話重播 + +agentmemory 紀錄的每個會話都可重播。打開檢視器,選擇 **Replay** 標籤,在時間軸上拖動:提示、工具呼叫、工具結果和回應都以離散事件呈現,支援播放/暫停、速度控制(0.5×–4×)和鍵盤快捷鍵(空白鍵切換,方向鍵單步)。 + +已有舊的 Claude Code JSONL 紀錄想匯入? + +```bash +# 匯入預設 ~/.claude/projects 下的全部內容 +npx @agentmemory/agentmemory import-jsonl + +# 或匯入單一檔案 +npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl +``` + +匯入的會話與原生會話一同出現在 Replay 選擇器中。底層每個條目都透過 `mem::replay::load`、`mem::replay::sessions`、`mem::replay::import-jsonl` 這些 iii 函式路由 — 沒有側通道伺服器。 + +### 升級 / 維護 + +當你確實想更新本地執行階段時,使用維護指令: + +```bash +npx @agentmemory/agentmemory upgrade +``` + +警告:此指令會變更目前工作區/執行階段。它可能更新 JavaScript 相依、可能執行 `cargo install iii-engine --force`、也可能拉取 Docker 鏡像。 + +實作細節見 `src/cli.ts`(參考 `src/cli.ts:544-595` 附近的 `runUpgrade`)。 + +### 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 路徑) + +若你直接透過 `~/.claude.json` 連接 agentmemory 的 MCP 伺服器而非使用 `/plugin install`,Claude Code 永遠不會解析 `${CLAUDE_PLUGIN_ROOT}`,你必須把 hook 腳本指向 `~/.claude/settings.json` 中的絕對路徑。這些路徑通常會嵌入 agentmemory 版本號(例如 `~/.codex/plugins/cache/agentmemory/agentmemory/0.9.21/scripts/…`),因此下次升級會靜默破壞所有 hooks([#508](https://github.com/rohitg00/agentmemory/issues/508))。 + +變通方法: + +```bash +agentmemory connect claude-code --with-hooks +``` + +這會把同樣的 hook 指令合併到 `~/.claude/settings.json`,絕對路徑解析到目前安裝的 `@agentmemory/agentmemory` 套件的 `plugin/` 目錄。升級 agentmemory 後重新執行該指令以重新整理路徑。同一檔案中的使用者條目會被保留;只取代之前的 agentmemory 條目。仍然推薦使用 `/plugin install` 路徑。 + +對於遠端或受保護的部署,啟動 Claude Code 時設定 `AGENTMEMORY_URL` 和 `AGENTMEMORY_SECRET`。外掛會把這兩個值傳遞給其捆綁的 MCP 伺服器;當 `AGENTMEMORY_URL` 為空時,MCP shim 預設使用 `http://localhost:3111`。 + +### Codex CLI(Codex 外掛平台) + +```bash +# 1. 在另一個終端啟動記憶伺服器 +npx @agentmemory/agentmemory + +# 2. 註冊 agentmemory 市集並安裝外掛 +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 引擎會把 `CLAUDE_PLUGIN_ROOT` 注入 hook 子行程(參見 [`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 +``` + +這會在 `~/.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` + +在使用 `mcpServers` 結構的每個宿主(Cursor、Claude Desktop、Cline、Roo Code、Windsurf、Gemini CLI、OpenClaw)中,agentmemory 條目是**相同的 MCP 伺服器區塊**: + +```json +"agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}" + } +} +``` + +**把此條目合併到宿主設定檔現有的 `mcpServers` 物件中** — 不要取代整個檔案。若檔案已有其他伺服器,把 `agentmemory` 作為另一個 key 加在它們旁邊。若完全缺少 `mcpServers`,把整個區塊貼到 `{ "mcpServers": { ... } }` 裡。`${VAR}` 佔位符會在 MCP 伺服器啟動時從 shell 繼承 `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` — 未設定的變數傳空字串,shim 回退到 `http://localhost:3111`。一個接好的條目同時涵蓋本地和遠端(k8s / 反向代理)部署。 + +| 代理 | 設定檔 | 備註 | +|---|---|---| +| **Cursor** | `~/.cursor/mcp.json` | 合併到 `mcpServers`。網站上也提供一鍵深層連結。 | +| **Claude Desktop** | `claude_desktop_config.json`(Application Support) | 合併到 `mcpServers`。編輯後重新啟動 Claude Desktop。 | +| **Cline / Roo Code / Kilo Code** | Cline MCP 設定(設定 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 設定 | 同樣的 `mcpServers` 區塊,或使用更深的[記憶外掛](../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 個生命週期 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)** | `opencode.json` | 不同結構 — 頂層 `mcp` key,command 是陣列:`{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`。 | +| **OpenCode(完整外掛)** | `plugin/opencode/` | 22 個自動捕捉 hooks,涵蓋會話生命週期、訊息、工具、錯誤。兩個斜線指令(`/recall`、`/remember`)。把 `plugin/opencode/` 複製到你的 OpenCode 工作區並把外掛條目新增到 `opencode.json`。完整 hook 表與差異分析見 [`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` 區塊。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 停止服務後使用。 | +| **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` 寫入使用者層級設定。工作區覆寫放在你的程式碼旁的 `.kiro/settings/mcp.json` 中。 | +| **Goose** | Goose MCP 設定 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/)(快速開始 + 觀測/召回流程)。`:3111` 上的 REST 對沒有 iii 執行階段的宿主仍可用。 + +### 從原始碼建置 + +```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 尚未為此重構。重構落地後即解除釘版。若你已手動遷移到沙盒模型,可用 `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`)。完整文件:[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. 在瀏覽器打開 https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 +# (我們釘在 v0.11.2,直到 agentmemory 為 v0.11.6+ 引擎需求的 +# 新沙盒模型完成重構) +# 2. 下載 iii-x86_64-pc-windows-msvc.zip +# (若是 ARM 機器則下載 iii-aarch64-pc-windows-msvc.zip) +# 3. 把 iii.exe 解壓到 PATH 上的某處,或放在: +# %USERPROFILE%\.local\bin\iii.exe +# (agentmemory 會自動檢查該位置) +# 4. 驗證: +iii --version +# 應輸出:0.11.2 + +# 5. 然後照常執行 agentmemory: +npx -y @agentmemory/agentmemory +``` + +**選項 B — Docker Desktop:** + +```powershell +# 1. 安裝 Docker Desktop for Windows +# 2. 啟動 Docker Desktop 並確保引擎執行中 +# 3. 執行 agentmemory — 它會自動啟動捆綁的 compose 檔: +npx -y @agentmemory/agentmemory +``` + +**選項 C — 僅獨立 MCP(無引擎):** 若你只需要 MCP 工具供代理使用,不需要 REST API、檢視器或定時工作,則完全跳過引擎: + +```powershell +npx -y @agentmemory/agentmemory mcp +# 或透過 shim 套件: +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` 查看佔用,然後 kill 或用 `--port ` | +| Docker 已安裝但仍跳過回退 | 確保 Docker Desktop 確實在執行(系統匣圖示) | + +> 注意:沒有 `cargo install iii-engine` — `iii` 未發布到 crates.io。唯一受支援的安裝方式是上述預建二進位、上游 `sh` 安裝指令稿(僅 macOS/Linux)和 Docker 鏡像。 + +--- + +

部署

+ +託管主機的一鍵範本。每個範本都附帶自含的 +Dockerfile,從 npm 拉取 `@agentmemory/agentmemory` 並從官方 +`iiidev/iii` Docker Hub 鏡像複製 iii 引擎二進位 — 無需 +預建 agentmemory 鏡像。持久儲存掛載在 +`/data`;首次啟動 entrypoint 用面向部署調校的設定 +覆寫 npm 捆綁的 iii 設定(原設定繫結 `127.0.0.1`), +讓其繫結 `0.0.0.0` 並使用絕對 `/data` 路徑,產生 +HMAC secret,然後透過 `gosu` 從 `root` 降權到 `node` +再 exec agentmemory CLI。 + +

+ Deploy to fly.io + Deploy to Railway +

+ +Render 的一鍵部署按鈕要求倉庫根有 `render.yaml`,我們刻意保持根目錄整潔。使用 [`deploy/render/`](../deploy/render/README.md) 中文件化的 Render 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 隧道模式。 + +--- + +

Why agentmemory

+ +每個編碼代理在會話結束時都會忘記一切。你每次會話的前 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 + 向量 + 圖(僅 top-K) | +| Token 成本 | 240 條觀測達 22K+ | ~1,900 tokens(少 92%) | +| 跨代理 | 每個代理一個檔案 | MCP + REST(任何代理) | +| 協調 | 無 | 租約、訊號、動作、例程 | +| 可觀測性 | 手動讀檔 | 連接埠 3113 即時檢視器 | + +--- + +

How It Works

+ +### 記憶流水線 + +```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(程序記憶)** | 工作流與決策模式 | 「怎麼做」 | + +記憶隨時間衰減(Ebbinghaus 曲線)。頻繁存取的記憶會強化。陳舊記憶會自動清除。矛盾會被偵測並解決。 + +### 捕捉了什麼 + +| Hook | 捕捉內容 | +|------|----------| +| `SessionStart` | 專案路徑、會話 ID | +| `UserPromptSubmit` | 使用者提示(隱私過濾) | +| `PreToolUse` | 檔案存取模式 + 富化上下文 | +| `PostToolUse` | 工具名、輸入、輸出 | +| `PostToolUseFailure` | 錯誤上下文 | +| `PreCompact` | 在壓縮前重新注入記憶 | +| `SubagentStart/Stop` | 子代理生命週期 | +| `Stop` | 會話結束摘要 | +| `SessionEnd` | 會話完成標記 | + +### 關鍵能力 + +| 能力 | 描述 | +|---|---| +| **自動捕捉** | 每次工具使用都透過 hooks 記錄 — 零人工 | +| **語意搜尋** | BM25 + 向量 + 知識圖譜,RRF 融合 | +| **記憶演化** | 版本控制、覆寫關係、關係圖 | +| **自動遺忘** | TTL 過期、矛盾偵測、重要性驅逐 | +| **隱私優先** | API key、secret、`` 標籤儲存前被剝除 | +| **自癒** | 熔斷器、提供者回退鏈、健康監控 | +| **Claude 橋接** | 與 MEMORY.md 雙向同步 | +| **知識圖譜** | 實體擷取 + BFS 走訪 | +| **團隊記憶** | 團隊成員之間的命名空間共享 + 私有 | +| **引用溯源** | 任意記憶追溯到來源觀測 | +| **Git 快照** | 記憶狀態的版本、回滾、diff | + +--- + + + +三路檢索結合三種訊號: + +| 流 | 功用 | 何時啟用 | +|---|---|---| +| **BM25** | 詞幹化關鍵字比對 + 同義詞擴展 | 始終啟用 | +| **Vector(向量)** | 稠密嵌入上的餘弦相似度 | 已設定嵌入提供者 | +| **Graph(圖)** | 透過實體比對進行知識圖譜走訪 | 查詢中偵測到實體 | + +透過 Reciprocal Rank Fusion (RRF, k=60) 融合,並按會話多樣化(每個會話最多 3 個結果)。 + +BM25 開箱即用支援希臘文、西里爾文、希伯來文、阿拉伯文和帶音標拉丁文的分詞。對於中文/日文/韓文記憶,安裝可選分詞器(`npm install @node-rs/jieba tiny-segmenter`)以把 CJK 串切分為詞級 token;若未安裝,agentmemory 會軟回退到整串分詞並在 stderr 印出一次性提示。 + +### 嵌入提供者 + +agentmemory 自動偵測你的提供者。為獲得最佳效果,安裝本地嵌入(免費): + +```bash +npm install @xenova/transformers +``` + +| 提供者 | 模型 | 成本 | 備註 | +|---|---|---|---| +| **本地(推薦)** | `all-MiniLM-L6-v2` | 免費 | 離線,比僅 BM25 召回率高 +8pp | +| Gemini | `gemini-embedding-001` | 免費層 | 100+ 語言,768/1536/3072 維 (MRL),2048-token 輸入。取代 `text-embedding-004`([已棄用,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 | 任意模型 | 視情況 | 多模型代理 | + +--- + +

MCP Server

+ +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 層整合 | +| `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` | 獨佔動作租約(多代理) | +| `memory_routine_run` | 實例化工作流例程 | +| `memory_signal_send` | 代理之間的訊息 | +| `memory_signal_read` | 帶回執讀取訊息 | +| `memory_checkpoint` | 外部條件閘門 | +| `memory_mesh_sync` | 實例之間 P2P 同步 | +| `memory_sentinel_create` | 事件驅動監視器 | +| `memory_sentinel_trigger` | 外部觸發哨兵 | +| `memory_sketch_create` | 暫時動作圖 | +| `memory_sketch_promote` | 提升為永久 | +| `memory_crystallize` | 緊湊化動作鏈 | +| `memory_diagnose` | 健康檢查 | +| `memory_heal` | 自動修復卡住的狀態 | +| `memory_facet_tag` | 維度:值 標籤 | +| `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 # 標準指令(始終可用) +npx -y @agentmemory/mcp # shim 套件別名 +``` + +或新增到你的代理的 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` 物件中,而非取代檔案。對於無法存取宿主 `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/ +``` + +--- + +

Real-Time Viewer

+ +在連接埠 `3113` 自動啟動。即時觀測流、會話瀏覽器、記憶瀏覽器、知識圖譜視覺化和健康儀表板。 + +```bash +open http://localhost:3113 +``` + +檢視器伺服器預設繫結 `127.0.0.1`。REST 提供的 `/agentmemory/viewer` 端點遵循正常的 `AGENTMEMORY_SECRET` bearer-token 規則。CSP 標頭使用每回應 script nonce 並停用行內處理常式屬性(`script-src-attr 'none'`)。 + +--- + +

iii Console

+ +`:3113` 上的檢視器展示你的代理**記住了什麼**。[iii 主控台](https://iii.dev/docs/console) 展示你的代理**做了什麼** — 每個記憶操作都是 OpenTelemetry trace,每個 KV 條目都可編輯,每個函式都可呼叫,每個串流都可掛載。同一記憶的兩個視窗:一個面向產品,一個面向引擎。 + +觀察一次 `memory_smart_search` 觸發,在瀑布圖中看到 BM25 掃描 → 嵌入查找 → RRF 融合 → 重新排序器。在 KV 瀏覽器中編輯卡住的整合計時器。用調整後的負載重播一個 `PostToolUse` hook。釘選 WebSocket 串流,即時觀察觀測落地。 + +agentmemory 免費提供這一切,因為每個函式、觸發器、狀態範圍、串流都是 iii 原語 — 沒有自訂、沒有需要插樁的地方。 + +

+ iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata +
+ Workers 頁面:每個已連接 worker — 包括 agentmemory 本身 — 顯示 PID、函式數、執行階段和最後在線時間。 +

+ +**已經裝好了。** 主控台隨 `iii` 一同發布 — 無需獨立安裝器。 + +**與 agentmemory 並行啟動:** + +```bash +# agentmemory 檢視器佔用連接埠 3113,所以在 3114 執行主控台。 +# 引擎 REST (3111)、WebSocket (3112)、bridge (49134) 預設值與 agentmemory 相符。 +iii console --port 3114 +``` + +然後打開 `http://localhost:3114`。加 `--enable-flow` 開啟實驗性架構圖頁面。 + +僅在你已移動引擎端點時才覆寫: + +```bash +iii console --port 3114 \ + --engine-port 3111 \ + --ws-port 3112 \ + --bridge-port 49134 +``` + +**主控台能做什麼:** + +| 頁面 | 用途 | +|------|-----------| +| **Workers** | 查看每個已連接 worker 及其即時指標 — 包括 agentmemory worker 本身。 | +| **Functions** | 直接以 JSON 負載呼叫 agentmemory 的任何函式 — 測試 `memory.recall`、`memory.consolidate`、`graph.query` 無需接入用戶端。 | +| **Triggers** | 重播 HTTP、cron、事件和狀態觸發器 — 手動觸發整合 cron、重試 HTTP 路由、發出狀態變更。 | +| **States** | 完整 CRUD 的 KV 瀏覽器 — 會話、記憶槽位、生命週期計時器、嵌入索引 — 就地編輯值。 | +| **Streams** | 記憶寫入、hook 事件和觀測更新流經 iii 串流時的即時 WebSocket 監視器。 | +| **Queues** | 持久佇列主題 + 死信管理。重播或捨棄失敗的嵌入/壓縮工作。 | +| **Traces** | OpenTelemetry 瀑布/火焰/服務分解視圖。按 `trace_id` 過濾,精確查看單次 `memory.search` 產生了哪些函式、DB 呼叫和嵌入請求。 | +| **Logs** | 結構化 OTEL 日誌,過濾並與 trace/span ID 關聯。 | +| **Config** | 執行階段設定 — 看到引擎正在使用的 workers、提供者和連接埠。 | +| **Flow** | (選用,`--enable-flow`)每個 worker、觸發器和串流的互動式架構圖。 | + +

+ iii console trace waterfall view showing per-span duration +
+ Traces:每個記憶操作的瀑布/火焰/服務分解。 +

+ +**Traces 已開啟:** + +`iii-config.yaml` 出廠啟用 `iii-observability` worker(`exporter: memory`、`sampling_ratio: 1.0`、指標 + 日誌)。無需額外設定 — agentmemory 啟動那一刻,每個記憶操作都會發出一個 trace span 和一個主控台可讀的結構化日誌。 + +若你想改為匯出到 Jaeger/Honeycomb/Grafana Tempo,把 `exporter: memory` 改為 `exporter: otlp` 並依 iii 的可觀測性文件設定收集器端點。 + +> **提醒:** 主控台本身未強制驗證 — 保持其繫結 `127.0.0.1`(預設)並永遠不要對外暴露。 + +--- + +

Powered by iii

+ +agentmemory **本身就是一個執行中的 [iii](https://iii.dev) 實例**。函式、觸發器、KV 狀態、串流、OTEL traces — 全部都是 iii 原語。你沒有安裝 Postgres、Redis、Express、pm2 或 Prometheus,因為 iii 取代了它們。 + +這代表多一條指令就能為 agentmemory 增加一整套新能力。 + +### 一條指令擴展 agentmemory + +```bash +iii worker add iii-pubsub # 把記憶寫入扇出到每個連接的實例 +iii worker add iii-cron # 排程整合、衰減掃描、快照輪替 +iii worker add iii-queue # 嵌入 + 壓縮工作的持久重試 +iii worker add iii-observability # 每個記憶操作的 OTEL traces(預設開啟) +iii worker add iii-sandbox # 在隔離 microVM 內執行召回到的程式碼 +iii worker add iii-database # 切換 SQL 後端的狀態適配器 +iii worker add mcp # 在 agentmemory 的 MCP 旁開設通用 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、指標、日誌 — 從第一天起就接入 `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) | 當預設的記憶體 KV 不夠用時,SQL 後端狀態適配器 | +| [`mcp`](https://workers.iii.dev/workers/mcp) | 在 agentmemory 的旁邊架設額外 MCP 伺服器,共享同一引擎 | + +完整登錄表:[workers.iii.dev](https://workers.iii.dev)。那裡的每個 worker 都透過 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 監管 | +| Prometheus / Grafana | iii OTEL + 健康監控 | +| 自訂外掛系統 | `iii worker add ` | + +**118 個原始檔 · ~21,800 行程式碼 · 950+ 測試 · 123 個函式 · 34 個 KV 範圍** — 全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。 + +--- + +

Configuration

+ +### LLM 提供者 + +agentmemory 從你的環境自動偵測。預設情況下,除非你設定提供者或明確啟用 Claude 訂閱回退,否則不會發起 LLM 呼叫。 + +| 提供者 | 設定 | 備註 | +|----------|--------|-------| +| **No-op(預設)** | 無需設定 | LLM 驅動的 compress/summarize 被停用。合成 BM25 壓縮 + 召回仍可用。若你以前依賴 Claude 訂閱回退,請見下面的 `AGENTMEMORY_ALLOW_AGENT_SDK`。 | +| Anthropic API | `ANTHROPIC_API_KEY` | 依 token 計費 | +| MiniMax | `MINIMAX_API_KEY` | Anthropic 相容 | +| Gemini | `GEMINI_API_KEY` | 同時啟用嵌入 | +| OpenRouter | `OPENROUTER_API_KEY` | 任意模型 | +| Claude 訂閱回退 | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | 僅按需啟用。會衍生 `@anthropic-ai/claude-agent-sdk` 會話 — 曾導致無限 Stop-hook 遞迴(#149 後續)故不再預設。 | + +### 成本感知的模型選擇 + +背景壓縮在每次觀測時執行,模型選擇會顯著影響月支出。擷取的工作負載資料:635 次請求 / 888K tokens / 35 小時活躍使用,基於 2026-05-23 OpenRouter 定價對三個模型評測。 + +| 等級 | 模型 | 輸入 / 1M | 輸出 / 1M | 35 小時擷取工作負載成本 | 備註 | +|------|-------|------------|-------------|---------------------------|-------| +| 推薦 | `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 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` 控制召回是否依該標籤過濾。 + +```env +TEAM_ID=company +USER_ID=engineering-team +AGENT_ID=architect +AGENTMEMORY_AGENT_SCOPE=isolated # 選填;預設 "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=` 來依請求覆寫,以及 `?agentId=*` 來完全跳過環境範圍。`/memories` 還接受 `?includeOrphans=true` 來浮現 `agentId` 為 undefined 的 pre-AGENT_ID 記憶。 + +SDK / REST 層的依呼叫覆寫:每個變更端點(`/session/start`、`/remember`)都接受請求體中的 `agentId` 欄位,勝過環境變數。對於在一個伺服器行程中路由多角色的執行階段很有用。 + +當 `AGENT_ID` 未設定時,記憶保持無範圍(舊行為,無標籤、無過濾)。 + +### 連接埠 + +agentmemory + iii-engine 預設繫結四個連接埠。若重啟失敗並顯示 `port in use`,這張表告訴你該查找什麼行程。 + +| 連接埠 | 行程 | 用途 | 環境覆寫 | +|------|---------|---------|--------------| +| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` | +| `3112` | iii-engine | 內部串流 worker(由 agentmemory + 檢視器消費) | `III_STREAMS_PORT` | +| `3113` | agentmemory | 即時檢視器(`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` | +| `49134` | iii-engine | WebSocket — workers 在此註冊,OTel 遙測在此流過 | `III_ENGINE_URL`(完整 URL,預設 `ws://localhost:49134`) | + +當機後連接埠仍被佔用時的陳舊行程清理: + +```bash +# macOS / Linux — 找出每個連接埠上的行程並 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` 在優雅關閉時乾淨地回收 worker 和 engine pidfile(#640、#474)。上述手動清理僅針對當機後兩個 pidfile 都未留下的情況。 + +### 設定檔 + +把 agentmemory 執行階段設定放到 `~/.agentmemory/.env`,而非在每個 shell 中 export 變數。若檢視器顯示像 `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 key 測試,明確啟用: + +```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 +``` + +--- + +

API

+ +連接埠 `3111` 上的 124 個端點。REST API 預設繫結 `127.0.0.1`。當 `AGENTMEMORY_SECRET` 已設定時,受保護端點需要 `Authorization: Bearer `,網狀同步端點要求兩端都設定 `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` | 檔案上下文 + 記憶 + bugs | +| `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) + +
+ +--- + +

Development

+ +```bash +npm run dev # 熱重新載入 +npm run build # 生產建置 +npm test # 950+ 測試 +npm run test:integration # API 測試(需要服務執行中) +``` + +**先決條件:** Node.js >= 20、[iii-engine](https://iii.dev/docs) 或 Docker + +

License

+ +[Apache-2.0](../LICENSE) diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000000000000000000000000000000000000..f77f371d7cf2e7d333189d6c7016294eedbf46ba --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,92 @@ +# Roadmap + +This is agentmemory's public 12-month roadmap. It covers Q2 2026 through Q1 2027. The roadmap is the source of truth for where the project is heading; anything significant that lands in main should trace back to an item here or a ratified issue. + +Items shift as evidence changes. Each quarter we publish a short retrospective on what landed, what slipped, and why — attached to the release notes. + +## How to read this + +- **Shipped** — landed in main and tagged in a release. +- **Active** — in-flight, has an open PR or issue owner. +- **Planned** — accepted scope for the quarter, not started. +- **Candidate** — under consideration, may defer. + +Anything not on this list that a contributor wants to pursue is welcome — open an issue labeled `roadmap` and it gets triaged against the quarterly theme. + +## Themes + +- **Q2 2026 — Depth.** Multimodal memory, more connectors, close out backlog from the v0.9 cycle. +- **Q3 2026 — Breadth.** Hook parity across more agents, community expansion, OpenSSF best-practices alignment. +- **Q4 2026 — Trust.** Enterprise features — SSO, audit export, RBAC, long-running deployment story. +- **Q1 2027 — v1.0.** Stability, LTS branch, semver freeze on the REST + MCP surface. + +## Q2 2026 — Depth (April – June) + +### Shipped so far in this quarter +- [x] iii console docs in README with vendored screenshots (#157) +- [x] Health severity gated on RSS floor (#158 / PR #160) +- [x] Standalone MCP proxies to the running server (#159 / PR #161) +- [x] Audit coverage for `mem::forget` + audit policy doc (#125 / PR #162) +- [x] `@agentmemory/fs-watcher` filesystem connector (#62 / PR #163) +- [x] Next.js website on Vercel (PR #164) +- [x] CI publishes all three npm packages on release (PR #166) + +### Active +- [ ] **Multimodal memory** — content-addressed image store, vision-prompt compression, disk quota + refcount on eviction (#64, PR #111) +- [ ] **Governance baseline** — this file, plus `GOVERNANCE.md`, `CONTRIBUTING.md`, `MAINTAINERS.md`, `CODE_OF_CONDUCT.md`, `SECURITY.md` + +### Planned +- [ ] **GitHub connector** (`@agentmemory/github-watcher`) — sync issues, PRs, discussions as observations. Shares the `POST /agentmemory/observe` wire format with the filesystem connector. +- [x] **OpenCode hook bus** (#156) — wired 22 hooks covering all 12 Claude Code hook types: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool capture (before + rich ToolPart lifecycle in message.part.updated), memory injection (context + enrich via system.transform), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline (stash via tool.execute.before + file.edited + file parts), permissions (updated + replied), task tracking (todo.updated w/ priority), commands (command.executed), config & model tracking (config + chat.params). Plus 2 slash commands (recall/remember). See `plugin/opencode/`. +- [ ] **Session replay UI** in the real-time viewer — scrub the timeline, inspect per-observation payloads. +- [ ] **Benchmark harness in CI** — keep the 95.2% R@5 number honest across releases by re-running LongMemEval-S on every minor tag. + +## Q3 2026 — Breadth (July – September) + +### Planned +- [ ] **Additional maintainer onboarding** — at least one Maintainer from a different organization added via the process in `GOVERNANCE.md`. This is a prerequisite for advancing past the foundation's Growth Stage. +- [ ] **Slack / Discord connector** — third source in the connector family. +- [ ] **OpenSSF Scorecard** — enroll, reach a Silver-equivalent score. Badged in the README. +- [ ] **Hermes integration hardening** — reach parity with the OpenClaw plugin surface (session lifecycle + tool-use hooks). +- [ ] **Knowledge graph query language** — small DSL on top of `/agentmemory/graph` for multi-hop questions. +- [ ] **First conference talk** — submit to KubeCon / LlamaCon / similar. + +### Candidate +- Cross-agent shared memory namespace. Currently each agent installs its own instance. This would let a Claude Code session and a Cursor session recall each other's observations via a shared mesh node. + +## Q4 2026 — Trust (October – December) + +### Planned +- [ ] **SSO gateway** — accept OIDC in front of the REST surface for team deployments. +- [ ] **Audit log export** — streamable tail to S3 / Loki / stdout for compliance pipelines. +- [ ] **RBAC on memory scope** — `project:read`, `project:write`, `governance:delete` role set. +- [ ] **Long-running deployment guide** — first-class Docker, systemd unit, and launchd plist. +- [ ] **Performance SLO** — publish p50/p95 recall latency targets, enforce via the benchmark harness. +- [ ] **Security audit** — external review of the REST surface + mesh-sync path. Fund through LF if foundation acceptance lands before end of quarter. + +### Candidate +- Agent-to-agent memory handoff protocol — standardize what one agent can inherit from another's memory, complementing MCP. + +## Q1 2027 — v1.0 (January – March) + +### Planned +- [ ] **REST + MCP surface freeze.** Any break requires a major-version tag per `GOVERNANCE.md`. +- [ ] **LTS branch `v1.x`** — 12-month security-fix commitment. +- [ ] **v1.0 release** — full documentation pass, all roadmap items from prior quarters either shipped or formally deferred. +- [ ] **Foundation membership** — Growth → Impact stage application if adoption + maintainer diversity metrics justify. + +### Candidate +- Hosted reference instance for the community to benchmark against. +- Reference implementation in a second language (Rust or Go) for the MCP server — would expand the set of runtimes that can host agentmemory. + +## Out of scope + +For transparency, these are deliberately *not* on the roadmap: + +- A cloud-hosted agentmemory SaaS. +- Billing, subscription tiers, commercial licensing beyond Apache-2.0. +- Agent frameworks themselves — agentmemory is a dependency, not a replacement for the agent runtime. + +## Feedback + +Anything on this list you disagree with, or think should move up / down — open an issue tagged `roadmap`. Quarterly themes are revisited with every quarterly retrospective. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..a24b6e9672a576af23e0365ee7b5cd6241dbf7d5 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,85 @@ +# Security Policy + +## Reporting a vulnerability + +**Do not open a public GitHub issue for a suspected vulnerability.** + +Use one of: + +- **GitHub Security Advisories (preferred)** — private report form at . GitHub routes the report to the Maintainers, assigns a GHSA identifier, and keeps you in a private thread until the fix ships. All sensitive details (stack traces, credentials, exploit payloads) stay end-to-end within GitHub's security infrastructure — use this channel whenever possible. +- **Encrypted email (fallback)** — if GitHub is unavailable or the issue cannot be described in the GHSA form, send an encrypted message to `ghumare64@gmail.com` with subject `agentmemory security`. Encrypt with the Maintainer public keys published at (PGP) and (SSH for verification); attach your own public key so we can reply encrypted. Plaintext email is accepted only as a last resort — prefer GHSA. + +Include, at minimum: + +- agentmemory version (`npm view @agentmemory/agentmemory version` against your install). +- The affected surface — REST endpoint, MCP tool, hook, CLI flag, or filesystem layout. +- A minimal reproduction — prefer one curl invocation or one MCP tool call plus the environment state required. +- Impact, in your own words. + +## What we do with it + +1. **Acknowledge** within 72 hours (target: 24). +2. **Triage** — confirm reproduction, assign a severity using CVSS 3.1, and give you a rough timeline. +3. **Fix** in a private branch. Draft a GitHub Security Advisory with the patched version, CWE, CVSS vector, affected versions, and attribution to you (unless you prefer anonymity). +4. **Coordinate disclosure** — we agree a disclosure date with you. Default window is 30 days from acknowledgment for straightforward vulnerabilities, up to 90 days for ones that need a deep refactor. +5. **Publish** — release the patched version on npm, publish the advisory, update `CHANGELOG.md` under a `### Security` section for the release, notify downstream scanners. + +## Supported versions + +| Version | Security fixes? | +|-|-| +| Latest minor (currently `0.9.x`) | Yes | +| Previous minor (currently `0.8.x`) | Critical / High severity only, for 90 days after a new minor is released | +| Older | No | + +At v1.0 this policy switches to a stated LTS window per the roadmap. + +## Scope + +In scope: + +- The `@agentmemory/agentmemory` server (REST + MCP surface, hook handlers, state store). +- The `@agentmemory/mcp` standalone MCP server. +- The `@agentmemory/fs-watcher` connector. +- First-party integrations under `integrations/` (`hermes/`, `openclaw/`, `filesystem-watcher/`). +- The Claude Code plugin under `plugin/`. + +Out of scope: + +- Third-party MCP clients consuming agentmemory — report to those projects. +- `iii-sdk` upstream — report to the iii project. +- The marketing site under `website/` unless the issue affects user security (XSS against visitors, credential leak in build output). + +## Supply-chain stance + +agentmemory ships pre-built artifacts in the npm tarball — `dist/` is bundled at publish time, not built from `node_modules` at install time. The package's runtime dependency tree is intentionally small (6 production deps: `@anthropic-ai/sdk`, `@anthropic-ai/claude-agent-sdk`, `@clack/prompts`, `dotenv`, `iii-sdk`, `zod`) plus an optional set guarded behind `optionalDependencies` for embeddings. + +**No lockfile is committed** (#540). The reasoning: + +- The npm tarball ships pre-built `dist/` — fresh installs don't compile from source, so no lockfile is consulted at the user's install step. +- The lockfile only affects contributor-local builds. Pinning it would shift the supply-chain attack surface from "what npm resolves today" to "what was resolved when the lockfile was last regenerated," which is a different tradeoff, not strictly better. +- We use SemVer ranges (`^x.y.z`) on the published deps so security patches reach users without a re-release. + +If you ship agentmemory inside a hardened pipeline that requires reproducible installs, the recommended path is: + +1. `npm install --legacy-peer-deps` against the published tarball in a controlled environment. +2. `npm shrinkwrap` to produce a versioned `npm-shrinkwrap.json` that travels with your deployment. +3. Audit `node_modules/` once at that point and republish internally. + +CI runs `npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund` then `npm ci` against that generated lockfile, so every test job builds against a fully resolved tree. The lockfile is regenerated on each CI run rather than checked in, which keeps the published tarball aligned with whatever SemVer-compatible patch level was current at release time. + +Supply-chain monitoring we already do: + +- Dependabot opens PRs for every minor/patch bump on the production dep list (visible in the open PRs). +- Every PR runs the full test suite on ubuntu-latest + macos-latest, Node 20 + 22, before any merge. +- `optionalDependencies` (`@xenova/transformers`, `onnxruntime-node`, etc.) are guarded by `try { await import("...") } catch` so a missing or compromised optional dep cannot break the core runtime path. + +If you find a malicious package in our dep tree, file via the GHSA flow at the top of this document — that's the fastest path to a fixed release on npm. + +## Past advisories + +See the [`.github/security-advisories/`](./.github/security-advisories) directory for advisory drafts. Published advisories (with assigned GHSA IDs) live at . + +## Safe harbor + +Good-faith research, reported privately, does not get legal heat from the project. Research targeting third-party deployments of agentmemory is not covered — that's between you and the deployer. diff --git a/benchmark/COMPARISON.md b/benchmark/COMPARISON.md new file mode 100644 index 0000000000000000000000000000000000000000..794833a0978d2ce2db2a3b9aadf2a764461c95a7 --- /dev/null +++ b/benchmark/COMPARISON.md @@ -0,0 +1,158 @@ +# AI Agent Memory: Benchmark Comparison + +How agentmemory compares against other persistent memory solutions for AI coding agents. + +All numbers here come from published benchmarks or public repositories. We link to primary sources wherever possible so you can reproduce. + +--- + +## Retrieval Accuracy (LongMemEval) + +[LongMemEval](https://arxiv.org/abs/2410.10813) (ICLR 2025) measures long-term memory retrieval across ~48 sessions per question on the S variant (500 questions, ~115K tokens each). + +| System | Benchmark | R@5 | Notes | +|---|---|---|---| +| **agentmemory** (BM25 + Vector) | LongMemEval-S | **95.2%** | `all-MiniLM-L6-v2` embeddings, no API key | +| agentmemory (BM25-only) | LongMemEval-S | 86.2% | Fallback when no embedding provider available | +| MemPalace | LongMemEval-S | ~96.6% (self-reported) | Vendor-published number we have not independently reproduced. Vector-only with a larger embedding model and no agent-integration surface (no hooks, no MCP, no multi-agent) | +| Letta / MemGPT | LoCoMo | 83.2% | Different benchmark (LoCoMo, not LongMemEval) | +| Mem0 | LoCoMo | 68.5% | Different benchmark (LoCoMo, not LongMemEval) | + +**⚠️ Apples vs oranges caveat:** only agentmemory's 95.2% is our own measured result, reproducible from the methodology below. Every other number here is the vendor's published claim, on a different benchmark or harness, that we have not independently reproduced: MemPalace reports LongMemEval-S, while Letta and Mem0 publish on [LoCoMo](https://snap-stanford.github.io/LoCoMo/). Treat them as ballpark vendor claims, not a head-to-head on identical data. We'd love to run every system on the same dataset; if any maintainer wants to collaborate, open an issue. + +Full agentmemory methodology: [`LONGMEMEVAL.md`](LONGMEMEVAL.md) + +--- + +## Feature Matrix + +| Feature | agentmemory | mem0 | Letta/MemGPT | Khoj | supermemory | MemPalace | Hippo | +|---|---|---|---|---|---|---|---| +| **GitHub stars** | Growing | 58K+ | 23K+ | 35K+ | 26K+ | 54K+ | Trending | +| **Type** | Memory engine + MCP server | Memory layer API | Full agent runtime | Personal AI | Memory API + app | Benchmark-focused OSS | Memory system | +| **Auto-capture via hooks** | ✅ 12 lifecycle hooks | ❌ Manual `add()` | ❌ Agent self-edits | ❌ Manual | ❌ API-side extraction | ❌ Manual | ❌ Manual | +| **Search strategy** | BM25 + Vector + Graph | Vector + Graph | Vector (archival) | Semantic | Vector + RAG | Vector-only (large model) | Decay-weighted | +| **Multi-agent coordination** | ✅ Leases + signals + mesh | ❌ | Runtime-internal only | ❌ | ❌ | ❌ | Multi-agent shared | +| **Framework lock-in** | None | None | High | Standalone | None (drop-in wrappers) | None | None | +| **External deps** | None | Qdrant/pgvector | Postgres + vector | Multiple | Managed cloud | Vector store | None | +| **Self-hostable** | ✅ default | Optional | Optional | ✅ | ❌ Cloud-only | ✅ | ✅ | +| **Knowledge graph** | ✅ Entity extraction + BFS | ✅ Mem0g variant | ❌ | Doc links | ❌ | ❌ | ❌ | +| **Memory decay** | ✅ Ebbinghaus + tiered | ❌ | ❌ | ❌ | ✅ Auto-forget | ❌ | ✅ Half-lives | +| **4-tier consolidation** | ✅ Working → episodic → semantic → procedural | ❌ | OS-inspired tiers | ❌ | ❌ | ❌ | Episodic + semantic | +| **Version / supersession** | ✅ Jaccard-based | Passive | ❌ | ❌ | ✅ Auto-resolve | ❌ | ❌ | +| **Real-time viewer** | ✅ Port 3113 | Cloud dashboard | Cloud dashboard | Web UI | Cloud dashboard | ❌ | ❌ | +| **Privacy filtering** | ✅ Strips secrets pre-store | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| **Obsidian export** | ✅ Built-in | ❌ | ❌ | Native format | ❌ | ❌ | ❌ | +| **Cross-agent** | ✅ MCP + REST | API calls | Within runtime | Standalone | MCP + API | Standalone | Multi-agent shared | +| **Audit trail** | ✅ All mutations logged | ❌ | Limited | ❌ | ❌ | ❌ | ❌ | +| **Language SDKs** | Any (REST + MCP) | Python + TS | Python only | API | Python + TS | Python | Node | + +--- + +## Token Efficiency + +The main reason to use persistent memory at all: token cost. Here's what one year of heavy agent use looks like across approaches. + +| Approach | Tokens / year | Cost / year | Notes | +|---|---|---|---| +| Paste full history into context | 19.5M+ | Impossible | Exceeds context window after ~200 observations | +| LLM-summarized memory (extraction-based) | ~650K | ~$500 | Lossy — summarization drops detail | +| **agentmemory (API embeddings)** | **~170K** | **~$10** | Token-budgeted, only relevant memories injected | +| **agentmemory (local embeddings)** | **~170K** | **$0** | `all-MiniLM-L6-v2` runs in-process | +| supermemory | Not published | Cloud pricing | Managed API, no local token budget | +| Mem0 | Varies by integration | Varies | Extraction-based, no token budget | + +**agentmemory ships with a built-in token savings calculator.** Run `npx @agentmemory/agentmemory status` after a few sessions and you'll see exactly how many tokens you've saved vs. pasting the full history. + +--- + +## What Each Tool Is Best At + +This isn't a "agentmemory wins everything" page. Different tools solve different problems. + +**Choose agentmemory if you want:** +- Automatic capture with zero manual `add()` calls +- MCP server that works across Claude Code, Cursor, Codex, Gemini CLI, etc. +- Hybrid BM25 + vector + graph search +- Real-time viewer to see what your agent is learning +- Self-hostable with zero external databases +- Privacy filtering on API keys and secrets +- Multi-agent coordination (leases, signals, routines) + +**Choose Mem0 if you want:** +- Framework-agnostic API to bolt onto an existing agent +- Managed cloud option with a dashboard +- Python + TypeScript SDKs for direct integration +- Entity/relationship extraction as the primary abstraction + +**Choose Letta/MemGPT if you want:** +- A full agent runtime, not just memory +- OS-inspired memory tiers (core/archival/recall) +- Agents that self-edit their memory via function calls +- Long-running conversational agents (weeks/months) + +**Choose Khoj if you want:** +- A personal AI second brain, not agent infrastructure +- Document-first search over your files and the web +- Obsidian/Notion/Emacs integrations +- Scheduled automations and research tasks + +**Choose supermemory if you want:** +- A managed memory API with server-side auto-extraction and automatic forgetting +- Drop-in wrappers for major AI frameworks (Vercel AI, LangChain, LangGraph) +- A hosted dashboard with no infrastructure to run yourself +- RAG plus memory served from a single query + +**Choose MemPalace if you want:** +- A simple, free, open-source vector memory store +- To chase its self-reported retrieval benchmark (we have not reproduced it) +- Pure retrieval over agent workflow features +- Note: no auto-capture, no MCP, no multi-agent coordination, so you wire all integration yourself + +**Choose Hippo if you want:** +- Biologically-inspired memory model (decay, consolidation, sleep) +- Multi-agent shared memory as a primary feature +- "Forget by default, earn persistence through use" philosophy + +--- + +## Running Your Own Benchmarks + +We encourage you to measure this yourself rather than trust any README. Here's how: + +```bash +# Clone the repo +git clone https://github.com/rohitg00/agentmemory.git +cd agentmemory && npm install + +# Run LongMemEval-S +npm run bench:longmemeval + +# Run quality benchmark (240 observations, 20 queries) +npm run bench:quality + +# Run scale benchmark +npm run bench:scale + +# Run real embeddings benchmark +npm run bench:real-embeddings +``` + +Results land in `benchmark/results/`. All scripts, datasets, and results are committed for reproducibility. + +--- + +## Corrections Welcome + +If you maintain one of these tools and we got a number wrong, please open an issue or PR. We'd rather have accurate numbers than convenient ones. + +If you want to add your tool to this comparison, open a PR with: +1. A link to your benchmark methodology +2. The metric and dataset you're measuring on +3. A commit hash / version so we can reproduce + +**Sources:** +- Mem0 LoCoMo benchmark: [mem0.ai blog](https://mem0.ai) +- Letta LoCoMo benchmark: [letta.com/blog/benchmarking-ai-agent-memory](https://letta.com/blog/benchmarking-ai-agent-memory) +- LongMemEval paper: [arxiv.org/abs/2410.10813](https://arxiv.org/abs/2410.10813) +- LoCoMo paper: [snap-stanford.github.io/LoCoMo](https://snap-stanford.github.io/LoCoMo/) diff --git a/benchmark/LONGMEMEVAL.md b/benchmark/LONGMEMEVAL.md new file mode 100644 index 0000000000000000000000000000000000000000..00de938e4c265bff42d5f6180ced937611699421 --- /dev/null +++ b/benchmark/LONGMEMEVAL.md @@ -0,0 +1,79 @@ +# LongMemEval-S Benchmark Results + +[LongMemEval](https://arxiv.org/abs/2410.10813) (ICLR 2025) is an academic benchmark for evaluating long-term memory in chat assistants. It tests 5 core abilities: information extraction, multi-session reasoning, temporal reasoning, knowledge updates, and abstention. + +## Setup + +- **Dataset**: LongMemEval-S (500 questions, ~48 sessions per question, ~115K tokens) +- **Source**: [xiaowu0162/longmemeval-cleaned](https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned) +- **Metric**: `recall_any@K` — does ANY gold session appear in top-K retrieved results? +- **Embedding model**: `all-MiniLM-L6-v2` (384 dimensions, local, no API key) +- **No LLM in the loop**: Pure retrieval evaluation, no answer generation or judge + +## Results + +| System | R@5 | R@10 | R@20 | NDCG@10 | MRR | +|---|---|---|---|---|---| +| **agentmemory BM25+Vector** | **95.2%** | **98.6%** | **99.4%** | **87.9%** | **88.2%** | +| agentmemory BM25-only | 86.2% | 94.6% | 98.6% | 73.0% | 71.5% | +| MemPalace raw (vector-only) | 96.6% | ~97.6% | — | — | — | + +### By Question Type (BM25+Vector) + +| Type | R@5 | R@10 | Count | +|---|---|---|---| +| knowledge-update | 98.7% | 100.0% | 78 | +| multi-session | 97.7% | 100.0% | 133 | +| single-session-assistant | 96.4% | 98.2% | 56 | +| temporal-reasoning | 95.5% | 97.7% | 133 | +| single-session-user | 90.0% | 97.1% | 70 | +| single-session-preference | 83.3% | 96.7% | 30 | + +### By Question Type (BM25-only) + +| Type | R@5 | R@10 | Count | +|---|---|---|---| +| knowledge-update | 92.3% | 98.7% | 78 | +| single-session-user | 91.4% | 95.7% | 70 | +| temporal-reasoning | 88.0% | 94.7% | 133 | +| multi-session | 86.5% | 96.2% | 133 | +| single-session-assistant | 80.4% | 91.1% | 56 | +| single-session-preference | 60.0% | 80.0% | 30 | + +## Analysis + +1. **BM25+Vector (95.2%) nearly matches pure vector search (96.6%)** with only a 1.4pp gap. Both use the same embedding model (all-MiniLM-L6-v2). + +2. **BM25 alone gets 86.2%** — keyword search with Porter stemming and synonym expansion is surprisingly effective on conversational data. + +3. **Adding vectors to BM25 gives +9pp** (86.2% → 95.2%), the largest improvement from any single component. + +4. **Preferences are the hardest category** for both BM25 (60%) and hybrid (83.3%). These require understanding implicit/indirect statements. + +5. **Multi-session and knowledge-update are strongest** (97.7%+ hybrid). The hybrid approach excels when facts are distributed across sessions. + +6. **R@10 reaches 98.6%** — nearly all gold sessions are found within the top 10 results. + +## Important Notes on Methodology + +- These are **retrieval recall** scores, not end-to-end QA accuracy. The official LongMemEval metric is QA accuracy (retrieve + generate answer + GPT-4o judge). +- Systems on the actual LongMemEval QA leaderboard score 60-95% depending on the LLM reader (Oracle GPT-4o gets ~82.4%). +- We do NOT claim these as "LongMemEval scores" — they are retrieval-only evaluations on the LongMemEval-S haystack. +- Each question builds a fresh index from its ~48 sessions, searches with the question text, and checks if gold session IDs appear in results. + +## Reproducibility + +```bash +# Download dataset (264 MB) +pip install huggingface_hub +python3 -c " +from huggingface_hub import hf_hub_download +hf_hub_download(repo_id='xiaowu0162/longmemeval-cleaned', filename='longmemeval_s_cleaned.json', repo_type='dataset', local_dir='benchmark/data') +" + +# Run BM25-only +npx tsx benchmark/longmemeval-bench.ts bm25 + +# Run BM25+Vector hybrid (requires @xenova/transformers) +npx tsx benchmark/longmemeval-bench.ts hybrid +``` diff --git a/benchmark/QUALITY.md b/benchmark/QUALITY.md new file mode 100644 index 0000000000000000000000000000000000000000..a5b9cafcc5b6b76e257a67bf2cdf12b9ee558ae0 --- /dev/null +++ b/benchmark/QUALITY.md @@ -0,0 +1,75 @@ +# agentmemory v0.6.0 — Search Quality Evaluation (Internal Dataset) + +> For results on the academic LongMemEval-S benchmark (ICLR 2025, 500 questions), see [`LONGMEMEVAL.md`](LONGMEMEVAL.md) — **95.2% R@5, 98.6% R@10**. + +**Date:** 2026-03-18T07:44:43.397Z +**Dataset:** 240 synthetic observations across 30 sessions (internal coding project) +**Queries:** 20 labeled queries with ground-truth relevance +**Metric definitions:** Recall@K (fraction of relevant docs in top K), Precision@K (fraction of top K that are relevant), NDCG@10 (ranking quality), MRR (position of first relevant result) + +## Head-to-Head Comparison + +| System | Recall@5 | Recall@10 | Precision@5 | NDCG@10 | MRR | Latency | Tokens/query | +|--------|----------|-----------|-------------|---------|-----|---------|--------------| +| Built-in (CLAUDE.md / grep) | 37.0% | 55.8% | 78.0% | 80.3% | 82.5% | 0.50ms | 22,610 | +| Built-in (200-line MEMORY.md) | 27.4% | 37.8% | 63.0% | 56.4% | 65.5% | 0.16ms | 7,938 | +| BM25-only | 43.8% | 55.9% | 95.0% | 82.7% | 95.5% | 0.17ms | 3,142 | +| Dual-stream (BM25+Vector) | 42.4% | 58.6% | 90.0% | 84.7% | 95.4% | 0.71ms | 3,142 | +| Triple-stream (BM25+Vector+Graph) | 36.8% | 58.0% | 87.0% | 81.7% | 87.9% | 1.02ms | 3,142 | + +## Why This Matters + +**Recall improvement:** agentmemory triple-stream finds 58.0% of relevant memories at K=10 vs 55.8% for keyword grep (+4%) +**Token savings:** agentmemory returns only the top 10 results (3,142 tokens) vs loading everything into context (22,610 tokens) — 86% reduction +**200-line cap:** Claude Code's MEMORY.md is capped at 200 lines. With 240 observations, 37.8% recall at K=10 — memories from later sessions are simply invisible. + +## Per-Query Breakdown (Triple-Stream) + +| Query | Category | Recall@10 | NDCG@10 | MRR | Relevant | Latency | +|-------|----------|-----------|---------|-----|----------|---------| +| How did we set up authentication? | semantic | 50.0% | 100.0% | 100.0% | 20 | 1.7ms | +| JWT token validation middleware | exact | 50.0% | 64.9% | 100.0% | 10 | 1.2ms | +| PostgreSQL connection issues | semantic | 33.3% | 100.0% | 100.0% | 30 | 1.0ms | +| Playwright test configuration | exact | 100.0% | 100.0% | 100.0% | 10 | 1.1ms | +| Why did the production deployment fail? | cross-session | 33.3% | 100.0% | 100.0% | 30 | 0.8ms | +| rate limiting implementation | exact | 80.0% | 64.1% | 33.3% | 10 | 0.7ms | +| What security measures did we add? | semantic | 33.3% | 100.0% | 100.0% | 30 | 0.7ms | +| database performance optimization | semantic | 0.0% | 0.0% | 7.1% | 25 | 0.8ms | +| Kubernetes pod crash debugging | entity | 100.0% | 96.7% | 100.0% | 5 | 1.2ms | +| Docker containerization setup | entity | 100.0% | 100.0% | 100.0% | 10 | 0.9ms | +| How does caching work in the app? | semantic | 25.0% | 64.9% | 100.0% | 20 | 0.8ms | +| test infrastructure and factories | exact | 50.0% | 64.9% | 100.0% | 10 | 0.7ms | +| What happened with the OAuth callback error? | cross-session | 100.0% | 54.1% | 16.7% | 5 | 1.1ms | +| monitoring and observability setup | semantic | 66.7% | 100.0% | 100.0% | 15 | 0.8ms | +| Prisma ORM configuration | entity | 25.7% | 93.6% | 100.0% | 35 | 1.8ms | +| CI/CD pipeline configuration | exact | 20.0% | 64.9% | 100.0% | 25 | 1.0ms | +| memory leak debugging | cross-session | 100.0% | 100.0% | 100.0% | 5 | 0.7ms | +| API design decisions | semantic | 25.0% | 64.9% | 100.0% | 20 | 1.4ms | +| zod validation schemas | entity | 66.7% | 100.0% | 100.0% | 15 | 0.7ms | +| infrastructure as code Terraform | entity | 100.0% | 100.0% | 100.0% | 5 | 1.5ms | + +## By Query Category + +| Category | Avg Recall@10 | Avg NDCG@10 | Avg MRR | Queries | +|----------|---------------|-------------|---------|---------| +| exact | 60.0% | 71.8% | 86.7% | 5 | +| semantic | 33.3% | 75.7% | 86.7% | 7 | +| cross-session | 77.8% | 84.7% | 72.2% | 3 | +| entity | 78.5% | 98.1% | 100.0% | 5 | + +## Context Window Analysis + +The fundamental problem with built-in agent memory: + +| Observations | MEMORY.md tokens | agentmemory tokens (top 10) | Savings | MEMORY.md reachable | +|-------------|-----------------|---------------------------|---------|-------------------| +| 240 | 12,000 | 3,142 | 74% | 83% | +| 500 | 25,000 | 3,142 | 87% | 40% | +| 1,000 | 50,000 | 3,142 | 94% | 20% | +| 5,000 | 250,000 | 3,142 | 99% | 4% | + +At 240 observations (our dataset), MEMORY.md already hits its 200-line cap and loses access to the most recent 40 observations. At 1,000 observations, 80% of memories are invisible. agentmemory always searches the full corpus. + +--- + +*100 evaluations across 5 systems. Ground-truth labels assigned by concept matching against observation metadata.* \ No newline at end of file diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 0000000000000000000000000000000000000000..23d2285222db898dddb1718e79da7d27a83de8e3 --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,100 @@ +# benchmark/ + +Two kinds of numbers live in this directory: + +1. **Quality / retrieval** — `longmemeval-bench.ts`, `quality-eval.ts`, + `real-embeddings-eval.ts`, `scale-eval.ts`. Recall, precision, token + savings. Documented in `LONGMEMEVAL.md`, `QUALITY.md`, + `REAL-EMBEDDINGS.md`, `SCALE.md`. + +2. **Load shape** — `load-100k.ts`. p50 / p90 / p99 latency and + throughput against a running daemon. This is the file you want when + somebody asks "what's p99 at 100k memories under concurrency 100?". + +## load-100k.ts + +Hand-rolled, dependency-free load harness. Issues real HTTP against a +local agentmemory daemon at `http://localhost:3111`, records per-request +latency with `performance.now()`, and writes a JSON report per run. + +### What it measures + +For each cell in the matrix `(N, concurrency, endpoint)` it records: + +- `p50_ms`, `p90_ms`, `p99_ms` — nearest-rank percentiles. +- `min_ms`, `max_ms`, `ops`, `errors`. +- `throughput_per_sec` — wall-clock ops / sec for that cell. + +Default matrix: + +- `N` ∈ {1000, 10000, 100000} — number of memories seeded before the + cell runs. +- `C` ∈ {1, 10, 100} — concurrent in-flight requests during the cell. +- Endpoints under test: + - `POST /agentmemory/remember` + - `POST /agentmemory/smart-search` + - `GET /agentmemory/memories?latest=true` + +Each cell issues `BENCH_OPS=200` requests by default — enough samples +for stable p99 without dragging a 100k-seed run past tens of minutes. + +### Why p99 is the number that matters + +p50 tells you the median request feels fast. p90 tells you the bulk of +requests feel fast. **p99 tells you the request your tail user hits when +they really need it feels fast.** Capacity planning lives here — if you +want to size a fleet, scale your daemon, or set an SLO, p99 is the +number to plan against. p50 will lie to you. + +### Running it + +```bash +# 1. Start the daemon however you normally do (npx, Docker, etc.) +npx @agentmemory/agentmemory + +# 2. From the repo root, in another shell: +npm run bench:load +``` + +To override the matrix: + +```bash +BENCH_N=1000 BENCH_C=1,10 BENCH_OPS=100 npm run bench:load +``` + +To have the harness spawn a daemon for the run (after `npm run build`): + +```bash +AGENTMEMORY_BENCH_AUTOSTART=1 npm run bench:load +``` + +Other env knobs (see the file header for the canonical list): + +- `AGENTMEMORY_URL` — base URL of the daemon (default + `http://localhost:3111`). +- `BENCH_SEED` — seed for the `mulberry32` content RNG. Same seed + + same daemon build = byte-identical seed corpus. +- `BENCH_OUT_DIR` — where the JSON report lands (default + `benchmark/results/`). + +### Where results land + +`benchmark/results/load-100k-.json`. The harness +`mkdir -p`s the directory. The file has a `schema_version: 1` field so +future format changes don't silently break consumers. + +### Content generation is seedable + +Synthetic memory content is built from a small noun / verb / concept +vocabulary fed by a `mulberry32(BENCH_SEED)` PRNG. Same seed + same +build = same corpus. The point isn't "realistic" content (there isn't +one realistic content); the point is **reproducibility** — re-running +the harness against the same git sha should give the same content +mixture going in, so latency variance comes from the daemon and not +from JSON payload jitter. + +### Publishing numbers per release + +The release flow appends a `## Performance` section to `CHANGELOG.md` +referencing the JSON in `benchmark/results/` for that release's git +sha. p99 is the headline number; the JSON is the receipt. diff --git a/benchmark/REAL-EMBEDDINGS.md b/benchmark/REAL-EMBEDDINGS.md new file mode 100644 index 0000000000000000000000000000000000000000..95c5863680bff7708c0e4685d26ccfee073bb748 --- /dev/null +++ b/benchmark/REAL-EMBEDDINGS.md @@ -0,0 +1,67 @@ +# agentmemory v0.6.0 — Real Embeddings Quality Evaluation + +**Date:** 2026-03-18T07:38:21.450Z +**Platform:** darwin arm64, Node v20.20.0 +**Dataset:** 240 observations, 30 sessions, 20 labeled queries +**Embedding model:** Xenova/all-MiniLM-L6-v2 (384d, local, no API key) + +## Head-to-Head: Real Embeddings vs Keyword Search + +| System | Recall@5 | Recall@10 | Precision@5 | NDCG@10 | MRR | Avg Latency | Tokens/query | +|--------|----------|-----------|-------------|---------|-----|-------------|--------------| +| Built-in (grep all) | 37.0% | 55.8% | 78.0% | 80.3% | 82.5% | 0.44ms | 19,462 | +| BM25-only (stemmed+synonyms) | 43.8% | 55.9% | 95.0% | 82.7% | 95.5% | 0.26ms | 1,571 | +| Dual-stream (BM25+Xenova) | 43.8% | 64.1% | 98.0% | 94.9% | 100.0% | 2.39ms | 1,571 | +| Triple-stream (BM25+Xenova+Graph) | 43.8% | 64.1% | 98.0% | 94.9% | 100.0% | 2.07ms | 1,571 | + +## Improvement from Real Embeddings + +Adding real vector embeddings to BM25 improves recall@10 by **8.2 percentage points**. +Token savings vs loading everything: **92%** (1,571 vs 19,462 tokens). + +## Per-Query: Where Real Embeddings Win + +Queries where dual-stream (real embeddings) outperforms BM25-only: + +| Query | Category | BM25 Recall@10 | +Vector Recall@10 | Delta | +|-------|----------|---------------|-------------------|-------| +| How did we set up authentication? | semantic | 25.0% | 45.0% | +20.0pp ** | +| Playwright test configuration | exact | 50.0% | 90.0% | +40.0pp ** | +| database performance optimization | semantic | 0.0% | 40.0% | +40.0pp ** | +| test infrastructure and factories | exact | 50.0% | 80.0% | +30.0pp ** | +| Prisma ORM configuration | entity | 14.3% | 28.6% | +14.3pp ** | +| CI/CD pipeline configuration | exact | 20.0% | 40.0% | +20.0pp ** | + +## By Category Comparison + +| Category | Built-in grep | BM25 (stemmed) | +Real Vectors | +Graph | +|----------|--------------|----------------|--------------|--------| +| exact | 48.0% | 54.0% | 72.0% | 72.0% | +| semantic | 35.5% | 33.3% | 41.9% | 41.9% | +| cross-session | 77.8% | 77.8% | 77.8% | 77.8% | +| entity | 79.0% | 76.2% | 79.0% | 79.0% | + +## Embedding Performance + +| System | Embedding Time | Model | Dimensions | +|--------|---------------|-------|------------| +| Dual-stream (BM25+Xenova) | 3.1s | Xenova/all-MiniLM-L6-v2 | 384 | +| Triple-stream (BM25+Xenova+Graph) | 2.9s | Xenova/all-MiniLM-L6-v2 | 384 | + +Embedding is a one-time cost at ingestion. Search is sub-millisecond after indexing. + +## Key Findings + +1. **Semantic queries improve most**: 8.6pp recall@10 gain from real embeddings +2. **"database performance optimization"** — the hardest query — goes from BM25 0.0% to vector-augmented 40.0% +3. **Entity/exact queries** are already well-served by BM25+stemming — vectors add marginal value +4. **Local embeddings (Xenova)** run without API keys — zero cost, zero latency concerns + +## Recommendation + +Enable local embeddings by default (`EMBEDDING_PROVIDER=local` or install `@xenova/transformers`). +This gives agentmemory genuine semantic search that built-in agent memories cannot match — +understanding that "database performance optimization" relates to "N+1 query fix" and "eager loading". + +--- +*All measurements use Xenova/all-MiniLM-L6-v2 local embeddings (384 dimensions, no API calls).* \ No newline at end of file diff --git a/benchmark/SCALE.md b/benchmark/SCALE.md new file mode 100644 index 0000000000000000000000000000000000000000..ae0762dfc372e50a4254eeda513ea5c96c88ddd6 --- /dev/null +++ b/benchmark/SCALE.md @@ -0,0 +1,110 @@ +# agentmemory v0.6.0 — Scale & Cross-Session Evaluation + +**Date:** 2026-03-18T07:45:03.529Z +**Platform:** darwin arm64, Node v20.20.0 + +## 1. Scale: agentmemory vs Built-in Memory + +Every built-in agent memory (CLAUDE.md, .cursorrules, Cline's memory-bank) loads ALL memory into context every session. agentmemory searches and returns only relevant results. + +| Observations | Sessions | Index Build | BM25 Search | Hybrid Search | Heap | Context Tokens (built-in) | Context Tokens (agentmemory) | Savings | Built-in Unreachable | +|-------------|----------|------------|-------------|---------------|------|--------------------------|-----------------------------|---------|--------------------| +| 240 | 30 | 177ms | 0.112ms | 0.63ms | 9MB | 10,504 | 1,924 | 82% | 17% | +| 1,000 | 125 | 155ms | 0.317ms | 1.709ms | 6MB | 43,834 | 1,969 | 96% | 80% | +| 5,000 | 625 | 810ms | 1.496ms | 8.58ms | 25MB | 220,335 | 1,972 | 99% | 96% | +| 10,000 | 1250 | 1657ms | 3.195ms | 17.49ms | 1MB | 440,973 | 1,974 | 100% | 98% | +| 50,000 | 6250 | 9182ms | 22.827ms | 108.722ms | 316MB | 2,216,173 | 1,981 | 100% | 100% | + +### What the numbers mean + +**Context Tokens (built-in):** How many tokens Claude Code/Cursor/Cline would consume loading ALL memory into the context window. At 5,000 observations, this is ~250K tokens — exceeding most context windows entirely. + +**Context Tokens (agentmemory):** How many tokens the top-10 search results consume. Stays constant regardless of corpus size. + +**Built-in Unreachable:** Percentage of memories that built-in systems CANNOT access because they exceed the 200-line MEMORY.md cap or context window limits. At 1,000 observations, 80% of your project history is invisible. + +### Storage Costs + +| Observations | BM25 Index | Vector Index (d=384) | Total Storage | +|-------------|-----------|---------------------|---------------| +| 240 | 395 KB | 494 KB | 0.9 MB | +| 1,000 | 1,599 KB | 2,060 KB | 3.6 MB | +| 5,000 | 8,006 KB | 10,298 KB | 17.9 MB | +| 10,000 | 16,005 KB | 20,596 KB | 35.7 MB | +| 50,000 | 80,126 KB | 102,979 KB | 178.8 MB | + +## 2. Cross-Session Retrieval + +Can the system find relevant information from past sessions? This is impossible for built-in memory once observations exceed the line/context cap. + +| Query | Target Session | Gap | BM25 Found | BM25 Rank | Hybrid Found | Hybrid Rank | Built-in Visible | +|-------|---------------|-----|-----------|-----------|-------------|-------------|-----------------| +| How did we set up OAuth providers? | ses_005-009 | 24 | Yes | #1 | Yes | #1 | Yes | +| What was the N+1 query fix? | ses_010-014 | 18 | Yes | #1 | Yes | #2 | Yes | +| PostgreSQL full-text search setup | ses_010-014 | 17 | Yes | #1 | Yes | #1 | Yes | +| bcrypt password hashing configuration | ses_005-009 | 20 | Yes | #1 | Yes | #1 | Yes | +| Vitest unit testing setup | ses_020-024 | 9 | Yes | #1 | Yes | #1 | Yes | +| webhook retry exponential backoff | ses_015-019 | 14 | Yes | #1 | Yes | #1 | Yes | +| ESLint flat config migration | ses_000-004 | 29 | Yes | #1 | Yes | #1 | Yes | +| Kubernetes HPA autoscaling configuration | ses_025-029 | 4 | Yes | #1 | Yes | #1 | No | +| Prisma database seed script | ses_010-014 | 16 | Yes | #1 | Yes | #1 | Yes | +| API cursor-based pagination | ses_015-019 | 14 | Yes | #1 | Yes | #1 | Yes | +| CSRF protection double-submit cookie | ses_005-009 | 24 | Yes | #1 | Yes | #1 | Yes | +| blue-green deployment rollback | ses_025-029 | 4 | Yes | #1 | Yes | #1 | No | + +**Summary:** agentmemory BM25 found 12/12 cross-session queries. Hybrid found 12/12. Built-in memory (200-line cap) could only reach 10/12. + +## 3. The Context Window Problem + +``` +Agent context window: ~200K tokens +System prompt + tools: ~20K tokens +User conversation: ~30K tokens +Available for memory: ~150K tokens + +At 50 tokens/observation: + 200 observations = 10,000 tokens (fits, but 200-line cap hits first) + 1,000 observations = 50,000 tokens (33% of available budget) + 5,000 observations = 250,000 tokens (EXCEEDS total context window) + +agentmemory top-10 results: + Any corpus size = ~1,924 tokens (0.3% of budget) +``` + +## 4. What Built-in Memory Cannot Do + +| Capability | Built-in (CLAUDE.md) | agentmemory | +|-----------|---------------------|-------------| +| Semantic search | No (keyword grep only) | BM25 + vector + graph | +| Scale beyond 200 lines | No (hard cap) | Unlimited | +| Cross-session recall | Only if in 200-line window | Full corpus search | +| Cross-agent sharing | No (per-agent files) | MCP + REST API | +| Multi-agent coordination | No | Leases, signals, actions | +| Temporal queries | No | Point-in-time graph | +| Memory lifecycle | No (manual pruning) | Ebbinghaus decay + eviction | +| Knowledge graph | No | Entity extraction + traversal | +| Query expansion | No | LLM-generated reformulations | +| Retention scoring | No | Time-frequency decay model | +| Real-time dashboard | No (read files manually) | Viewer on :3113 | +| Concurrent access | No (file lock) | Keyed mutex + KV store | + +## 5. When to Use What + +**Use built-in memory (CLAUDE.md) when:** +- You have < 200 items to remember +- Single agent, single project +- Preferences and quick facts only +- Zero setup is the priority + +**Use agentmemory when:** +- Project history exceeds 200 observations +- You need to recall specific incidents from weeks ago +- Multiple agents work on the same codebase +- You want semantic search ("how does auth work?") not just keyword matching +- You need to track memory quality, decay, and lifecycle +- You want a shared memory layer across Claude Code, Cursor, Windsurf, etc. + +Built-in memory is your sticky notes. agentmemory is the searchable database behind them. + +--- +*Scale tests: 5 corpus sizes. Cross-session tests: 12 queries targeting specific past sessions.* \ No newline at end of file diff --git a/benchmark/dataset.ts b/benchmark/dataset.ts new file mode 100644 index 0000000000000000000000000000000000000000..a39e87b7de7ba0b1c8c8a46450a95da7e9958d18 --- /dev/null +++ b/benchmark/dataset.ts @@ -0,0 +1,293 @@ +import type { CompressedObservation } from "../src/types.js"; + +export interface LabeledQuery { + query: string; + relevantObsIds: string[]; + description: string; + category: "exact" | "semantic" | "temporal" | "cross-session" | "entity"; +} + +const SESSION_COUNT = 30; +const OBS_PER_SESSION = 8; + +function ts(daysAgo: number): string { + return new Date(Date.now() - daysAgo * 86400000).toISOString(); +} + +const RAW_SESSIONS: Array<{ + sessionRange: [number, number]; + daysAgoRange: [number, number]; + project: string; + observations: Array>; +}> = [ + { + sessionRange: [0, 4], + daysAgoRange: [28, 25], + project: "webapp", + observations: [ + { type: "command_run", title: "Initialize Next.js 15 project", subtitle: "create-next-app", facts: ["Created Next.js 15 app with App Router", "TypeScript template selected", "Tailwind CSS v4 configured"], narrative: "Initialized a new Next.js 15 project using create-next-app with TypeScript and Tailwind CSS. Selected the App Router layout.", concepts: ["nextjs", "typescript", "tailwind", "app-router"], files: ["package.json", "tsconfig.json", "tailwind.config.ts"], importance: 6 }, + { type: "file_edit", title: "Configure ESLint with flat config", subtitle: "eslint.config.mjs", facts: ["Migrated to ESLint flat config format", "Added typescript-eslint plugin", "Configured import sorting rules"], narrative: "Set up ESLint using the new flat config format (eslint.config.mjs). Added typescript-eslint for type-aware linting and configured import sorting with eslint-plugin-import.", concepts: ["eslint", "linting", "code-quality", "typescript"], files: ["eslint.config.mjs", "package.json"], importance: 5 }, + { type: "file_edit", title: "Set up Prettier with Tailwind plugin", subtitle: "Formatting", facts: ["Installed prettier and prettier-plugin-tailwindcss", "Added .prettierrc with semi: false, singleQuote: true", "Configured format-on-save in VS Code settings"], narrative: "Configured Prettier for automatic code formatting. Added the Tailwind CSS class sorting plugin. Set up VS Code to format on save.", concepts: ["prettier", "formatting", "tailwind", "developer-experience"], files: [".prettierrc", ".vscode/settings.json"], importance: 4 }, + { type: "file_edit", title: "Create shared UI component library", subtitle: "Components", facts: ["Created Button, Input, Card, Badge components", "Used cva (class-variance-authority) for variant styling", "Added Radix UI primitives for accessibility"], narrative: "Built a shared component library with Button, Input, Card, and Badge components. Used class-variance-authority (cva) for type-safe variant styling and Radix UI primitives for keyboard navigation and screen reader support.", concepts: ["components", "ui-library", "radix-ui", "cva", "accessibility"], files: ["src/components/ui/button.tsx", "src/components/ui/input.tsx", "src/components/ui/card.tsx"], importance: 7 }, + { type: "file_edit", title: "Add global layout with navigation", subtitle: "Layout", facts: ["Created root layout with metadata", "Added responsive navigation bar", "Implemented mobile hamburger menu"], narrative: "Created the root layout component with SEO metadata, Open Graph tags, and a responsive navigation bar that collapses into a hamburger menu on mobile devices.", concepts: ["layout", "navigation", "responsive-design", "seo"], files: ["src/app/layout.tsx", "src/components/nav.tsx"], importance: 6 }, + { type: "file_edit", title: "Configure path aliases and absolute imports", subtitle: "tsconfig", facts: ["Added @ alias pointing to src/", "Configured baseUrl for absolute imports"], narrative: "Set up TypeScript path aliases so imports can use @/components instead of relative paths. Configured baseUrl in tsconfig.json.", concepts: ["typescript", "path-aliases", "developer-experience"], files: ["tsconfig.json"], importance: 3 }, + { type: "command_run", title: "Add Vitest for unit testing", subtitle: "Testing setup", facts: ["Installed vitest and @testing-library/react", "Created vitest.config.ts with jsdom environment", "Added test script to package.json"], narrative: "Set up Vitest as the unit testing framework with React Testing Library for component tests. Configured jsdom environment for DOM testing.", concepts: ["vitest", "testing", "react-testing-library", "configuration"], files: ["vitest.config.ts", "package.json"], importance: 5 }, + { type: "file_edit", title: "Set up Husky pre-commit hooks", subtitle: "Git hooks", facts: ["Installed husky and lint-staged", "Pre-commit runs ESLint and Prettier", "Added commitlint for conventional commits"], narrative: "Configured Husky git hooks with lint-staged to run ESLint and Prettier on staged files before each commit. Added commitlint to enforce conventional commit message format.", concepts: ["husky", "git-hooks", "lint-staged", "commitlint", "ci"], files: [".husky/pre-commit", ".lintstagedrc", "commitlint.config.js"], importance: 4 }, + ], + }, + { + sessionRange: [5, 9], + daysAgoRange: [24, 20], + project: "webapp", + observations: [ + { type: "file_edit", title: "Implement NextAuth.js v5 authentication", subtitle: "Auth setup", facts: ["Configured NextAuth.js v5 with Auth.js", "Added GitHub and Google OAuth providers", "Set up JWT session strategy with 30-day expiry"], narrative: "Implemented authentication using NextAuth.js v5 (Auth.js). Configured GitHub and Google as OAuth providers. Using JWT-based sessions with 30-day expiry instead of database sessions for simplicity.", concepts: ["nextauth", "authentication", "oauth", "jwt", "github", "google"], files: ["src/auth.ts", "src/app/api/auth/[...nextauth]/route.ts", ".env.local"], importance: 9 }, + { type: "file_edit", title: "Create login and signup pages", subtitle: "Auth UI", facts: ["Built login page with OAuth buttons", "Added email/password form with validation", "Implemented error toast notifications"], narrative: "Created the login page with GitHub and Google OAuth sign-in buttons plus an email/password form. Used react-hook-form with zod validation. Added toast notifications for login errors.", concepts: ["login", "signup", "oauth", "form-validation", "react-hook-form", "zod"], files: ["src/app/login/page.tsx", "src/app/signup/page.tsx"], importance: 7 }, + { type: "file_edit", title: "Add middleware for route protection", subtitle: "Auth middleware", facts: ["Created middleware.ts to protect /dashboard routes", "Redirects unauthenticated users to /login", "Allows public access to /api/webhooks"], narrative: "Added Next.js middleware that checks for valid sessions on protected routes (/dashboard/*). Unauthenticated users are redirected to /login. The /api/webhooks path is excluded from auth checks for third-party integrations.", concepts: ["middleware", "route-protection", "authentication", "security"], files: ["src/middleware.ts"], importance: 8 }, + { type: "file_edit", title: "Implement role-based access control", subtitle: "RBAC", facts: ["Added user roles: admin, editor, viewer", "Created withAuth HOC for role checking", "Stored roles in JWT custom claims"], narrative: "Implemented role-based access control with three roles: admin, editor, and viewer. Created a withAuth higher-order component that checks user roles before rendering protected components. Roles are stored as custom claims in the JWT token.", concepts: ["rbac", "authorization", "roles", "jwt-claims", "security"], files: ["src/lib/auth/rbac.ts", "src/lib/auth/with-auth.tsx"], importance: 8 }, + { type: "file_edit", title: "Add password hashing with bcrypt", subtitle: "Security", facts: ["Using bcrypt with cost factor 12", "Added password strength validation (min 8 chars, mixed case, number)", "Implemented rate limiting on login endpoint (5 attempts per 15 min)"], narrative: "Added bcrypt password hashing with cost factor 12 for the email/password authentication flow. Implemented password strength validation requiring minimum 8 characters with mixed case and numbers. Added rate limiting on the login API endpoint: 5 attempts per 15-minute window per IP.", concepts: ["bcrypt", "password-hashing", "rate-limiting", "security", "validation"], files: ["src/lib/auth/password.ts", "src/app/api/auth/login/route.ts"], importance: 9 }, + { type: "file_edit", title: "Create user profile settings page", subtitle: "User settings", facts: ["Profile page shows avatar, name, email", "Added avatar upload with S3 presigned URLs", "Implemented account deletion flow"], narrative: "Built the user profile settings page showing avatar, name, and email. Added avatar upload using S3 presigned URLs for direct browser-to-S3 uploads. Implemented a full account deletion flow with email confirmation.", concepts: ["user-profile", "settings", "s3", "file-upload", "account-deletion"], files: ["src/app/dashboard/settings/page.tsx", "src/app/api/upload/route.ts"], importance: 6 }, + { type: "command_run", title: "Debug OAuth callback URL mismatch", subtitle: "Auth debugging", facts: ["GitHub OAuth callback failed with redirect_uri_mismatch", "Fixed: NEXTAUTH_URL was set to http:// but app served on https://", "Lesson: always use HTTPS in production OAuth callback URLs"], narrative: "Spent time debugging why GitHub OAuth login failed in production. The error was redirect_uri_mismatch. Root cause: NEXTAUTH_URL environment variable was set to http://localhost:3000 in production instead of the HTTPS production URL. Fixed by updating the environment variable.", concepts: ["oauth-debugging", "github", "callback-url", "environment-variables", "production"], files: [".env.production"], importance: 7 }, + { type: "file_edit", title: "Add CSRF protection to API routes", subtitle: "Security", facts: ["Implemented double-submit cookie pattern", "Added CSRF token generation in layout", "Validated CSRF token on all POST/PUT/DELETE requests"], narrative: "Added CSRF protection using the double-submit cookie pattern. A CSRF token is generated on page load and stored in both a cookie and a hidden form field. All mutating API requests (POST, PUT, DELETE) validate the token.", concepts: ["csrf", "security", "cookies", "api-protection"], files: ["src/lib/csrf.ts", "src/middleware.ts"], importance: 8 }, + ], + }, + { + sessionRange: [10, 14], + daysAgoRange: [19, 15], + project: "webapp", + observations: [ + { type: "file_edit", title: "Set up Prisma ORM with PostgreSQL", subtitle: "Database", facts: ["Initialized Prisma with PostgreSQL provider", "Created User, Post, Comment, Tag models", "Generated migrations with prisma migrate dev"], narrative: "Set up Prisma ORM connecting to a PostgreSQL database. Defined the initial schema with User, Post, Comment, and Tag models including many-to-many relationships between Post and Tag.", concepts: ["prisma", "postgresql", "database", "orm", "schema", "migrations"], files: ["prisma/schema.prisma", "src/lib/db.ts"], importance: 9 }, + { type: "file_edit", title: "Create database seed script", subtitle: "Seeding", facts: ["Created seed.ts with faker-generated data", "Seeds 10 users, 50 posts, 200 comments", "Runs via prisma db seed command"], narrative: "Built a database seed script using faker.js to generate realistic test data. Creates 10 users with posts, comments, and tags. Configured to run automatically on prisma db seed.", concepts: ["database", "seeding", "faker", "test-data", "prisma"], files: ["prisma/seed.ts", "package.json"], importance: 5 }, + { type: "file_edit", title: "Implement server actions for CRUD operations", subtitle: "Data layer", facts: ["Created server actions for post CRUD", "Used Prisma transactions for multi-step operations", "Added revalidatePath after mutations"], narrative: "Implemented Next.js server actions for post create, read, update, and delete operations. Used Prisma transactions for operations that modify multiple tables. Called revalidatePath after mutations to refresh cached data.", concepts: ["server-actions", "crud", "prisma", "transactions", "revalidation", "caching"], files: ["src/app/actions/posts.ts"], importance: 8 }, + { type: "command_run", title: "Fix N+1 query in post listing", subtitle: "Performance", facts: ["Identified N+1 query loading post authors individually", "Fixed with Prisma include for eager loading", "Query count dropped from 52 to 3"], narrative: "Discovered an N+1 query problem on the post listing page — each post was triggering a separate query to load its author. Fixed by using Prisma's include option for eager loading. Total query count dropped from 52 to 3.", concepts: ["n+1", "performance", "prisma", "eager-loading", "query-optimization"], files: ["src/app/actions/posts.ts"], importance: 8 }, + { type: "file_edit", title: "Add full-text search with PostgreSQL tsvector", subtitle: "Search", facts: ["Created tsvector column on posts table", "Built GIN index for fast text search", "Implemented search API with ts_rank scoring"], narrative: "Added full-text search using PostgreSQL's built-in tsvector functionality. Created a generated tsvector column combining title and body, with a GIN index. The search API uses ts_rank for relevance scoring and supports phrase matching.", concepts: ["full-text-search", "postgresql", "tsvector", "gin-index", "search"], files: ["prisma/migrations/20260301_add_search.sql", "src/app/api/search/route.ts"], importance: 7 }, + { type: "file_edit", title: "Set up connection pooling with PgBouncer", subtitle: "Database infra", facts: ["Deployed PgBouncer in transaction pooling mode", "Configured max 25 client connections, 10 server connections", "Added DATABASE_URL_DIRECT for migrations (bypasses pooler)"], narrative: "Deployed PgBouncer as a connection pooler for PostgreSQL. Using transaction pooling mode to maximize connection reuse. Configured separate DATABASE_URL for application use (through pooler) and DATABASE_URL_DIRECT for migrations.", concepts: ["pgbouncer", "connection-pooling", "postgresql", "infrastructure"], files: ["docker-compose.yml", ".env"], importance: 7 }, + { type: "command_run", title: "Debug Prisma migration drift", subtitle: "Database debugging", facts: ["prisma migrate deploy failed with drift detected", "Cause: manual SQL ALTER was run directly on production", "Resolution: ran prisma migrate resolve to mark migration as applied"], narrative: "Production deployment failed because Prisma detected schema drift — someone had run a manual ALTER TABLE directly on the production database. Resolved by using prisma migrate resolve to mark the conflicting migration as already applied.", concepts: ["prisma", "migration-drift", "database", "production", "debugging"], files: ["prisma/schema.prisma"], importance: 7 }, + { type: "file_edit", title: "Add Redis caching layer for expensive queries", subtitle: "Caching", facts: ["Used ioredis with 60-second TTL for post listings", "Implemented cache-aside pattern", "Added cache invalidation on post mutations"], narrative: "Added a Redis caching layer for expensive database queries. Post listings are cached for 60 seconds using a cache-aside pattern. Cache entries are invalidated when posts are created, updated, or deleted.", concepts: ["redis", "caching", "cache-aside", "ioredis", "performance"], files: ["src/lib/cache.ts", "src/app/actions/posts.ts"], importance: 7 }, + ], + }, + { + sessionRange: [15, 19], + daysAgoRange: [14, 10], + project: "webapp", + observations: [ + { type: "file_edit", title: "Build REST API with input validation", subtitle: "API", facts: ["Created /api/v1/posts, /api/v1/users endpoints", "Used zod for request body validation", "Added consistent error response format with error codes"], narrative: "Built a versioned REST API under /api/v1/ with endpoints for posts and users. All request bodies are validated with zod schemas. Errors follow a consistent format with error codes, messages, and field-level details.", concepts: ["rest-api", "zod", "validation", "error-handling", "api-design"], files: ["src/app/api/v1/posts/route.ts", "src/app/api/v1/users/route.ts", "src/lib/api/errors.ts"], importance: 8 }, + { type: "file_edit", title: "Implement cursor-based pagination", subtitle: "API pagination", facts: ["Replaced offset pagination with cursor-based approach", "Uses Prisma cursor with opaque base64-encoded cursors", "Returns hasNextPage and endCursor in response"], narrative: "Switched from offset-based to cursor-based pagination for the post listing API. Cursors are base64-encoded Prisma record IDs. Response includes hasNextPage boolean and endCursor for the client to request the next page.", concepts: ["pagination", "cursor-based", "prisma", "api-design", "performance"], files: ["src/app/api/v1/posts/route.ts", "src/lib/api/pagination.ts"], importance: 7 }, + { type: "file_edit", title: "Add API rate limiting with Upstash Redis", subtitle: "Rate limiting", facts: ["Used @upstash/ratelimit with sliding window algorithm", "10 requests per 10 seconds per API key", "Returns X-RateLimit-Remaining header"], narrative: "Implemented API rate limiting using Upstash Redis with a sliding window algorithm. Each API key is limited to 10 requests per 10-second window. Rate limit status is communicated via standard X-RateLimit-* headers.", concepts: ["rate-limiting", "upstash", "redis", "api-security", "sliding-window"], files: ["src/middleware.ts", "src/lib/rate-limit.ts"], importance: 8 }, + { type: "file_edit", title: "Create webhook system for external integrations", subtitle: "Webhooks", facts: ["Built webhook registration and delivery system", "Events: post.created, post.updated, user.signup", "Implemented retry with exponential backoff (max 3 retries)"], narrative: "Created a webhook system allowing external services to subscribe to events. Supports post.created, post.updated, and user.signup events. Webhook deliveries use exponential backoff with up to 3 retries on failure.", concepts: ["webhooks", "events", "integrations", "retry", "exponential-backoff"], files: ["src/lib/webhooks.ts", "src/app/api/v1/webhooks/route.ts"], importance: 7 }, + { type: "file_edit", title: "Add OpenAPI specification with Swagger UI", subtitle: "API docs", facts: ["Generated OpenAPI 3.1 spec from zod schemas", "Added Swagger UI at /api/docs", "Included request/response examples"], narrative: "Generated an OpenAPI 3.1 specification from the existing zod validation schemas. Added Swagger UI accessible at /api/docs for interactive API documentation with request/response examples.", concepts: ["openapi", "swagger", "api-documentation", "zod"], files: ["src/app/api/docs/route.ts", "src/lib/openapi.ts"], importance: 5 }, + { type: "command_run", title: "Debug 504 gateway timeout on large queries", subtitle: "Performance debugging", facts: ["Large post queries timing out after 30 seconds on Vercel", "Root cause: missing database index on posts.authorId", "Added composite index (authorId, createdAt DESC), query dropped to 50ms"], narrative: "Investigated 504 Gateway Timeout errors on the post listing endpoint in production (Vercel). Found that large queries filtering by author were doing a full table scan. Added a composite index on (authorId, createdAt DESC) which reduced query time from 30+ seconds to 50ms.", concepts: ["performance", "timeout", "database-index", "postgresql", "vercel", "debugging"], files: ["prisma/migrations/20260310_add_author_index.sql"], importance: 9 }, + { type: "file_edit", title: "Implement API versioning strategy", subtitle: "API design", facts: ["URL-based versioning: /api/v1/, /api/v2/", "v1 deprecated with Sunset header", "Migration guide in API docs"], narrative: "Established an API versioning strategy using URL-based versioning (/api/v1/, /api/v2/). The v1 API returns a Sunset header indicating its deprecation date. Added a migration guide to the API documentation.", concepts: ["api-versioning", "deprecation", "sunset-header", "backward-compatibility"], files: ["src/app/api/v2/posts/route.ts", "src/lib/api/versioning.ts"], importance: 6 }, + { type: "file_edit", title: "Add request logging with structured JSON", subtitle: "Observability", facts: ["Used pino for structured JSON logging", "Logs request method, path, status, duration, user ID", "Configured log levels per environment"], narrative: "Added structured JSON request logging using pino. Each request logs method, path, response status, duration in milliseconds, and authenticated user ID. Log levels are configured per environment (debug in dev, info in production).", concepts: ["logging", "pino", "observability", "structured-logging", "monitoring"], files: ["src/lib/logger.ts", "src/middleware.ts"], importance: 6 }, + ], + }, + { + sessionRange: [20, 24], + daysAgoRange: [9, 5], + project: "webapp", + observations: [ + { type: "file_edit", title: "Write unit tests for auth module", subtitle: "Testing", facts: ["25 test cases covering login, signup, role checking", "Mocked Prisma client with vitest", "Achieved 92% coverage on auth module"], narrative: "Wrote comprehensive unit tests for the authentication module. 25 test cases covering login flow, signup validation, role-based access checks, and password hashing. Mocked the Prisma client using vitest's vi.mock. Achieved 92% code coverage.", concepts: ["unit-testing", "vitest", "mocking", "authentication", "coverage"], files: ["tests/unit/auth.test.ts", "tests/unit/rbac.test.ts"], importance: 7 }, + { type: "file_edit", title: "Add E2E tests with Playwright", subtitle: "E2E testing", facts: ["Configured Playwright with Chrome and Firefox", "Tests: login flow, post CRUD, search, pagination", "Set up test database with Docker for isolation"], narrative: "Set up Playwright for end-to-end testing with Chrome and Firefox browsers. Created E2E tests for the complete login flow, post CRUD operations, search functionality, and pagination. Each test run gets a fresh database via Docker containers.", concepts: ["playwright", "e2e-testing", "docker", "test-isolation", "browser-testing"], files: ["playwright.config.ts", "tests/e2e/auth.spec.ts", "tests/e2e/posts.spec.ts", "docker-compose.test.yml"], importance: 8 }, + { type: "command_run", title: "Fix flaky Playwright test on CI", subtitle: "CI debugging", facts: ["Test passed locally but failed in GitHub Actions", "Root cause: missing waitForNavigation after form submit", "Fixed by using page.waitForURL instead of waitForNavigation"], narrative: "Debugged a flaky Playwright test that passed locally but failed intermittently in GitHub Actions CI. The issue was a race condition after form submission — the test was checking the URL before navigation completed. Fixed by replacing the deprecated waitForNavigation with page.waitForURL.", concepts: ["playwright", "flaky-test", "ci", "github-actions", "debugging", "race-condition"], files: ["tests/e2e/auth.spec.ts"], importance: 6 }, + { type: "file_edit", title: "Add API integration tests with supertest", subtitle: "API testing", facts: ["30 test cases for REST API endpoints", "Tests validation, auth, error responses, pagination", "Uses test database with transaction rollback"], narrative: "Created API integration tests using supertest. 30 test cases covering request validation, authentication requirements, error response formats, and cursor-based pagination. Each test runs in a database transaction that rolls back after completion.", concepts: ["integration-testing", "supertest", "api-testing", "transactions", "test-isolation"], files: ["tests/integration/api.test.ts"], importance: 7 }, + { type: "file_edit", title: "Set up test coverage reporting with codecov", subtitle: "Coverage", facts: ["Configured vitest coverage with v8 provider", "Minimum coverage thresholds: 80% branches, 85% lines", "Upload to Codecov in CI pipeline"], narrative: "Configured vitest code coverage using the v8 provider. Set minimum coverage thresholds at 80% for branches and 85% for lines. Coverage reports are uploaded to Codecov as part of the GitHub Actions CI pipeline.", concepts: ["code-coverage", "codecov", "vitest", "ci", "quality-gates"], files: ["vitest.config.ts", ".github/workflows/ci.yml"], importance: 5 }, + { type: "file_edit", title: "Create test fixtures and factories", subtitle: "Test infrastructure", facts: ["Built factory functions for User, Post, Comment, Tag", "Uses faker for realistic data generation", "Supports partial overrides for specific test scenarios"], narrative: "Created test factory functions for all main models (User, Post, Comment, Tag). Factories use faker.js for realistic data and support partial overrides so individual tests can customize specific fields.", concepts: ["test-factories", "faker", "testing-infrastructure", "fixtures"], files: ["tests/fixtures/factories.ts"], importance: 5 }, + { type: "command_run", title: "Debug memory leak in test suite", subtitle: "Test debugging", facts: ["Tests consuming 2GB+ RAM after 100+ test files", "Root cause: Prisma client not disconnected in afterAll", "Fixed by adding global teardown that calls prisma.$disconnect()"], narrative: "Investigated why the test suite was consuming over 2GB of RAM. The Prisma client was creating new connections in each test file but never disconnecting. Fixed by adding a global teardown hook that calls prisma.$disconnect().", concepts: ["memory-leak", "testing", "prisma", "debugging", "resource-management"], files: ["vitest.config.ts", "tests/setup.ts"], importance: 7 }, + { type: "file_edit", title: "Add snapshot testing for API responses", subtitle: "Snapshot tests", facts: ["Added toMatchSnapshot for API response shapes", "Snapshot updates require --update flag", "Catches unintended breaking changes in API responses"], narrative: "Added snapshot testing for API response shapes to catch unintended breaking changes. Response bodies are compared against stored snapshots. Snapshots must be explicitly updated with the --update flag when intentional changes are made.", concepts: ["snapshot-testing", "api-testing", "regression-testing", "vitest"], files: ["tests/integration/api.test.ts", "tests/integration/__snapshots__/"], importance: 4 }, + ], + }, + { + sessionRange: [25, 29], + daysAgoRange: [4, 0], + project: "webapp", + observations: [ + { type: "file_edit", title: "Create multi-stage Dockerfile", subtitle: "Docker", facts: ["Multi-stage build: deps → build → production", "Final image size 180MB (down from 1.2GB)", "Runs as non-root user with UID 1001"], narrative: "Created a multi-stage Dockerfile for the Next.js application. Stage 1 installs dependencies, stage 2 builds the app, stage 3 copies only production artifacts. Final image is 180MB (down from 1.2GB). Application runs as a non-root user for security.", concepts: ["docker", "multi-stage-build", "containerization", "security", "image-optimization"], files: ["Dockerfile", ".dockerignore"], importance: 7 }, + { type: "file_edit", title: "Set up GitHub Actions CI/CD pipeline", subtitle: "CI/CD", facts: ["Matrix build: Node 18 and 20", "Jobs: lint, test, build, deploy", "Auto-deploy to Vercel on main branch push"], narrative: "Created a comprehensive GitHub Actions CI/CD pipeline with matrix builds for Node 18 and 20. Pipeline runs lint, test (with coverage), build, and deploy jobs. Merges to main automatically trigger Vercel deployment.", concepts: ["github-actions", "ci-cd", "deployment", "vercel", "automation"], files: [".github/workflows/ci.yml", ".github/workflows/deploy.yml"], importance: 8 }, + { type: "file_edit", title: "Configure Kubernetes deployment manifests", subtitle: "K8s", facts: ["Created Deployment, Service, Ingress, HPA resources", "HPA: min 2, max 10 replicas, CPU target 70%", "Health checks: liveness on /healthz, readiness on /readyz"], narrative: "Created Kubernetes deployment manifests including Deployment, Service, Ingress, and HorizontalPodAutoscaler. HPA scales between 2 and 10 replicas targeting 70% CPU utilization. Added liveness and readiness probes for health monitoring.", concepts: ["kubernetes", "deployment", "hpa", "autoscaling", "health-checks", "ingress"], files: ["k8s/deployment.yaml", "k8s/service.yaml", "k8s/ingress.yaml", "k8s/hpa.yaml"], importance: 8 }, + { type: "file_edit", title: "Add Terraform for AWS infrastructure", subtitle: "IaC", facts: ["VPC with public/private subnets across 3 AZs", "RDS PostgreSQL with Multi-AZ failover", "ElastiCache Redis cluster with 2 replicas"], narrative: "Created Terraform modules for AWS infrastructure. VPC spans 3 availability zones with public and private subnets. RDS PostgreSQL instance with Multi-AZ failover for high availability. ElastiCache Redis cluster with 2 read replicas.", concepts: ["terraform", "aws", "infrastructure-as-code", "vpc", "rds", "elasticache"], files: ["terraform/main.tf", "terraform/vpc.tf", "terraform/rds.tf", "terraform/redis.tf"], importance: 8 }, + { type: "command_run", title: "Debug Kubernetes pod crash loop", subtitle: "K8s debugging", facts: ["Pods in CrashLoopBackOff status", "Root cause: DATABASE_URL secret not mounted correctly", "Fixed: Secret key name was 'database-url' but env var expected 'DATABASE_URL'"], narrative: "Debugged pods stuck in CrashLoopBackOff. The application was failing to start because the DATABASE_URL environment variable was empty. Root cause: the Kubernetes secret had the key 'database-url' (kebab-case) but the secretKeyRef expected 'DATABASE_URL' (uppercase).", concepts: ["kubernetes", "debugging", "crashloopbackoff", "secrets", "environment-variables"], files: ["k8s/deployment.yaml", "k8s/secrets.yaml"], importance: 8 }, + { type: "file_edit", title: "Set up Datadog monitoring and alerting", subtitle: "Monitoring", facts: ["Deployed Datadog agent as DaemonSet", "Custom metrics: request latency, error rate, DB query time", "Alerts: p99 latency > 500ms, error rate > 1%"], narrative: "Deployed the Datadog monitoring agent as a Kubernetes DaemonSet. Created custom metrics for request latency, error rate, and database query time. Set up alerts that trigger when p99 latency exceeds 500ms or error rate exceeds 1%.", concepts: ["datadog", "monitoring", "alerting", "observability", "kubernetes"], files: ["k8s/datadog-agent.yaml", "src/lib/metrics.ts"], importance: 7 }, + { type: "file_edit", title: "Implement blue-green deployment strategy", subtitle: "Deployment", facts: ["Two identical environments: blue and green", "Health check must pass before traffic switch", "Instant rollback by switching back to previous color"], narrative: "Implemented blue-green deployment strategy. Two identical environments run simultaneously — deploy to the inactive one, run health checks, then switch traffic via Kubernetes service selector update. Rollback is instant by pointing traffic back to the previous color.", concepts: ["blue-green", "deployment-strategy", "zero-downtime", "rollback", "kubernetes"], files: ["k8s/blue-deployment.yaml", "k8s/green-deployment.yaml", "scripts/deploy.sh"], importance: 7 }, + { type: "file_edit", title: "Add Prometheus metrics and Grafana dashboards", subtitle: "Observability", facts: ["Exported custom metrics via /metrics endpoint", "Metrics: http_request_duration, db_query_duration, cache_hit_ratio", "Created Grafana dashboard with request rate, latency, error panels"], narrative: "Added Prometheus metrics export on a /metrics endpoint. Custom metrics include HTTP request duration histogram, database query duration, and cache hit ratio. Created a Grafana dashboard with panels for request rate, latency percentiles, error rate, and cache performance.", concepts: ["prometheus", "grafana", "metrics", "observability", "dashboards"], files: ["src/lib/metrics.ts", "grafana/dashboard.json"], importance: 6 }, + ], + }, +]; + +export function generateDataset(): { + observations: CompressedObservation[]; + queries: LabeledQuery[]; + sessions: Map; +} { + const observations: CompressedObservation[] = []; + const sessions = new Map(); + + for (const group of RAW_SESSIONS) { + const [sStart, sEnd] = group.sessionRange; + const [dStart, dEnd] = group.daysAgoRange; + + for (let s = sStart; s <= sEnd; s++) { + const sessionId = `ses_${s.toString().padStart(3, "0")}`; + const daysAgo = dStart - ((s - sStart) / Math.max(1, sEnd - sStart)) * (dStart - dEnd); + const obsIds: string[] = []; + + const obsPerSession = Math.min(group.observations.length, OBS_PER_SESSION); + for (let o = 0; o < obsPerSession; o++) { + const idx = ((s - sStart) * obsPerSession + o) % group.observations.length; + const raw = group.observations[idx]; + const obsId = `obs_${sessionId}_${o.toString().padStart(2, "0")}`; + const hourOffset = o * 0.5; + + observations.push({ + id: obsId, + sessionId, + timestamp: ts(daysAgo - hourOffset / 24), + ...raw, + }); + obsIds.push(obsId); + } + sessions.set(sessionId, obsIds); + } + } + + const queries: LabeledQuery[] = [ + { + query: "How did we set up authentication?", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["nextauth", "authentication", "oauth", "jwt", "login", "signup"].includes(c))).map(o => o.id), + description: "Should find all auth-related observations across sessions 5-9", + category: "semantic", + }, + { + query: "JWT token validation middleware", + relevantObsIds: observations.filter(o => o.concepts.includes("jwt") || (o.concepts.includes("middleware") && o.concepts.includes("authentication"))).map(o => o.id), + description: "Exact match on JWT middleware setup", + category: "exact", + }, + { + query: "PostgreSQL connection issues", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["postgresql", "pgbouncer", "connection-pooling", "database"].includes(c))).map(o => o.id), + description: "Should find database connection and pooling observations", + category: "semantic", + }, + { + query: "Playwright test configuration", + relevantObsIds: observations.filter(o => o.concepts.includes("playwright") || (o.concepts.includes("e2e-testing"))).map(o => o.id), + description: "E2E testing setup with Playwright", + category: "exact", + }, + { + query: "Why did the production deployment fail?", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["debugging", "production", "crashloopbackoff", "timeout", "migration-drift"].includes(c))).map(o => o.id), + description: "Cross-session: find all production debugging incidents", + category: "cross-session", + }, + { + query: "rate limiting implementation", + relevantObsIds: observations.filter(o => o.concepts.includes("rate-limiting")).map(o => o.id), + description: "Rate limiting across auth and API modules", + category: "exact", + }, + { + query: "What security measures did we add?", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["security", "csrf", "bcrypt", "rate-limiting", "rbac", "password-hashing"].includes(c))).map(o => o.id), + description: "Broad semantic: all security-related work", + category: "semantic", + }, + { + query: "database performance optimization", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["n+1", "query-optimization", "database-index", "performance", "eager-loading", "caching"].includes(c))).map(o => o.id), + description: "Performance optimizations across database and caching", + category: "semantic", + }, + { + query: "Kubernetes pod crash debugging", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["crashloopbackoff", "kubernetes"].includes(c)) && o.concepts.includes("debugging")).map(o => o.id), + description: "Specific K8s debugging incident", + category: "entity", + }, + { + query: "Docker containerization setup", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["docker", "multi-stage-build", "containerization", "dockerfile"].includes(c))).map(o => o.id), + description: "Docker-related observations", + category: "entity", + }, + { + query: "How does caching work in the app?", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["redis", "caching", "cache-aside", "ioredis", "elasticache"].includes(c))).map(o => o.id), + description: "All caching-related observations", + category: "semantic", + }, + { + query: "test infrastructure and factories", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["test-factories", "testing-infrastructure", "fixtures", "mocking"].includes(c))).map(o => o.id), + description: "Test setup infrastructure", + category: "exact", + }, + { + query: "What happened with the OAuth callback error?", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["oauth-debugging", "callback-url"].includes(c))).map(o => o.id), + description: "Specific debugging incident recall", + category: "cross-session", + }, + { + query: "monitoring and observability setup", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["datadog", "prometheus", "grafana", "monitoring", "observability", "alerting", "metrics", "logging", "pino"].includes(c))).map(o => o.id), + description: "All monitoring/observability observations", + category: "semantic", + }, + { + query: "Prisma ORM configuration", + relevantObsIds: observations.filter(o => o.concepts.includes("prisma")).map(o => o.id), + description: "All Prisma-related observations", + category: "entity", + }, + { + query: "CI/CD pipeline configuration", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["ci-cd", "github-actions", "deployment", "ci"].includes(c))).map(o => o.id), + description: "CI/CD related observations", + category: "exact", + }, + { + query: "memory leak debugging", + relevantObsIds: observations.filter(o => o.concepts.includes("memory-leak")).map(o => o.id), + description: "Memory leak incidents (WebSocket handler, test suite)", + category: "cross-session", + }, + { + query: "API design decisions", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["rest-api", "api-design", "api-versioning", "pagination", "openapi", "error-handling"].includes(c))).map(o => o.id), + description: "API design and architecture decisions", + category: "semantic", + }, + { + query: "zod validation schemas", + relevantObsIds: observations.filter(o => o.concepts.includes("zod")).map(o => o.id), + description: "Where zod is used for validation", + category: "entity", + }, + { + query: "infrastructure as code Terraform", + relevantObsIds: observations.filter(o => o.concepts.some(c => ["terraform", "infrastructure-as-code", "aws", "vpc", "rds", "elasticache"].includes(c))).map(o => o.id), + description: "Terraform/IaC observations", + category: "entity", + }, + ]; + + return { observations, queries, sessions }; +} + +export function generateScaleDataset(count: number): CompressedObservation[] { + const base = generateDataset().observations; + const result: CompressedObservation[] = []; + + for (let i = 0; i < count; i++) { + const src = base[i % base.length]; + result.push({ + ...src, + id: `obs_scale_${i.toString().padStart(6, "0")}`, + sessionId: `ses_${Math.floor(i / 8).toString().padStart(4, "0")}`, + timestamp: ts(Math.random() * 90), + title: `${src.title} (iteration ${i})`, + narrative: `${src.narrative} [Scale test variant ${i}, session group ${Math.floor(i / 8)}]`, + }); + } + return result; +} diff --git a/benchmark/lib/percentiles.ts b/benchmark/lib/percentiles.ts new file mode 100644 index 0000000000000000000000000000000000000000..204feeab12cae89abf74c267869201087ad0f127 --- /dev/null +++ b/benchmark/lib/percentiles.ts @@ -0,0 +1,22 @@ +/** + * Nearest-rank percentile over a pre-sorted ascending array of numbers. + * + * No dependencies, no allocation. The caller is responsible for sorting + * the input ascending (`arr.sort((a, b) => a - b)`) — sorting in here + * would hide an O(n log n) cost in what looks like a cheap lookup. + * + * @param sorted Ascending-sorted samples. Empty array returns `NaN`. + * @param p Percentile in [0, 100]. Values outside the range are clamped. + * @returns The sample at the nearest rank, or `NaN` for empty input. + */ +export function pXX(sorted: number[], p: number): number { + const n = sorted.length; + if (n === 0) return NaN; + const clamped = Math.max(0, Math.min(100, p)); + if (clamped === 0) return sorted[0]!; + if (clamped === 100) return sorted[n - 1]!; + // Nearest-rank: rank = ceil(p/100 * n), index = rank - 1. + const rank = Math.ceil((clamped / 100) * n); + const idx = Math.min(n - 1, Math.max(0, rank - 1)); + return sorted[idx]!; +} diff --git a/benchmark/load-100k.ts b/benchmark/load-100k.ts new file mode 100644 index 0000000000000000000000000000000000000000..676aa647c659eebd0213544193b9bcf8cdd1d7b2 --- /dev/null +++ b/benchmark/load-100k.ts @@ -0,0 +1,528 @@ +/** + * Load harness — seeds N synthetic memories against a local agentmemory + * daemon, then drives a matrix of (N, concurrency, endpoint) cells and + * records p50 / p90 / p99 latency + throughput per cell. + * + * Spec: GitHub issue #346. + * + * Runs against an already-running daemon at `http://localhost:3111` by + * default. Set `AGENTMEMORY_BENCH_AUTOSTART=1` to spawn one via + * `node dist/cli.js start` for the duration of the run. + * + * Env knobs: + * AGENTMEMORY_BENCH_AUTOSTART "1" to spawn the daemon (default: assume up) + * AGENTMEMORY_URL base URL of the daemon (default: http://localhost:3111) + * BENCH_N comma-separated N sizes (default: 1000,10000,100000) + * BENCH_C comma-separated concurrency levels (default: 1,10,100) + * BENCH_OPS ops per cell during measurement (default: 200) + * BENCH_SEED seed for the mulberry32 RNG (default: 0xC0FFEE) + * BENCH_OUT_DIR results dir (default: benchmark/results) + * + * The harness writes one JSON file per run named + * `load-100k-.json`. The git sha is best-effort — falls + * back to a timestamp when run outside a checkout. + */ + +import { spawn, type ChildProcess } from "node:child_process"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync, existsSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; + +import { pXX } from "./lib/percentiles.js"; + +/** Seedable PRNG. Mulberry32 — 32-bit state, uniform output in [0, 1). */ +function mulberry32(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const NOUNS = [ + "cache", "queue", "router", "stream", "shard", "lock", "buffer", "worker", + "engine", "trigger", "function", "memory", "index", "graph", "vector", + "session", "observation", "summary", "embedding", "tokenizer", "scheduler", + "consumer", "producer", "channel", "actor", "pipeline", "watcher", "pool", +]; +const VERBS = [ + "flushes", "rotates", "compacts", "rebalances", "drains", "warms", + "expires", "deduplicates", "snapshots", "replays", "promotes", "demotes", + "merges", "splits", "indexes", "scans", "compresses", "uploads", +]; +const CONCEPTS = [ + "throughput", "latency", "backpressure", "consistency", "isolation", + "durability", "idempotency", "fan-out", "cardinality", "skew", + "hot-path", "cold-start", "tail-latency", "saturation", "quiescence", +]; + +function buildContent(rng: () => number, i: number): string { + const n = NOUNS[Math.floor(rng() * NOUNS.length)]!; + const v = VERBS[Math.floor(rng() * VERBS.length)]!; + const c1 = CONCEPTS[Math.floor(rng() * CONCEPTS.length)]!; + const c2 = CONCEPTS[Math.floor(rng() * CONCEPTS.length)]!; + const k = Math.floor(rng() * 9999); + return `seed-${i} the ${n} ${v} ${c1} under ${c2} pressure (k=${k})`; +} + +interface RunConfig { + baseUrl: string; + Ns: number[]; + Cs: number[]; + opsPerCell: number; + seed: number; + outDir: string; + autoStart: boolean; +} + +function parseIntList(raw: string | undefined, fallback: number[]): number[] { + if (!raw) return fallback; + const out = raw + .split(",") + .map((s) => parseInt(s.trim(), 10)) + .filter((n) => Number.isFinite(n) && n > 0); + return out.length > 0 ? out : fallback; +} + +function loadConfig(): RunConfig { + return { + baseUrl: (process.env["AGENTMEMORY_URL"] || "http://localhost:3111").replace( + /\/+$/, + "", + ), + Ns: parseIntList(process.env["BENCH_N"], [1000, 10000, 100000]), + Cs: parseIntList(process.env["BENCH_C"], [1, 10, 100]), + opsPerCell: parseInt(process.env["BENCH_OPS"] || "200", 10) || 200, + seed: parseInt(process.env["BENCH_SEED"] || "12648430", 10) || 12648430, + outDir: + process.env["BENCH_OUT_DIR"] || + resolve(process.cwd(), "benchmark", "results"), + autoStart: process.env["AGENTMEMORY_BENCH_AUTOSTART"] === "1", + }; +} + +async function waitForLivez(baseUrl: string, timeoutMs: number): Promise { + const start = Date.now(); + let lastErr: unknown = null; + while (Date.now() - start < timeoutMs) { + try { + const res = await fetch(`${baseUrl}/agentmemory/livez`, { + signal: AbortSignal.timeout(2000), + }); + if (res.ok) return; + lastErr = new Error(`livez HTTP ${res.status}`); + } catch (err) { + lastErr = err; + } + await new Promise((r) => setTimeout(r, 500)); + } + const reason = + lastErr instanceof Error ? lastErr.message : String(lastErr ?? "unknown"); + throw new Error( + `daemon at ${baseUrl} did not become ready within ${timeoutMs} ms: ${reason}`, + ); +} + +function maybeStartDaemon(): ChildProcess | null { + const candidates = ["dist/cli.mjs", "dist/cli.js"].map((p) => + resolve(process.cwd(), p), + ); + const cliPath = candidates.find((p) => existsSync(p)); + if (!cliPath) { + throw new Error( + `AGENTMEMORY_BENCH_AUTOSTART=1 but neither ${candidates.join(" nor ")} exists — run \`npm run build\` first`, + ); + } + const child = spawn(process.execPath, [cliPath, "start"], { + stdio: ["ignore", "pipe", "pipe"], + detached: false, + }); + child.stdout?.on("data", () => { + /* drain */ + }); + child.stderr?.on("data", () => { + /* drain */ + }); + return child; +} + +function shortGitSha(): string { + try { + const sha = execFileSync("git", ["rev-parse", "--short", "HEAD"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + if (sha) return sha; + } catch { + /* no git */ + } + return `nogit-${Date.now().toString(36)}`; +} + +interface CellResult { + endpoint: string; + N: number; + C: number; + ops: number; + errors: number; + wall_ms: number; + throughput_per_sec: number; + p50_ms: number; + p90_ms: number; + p99_ms: number; + min_ms: number; + max_ms: number; +} + +/** + * Issue `total` requests against `fetcher`, capped at `concurrency` + * in-flight at any moment. Records per-request latency in ms. + */ +async function driveLoad( + concurrency: number, + total: number, + fetcher: (i: number) => Promise, +): Promise<{ latencies: number[]; errors: number; wallMs: number }> { + const latencies: number[] = []; + let errors = 0; + let issued = 0; + const wallStart = performance.now(); + + async function worker(): Promise { + while (true) { + const i = issued++; + if (i >= total) return; + const t0 = performance.now(); + try { + await fetcher(i); + latencies.push(performance.now() - t0); + } catch { + errors++; + } + } + } + + const workers = Array.from({ length: Math.max(1, concurrency) }, () => + worker(), + ); + await Promise.allSettled(workers); + const wallMs = performance.now() - wallStart; + return { latencies, errors, wallMs }; +} + +function summarize( + endpoint: string, + N: number, + C: number, + latencies: number[], + errors: number, + wallMs: number, +): CellResult { + const sorted = latencies.slice().sort((a, b) => a - b); + const ops = sorted.length; + return { + endpoint, + N, + C, + ops, + errors, + wall_ms: Math.round(wallMs * 1000) / 1000, + throughput_per_sec: + wallMs > 0 ? Math.round((ops / (wallMs / 1000)) * 100) / 100 : 0, + p50_ms: Math.round(pXX(sorted, 50) * 1000) / 1000, + p90_ms: Math.round(pXX(sorted, 90) * 1000) / 1000, + p99_ms: Math.round(pXX(sorted, 99) * 1000) / 1000, + min_ms: ops > 0 ? Math.round(sorted[0]! * 1000) / 1000 : NaN, + max_ms: ops > 0 ? Math.round(sorted[ops - 1]! * 1000) / 1000 : NaN, + }; +} + +async function seedMemories( + baseUrl: string, + count: number, + rng: () => number, + seedConcurrency = 32, +): Promise<{ seeded: number; errors: number; wallMs: number }> { + let issued = 0; + let seeded = 0; + let errors = 0; + const t0 = performance.now(); + async function worker(): Promise { + while (true) { + const i = issued++; + if (i >= count) return; + const body = JSON.stringify({ + content: buildContent(rng, i), + type: "observation", + }); + try { + const res = await fetch(`${baseUrl}/agentmemory/remember`, { + method: "POST", + headers: { "content-type": "application/json" }, + body, + signal: AbortSignal.timeout(30_000), + }); + if (res.ok) { + seeded++; + } else { + errors++; + } + // drain body to free the socket + await res.text().catch(() => ""); + } catch { + errors++; + } + } + } + await Promise.allSettled( + Array.from({ length: seedConcurrency }, () => worker()), + ); + return { seeded, errors, wallMs: performance.now() - t0 }; +} + +async function measureRemember( + baseUrl: string, + rng: () => number, + N: number, + C: number, + ops: number, +): Promise { + const { latencies, errors, wallMs } = await driveLoad(C, ops, async (i) => { + const body = JSON.stringify({ + content: buildContent(rng, N + i), + type: "observation", + }); + const res = await fetch(`${baseUrl}/agentmemory/remember`, { + method: "POST", + headers: { "content-type": "application/json" }, + body, + signal: AbortSignal.timeout(30_000), + }); + await res.text().catch(() => ""); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + }); + return summarize("POST /agentmemory/remember", N, C, latencies, errors, wallMs); +} + +async function measureSmartSearch( + baseUrl: string, + rng: () => number, + N: number, + C: number, + ops: number, +): Promise { + const queries = Array.from({ length: 32 }, (_, i) => buildContent(rng, i)); + const { latencies, errors, wallMs } = await driveLoad(C, ops, async (i) => { + const body = JSON.stringify({ + query: queries[i % queries.length], + limit: 5, + }); + const res = await fetch(`${baseUrl}/agentmemory/smart-search`, { + method: "POST", + headers: { "content-type": "application/json" }, + body, + signal: AbortSignal.timeout(30_000), + }); + await res.text().catch(() => ""); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + }); + return summarize( + "POST /agentmemory/smart-search", + N, + C, + latencies, + errors, + wallMs, + ); +} + +async function measureMemoriesLatest( + baseUrl: string, + N: number, + C: number, + ops: number, +): Promise { + const { latencies, errors, wallMs } = await driveLoad(C, ops, async () => { + const res = await fetch(`${baseUrl}/agentmemory/memories?latest=true`, { + method: "GET", + signal: AbortSignal.timeout(30_000), + }); + await res.text().catch(() => ""); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + }); + return summarize( + "GET /agentmemory/memories?latest=true", + N, + C, + latencies, + errors, + wallMs, + ); +} + +interface RunReport { + schema_version: 1; + generated_at: string; + git_sha: string; + base_url: string; + seed: number; + matrix: { N: number[]; C: number[] }; + ops_per_cell: number; + cells: CellResult[]; + notes: string; +} + +async function main(): Promise { + const cfg = loadConfig(); + console.log( + `[load-100k] base=${cfg.baseUrl} N=${cfg.Ns.join(",")} C=${cfg.Cs.join(",")} ops/cell=${cfg.opsPerCell} seed=${cfg.seed}`, + ); + + let daemon: ChildProcess | null = null; + if (cfg.autoStart) { + console.log("[load-100k] AGENTMEMORY_BENCH_AUTOSTART=1 — spawning daemon"); + daemon = maybeStartDaemon(); + } + + try { + console.log("[load-100k] waiting for /agentmemory/livez (timeout 30s)"); + await waitForLivez(cfg.baseUrl, 30_000); + + const cells: CellResult[] = []; + // N sorted ascending so each cell builds on the previous seed work. + const sortedNs = cfg.Ns.slice().sort((a, b) => a - b); + let seededSoFar = 0; + for (const N of sortedNs) { + const delta = N - seededSoFar; + if (delta > 0) { + console.log( + `[load-100k] seeding ${delta} memories (target N=${N})`, + ); + const rng = mulberry32(cfg.seed + seededSoFar); + const seedRes = await seedMemories(cfg.baseUrl, delta, rng); + seededSoFar += seedRes.seeded; + console.log( + `[load-100k] seeded=${seedRes.seeded} errors=${seedRes.errors} wall=${( + seedRes.wallMs / 1000 + ).toFixed(2)}s`, + ); + if (seedRes.errors > 0 && seedRes.seeded === 0) { + throw new Error( + `seeding produced 0 successes and ${seedRes.errors} errors — daemon misconfigured`, + ); + } + } + + for (const C of cfg.Cs) { + const probeRng = mulberry32(cfg.seed ^ (N * 0x9e3779b1) ^ C); + + console.log(`[load-100k] cell N=${N} C=${C} remember`); + const remember = await measureRemember( + cfg.baseUrl, + probeRng, + N, + C, + cfg.opsPerCell, + ); + cells.push(remember); + + console.log(`[load-100k] cell N=${N} C=${C} smart-search`); + const search = await measureSmartSearch( + cfg.baseUrl, + mulberry32(cfg.seed ^ (N * 0x85ebca77) ^ C), + N, + C, + cfg.opsPerCell, + ); + cells.push(search); + + console.log(`[load-100k] cell N=${N} C=${C} memories?latest=true`); + const memories = await measureMemoriesLatest( + cfg.baseUrl, + N, + C, + cfg.opsPerCell, + ); + cells.push(memories); + } + } + + const report: RunReport = { + schema_version: 1, + generated_at: new Date().toISOString(), + git_sha: shortGitSha(), + base_url: cfg.baseUrl, + seed: cfg.seed, + matrix: { N: sortedNs, C: cfg.Cs.slice() }, + ops_per_cell: cfg.opsPerCell, + cells, + notes: + "Single-process load harness. Latency in milliseconds. " + + "Throughput is wall-clock ops/sec for the cell (concurrent in-flight = C).", + }; + + mkdirSync(cfg.outDir, { recursive: true }); + const outPath = join(cfg.outDir, `load-100k-${report.git_sha}.json`); + writeFileSync(outPath, JSON.stringify(report, null, 2) + "\n", "utf8"); + console.log(`[load-100k] wrote ${outPath} (${cells.length} cells)`); + + // Compact table to stdout for the verification commit. + console.log(""); + console.log( + [ + "endpoint".padEnd(40), + "N".padStart(8), + "C".padStart(4), + "ops".padStart(6), + "err".padStart(4), + "p50_ms".padStart(8), + "p90_ms".padStart(8), + "p99_ms".padStart(8), + "tp/s".padStart(9), + ].join(" "), + ); + for (const c of cells) { + console.log( + [ + c.endpoint.padEnd(40), + String(c.N).padStart(8), + String(c.C).padStart(4), + String(c.ops).padStart(6), + String(c.errors).padStart(4), + c.p50_ms.toFixed(2).padStart(8), + c.p90_ms.toFixed(2).padStart(8), + c.p99_ms.toFixed(2).padStart(8), + c.throughput_per_sec.toFixed(2).padStart(9), + ].join(" "), + ); + } + } finally { + if (daemon) { + daemon.kill("SIGTERM"); + // give it 2s to exit cleanly before SIGKILL + await new Promise((resolveFn) => { + const t = setTimeout(() => { + try { + daemon!.kill("SIGKILL"); + } catch { + /* already dead */ + } + resolveFn(); + }, 2000); + daemon!.once("exit", () => { + clearTimeout(t); + resolveFn(); + }); + }); + } + } +} + +main().catch((err) => { + console.error("[load-100k] failed:", err instanceof Error ? err.stack : err); + process.exit(1); +}); diff --git a/benchmark/longmemeval-bench.ts b/benchmark/longmemeval-bench.ts new file mode 100644 index 0000000000000000000000000000000000000000..d826e1ac17f78bfb06d0731391f5f51e6893db7d --- /dev/null +++ b/benchmark/longmemeval-bench.ts @@ -0,0 +1,317 @@ +import { SearchIndex } from "../src/state/search-index.js"; +import { VectorIndex } from "../src/state/vector-index.js"; +import { HybridSearch } from "../src/state/hybrid-search.js"; +import type { + CompressedObservation, + EmbeddingProvider, +} from "../src/types.js"; +import { readFileSync, writeFileSync, existsSync } from "node:fs"; + +interface LongMemEvalEntry { + question_id: string; + question_type: string; + question: string; + question_date: string; + answer: string; + answer_session_ids: string[]; + haystack_dates: string[]; + haystack_session_ids: string[]; + haystack_sessions: Array>; +} + +interface SessionChunk { + sessionId: string; + text: string; + turnCount: number; +} + +interface BenchResult { + question_id: string; + question_type: string; + recall_any_at_5: number; + recall_any_at_10: number; + recall_any_at_20: number; + ndcg_at_10: number; + mrr: number; + retrieved_session_ids: string[]; + gold_session_ids: string[]; +} + +function chunkSessionToText( + turns: Array<{ role: string; content: string }>, +): string { + return turns + .map((t) => `${t.role}: ${t.content}`) + .join("\n"); +} + +function recallAny( + retrievedSessionIds: string[], + goldSessionIds: string[], + k: number, +): number { + const topK = new Set(retrievedSessionIds.slice(0, k)); + return goldSessionIds.some((gid) => topK.has(gid)) ? 1.0 : 0.0; +} + +function dcg(relevances: boolean[], k: number): number { + let sum = 0; + for (let i = 0; i < Math.min(k, relevances.length); i++) { + sum += (relevances[i] ? 1 : 0) / Math.log2(i + 2); + } + return sum; +} + +function ndcg( + retrievedSessionIds: string[], + goldSessionIds: Set, + k: number, +): number { + const rels = retrievedSessionIds + .slice(0, k) + .map((id) => goldSessionIds.has(id)); + const idealRels = Array.from( + { length: Math.min(k, goldSessionIds.size) }, + () => true, + ); + const idealDCG = dcg(idealRels, k); + if (idealDCG === 0) return 0; + return dcg(rels, k) / idealDCG; +} + +function mrr( + retrievedSessionIds: string[], + goldSessionIds: Set, +): number { + for (let i = 0; i < retrievedSessionIds.length; i++) { + if (goldSessionIds.has(retrievedSessionIds[i])) return 1 / (i + 1); + } + return 0; +} + +class MockKV { + private store = new Map>(); + async get(scope: string, key: string): Promise { + const m = this.store.get(scope); + if (!m || !m.has(key)) throw new Error(`Not found: ${scope}/${key}`); + return m.get(key) as T; + } + async set(scope: string, key: string, value: unknown): Promise { + if (!this.store.has(scope)) this.store.set(scope, new Map()); + this.store.get(scope)!.set(key, value); + } + async list(scope: string): Promise { + const m = this.store.get(scope); + if (!m) return []; + return Array.from(m.values()) as T[]; + } + async delete(scope: string, key: string): Promise { + this.store.get(scope)?.delete(key); + } +} + +async function runBenchmark( + mode: "bm25" | "vector" | "hybrid", + embeddingProvider?: EmbeddingProvider, +) { + const dataPath = new URL("./data/longmemeval_s_cleaned.json", import.meta.url).pathname; + if (!existsSync(dataPath)) { + console.error(`Dataset not found at ${dataPath}`); + console.error("Download from: https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned"); + process.exit(1); + } + + console.log(`Loading LongMemEval-S dataset...`); + const raw = JSON.parse(readFileSync(dataPath, "utf-8")) as LongMemEvalEntry[]; + + const abstentionTypes = new Set([ + "single-session-user_abs", + "multi-session_abs", + "knowledge-update_abs", + "temporal-reasoning_abs", + ]); + const entries = raw.filter((e) => !abstentionTypes.has(e.question_type)); + console.log( + `Loaded ${entries.length} questions (${raw.length - entries.length} abstention excluded)`, + ); + + const results: BenchResult[] = []; + let processed = 0; + + for (const entry of entries) { + const sessionChunks: SessionChunk[] = []; + for (let i = 0; i < entry.haystack_sessions.length; i++) { + const sessionId = entry.haystack_session_ids[i]; + const turns = entry.haystack_sessions[i]; + const text = chunkSessionToText(turns); + sessionChunks.push({ sessionId, text, turnCount: turns.length }); + } + + const bm25 = new SearchIndex(); + const vector = mode !== "bm25" ? new VectorIndex() : null; + const kv = new MockKV(); + + const observations: CompressedObservation[] = []; + for (const chunk of sessionChunks) { + const obs: CompressedObservation = { + id: `obs_${chunk.sessionId}`, + sessionId: chunk.sessionId, + timestamp: new Date().toISOString(), + type: "conversation", + title: chunk.text.slice(0, 80), + facts: [], + narrative: chunk.text, + concepts: [], + files: [], + importance: 5, + }; + observations.push(obs); + bm25.add(obs); + + if (vector && embeddingProvider) { + try { + const embedding = await embeddingProvider.embed( + chunk.text.slice(0, 512), + ); + vector.add(obs.id, chunk.sessionId, embedding); + } catch {} + } + + await kv.set(`mem:obs:${chunk.sessionId}`, obs.id, obs); + } + + let retrievedObsIds: string[]; + + if (mode === "bm25") { + const bm25Results = bm25.search(entry.question, 20); + retrievedObsIds = bm25Results.map((r) => r.obsId); + } else { + const hybridSearch = new HybridSearch( + bm25, + vector, + embeddingProvider || null, + kv as any, + 0.4, + 0.6, + 0.0, + false, + ); + const hybridResults = await hybridSearch.search(entry.question, 20); + retrievedObsIds = hybridResults.map((r) => r.observation.id); + } + + const retrievedSessionIds = retrievedObsIds.map((oid) => + oid.replace(/^obs_/, ""), + ); + const goldSet = new Set(entry.answer_session_ids); + + const result: BenchResult = { + question_id: entry.question_id, + question_type: entry.question_type, + recall_any_at_5: recallAny(retrievedSessionIds, entry.answer_session_ids, 5), + recall_any_at_10: recallAny(retrievedSessionIds, entry.answer_session_ids, 10), + recall_any_at_20: recallAny(retrievedSessionIds, entry.answer_session_ids, 20), + ndcg_at_10: ndcg(retrievedSessionIds, goldSet, 10), + mrr: mrr(retrievedSessionIds, goldSet), + retrieved_session_ids: retrievedSessionIds.slice(0, 10), + gold_session_ids: entry.answer_session_ids, + }; + results.push(result); + processed++; + + if (processed % 50 === 0) { + const avgRecall5 = + results.reduce((s, r) => s + r.recall_any_at_5, 0) / results.length; + console.log( + ` [${processed}/${entries.length}] running recall_any@5: ${(avgRecall5 * 100).toFixed(1)}%`, + ); + } + } + + const avgRecallAny5 = + results.reduce((s, r) => s + r.recall_any_at_5, 0) / results.length; + const avgRecallAny10 = + results.reduce((s, r) => s + r.recall_any_at_10, 0) / results.length; + const avgRecallAny20 = + results.reduce((s, r) => s + r.recall_any_at_20, 0) / results.length; + const avgNdcg10 = + results.reduce((s, r) => s + r.ndcg_at_10, 0) / results.length; + const avgMrr = + results.reduce((s, r) => s + r.mrr, 0) / results.length; + + const byType = new Map(); + for (const r of results) { + if (!byType.has(r.question_type)) byType.set(r.question_type, []); + byType.get(r.question_type)!.push(r); + } + + console.log(`\n=== LongMemEval-S Results (${mode}) ===`); + console.log(`Questions: ${results.length} (excl. abstention)`); + console.log(`recall_any@5: ${(avgRecallAny5 * 100).toFixed(1)}%`); + console.log(`recall_any@10: ${(avgRecallAny10 * 100).toFixed(1)}%`); + console.log(`recall_any@20: ${(avgRecallAny20 * 100).toFixed(1)}%`); + console.log(`NDCG@10: ${(avgNdcg10 * 100).toFixed(1)}%`); + console.log(`MRR: ${(avgMrr * 100).toFixed(1)}%`); + + console.log(`\nBy question type:`); + for (const [type, typeResults] of byType) { + const r5 = + typeResults.reduce((s, r) => s + r.recall_any_at_5, 0) / + typeResults.length; + const r10 = + typeResults.reduce((s, r) => s + r.recall_any_at_10, 0) / + typeResults.length; + console.log( + ` ${type.padEnd(30)} R@5: ${(r5 * 100).toFixed(1)}% R@10: ${(r10 * 100).toFixed(1)}% (n=${typeResults.length})`, + ); + } + + const outPath = new URL( + `./data/longmemeval_results_${mode}.json`, + import.meta.url, + ).pathname; + writeFileSync( + outPath, + JSON.stringify( + { + mode, + questions: results.length, + recall_any_at_5: avgRecallAny5, + recall_any_at_10: avgRecallAny10, + recall_any_at_20: avgRecallAny20, + ndcg_at_10: avgNdcg10, + mrr: avgMrr, + per_type: Object.fromEntries( + Array.from(byType).map(([type, tr]) => [ + type, + { + count: tr.length, + recall_any_at_5: + tr.reduce((s, r) => s + r.recall_any_at_5, 0) / tr.length, + recall_any_at_10: + tr.reduce((s, r) => s + r.recall_any_at_10, 0) / tr.length, + }, + ]), + ), + per_question: results, + }, + null, + 2, + ), + ); + console.log(`\nResults saved to ${outPath}`); +} + +const mode = (process.argv[2] || "bm25") as "bm25" | "vector" | "hybrid"; +console.log(`Running LongMemEval-S benchmark in ${mode} mode...`); + +if (mode === "bm25") { + runBenchmark("bm25").catch(console.error); +} else { + import("../src/providers/embedding/local.js") + .then(({ LocalEmbeddingProvider }) => { + const provider = new LocalEmbeddingProvider(); + return runBenchmark(mode, provider); + }) + .catch(console.error); +} diff --git a/benchmark/quality-eval.ts b/benchmark/quality-eval.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd46fbc292ea10e781317d1fd6408332f7797adf --- /dev/null +++ b/benchmark/quality-eval.ts @@ -0,0 +1,643 @@ +import { SearchIndex } from "../src/state/search-index.js"; +import { VectorIndex } from "../src/state/vector-index.js"; +import { HybridSearch } from "../src/state/hybrid-search.js"; +import { GraphRetrieval } from "../src/functions/graph-retrieval.js"; +import { extractEntitiesFromQuery } from "../src/functions/query-expansion.js"; +import type { CompressedObservation, GraphNode, GraphEdge, GraphEdgeType } from "../src/types.js"; +import { generateDataset, type LabeledQuery } from "./dataset.js"; +import { writeFileSync } from "node:fs"; + +interface QualityMetrics { + query: string; + category: string; + recall_at_5: number; + recall_at_10: number; + recall_at_20: number; + precision_at_5: number; + precision_at_10: number; + ndcg_at_10: number; + mrr: number; + relevant_count: number; + retrieved_count: number; + latency_ms: number; +} + +interface SystemMetrics { + system: string; + avg_recall_at_5: number; + avg_recall_at_10: number; + avg_recall_at_20: number; + avg_precision_at_5: number; + avg_precision_at_10: number; + avg_ndcg_at_10: number; + avg_mrr: number; + avg_latency_ms: number; + total_tokens_per_query: number; + per_query: QualityMetrics[]; +} + +function dcg(relevances: boolean[], k: number): number { + let sum = 0; + for (let i = 0; i < Math.min(k, relevances.length); i++) { + sum += (relevances[i] ? 1 : 0) / Math.log2(i + 2); + } + return sum; +} + +function ndcg(retrieved: string[], relevant: Set, k: number): number { + const actualRelevances = retrieved.slice(0, k).map(id => relevant.has(id)); + const idealRelevances = Array.from({ length: Math.min(k, relevant.size) }, () => true); + const idealDCG = dcg(idealRelevances, k); + if (idealDCG === 0) return 0; + return dcg(actualRelevances, k) / idealDCG; +} + +function recall(retrieved: string[], relevant: Set, k: number): number { + if (relevant.size === 0) return 1; + const topK = new Set(retrieved.slice(0, k)); + let hits = 0; + for (const id of relevant) { + if (topK.has(id)) hits++; + } + return hits / relevant.size; +} + +function precision(retrieved: string[], relevant: Set, k: number): number { + const topK = retrieved.slice(0, k); + if (topK.length === 0) return 0; + let hits = 0; + for (const id of topK) { + if (relevant.has(id)) hits++; + } + return hits / topK.length; +} + +function mrr(retrieved: string[], relevant: Set): number { + for (let i = 0; i < retrieved.length; i++) { + if (relevant.has(retrieved[i])) return 1 / (i + 1); + } + return 0; +} + +function estimateTokens(text: string): number { + return Math.ceil(text.length / 4); +} + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => { + return (store.get(scope)?.get(key) as T) ?? null; + }, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function deterministicEmbedding(text: string, dims = 384): Float32Array { + const arr = new Float32Array(dims); + const words = text.toLowerCase().split(/\W+/).filter(w => w.length > 2); + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const idx = (word.charCodeAt(i) * 31 + i * 17) % dims; + arr[idx] += 1; + const idx2 = (word.charCodeAt(i) * 37 + i * 13 + word.length * 7) % dims; + arr[idx2] += 0.5; + } + } + const norm = Math.sqrt(arr.reduce((s, v) => s + v * v, 0)); + if (norm > 0) for (let i = 0; i < dims; i++) arr[i] /= norm; + return arr; +} + +async function evalBm25Only( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const index = new SearchIndex(); + for (const obs of observations) index.add(obs); + + const perQuery: QualityMetrics[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + const results = index.search(q.query, 20); + const latency = performance.now() - start; + + const retrieved = results.map(r => r.obsId); + perQuery.push({ + query: q.query, + category: q.category, + recall_at_5: recall(retrieved, relevant, 5), + recall_at_10: recall(retrieved, relevant, 10), + recall_at_20: recall(retrieved, relevant, 20), + precision_at_5: precision(retrieved, relevant, 5), + precision_at_10: precision(retrieved, relevant, 10), + ndcg_at_10: ndcg(retrieved, relevant, 10), + mrr: mrr(retrieved, relevant), + relevant_count: relevant.size, + retrieved_count: results.length, + latency_ms: latency, + }); + } + + const avgTokens = perQuery.reduce((sum, q) => sum + q.retrieved_count, 0) / perQuery.length; + const avgObsTokens = observations.slice(0, 50).reduce((s, o) => s + estimateTokens(JSON.stringify(o)), 0) / 50; + + return { + system: "BM25-only", + avg_recall_at_5: avg(perQuery.map(q => q.recall_at_5)), + avg_recall_at_10: avg(perQuery.map(q => q.recall_at_10)), + avg_recall_at_20: avg(perQuery.map(q => q.recall_at_20)), + avg_precision_at_5: avg(perQuery.map(q => q.precision_at_5)), + avg_precision_at_10: avg(perQuery.map(q => q.precision_at_10)), + avg_ndcg_at_10: avg(perQuery.map(q => q.ndcg_at_10)), + avg_mrr: avg(perQuery.map(q => q.mrr)), + avg_latency_ms: avg(perQuery.map(q => q.latency_ms)), + total_tokens_per_query: Math.round(avgObsTokens * avgTokens), + per_query: perQuery, + }; +} + +async function evalDualStream( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const kv = mockKV(); + const bm25 = new SearchIndex(); + const vector = new VectorIndex(); + const dims = 384; + + for (const obs of observations) { + bm25.add(obs); + const text = [obs.title, obs.narrative, ...obs.concepts, ...obs.facts].join(" "); + vector.add(obs.id, obs.sessionId, deterministicEmbedding(text, dims)); + await kv.set(`mem:obs:${obs.sessionId}`, obs.id, obs); + } + + const mockEmbed: any = { + name: "deterministic", + dimensions: dims, + embed: async (text: string) => deterministicEmbedding(text, dims), + embedBatch: async (texts: string[]) => texts.map(t => deterministicEmbedding(t, dims)), + }; + + const hybrid = new HybridSearch(bm25, vector, mockEmbed, kv as never, 0.4, 0.6, 0); + const perQuery: QualityMetrics[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + const results = await hybrid.search(q.query, 20); + const latency = performance.now() - start; + + const retrieved = results.map(r => r.observation.id); + perQuery.push({ + query: q.query, + category: q.category, + recall_at_5: recall(retrieved, relevant, 5), + recall_at_10: recall(retrieved, relevant, 10), + recall_at_20: recall(retrieved, relevant, 20), + precision_at_5: precision(retrieved, relevant, 5), + precision_at_10: precision(retrieved, relevant, 10), + ndcg_at_10: ndcg(retrieved, relevant, 10), + mrr: mrr(retrieved, relevant), + relevant_count: relevant.size, + retrieved_count: results.length, + latency_ms: latency, + }); + } + + const avgResultTokens = perQuery.reduce((sum, q) => { + return sum + q.retrieved_count; + }, 0) / perQuery.length; + const avgObsTokens2 = observations.slice(0, 50).reduce((s, o) => s + estimateTokens(JSON.stringify(o)), 0) / 50; + + return { + system: "Dual-stream (BM25+Vector)", + avg_recall_at_5: avg(perQuery.map(q => q.recall_at_5)), + avg_recall_at_10: avg(perQuery.map(q => q.recall_at_10)), + avg_recall_at_20: avg(perQuery.map(q => q.recall_at_20)), + avg_precision_at_5: avg(perQuery.map(q => q.precision_at_5)), + avg_precision_at_10: avg(perQuery.map(q => q.precision_at_10)), + avg_ndcg_at_10: avg(perQuery.map(q => q.ndcg_at_10)), + avg_mrr: avg(perQuery.map(q => q.mrr)), + avg_latency_ms: avg(perQuery.map(q => q.latency_ms)), + total_tokens_per_query: Math.round(avgObsTokens2 * avgResultTokens), + per_query: perQuery, + }; +} + +async function evalTripleStream( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const kv = mockKV(); + const bm25 = new SearchIndex(); + const vector = new VectorIndex(); + const dims = 384; + + for (const obs of observations) { + bm25.add(obs); + const text = [obs.title, obs.narrative, ...obs.concepts, ...obs.facts].join(" "); + vector.add(obs.id, obs.sessionId, deterministicEmbedding(text, dims)); + await kv.set(`mem:obs:${obs.sessionId}`, obs.id, obs); + } + + const conceptToNodes = new Map(); + const nodeTypes: GraphNode["type"][] = ["concept", "library", "file", "pattern"]; + const edgeTypes: GraphEdgeType[] = ["uses", "related_to", "depends_on", "modifies"]; + const now = new Date().toISOString(); + let nodeId = 0; + + for (const obs of observations) { + for (const concept of obs.concepts) { + if (!conceptToNodes.has(concept)) { + const nid = `gn_${nodeId++}`; + conceptToNodes.set(concept, nid); + await kv.set("mem:graph:nodes", nid, { + id: nid, + type: nodeTypes[nodeId % nodeTypes.length], + name: concept, + properties: {}, + sourceObservationIds: [], + createdAt: now, + } as GraphNode); + } + const nid = conceptToNodes.get(concept)!; + const existing = await kv.get("mem:graph:nodes", nid); + if (existing && !existing.sourceObservationIds.includes(obs.id)) { + existing.sourceObservationIds.push(obs.id); + await kv.set("mem:graph:nodes", nid, existing); + } + } + + const capped = obs.concepts.slice(0, 10); + for (let i = 0; i < capped.length; i++) { + for (let j = i + 1; j < capped.length; j++) { + const srcNid = conceptToNodes.get(capped[i])!; + const tgtNid = conceptToNodes.get(capped[j])!; + if (srcNid && tgtNid && srcNid !== tgtNid) { + const eid = `ge_${srcNid}_${tgtNid}`; + const existing = await kv.get("mem:graph:edges", eid); + const weight = existing ? Math.min(1.0, existing.weight + 0.1) : 0.5; + await kv.set("mem:graph:edges", eid, { + id: eid, + type: edgeTypes[(i + j) % edgeTypes.length], + sourceNodeId: srcNid, + targetNodeId: tgtNid, + weight, + sourceObservationIds: existing + ? [...new Set([...existing.sourceObservationIds, obs.id])] + : [obs.id], + createdAt: now, + tcommit: now, + version: 1, + isLatest: true, + } as GraphEdge); + } + } + } + } + + const mockEmbed: any = { + name: "deterministic", + dimensions: dims, + embed: async (text: string) => deterministicEmbedding(text, dims), + embedBatch: async (texts: string[]) => texts.map(t => deterministicEmbedding(t, dims)), + }; + + const hybrid = new HybridSearch(bm25, vector, mockEmbed, kv as never, 0.4, 0.6, 0.3); + const perQuery: QualityMetrics[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + const results = await hybrid.search(q.query, 20); + const latency = performance.now() - start; + + const retrieved = results.map(r => r.observation.id); + perQuery.push({ + query: q.query, + category: q.category, + recall_at_5: recall(retrieved, relevant, 5), + recall_at_10: recall(retrieved, relevant, 10), + recall_at_20: recall(retrieved, relevant, 20), + precision_at_5: precision(retrieved, relevant, 5), + precision_at_10: precision(retrieved, relevant, 10), + ndcg_at_10: ndcg(retrieved, relevant, 10), + mrr: mrr(retrieved, relevant), + relevant_count: relevant.size, + retrieved_count: results.length, + latency_ms: latency, + }); + } + + const avgResultTokens3 = perQuery.reduce((sum, q) => { + return sum + q.retrieved_count; + }, 0) / perQuery.length; + const avgObsTokens3 = observations.slice(0, 50).reduce((s, o) => s + estimateTokens(JSON.stringify(o)), 0) / 50; + + return { + system: "Triple-stream (BM25+Vector+Graph)", + avg_recall_at_5: avg(perQuery.map(q => q.recall_at_5)), + avg_recall_at_10: avg(perQuery.map(q => q.recall_at_10)), + avg_recall_at_20: avg(perQuery.map(q => q.recall_at_20)), + avg_precision_at_5: avg(perQuery.map(q => q.precision_at_5)), + avg_precision_at_10: avg(perQuery.map(q => q.precision_at_10)), + avg_ndcg_at_10: avg(perQuery.map(q => q.ndcg_at_10)), + avg_mrr: avg(perQuery.map(q => q.mrr)), + avg_latency_ms: avg(perQuery.map(q => q.latency_ms)), + total_tokens_per_query: Math.round(avgObsTokens3 * avgResultTokens3), + per_query: perQuery, + }; +} + +async function evalBuiltinMemory( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const allText = observations.map(o => + `## ${o.title}\n${o.narrative}\nConcepts: ${o.concepts.join(", ")}\nFiles: ${o.files.join(", ")}` + ).join("\n\n"); + + const totalTokens = estimateTokens(allText); + + const perQuery: QualityMetrics[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + + const queryTerms = q.query.toLowerCase().split(/\W+/).filter(w => w.length > 2); + const scored: Array<{ id: string; score: number }> = []; + + for (const obs of observations) { + const text = [obs.title, obs.narrative, ...obs.concepts, ...obs.facts].join(" ").toLowerCase(); + let score = 0; + for (const term of queryTerms) { + if (text.includes(term)) score++; + } + if (score > 0) scored.push({ id: obs.id, score }); + } + + scored.sort((a, b) => b.score - a.score); + const latency = performance.now() - start; + + const retrieved = scored.map(s => s.id).slice(0, 20); + perQuery.push({ + query: q.query, + category: q.category, + recall_at_5: recall(retrieved, relevant, 5), + recall_at_10: recall(retrieved, relevant, 10), + recall_at_20: recall(retrieved, relevant, 20), + precision_at_5: precision(retrieved, relevant, 5), + precision_at_10: precision(retrieved, relevant, 10), + ndcg_at_10: ndcg(retrieved, relevant, 10), + mrr: mrr(retrieved, relevant), + relevant_count: relevant.size, + retrieved_count: Math.min(scored.length, 20), + latency_ms: latency, + }); + } + + return { + system: "Built-in (CLAUDE.md / grep)", + avg_recall_at_5: avg(perQuery.map(q => q.recall_at_5)), + avg_recall_at_10: avg(perQuery.map(q => q.recall_at_10)), + avg_recall_at_20: avg(perQuery.map(q => q.recall_at_20)), + avg_precision_at_5: avg(perQuery.map(q => q.precision_at_5)), + avg_precision_at_10: avg(perQuery.map(q => q.precision_at_10)), + avg_ndcg_at_10: avg(perQuery.map(q => q.ndcg_at_10)), + avg_mrr: avg(perQuery.map(q => q.mrr)), + avg_latency_ms: avg(perQuery.map(q => q.latency_ms)), + total_tokens_per_query: totalTokens, + per_query: perQuery, + }; +} + +async function evalBuiltinMemoryTruncated( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const MAX_LINES = 200; + const lines = observations.map(o => + `- ${o.title}: ${o.narrative.slice(0, 80)}... [${o.concepts.slice(0, 3).join(", ")}]` + ); + const truncated = lines.slice(0, MAX_LINES); + const truncatedIds = new Set(observations.slice(0, MAX_LINES).map(o => o.id)); + const totalTokens = estimateTokens(truncated.join("\n")); + + const perQuery: QualityMetrics[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + + const queryTerms = q.query.toLowerCase().split(/\W+/).filter(w => w.length > 2); + const scored: Array<{ id: string; score: number }> = []; + + for (let i = 0; i < Math.min(MAX_LINES, observations.length); i++) { + const obs = observations[i]; + const line = truncated[i]; + let score = 0; + for (const term of queryTerms) { + if (line.toLowerCase().includes(term)) score++; + } + if (score > 0) scored.push({ id: obs.id, score }); + } + + scored.sort((a, b) => b.score - a.score); + const latency = performance.now() - start; + + const retrieved = scored.map(s => s.id).slice(0, 20); + + const reachableRelevant = new Set( + [...relevant].filter(id => truncatedIds.has(id)) + ); + + perQuery.push({ + query: q.query, + category: q.category, + recall_at_5: recall(retrieved, relevant, 5), + recall_at_10: recall(retrieved, relevant, 10), + recall_at_20: recall(retrieved, relevant, 20), + precision_at_5: precision(retrieved, relevant, 5), + precision_at_10: precision(retrieved, relevant, 10), + ndcg_at_10: ndcg(retrieved, relevant, 10), + mrr: mrr(retrieved, relevant), + relevant_count: relevant.size, + retrieved_count: Math.min(scored.length, 20), + latency_ms: latency, + }); + } + + return { + system: "Built-in (200-line MEMORY.md)", + avg_recall_at_5: avg(perQuery.map(q => q.recall_at_5)), + avg_recall_at_10: avg(perQuery.map(q => q.recall_at_10)), + avg_recall_at_20: avg(perQuery.map(q => q.recall_at_20)), + avg_precision_at_5: avg(perQuery.map(q => q.precision_at_5)), + avg_precision_at_10: avg(perQuery.map(q => q.precision_at_10)), + avg_ndcg_at_10: avg(perQuery.map(q => q.ndcg_at_10)), + avg_mrr: avg(perQuery.map(q => q.mrr)), + avg_latency_ms: avg(perQuery.map(q => q.latency_ms)), + total_tokens_per_query: totalTokens, + per_query: perQuery, + }; +} + +function avg(nums: number[]): number { + return nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : 0; +} + +function pct(n: number): string { + return (n * 100).toFixed(1) + "%"; +} + +function generateReport(systems: SystemMetrics[], obsCount: number, queryCount: number): string { + const lines: string[] = []; + const w = (s: string) => lines.push(s); + + w("# agentmemory v0.6.0 — Search Quality Evaluation"); + w(""); + w(`**Date:** ${new Date().toISOString()}`); + w(`**Dataset:** ${obsCount} observations across 30 sessions (realistic coding project)`); + w(`**Queries:** ${queryCount} labeled queries with ground-truth relevance`); + w(`**Metric definitions:** Recall@K (fraction of relevant docs in top K), Precision@K (fraction of top K that are relevant), NDCG@10 (ranking quality), MRR (position of first relevant result)`); + w(""); + + w("## Head-to-Head Comparison"); + w(""); + w("| System | Recall@5 | Recall@10 | Precision@5 | NDCG@10 | MRR | Latency | Tokens/query |"); + w("|--------|----------|-----------|-------------|---------|-----|---------|--------------|"); + for (const s of systems) { + w(`| ${s.system} | ${pct(s.avg_recall_at_5)} | ${pct(s.avg_recall_at_10)} | ${pct(s.avg_precision_at_5)} | ${pct(s.avg_ndcg_at_10)} | ${pct(s.avg_mrr)} | ${s.avg_latency_ms.toFixed(2)}ms | ${s.total_tokens_per_query.toLocaleString()} |`); + } + + w(""); + w("## Why This Matters"); + w(""); + + const builtin = systems.find(s => s.system.includes("CLAUDE.md / grep")); + const truncated = systems.find(s => s.system.includes("200-line")); + const triple = systems.find(s => s.system.includes("Triple")); + const bm25 = systems.find(s => s.system === "BM25-only"); + + if (builtin && triple) { + const recallLift = ((triple.avg_recall_at_10 - builtin.avg_recall_at_10) / Math.max(0.001, builtin.avg_recall_at_10) * 100); + const tokenSaving = ((1 - triple.total_tokens_per_query / builtin.total_tokens_per_query) * 100); + w(`**Recall improvement:** agentmemory triple-stream finds ${pct(triple.avg_recall_at_10)} of relevant memories at K=10 vs ${pct(builtin.avg_recall_at_10)} for keyword grep (${recallLift > 0 ? "+" : ""}${recallLift.toFixed(0)}%)`); + w(`**Token savings:** agentmemory returns only the top 10 results (${triple.total_tokens_per_query.toLocaleString()} tokens) vs loading everything into context (${builtin.total_tokens_per_query.toLocaleString()} tokens) — ${tokenSaving.toFixed(0)}% reduction`); + } + + if (truncated && triple) { + w(`**200-line cap:** Claude Code's MEMORY.md is capped at 200 lines. With ${obsCount} observations, ${pct(truncated.avg_recall_at_10)} recall at K=10 — memories from later sessions are simply invisible.`); + } + + w(""); + w("## Per-Query Breakdown (Triple-Stream)"); + w(""); + + if (triple) { + w("| Query | Category | Recall@10 | NDCG@10 | MRR | Relevant | Latency |"); + w("|-------|----------|-----------|---------|-----|----------|---------|"); + for (const q of triple.per_query) { + w(`| ${q.query.slice(0, 45)}${q.query.length > 45 ? "..." : ""} | ${q.category} | ${pct(q.recall_at_10)} | ${pct(q.ndcg_at_10)} | ${pct(q.mrr)} | ${q.relevant_count} | ${q.latency_ms.toFixed(1)}ms |`); + } + } + + w(""); + w("## By Query Category"); + w(""); + + const categories = ["exact", "semantic", "cross-session", "entity"]; + if (triple) { + w("| Category | Avg Recall@10 | Avg NDCG@10 | Avg MRR | Queries |"); + w("|----------|---------------|-------------|---------|---------|"); + for (const cat of categories) { + const qs = triple.per_query.filter(q => q.category === cat); + if (qs.length === 0) continue; + w(`| ${cat} | ${pct(avg(qs.map(q => q.recall_at_10)))} | ${pct(avg(qs.map(q => q.ndcg_at_10)))} | ${pct(avg(qs.map(q => q.mrr)))} | ${qs.length} |`); + } + } + + w(""); + w("## Context Window Analysis"); + w(""); + w("The fundamental problem with built-in agent memory:"); + w(""); + w("| Observations | MEMORY.md tokens | agentmemory tokens (top 10) | Savings | MEMORY.md reachable |"); + w("|-------------|-----------------|---------------------------|---------|-------------------|"); + + for (const count of [240, 500, 1000, 5000]) { + const memTokens = Math.round(count * 50); + const amTokens = triple ? triple.total_tokens_per_query : 500; + const saving = ((1 - amTokens / memTokens) * 100); + const reachable = count <= 200 ? "100%" : `${((200 / count) * 100).toFixed(0)}%`; + w(`| ${count.toLocaleString()} | ${memTokens.toLocaleString()} | ${amTokens.toLocaleString()} | ${saving.toFixed(0)}% | ${reachable} |`); + } + + w(""); + w("At 240 observations (our dataset), MEMORY.md already hits its 200-line cap and loses access to the most recent 40 observations. At 1,000 observations, 80% of memories are invisible. agentmemory always searches the full corpus."); + + w(""); + w("---"); + w(""); + w(`*${systems.reduce((s, sys) => s + sys.per_query.length, 0)} evaluations across ${systems.length} systems. Ground-truth labels assigned by concept matching against observation metadata.*`); + + return lines.join("\n"); +} + +async function main() { + console.log("Generating labeled dataset..."); + const { observations, queries, sessions } = generateDataset(); + console.log(`Dataset: ${observations.length} observations, ${sessions.size} sessions, ${queries.length} queries`); + console.log(`Avg relevant docs per query: ${(queries.reduce((s, q) => s + q.relevantObsIds.length, 0) / queries.length).toFixed(1)}`); + console.log(""); + + console.log("Evaluating: Built-in (CLAUDE.md / grep)..."); + const builtinResults = await evalBuiltinMemory(observations, queries); + console.log(` Recall@10: ${pct(builtinResults.avg_recall_at_10)}, NDCG@10: ${pct(builtinResults.avg_ndcg_at_10)}`); + + console.log("Evaluating: Built-in (200-line MEMORY.md)..."); + const truncatedResults = await evalBuiltinMemoryTruncated(observations, queries); + console.log(` Recall@10: ${pct(truncatedResults.avg_recall_at_10)}, NDCG@10: ${pct(truncatedResults.avg_ndcg_at_10)}`); + + console.log("Evaluating: BM25-only..."); + const bm25Results = await evalBm25Only(observations, queries); + console.log(` Recall@10: ${pct(bm25Results.avg_recall_at_10)}, NDCG@10: ${pct(bm25Results.avg_ndcg_at_10)}`); + + console.log("Evaluating: Dual-stream (BM25+Vector)..."); + const dualResults = await evalDualStream(observations, queries); + console.log(` Recall@10: ${pct(dualResults.avg_recall_at_10)}, NDCG@10: ${pct(dualResults.avg_ndcg_at_10)}`); + + console.log("Evaluating: Triple-stream (BM25+Vector+Graph)..."); + const tripleResults = await evalTripleStream(observations, queries); + console.log(` Recall@10: ${pct(tripleResults.avg_recall_at_10)}, NDCG@10: ${pct(tripleResults.avg_ndcg_at_10)}`); + + console.log(""); + + const report = generateReport( + [builtinResults, truncatedResults, bm25Results, dualResults, tripleResults], + observations.length, + queries.length, + ); + + writeFileSync("benchmark/QUALITY.md", report); + console.log(report); + console.log(`\nReport written to benchmark/QUALITY.md`); +} + +main().catch(console.error); diff --git a/benchmark/real-embeddings-eval.ts b/benchmark/real-embeddings-eval.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e4628e5d1fcfa972511558561611bf397e4d21d --- /dev/null +++ b/benchmark/real-embeddings-eval.ts @@ -0,0 +1,405 @@ +import { SearchIndex } from "../src/state/search-index.js"; +import { VectorIndex } from "../src/state/vector-index.js"; +import { HybridSearch } from "../src/state/hybrid-search.js"; +import { LocalEmbeddingProvider } from "../src/providers/embedding/local.js"; +import type { CompressedObservation, EmbeddingProvider } from "../src/types.js"; +import { generateDataset, type LabeledQuery } from "./dataset.js"; +import { writeFileSync } from "node:fs"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function estimateTokens(text: string): number { + return Math.ceil(text.length / 4); +} + +function obsToText(obs: CompressedObservation): string { + return [obs.title, obs.subtitle || "", obs.narrative, ...obs.facts, ...obs.concepts].join(" "); +} + +function recall(retrieved: string[], relevant: Set, k: number): number { + if (relevant.size === 0) return 1; + const topK = new Set(retrieved.slice(0, k)); + let hits = 0; + for (const id of relevant) if (topK.has(id)) hits++; + return hits / relevant.size; +} + +function precision(retrieved: string[], relevant: Set, k: number): number { + const topK = retrieved.slice(0, k); + if (topK.length === 0) return 0; + let hits = 0; + for (const id of topK) if (relevant.has(id)) hits++; + return hits / topK.length; +} + +function dcg(relevances: boolean[], k: number): number { + let sum = 0; + for (let i = 0; i < Math.min(k, relevances.length); i++) + sum += (relevances[i] ? 1 : 0) / Math.log2(i + 2); + return sum; +} + +function ndcg(retrieved: string[], relevant: Set, k: number): number { + const actual = retrieved.slice(0, k).map(id => relevant.has(id)); + const ideal = Array.from({ length: Math.min(k, relevant.size) }, () => true); + const idealDCG = dcg(ideal, k); + return idealDCG === 0 ? 0 : dcg(actual, k) / idealDCG; +} + +function mrr(retrieved: string[], relevant: Set): number { + for (let i = 0; i < retrieved.length; i++) + if (relevant.has(retrieved[i])) return 1 / (i + 1); + return 0; +} + +function avg(nums: number[]): number { + return nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : 0; +} + +function pct(n: number): string { + return (n * 100).toFixed(1) + "%"; +} + +interface QueryResult { + query: string; + category: string; + recall_5: number; + recall_10: number; + precision_5: number; + ndcg_10: number; + mrr_val: number; + relevant_count: number; + latency_ms: number; +} + +interface SystemResult { + name: string; + results: QueryResult[]; + embed_time_ms: number; + tokens_per_query: number; +} + +async function evalSystem( + name: string, + observations: CompressedObservation[], + queries: LabeledQuery[], + provider: EmbeddingProvider | null, + weights: { bm25: number; vector: number; graph: number }, +): Promise { + const kv = mockKV(); + const bm25 = new SearchIndex(); + const vector = provider ? new VectorIndex() : null; + + console.log(` Indexing ${observations.length} observations...`); + const embedStart = performance.now(); + + for (const obs of observations) { + bm25.add(obs); + await kv.set(`mem:obs:${obs.sessionId}`, obs.id, obs); + } + + if (provider && vector) { + const batchSize = 32; + for (let i = 0; i < observations.length; i += batchSize) { + const batch = observations.slice(i, i + batchSize); + const texts = batch.map(o => obsToText(o)); + const embeddings = await provider.embedBatch(texts); + for (let j = 0; j < batch.length; j++) { + vector.add(batch[j].id, batch[j].sessionId, embeddings[j]); + } + if ((i + batchSize) % 100 === 0 || i + batchSize >= observations.length) { + process.stdout.write(`\r Embedded ${Math.min(i + batchSize, observations.length)}/${observations.length}`); + } + } + console.log(""); + } + + const embedTime = performance.now() - embedStart; + + const hybrid = new HybridSearch( + bm25, + vector, + provider, + kv as never, + weights.bm25, + weights.vector, + weights.graph, + ); + + console.log(` Running ${queries.length} queries...`); + const results: QueryResult[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const start = performance.now(); + const searchResults = await hybrid.search(q.query, 20); + const latency = performance.now() - start; + + const retrieved = searchResults.map(r => r.observation.id); + results.push({ + query: q.query, + category: q.category, + recall_5: recall(retrieved, relevant, 5), + recall_10: recall(retrieved, relevant, 10), + precision_5: precision(retrieved, relevant, 5), + ndcg_10: ndcg(retrieved, relevant, 10), + mrr_val: mrr(retrieved, relevant), + relevant_count: relevant.size, + latency_ms: latency, + }); + } + + let totalReturnedTokens = 0; + for (const q of queries) { + const searchResults = await hybrid.search(q.query, 10); + totalReturnedTokens += searchResults.reduce( + (sum, r) => sum + estimateTokens(JSON.stringify(r.observation)), + 0, + ); + } + const avgReturnedTokens = Math.round(totalReturnedTokens / queries.length); + + return { + name, + results, + embed_time_ms: embedTime, + tokens_per_query: avgReturnedTokens, + }; +} + +async function evalBuiltinGrep( + observations: CompressedObservation[], + queries: LabeledQuery[], +): Promise { + const results: QueryResult[] = []; + + for (const q of queries) { + const relevant = new Set(q.relevantObsIds); + const queryTerms = q.query.toLowerCase().split(/\W+/).filter(w => w.length > 2); + const start = performance.now(); + + const scored: Array<{ id: string; score: number }> = []; + for (const obs of observations) { + const text = [obs.title, obs.narrative, ...obs.concepts, ...obs.facts].join(" ").toLowerCase(); + let score = 0; + for (const term of queryTerms) if (text.includes(term)) score++; + if (score > 0) scored.push({ id: obs.id, score }); + } + scored.sort((a, b) => b.score - a.score); + const latency = performance.now() - start; + + const retrieved = scored.map(s => s.id).slice(0, 20); + results.push({ + query: q.query, + category: q.category, + recall_5: recall(retrieved, relevant, 5), + recall_10: recall(retrieved, relevant, 10), + precision_5: precision(retrieved, relevant, 5), + ndcg_10: ndcg(retrieved, relevant, 10), + mrr_val: mrr(retrieved, relevant), + relevant_count: relevant.size, + latency_ms: latency, + }); + } + + const allTokens = estimateTokens(observations.map(o => + `## ${o.title}\n${o.narrative}\nConcepts: ${o.concepts.join(", ")}` + ).join("\n\n")); + + return { name: "Built-in (grep all)", results, embed_time_ms: 0, tokens_per_query: allTokens }; +} + +function generateReport(systems: SystemResult[], obsCount: number): string { + const lines: string[] = []; + const w = (s: string) => lines.push(s); + + w("# agentmemory v0.6.0 — Real Embeddings Quality Evaluation"); + w(""); + w(`**Date:** ${new Date().toISOString()}`); + w(`**Platform:** ${process.platform} ${process.arch}, Node ${process.version}`); + w(`**Dataset:** ${obsCount} observations, 30 sessions, 20 labeled queries`); + w(`**Embedding model:** Xenova/all-MiniLM-L6-v2 (384d, local, no API key)`); + w(""); + + w("## Head-to-Head: Real Embeddings vs Keyword Search"); + w(""); + w("| System | Recall@5 | Recall@10 | Precision@5 | NDCG@10 | MRR | Avg Latency | Tokens/query |"); + w("|--------|----------|-----------|-------------|---------|-----|-------------|--------------|"); + + for (const s of systems) { + const r = s.results; + w(`| ${s.name} | ${pct(avg(r.map(q => q.recall_5)))} | ${pct(avg(r.map(q => q.recall_10)))} | ${pct(avg(r.map(q => q.precision_5)))} | ${pct(avg(r.map(q => q.ndcg_10)))} | ${pct(avg(r.map(q => q.mrr_val)))} | ${avg(r.map(q => q.latency_ms)).toFixed(2)}ms | ${s.tokens_per_query.toLocaleString()} |`); + } + + w(""); + w("## Improvement from Real Embeddings"); + w(""); + + const bm25Only = systems.find(s => s.name === "BM25-only (stemmed+synonyms)"); + const dual = systems.find(s => s.name.includes("Dual-stream")); + const triple = systems.find(s => s.name.includes("Triple-stream")); + const builtin = systems.find(s => s.name.includes("grep")); + + if (bm25Only && dual) { + const recallDelta = avg(dual.results.map(q => q.recall_10)) - avg(bm25Only.results.map(q => q.recall_10)); + w(`Adding real vector embeddings to BM25 improves recall@10 by **${(recallDelta * 100).toFixed(1)} percentage points**.`); + } + if (builtin && dual) { + const tokenSaving = (1 - dual.tokens_per_query / builtin.tokens_per_query) * 100; + w(`Token savings vs loading everything: **${tokenSaving.toFixed(0)}%** (${dual.tokens_per_query.toLocaleString()} vs ${builtin.tokens_per_query.toLocaleString()} tokens).`); + } + + w(""); + w("## Per-Query: Where Real Embeddings Win"); + w(""); + + if (bm25Only && dual) { + w("Queries where dual-stream (real embeddings) outperforms BM25-only:"); + w(""); + w("| Query | Category | BM25 Recall@10 | +Vector Recall@10 | Delta |"); + w("|-------|----------|---------------|-------------------|-------|"); + + for (let i = 0; i < bm25Only.results.length; i++) { + const bq = bm25Only.results[i]; + const dq = dual.results[i]; + const delta = dq.recall_10 - bq.recall_10; + const marker = delta > 0 ? " **" : delta < 0 ? " *" : ""; + if (Math.abs(delta) > 0.001) { + w(`| ${bq.query.slice(0, 45)}${bq.query.length > 45 ? "..." : ""} | ${bq.category} | ${pct(bq.recall_10)} | ${pct(dq.recall_10)} | ${delta > 0 ? "+" : ""}${(delta * 100).toFixed(1)}pp${marker} |`); + } + } + } + + w(""); + w("## By Category Comparison"); + w(""); + const categories = ["exact", "semantic", "cross-session", "entity"]; + + w("| Category | Built-in grep | BM25 (stemmed) | +Real Vectors | +Graph |"); + w("|----------|--------------|----------------|--------------|--------|"); + + for (const cat of categories) { + const vals = systems.map(s => { + const qs = s.results.filter(q => q.category === cat); + return qs.length ? pct(avg(qs.map(q => q.recall_10))) : "-"; + }); + w(`| ${cat} | ${vals.join(" | ")} |`); + } + + w(""); + w("## Embedding Performance"); + w(""); + w("| System | Embedding Time | Model | Dimensions |"); + w("|--------|---------------|-------|------------|"); + for (const s of systems) { + if (s.embed_time_ms > 100) { + w(`| ${s.name} | ${(s.embed_time_ms / 1000).toFixed(1)}s | Xenova/all-MiniLM-L6-v2 | 384 |`); + } + } + w(""); + w("Embedding is a one-time cost at ingestion. Search is sub-millisecond after indexing."); + + w(""); + w("## Key Findings"); + w(""); + + if (bm25Only && dual) { + const semBm25 = bm25Only.results.filter(q => q.category === "semantic"); + const semDual = dual.results.filter(q => q.category === "semantic"); + const semImprove = avg(semDual.map(q => q.recall_10)) - avg(semBm25.map(q => q.recall_10)); + + w(`1. **Semantic queries improve most**: ${(semImprove * 100).toFixed(1)}pp recall@10 gain from real embeddings`); + w(`2. **"database performance optimization"** — the hardest query — goes from BM25 ${pct(bm25Only.results.find(q => q.query.includes("database perf"))?.recall_10 ?? 0)} to vector-augmented ${pct(dual.results.find(q => q.query.includes("database perf"))?.recall_10 ?? 0)}`); + w(`3. **Entity/exact queries** are already well-served by BM25+stemming — vectors add marginal value`); + w(`4. **Local embeddings (Xenova)** run without API keys — zero cost, zero latency concerns`); + } + + w(""); + w("## Recommendation"); + w(""); + w("Enable local embeddings by default (`EMBEDDING_PROVIDER=local` or install `@xenova/transformers`)."); + w("This gives agentmemory genuine semantic search that built-in agent memories cannot match —"); + w("understanding that \"database performance optimization\" relates to \"N+1 query fix\" and \"eager loading\"."); + w(""); + + w("---"); + w(`*All measurements use Xenova/all-MiniLM-L6-v2 local embeddings (384 dimensions, no API calls).*`); + + return lines.join("\n"); +} + +async function main() { + console.log("=== agentmemory Real Embeddings Benchmark ===\n"); + + console.log("Loading Xenova/all-MiniLM-L6-v2 model (first run downloads ~80MB)..."); + let provider: EmbeddingProvider; + try { + provider = new LocalEmbeddingProvider(); + const testEmbed = await provider.embed("test"); + console.log(`Model loaded. Dimensions: ${testEmbed.length}\n`); + } catch (err) { + console.error("Failed to load Xenova model:", err); + console.error("Install with: npm install @xenova/transformers"); + process.exit(1); + } + + const { observations, queries } = generateDataset(); + console.log(`Dataset: ${observations.length} observations, ${queries.length} queries\n`); + + console.log("1. Built-in (grep all)..."); + const builtinResult = await evalBuiltinGrep(observations, queries); + console.log(` Recall@10: ${pct(avg(builtinResult.results.map(q => q.recall_10)))}\n`); + + console.log("2. BM25-only (stemmed+synonyms)..."); + const bm25Result = await evalSystem( + "BM25-only (stemmed+synonyms)", + observations, queries, null, + { bm25: 1.0, vector: 0, graph: 0 }, + ); + console.log(` Recall@10: ${pct(avg(bm25Result.results.map(q => q.recall_10)))}\n`); + + console.log("3. Dual-stream (BM25 + real Xenova vectors)..."); + const dualResult = await evalSystem( + "Dual-stream (BM25+Xenova)", + observations, queries, provider, + { bm25: 0.4, vector: 0.6, graph: 0 }, + ); + console.log(` Recall@10: ${pct(avg(dualResult.results.map(q => q.recall_10)))}\n`); + + console.log("4. Triple-stream (BM25 + Xenova + Graph)..."); + const tripleResult = await evalSystem( + "Triple-stream (BM25+Xenova+Graph)", + observations, queries, provider, + { bm25: 0.4, vector: 0.6, graph: 0.3 }, + ); + console.log(` Recall@10: ${pct(avg(tripleResult.results.map(q => q.recall_10)))}\n`); + + const report = generateReport( + [builtinResult, bm25Result, dualResult, tripleResult], + observations.length, + ); + + writeFileSync("benchmark/REAL-EMBEDDINGS.md", report); + console.log(report); + console.log(`\nReport written to benchmark/REAL-EMBEDDINGS.md`); +} + +main().catch(console.error); diff --git a/benchmark/results/load-100k-96c0ed0.json b/benchmark/results/load-100k-96c0ed0.json new file mode 100644 index 0000000000000000000000000000000000000000..726a0023cafed1d47508734274e5613d156c3464 --- /dev/null +++ b/benchmark/results/load-100k-96c0ed0.json @@ -0,0 +1,61 @@ +{ + "schema_version": 1, + "generated_at": "2026-05-13T19:49:26.116Z", + "git_sha": "96c0ed0", + "base_url": "http://localhost:3111", + "seed": 12648430, + "matrix": { + "N": [ + 1000 + ], + "C": [ + 10 + ] + }, + "ops_per_cell": 200, + "cells": [ + { + "endpoint": "POST /agentmemory/remember", + "N": 1000, + "C": 10, + "ops": 200, + "errors": 0, + "wall_ms": 11504.64, + "throughput_per_sec": 17.38, + "p50_ms": 577.435, + "p90_ms": 607.335, + "p99_ms": 675.269, + "min_ms": 64.46, + "max_ms": 683.164 + }, + { + "endpoint": "POST /agentmemory/smart-search", + "N": 1000, + "C": 10, + "ops": 200, + "errors": 0, + "wall_ms": 3264.572, + "throughput_per_sec": 61.26, + "p50_ms": 160.064, + "p90_ms": 185.608, + "p99_ms": 224.354, + "min_ms": 98.498, + "max_ms": 251.317 + }, + { + "endpoint": "GET /agentmemory/memories?latest=true", + "N": 1000, + "C": 10, + "ops": 200, + "errors": 0, + "wall_ms": 8051.764, + "throughput_per_sec": 24.84, + "p50_ms": 395.462, + "p90_ms": 475.714, + "p99_ms": 542.648, + "min_ms": 158.79, + "max_ms": 635.331 + } + ], + "notes": "Single-process load harness. Latency in milliseconds. Throughput is wall-clock ops/sec for the cell (concurrent in-flight = C)." +} diff --git a/benchmark/scale-eval.ts b/benchmark/scale-eval.ts new file mode 100644 index 0000000000000000000000000000000000000000..43a5a47a0a171ca24291b81c1cb4a9ddef1649ae --- /dev/null +++ b/benchmark/scale-eval.ts @@ -0,0 +1,398 @@ +import { SearchIndex } from "../src/state/search-index.js"; +import { VectorIndex } from "../src/state/vector-index.js"; +import { HybridSearch } from "../src/state/hybrid-search.js"; +import type { CompressedObservation } from "../src/types.js"; +import { generateScaleDataset, generateDataset } from "./dataset.js"; +import { writeFileSync } from "node:fs"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function deterministicEmbedding(text: string, dims = 384): Float32Array { + const arr = new Float32Array(dims); + const words = text.toLowerCase().split(/\W+/).filter(w => w.length > 2); + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const idx = (word.charCodeAt(i) * 31 + i * 17) % dims; + arr[idx] += 1; + const idx2 = (word.charCodeAt(i) * 37 + i * 13 + word.length * 7) % dims; + arr[idx2] += 0.5; + } + } + const norm = Math.sqrt(arr.reduce((s, v) => s + v * v, 0)); + if (norm > 0) for (let i = 0; i < dims; i++) arr[i] /= norm; + return arr; +} + +function estimateTokens(text: string): number { + return Math.ceil(text.length / 4); +} + +interface ScaleResult { + scale: number; + sessions: number; + index_build_ms: number; + index_build_per_doc_ms: number; + bm25_search_ms: number; + hybrid_search_ms: number; + index_size_kb: number; + vector_size_kb: number; + heap_mb: number; + builtin_tokens: number; + builtin_200line_tokens: number; + agentmemory_tokens: number; + token_savings_pct: number; + builtin_unreachable_pct: number; +} + +interface CrossSessionResult { + query: string; + target_session: string; + current_session: string; + sessions_apart: number; + bm25_found: boolean; + bm25_rank: number; + hybrid_found: boolean; + hybrid_rank: number; + builtin_found: boolean; + latency_ms: number; +} + +const SEARCH_QUERIES = [ + "authentication middleware JWT", + "PostgreSQL connection pooling", + "Kubernetes pod crash", + "rate limiting API", + "Playwright E2E tests", + "Docker multi-stage build", + "Redis caching layer", + "CI/CD GitHub Actions", + "Prisma migration drift", + "monitoring Datadog alerts", +]; + +async function benchmarkScale(counts: number[]): Promise { + const results: ScaleResult[] = []; + + for (const count of counts) { + console.log(` Scale: ${count.toLocaleString()} observations...`); + const observations = generateScaleDataset(count); + const sessionCount = new Set(observations.map(o => o.sessionId)).size; + + const heapBefore = process.memoryUsage().heapUsed; + + const buildStart = performance.now(); + const bm25 = new SearchIndex(); + const vector = new VectorIndex(); + const kv = mockKV(); + const dims = 384; + + for (const obs of observations) { + bm25.add(obs); + const text = [obs.title, obs.narrative, ...obs.concepts].join(" "); + vector.add(obs.id, obs.sessionId, deterministicEmbedding(text, dims)); + await kv.set(`mem:obs:${obs.sessionId}`, obs.id, obs); + } + const buildMs = performance.now() - buildStart; + + const heapAfter = process.memoryUsage().heapUsed; + + const mockEmbed: any = { + name: "deterministic", dimensions: dims, + embed: async (t: string) => deterministicEmbedding(t, dims), + embedBatch: async (ts: string[]) => ts.map(t => deterministicEmbedding(t, dims)), + }; + const hybrid = new HybridSearch(bm25, vector, mockEmbed, kv as never, 0.4, 0.6, 0); + + let bm25Total = 0; + let hybridTotal = 0; + const iters = 20; + + for (let i = 0; i < iters; i++) { + const q = SEARCH_QUERIES[i % SEARCH_QUERIES.length]; + const s1 = performance.now(); + bm25.search(q, 10); + bm25Total += performance.now() - s1; + + const s2 = performance.now(); + await hybrid.search(q, 10); + hybridTotal += performance.now() - s2; + } + + const bm25Ser = bm25.serialize(); + const vecSer = vector.serialize(); + + const allText = observations.map(o => + `- ${o.title}: ${o.narrative.slice(0, 80)}... [${o.concepts.slice(0, 3).join(", ")}]` + ).join("\n"); + const builtinTokens = estimateTokens(allText); + + const truncatedText = observations.slice(0, 200).map(o => + `- ${o.title}: ${o.narrative.slice(0, 60)}... [${o.concepts.slice(0, 3).join(", ")}]` + ).join("\n"); + const builtin200Tokens = estimateTokens(truncatedText); + + let totalResultTokens = 0; + for (let i = 0; i < iters; i++) { + const q = SEARCH_QUERIES[i % SEARCH_QUERIES.length]; + const results = await hybrid.search(q, 10); + totalResultTokens += estimateTokens(JSON.stringify(results.map(r => r.observation))); + } + const agentmemoryTokens = Math.round(totalResultTokens / iters); + + results.push({ + scale: count, + sessions: sessionCount, + index_build_ms: Math.round(buildMs), + index_build_per_doc_ms: +(buildMs / count).toFixed(3), + bm25_search_ms: +(bm25Total / iters).toFixed(3), + hybrid_search_ms: +(hybridTotal / iters).toFixed(3), + index_size_kb: Math.round(Buffer.byteLength(bm25Ser, "utf-8") / 1024), + vector_size_kb: Math.round(Buffer.byteLength(vecSer, "utf-8") / 1024), + heap_mb: Math.round((heapAfter - heapBefore) / 1024 / 1024), + builtin_tokens: builtinTokens, + builtin_200line_tokens: builtin200Tokens, + agentmemory_tokens: agentmemoryTokens, + token_savings_pct: Math.round((1 - agentmemoryTokens / builtinTokens) * 100), + builtin_unreachable_pct: count <= 200 ? 0 : Math.round((1 - 200 / count) * 100), + }); + } + + return results; +} + +async function benchmarkCrossSession(): Promise { + const { observations } = generateDataset(); + const results: CrossSessionResult[] = []; + + const bm25 = new SearchIndex(); + const kv = mockKV(); + const vector = new VectorIndex(); + const dims = 384; + + for (const obs of observations) { + bm25.add(obs); + const text = [obs.title, obs.narrative, ...obs.concepts].join(" "); + vector.add(obs.id, obs.sessionId, deterministicEmbedding(text, dims)); + await kv.set(`mem:obs:${obs.sessionId}`, obs.id, obs); + } + + const mockEmbed: any = { + name: "deterministic", dimensions: dims, + embed: async (t: string) => deterministicEmbedding(t, dims), + embedBatch: async (ts: string[]) => ts.map(t => deterministicEmbedding(t, dims)), + }; + const hybrid = new HybridSearch(bm25, vector, mockEmbed, kv as never, 0.4, 0.6, 0); + + const crossQueries: Array<{ + query: string; + targetConcepts: string[]; + targetSessionRange: [number, number]; + currentSession: number; + }> = [ + { query: "How did we set up OAuth providers?", targetConcepts: ["oauth", "nextauth"], targetSessionRange: [5, 9], currentSession: 29 }, + { query: "What was the N+1 query fix?", targetConcepts: ["n+1", "eager-loading"], targetSessionRange: [10, 14], currentSession: 28 }, + { query: "PostgreSQL full-text search setup", targetConcepts: ["full-text-search", "tsvector"], targetSessionRange: [10, 14], currentSession: 27 }, + { query: "bcrypt password hashing configuration", targetConcepts: ["bcrypt", "password-hashing"], targetSessionRange: [5, 9], currentSession: 25 }, + { query: "Vitest unit testing setup", targetConcepts: ["vitest", "unit-testing"], targetSessionRange: [20, 24], currentSession: 29 }, + { query: "webhook retry exponential backoff", targetConcepts: ["webhooks", "exponential-backoff"], targetSessionRange: [15, 19], currentSession: 29 }, + { query: "ESLint flat config migration", targetConcepts: ["eslint", "linting"], targetSessionRange: [0, 4], currentSession: 29 }, + { query: "Kubernetes HPA autoscaling configuration", targetConcepts: ["hpa", "autoscaling", "kubernetes"], targetSessionRange: [25, 29], currentSession: 29 }, + { query: "Prisma database seed script", targetConcepts: ["seeding", "faker", "prisma"], targetSessionRange: [10, 14], currentSession: 26 }, + { query: "API cursor-based pagination", targetConcepts: ["cursor-based", "pagination"], targetSessionRange: [15, 19], currentSession: 29 }, + { query: "CSRF protection double-submit cookie", targetConcepts: ["csrf", "cookies"], targetSessionRange: [5, 9], currentSession: 29 }, + { query: "blue-green deployment rollback", targetConcepts: ["blue-green", "rollback", "zero-downtime"], targetSessionRange: [25, 29], currentSession: 29 }, + ]; + + for (const cq of crossQueries) { + const targetObs = observations.filter(o => + o.concepts.some(c => cq.targetConcepts.includes(c)) + ); + const targetIds = new Set(targetObs.map(o => o.id)); + + const start = performance.now(); + const bm25Results = bm25.search(cq.query, 20); + const hybridResults = await hybrid.search(cq.query, 20); + const latency = performance.now() - start; + + const bm25Rank = bm25Results.findIndex(r => targetIds.has(r.obsId)); + const hybridRank = hybridResults.findIndex(r => targetIds.has(r.observation.id)); + + const builtinLines = 200; + const visibleObs = observations.slice(0, builtinLines); + const builtinFound = visibleObs.some(o => targetIds.has(o.id)); + + const sessionsApart = cq.currentSession - cq.targetSessionRange[0]; + + results.push({ + query: cq.query, + target_session: `ses_${cq.targetSessionRange[0].toString().padStart(3, "0")}-${cq.targetSessionRange[1].toString().padStart(3, "0")}`, + current_session: `ses_${cq.currentSession.toString().padStart(3, "0")}`, + sessions_apart: sessionsApart, + bm25_found: bm25Rank >= 0, + bm25_rank: bm25Rank >= 0 ? bm25Rank + 1 : -1, + hybrid_found: hybridRank >= 0, + hybrid_rank: hybridRank >= 0 ? hybridRank + 1 : -1, + builtin_found: builtinFound, + latency_ms: latency, + }); + } + + return results; +} + +function generateReport(scale: ScaleResult[], cross: CrossSessionResult[]): string { + const lines: string[] = []; + const w = (s: string) => lines.push(s); + + w("# agentmemory v0.6.0 — Scale & Cross-Session Evaluation"); + w(""); + w(`**Date:** ${new Date().toISOString()}`); + w(`**Platform:** ${process.platform} ${process.arch}, Node ${process.version}`); + w(""); + + w("## 1. Scale: agentmemory vs Built-in Memory"); + w(""); + w("Every built-in agent memory (CLAUDE.md, .cursorrules, Cline's memory-bank) loads ALL memory into context every session. agentmemory searches and returns only relevant results."); + w(""); + w("| Observations | Sessions | Index Build | BM25 Search | Hybrid Search | Heap | Context Tokens (built-in) | Context Tokens (agentmemory) | Savings | Built-in Unreachable |"); + w("|-------------|----------|------------|-------------|---------------|------|--------------------------|-----------------------------|---------|--------------------|"); + + for (const r of scale) { + w(`| ${r.scale.toLocaleString()} | ${r.sessions} | ${r.index_build_ms}ms | ${r.bm25_search_ms}ms | ${r.hybrid_search_ms}ms | ${r.heap_mb}MB | ${r.builtin_tokens.toLocaleString()} | ${r.agentmemory_tokens.toLocaleString()} | ${r.token_savings_pct}% | ${r.builtin_unreachable_pct}% |`); + } + + w(""); + w("### What the numbers mean"); + w(""); + w("**Context Tokens (built-in):** How many tokens Claude Code/Cursor/Cline would consume loading ALL memory into the context window. At 5,000 observations, this is ~250K tokens — exceeding most context windows entirely."); + w(""); + w("**Context Tokens (agentmemory):** How many tokens the top-10 search results consume. Stays constant regardless of corpus size."); + w(""); + w("**Built-in Unreachable:** Percentage of memories that built-in systems CANNOT access because they exceed the 200-line MEMORY.md cap or context window limits. At 1,000 observations, 80% of your project history is invisible."); + w(""); + + w("### Storage Costs"); + w(""); + w("| Observations | BM25 Index | Vector Index (d=384) | Total Storage |"); + w("|-------------|-----------|---------------------|---------------|"); + for (const r of scale) { + const total = r.index_size_kb + r.vector_size_kb; + w(`| ${r.scale.toLocaleString()} | ${r.index_size_kb.toLocaleString()} KB | ${r.vector_size_kb.toLocaleString()} KB | ${(total / 1024).toFixed(1)} MB |`); + } + + w(""); + w("## 2. Cross-Session Retrieval"); + w(""); + w("Can the system find relevant information from past sessions? This is impossible for built-in memory once observations exceed the line/context cap."); + w(""); + w("| Query | Target Session | Gap | BM25 Found | BM25 Rank | Hybrid Found | Hybrid Rank | Built-in Visible |"); + w("|-------|---------------|-----|-----------|-----------|-------------|-------------|-----------------|"); + + for (const r of cross) { + w(`| ${r.query.slice(0, 40)}${r.query.length > 40 ? "..." : ""} | ${r.target_session} | ${r.sessions_apart} | ${r.bm25_found ? "Yes" : "No"} | ${r.bm25_rank > 0 ? `#${r.bm25_rank}` : "-"} | ${r.hybrid_found ? "Yes" : "No"} | ${r.hybrid_rank > 0 ? `#${r.hybrid_rank}` : "-"} | ${r.builtin_found ? "Yes" : "No"} |`); + } + + const bm25Found = cross.filter(r => r.bm25_found).length; + const hybridFound = cross.filter(r => r.hybrid_found).length; + const builtinFound = cross.filter(r => r.builtin_found).length; + + w(""); + w(`**Summary:** agentmemory BM25 found ${bm25Found}/${cross.length} cross-session queries. Hybrid found ${hybridFound}/${cross.length}. Built-in memory (200-line cap) could only reach ${builtinFound}/${cross.length}.`); + + w(""); + w("## 3. The Context Window Problem"); + w(""); + w("```"); + w("Agent context window: ~200K tokens"); + w("System prompt + tools: ~20K tokens"); + w("User conversation: ~30K tokens"); + w("Available for memory: ~150K tokens"); + w(""); + w("At 50 tokens/observation:"); + w(" 200 observations = 10,000 tokens (fits, but 200-line cap hits first)"); + w(" 1,000 observations = 50,000 tokens (33% of available budget)"); + w(" 5,000 observations = 250,000 tokens (EXCEEDS total context window)"); + w(""); + w("agentmemory top-10 results:"); + w(` Any corpus size = ~${scale[0]?.agentmemory_tokens.toLocaleString() || "500"} tokens (0.3% of budget)`); + w("```"); + w(""); + + w("## 4. What Built-in Memory Cannot Do"); + w(""); + w("| Capability | Built-in (CLAUDE.md) | agentmemory |"); + w("|-----------|---------------------|-------------|"); + w("| Semantic search | No (keyword grep only) | BM25 + vector + graph |"); + w("| Scale beyond 200 lines | No (hard cap) | Unlimited |"); + w("| Cross-session recall | Only if in 200-line window | Full corpus search |"); + w("| Cross-agent sharing | No (per-agent files) | MCP + REST API |"); + w("| Multi-agent coordination | No | Leases, signals, actions |"); + w("| Temporal queries | No | Point-in-time graph |"); + w("| Memory lifecycle | No (manual pruning) | Ebbinghaus decay + eviction |"); + w("| Knowledge graph | No | Entity extraction + traversal |"); + w("| Query expansion | No | LLM-generated reformulations |"); + w("| Retention scoring | No | Time-frequency decay model |"); + w("| Real-time dashboard | No (read files manually) | Viewer on :3113 |"); + w("| Concurrent access | No (file lock) | Keyed mutex + KV store |"); + w(""); + + w("## 5. When to Use What"); + w(""); + w("**Use built-in memory (CLAUDE.md) when:**"); + w("- You have < 200 items to remember"); + w("- Single agent, single project"); + w("- Preferences and quick facts only"); + w("- Zero setup is the priority"); + w(""); + w("**Use agentmemory when:**"); + w("- Project history exceeds 200 observations"); + w("- You need to recall specific incidents from weeks ago"); + w("- Multiple agents work on the same codebase"); + w("- You want semantic search (\"how does auth work?\") not just keyword matching"); + w("- You need to track memory quality, decay, and lifecycle"); + w("- You want a shared memory layer across Claude Code, Cursor, Windsurf, etc."); + w(""); + w("Built-in memory is your sticky notes. agentmemory is the searchable database behind them."); + w(""); + + w("---"); + w(`*Scale tests: ${scale.length} corpus sizes. Cross-session tests: ${cross.length} queries targeting specific past sessions.*`); + + return lines.join("\n"); +} + +async function main() { + console.log("=== agentmemory Scale & Cross-Session Evaluation ===\n"); + + console.log("1. Scale benchmarks..."); + const scaleResults = await benchmarkScale([240, 1_000, 5_000, 10_000, 50_000]); + + console.log("\n2. Cross-session retrieval..."); + const crossResults = await benchmarkCrossSession(); + + console.log(""); + const report = generateReport(scaleResults, crossResults); + writeFileSync("benchmark/SCALE.md", report); + console.log(report); + console.log(`\nReport written to benchmark/SCALE.md`); +} + +main().catch(console.error); diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..91aa199e283090168671cc48c4b68976a3bf320c --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,100 @@ +# One-click deploy templates + +Stand up agentmemory on managed infrastructure without rolling your own +Docker host. Each template ships a self-contained Dockerfile that pulls +`@agentmemory/agentmemory` from npm at build time and copies the iii +engine binary in from the official `iiidev/iii` image — no pre-built +agentmemory image required. Storage mounts at `/data`; an HMAC secret +is generated by the first-boot entrypoint and persisted to the volume. +The entrypoint overwrites the npm-bundled iii config with a +deploy-tuned one that binds `0.0.0.0` and uses absolute `/data` paths, +then drops privileges from `root` to `node` via `gosu` before +exec'ing the agentmemory CLI. + +| Platform | Pitch | Cost floor | +|----------|-------|------------| +| [fly.io](./fly/README.md) | Single machine with auto-stop. Cheapest idle cost on a managed host; cold-start on first request after sleep. | ~$0.15/month at full idle | +| [Railway](./railway/README.md) | Push from GitHub, volume in the dashboard. Easiest managed dashboard flow. | $5/month (Hobby plan flat fee) | +| [Render](./render/README.md) | Blueprint-driven; persistent disk attaches automatically. Most "set it and forget it." | $7.25/month (Starter web + 1 GB disk) | +| [Coolify](./coolify/README.md) | Self-hosted on your own VPS. Same Docker Compose stack, you own the host and the data. | VPS cost only (Hetzner CX22 ~€3.79/month) | + +## What every template guarantees + +- **Volume mounted at `/data`.** Matches the path the engine has used + since v0.9.10. +- **HMAC secret generated on first boot** via `openssl rand -hex 32`, + written to `/data/.hmac` with `chmod 600`, and printed to stdout + exactly once so the operator can capture it from the deploy logs. + Subsequent boots load the secret from the file. The secret is never + committed to a config file or set as a platform env var. +- **Only port 3111 is exposed publicly.** The viewer on port 3113 + stays bound to the container's localhost. Reach it via SSH tunnel + (see each platform's README). +- **TLS upstream of the container.** Every managed platform terminates + TLS at its edge proxy; the templates publish a single internal port + (`3111`) to that proxy, never to the host. Integration plugins + configured with `AGENTMEMORY_REQUIRE_HTTPS=1` will refuse to send the + bearer over plaintext HTTP to a non-loopback host, so a + misconfigured TLS layer fails loud instead of silently leaking the + secret. + +## Pick a platform + +- Pick **fly.io** if you want the lowest idle cost and don't mind a + cold-start latency hit on the first request after sleep. +- Pick **Railway** if you want a clicky dashboard flow and a flat + monthly bill. +- Pick **Render** if you want the most "set it and forget it" + Blueprint flow with automatic disk snapshots on paid plans. +- Pick **Coolify** if you already run a VPS and want a self-hosted + control plane — same Docker Compose stack, no third-party host has + your memories. + +All four give you the same agentmemory API at the same port (3111) +with the same auth model. Migrating between them later is a `tar` of +`/data` and a re-import — see each platform's README for the exact +commands. + +## Optional: LLM + embedding provider keys + +Every template runs out of the box without any LLM or embedding key — +search falls back to BM25-only mode and synthetic (zero-LLM) +compression keeps memories indexable. To unlock LLM-powered +compression and hybrid (BM25 + vector) recall, add one of the +following to your platform's environment variables (Fly: +`flyctl secrets set`; Railway / Render / Coolify: dashboard +*Variables / Environment* tab): + +| Variable | Purpose | +|---------------------------|----------------------------------------------------------| +| `ANTHROPIC_API_KEY` | LLM-backed compression + summarization | +| `GEMINI_API_KEY` | LLM provider alternative | +| `OPENROUTER_API_KEY` | LLM provider alternative | +| `OPENAI_API_KEY` | Embedding provider (text-embedding-3-small by default) | +| `VOYAGE_API_KEY` | Embedding provider alternative | +| `AGENTMEMORY_AUTO_COMPRESS=true` | Run LLM compression on every observation batch | +| `AGENTMEMORY_INJECT_CONTEXT=true` | Inject recalled memories back into agent prompts | + +The defaults are intentionally conservative: provider keys default to +absent (no third-party calls), `AGENTMEMORY_AUTO_COMPRESS` is off, +and `AGENTMEMORY_INJECT_CONTEXT` is off. Opt in only after you've +confirmed your provider quota can absorb the workload. + +## Cold-start budget + +Measured against fly.io's `iad` region with a 1 GB volume: + +``` +machine image prepared : 5.1 s +volume mount + format : 2.5 s +firecracker boot : 1.0 s +entrypoint + chown : 0.5 s +iii-engine ready : 3.0 s +agentmemory worker reg : 2.0 s +───────────────────────────────── +healthcheck passes : ~9-10 s +``` + +Every template's health-check `grace_period` (or compose +`start_period`) is set to 30 s for a 3x safety margin. Tune lower +once you've measured your own platform's image-pull characteristics. diff --git a/deploy/coolify/Dockerfile b/deploy/coolify/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f6c433ffb48bf55b82681354fd2155b3e6665e8 --- /dev/null +++ b/deploy/coolify/Dockerfile @@ -0,0 +1,32 @@ +ARG III_VERSION=0.11.2 + +FROM iiidev/iii:${III_VERSION} AS iii-image + +FROM node:22-slim + +ARG AGENTMEMORY_VERSION=0.9.12 +ARG III_VERSION=0.11.2 +ARG III_SDK_VERSION=0.11.2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates tini gosu curl \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=iii-image /app/iii /usr/local/bin/iii + +WORKDIR /opt/agentmemory +RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ + && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ + && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory + +ENV AGENTMEMORY_III_VERSION=${III_VERSION} \ + TINI_SUBREAPER=1 + +COPY --chmod=0755 entrypoint.sh /usr/local/bin/agentmemory-entrypoint.sh + +EXPOSE 3111 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \ + CMD curl -fsS http://127.0.0.1:3111/agentmemory/livez || exit 1 + +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agentmemory-entrypoint.sh"] diff --git a/deploy/coolify/README.md b/deploy/coolify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..feec4757b3786889d87229cba107aafab3c0773e --- /dev/null +++ b/deploy/coolify/README.md @@ -0,0 +1,132 @@ +# Deploy agentmemory on Coolify + +[Coolify](https://coolify.io/self-hosted) is an open-source, self-hosted +Heroku/Render alternative that you run on your own VPS. This template +deploys agentmemory as a Coolify *Application* backed by a Docker +Compose stack — Coolify handles TLS termination, persistent volume +provisioning, log aggregation, and the deploy webhook for you. + +## What you get + +- A public HTTPS endpoint serving the agentmemory REST API behind + Coolify's built-in Traefik/Caddy proxy. The container port (`3111`) + is exposed to the proxy network only — never bound to the host — so + TLS termination and domain routing stay under proxy control. +- A persistent Docker volume backing `/data` for memories, BM25 index, + and stream backlog. Coolify auto-prefixes the volume name with the + application's UUID so the data survives redeploys. +- An HTTP health-check at `/agentmemory/livez` declared in the + Dockerfile (`HEALTHCHECK` directive). Coolify reuses it for + rolling-deploy decisions. + +## One-time setup + +1. **Open your Coolify dashboard** and click **+ New → Application**. +2. **Source**: pick *Public Repository*. Paste: + ``` + https://github.com/rohitg00/agentmemory + ``` + Branch: `main`. +3. **Build Pack**: select *Docker Compose*. +4. **Base Directory**: `deploy/coolify` +5. **Compose Path**: `docker-compose.yml` +6. Click **Save**, then on the application settings screen set a + **Domain** in the form `https://:3111` (the `:3111` + suffix tells Coolify's proxy which container port to forward to; + it still serves over 443/80 publicly). +7. Click **Deploy**. + +That's it. Coolify clones the repo, builds the Dockerfile under +`deploy/coolify/`, provisions the `agentmemory-data` named volume on +the host, attaches Traefik (or Caddy) for the public domain, and starts +the service. The container is reachable only through the proxy — there +is no published host port. + +## Capture the HMAC secret + +Once the deploy logs show the service is up, open the application's +**Logs** tab in Coolify and search for `AGENTMEMORY_SECRET=`. You will +see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`. +Copy it into your client environment (`~/.bashrc`, Claude Desktop +config, etc.). The secret is never printed again on subsequent boots. + +## Verify the deployment + +```bash +curl "https:///agentmemory/livez" +# {"status":"ok"} +``` + +For an authenticated call, your client must send +`Authorization: Bearer `. + +## Viewer access (port 3113 stays internal) + +The viewer port is not exposed by the compose file on purpose — it +holds the unauthenticated admin surface in older releases and the +proxied surface in current ones, neither of which belongs on the open +internet. Two paths to reach it: + +**Option A — SSH tunnel from the Coolify host.** Coolify gives you SSH +access to the underlying VPS. From your laptop: + +```bash +ssh -L 3113:127.0.0.1:3113 @ +# inside the SSH session, find the container: +docker ps --filter name=agentmemory --format "{{.Names}}" +# tunnel into the container's port from the host: +docker exec -it sh -c "curl http://localhost:3113" +``` + +Cleaner version: bind the container's 3113 to the host's loopback by +adding `- "127.0.0.1:3113:3113"` to the `ports:` block in +`docker-compose.yml`, redeploy, then `ssh -L 3113:127.0.0.1:3113 +@` is enough. + +**Option B — expose 3113 as a second Coolify domain protected by HTTP +basic auth.** Coolify's per-service routing supports adding a second +public endpoint with basic-auth middleware. Useful if you want to +share the viewer with a teammate without giving them SSH. + +## Rotate the HMAC secret + +```bash +ssh @ +docker exec -it sh -c "rm /data/.hmac" +exit +``` + +Then click **Redeploy** in the Coolify dashboard. The next boot prints +a fresh secret to the logs. + +## Back up `/data` + +Coolify exposes the named volume on the host filesystem under +`/var/lib/docker/volumes/_agentmemory-data/_data`. Back it +up with your existing host-level snapshot tooling (Restic, Borg, +`rsync`, BTRFS snapshots, etc.) or via Coolify's built-in *Backups* +feature for Docker volumes. + +## Cost floor and resources + +- **Hardware**: the agentmemory container idles at ~150 MB RSS, climbs + to ~400 MB under steady traffic. The bundled iii engine adds another + ~80 MB. A 1 vCPU / 1 GB VPS is comfortably enough for a personal + install. +- **VPS providers commonly paired with Coolify**: Hetzner CX22 + (~€3.79/month), DigitalOcean Basic Droplet ($6/month), Vultr Cloud + Compute ($6/month). Coolify itself is free. +- **Volume storage**: tied to whatever block storage the VPS provides; + typically pennies per GB-month. + +## Known caveats + +- The Dockerfile builds on the Coolify host on every deploy. First + deploy takes ~2 minutes; cached layers shrink subsequent rebuilds to + under 30 seconds. Pin `AGENTMEMORY_VERSION` and `III_VERSION` in + `docker-compose.yml`'s `build.args` block to lock a specific release. +- Coolify's *Persistent Storage* tab will show `agentmemory-data` as a + managed volume — do not delete it from the dashboard if you want + your memories to survive a redeploy. +- arm64 hosts work — the iii binary selection in the Dockerfile uses + `uname -m` and downloads the matching tarball. diff --git a/deploy/coolify/docker-compose.yml b/deploy/coolify/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..149f806d0a379804589da1fd0f5703761b7e60e2 --- /dev/null +++ b/deploy/coolify/docker-compose.yml @@ -0,0 +1,30 @@ +services: + agentmemory: + build: + context: . + dockerfile: Dockerfile + args: + AGENTMEMORY_VERSION: "0.9.12" + III_VERSION: "0.11.2" + III_SDK_VERSION: "0.11.2" + restart: unless-stopped + environment: + SERVICE_FQDN_AGENTMEMORY_3111: ${SERVICE_FQDN_AGENTMEMORY_3111} + expose: + - "3111" + volumes: + - agentmemory-data:/data + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:3111/agentmemory/livez || exit 1"] + interval: 30s + timeout: 5s + start_period: 30s + retries: 3 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + +volumes: + agentmemory-data: diff --git a/deploy/coolify/entrypoint.sh b/deploy/coolify/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffdd633395ff9a11f2b81ccea11db01a8042bf98 --- /dev/null +++ b/deploy/coolify/entrypoint.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# agentmemory first-boot entrypoint. +# +# Runs as root so it can: +# 1. Overwrite the npm-bundled iii-config.yaml (which binds 127.0.0.1 +# and uses relative ./data paths) with a deploy-tuned version that +# binds 0.0.0.0 and uses absolute /data paths. +# 2. chown the platform-mounted /data volume to the runtime user +# (managed platforms mount volumes root-owned 755 by default). +# 3. Generate the HMAC secret on first boot and persist it to +# /data/.hmac (chmod 600) so the secret survives restarts. +# +# Then it execs the agentmemory CLI under gosu as the unprivileged +# `node` user. + +set -eu + +DATA_DIR="${AGENTMEMORY_DATA_DIR:-/data}" +HMAC_FILE="${AGENTMEMORY_HMAC_FILE:-/data/.hmac}" +RUN_AS="node:node" +III_CONFIG="/opt/agentmemory/node_modules/@agentmemory/agentmemory/dist/iii-config.yaml" + +mkdir -p "$DATA_DIR" +chown -R "$RUN_AS" "$DATA_DIR" + +cat > "$III_CONFIG" <<'EOF' +workers: + - name: iii-http + config: + port: 3111 + host: 0.0.0.0 + default_timeout: 180000 + cors: + allowed_origins: + - "http://localhost:3111" + - "http://localhost:3113" + - "http://127.0.0.1:3111" + - "http://127.0.0.1:3113" + allowed_methods: [GET, POST, PUT, DELETE, OPTIONS] + - name: iii-state + config: + adapter: + name: kv + config: + store_method: file_based + file_path: /data/state_store.db + - name: iii-queue + config: + adapter: + name: builtin + - name: iii-pubsub + config: + adapter: + name: local + - name: iii-cron + config: + adapter: + name: kv + - name: iii-stream + config: + port: 3112 + host: 0.0.0.0 + adapter: + name: kv + config: + store_method: file_based + file_path: /data/stream_store + - name: iii-observability + config: + enabled: true + service_name: agentmemory + exporter: memory + sampling_ratio: 1.0 + metrics_enabled: true + logs_enabled: true + logs_console_output: true +EOF +chown "$RUN_AS" "$III_CONFIG" + +if [ ! -s "$HMAC_FILE" ]; then + SECRET="$(openssl rand -hex 32)" + umask 077 + printf '%s\n' "$SECRET" > "$HMAC_FILE" + chmod 600 "$HMAC_FILE" + chown "$RUN_AS" "$HMAC_FILE" + echo "================================================================" + echo "agentmemory: generated HMAC secret on first boot" + echo "AGENTMEMORY_SECRET=$SECRET" + echo "Copy this value now. It will not be printed again." + echo "Stored at: $HMAC_FILE (chmod 600)" + echo "To rotate: delete $HMAC_FILE on the persistent volume and restart." + echo "================================================================" +fi + +AGENTMEMORY_SECRET="$(cat "$HMAC_FILE")" +export AGENTMEMORY_SECRET + +exec gosu "$RUN_AS" agentmemory "$@" diff --git a/deploy/fly/Dockerfile b/deploy/fly/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89257f9378a7c35070307d1886af0b3c1fe24485 --- /dev/null +++ b/deploy/fly/Dockerfile @@ -0,0 +1,35 @@ +ARG III_VERSION=0.11.2 + +FROM iiidev/iii:${III_VERSION} AS iii-image + +FROM node:22-slim + +ARG AGENTMEMORY_VERSION=0.9.12 +ARG III_VERSION=0.11.2 +ARG III_SDK_VERSION=0.11.2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates tini gosu curl \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=iii-image /app/iii /usr/local/bin/iii + +# Install agentmemory into a dedicated prefix so the local package.json's +# `overrides` field pins iii-sdk down to match the engine (agentmemory's +# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that +# requires the new sandbox-everything worker model the agentmemory CLI +# is not refactored for yet). `npm install -g` ignores overrides, hence +# the local prefix. +WORKDIR /opt/agentmemory +RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ + && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ + && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory + +ENV AGENTMEMORY_III_VERSION=${III_VERSION} \ + TINI_SUBREAPER=1 + +COPY --chmod=0755 entrypoint.sh /usr/local/bin/agentmemory-entrypoint.sh + +EXPOSE 3111 + +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agentmemory-entrypoint.sh"] diff --git a/deploy/fly/README.md b/deploy/fly/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b7b4e9096d0329b6b207bba171ced4f50e0b937 --- /dev/null +++ b/deploy/fly/README.md @@ -0,0 +1,166 @@ +# Deploy agentmemory on fly.io + +This template runs agentmemory on a single fly.io machine with a 1 GB +persistent volume mounted at `/data`. The HMAC secret is generated on +first boot and persisted to the volume — you capture it from the deploy +logs exactly once. + +## What you get + +- A public HTTPS endpoint serving the agentmemory REST API on port 3111 +- A 1 GB Fly Volume at `/data` for memories, BM25 index, and stream backlog +- `auto_stop_machines = "stop"` and `min_machines_running = 0` — the + machine sleeps when idle, so cost floor approaches $0 for low traffic +- HTTP healthcheck at `/agentmemory/livez` every 30 s +- The HMAC bearer secret is generated on first boot inside the + container and persisted to `/data/.hmac` (chmod 600); the operator + copies it from the deploy logs once. + +## One-time setup + +Pick a unique Fly app name first — `agentmemory` itself is likely taken. +Every command below references `$APP`, so set it once and the rest of the +flow stays consistent: + +```bash +# 1. Install flyctl: https://fly.io/docs/flyctl/install/ +# 2. Pick your unique app name (and matching volume name): +export APP="agentmemory-$(whoami)" # or any other globally-unique name +export VOLUME="${APP//-/_}_data" # Fly volume names can't contain '-' + +# 3. From this directory: +fly launch --copy-config --no-deploy --name "$APP" + +# 4. Create the volume in the same region as the app: +fly volumes create "$VOLUME" --region iad --size 1 + +# 5. Deploy: +fly deploy --app "$APP" +``` + +If `fly launch` reports the name is taken, pick another value for `$APP`, +re-export, and re-run. + +## Capture the HMAC secret + +Right after the first deploy succeeds: + +```bash +fly logs --app "$APP" | grep -A1 AGENTMEMORY_SECRET= +``` + +You will see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`. +Copy it into your client environment (`~/.bashrc`, Claude Desktop config, +the viewer unlock prompt, etc.). The secret is never printed again on +subsequent boots. + +If the first-boot log line is no longer available, read the persisted +secret from the mounted volume: + +```bash +fly ssh console --app "$APP" -C "sh -lc 'cat /data/.hmac'" +``` + +## Verify the deployment + +```bash +curl "https://$APP.fly.dev/agentmemory/livez" +# {"status":"ok"} +``` + +For an authenticated call, your client must send `Authorization: Bearer `. + +## Viewer access (port 3113 stays internal) + +The viewer port is intentionally not exposed publicly. Tunnel to it: + +```bash +fly proxy 3113:3113 --app "$APP" +# then open http://localhost:3113 +``` + +`fly proxy` opens an mTLS WireGuard channel to the machine, so the +viewer's bearer token still has to ride a loopback connection on your +laptop — the v0.9.12 plaintext-bearer guard stays satisfied. + +The entrypoint sets `AGENTMEMORY_VIEWER_HOST=::` **only when it detects +Fly's runtime variables** (`FLY_APP_NAME` / `FLY_ALLOC_ID`). That makes +the viewer listen on the machine's `fly-local-6pn` WireGuard interface +as well as loopback so `fly proxy` can reach it. The same branch +pre-seeds `VIEWER_ALLOWED_HOSTS=localhost:3113,127.0.0.1:3113,[::1]:3113`, +which are the Host headers `fly proxy 3113:3113` actually emits on +your laptop. + +When `AGENTMEMORY_VIEWER_HOST` is non-loopback the viewer enforces two +extra guards: it refuses to start unless `VIEWER_ALLOWED_HOSTS` is +explicitly set, and every request to `/agentmemory/*` must present +`Authorization: Bearer $AGENTMEMORY_SECRET`. Static HTML and the +favicon are still served unauthenticated. If a proxied viewer request +gets a 401, the browser UI prompts for `AGENTMEMORY_SECRET` and stores +it in session storage so subsequent viewer API calls include the bearer. +Use the value printed in the first-boot logs or read `/data/.hmac` +inside the machine. + +> **Security warning.** Setting `AGENTMEMORY_VIEWER_HOST=0.0.0.0` or +> `::` turns the viewer into a network-reachable proxy that signs every +> upstream call with `AGENTMEMORY_SECRET`. Never enable that outside a +> network you trust (Fly's WireGuard mesh in this template), and never +> set it in a plain `docker run -p 3113:3113 …` on a shared host — the +> entrypoint deliberately skips the override when Fly env vars are +> absent so a plain Docker pull stays loopback-only. + +## Rotate the HMAC secret + +```bash +fly ssh console --app "$APP" +rm /data/.hmac +exit +fly machine restart +fly logs --app "$APP" | grep AGENTMEMORY_SECRET= +``` + +Update every client with the new secret. Old tokens stop working +immediately. + +## Back up `/data` + +```bash +fly ssh console --app "$APP" -C "tar czf - /data" > "$APP-$(date +%Y%m%d).tar.gz" +``` + +To restore on a fresh machine: + +```bash +cat "$APP-YYYYMMDD.tar.gz" | fly ssh console --app "$APP" -C "tar xzf - -C /" +fly machine restart +``` + +## Cost floor and egress + +- Idle (machine stopped): the volume costs ~$0.15/GB/month. A 1 GB + volume is roughly $0.15/month. +- Active (machine running on `shared-cpu-1x` with 512 MB): about + $1.94/month if it ran 24/7; in practice `auto_stop_machines` keeps + that well under $1. +- Outbound bandwidth: 100 GB/month free on the Hobby plan, then $0.02/GB + in North America / Europe. + +See for the up-to-date rate card. + +## Known caveats + +- The volume lives in one region. To survive a region outage, create a + second volume in another region and update `primary_region` after the + failover, or take snapshots with `fly volumes snapshots create`. +- The Dockerfile builds in the Fly Builder on every deploy — first + build is ~30 seconds; cached layers shrink rebuilds to under 10 + seconds. Image is ~114 MB. +- First deploy lands on a **shared IPv4 + dedicated IPv6** by default + (free). If you need a dedicated IPv4 for legacy clients without SNI, + run `fly ips allocate-v4 --app "$APP"` — costs $2/month. +- Cold-start (from machine launch to passing `/agentmemory/livez`) is + ~9 seconds measured. `grace_period = "30s"` on the health check + gives a 3x safety margin. +- Bump `AGENTMEMORY_VERSION` or `III_VERSION` in the Dockerfile to + upgrade. `fly deploy --build-arg AGENTMEMORY_VERSION=` also works + for a one-off without editing the file. diff --git a/deploy/fly/entrypoint.sh b/deploy/fly/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..5fd4cc2681f1b07a55c7e4e78e6caf6dc9ca0fee --- /dev/null +++ b/deploy/fly/entrypoint.sh @@ -0,0 +1,112 @@ +#!/bin/sh +# agentmemory first-boot entrypoint. +# +# Runs as root so it can: +# 1. Overwrite the npm-bundled iii-config.yaml (which binds 127.0.0.1 +# and uses relative ./data paths) with a deploy-tuned version that +# binds 0.0.0.0 and uses absolute /data paths. +# 2. chown the platform-mounted /data volume to the runtime user +# (managed platforms mount volumes root-owned 755 by default). +# 3. Generate the HMAC secret on first boot and persist it to +# /data/.hmac (chmod 600) so the secret survives restarts. +# +# Then it execs the agentmemory CLI under gosu as the unprivileged +# `node` user. + +set -eu + +DATA_DIR="${AGENTMEMORY_DATA_DIR:-/data}" +HMAC_FILE="${AGENTMEMORY_HMAC_FILE:-/data/.hmac}" +RUN_AS="node:node" +III_CONFIG="/opt/agentmemory/node_modules/@agentmemory/agentmemory/dist/iii-config.yaml" + +mkdir -p "$DATA_DIR" +chown -R "$RUN_AS" "$DATA_DIR" + +cat > "$III_CONFIG" <<'EOF' +workers: + - name: iii-http + config: + port: 3111 + host: 0.0.0.0 + default_timeout: 180000 + cors: + allowed_origins: + - "http://localhost:3111" + - "http://localhost:3113" + - "http://127.0.0.1:3111" + - "http://127.0.0.1:3113" + allowed_methods: [GET, POST, PUT, DELETE, OPTIONS] + - name: iii-state + config: + adapter: + name: kv + config: + store_method: file_based + file_path: /data/state_store.db + - name: iii-queue + config: + adapter: + name: builtin + - name: iii-pubsub + config: + adapter: + name: local + - name: iii-cron + config: + adapter: + name: kv + - name: iii-stream + config: + port: 3112 + host: 0.0.0.0 + adapter: + name: kv + config: + store_method: file_based + file_path: /data/stream_store + - name: iii-observability + config: + enabled: true + service_name: agentmemory + exporter: memory + sampling_ratio: 1.0 + metrics_enabled: true + logs_enabled: true + logs_console_output: true +EOF +chown "$RUN_AS" "$III_CONFIG" + +if [ ! -s "$HMAC_FILE" ]; then + SECRET="$(openssl rand -hex 32)" + umask 077 + printf '%s\n' "$SECRET" > "$HMAC_FILE" + chmod 600 "$HMAC_FILE" + chown "$RUN_AS" "$HMAC_FILE" + echo "================================================================" + echo "agentmemory: generated HMAC secret on first boot" + echo "AGENTMEMORY_SECRET=$SECRET" + echo "Copy this value now. It will not be printed again." + echo "Stored at: $HMAC_FILE (chmod 600)" + echo "To rotate: delete $HMAC_FILE on the persistent volume and restart." + echo "================================================================" +fi + +AGENTMEMORY_SECRET="$(cat "$HMAC_FILE")" +export AGENTMEMORY_SECRET + +# The viewer's default 127.0.0.1 bind is unreachable through fly proxy, +# which enters the machine via fly-local-6pn (IPv6). Opt into a +# non-loopback bind ONLY when we're actually inside Fly (detected via +# Fly's runtime variables). A plain `docker run` of this image will not +# see these variables and will keep the safe-by-default loopback bind, +# so it can't silently expose the viewer's bearer-authorized proxy to +# the LAN. VIEWER_ALLOWED_HOSTS is preseeded to the Host headers that +# `fly proxy 3113:3113` actually produces on the operator's laptop. +if [ -n "${FLY_APP_NAME:-}" ] || [ -n "${FLY_ALLOC_ID:-}" ]; then + : "${AGENTMEMORY_VIEWER_HOST:=::}" + : "${VIEWER_ALLOWED_HOSTS:=localhost:3113,127.0.0.1:3113,[::1]:3113}" + export AGENTMEMORY_VIEWER_HOST VIEWER_ALLOWED_HOSTS +fi + +exec gosu "$RUN_AS" agentmemory "$@" diff --git a/deploy/fly/fly.toml b/deploy/fly/fly.toml new file mode 100644 index 0000000000000000000000000000000000000000..03f58bc9217957d556f02ea20a8a96554191fdec --- /dev/null +++ b/deploy/fly/fly.toml @@ -0,0 +1,44 @@ +# fly.io deployment for agentmemory. +# +# The HMAC secret is generated by entrypoint.sh on first boot and persisted +# to the mounted volume at /data/.hmac. Operator copies it once from +# `fly logs` then never sees it again. To rotate: `fly ssh console` and +# `rm /data/.hmac`, then `fly machine restart`. +# +# Only port 3111 (REST API) is exposed publicly. Viewer 3113 stays bound +# to localhost inside the machine; reach it via `fly proxy 3113:3113`. + +app = "agentmemory" +primary_region = "iad" + +[build] + dockerfile = "Dockerfile" + +[[mounts]] + source = "agentmemory_data" + destination = "/data" + initial_size = "1gb" + +[http_service] + internal_port = 3111 + force_https = true + auto_stop_machines = "stop" + auto_start_machines = true + min_machines_running = 0 + processes = ["app"] + + [http_service.concurrency] + type = "requests" + soft_limit = 200 + hard_limit = 250 + + [[http_service.checks]] + interval = "30s" + timeout = "5s" + grace_period = "30s" + method = "GET" + path = "/agentmemory/livez" + +[[vm]] + size = "shared-cpu-1x" + memory = "512mb" diff --git a/deploy/railway/Dockerfile b/deploy/railway/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89257f9378a7c35070307d1886af0b3c1fe24485 --- /dev/null +++ b/deploy/railway/Dockerfile @@ -0,0 +1,35 @@ +ARG III_VERSION=0.11.2 + +FROM iiidev/iii:${III_VERSION} AS iii-image + +FROM node:22-slim + +ARG AGENTMEMORY_VERSION=0.9.12 +ARG III_VERSION=0.11.2 +ARG III_SDK_VERSION=0.11.2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates tini gosu curl \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=iii-image /app/iii /usr/local/bin/iii + +# Install agentmemory into a dedicated prefix so the local package.json's +# `overrides` field pins iii-sdk down to match the engine (agentmemory's +# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that +# requires the new sandbox-everything worker model the agentmemory CLI +# is not refactored for yet). `npm install -g` ignores overrides, hence +# the local prefix. +WORKDIR /opt/agentmemory +RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ + && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ + && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory + +ENV AGENTMEMORY_III_VERSION=${III_VERSION} \ + TINI_SUBREAPER=1 + +COPY --chmod=0755 entrypoint.sh /usr/local/bin/agentmemory-entrypoint.sh + +EXPOSE 3111 + +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agentmemory-entrypoint.sh"] diff --git a/deploy/railway/README.md b/deploy/railway/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9aad4fb32e5daa30db99db0fd474ba74e03948a3 --- /dev/null +++ b/deploy/railway/README.md @@ -0,0 +1,136 @@ +# Deploy agentmemory on Railway + +This template runs agentmemory on a single Railway service with a +persistent volume mounted at `/data`. The HMAC secret is generated on +first boot and persisted to the volume — you read it once from the +deploy logs and copy it into your client. + +## What you get + +- A public HTTPS endpoint serving the agentmemory REST API on port 3111 +- A persistent Railway Volume at `/data` for memories, BM25 index, and + stream backlog +- Railway healthcheck against `/agentmemory/livez` +- The HMAC bearer secret is generated on first boot inside the + container and persisted to `/data/.hmac` (chmod 600); the operator + copies it from the deploy logs once. +- The deploy uses `requiredMountPath: /data` so Railway refuses to + start the service if no volume is attached at that path — first + deploy must create the volume from the dashboard. + +## Deploy via Railway dashboard + +1. Click **Deploy from GitHub** in the Railway dashboard and pick the + `rohitg00/agentmemory` repo. +2. Set the **Config-as-Code Path** under the service Settings to + `deploy/railway/railway.json`. Railway picks up the Dockerfile path + from there. +3. Open the service's **Volumes** tab and add a volume mounted at + `/data` (Railway volumes are configured in the dashboard or via + `railway volume add`, not in `railway.json`). +4. Click **Deploy**. + +## Deploy via Railway CLI + +```bash +# Install: https://docs.railway.com/guides/cli +railway login +railway init # link a new project +railway up --service agentmemory # builds + deploys +railway volume add --service agentmemory --mount /data # attach persistent volume +railway redeploy # restart with the volume +``` + +## Capture the HMAC secret + +After the first deploy succeeds, open the service's **Deploy Logs**: + +```bash +railway logs --service agentmemory | grep AGENTMEMORY_SECRET= +``` + +You will see exactly one line of the form `AGENTMEMORY_SECRET=<64 hex chars>`. +Copy it into your client environment. The secret is never printed again +on subsequent boots. + +## Verify the deployment + +```bash +curl https://.up.railway.app/agentmemory/livez +# {"status":"ok"} +``` + +For an authenticated call, your client must send `Authorization: Bearer `. + +## Viewer access (port 3113 stays internal) + +Railway only exposes the single public port from your service's +`PORT` env var (which we map to 3111). The viewer stays bound to +localhost inside the container. `railway ssh` is an interactive shell +only — it does not support `-L`-style port forwarding, so reach the +viewer with one of the following. + +**Quick in-container check:** + +```bash +railway ssh --service agentmemory +# inside the container: +curl http://localhost:3113 +``` + +**Browser session — option A (TCP Proxy, recommended):** in the Railway +dashboard, open the service's *Settings → Networking* tab and add a +**TCP Proxy** for container port `3113`. Railway returns a public +host/port pair you can hit directly from your browser. Pair it with the +HMAC bearer-auth header so the viewer is not anonymously reachable. + +**Browser session — option B (in-container sshd):** add an `openssh-server` +process to the image and start it from `entrypoint.sh` on a fixed port, +expose that port through a second Railway TCP Proxy, then use a native +`ssh -L 3113:localhost:3113 -p ` from your laptop. +This is the heavier path; option A is what most users will want. + +## Rotate the HMAC secret + +```bash +railway ssh --service agentmemory +rm /data/.hmac +exit +railway redeploy --service agentmemory +railway logs --service agentmemory | grep AGENTMEMORY_SECRET= +``` + +Update every client with the new secret. Old tokens stop working +immediately. + +## Back up `/data` + +```bash +railway ssh --service agentmemory -- "tar czf - /data" > agentmemory-$(date +%Y%m%d).tar.gz +``` + +To restore on a fresh volume: + +```bash +cat agentmemory-YYYYMMDD.tar.gz | railway ssh --service agentmemory -- "tar xzf - -C /" +railway redeploy --service agentmemory +``` + +## Cost floor and egress + +- Hobby plan: $5/month flat, includes $5 of usage. +- agentmemory at idle plus a 1 GB volume typically uses $3–$6 of usage + per month on the smallest instance, so most users stay near the $5 + floor. +- Egress: $0.10/GB after the bundled allowance. + +See for the current rate card. + +## Known caveats + +- Railway volumes do not auto-snapshot. Take your own backups (above) + or use the dashboard's manual snapshot feature. +- The Dockerfile builds on Railway's builder on every deploy. First + deploy is ~2 minutes; cached layers make subsequent rebuilds quick. + Pin `AGENTMEMORY_VERSION` / `III_VERSION` build args in the + service's *Variables* tab to lock a specific release. diff --git a/deploy/railway/entrypoint.sh b/deploy/railway/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffdd633395ff9a11f2b81ccea11db01a8042bf98 --- /dev/null +++ b/deploy/railway/entrypoint.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# agentmemory first-boot entrypoint. +# +# Runs as root so it can: +# 1. Overwrite the npm-bundled iii-config.yaml (which binds 127.0.0.1 +# and uses relative ./data paths) with a deploy-tuned version that +# binds 0.0.0.0 and uses absolute /data paths. +# 2. chown the platform-mounted /data volume to the runtime user +# (managed platforms mount volumes root-owned 755 by default). +# 3. Generate the HMAC secret on first boot and persist it to +# /data/.hmac (chmod 600) so the secret survives restarts. +# +# Then it execs the agentmemory CLI under gosu as the unprivileged +# `node` user. + +set -eu + +DATA_DIR="${AGENTMEMORY_DATA_DIR:-/data}" +HMAC_FILE="${AGENTMEMORY_HMAC_FILE:-/data/.hmac}" +RUN_AS="node:node" +III_CONFIG="/opt/agentmemory/node_modules/@agentmemory/agentmemory/dist/iii-config.yaml" + +mkdir -p "$DATA_DIR" +chown -R "$RUN_AS" "$DATA_DIR" + +cat > "$III_CONFIG" <<'EOF' +workers: + - name: iii-http + config: + port: 3111 + host: 0.0.0.0 + default_timeout: 180000 + cors: + allowed_origins: + - "http://localhost:3111" + - "http://localhost:3113" + - "http://127.0.0.1:3111" + - "http://127.0.0.1:3113" + allowed_methods: [GET, POST, PUT, DELETE, OPTIONS] + - name: iii-state + config: + adapter: + name: kv + config: + store_method: file_based + file_path: /data/state_store.db + - name: iii-queue + config: + adapter: + name: builtin + - name: iii-pubsub + config: + adapter: + name: local + - name: iii-cron + config: + adapter: + name: kv + - name: iii-stream + config: + port: 3112 + host: 0.0.0.0 + adapter: + name: kv + config: + store_method: file_based + file_path: /data/stream_store + - name: iii-observability + config: + enabled: true + service_name: agentmemory + exporter: memory + sampling_ratio: 1.0 + metrics_enabled: true + logs_enabled: true + logs_console_output: true +EOF +chown "$RUN_AS" "$III_CONFIG" + +if [ ! -s "$HMAC_FILE" ]; then + SECRET="$(openssl rand -hex 32)" + umask 077 + printf '%s\n' "$SECRET" > "$HMAC_FILE" + chmod 600 "$HMAC_FILE" + chown "$RUN_AS" "$HMAC_FILE" + echo "================================================================" + echo "agentmemory: generated HMAC secret on first boot" + echo "AGENTMEMORY_SECRET=$SECRET" + echo "Copy this value now. It will not be printed again." + echo "Stored at: $HMAC_FILE (chmod 600)" + echo "To rotate: delete $HMAC_FILE on the persistent volume and restart." + echo "================================================================" +fi + +AGENTMEMORY_SECRET="$(cat "$HMAC_FILE")" +export AGENTMEMORY_SECRET + +exec gosu "$RUN_AS" agentmemory "$@" diff --git a/deploy/railway/railway.json b/deploy/railway/railway.json new file mode 100644 index 0000000000000000000000000000000000000000..43f52173b93ad954b5a469b85e81ee7ed0f946ae --- /dev/null +++ b/deploy/railway/railway.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://railway.com/railway.schema.json", + "build": { + "builder": "DOCKERFILE", + "dockerfilePath": "deploy/railway/Dockerfile" + }, + "deploy": { + "numReplicas": 1, + "healthcheckPath": "/agentmemory/livez", + "healthcheckTimeout": 30, + "restartPolicyType": "ON_FAILURE", + "restartPolicyMaxRetries": 10, + "requiredMountPath": "/data" + } +} diff --git a/deploy/render/Dockerfile b/deploy/render/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89257f9378a7c35070307d1886af0b3c1fe24485 --- /dev/null +++ b/deploy/render/Dockerfile @@ -0,0 +1,35 @@ +ARG III_VERSION=0.11.2 + +FROM iiidev/iii:${III_VERSION} AS iii-image + +FROM node:22-slim + +ARG AGENTMEMORY_VERSION=0.9.12 +ARG III_VERSION=0.11.2 +ARG III_SDK_VERSION=0.11.2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates tini gosu curl \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=iii-image /app/iii /usr/local/bin/iii + +# Install agentmemory into a dedicated prefix so the local package.json's +# `overrides` field pins iii-sdk down to match the engine (agentmemory's +# caret range `^0.11.2` otherwise resolves to 0.11.6, the version that +# requires the new sandbox-everything worker model the agentmemory CLI +# is not refactored for yet). `npm install -g` ignores overrides, hence +# the local prefix. +WORKDIR /opt/agentmemory +RUN printf '{"name":"agentmemory-deploy","version":"1.0.0","private":true,"overrides":{"iii-sdk":"%s"}}\n' "${III_SDK_VERSION}" > package.json \ + && npm install "@agentmemory/agentmemory@${AGENTMEMORY_VERSION}" --omit=optional --no-fund --no-audit \ + && ln -s /opt/agentmemory/node_modules/.bin/agentmemory /usr/local/bin/agentmemory + +ENV AGENTMEMORY_III_VERSION=${III_VERSION} \ + TINI_SUBREAPER=1 + +COPY --chmod=0755 entrypoint.sh /usr/local/bin/agentmemory-entrypoint.sh + +EXPOSE 3111 + +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agentmemory-entrypoint.sh"] diff --git a/deploy/render/README.md b/deploy/render/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b73f7eed36824706bd6d639b1757c53a319172b --- /dev/null +++ b/deploy/render/README.md @@ -0,0 +1,113 @@ +# Deploy agentmemory on Render + +This template runs agentmemory on a single Render Web Service with a +persistent disk mounted at `/data`. The HMAC secret is generated on +first boot and persisted to the disk — you capture it from the deploy +logs exactly once. + +## What you get + +- A public HTTPS endpoint serving the agentmemory REST API on port 3111 + (Render injects `PORT` defaulting to 10000; we override it to 3111 + via `envVars` so the published port matches the container's bind) +- A 1 GB persistent disk at `/data` for memories, BM25 index, and + stream backlog +- Render healthcheck against `/agentmemory/livez` +- The HMAC bearer secret is generated on first boot inside the + container and persisted to `/data/.hmac` (chmod 600); the operator + copies it from the deploy logs once. + +## Deploy via Render Blueprint + +Render's one-click deploy button only auto-detects `render.yaml` at the +repository root, which the agentmemory repo keeps clean. Use the +dashboard's manual Blueprint flow instead: + +1. Push the `deploy/render/` directory to a Git provider Render can + reach (a fork of `rohitg00/agentmemory` works). +2. In the Render dashboard, click **New +** → **Blueprint**. +3. Point Render at the repo and the path `deploy/render/render.yaml`. +4. Render reads the Blueprint, provisions the disk, builds the + Dockerfile, and starts the service. The whole flow takes 3–5 + minutes on the first run. + +## Deploy via Render Deploy Hook (one-click) + +Once the Blueprint exists in your account, generate a Deploy Hook URL +in the service settings. Future deploys are a single curl call: + +```bash +curl "https://api.render.com/deploy/srv-XXYYZZ?key=AABBCC" +``` + +To pin a specific `@agentmemory/agentmemory` release, set the +`AGENTMEMORY_VERSION` build arg in the service's *Environment* tab +before the next deploy. Same for `III_VERSION`. + +## Capture the HMAC secret + +After the first deploy succeeds, open the service's **Logs** tab and +search for `AGENTMEMORY_SECRET=`. You will see exactly one line of the +form `AGENTMEMORY_SECRET=<64 hex chars>`. Copy it into your client +environment. The secret is never printed again on subsequent boots. + +## Verify the deployment + +```bash +curl https://agentmemory.onrender.com/agentmemory/livez +# {"status":"ok"} +``` + +For an authenticated call, your client must send `Authorization: Bearer `. + +## Viewer access (port 3113 stays internal) + +Render only exposes one public port per service, and we use it for +3111. The viewer port stays bound to localhost inside the container. +Reach it via Render's SSH: + +```bash +# Settings → SSH → enable for your service, copy the connection command +ssh srv-XXYYZZ@ssh..render.com -L 3113:localhost:3113 +# now http://localhost:3113 in your browser hits the in-container viewer +``` + +## Rotate the HMAC secret + +```bash +ssh srv-XXYYZZ@ssh..render.com +rm /data/.hmac +exit +# trigger a redeploy from the Render dashboard or via the Deploy Hook +``` + +After the redeploy, grab the new secret from the logs and update every +client. Old tokens stop working immediately. + +## Back up `/data` + +```bash +ssh srv-XXYYZZ@ssh..render.com "tar czf - /data" > agentmemory-$(date +%Y%m%d).tar.gz +``` + +Render also takes daily snapshots of persistent disks automatically on +paid plans — the SSH tarball is a belt-and-braces option you can ship +off-platform. + +## Cost floor and egress + +- Starter plan web service: $7/month (0.5 CPU, 512 MB RAM). +- 1 GB persistent disk: $0.25/GB/month, so $0.25/month for the default. +- Bandwidth: 100 GB outbound included, then $0.10/GB. + +See for the current rate card. + +## Known caveats + +- Render Free tier does not support persistent disks. The Starter plan + ($7/month) is the minimum. +- Render restarts the service on every deploy. The HMAC secret survives + because it lives on the disk, but expect a 10–30 s gap of 502s + during rollouts. +- Render runs amd64 only for web services. The Dockerfile selects the + matching iii binary automatically via `uname -m`. diff --git a/deploy/render/entrypoint.sh b/deploy/render/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffdd633395ff9a11f2b81ccea11db01a8042bf98 --- /dev/null +++ b/deploy/render/entrypoint.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# agentmemory first-boot entrypoint. +# +# Runs as root so it can: +# 1. Overwrite the npm-bundled iii-config.yaml (which binds 127.0.0.1 +# and uses relative ./data paths) with a deploy-tuned version that +# binds 0.0.0.0 and uses absolute /data paths. +# 2. chown the platform-mounted /data volume to the runtime user +# (managed platforms mount volumes root-owned 755 by default). +# 3. Generate the HMAC secret on first boot and persist it to +# /data/.hmac (chmod 600) so the secret survives restarts. +# +# Then it execs the agentmemory CLI under gosu as the unprivileged +# `node` user. + +set -eu + +DATA_DIR="${AGENTMEMORY_DATA_DIR:-/data}" +HMAC_FILE="${AGENTMEMORY_HMAC_FILE:-/data/.hmac}" +RUN_AS="node:node" +III_CONFIG="/opt/agentmemory/node_modules/@agentmemory/agentmemory/dist/iii-config.yaml" + +mkdir -p "$DATA_DIR" +chown -R "$RUN_AS" "$DATA_DIR" + +cat > "$III_CONFIG" <<'EOF' +workers: + - name: iii-http + config: + port: 3111 + host: 0.0.0.0 + default_timeout: 180000 + cors: + allowed_origins: + - "http://localhost:3111" + - "http://localhost:3113" + - "http://127.0.0.1:3111" + - "http://127.0.0.1:3113" + allowed_methods: [GET, POST, PUT, DELETE, OPTIONS] + - name: iii-state + config: + adapter: + name: kv + config: + store_method: file_based + file_path: /data/state_store.db + - name: iii-queue + config: + adapter: + name: builtin + - name: iii-pubsub + config: + adapter: + name: local + - name: iii-cron + config: + adapter: + name: kv + - name: iii-stream + config: + port: 3112 + host: 0.0.0.0 + adapter: + name: kv + config: + store_method: file_based + file_path: /data/stream_store + - name: iii-observability + config: + enabled: true + service_name: agentmemory + exporter: memory + sampling_ratio: 1.0 + metrics_enabled: true + logs_enabled: true + logs_console_output: true +EOF +chown "$RUN_AS" "$III_CONFIG" + +if [ ! -s "$HMAC_FILE" ]; then + SECRET="$(openssl rand -hex 32)" + umask 077 + printf '%s\n' "$SECRET" > "$HMAC_FILE" + chmod 600 "$HMAC_FILE" + chown "$RUN_AS" "$HMAC_FILE" + echo "================================================================" + echo "agentmemory: generated HMAC secret on first boot" + echo "AGENTMEMORY_SECRET=$SECRET" + echo "Copy this value now. It will not be printed again." + echo "Stored at: $HMAC_FILE (chmod 600)" + echo "To rotate: delete $HMAC_FILE on the persistent volume and restart." + echo "================================================================" +fi + +AGENTMEMORY_SECRET="$(cat "$HMAC_FILE")" +export AGENTMEMORY_SECRET + +exec gosu "$RUN_AS" agentmemory "$@" diff --git a/deploy/render/render.yaml b/deploy/render/render.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c96516d07acf90222ccd0d412832691549ba53e7 --- /dev/null +++ b/deploy/render/render.yaml @@ -0,0 +1,22 @@ +services: + - type: web + name: agentmemory + runtime: docker + plan: starter + dockerfilePath: ./deploy/render/Dockerfile + dockerContext: ./deploy/render + healthCheckPath: /agentmemory/livez + autoDeploy: false + disk: + name: data + mountPath: /data + sizeGB: 1 + envVars: + - key: PORT + value: "3111" + - key: AGENTMEMORY_VERSION + value: "0.9.12" + - key: III_VERSION + value: "0.11.2" + - key: III_SDK_VERSION + value: "0.11.2" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b1176521dace6395504e07ce4d73129f0ca056a --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,47 @@ +services: + # One-shot init container: docker creates named volumes root:root mode + # 755, but the iii-engine image is distroless and runs as UID 65532 + # with no `chown` of its own. Without this, /data is unwritable, the + # engine silently buffers in RAM, and state evaporates on every + # restart — the exact symptom v0.9.7's working-directory fix set out + # to solve. Runs once at compose-up and exits. + iii-init: + image: busybox:1.36 + user: "0:0" + volumes: + - iii-data:/data + entrypoint: ["sh", "-c", "chown -R 65532:65532 /data && chmod 755 /data"] + restart: "no" + + iii-engine: + # Pinned to v0.11.2 — the last engine that runs agentmemory's current + # worker model cleanly. v0.11.6 introduces a new sandbox-everything- + # via-`iii worker add` model that agentmemory hasn't been refactored + # for yet; the architectural mismatch surfaces as EPIPE reconnect + # loops and empty search after save. Bump only after agentmemory is + # refactored to register as a sandboxed worker. + # + # Override per-shell or via .env file: + # AGENTMEMORY_III_VERSION=0.11.7 docker compose up + image: iiidev/iii:${AGENTMEMORY_III_VERSION:-0.11.2} + user: "65532:65532" + depends_on: + iii-init: + condition: service_completed_successfully + ports: + - "127.0.0.1:49134:49134" + - "127.0.0.1:3111:3111" + - "127.0.0.1:3112:3112" + - "127.0.0.1:9464:9464" + volumes: + - iii-data:/data + - ./iii-config.docker.yaml:/app/config.yaml:ro + restart: unless-stopped + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + +volumes: + iii-data: diff --git a/docs/benchmarks/2026-05-20-coding-agent-life-v1.md b/docs/benchmarks/2026-05-20-coding-agent-life-v1.md new file mode 100644 index 0000000000000000000000000000000000000000..6ee857713aa13d6647de54256ad293c0f326da3f --- /dev/null +++ b/docs/benchmarks/2026-05-20-coding-agent-life-v1.md @@ -0,0 +1,101 @@ +# 2026-05-20 — coding-agent-life-v1 (v0.9.26) + +**Bench:** coding-agent-life-v1 (15 sessions, 15 queries) +**N:** 15 +**K:** 5 +**Hardware:** macOS 15 (Apple Silicon) +**agentmemory:** v0.9.26 +**iii-engine:** v0.11.2 +**Embedding provider:** local default +**Sandbox:** isolated data dir at `/tmp/agentmemory-eval-sandbox/`, ports 3411/3412 + +## Math ceiling on this dataset + +12 of 15 questions have 1 gold session, 3 have 2 gold sessions. Per +`scoreQuestion` in `eval/runner/score.ts`, P@K = `hits / k` averaged +across questions, so the **maximum achievable P@5** is: + +``` +(12 * 1/5) + (3 * 2/5)) / 15 = (2.4 + 1.2) / 15 = 0.240 +``` + +R@5 ceiling is **1.000** (every gold session found in top-5). + +The benchmark is **small** (15 questions) and **gold-sparse** (mostly +single-gold). It's tuned for fast iteration on the retrieval stack, +not for headline P@K comparisons. **Recall** + per-question-type +**P@5** are the signals; aggregate P@5 saturates at 0.240 so it can't +differentiate top-tier adapters. + +## Headline + +`agentmemory-hybrid` hits **100% top-5 hit rate**, R@5 = **1.000**, +P@5 = **0.240** (at the math ceiling — every gold session retrieved +in top-5). + +grep baseline: R@5 = **0.967**, P@5 = **0.227** — missed one gold +session in one multi-gold question. Lift is **recall**, not aggregate +precision. + +## Per-adapter + +| Adapter | P@5 | R@5 | Hit rate | p50 latency | +|---|---|---|---|---| +| grep (tokenized substring) | 0.227 | 0.967 | 15 / 15 | 0 ms | +| `agentmemory-hybrid` | **0.240** | **1.000** | **15 / 15** | 14 ms | + +`agentmemory-hybrid` runs through the production smart-search endpoint (`POST /agentmemory/smart-search`) so it exercises the full BM25 + embedding + reranker stack. + +## Per-question-type + +At K=5 with 1 gold per single-session question, the P@5 ceiling per +question is **0.20**; with 2 gold the ceiling is **0.40**. Both +adapters saturate the per-type ceiling on most types, so the per-type +table primarily exposes where one adapter **misses** gold (failing +the recall side). + +| Type | grep P@5 | grep R@5 | hybrid P@5 | hybrid R@5 | +|---|---|---|---|---| +| single-session-bug | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-infra (n=2) | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-refactor | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-feature | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-test | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-perf | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-api | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-db | 0.20 | 1.00 | 0.20 | 1.00 | +| single-session-release | 0.20 | 1.00 | 0.20 | 1.00 | +| multi-session-causal (2 gold) | 0.40 | 1.00 | 0.40 | 1.00 | +| preference (n=2) | 0.20 | 1.00 | 0.20 | 1.00 | +| multi-session-review (2 gold) | 0.40 | 1.00 | 0.40 | 1.00 | +| temporal (2 gold) | 0.20 | 0.50 | 0.40 | 1.00 | + +The differentiator at this corpus size is **temporal** (`What was shipped on April 8th 2026?`): grep finds 1 of 2 gold sessions, hybrid finds both. Per-type R@5 saturates everywhere else. + +## Methodology + +- 15 fictional Claude Code sessions across a 10-day stretch of a Rust CLI project (`shipctl`) — bug fixes, refactors, infra, perf, schema migrations, preferences, post-mortem +- 15 hand-graded queries with `goldSessionIds[]` covering single-session, multi-session causal, multi-session review, preference, temporal +- Each session ingested via `POST /agentmemory/remember` with `type=eval-session` and `concepts=[session_id]` +- Each query hits `POST /agentmemory/smart-search` with `limit=50`; dedupe by session ID; truncate to K=5 +- No LLM in the retrieval loop +- Sandbox: clean `~/.agentmemory` via `HOME` override + alt ports (3411/3412) so no cross-contamination from a user's real store + +## Reproduce + +```sh +git checkout e9dc710 +npm install --legacy-peer-deps +npm run build + +source eval/scripts/sandbox.sh +npm run eval:coding-life -- --adapters grep,agentmemory +``` + +Outputs land in `eval/reports/coding-life/`: `scores.ndjson` (per-query rows) and `summary.json` (per-adapter and per-type aggregates). + +## Notes + +- The single-session-feature tie (`Which PR introduced helm chart support?`) is interesting: query says `PR introduced helm chart` and gold session has `helm chart` literally — grep wins on lexical exactness, hybrid matches but doesn't outperform. +- The corpus is intentionally small for fast iteration. Hardening targets: paraphrased queries, synonym substitution, in-corpus distractors with shared keywords, longer multi-session chains. +- Vector adapter not measured here — requires `OPENAI_API_KEY`; will be added in a follow-up scorecard alongside LongMemEval `_s`. diff --git a/docs/benchmarks/TEMPLATE.md b/docs/benchmarks/TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..b830e24e00bed1273f0d0b655fb772d101977e72 --- /dev/null +++ b/docs/benchmarks/TEMPLATE.md @@ -0,0 +1,54 @@ +# — + +**Commit:** `` +**Bench:** LongMemEval `_s` / coding-agent-life-v1 / ... +**N:** 500 / 15 / ... +**K:** 5 +**Hardware:** macos-15 / ubuntu-22.04 / ... +**OpenAI model:** text-embedding-3-small +**Anthropic model:** N/A (no LLM in retrieval loop) + +## Headline + +agentmemory-hybrid: **R@5 = XX.XX%**, P@5 = XX.XX%, p50 latency = XXms + +Beats grep baseline by +X.Xpt R@5, vector by +X.Xpt R@5. + +## Per-adapter + +| Adapter | P@5 | R@5 | Hit rate | p50 latency | +|---|---|---|---|---| +| grep | | | | | +| vector | | | | | +| agentmemory-hybrid | | | | | + +## Per-question-type + +| Type | grep R@5 | vector R@5 | agentmemory R@5 | +|---|---|---|---| +| single-session-bug | | | | +| single-session-refactor | | | | +| preference | | | | +| multi-session-causal | | | | +| temporal | | | | + +## Methodology + +- Sessions ingested via `POST /agentmemory/remember` with `type=eval-session` +- Queries hit `POST /agentmemory/smart-search` with `limit=k*4` +- No LLM in retrieval loop. Direct rank from hybrid scoring. +- Ranks dedup by sessionId before truncating to K +- Latency measured as init+query for LongMemEval (per-question fresh state), query-only for coding-life (shared state) + +## Reproduce + +```sh +git checkout +npm install --legacy-peer-deps +OPENAI_API_KEY=sk-... AGENTMEMORY_BASE_URL=http://localhost:3111 \ + npm run eval:longmemeval -- --stratify 10 +``` + +## Notes + + diff --git a/docs/recipes/pairings.md b/docs/recipes/pairings.md new file mode 100644 index 0000000000000000000000000000000000000000..093abf85542ff308b16e5e337d4504e18d7417e0 --- /dev/null +++ b/docs/recipes/pairings.md @@ -0,0 +1,119 @@ +# Pairings + +Open-source projects shipping the rest of the AI coding agent context layer. agentmemory ships persistent session memory. The projects below ship code-graph indexing, multi-agent build pipelines with dashboards, and broader knowledge graphs across non-code assets. Stack them and your agent gets a fuller picture in fewer tool calls. + +## [codegraph](https://github.com/colbymchenry/codegraph) — pre-indexed code knowledge graph (MCP) + +What it does: builds a SQLite-backed code knowledge graph (symbols, call edges, route handlers, full-text search) and exposes it through an MCP server with 8 tools (`codegraph_search`, `codegraph_context`, `codegraph_callers`, `codegraph_callees`, `codegraph_impact`, `codegraph_node`, `codegraph_status`, `codegraph_files`). File watcher keeps the index fresh. Their published benchmark (across VS Code, Django, Tokio, OkHttp, Gin, Alamofire, Excalidraw) shows agents finishing the same architecture question in **~35% less cost, ~70% fewer tool calls** when codegraph is wired in. + +Recipe with agentmemory — both as MCP servers on the same agent: + +```jsonc +// ~/.claude.json or your agent's MCP config +{ + "mcpServers": { + "codegraph": { + "type": "stdio", + "command": "codegraph", + "args": ["serve", "--mcp"] + }, + "agentmemory": { + "type": "stdio", + "command": "npx", + "args": ["@agentmemory/mcp"] + } + } +} +``` + +Question routing that falls out: + +| Question | Tool the agent reaches for | +|---|---| +| "What does `shipctl helm install` call?" | `codegraph_callees` | +| "Where is `auth_check` defined?" | `codegraph_node` | +| "Which routes hit the user controller?" | `codegraph_callers` on the controller node | +| "What did we decide last week about retries?" | `memory_smart_search` | +| "Why did we pick async-std?" | `memory_recall` | +| "Fix the auth bug from the post-mortem" | `memory_smart_search` → post-mortem session, then `codegraph_node` → current `auth.rs` | + +## [Understand Anything](https://github.com/Lum1104/Understand-Anything) — multi-agent code-graph pipeline + dashboard + +What it does: a Claude Code plugin (also installable on 13+ other agents) runs a multi-agent pipeline over a project and produces an interactive web dashboard at `understand-anything.com`. Architecture layers, business-flow domain view, guided tours, persona-adaptive UI, diff impact analysis, framework-aware routes across 14 frameworks. The graph commits to `.understand-anything/knowledge-graph.json` so teammates skip the pipeline. + +Slash commands: +- `/understand` — build the graph (incremental on re-run) +- `/understand-dashboard` — open the interactive web dashboard +- `/understand-chat` — ask anything about the codebase +- `/understand-diff` — analyze impact of current changes +- `/understand-explain` — deep-dive a file or function +- `/understand-onboard` — generate an onboarding guide +- `/understand-domain` — extract business domains, flows, steps +- `/understand-knowledge` — analyze an LLM wiki knowledge base + +Recipe with agentmemory: + +```bash +# Day 1 — new team member joins +/understand # builds the graph +/understand-dashboard # opens the visual map +/understand-onboard # generates onboarding guide + +# Week 2 — same engineer hits a bug +/understand-explain src/auth.rs # architecture context +# agentmemory MCP surfaces the post-mortem and the past 3 fixes touching auth.rs +``` + +The graph teaches you the codebase. agentmemory remembers what you and the agent already did inside it. The two planes don't overlap. + +## [Graphify](https://github.com/safishamsi/graphify) — broader knowledge graph across code, docs, PDFs, images, videos + +What it does: a single slash command (`/graphify .`) maps a whole project — application code, SQL schemas, R scripts, shell scripts, docs, PDFs, papers, images, videos — into one queryable knowledge graph. Output is three files: an interactive `graph.html`, a markdown `GRAPH_REPORT.md` with highlights and suggested questions, and the full `graph.json`. Also ships `graphify export callflow-html` for Mermaid call-flow architecture pages. + +Runs as a skill on Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, and Google Antigravity. + +Recipe with agentmemory: + +```bash +/graphify . # one graph: code + docs + PDFs + images +``` + +This is the broadest sweep across artifacts that live alongside the code. agentmemory then captures everything the agent does while exploring that graph — the questions you asked, the conclusions, the decisions — so the next session opens with both the graph and the conversation history available. + +## How the four projects line up + +Four planes, four consumers, four update models. None of them try to do what the others do. + +| Project | Plane | Surface | Consumer | Update model | +|---|---|---|---|---| +| [agentmemory](https://github.com/rohitg00/agentmemory) | session history (observations, decisions, preferences) | MCP + REST + hooks | agent | live (observations stream) | +| [codegraph](https://github.com/colbymchenry/codegraph) | code structure (symbols, call edges, routes) | MCP server | agent | live (FS watcher) | +| [Understand Anything](https://github.com/Lum1104/Understand-Anything) | code structure + business domain + architecture | plugin (slash commands) + web dashboard | **human** + agent | on-demand `/understand` | +| [Graphify](https://github.com/safishamsi/graphify) | code + docs + PDFs + images + videos | skill (slash command) | human + agent | on-demand `/graphify` | + +## Question types each project handles best + +| Question shape | Best tool | +|---|---| +| "What's the architecture of this repo?" | Understand-Anything dashboard or Graphify `graph.html` | +| "Where is symbol X defined? Who calls it?" | codegraph (`codegraph_node`, `codegraph_callers`) | +| "What does this PDF spec say about the rate limit?" | Graphify | +| "Why did we pick X over Y three sessions ago?" | agentmemory (`memory_smart_search`) | +| "What did we ship on April 8?" | agentmemory (`memory_timeline`) | +| "How does the payment flow work in this codebase?" | Understand-Anything (`/understand-chat`) | +| "Trace impact of changing `Foo::bar`" | codegraph (`codegraph_impact`) or Understand-Anything (`/understand-diff`) | +| "What preferences has the team locked in?" | agentmemory | + +## Suggested install order for a brand-new project + +1. **agentmemory** — observe and persist from day one, even before the codebase has structure. Run `npx @agentmemory/agentmemory connect` and pick your agent. +2. **codegraph** — once code lands, agent queries answer from the index instead of grepping. Run `npx @colbymchenry/codegraph`. +3. **Understand Anything** *or* **Graphify** — when the codebase passes a few thousand LOC or starts shipping docs and PDFs alongside code, generate the graph for visual exploration and onboarding. Run `/plugin install understand-anything` or `uv tool install graphifyy && graphify install`. + +All four are local-first (no data leaves the machine for code-graph workloads). Stacking them costs nothing extra at the network boundary. + +## Cross-project benchmark idea + +`eval/runner/adapters/` accepts new adapters against the same coding-agent-life-v1 corpus and the published LongMemEval `_s` benchmark. A `codegraph` adapter or an `understand-anything` adapter or a `graphify` adapter would let us publish a side-by-side scorecard showing which project owns which question class. The win for the ecosystem is precise framing: each project gets credit for what it does best, with reproducible numbers from a shared harness. + +If you build any of those adapters, open a PR against `agentmemory` with the adapter file under `eval/runner/adapters/` and a scorecard under `docs/benchmarks/`. The scaffold and contract live in [`eval/README.md`](../../eval/README.md). diff --git a/eval/README.md b/eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f29536705bf80280b3ab40164c65e94e6a0876e --- /dev/null +++ b/eval/README.md @@ -0,0 +1,111 @@ +# agentmemory-evals + +Public benchmarks for agentmemory's hybrid memory stack (BM25 + embeddings + consolidation + graph). + +Two families, both reproducible: + +- **LongMemEval** — public 500-question retrieval benchmark over multi-session chat +- **coding-agent-life-v1** — in-house corpus of 15 fictional Claude Code sessions for a Rust CLI project (`shipctl`), with 15 hand-graded queries covering bug fixes, refactors, preferences, and multi-session causal reasoning + +## Adapters + +| Adapter | Backend | API key needed | +|---|---|---| +| `grep` | Tokenized substring match | none | +| `vector` | OpenAI `text-embedding-3-small` + cosine | `OPENAI_API_KEY` | +| `agentmemory` | Running agentmemory server, smart-search endpoint | none (auth optional via `AGENTMEMORY_SECRET`) | + +## Sandbox first + +Running the `agentmemory` adapter against your real `~/.agentmemory` directory pollutes the eval with pre-existing memories AND pollutes your real store with eval test data. Always sandbox. + +`eval/scripts/sandbox.sh` spins up a clean agentmemory + iii-engine on ports 3411/3412 with state in `/tmp/agentmemory-eval-sandbox/`, exports `AGENTMEMORY_BASE_URL`, and tears down on exit. + +```sh +source eval/scripts/sandbox.sh +npm run eval:coding-life -- --adapters grep,agentmemory +``` + +Requires iii v0.11.2 on PATH (agentmemory pin). If you already have a different version installed, install the pinned build into `~/.local/bin` and make sure that directory comes first on `PATH`: + +```sh +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 +export PATH="$HOME/.local/bin:$PATH" # add to ~/.zshrc or ~/.bashrc for persistence +``` + +## Quickstart + +### coding-agent-life-v1 (in-house, no download) + +```sh +# grep baseline, no sandbox needed +npm run eval:coding-life -- --adapters grep + +# add agentmemory + vector (sandbox + OpenAI key) +source eval/scripts/sandbox.sh +OPENAI_API_KEY=sk-... npm run eval:coding-life -- --adapters grep,vector,agentmemory +``` + +### LongMemEval `_s` (public, 278MB download) + +```sh +mkdir -p ~/datasets/longmemeval +curl -Lo ~/datasets/longmemeval/longmemeval_s.json \ + https://huggingface.co/datasets/xiaowu0162/longmemeval/resolve/main/longmemeval_s + +source eval/scripts/sandbox.sh + +# Stratified sample of 10 per type (fast iteration, ~$0.20 OpenAI cost) +OPENAI_API_KEY=sk-... LONGMEMEVAL_PATH=~/datasets/longmemeval/longmemeval_s.json \ + npm run eval:longmemeval -- --stratify 10 + +# Full 500 questions × 3 adapters (~$2 OpenAI cost) +OPENAI_API_KEY=sk-... LONGMEMEVAL_PATH=~/datasets/longmemeval/longmemeval_s.json \ + npm run eval:longmemeval +``` + +## Repo layout + +```text +eval/ +├── README.md +├── runner/ +│ ├── types.ts Adapter, Question, RankedDoc, ScoreRow +│ ├── score.ts P@K, R@K, aggregation +│ ├── load.ts LongMemEval JSON → Question[] +│ ├── adapters/ +│ │ ├── grep.ts tokenized substring baseline +│ │ ├── vector.ts OpenAI embeddings + cosine +│ │ └── agentmemory.ts POST /agentmemory/{remember,smart-search} +│ ├── longmemeval.ts public benchmark runner +│ └── coding-life.ts in-house benchmark runner +└── data/ + └── coding-agent-life-v1/ + ├── sessions.json 15 fictional sessions (~6KB) + └── queries.json 15 queries with gold session IDs +``` + +Reports land in `eval/reports//` (gitignored): `scores.ndjson` + `summary.json`. + +Published scorecards land in `docs/benchmarks/YYYY-MM-DD-.md`. + +## Writing a new adapter + +1. Implement `Adapter` from `eval/runner/types.ts`: + ```ts + import type { Adapter } from "../types.js"; + export const myAdapter: Adapter = { + name: "my-adapter", + async init(sessions, config) { /* index */ return state; }, + async query(q, state, k) { /* search */ return ranked; }, + }; + ``` +2. Register in `eval/runner/{longmemeval,coding-life}.ts` `ADAPTERS` map. +3. Run against `coding-agent-life-v1` to sanity-check before committing OpenAI spend on LongMemEval. + +## Why a benchmark for agentmemory + +agentmemory ships BM25 + embeddings + consolidation + graph retrieval. Numbers from those layers should be measured against grep/vector baselines so the value of each layer is provable. + +The in-house corpus is small on purpose (15 sessions) — covers single-session, multi-session, preference, and temporal question types without taking 15 minutes to run. LongMemEval gives the public-comparison axis. diff --git a/eval/data/coding-agent-life-v1/queries.json b/eval/data/coding-agent-life-v1/queries.json new file mode 100644 index 0000000000000000000000000000000000000000..5603e8a037ac12ff9dca9676b39dbef12a8bc359 --- /dev/null +++ b/eval/data/coding-agent-life-v1/queries.json @@ -0,0 +1,107 @@ +[ + { + "id": "q-001", + "type": "single-session-bug", + "question": "Where did we land the auth env var precedence fix?", + "answer": "PR #11 with SHIPCTL_TOKEN > SHIP_TOKEN > SC_TOKEN precedence", + "goldSessionIds": ["sess-001"] + }, + { + "id": "q-002", + "type": "single-session-infra", + "question": "What was the multi-arch Docker fix?", + "answer": "Added --platform=$BUILDPLATFORM and BUILDX_PLATFORMS for amd64+arm64", + "goldSessionIds": ["sess-002"] + }, + { + "id": "q-003", + "type": "single-session-refactor", + "question": "Where did we consolidate the retry logic?", + "answer": "src/retry.rs with exponential backoff base=200ms cap=30s full jitter", + "goldSessionIds": ["sess-003"] + }, + { + "id": "q-004", + "type": "single-session-feature", + "question": "Which PR introduced helm chart support?", + "answer": "PR #14", + "goldSessionIds": ["sess-004"] + }, + { + "id": "q-005", + "type": "single-session-test", + "question": "Which test was flaky on macos and how was it fixed?", + "answer": "fs-watcher emits_changekind_file_delete; bumped wait to 1500ms + retry: 2", + "goldSessionIds": ["sess-005"] + }, + { + "id": "q-006", + "type": "single-session-perf", + "question": "How did we fix the memory leak?", + "answer": "Replaced unbounded HashMap with LruCache cap=10k in src/cache.rs (PR #16)", + "goldSessionIds": ["sess-006"] + }, + { + "id": "q-007", + "type": "single-session-api", + "question": "How did we handle the github API rate limit?", + "answer": "Conditional requests with If-None-Match etag and 304 caching via http-cache", + "goldSessionIds": ["sess-007"] + }, + { + "id": "q-008", + "type": "single-session-db", + "question": "What was the schema migration approach for run_history?", + "answer": "Three-phase: nullable column + dual-write, backfill + flip reads, drop old column", + "goldSessionIds": ["sess-008"] + }, + { + "id": "q-009", + "type": "single-session-infra", + "question": "How is the docs site deployed?", + "answer": "GitHub Actions docs.yml workflow + mdbook build + Cloudflare Pages on shipctl.dev", + "goldSessionIds": ["sess-009"] + }, + { + "id": "q-010", + "type": "single-session-release", + "question": "Which PR set up the cross-platform release pipeline?", + "answer": "PR #19 with cross-rs for linux and native macos/windows builds", + "goldSessionIds": ["sess-010"] + }, + { + "id": "q-011", + "type": "multi-session-causal", + "question": "What was the root cause of the staging incident, and where was it fixed?", + "answer": "SHIPCTL_TOKEN unset caused fallback to bad SC_TOKEN; fixed in PR #11 (sess-001) with precedence test; documented in post-mortem (sess-014)", + "goldSessionIds": ["sess-001", "sess-014"] + }, + { + "id": "q-012", + "type": "preference", + "question": "Which async runtime does the team prefer for new code?", + "answer": "async-std (decided in arch review, not tokio)", + "goldSessionIds": ["sess-015"] + }, + { + "id": "q-013", + "type": "preference", + "question": "What are the user's formatting preferences?", + "answer": "2-space indent in yaml, tab in rust, rust-analyzer over rls, cargo clippy before commit", + "goldSessionIds": ["sess-012"] + }, + { + "id": "q-014", + "type": "multi-session-review", + "question": "What was the race condition Aria fixed in the schema migration?", + "answer": "Dual-write step had race when two writers hit same row; Aria added per-row advisory lock", + "goldSessionIds": ["sess-008", "sess-013"] + }, + { + "id": "q-015", + "type": "temporal", + "question": "What was shipped on April 8th 2026?", + "answer": "Auth env-var precedence fix in PR #11, then started docker arm64 work", + "goldSessionIds": ["sess-001", "sess-011"] + } +] diff --git a/eval/data/coding-agent-life-v1/sessions.json b/eval/data/coding-agent-life-v1/sessions.json new file mode 100644 index 0000000000000000000000000000000000000000..7113413422832b6c401b5da78f53dfcc8dc5728e --- /dev/null +++ b/eval/data/coding-agent-life-v1/sessions.json @@ -0,0 +1,77 @@ +[ + { + "id": "sess-001", + "timestamp": "2026-04-08T09:14:00Z", + "content": "[user] auth check broken on staging when SHIPCTL_TOKEN unset, falling back to wrong env var\n[assistant] looked at src/auth.rs:42. precedence is SHIPCTL_TOKEN > SHIP_TOKEN > legacy SC_TOKEN. legacy path didn't validate. fixing precedence + adding length check.\n[user] yeah ship it\n[assistant] PR #11 opened with fix + regression test. covers all three env names." + }, + { + "id": "sess-002", + "timestamp": "2026-04-08T14:30:00Z", + "content": "[user] docker build failing for arm64 on M2 runner\n[assistant] missing target in Dockerfile FROM line. need --platform=$BUILDPLATFORM on builder stage. updated Dockerfile + Makefile to set BUILDX_PLATFORMS=linux/amd64,linux/arm64. tested locally on apple silicon, builds clean." + }, + { + "id": "sess-003", + "timestamp": "2026-04-09T10:02:00Z", + "content": "[user] retry logic is duplicated across handlers. consolidate.\n[assistant] extracted retry_with_backoff into src/retry.rs. exponential backoff base=200ms cap=30s jitter=full. all 4 callsites now use it. cuts ~80 lines." + }, + { + "id": "sess-004", + "timestamp": "2026-04-10T11:45:00Z", + "content": "[user] add helm chart support\n[assistant] new subcommand `shipctl helm install`. wraps helm CLI, threads through --namespace and --values. PR #14 has the changes + 12 integration tests. Aria reviewed and approved." + }, + { + "id": "sess-005", + "timestamp": "2026-04-11T16:20:00Z", + "content": "[user] test flake on macos-22 runner. emits_changekind_file_delete keeps failing\n[assistant] fsevents propagation slower on apple silicon, the 800ms wait isn't enough. bumped to 1500ms + describe-level retry: 2. all 15 fs-watcher tests pass now." + }, + { + "id": "sess-006", + "timestamp": "2026-04-12T09:50:00Z", + "content": "[user] memory leak in long-running daemon. RSS grows 5MB/min.\n[assistant] traced to unbounded HashMap in src/cache.rs. swapped for LruCache with 10k cap. RSS stable at 180MB after 6h soak test. PR #16." + }, + { + "id": "sess-007", + "timestamp": "2026-04-13T13:15:00Z", + "content": "[user] github API rate-limiting us when listing PRs. 5000/hr isn't enough during ci\n[assistant] added conditional requests with If-None-Match etag. cache 304 responses. drops actual API calls by ~70%. used http-cache crate." + }, + { + "id": "sess-008", + "timestamp": "2026-04-15T10:30:00Z", + "content": "[user] schema migration for run_history table needs zero-downtime\n[assistant] three-phase migration. phase 1: add nullable new column + dual-write. phase 2: backfill + flip reads. phase 3: drop old column. avoids ALTER TABLE locks. ran on staging, took 4s for 2M rows." + }, + { + "id": "sess-009", + "timestamp": "2026-04-16T15:40:00Z", + "content": "[user] docs site is stale. set up auto-deploy from main\n[assistant] added .github/workflows/docs.yml. mdbook build + cloudflare pages deploy. domain shipctl.dev wired up. preview deploys on PRs." + }, + { + "id": "sess-010", + "timestamp": "2026-04-17T11:00:00Z", + "content": "[user] release pipeline. cut v0.3.0 with binaries for linux/macos/windows\n[assistant] new .github/workflows/release.yml. cross-rs for static linux, native for macos + windows. uploads to gh release + crates.io publish. tag-triggered. PR #19 has the workflow." + }, + { + "id": "sess-011", + "timestamp": "2026-04-08T17:00:00Z", + "content": "[user] standup notes: shipped #11 auth fix this morning. starting on docker arm64 next." + }, + { + "id": "sess-012", + "timestamp": "2026-04-10T18:30:00Z", + "content": "[user] preferences: I like rust analyzer over rls. always run cargo clippy before commit. prefer 2-space indent in yaml but tab in rust." + }, + { + "id": "sess-013", + "timestamp": "2026-04-15T19:00:00Z", + "content": "[assistant] reviewed Aria's PR #18 (schema migration). flagged race condition in dual-write step when two writers hit same row. Aria added per-row advisory lock. lgtm now." + }, + { + "id": "sess-014", + "timestamp": "2026-04-16T20:10:00Z", + "content": "[user] post-mortem from prod incident last week: SHIPCTL_TOKEN was unset in staging, fell back to bad SC_TOKEN which had wrong perms. delivery delayed 40min. action items: (1) precedence test (done in #11), (2) startup validation, (3) alert on auth fallback." + }, + { + "id": "sess-015", + "timestamp": "2026-04-17T16:45:00Z", + "content": "[user] preferences: stick to async-std not tokio for new code. team agreed in arch review." + } +] diff --git a/eval/runner/adapters/agentmemory.ts b/eval/runner/adapters/agentmemory.ts new file mode 100644 index 0000000000000000000000000000000000000000..38028a7d8bfde9e58124017eeb0f443da93983fb --- /dev/null +++ b/eval/runner/adapters/agentmemory.ts @@ -0,0 +1,93 @@ +import type { Adapter, RankedDoc, Session } from "../types.js"; + +interface AgentMemoryState { + baseUrl: string; + secret?: string; + sessions: Session[]; + observationToSession: Map; +} + +interface RememberResponse { + memory?: { id?: string }; + observationId?: string; + id?: string; + observation?: { id?: string }; +} + +interface SmartSearchResponse { + results?: Array<{ + obsId?: string; + id?: string; + observationId?: string; + sessionId?: string; + score?: number; + content?: string; + }>; + observations?: Array<{ + obsId?: string; + id?: string; + sessionId?: string; + score?: number; + content?: string; + }>; +} + +function authHeaders(secret?: string): Record { + const h: Record = { "Content-Type": "application/json" }; + if (secret) h.Authorization = `Bearer ${secret}`; + return h; +} + +export const agentmemoryAdapter: Adapter = { + name: "agentmemory-hybrid", + async init(sessions, config) { + const baseUrl = (config?.baseUrl as string) ?? process.env.AGENTMEMORY_BASE_URL ?? "http://localhost:3111"; + const secret = (config?.secret as string) ?? process.env.AGENTMEMORY_SECRET; + const observationToSession = new Map(); + for (const s of sessions) { + const res = await fetch(`${baseUrl}/agentmemory/remember`, { + method: "POST", + headers: authHeaders(secret), + body: JSON.stringify({ + content: s.content, + type: "eval-session", + concepts: [s.id], + }), + }); + if (!res.ok) { + throw new Error(`remember failed for ${s.id}: ${res.status} ${await res.text()}`); + } + const body = (await res.json()) as RememberResponse; + const obsId = + body.memory?.id ?? body.observationId ?? body.id ?? body.observation?.id; + if (obsId) observationToSession.set(obsId, s.id); + } + return { baseUrl, secret, sessions, observationToSession }; + }, + async query(q, state, k) { + const res = await fetch(`${state.baseUrl}/agentmemory/smart-search`, { + method: "POST", + headers: authHeaders(state.secret), + body: JSON.stringify({ query: q, limit: Math.max(k * 10, 50) }), + }); + if (!res.ok) { + throw new Error(`smart-search failed: ${res.status} ${await res.text()}`); + } + const body = (await res.json()) as SmartSearchResponse; + const rows = body.results ?? body.observations ?? []; + const ranked: RankedDoc[] = []; + const seen = new Set(); + for (const row of rows) { + let sessionId = row.sessionId; + if (!sessionId) { + const memId = row.obsId ?? row.id ?? row.observationId; + sessionId = memId ? state.observationToSession.get(memId) : undefined; + } + if (!sessionId || seen.has(sessionId)) continue; + seen.add(sessionId); + ranked.push({ sessionId, score: row.score ?? 0 }); + if (ranked.length >= k) break; + } + return ranked; + }, +}; diff --git a/eval/runner/adapters/grep.ts b/eval/runner/adapters/grep.ts new file mode 100644 index 0000000000000000000000000000000000000000..28b18ea66e10760ee17666fd9b43c8deb02c479d --- /dev/null +++ b/eval/runner/adapters/grep.ts @@ -0,0 +1,36 @@ +import type { Adapter, RankedDoc, Session } from "../types.js"; + +interface GrepState { + sessions: Session[]; +} + +function tokenize(s: string): string[] { + return s + .toLowerCase() + .replace(/[^a-z0-9_]+/g, " ") + .split(/\s+/) + .filter((t) => t.length > 2); +} + +export const grepAdapter: Adapter = { + name: "grep", + async init(sessions) { + return { sessions }; + }, + async query(q, state, k) { + const terms = tokenize(q); + const scored: RankedDoc[] = []; + for (const s of state.sessions) { + const body = s.content.toLowerCase(); + let hits = 0; + for (const t of terms) { + if (body.includes(t)) hits += 1; + } + if (hits > 0) { + scored.push({ sessionId: s.id, score: hits }); + } + } + scored.sort((a, b) => b.score - a.score); + return scored.slice(0, k); + }, +}; diff --git a/eval/runner/adapters/vector.ts b/eval/runner/adapters/vector.ts new file mode 100644 index 0000000000000000000000000000000000000000..c40e414d7edd33f75b65a438bbf2b8f453537893 --- /dev/null +++ b/eval/runner/adapters/vector.ts @@ -0,0 +1,108 @@ +import type { Adapter, RankedDoc, Session } from "../types.js"; + +interface VectorState { + sessions: Session[]; + embeddings: Float32Array[]; +} + +const OPENAI_URL = "https://api.openai.com/v1/embeddings"; +const MODEL = "text-embedding-3-small"; +const DIM = 1536; + +async function embed(text: string, apiKey: string): Promise { + const res = await fetch(OPENAI_URL, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + body: JSON.stringify({ input: text, model: MODEL }), + }); + if (!res.ok) { + throw new Error(`OpenAI embed failed: ${res.status} ${await res.text()}`); + } + const data = (await res.json()) as { data: Array<{ embedding: number[] }> }; + return Float32Array.from(data.data[0].embedding); +} + +async function embedBatch(texts: string[], apiKey: string): Promise { + const res = await fetch(OPENAI_URL, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + body: JSON.stringify({ input: texts, model: MODEL }), + }); + if (!res.ok) { + throw new Error(`OpenAI batch embed failed: ${res.status} ${await res.text()}`); + } + const data = (await res.json()) as { data: Array<{ embedding: number[]; index: number }> }; + if (!Array.isArray(data.data) || data.data.length !== texts.length) { + throw new Error( + `OpenAI batch embed: expected ${texts.length} embeddings, got ${data.data?.length ?? 0}`, + ); + } + const out = new Array(texts.length); + for (const row of data.data) { + if ( + !Number.isInteger(row.index) || + row.index < 0 || + row.index >= texts.length || + out[row.index] !== undefined + ) { + throw new Error(`OpenAI batch embed: invalid or duplicate index ${row.index}`); + } + if (!Array.isArray(row.embedding) || row.embedding.length === 0) { + throw new Error(`OpenAI batch embed: empty embedding at index ${row.index}`); + } + out[row.index] = Float32Array.from(row.embedding); + } + return out; +} + +function cosine(a: Float32Array, b: Float32Array): number { + let dot = 0; + let na = 0; + let nb = 0; + for (let i = 0; i < a.length; i++) { + dot += a[i] * b[i]; + na += a[i] * a[i]; + nb += b[i] * b[i]; + } + const denom = Math.sqrt(na) * Math.sqrt(nb); + return denom === 0 ? 0 : dot / denom; +} + +export const vectorAdapter: Adapter = { + name: "vector", + async init(sessions) { + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) throw new Error("OPENAI_API_KEY required for vector adapter"); + const embeddings: Float32Array[] = new Array(sessions.length); + const BATCH = 50; + for (let i = 0; i < sessions.length; i += BATCH) { + const batch = sessions.slice(i, i + BATCH); + const vecs = await embedBatch( + batch.map((s) => s.content.slice(0, 8000)), + apiKey, + ); + for (let j = 0; j < vecs.length; j++) embeddings[i + j] = vecs[j]; + } + if (embeddings.length > 0 && embeddings[0].length !== DIM) { + throw new Error(`unexpected embedding dim: ${embeddings[0].length}`); + } + return { sessions, embeddings }; + }, + async query(q, state, k) { + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) throw new Error("OPENAI_API_KEY required for vector adapter"); + const qvec = await embed(q, apiKey); + const scored: RankedDoc[] = state.sessions.map((s, i) => ({ + sessionId: s.id, + score: cosine(qvec, state.embeddings[i]), + })); + scored.sort((a, b) => b.score - a.score); + return scored.slice(0, k); + }, +}; diff --git a/eval/runner/coding-life.ts b/eval/runner/coding-life.ts new file mode 100644 index 0000000000000000000000000000000000000000..753ca87f4724ca09be7ecf3226eb0718e15b83ca --- /dev/null +++ b/eval/runner/coding-life.ts @@ -0,0 +1,101 @@ +import { readFileSync, existsSync, mkdirSync, writeFileSync, appendFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { parseArgs } from "node:util"; +import { agentmemoryAdapter } from "./adapters/agentmemory.js"; +import { grepAdapter } from "./adapters/grep.js"; +import { vectorAdapter } from "./adapters/vector.js"; +import { aggregate, scoreQuestion } from "./score.js"; +import type { Adapter, Question, ScoreRow, Session } from "./types.js"; + +const ADAPTERS: Record = { + grep: grepAdapter as unknown as Adapter, + vector: vectorAdapter as unknown as Adapter, + agentmemory: agentmemoryAdapter as unknown as Adapter, +}; + +interface CliOptions { + data: string; + adapters: string; + k: string; + out: string; +} + +function parse(): CliOptions { + const { values } = parseArgs({ + options: { + data: { type: "string", default: "eval/data/coding-agent-life-v1" }, + adapters: { type: "string", default: "grep,vector,agentmemory" }, + k: { type: "string", default: "5" }, + out: { type: "string", default: "eval/reports/coding-life" }, + }, + }); + return values as unknown as CliOptions; +} + +async function main(): Promise { + const opts = parse(); + const k = Number(opts.k); + if (!Number.isInteger(k) || k <= 0) { + console.error(`--k must be a positive integer, got: ${opts.k}`); + process.exit(2); + } + const sessions = JSON.parse( + readFileSync(resolve(opts.data, "sessions.json"), "utf8"), + ) as Session[]; + const queriesRaw = JSON.parse( + readFileSync(resolve(opts.data, "queries.json"), "utf8"), + ) as Array>; + const questions: Question[] = queriesRaw.map((q) => ({ ...q, haystack: sessions })); + const adapterNames = opts.adapters.split(",").map((s) => s.trim()).filter(Boolean); + for (const a of adapterNames) { + if (!ADAPTERS[a]) { + console.error(`unknown adapter: ${a}. options: ${Object.keys(ADAPTERS).join(",")}`); + process.exit(2); + } + } + console.log( + `loaded ${sessions.length} sessions, ${questions.length} queries, adapters: ${adapterNames.join(",")}, k=${k}`, + ); + + const outDir = resolve(opts.out); + mkdirSync(outDir, { recursive: true }); + const ndjsonPath = `${outDir}/scores.ndjson`; + if (existsSync(ndjsonPath)) writeFileSync(ndjsonPath, ""); + + const rows: ScoreRow[] = []; + for (const adapterName of adapterNames) { + const adapter = ADAPTERS[adapterName]; + console.log(`\n== ${adapter.name} ==`); + const state = await adapter.init(sessions); + try { + for (const q of questions) { + const t0 = performance.now(); + const ranked = await adapter.query(q.question, state, k); + const latencyMs = performance.now() - t0; + const row = scoreQuestion(q, ranked, k, adapter.name, latencyMs); + rows.push(row); + appendFileSync(ndjsonPath, JSON.stringify(row) + "\n"); + const mark = row.hit ? "+" : "-"; + console.log( + ` ${mark} ${q.id} [${q.type}] R@${k}=${row.recallAtK.toFixed(2)} (${Math.round(latencyMs)}ms)`, + ); + } + } finally { + if (adapter.teardown) await adapter.teardown(state); + } + } + + const agg = aggregate(rows); + writeFileSync(`${outDir}/summary.json`, JSON.stringify(agg, null, 2)); + console.log("\n=== Summary ==="); + for (const [adapter, stats] of Object.entries(agg.byAdapter)) { + console.log( + ` ${adapter.padEnd(22)} P@${k}=${stats.p.toFixed(3)} R@${k}=${stats.r.toFixed(3)} hit=${stats.hit}/${stats.n} p50=${Math.round(stats.latencyP50)}ms`, + ); + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/eval/runner/load.ts b/eval/runner/load.ts new file mode 100644 index 0000000000000000000000000000000000000000..aece245246696f2dbbd278b5842f41af8bcabbd2 --- /dev/null +++ b/eval/runner/load.ts @@ -0,0 +1,54 @@ +import { readFileSync } from "node:fs"; +import type { Question, Session } from "./types.js"; + +interface LongMemEvalRaw { + question_id: string; + question_type: string; + question: string; + answer?: string; + answer_session_ids: string[]; + haystack_session_ids: string[]; + haystack_sessions: Array>; +} + +function flattenSession(turns: Array<{ role: string; content: string }>): string { + return turns.map((t) => `[${t.role}] ${t.content}`).join("\n\n"); +} + +export function loadLongMemEval(path: string, limit?: number): Question[] { + const raw = JSON.parse(readFileSync(path, "utf8")) as LongMemEvalRaw[]; + const slice = typeof limit === "number" ? raw.slice(0, limit) : raw; + const questions: Question[] = []; + for (const r of slice) { + if (r.haystack_session_ids.length !== r.haystack_sessions.length) { + throw new Error( + `LongMemEval row ${r.question_id}: haystack_session_ids (${r.haystack_session_ids.length}) and haystack_sessions (${r.haystack_sessions.length}) length mismatch`, + ); + } + const haystack: Session[] = r.haystack_session_ids.map((id, i) => ({ + id, + content: flattenSession(r.haystack_sessions[i]), + })); + questions.push({ + id: r.question_id, + type: r.question_type, + question: r.question, + answer: r.answer, + goldSessionIds: r.answer_session_ids, + haystack, + }); + } + return questions; +} + +export function stratifySample(questions: Question[], perType: number): Question[] { + const buckets: Record = {}; + for (const q of questions) { + (buckets[q.type] ??= []).push(q); + } + const out: Question[] = []; + for (const type of Object.keys(buckets).sort()) { + out.push(...buckets[type].slice(0, perType)); + } + return out; +} diff --git a/eval/runner/longmemeval.ts b/eval/runner/longmemeval.ts new file mode 100644 index 0000000000000000000000000000000000000000..a906fa2157ff2c512eb92bd5b643658bdb7215c3 --- /dev/null +++ b/eval/runner/longmemeval.ts @@ -0,0 +1,126 @@ +import { existsSync, mkdirSync, writeFileSync, appendFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { parseArgs } from "node:util"; +import { agentmemoryAdapter } from "./adapters/agentmemory.js"; +import { grepAdapter } from "./adapters/grep.js"; +import { vectorAdapter } from "./adapters/vector.js"; +import { loadLongMemEval, stratifySample } from "./load.js"; +import { aggregate, scoreQuestion } from "./score.js"; +import type { Adapter, ScoreRow } from "./types.js"; + +const ADAPTERS: Record = { + grep: grepAdapter as unknown as Adapter, + vector: vectorAdapter as unknown as Adapter, + agentmemory: agentmemoryAdapter as unknown as Adapter, +}; + +interface CliOptions { + data: string; + adapters: string; + k: string; + limit?: string; + stratify?: string; + out: string; +} + +function parse(): CliOptions { + const { values } = parseArgs({ + options: { + data: { type: "string", default: process.env.LONGMEMEVAL_PATH ?? "" }, + adapters: { type: "string", default: "grep,vector,agentmemory" }, + k: { type: "string", default: "5" }, + limit: { type: "string" }, + stratify: { type: "string" }, + out: { type: "string", default: "eval/reports/longmemeval" }, + }, + }); + return values as unknown as CliOptions; +} + +async function main(): Promise { + const opts = parse(); + if (!opts.data) { + console.error("--data required (or LONGMEMEVAL_PATH env)"); + process.exit(2); + } + const k = Number(opts.k); + if (!Number.isInteger(k) || k <= 0) { + console.error(`--k must be a positive integer, got: ${opts.k}`); + process.exit(2); + } + let limit: number | undefined; + if (opts.limit !== undefined) { + limit = Number(opts.limit); + if (!Number.isInteger(limit) || limit <= 0) { + console.error(`--limit must be a positive integer, got: ${opts.limit}`); + process.exit(2); + } + } + let perType: number | undefined; + if (opts.stratify !== undefined) { + perType = Number(opts.stratify); + if (!Number.isInteger(perType) || perType <= 0) { + console.error(`--stratify must be a positive integer, got: ${opts.stratify}`); + process.exit(2); + } + } + const adapterNames = opts.adapters.split(",").map((s) => s.trim()).filter(Boolean); + for (const a of adapterNames) { + if (!ADAPTERS[a]) { + console.error(`unknown adapter: ${a}. options: ${Object.keys(ADAPTERS).join(",")}`); + process.exit(2); + } + } + let questions = loadLongMemEval(resolve(opts.data), limit); + if (perType) questions = stratifySample(questions, perType); + console.log( + `loaded ${questions.length} questions, adapters: ${adapterNames.join(",")}, k=${k}`, + ); + + const outDir = resolve(opts.out); + mkdirSync(outDir, { recursive: true }); + const ndjsonPath = `${outDir}/scores.ndjson`; + if (existsSync(ndjsonPath)) writeFileSync(ndjsonPath, ""); + mkdirSync(dirname(ndjsonPath), { recursive: true }); + + const rows: ScoreRow[] = []; + for (const adapterName of adapterNames) { + const adapter = ADAPTERS[adapterName]; + console.log(`\n== ${adapter.name} ==`); + for (const q of questions) { + const t0 = performance.now(); + const state = await adapter.init(q.haystack); + try { + const ranked = await adapter.query(q.question, state, k); + const latencyMs = performance.now() - t0; + const row = scoreQuestion(q, ranked, k, adapter.name, latencyMs); + rows.push(row); + appendFileSync(ndjsonPath, JSON.stringify(row) + "\n"); + const mark = row.hit ? "+" : "-"; + console.log( + ` ${mark} ${q.id} [${q.type}] R@${k}=${row.recallAtK.toFixed(2)} (${Math.round(latencyMs)}ms)`, + ); + } finally { + if (adapter.teardown) await adapter.teardown(state); + } + } + } + + const agg = aggregate(rows); + const summaryPath = `${outDir}/summary.json`; + writeFileSync(summaryPath, JSON.stringify(agg, null, 2)); + + console.log("\n=== Summary ==="); + for (const [adapter, stats] of Object.entries(agg.byAdapter)) { + console.log( + ` ${adapter.padEnd(22)} P@${k}=${stats.p.toFixed(3)} R@${k}=${stats.r.toFixed(3)} hit=${stats.hit}/${stats.n} p50=${Math.round(stats.latencyP50)}ms`, + ); + } + console.log(`\nwrote ${ndjsonPath}`); + console.log(`wrote ${summaryPath}`); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/eval/runner/score.ts b/eval/runner/score.ts new file mode 100644 index 0000000000000000000000000000000000000000..b21d30cada4db96e7b0ae7858499deed04f41bc6 --- /dev/null +++ b/eval/runner/score.ts @@ -0,0 +1,78 @@ +import type { Question, RankedDoc, ScoreRow } from "./types.js"; + +export function scoreQuestion( + q: Question, + ranked: RankedDoc[], + k: number, + adapter: string, + latencyMs: number, +): ScoreRow { + const topK = ranked.slice(0, k).map((r) => r.sessionId); + const gold = new Set(q.goldSessionIds); + const hits = topK.filter((id) => gold.has(id)).length; + const precisionAtK = k > 0 ? hits / k : 0; + const recallAtK = gold.size === 0 ? 0 : hits / gold.size; + const hit = hits > 0; + let topGoldRank: number | null = null; + for (let i = 0; i < ranked.length; i++) { + if (gold.has(ranked[i].sessionId)) { + topGoldRank = i + 1; + break; + } + } + return { + questionId: q.id, + questionType: q.type, + adapter, + k, + precisionAtK, + recallAtK, + hit, + topGoldRank, + latencyMs, + }; +} + +export function aggregate(rows: ScoreRow[]): { + byAdapter: Record; + byType: Record>; +} { + const byAdapter: Record< + string, + { p: number; r: number; hit: number; n: number; latencyP50: number } + > = {}; + const latencies: Record = {}; + for (const r of rows) { + const a = (byAdapter[r.adapter] ??= { p: 0, r: 0, hit: 0, n: 0, latencyP50: 0 }); + a.p += r.precisionAtK; + a.r += r.recallAtK; + a.hit += r.hit ? 1 : 0; + a.n += 1; + (latencies[r.adapter] ??= []).push(r.latencyMs); + } + for (const adapter of Object.keys(byAdapter)) { + const a = byAdapter[adapter]; + a.p = a.p / a.n; + a.r = a.r / a.n; + const sorted = latencies[adapter].slice().sort((x, y) => x - y); + a.latencyP50 = sorted[Math.floor(sorted.length / 2)] ?? 0; + } + const byType: Record> = + {}; + for (const r of rows) { + const t = (byType[r.questionType] ??= {}); + const a = (t[r.adapter] ??= { p: 0, r: 0, hit: 0, n: 0 }); + a.p += r.precisionAtK; + a.r += r.recallAtK; + a.hit += r.hit ? 1 : 0; + a.n += 1; + } + for (const t of Object.keys(byType)) { + for (const adapter of Object.keys(byType[t])) { + const a = byType[t][adapter]; + a.p = a.p / a.n; + a.r = a.r / a.n; + } + } + return { byAdapter, byType }; +} diff --git a/eval/runner/types.ts b/eval/runner/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..e72a64082559af12b2ae4ae3d7595697485ace6b --- /dev/null +++ b/eval/runner/types.ts @@ -0,0 +1,38 @@ +export interface Session { + id: string; + timestamp?: string; + content: string; +} + +export interface Question { + id: string; + type: string; + question: string; + answer?: string; + goldSessionIds: string[]; + haystack: Session[]; +} + +export interface RankedDoc { + sessionId: string; + score: number; +} + +export interface Adapter { + name: string; + init(sessions: Session[], config?: Record): Promise; + query(q: string, state: State, k: number): Promise; + teardown?(state: State): Promise; +} + +export interface ScoreRow { + questionId: string; + questionType: string; + adapter: string; + k: number; + precisionAtK: number; + recallAtK: number; + hit: boolean; + topGoldRank: number | null; + latencyMs: number; +} diff --git a/eval/scripts/sandbox.sh b/eval/scripts/sandbox.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d4023300f957d24ae70d1e24c0dd0b046722a5d --- /dev/null +++ b/eval/scripts/sandbox.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Boot a sandboxed agentmemory + iii-engine on alt ports with a clean data dir, +# so eval runs aren't polluted by (and don't pollute) your real ~/.agentmemory. +# Source it: `source eval/scripts/sandbox.sh` then run eval scripts; +# the sandbox is torn down on EXIT. + +set -euo pipefail + +SANDBOX_ROOT="${SANDBOX_ROOT:-/tmp/agentmemory-eval-sandbox}" +SANDBOX_PORT="${SANDBOX_PORT:-3411}" +SANDBOX_STREAM_PORT="${SANDBOX_STREAM_PORT:-3412}" + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + +if ! command -v iii >/dev/null 2>&1; then + echo "iii binary not on PATH. Install pinned version:" + echo " 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" + exit 1 +fi + +iii_ver=$(iii --version 2>&1 | head -1) +if [[ "$iii_ver" != "0.11.2" ]]; then + echo "warning: iii version on PATH is $iii_ver; agentmemory pins 0.11.2" +fi + +if [[ ! -f "$REPO_ROOT/dist/index.mjs" ]]; then + echo "dist/ missing. Run: npm run build" >&2 + exit 1 +fi + +if [[ -z "${SANDBOX_ROOT:-}" || "$SANDBOX_ROOT" == "/" || "$SANDBOX_ROOT" != /tmp/* ]]; then + echo "refusing to wipe SANDBOX_ROOT='$SANDBOX_ROOT' — must be non-empty and under /tmp/" >&2 + exit 1 +fi +rm -rf "$SANDBOX_ROOT" +mkdir -p "$SANDBOX_ROOT/data" "$SANDBOX_ROOT/.agentmemory" + +cat > "$SANDBOX_ROOT/iii-config.yaml" < "$SANDBOX_ROOT/iii.log" 2>&1 & +SANDBOX_PID=$! + +cleanup() { + echo "tearing down sandbox (pid $SANDBOX_PID)" + kill "$SANDBOX_PID" 2>/dev/null || true + sleep 1 + kill -9 "$SANDBOX_PID" 2>/dev/null || true +} +trap cleanup EXIT + +# wait for livez +for i in $(seq 1 30); do + if curl -sS --max-time 1 "http://localhost:$SANDBOX_PORT/agentmemory/livez" 2>/dev/null | grep -q '"status":"ok"'; then + export AGENTMEMORY_BASE_URL="http://localhost:$SANDBOX_PORT" + echo "sandbox ready: $AGENTMEMORY_BASE_URL" + echo " state: $SANDBOX_ROOT/data/" + echo " logs: $SANDBOX_ROOT/iii.log" + return 0 2>/dev/null || exit 0 + fi + sleep 1 +done + +echo "sandbox failed to come up within 30s. last log lines:" >&2 +tail -10 "$SANDBOX_ROOT/iii.log" >&2 +exit 1 diff --git a/examples/python/README.md b/examples/python/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ea284dd47eea753de9a6813379d887f1898e4796 --- /dev/null +++ b/examples/python/README.md @@ -0,0 +1,71 @@ +# Python usage via `iii-sdk` + +agentmemory registers its core operations as iii functions (`mem::remember`, +`mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Any +language with an iii SDK can call them directly over the WebSocket transport +on `ws://localhost:49134` — no separate REST client needed. + +This example uses the official Python SDK. + +## Install + +```bash +pip install iii-sdk +``` + +## Quickstart + +Start the agentmemory daemon (defaults to `ws://localhost:49134`, REST on +`:3111`): + +```bash +npx -y @agentmemory/agentmemory +``` + +Then from Python: + +```python +from iii import register_worker + +iii = register_worker("ws://localhost:49134") +iii.connect() + +iii.trigger({ + "function_id": "mem::remember", + "payload": { + "project": "demo", + "title": "auth-stack", + "content": "Service uses HMAC bearer tokens; refresh every 24h.", + "concepts": ["auth", "hmac", "refresh"], + }, +}) + +hits = iii.trigger({ + "function_id": "mem::smart-search", + "payload": {"project": "demo", "query": "how do tokens refresh", "limit": 5}, +}) +print(hits) +``` + +## Functions exposed + +| Function id | Purpose | Required payload | +|---|---|---| +| `mem::remember` | Save a memory | `project`, `title`, `content` | +| `mem::observe` | Hook-driven observation ingest | `hookType`, `sessionId`, `project`, `cwd`, `timestamp` | +| `mem::context` | Render context for a session under a token budget | `sessionId`, `project`, optional `budget` | +| `mem::smart-search` | Hybrid BM25 + vector + concept recall | `project`, `query`, optional `limit` | +| `mem::forget` | Delete a memory by id | `id` | + +The HTTP-trigger wrappers under `api::*` (callable via REST on `:3111`) exist +for the same operations if you need to reach the daemon from a host without an +iii runtime. Inside the iii ecosystem, calling the `mem::*` functions directly +is lower latency. + +## Files + +- `quickstart.py` — minimal save-then-search loop. +- `observe_and_recall.py` — observation ingest + context rendering at a token + budget. + +Both scripts assume the daemon is already running. diff --git a/examples/python/observe_and_recall.py b/examples/python/observe_and_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..4747bf0b527c865c7c59bb872f78ef34dea95d8e --- /dev/null +++ b/examples/python/observe_and_recall.py @@ -0,0 +1,67 @@ +"""Observation ingest + context rendering at a token budget. + +Pattern: send hook-style observations during a coding session, then ask +agentmemory to render the most relevant context back at a fixed token budget. + +Prerequisites: + pip install iii-sdk + npx -y @agentmemory/agentmemory + +Run: + python examples/python/observe_and_recall.py +""" + +from datetime import datetime, timezone +from iii import register_worker + + +SESSION_ID = "py-example-session-001" +PROJECT = "demo" + + +def now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def main() -> None: + iii = register_worker("ws://localhost:49134") + iii.connect() + + observations = [ + ("PreToolUse", {"tool": "Bash", "command": "cargo test"}), + ("PostToolUse", {"tool": "Bash", "exit_code": 0}), + ("UserPromptSubmit", {"prompt": "refactor auth middleware to use HMAC"}), + ] + + for hook_type, data in observations: + iii.trigger( + { + "function_id": "mem::observe", + "payload": { + "hookType": hook_type, + "sessionId": SESSION_ID, + "project": PROJECT, + "cwd": "/home/user/service", + "timestamp": now_iso(), + "data": data, + }, + } + ) + + context = iii.trigger( + { + "function_id": "mem::context", + "payload": { + "sessionId": SESSION_ID, + "project": PROJECT, + "budget": 2000, + }, + } + ) + + print(f"Rendered context ({context.get('token_count', 0)} tokens):\n") + print(context.get("text", "")) + + +if __name__ == "__main__": + main() diff --git a/examples/python/quickstart.py b/examples/python/quickstart.py new file mode 100644 index 0000000000000000000000000000000000000000..56e5ae11aeb2cc1e15e7ebef3f8aac86cd6351af --- /dev/null +++ b/examples/python/quickstart.py @@ -0,0 +1,46 @@ +"""Minimal agentmemory usage via iii-sdk. + +Prerequisites: + pip install iii-sdk + npx -y @agentmemory/agentmemory # daemon at ws://localhost:49134 + +Run: + python examples/python/quickstart.py +""" + +from iii import register_worker + + +def main() -> None: + iii = register_worker("ws://localhost:49134") + iii.connect() + + iii.trigger( + { + "function_id": "mem::remember", + "payload": { + "project": "demo", + "title": "auth-stack", + "content": "Service uses HMAC bearer tokens; refresh every 24h.", + "concepts": ["auth", "hmac", "refresh"], + }, + } + ) + + hits = iii.trigger( + { + "function_id": "mem::smart-search", + "payload": { + "project": "demo", + "query": "how do tokens refresh", + "limit": 5, + }, + } + ) + + for memory in hits.get("results", []): + print(f"[{memory.get('score', 0):.3f}] {memory.get('title')}: {memory.get('content')}") + + +if __name__ == "__main__": + main() diff --git a/integrations/filesystem-watcher/README.md b/integrations/filesystem-watcher/README.md new file mode 100644 index 0000000000000000000000000000000000000000..12b11de7a36202a77fdf3322da9d6e30c49f6087 --- /dev/null +++ b/integrations/filesystem-watcher/README.md @@ -0,0 +1,63 @@ +# @agentmemory/fs-watcher + +Filesystem connector for agentmemory. Watches one or more directories and emits an observation to the running agentmemory server every time a file changes. + +Part of the data-source-connectors effort tracked in issue #62. + +## Install + +```bash +npm install -g @agentmemory/fs-watcher +``` + +Or run without installing: + +```bash +npx @agentmemory/fs-watcher ~/work/my-repo +``` + +## Usage + +```bash +# CLI args win over env. +agentmemory-fs-watcher ~/work/my-repo ~/notes + +# Or set env once in your shell. +export AGENTMEMORY_FS_WATCH_DIRS=~/work/my-repo,~/notes +export AGENTMEMORY_URL=http://localhost:3111 +export AGENTMEMORY_SECRET=... # only if the server requires auth +agentmemory-fs-watcher +``` + +Every file change inside the watched roots becomes a `post_tool_use` observation whose `data.changeKind` is `file_change` or `file_delete`. The first 4 KB of each text file is included as `data.content` so retrieval can match by substring; larger files are truncated with `data.truncated: true`. Binary files are not read (set `AGENTMEMORY_FS_WATCH_ALLOW_BINARY=1` to override). + +Session id and project are required by the observe endpoint — set them via env, or the watcher generates a per-process `fs-watcher--` session id and uses the first root's directory name as the project. + +Requires Node.js **>=20 LTS**. Recursive `fs.watch` needs Node 19.1.0+ on Linux; Node 20 is the minimum supported LTS line. + +## Configuration + +| Variable | Default | Meaning | +|---|---|---| +| `AGENTMEMORY_FS_WATCH_DIRS` | — | Comma-separated list of directories to watch | +| `AGENTMEMORY_FS_WATCH_IGNORE` | — | Comma-separated regex patterns to ignore (applied to relative paths) | +| `AGENTMEMORY_FS_WATCH_ALLOW_BINARY` | `0` | `1` to include binary files in the preview read | +| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL | +| `AGENTMEMORY_SECRET` | — | Bearer token, required if the server has `AGENTMEMORY_SECRET` set | +| `AGENTMEMORY_PROJECT` | — | Optional project label attached to each observation | +| `AGENTMEMORY_SESSION_ID` | — | Optional session id to attribute observations to | + +## Defaults + +Ignored out of the box: `.git/`, `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `coverage/`, `.DS_Store`, `*.log`, `*.lock`. Extend with `AGENTMEMORY_FS_WATCH_IGNORE`. + +Text extensions read for preview: common source, config, and docs (`.ts/.js/.py/.go/.rs/.md/.yaml/...`). Unknown extensions are recorded as a path-only observation without content. + +Writes are debounced 500 ms per path so a stream of saves from your editor becomes a single observation. + +## Notes + +- Uses Node's built-in `fs.watch` with `{ recursive: true }`. Works natively on macOS, Linux, and Windows 10+. No native deps. +- If `fs.watch` errors on a specific root (permission, platform quirk), the watcher logs and continues on the others. +- The process must keep running. Use a process manager (`launchd`, `systemd`, `pm2`) to supervise it. +- This connector is intentionally one-way: it writes observations and never reads the agentmemory store. diff --git a/integrations/filesystem-watcher/bin.mjs b/integrations/filesystem-watcher/bin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..34ebed722331df196e348283c54db0f16f9d7a5d --- /dev/null +++ b/integrations/filesystem-watcher/bin.mjs @@ -0,0 +1,28 @@ +#!/usr/bin/env node +import { FilesystemWatcher, configFromEnv } from "./watcher.mjs"; + +const cliArgs = process.argv.slice(2); +const envCfg = configFromEnv(process.env); + +const roots = cliArgs.length > 0 ? cliArgs : envCfg.roots; +if (!roots || roots.length === 0) { + process.stderr.write( + "agentmemory-fs-watcher: no directories to watch.\n" + + "Usage: agentmemory-fs-watcher [...]\n" + + "Or set AGENTMEMORY_FS_WATCH_DIRS=path1,path2\n", + ); + process.exit(2); +} + +const watcher = new FilesystemWatcher({ ...envCfg, roots }); +watcher.start(); +process.stderr.write( + `[fs-watcher] emitting to ${envCfg.baseUrl || "http://localhost:3111"}\n`, +); + +const shutdown = () => { + watcher.stop(); + process.exit(0); +}; +process.on("SIGINT", shutdown); +process.on("SIGTERM", shutdown); diff --git a/integrations/filesystem-watcher/package.json b/integrations/filesystem-watcher/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b260ab682bebdefab4e523b047577161481c6d3c --- /dev/null +++ b/integrations/filesystem-watcher/package.json @@ -0,0 +1,22 @@ +{ + "name": "@agentmemory/fs-watcher", + "version": "0.1.0", + "description": "Filesystem connector for agentmemory — emits observations on file changes.", + "type": "module", + "bin": { + "agentmemory-fs-watcher": "./bin.mjs" + }, + "main": "./watcher.mjs", + "exports": { + ".": "./watcher.mjs" + }, + "files": ["watcher.mjs", "bin.mjs", "README.md"], + "engines": { "node": ">=20" }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory/tree/main/integrations/filesystem-watcher", + "repository": { + "type": "git", + "url": "https://github.com/rohitg00/agentmemory.git", + "directory": "integrations/filesystem-watcher" + } +} diff --git a/integrations/filesystem-watcher/watcher.mjs b/integrations/filesystem-watcher/watcher.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d68b2b8d1650967c8a8fadcb27a48ae1e3e2c95a --- /dev/null +++ b/integrations/filesystem-watcher/watcher.mjs @@ -0,0 +1,317 @@ +import { watch, promises as fsp, statSync } from "node:fs"; +import { resolve, relative, join, extname, sep, basename } from "node:path"; +import { randomBytes } from "node:crypto"; + +const TEXT_EXTENSIONS = new Set([ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", + ".py", ".rb", ".go", ".rs", ".java", ".kt", ".swift", + ".c", ".cc", ".cpp", ".h", ".hpp", + ".md", ".mdx", ".txt", ".rst", + ".json", ".yaml", ".yml", ".toml", ".ini", ".env", + ".html", ".css", ".scss", ".vue", ".svelte", + ".sh", ".bash", ".zsh", ".fish", + ".sql", ".graphql", ".proto", +]); + +const DEFAULT_IGNORE = [ + /(?:^|\/)\.git(?:\/|$)/, + /(?:^|\/)node_modules(?:\/|$)/, + /(?:^|\/)dist(?:\/|$)/, + /(?:^|\/)build(?:\/|$)/, + /(?:^|\/)\.next(?:\/|$)/, + /(?:^|\/)\.turbo(?:\/|$)/, + /(?:^|\/)coverage(?:\/|$)/, + /(?:^|\/)\.DS_Store$/, + /\.log$/, + /\.lock$/, +]; + +const MAX_PREVIEW_BYTES = 4096; +const DEBOUNCE_MS = 500; +const REDACTED = "[REDACTED]"; +const PEM_BEGIN_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/; +const PEM_END_RE = /-----END [A-Z ]*PRIVATE KEY-----/; +const JWT_RE = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g; +const JWT_MIN_LEN = 100; + +function isDotEnvPath(path) { + const name = basename(path).toLowerCase(); + return name === ".env" || name.startsWith(".env."); +} + +function isSensitiveKey(key) { + const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase(); + return [ + "apikey", + "accesstoken", + "accesskey", + "authorization", + "bearer", + "clientsecret", + "password", + "passwd", + "privatekey", + "pwd", + "secret", + "token", + ].some((needle) => normalized.includes(needle)); +} + +function redactJwtTokens(line) { + return line.replace(JWT_RE, (match) => (match.length >= JWT_MIN_LEN ? REDACTED : match)); +} + +function redactSensitiveLine(line) { + if (PEM_BEGIN_RE.test(line) || PEM_END_RE.test(line)) { + return line; + } + const assignment = line.match( + /^(\s*(?:export\s+)?["']?([A-Za-z_][A-Za-z0-9_.-]*)["']?\s*([=:])\s*)(.*)$/, + ); + if (assignment && isSensitiveKey(assignment[2])) { + const bearer = assignment[3] === ":" ? assignment[4].match(/^(Bearer\s+).+/i) : null; + return `${assignment[1]}${bearer ? bearer[1] : ""}${REDACTED}`; + } + const bearerRedacted = line.replace( + /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}\b/gi, + `$1${REDACTED}`, + ); + return redactJwtTokens(bearerRedacted); +} + +function redactPemBlocks(preview) { + const lines = preview.split("\n"); + const out = []; + let inBlock = false; + for (const line of lines) { + if (!inBlock) { + const beginMatch = line.match(PEM_BEGIN_RE); + if (!beginMatch) { + out.push(line); + continue; + } + const beginIdx = beginMatch.index; + const endMatch = line.match(PEM_END_RE); + if (endMatch && endMatch.index > beginIdx) { + const before = line.slice(0, beginIdx); + const after = line.slice(endMatch.index + endMatch[0].length); + out.push(`${before}${beginMatch[0]}${REDACTED}${endMatch[0]}${after}`); + } else { + out.push(`${line.slice(0, beginIdx)}${beginMatch[0]}`); + out.push(REDACTED); + inBlock = true; + } + } else { + const endMatch = line.match(PEM_END_RE); + if (endMatch) { + out.push(`${endMatch[0]}${line.slice(endMatch.index + endMatch[0].length)}`); + inBlock = false; + } + } + } + return out.join("\n"); +} + +function redactSensitivePreview(preview) { + return redactPemBlocks(preview).split("\n").map(redactSensitiveLine).join("\n"); +} + +export class FilesystemWatcher { + constructor(config = {}) { + this.roots = (config.roots || []).map((r) => resolve(r)); + this.baseUrl = (config.baseUrl || "http://localhost:3111").replace(/\/+$/, ""); + this.secret = config.secret; + this.project = + config.project || + (this.roots[0] ? basename(this.roots[0]) : "filesystem-watcher"); + this.sessionId = + config.sessionId || + `fs-watcher-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`; + this.ignore = [...DEFAULT_IGNORE, ...(config.ignorePatterns || [])]; + this.allowBinary = Boolean(config.allowBinary); + this.logger = config.logger || console; + this.watchers = []; + this.pendingByPath = new Map(); + } + + isIgnored(path) { + return this.ignore.some((re) => re.test(path)); + } + + isTextFile(path) { + if (this.allowBinary) return true; + const ext = extname(path).toLowerCase(); + return TEXT_EXTENSIONS.has(ext) || isDotEnvPath(path); + } + + async readPreview(path) { + try { + const fh = await fsp.open(path, "r"); + try { + const buf = Buffer.alloc(MAX_PREVIEW_BYTES); + const { bytesRead } = await fh.read(buf, 0, MAX_PREVIEW_BYTES, 0); + return buf.slice(0, bytesRead).toString("utf-8"); + } finally { + await fh.close(); + } + } catch { + return null; + } + } + + async emit(event) { + const headers = { "content-type": "application/json" }; + if (this.secret) headers.authorization = `Bearer ${this.secret}`; + try { + const res = await fetch(`${this.baseUrl}/agentmemory/observe`, { + method: "POST", + headers, + body: JSON.stringify(event), + signal: AbortSignal.timeout(5000), + }); + if (!res.ok) { + this.logger.warn?.( + `[fs-watcher] observe ${res.status}: ${await res.text().catch(() => "")}`, + ); + } + } catch (err) { + this.logger.warn?.(`[fs-watcher] observe failed: ${err?.message || err}`); + } + } + + schedule(rootDir, relPath) { + const key = join(rootDir, relPath); + const existing = this.pendingByPath.get(key); + if (existing) clearTimeout(existing.timer); + const timer = setTimeout(() => { + this.pendingByPath.delete(key); + this.flush(rootDir, relPath).catch((err) => + this.logger.warn?.(`[fs-watcher] flush failed: ${err?.message || err}`), + ); + }, DEBOUNCE_MS); + this.pendingByPath.set(key, { timer }); + } + + async flush(rootDir, relPath) { + const absPath = join(rootDir, relPath); + if (this.isIgnored(relPath)) return; + let exists = true; + let size = 0; + try { + const st = statSync(absPath); + if (!st.isFile()) return; + size = st.size; + } catch { + exists = false; + } + const changeKind = exists ? "file_change" : "file_delete"; + let preview = null; + if (exists && this.isTextFile(absPath)) { + preview = await this.readPreview(absPath); + if (preview !== null) preview = redactSensitivePreview(preview); + } + const truncated = exists && size > MAX_PREVIEW_BYTES; + const payload = { + hookType: "post_tool_use", + sessionId: this.sessionId, + project: this.project, + cwd: rootDir, + timestamp: new Date().toISOString(), + data: { + source: "filesystem-watcher", + changeKind, + files: [relPath], + content: this.formatContent(relPath, changeKind, preview, { + size, + truncated, + }), + rootDir, + absPath, + size, + truncated, + }, + }; + await this.emit(payload); + } + + formatContent(relPath, changeKind, preview, { size, truncated }) { + if (changeKind === "file_delete") return `deleted: ${relPath}`; + const head = `${relPath} (${size} bytes${truncated ? ", truncated" : ""})`; + if (preview === null) return head; + return `${head}\n\n${preview}`; + } + + start() { + if (this.roots.length === 0) { + throw new Error("filesystem-watcher: at least one root directory is required"); + } + const failures = []; + for (const root of this.roots) { + try { + const handle = watch( + root, + { recursive: true, persistent: true }, + (_eventType, filename) => { + if (!filename) return; + const rel = filename.split(sep).join("/"); + if (this.isIgnored(rel)) return; + this.schedule(root, rel); + }, + ); + handle.on("error", (err) => { + this.logger.warn?.(`[fs-watcher] watch error on ${root}: ${err?.message || err}`); + }); + this.watchers.push(handle); + this.logger.info?.(`[fs-watcher] watching ${root}`); + } catch (err) { + const msg = err?.message || String(err); + failures.push(`${root}: ${msg}`); + this.logger.error?.(`[fs-watcher] failed to watch ${root}: ${msg}`); + } + } + if (this.watchers.length === 0) { + throw new Error( + `filesystem-watcher: could not watch any of the configured roots. ` + + `If you are on Node 18 + Linux, recursive fs.watch requires Node >=19.1.0; upgrade to Node 20 LTS or newer. ` + + `Failures: ${failures.join("; ")}`, + ); + } + } + + stop() { + for (const w of this.watchers) { + try { + w.close(); + } catch {} + } + this.watchers = []; + for (const { timer } of this.pendingByPath.values()) { + clearTimeout(timer); + } + this.pendingByPath.clear(); + } +} + +// Small helper used by tests and bin.mjs to parse env. +export function configFromEnv(env = process.env) { + const roots = (env.AGENTMEMORY_FS_WATCH_DIRS || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + const extraIgnore = (env.AGENTMEMORY_FS_WATCH_IGNORE || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => new RegExp(s)); + return { + roots, + baseUrl: env.AGENTMEMORY_URL, + secret: env.AGENTMEMORY_SECRET, + project: env.AGENTMEMORY_PROJECT || null, + sessionId: env.AGENTMEMORY_SESSION_ID || null, + ignorePatterns: extraIgnore, + allowBinary: env.AGENTMEMORY_FS_WATCH_ALLOW_BINARY === "1", + }; +} + +export { relative as _relativeForTests }; diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ba06c105cffccb7f04120ad4c295b7ce842de13b --- /dev/null +++ b/integrations/hermes/README.md @@ -0,0 +1,130 @@ +

+ agentmemory +

+ +

+ Hermes Agent +  agentmemory for Hermes Agent +

+ +

+ Your Hermes agent remembers everything. No more re-explaining.
+ Persistent cross-session memory via agentmemory — 95.2% retrieval accuracy on LongMemEval-S. Cross-agent shared with Claude Code, Cursor, OpenCode, and more. +

+ +

+ 43 MCP tools + 6 lifecycle hooks + 95.2% R@5 + Self-hosted + Apache 2.0 +

+ +--- + +## Install it in 30 seconds + +**Paste this prompt into Hermes** and it does the whole setup for you: + +```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 43 memory tools: + +mcp_servers: + agentmemory: + command: npx + args: ["-y", "@agentmemory/mcp"] + +memory: + provider: agentmemory + +Verify it's working with +`curl http://localhost:3111/agentmemory/health` — it should return +{"status":"healthy"}. Open the real-time viewer at +http://localhost:3113 to watch memories being captured live. + +If I want deeper integration — pre-LLM context injection, turn-level +capture, memory-write mirroring to MEMORY.md, and system prompt block +injection — copy `integrations/hermes` from the agentmemory repo to +`~/.hermes/plugins/agentmemory` instead. That gives me the +6-hook memory provider plugin on top of the MCP server. +``` + +That's it. Hermes handles the rest. + +## Quick setup + +### Option 1: MCP server (zero code) + +Add to `~/.hermes/config.yaml`: + +```yaml +mcp_servers: + agentmemory: + command: npx + args: ["-y", "@agentmemory/mcp"] + +memory: + provider: agentmemory +``` + +This gives Hermes access to all 43 MCP tools and enables the agentmemory memory provider. Start the server separately: + +```bash +npx @agentmemory/agentmemory +``` + +### Option 2: Memory provider plugin (deeper integration) + +Copy this folder to your Hermes plugins directory: + +```bash +cp -r integrations/hermes ~/.hermes/plugins/agentmemory +``` + +Start the agentmemory server: + +```bash +npx @agentmemory/agentmemory +``` + +The plugin auto-detects the running server and hooks into the Hermes agent loop. Make sure `memory.provider` is set to `agentmemory` in `~/.hermes/config.yaml`: + +- `prefetch()` injects relevant memories before each LLM call +- `sync_turn()` captures every conversation turn in the background +- `on_session_end()` marks sessions complete for summarization +- `on_pre_compress()` re-injects context before compaction +- `on_memory_write()` mirrors MEMORY.md writes to agentmemory +- `system_prompt_block()` injects project profile at session start + +### Environment variables + +| Variable | Default | Description | +|---|---|---| +| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL | +| `AGENTMEMORY_SECRET` | (none) | Auth token for protected instances | +| `AGENTMEMORY_REQUIRE_HTTPS` | (off) | When set to `1`, refuse to send the bearer token over plaintext HTTP to a non-loopback host. Sends only when `AGENTMEMORY_URL` is `https://...` or points at `localhost`/`127.0.0.1`/`::1`. With this off, the plugin warns once on stderr but still sends. | + +The plugin reads `~/.agentmemory/.env` (or `$XDG_CONFIG_HOME/agentmemory/.env`) at import time and populates any missing values into the process environment via `os.environ.setdefault`. Anything you set in the shell takes precedence; the file is only used to fill gaps. This means `hermes memory status` reports the plugin as available even when the agentmemory service is launched by systemd or another process manager that loads `~/.agentmemory/.env` directly without exporting it to the Hermes CLI shell (#250). + +## What Hermes gets + +- 95.2% retrieval accuracy (LongMemEval-S, ICLR 2025) +- Hybrid search: BM25 + vector + knowledge graph +- Memory versioning, decay, and auto-forget +- Cross-agent: memories from Claude Code, Cursor, Gemini CLI all accessible +- Real-time viewer at http://localhost:3113 + +## How it works + +Hermes has two memory files (MEMORY.md, USER.md) and SQLite full-text search. agentmemory adds structured memory on top: + +| Hermes built-in | agentmemory adds | +|---|---| +| MEMORY.md (flat text) | Structured observations with facts, concepts, files | +| USER.md (preferences) | Project profiles with top patterns and conventions | +| SQLite FTS5 (session search) | BM25 + vector + knowledge graph (95.2% R@5) | +| Skills (self-improving) | Skill extraction from completed sessions | +| Single agent | Cross-agent memory via MCP + REST | diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2933632d0a251caa043f405a0fc061e5d62360e0 --- /dev/null +++ b/integrations/hermes/__init__.py @@ -0,0 +1,388 @@ +""" +agentmemory memory provider for Hermes Agent. + +Drop this folder into ~/.hermes/plugins/agentmemory/ +or install via: hermes plugin install agentmemory + +Requires agentmemory server running: npx @agentmemory/agentmemory +""" + +from __future__ import annotations + +import json +import os +import sys +import threading +import time +from pathlib import Path +from typing import Any, Callable +from urllib.parse import urlparse +from urllib.request import Request, urlopen +from urllib.error import URLError + +try: + from agent.memory_provider import MemoryProvider +except ImportError: + from abc import ABC, abstractmethod + + class MemoryProvider(ABC): + @property + @abstractmethod + def name(self) -> str: ... + @abstractmethod + def is_available(self) -> bool: ... + @abstractmethod + def initialize(self, session_id: str, **kwargs: Any) -> None: ... + @abstractmethod + def get_tool_schemas(self) -> list[dict]: ... + @abstractmethod + def handle_tool_call(self, name: str, args: dict) -> str: ... + def get_config_schema(self) -> list[dict]: return [] + def save_config(self, values: dict, hermes_home: str) -> None: pass + def system_prompt_block(self) -> str: return "" + def prefetch(self, query: str, **kwargs: Any) -> str: return "" + def queue_prefetch(self, query: str, **kwargs: Any) -> None: pass + def sync_turn(self, user: str, assistant: str, **kwargs: Any) -> None: pass + def on_session_end(self, messages: list, **kwargs: Any) -> None: pass + def on_pre_compress(self, messages: list, **kwargs: Any) -> None: pass + def on_memory_write(self, action: str, target: str, content: str, **kwargs: Any) -> None: pass + def shutdown(self, **kwargs: Any) -> None: pass + + +DEFAULT_BASE_URL = "http://localhost:3111" +TIMEOUT = 5 +LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} +_plaintext_bearer_warned = False + +# agentmemory's documented runtime config lives at ~/.agentmemory/.env. +# When agentmemory is launched as a systemd user service (or any other +# process manager that loads that file directly), those values never +# reach an interactive shell. `hermes memory status` then reads +# os.environ in the Hermes CLI process, finds AGENTMEMORY_URL / +# AGENTMEMORY_SECRET unset, and reports the plugin as "Missing" even +# though the service is healthy and live sessions can use it (#250). +# +# Preload the file at plugin-import time using os.environ.setdefault so +# we never override anything the user explicitly set in the shell. The +# preload is best-effort and silent on any failure (file absent, +# unreadable, malformed) — the plugin falls back to its existing default +# (http://localhost:3111) and Hermes status reflects that. +def _preload_agentmemory_dotenv() -> None: + candidates: list[Path] = [] + home = os.environ.get("HOME") + if home: + candidates.append(Path(home) / ".agentmemory" / ".env") + xdg_config = os.environ.get("XDG_CONFIG_HOME") + if xdg_config: + candidates.append(Path(xdg_config) / "agentmemory" / ".env") + for path in candidates: + try: + if not path.is_file(): + continue + for raw in path.read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + key = key.strip() + value = value.strip().strip('"').strip("'") + if key: + os.environ.setdefault(key, value) + except (OSError, UnicodeDecodeError): + continue + # Guarantee AGENTMEMORY_URL is set so `hermes memory status` never + # reports it as Missing when a user runs agentmemory at the default + # localhost:3111 (or via systemd with the URL line commented out in + # ~/.agentmemory/.env because it matches the default). #520. + os.environ.setdefault("AGENTMEMORY_URL", DEFAULT_BASE_URL) + + +_preload_agentmemory_dotenv() + + +def _validate_url(base: str) -> bool: + if not base: + return False + try: + parsed = urlparse(base) + # .port raises ValueError on a non-numeric or out-of-range port + _ = parsed.port + except ValueError: + return False + if parsed.scheme not in ("http", "https"): + return False + return bool(parsed.hostname) + + +def _uses_plaintext_bearer_auth(base: str, secret: str = "") -> bool: + if not secret: + return False + parsed = urlparse(base) + return parsed.scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS + + +def _plaintext_bearer_auth_message(base: str) -> str: + return f"agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to {base}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel." + + +def _warn_plaintext_bearer_auth(message: str) -> None: + print(message, file=sys.stderr) + + +def _check_plaintext_bearer_guard( + base: str, + secret: str = "", + warn: Callable[[str], None] | None = None, +) -> None: + global _plaintext_bearer_warned + if not _uses_plaintext_bearer_auth(base, secret): + return + message = _plaintext_bearer_auth_message(base) + if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1": + raise RuntimeError(message) + if not _plaintext_bearer_warned: + _plaintext_bearer_warned = True + (warn or _warn_plaintext_bearer_auth)(message) + + +def _reset_plaintext_bearer_guard_for_tests() -> None: + global _plaintext_bearer_warned + _plaintext_bearer_warned = False + + +def _api(base: str, path: str, body: dict | None = None, method: str = "POST", secret: str = "") -> dict | None: + if not _validate_url(base): + return None + url = f"{base}/agentmemory/{path}" + headers = {"Content-Type": "application/json"} + auth = secret or os.environ.get("AGENTMEMORY_SECRET", "") + _check_plaintext_bearer_guard(base, auth) + if auth: + headers["Authorization"] = f"Bearer {auth}" + + data = json.dumps(body).encode() if body else None + req = Request(url, data=data, headers=headers, method=method) + try: + with urlopen(req, timeout=TIMEOUT) as resp: + return json.loads(resp.read().decode()) + except (URLError, TimeoutError, json.JSONDecodeError): + return None + + +def _api_bg(base: str, path: str, body: dict | None = None) -> None: + t = threading.Thread(target=_api, args=(base, path, body), daemon=True) + t.start() + + +class AgentMemoryProvider(MemoryProvider): + + @property + def name(self) -> str: + return "agentmemory" + + def is_available(self) -> bool: + # Hermes contract: no network calls in is_available. + base = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL) + return _validate_url(base) + + def initialize(self, session_id: str, **kwargs: Any) -> None: + self._base = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL) + self._session_id = session_id + self._project = kwargs.get("cwd", os.getcwd()) + if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1": + _check_plaintext_bearer_guard(self._base, os.environ.get("AGENTMEMORY_SECRET", "")) + + _api(self._base, "session/start", { + "sessionId": session_id, + "project": self._project, + "cwd": self._project, + }) + + def get_config_schema(self) -> list[dict]: + return [ + { + "key": "url", + "description": "agentmemory server URL", + "default": DEFAULT_BASE_URL, + "env_var": "AGENTMEMORY_URL", + }, + { + "key": "secret", + "description": "agentmemory auth secret (optional)", + "secret": True, + "required": False, + "env_var": "AGENTMEMORY_SECRET", + }, + ] + + def save_config(self, values: dict, hermes_home: str) -> None: + config_path = Path(hermes_home) / "agentmemory.json" + config_path.write_text(json.dumps(values, indent=2)) + + def system_prompt_block(self) -> str: + result = _api(self._base, "context", { + "sessionId": self._session_id, + "project": self._project, + }) + if result and result.get("context"): + return result["context"] + return "" + + def prefetch(self, query: str, **kwargs: Any) -> str: + result = _api(self._base, "smart-search", { + "query": query, + "limit": 5, + }) + if not result or not result.get("results"): + return "" + + lines = [] + for r in result["results"][:5]: + obs = r.get("observation", r) + title = obs.get("title", "") + narrative = obs.get("narrative", "") + if title: + lines.append(f"- {title}: {narrative[:200]}") + return "\n".join(lines) if lines else "" + + def queue_prefetch(self, query: str, **kwargs: Any) -> None: + _api_bg(self._base, "smart-search", {"query": query, "limit": 3}) + + def get_tool_schemas(self) -> list[dict]: + return [ + { + "name": "memory_recall", + "description": "Search agentmemory for past observations by keyword", + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query"}, + "limit": {"type": "integer", "description": "Max results", "default": 10}, + }, + "required": ["query"], + }, + }, + { + "name": "memory_save", + "description": "Save an insight, decision, or pattern to long-term memory", + "parameters": { + "type": "object", + "properties": { + "content": {"type": "string", "description": "What to remember"}, + "type": { + "type": "string", + "enum": ["pattern", "preference", "architecture", "bug", "workflow", "fact"], + "description": "Memory type", + }, + }, + "required": ["content"], + }, + }, + { + "name": "memory_search", + "description": "Hybrid semantic + keyword search across all memories", + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string"}, + "limit": {"type": "integer", "default": 5}, + }, + "required": ["query"], + }, + }, + ] + + def handle_tool_call(self, name: str, args: dict) -> str: + # Hermes stores the return value as the tool result `content` in the + # session history. Anthropic-protocol providers reject non-string + # content with a 400 on the next request, so always serialize to a + # JSON string here — matches what agentmemory's main MCP server does + # in src/mcp/standalone.ts (`{ type: "text", text: JSON.stringify(...) }`). + if name == "memory_recall": + result = _api(self._base, "search", { + "query": args["query"], + "limit": args.get("limit", 10), + }) + if not result: + return json.dumps({"results": []}) + items = [] + for r in result.get("results", []): + obs = r.get("observation", r) + items.append({ + "title": obs.get("title", ""), + "type": obs.get("type", ""), + "narrative": obs.get("narrative", ""), + "importance": obs.get("importance", 0), + "timestamp": obs.get("timestamp", ""), + }) + return json.dumps({"results": items}) + + if name == "memory_save": + result = _api(self._base, "remember", { + "content": args["content"], + "type": args.get("type", "fact"), + }) + return json.dumps(result or {"success": False}) + + if name == "memory_search": + result = _api(self._base, "smart-search", { + "query": args["query"], + "limit": args.get("limit", 5), + }) + if not result: + return json.dumps({"results": []}) + items = [] + for r in result.get("results", []): + obs = r.get("observation", r) + items.append({ + "title": obs.get("title", ""), + "narrative": obs.get("narrative", "")[:300], + "score": r.get("combinedScore", r.get("score", 0)), + }) + return json.dumps({"results": items}) + + return json.dumps({"error": f"Unknown tool: {name}"}) + + def sync_turn(self, user: str, assistant: str, **kwargs: Any) -> None: + _api_bg(self._base, "observe", { + "hookType": "post_tool_use", + "sessionId": kwargs.get("session_id", self._session_id), + "project": self._project, + "cwd": self._project, + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "data": { + "tool_name": "conversation", + "tool_input": user[:500], + "tool_output": assistant[:2000], + }, + }) + + def on_session_end(self, messages: list, **kwargs: Any) -> None: + _api(self._base, "session/end", { + "sessionId": kwargs.get("session_id", self._session_id), + }) + + def on_pre_compress(self, messages: list, **kwargs: Any) -> None: + result = _api(self._base, "context", { + "sessionId": kwargs.get("session_id", self._session_id), + "project": self._project, + }) + if result and result.get("context"): + messages.insert(0, { + "role": "user", + "content": f"[agentmemory context before compaction]\n{result['context']}", + }) + + def on_memory_write(self, action: str, target: str, content: str, **kwargs: Any) -> None: + if action in ("add", "update") and content: + _api_bg(self._base, "remember", { + "content": content, + "type": "fact", + }) + + def shutdown(self, **kwargs: Any) -> None: + pass + + +def register(ctx: Any) -> None: + ctx.register_memory_provider(AgentMemoryProvider()) diff --git a/integrations/hermes/plugin.yaml b/integrations/hermes/plugin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ea5cb989ba598f0ff198425fd29dd1170c4f66e --- /dev/null +++ b/integrations/hermes/plugin.yaml @@ -0,0 +1,12 @@ +name: agentmemory +version: 0.8.0 +description: "Persistent cross-session memory for Hermes Agent via agentmemory. 95.2% retrieval accuracy on LongMemEval." +author: "Rohit Ghumare" +homepage: "https://github.com/rohitg00/agentmemory" +hooks: + - prefetch + - sync_turn + - on_session_end + - on_pre_compress + - on_memory_write + - system_prompt_block diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1fe774ae85c42ea4ed3670350fe3c3aba950c7ec --- /dev/null +++ b/integrations/openclaw/README.md @@ -0,0 +1,155 @@ +

+ agentmemory +

+ +

+ OpenClaw +  agentmemory for OpenClaw +

+ +

+ Your OpenClaw agents remember everything. No more re-explaining.
+ Persistent cross-session memory via agentmemory — 95.2% retrieval accuracy on LongMemEval-S. +

+ +

+ 43 MCP tools + OpenClaw memory plugin + 95.2% R@5 + Self-hosted + Apache 2.0 +

+ +--- + +## Install it in 30 seconds + +**Paste this prompt into OpenClaw** and it does the whole setup for you: + +```text +Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. + +For zero-code setup, add this MCP server so OpenClaw gets all 43 memory tools: + +{ + "mcpServers": { + "agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"] + } + } +} + +For deeper memory integration, copy `integrations/openclaw` from the agentmemory repo to `~/.openclaw/extensions/agentmemory`, then enable it in `~/.openclaw/openclaw.json`: + +{ + "plugins": { + "slots": { + "memory": "agentmemory" + }, + "entries": { + "agentmemory": { + "enabled": true, + "config": { + "base_url": "http://localhost:3111", + "token_budget": 2000, + "min_confidence": 0.5, + "fallback_on_error": true, + "timeout_ms": 5000 + } + } + } + } +} + +Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. +``` + +That's it. OpenClaw handles the rest. + +## Option 1: MCP server (zero code) + +Start the agentmemory server in a separate terminal: + +```bash +npx @agentmemory/agentmemory +``` + +Then add to your OpenClaw MCP config: + +```json +{ + "mcpServers": { + "agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"] + } + } +} +``` + +OpenClaw now has access to all 43 MCP tools including `memory_recall`, `memory_save`, `memory_smart_search`, `memory_timeline`, `memory_profile`, and more. + +## Option 2: OpenClaw memory plugin (deeper integration) + +Copy this folder into OpenClaw's extension directory: + +```bash +mkdir -p ~/.openclaw/extensions +cp -r integrations/openclaw ~/.openclaw/extensions/agentmemory +``` + +Then enable it in `~/.openclaw/openclaw.json`: + +```json +{ + "plugins": { + "slots": { + "memory": "agentmemory" + }, + "entries": { + "agentmemory": { + "enabled": true, + "config": { + "base_url": "http://localhost:3111", + "token_budget": 2000, + "min_confidence": 0.5, + "fallback_on_error": true, + "timeout_ms": 5000 + } + } + } + } +} +``` + +What the plugin does: + +- claims the `plugins.slots.memory = "agentmemory"` slot via `api.registerMemoryCapability({ promptBuilder })` so OpenClaw recognises it as the active memory plugin +- recalls relevant long-term memory before the agent starts (via the `before_agent_start` hook) +- captures completed conversation turns after the agent finishes (via the `agent_end` hook) +- shares the same backend with Claude Code, Codex CLI, Gemini CLI, Hermes, pi, and other agents + +### Memory runtime (current scope) + +The plugin currently registers a `promptBuilder` only — not a full `MemoryPluginRuntime` adapter. OpenClaw's `MemoryRuntimeBackendConfig` type today is `{ backend: "builtin" }` or `{ backend: "qmd" }`; both are openclaw-internal backends that don't fit agentmemory's external REST shape. The hook-driven recall + capture flow above is the working integration path. If you need OpenClaw's in-process memory-runtime APIs (e.g. `getMemorySearchManager`) backed by agentmemory, file an upstream request against `openclaw` for an `"external"` backend type and we'll wire `runtime` here once the contract supports it. + +## Troubleshooting + +**Plugin validates but does not load** — make sure the folder contains `package.json`, `openclaw.plugin.json`, and `plugin.mjs`, and that `plugins.slots.memory` is set to `agentmemory`. + +**`plugins.slots.memory = "agentmemory"` reports `unavailable`** — upgrade to v0.9.11+. Older versions of this plugin registered hooks but never called `api.registerMemoryCapability(...)`, so the memory-slot machinery did not consider the slot claimed. The current plugin registers a memory capability (prompt builder) at startup, which is the documented OpenClaw API for occupying the slot. + +**Connection refused on port 3111** — the agentmemory server is not running. Start it with `npx @agentmemory/agentmemory`. + +**No memories returned** — open `http://localhost:3113` and verify observations are being captured. + +## See also + +- [agentmemory main README](../../README.md) +- [Hermes integration](../hermes/README.md) +- [pi integration](../pi/README.md) + +## License + +Apache-2.0 (same as agentmemory) diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..9f154384d07185c9b423929405a7a6b49972cf55 --- /dev/null +++ b/integrations/openclaw/openclaw.plugin.json @@ -0,0 +1,27 @@ +{ + "id": "agentmemory", + "kind": "memory", + "name": "agentmemory", + "description": "Persistent cross-session memory for OpenClaw via agentmemory.", + "version": "0.9.4", + "configSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { "type": "boolean" }, + "base_url": { "type": "string" }, + "token_budget": { "type": "number" }, + "min_confidence": { "type": "number" }, + "fallback_on_error": { "type": "boolean" }, + "timeout_ms": { "type": "number" } + } + }, + "uiHints": { + "enabled": { "label": "Enabled" }, + "base_url": { "label": "Base URL", "help": "agentmemory REST server base URL" }, + "token_budget": { "label": "Token Budget", "help": "Approximate context budget to inject before the agent starts" }, + "min_confidence": { "label": "Min Confidence" }, + "fallback_on_error": { "label": "Fallback On Error" }, + "timeout_ms": { "label": "Timeout (ms)" } + } +} diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c671f5d5b4f351c1e7b92e31609579c07990eb76 --- /dev/null +++ b/integrations/openclaw/package.json @@ -0,0 +1,10 @@ +{ + "name": "agentmemory", + "version": "0.9.4", + "type": "module", + "openclaw": { + "extensions": [ + "./plugin.mjs" + ] + } +} diff --git a/integrations/openclaw/plugin.mjs b/integrations/openclaw/plugin.mjs new file mode 100644 index 0000000000000000000000000000000000000000..332189d7e3c1b42b3d009c38d2945ad88cc9e203 --- /dev/null +++ b/integrations/openclaw/plugin.mjs @@ -0,0 +1,217 @@ +/** + * agentmemory plugin for OpenClaw + * + * Deeper integration than raw MCP: + * - claims the plugins.slots.memory slot via api.registerMemoryCapability({ promptBuilder }) + * - recalls relevant memories before the agent starts (before_agent_start hook) + * - captures completed conversation turns after the agent finishes (agent_end hook) + * + * Requires the agentmemory server on localhost:3111. + * Start it with: npx @agentmemory/agentmemory + */ + +const DEFAULT_BASE_URL = "http://localhost:3111"; +const DEFAULT_TIMEOUT_MS = 5000; +const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]); + +const configSchema = { + type: "object", + additionalProperties: false, + properties: { + enabled: { type: "boolean" }, + base_url: { type: "string" }, + token_budget: { type: "number" }, + min_confidence: { type: "number" }, + fallback_on_error: { type: "boolean" }, + timeout_ms: { type: "number" }, + }, +}; + +function extractText(content) { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .flatMap((block) => { + if (!block || typeof block !== "object") return []; + if (block.type === "text" && typeof block.text === "string") return [block.text]; + return []; + }) + .join("\n") + .trim(); +} + +function lastAssistantText(messages) { + for (const message of [...messages].reverse()) { + if (!message || typeof message !== "object") continue; + if (message.role !== "assistant") continue; + const text = extractText(message.content); + if (text) return text; + } + return ""; +} + +function latestUserText(messages) { + for (const message of [...messages].reverse()) { + if (!message || typeof message !== "object") continue; + if (message.role !== "user") continue; + const text = extractText(message.content); + if (text) return text; + } + return ""; +} + +function formatResults(results) { + if (!Array.isArray(results) || results.length === 0) return ""; + return results + .slice(0, 5) + .map((result, index) => { + const obs = result?.observation ?? result ?? {}; + const title = (obs.title || `Memory ${index + 1}`).trim(); + const narrative = (obs.narrative || "").trim(); + const type = (obs.type || "memory").trim(); + return `- ${title} (${type})${narrative ? `: ${narrative}` : ""}`; + }) + .join("\n"); +} + +function normalizedHostname(hostname) { + return hostname.replace(/^\[|\]$/g, "").toLowerCase(); +} + +function usesPlaintextBearerAuth(baseUrl, secret) { + if (!secret) return false; + try { + const parsed = new URL(baseUrl); + return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(normalizedHostname(parsed.hostname)); + } catch { + return false; + } +} + +function plaintextBearerAuthMessage(baseUrl) { + return `agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`; +} + +export function createPlaintextBearerAuthGuard(warn, env) { + let warned = false; + return function guardPlaintextBearerAuth(baseUrl, secret) { + if (!usesPlaintextBearerAuth(baseUrl, secret)) return; + const message = plaintextBearerAuthMessage(baseUrl); + if ((env || process.env).AGENTMEMORY_REQUIRE_HTTPS === "1") throw new Error(message); + if (!warned) { + warned = true; + warn(message); + } + }; +} + +function createClient(cfg, api) { + const baseUrl = String(cfg.base_url || DEFAULT_BASE_URL).replace(/\/+$/, ""); + const timeoutMs = Number(cfg.timeout_ms || DEFAULT_TIMEOUT_MS); + const fallbackOnError = cfg.fallback_on_error !== false; + const secret = process.env.AGENTMEMORY_SECRET; + const guardPlaintextBearerAuth = createPlaintextBearerAuthGuard( + (message) => api.logger.warn?.(message), + ); + if (process.env.AGENTMEMORY_REQUIRE_HTTPS === "1") { + guardPlaintextBearerAuth(baseUrl, secret); + } + + async function postJson(path, payload) { + guardPlaintextBearerAuth(baseUrl, secret); + const headers = { "Content-Type": "application/json" }; + if (secret) headers.Authorization = `Bearer ${secret}`; + try { + const res = await fetch(`${baseUrl}${path}`, { + method: "POST", + headers, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) { + if (fallbackOnError) return null; + const body = await res.text().catch(() => ""); + throw new Error(`agentmemory ${path} failed: ${res.status} ${body}`); + } + return await res.json(); + } catch (error) { + if (!fallbackOnError) throw error; + api.logger.warn?.(`agentmemory: ${String(error)}`); + return null; + } + } + + return { postJson, baseUrl }; +} + +const plugin = { + id: "agentmemory", + name: "agentmemory", + description: "Shared cross-session memory via the local agentmemory server.", + configSchema, + register(api) { + const cfg = { + enabled: api.pluginConfig?.enabled !== false, + base_url: api.pluginConfig?.base_url || DEFAULT_BASE_URL, + token_budget: api.pluginConfig?.token_budget || 2000, + min_confidence: api.pluginConfig?.min_confidence || 0.5, + fallback_on_error: api.pluginConfig?.fallback_on_error !== false, + timeout_ms: api.pluginConfig?.timeout_ms || DEFAULT_TIMEOUT_MS, + }; + const client = createClient(cfg, api); + + if (typeof api.registerMemoryCapability === "function") { + api.registerMemoryCapability({ + // OpenClaw passes { availableTools: Set, citationsMode? }. We + // don't currently branch on tool availability, but accept the params + // object so the signature matches MemoryPromptSectionBuilder exactly. + promptBuilder: (_params) => [ + "Long-term memory provider: agentmemory (external REST service on " + + client.baseUrl + + ").", + "agentmemory recalls relevant prior observations before each turn via the before_agent_start hook and captures completed turns via agent_end.", + "Treat recalled context as background, not authoritative — prefer current workspace state and explicit user instructions when they conflict.", + ], + }); + } + + api.on("before_agent_start", async (event) => { + if (!cfg.enabled) return; + const prompt = typeof event?.prompt === "string" ? event.prompt.trim() : ""; + if (!prompt) return; + const result = await client.postJson("/agentmemory/smart-search", { + query: prompt, + limit: 5, + }); + const block = formatResults(result?.results || []); + if (!block) return; + return { + prependContext: `Relevant long-term memory from agentmemory:\n${block}`, + }; + }); + + api.on("agent_end", async (event) => { + if (!cfg.enabled || !event?.success || !Array.isArray(event.messages)) return; + const userText = latestUserText(event.messages); + const assistantText = lastAssistantText(event.messages); + if (!userText || !assistantText) return; + const sessionId = + event.sessionId || + event.sessionKey || + event.runId || + `openclaw-${Date.now()}`; + await client.postJson("/agentmemory/observe", { + hookType: "post_tool_use", + sessionId, + timestamp: new Date().toISOString(), + data: { + tool_name: "conversation", + tool_input: userText.slice(0, 1000), + tool_output: assistantText.slice(0, 4000), + }, + }); + }); + }, +}; + +export default plugin; diff --git a/integrations/openclaw/plugin.yaml b/integrations/openclaw/plugin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f991323b89121e88345b0375dbbdd37311efec3b --- /dev/null +++ b/integrations/openclaw/plugin.yaml @@ -0,0 +1,27 @@ +name: agentmemory +version: 0.8.1 +description: "Persistent cross-session memory for OpenClaw via agentmemory. 95.2% retrieval accuracy on LongMemEval-S." +author: "Rohit Ghumare" +homepage: "https://github.com/rohitg00/agentmemory" +license: Apache-2.0 + +category: memory +tags: + - memory + - persistence + - mcp + - context + +hooks: + - on_session_start + - on_pre_llm_call + - on_post_tool_use + - on_session_end + +config: + enabled: true + base_url: http://localhost:3111 + token_budget: 2000 + min_confidence: 0.5 + fallback_on_error: true + timeout_ms: 5000 diff --git a/integrations/pi/README.md b/integrations/pi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..85a2758e9fe372d0484db5ba1d744c0365850003 --- /dev/null +++ b/integrations/pi/README.md @@ -0,0 +1,77 @@ +

+ agentmemory +

+ +

+  agentmemory for pi +

+ +

+ Your pi sessions remember everything. No more re-explaining.
+ Persistent cross-session memory via agentmemory — shared with Claude Code, Codex CLI, Gemini CLI, Hermes, OpenClaw, and more. +

+ +--- + +## Quick setup + +Start the agentmemory server in a separate terminal: + +```bash +npx @agentmemory/agentmemory +``` + +Copy this folder into pi's global extensions directory: + +```bash +mkdir -p ~/.pi/agent/extensions/agentmemory +cp integrations/pi/index.ts ~/.pi/agent/extensions/agentmemory/index.ts +``` + +Then enable it in `~/.pi/agent/settings.json` if you prefer explicit loading: + +```json +{ + "extensions": ["~/.pi/agent/extensions/agentmemory"] +} +``` + +If you place it under `~/.pi/agent/extensions/agentmemory/`, pi will also auto-discover it and `/reload` can hot-reload it. + +## What it adds + +- `memory_health` — confirm the shared memory server is reachable +- `memory_search` — search prior decisions, bugs, workflows, and preferences +- `memory_save` — write durable facts back to long-term memory +- `/agentmemory-status` — check health from inside pi +- `before_agent_start` recall — injects relevant memories into the prompt +- `agent_end` capture — saves completed conversation turns back to agentmemory + +## Environment variables + +| Variable | Default | Description | +|---|---|---| +| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL | +| `AGENTMEMORY_SECRET` | (none) | Bearer token for protected instances | +| `AGENTMEMORY_REQUIRE_HTTPS` | (off) | When set to `1`, refuse to send a bearer token over plaintext HTTP to a non-loopback host. Sends the token only when `AGENTMEMORY_URL` is `https://...` or points at `localhost`/`127.0.0.1`/`::1`. With this off, the plugin warns once but still sends. | + +## Smoke test + +Run pi and ask it to use the `memory_health` tool, or call the command directly: + +```text +/agentmemory-status +``` + +You should see `agentmemory healthy` and a footer status like `🧠 agentmemory`. + +## Notes + +- This extension uses pi's extension API, not MCP, so it can hook directly into the agent lifecycle. +- One local agentmemory server can be shared across pi, pi2, Hermes, OpenClaw, Claude Code, Codex CLI, and Gemini CLI. + +## See also + +- [agentmemory main README](../../README.md) +- [Hermes integration](../hermes/README.md) +- [OpenClaw integration](../openclaw/README.md) diff --git a/integrations/pi/index.ts b/integrations/pi/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c6cfc702404a479a43e2b9d2b1822d9714436dd --- /dev/null +++ b/integrations/pi/index.ts @@ -0,0 +1,275 @@ +import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; +import { Type } from "typebox"; +import path from "node:path"; +import crypto from "node:crypto"; +import { createPlaintextBearerAuthGuard } from "./security.js"; + +type TextBlock = { type?: string; text?: string }; +type AssistantMessage = { role?: string; content?: unknown }; +type SmartSearchResult = { + title?: string; + narrative?: string; + type?: string; + combinedScore?: number; + score?: number; + observation?: { + title?: string; + narrative?: string; + type?: string; + }; +}; + +type HealthResponse = { + status?: string; + service?: string; + version?: string; + health?: { + status?: string; + notes?: string[]; + }; +}; + +const DEFAULT_URL = process.env.AGENTMEMORY_URL || "http://localhost:3111"; +const guardPlaintextBearerAuth = createPlaintextBearerAuthGuard(); +const TOOL_GUIDANCE = [ + "agentmemory is available for cross-session memory.", + "Use memory_search to recall prior decisions, preferences, bugs, and workflows.", + "Use memory_save when you discover durable facts worth remembering beyond this session.", +].join(" "); + +function normalizeBaseUrl(url: string): string { + return url.replace(/\/+$/, ""); +} + +function getText(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .flatMap((part) => { + if (!part || typeof part !== "object") return [] as string[]; + const block = part as TextBlock; + if (block.type === "text" && typeof block.text === "string") return [block.text]; + return [] as string[]; + }) + .join("\n") + .trim(); +} + +function getLastAssistantText(messages: unknown[]): string { + for (const msg of [...messages].reverse()) { + if (!msg || typeof msg !== "object") continue; + const assistant = msg as AssistantMessage; + if (assistant.role !== "assistant") continue; + const text = getText(assistant.content); + if (text) return text; + } + return ""; +} + +function formatSearchResults(results: SmartSearchResult[]): string { + if (!results.length) return "No relevant memories found."; + return results + .slice(0, 5) + .map((result, index) => { + const obs = result.observation ?? result; + const title = obs.title?.trim() || `Memory ${index + 1}`; + const narrative = obs.narrative?.trim() || ""; + const type = obs.type?.trim() || "memory"; + const score = result.combinedScore ?? result.score; + const scoreText = typeof score === "number" ? ` [score=${score.toFixed(3)}]` : ""; + return `- ${title} (${type})${scoreText}${narrative ? `: ${narrative}` : ""}`; + }) + .join("\n"); +} + +async function callAgentMemory( + pathname: string, + options?: { + method?: "GET" | "POST"; + body?: unknown; + baseUrl?: string; + }, +): Promise { + const baseUrl = normalizeBaseUrl(options?.baseUrl || process.env.AGENTMEMORY_URL || DEFAULT_URL); + const method = options?.method || "POST"; + const url = `${baseUrl}/agentmemory/${pathname.replace(/^\/+/, "")}`; + const headers: Record = {}; + const secret = process.env.AGENTMEMORY_SECRET; + guardPlaintextBearerAuth(baseUrl, secret); + if (options?.body !== undefined) headers["Content-Type"] = "application/json"; + if (secret) headers.Authorization = `Bearer ${secret}`; + + try { + const response = await fetch(url, { + method, + headers, + body: options?.body !== undefined ? JSON.stringify(options.body) : undefined, + }); + if (!response.ok) return null; + return (await response.json()) as T; + } catch { + return null; + } +} + +export default function agentmemoryExtension(pi: ExtensionAPI) { + if (process.env.AGENTMEMORY_REQUIRE_HTTPS === "1") { + guardPlaintextBearerAuth( + normalizeBaseUrl(process.env.AGENTMEMORY_URL || DEFAULT_URL), + process.env.AGENTMEMORY_SECRET, + ); + } + let sessionId = `ephemeral-${crypto.randomUUID().slice(0, 8)}`; + let currentProject = process.cwd(); + let lastPrompt = ""; + let lastHealthOk = false; + + async function getHealth() { + return await callAgentMemory("health", { method: "GET" }); + } + + async function refreshStatus(ctx: { ui: { setStatus: (key: string, text: string) => void } }) { + const health = await getHealth(); + lastHealthOk = !!health && (health.status === "healthy" || health.health?.status === "healthy"); + ctx.ui.setStatus("agentmemory", lastHealthOk ? "🧠 agentmemory" : "🧠 agentmemory off"); + } + + pi.registerCommand("agentmemory-status", { + description: "Check local agentmemory server health", + handler: async (_args, ctx) => { + const health = await getHealth(); + if (!health) { + ctx.ui.notify("agentmemory is unreachable at http://localhost:3111", "warning"); + return; + } + ctx.ui.notify( + `agentmemory ${health.status || health.health?.status || "unknown"}${health.version ? ` v${health.version}` : ""}`, + "info", + ); + }, + }); + + pi.registerTool({ + name: "memory_health", + label: "Memory Health", + description: "Check whether the local agentmemory server is reachable and healthy", + parameters: Type.Object({}), + async execute() { + const health = await getHealth(); + if (!health) { + return { + content: [{ type: "text", text: "agentmemory is unreachable at http://localhost:3111" }], + details: { ok: false }, + }; + } + return { + content: [ + { + type: "text", + text: `agentmemory status: ${health.status || health.health?.status || "unknown"}${health.version ? ` (v${health.version})` : ""}`, + }, + ], + details: health, + }; + }, + }); + + pi.registerTool({ + name: "memory_search", + label: "Memory Search", + description: "Search agentmemory for cross-session project memory, prior decisions, bugs, and user preferences", + parameters: Type.Object({ + query: Type.String({ description: "What to search for in memory" }), + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, default: 5, description: "Maximum results" })), + }), + async execute(_toolCallId, params) { + const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", { + body: { query: params.query, limit: params.limit ?? 5 }, + }); + const results = result?.results || []; + return { + content: [{ type: "text", text: formatSearchResults(results) }], + details: { query: params.query, results }, + }; + }, + }); + + pi.registerTool({ + name: "memory_save", + label: "Memory Save", + description: "Save a durable fact, convention, workflow, preference, or bug fix into agentmemory", + parameters: Type.Object({ + content: Type.String({ description: "What should be remembered" }), + type: Type.Optional( + Type.String({ + description: "Memory type", + default: "fact", + }), + ), + }), + async execute(_toolCallId, params) { + const result = await callAgentMemory>("remember", { + body: { content: params.content, type: params.type || "fact" }, + }); + if (!result) { + return { + content: [{ type: "text", text: "Failed to save memory to agentmemory." }], + details: { ok: false }, + }; + } + return { + content: [{ type: "text", text: `Saved memory (${params.type || "fact"}): ${params.content}` }], + details: result, + }; + }, + }); + + pi.on("session_start", async (_event, ctx) => { + const sessionFile = ctx.sessionManager.getSessionFile(); + sessionId = sessionFile ? path.basename(sessionFile).replace(/\.[^.]+$/, "") : `ephemeral-${crypto.randomUUID().slice(0, 8)}`; + currentProject = process.cwd(); + await refreshStatus(ctx); + }); + + pi.on("before_agent_start", async (event, ctx) => { + currentProject = event.systemPromptOptions.cwd || process.cwd(); + lastPrompt = event.prompt?.trim() || ""; + if (!lastPrompt) return; + + const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", { + body: { query: lastPrompt, limit: 5 }, + }); + const results = result?.results || []; + const recallBlock = results.length + ? [ + "Relevant long-term memory from agentmemory:", + formatSearchResults(results), + ].join("\n") + : ""; + + await refreshStatus(ctx); + return { + systemPrompt: [event.systemPrompt, TOOL_GUIDANCE, recallBlock].filter(Boolean).join("\n\n"), + }; + }); + + pi.on("agent_end", async (event) => { + if (!lastHealthOk || !lastPrompt) return; + const assistantText = getLastAssistantText(event.messages as unknown[]); + if (!assistantText) return; + void callAgentMemory("observe", { + body: { + hookType: "post_tool_use", + sessionId, + project: currentProject, + cwd: currentProject, + timestamp: new Date().toISOString(), + data: { + tool_name: "conversation", + tool_input: lastPrompt.slice(0, 500), + tool_output: assistantText.slice(0, 4000), + }, + }, + }); + }); +} diff --git a/integrations/pi/package.json b/integrations/pi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..eec302de0653a1fcc79ef25b54f09381d3b8a796 --- /dev/null +++ b/integrations/pi/package.json @@ -0,0 +1,5 @@ +{ + "name": "agentmemory-pi-extension", + "private": true, + "type": "module" +} diff --git a/integrations/pi/security.ts b/integrations/pi/security.ts new file mode 100644 index 0000000000000000000000000000000000000000..4db0e5295c621c3fbdb085014cd2e61dc7154c46 --- /dev/null +++ b/integrations/pi/security.ts @@ -0,0 +1,35 @@ +const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]); + +function normalizedHostname(hostname: string): string { + return hostname.replace(/^\[|\]$/g, "").toLowerCase(); +} + +export function usesPlaintextBearerAuth(baseUrl: string, secret?: string): boolean { + if (!secret) return false; + try { + const parsed = new URL(baseUrl); + return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(normalizedHostname(parsed.hostname)); + } catch { + return false; + } +} + +export function plaintextBearerAuthMessage(baseUrl: string): string { + return `agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`; +} + +export function createPlaintextBearerAuthGuard( + warn: (message: string) => void = (message) => console.warn(message), + env?: { AGENTMEMORY_REQUIRE_HTTPS?: string }, +): (baseUrl: string, secret?: string) => void { + let warned = false; + return (baseUrl, secret) => { + if (!usesPlaintextBearerAuth(baseUrl, secret)) return; + const message = plaintextBearerAuthMessage(baseUrl); + if ((env || process.env).AGENTMEMORY_REQUIRE_HTTPS === "1") throw new Error(message); + if (!warned) { + warned = true; + warn(message); + } + }; +} diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..cb4e6df7b858f12aba8ac5c510991935f384f853 --- /dev/null +++ b/plugin/.claude-plugin/plugin.json @@ -0,0 +1,13 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 8 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": ["./skills/"] +} diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..7c42f1309487b040a7e90b52a9b2ff16cb43e2bf --- /dev/null +++ b/plugin/.codex-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 53 MCP tools, 8 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "hooks": "./hooks/hooks.codex.json" +} diff --git a/plugin/.mcp.copilot.json b/plugin/.mcp.copilot.json new file mode 100644 index 0000000000000000000000000000000000000000..827330add9127d4d0ef6289cc77daf831f243a86 --- /dev/null +++ b/plugin/.mcp.copilot.json @@ -0,0 +1,15 @@ +{ + "mcpServers": { + "agentmemory": { + "type": "local", + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}", + "AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}" + }, + "tools": ["*"] + } + } +} diff --git a/plugin/.mcp.json b/plugin/.mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..37f7754fff846d93ce25a7aae6d926381b887415 --- /dev/null +++ b/plugin/.mcp.json @@ -0,0 +1,13 @@ +{ + "mcpServers": { + "agentmemory": { + "command": "npx", + "args": ["-y", "@agentmemory/mcp"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}", + "AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}" + } + } + } +} diff --git a/plugin/hooks/hooks.codex.json b/plugin/hooks/hooks.codex.json new file mode 100644 index 0000000000000000000000000000000000000000..d2c3a3b6dad722d34eac373ebef1a0139afb4df4 --- /dev/null +++ b/plugin/hooks/hooks.codex.json @@ -0,0 +1,67 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"", + "statusMessage": "agentmemory: loading session context" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/prompt-submit.mjs\"", + "statusMessage": "agentmemory: recalling relevant memories" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep", + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-tool-use.mjs\"" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-use.mjs\"" + } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-compact.mjs\"" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/stop.mjs\"" + } + ] + } + ] + } +} diff --git a/plugin/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.json new file mode 100644 index 0000000000000000000000000000000000000000..b7d09f8bcf0cfab75950277338bc540e403320f3 --- /dev/null +++ b/plugin/hooks/hooks.copilot.json @@ -0,0 +1,72 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-start.mjs" + } + ], + "userPromptSubmitted": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/prompt-submit.mjs" + } + ], + "preToolUse": [ + { + "type": "command", + "matcher": "edit|write|create|read|view|glob|grep", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-tool-use.mjs" + } + ], + "postToolUse": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-use.mjs" + } + ], + "postToolUseFailure": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-failure.mjs" + } + ], + "preCompact": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-compact.mjs" + } + ], + "agentStop": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/stop.mjs" + } + ], + "sessionEnd": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-end.mjs" + } + ], + "subagentStart": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-start.mjs" + } + ], + "subagentStop": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-stop.mjs" + } + ], + "notification": [ + { + "type": "command", + "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/notification.mjs" + } + ] + } +} diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..a13c99736ce53416aeae4b1cbf0f02462340f0cd --- /dev/null +++ b/plugin/hooks/hooks.json @@ -0,0 +1,125 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/prompt-submit.mjs\"" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep", + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-tool-use.mjs\"" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-use.mjs\"" + } + ] + } + ], + "PostToolUseFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-failure.mjs\"" + } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-compact.mjs\"" + } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/subagent-start.mjs\"" + } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/subagent-stop.mjs\"" + } + ] + } + ], + "Notification": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/notification.mjs\"" + } + ] + } + ], + "TaskCompleted": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/task-completed.mjs\"" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/stop.mjs\"" + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs\"" + } + ] + } + ] + } +} diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md new file mode 100644 index 0000000000000000000000000000000000000000..60f5e5bb94a749f85af0fa946673e8bee7e5dc71 --- /dev/null +++ b/plugin/opencode/README.md @@ -0,0 +1,229 @@ +

+ OpenCode +  agentmemory for OpenCode +

+ +

+ Your OpenCode agents remember everything. No more re-explaining.
+ Persistent cross-session memory via agentmemory — 95.2% retrieval accuracy on LongMemEval-S. +

+ +

+ 53 MCP tools + 22 hooks + 2 slash commands + 95.2% R@5 +

+ +--- + +## Quick start + +### 1. Start the agentmemory server + +```bash +npx @agentmemory/agentmemory +``` + +The server starts on `http://localhost:3111`. + +### 2. Configure the MCP server + +Add to `~/.config/opencode/opencode.json` or your project's `.opencode/opencode.json`: + +```json +{ + "mcp": { + "agentmemory": { + "type": "local", + "command": ["npx", "-y", "@agentmemory/mcp"], + "enabled": true + } + } +} +``` + +### 3. Install the plugin + +Add to `~/.config/opencode/opencode.json`: + +```json +{ + "plugin": ["./plugins/agentmemory-capture.ts"] +} +``` + +Copy the plugin file from this repo: + +```bash +mkdir -p ~/.config/opencode/plugins +cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/ +``` + +### 4. Add the slash commands + +Copy the commands into your project or global `.opencode/commands/` directory: + +```bash +mkdir -p ~/.config/opencode/commands +cp plugin/opencode/commands/recall.md ~/.config/opencode/commands/ +cp plugin/opencode/commands/remember.md ~/.config/opencode/commands/ +``` + +Restart OpenCode or open a new session. The plugin auto-captures everything. + +## What gets captured + +### Session lifecycle + +| Event | Hook | agentmemory API | +|---|---|---| +| Session start | `session.created` | POST /session/start | +| Idle → summarize | `session.idle` + `session.status` (idle) | POST /summarize | +| Status transitions | `session.status` (idle/busy/retry) | POST /observe | +| Compaction | `session.compacted` | POST /summarize + POST /observe | +| Metadata updates | `session.updated` | POST /observe | +| Code change tracking | `session.diff` | POST /observe | +| Session delete | `session.deleted` | POST /session/end | +| Session error | `session.error` | POST /observe | + +### Messages & prompts + +| Event | Hook | agentmemory API | +|---|---|---| +| User prompt (rich) | `chat.message` | POST /observe | +| User prompt metadata | `message.updated` (user) | POST /observe | +| Assistant response | `message.updated` (assistant) | POST /observe | +| Message removed (undo) | `message.removed` | POST /observe | + +### Parts & steps + +| Event | Hook | agentmemory API | +|---|---|---| +| Subagent start | `message.part.updated` (subtask) | POST /observe | +| Tool completed | `message.part.updated` (tool completed) | POST /observe | +| Tool error | `message.part.updated` (tool error) | POST /observe | +| Step finish (cost/tokens) | `message.part.updated` (step-finish) | POST /observe | +| Reasoning trace | `message.part.updated` (reasoning) | POST /observe | +| Patch applied | `message.part.updated` (patch) | POST /observe | +| Auto/manual compaction | `message.part.updated` (compaction) | POST /observe | +| Agent selection | `message.part.updated` (agent) | POST /observe | +| API retry | `message.part.updated` (retry) | POST /observe | + +### File enrichment pipeline + +| Event | Hook | agentmemory API | +|---|---|---| +| File tool params | `tool.execute.before` → stash paths | — | +| File edited | `file.edited` → stash paths | — | +| File part attached | `message.part.updated` (file) → stash paths | — | +| Enrichment inject | `experimental.chat.system.transform` | POST /enrich → `output.system[]` | +| Memory context inject | `experimental.chat.system.transform` | POST /context → `output.system[]` | + +### Permissions + +| Event | Hook | agentmemory API | +|---|---|---| +| Permission prompt | `permission.updated` | POST /observe | +| Permission reply | `permission.replied` | POST /observe | + +### Tasks & commands + +| Event | Hook | agentmemory API | +|---|---|---| +| Task tracking (w/ priority) | `todo.updated` | POST /observe | +| Command executed | `command.executed` | POST /observe | + +### Model & config + +| Event | Hook | agentmemory API | +|---|---|---| +| LLM parameters | `chat.params` | POST /observe | +| Config loaded | `config` | POST /observe | +| Compaction (WIP) | `experimental.session.compacting` | POST /context → `output.context[]` | + +### File enrichment + memory injection (two-layer pipeline) + +`experimental.chat.system.transform` fires before every LLM call and injects two layers of context: + +1. **Memory context** (once per session): calls `/agentmemory/context` and injects project profile, recent session summaries, and important past observations into the system prompt. This is the OpenCode equivalent of Claude's MEMORY.md bridge — instead of syncing to a markdown file, context is injected directly into the system prompt. + +2. **File enrichment** (every turn with stashed files): calls `/agentmemory/enrich` with files stashed by `tool.execute.before`, `file.edited`, and `message.part.updated` (file parts). File-specific context (past observations, related bugs, semantic search) is injected into the system prompt. + +```text +System prompt = [OpenCode instructions] + [memory context] + [file enrichment] + [user message] + ^ ^ + first turn only every file-touching turn +``` + +**Differences from Claude's PreToolUse:** + +| Dimension | Claude (PreToolUse) | OpenCode (two-hop pipeline) | +|---|---|---| +| Injection mechanism | stdout → context window | `output.system[]` → system prompt | +| Timing | Same turn (parallel with tool) | Next turn (before next LLM call) | +| File set | Per-tool (immediate) | Batched (all files since last enrichment) | +| Coverage | Edit/Write/Read/Glob/Grep only | Edit/Write/Read/Glob/Grep only | +| What gets injected | `` + bug memories | Identical `/enrich` response | + +## MEMORY.md vs AGENTS.md: how context flows + +Claude Code and OpenCode take fundamentally different approaches to injecting memory context into the agent's system prompt. + +### Claude Code: file-backed bridge (two-hop) + +``` +agentmemory ──write──▶ MEMORY.md ──read──▶ Claude system prompt +``` + +- The `claude-bridge/sync` endpoint serializes agentmemory observations into a `MEMORY.md` file in the project root +- Claude Code reads `MEMORY.md` on session start and prepends it to the system prompt +- **Sync is periodic** — sessions only get fresh context when the bridge last ran (session end, pre-compact) +- **Coupling**: memory data lives in a git-trackable file, visible to CI, team members, and other tools + +### OpenCode: direct injection (one-hop) + +``` +agentmemory ──push──▶ OpenCode system prompt +``` + +- `experimental.chat.system.transform` calls `/context` at runtime and pushes the response directly into `output.system[]` +- **Always current** — context is fetched at session start (once) and before file-touching turns (per-batch) +- **No file intermediary** — no stale copies, no merge conflicts, no disk I/O +- `AGENTS.md` is a static instruction file for project conventions, coding standards, and tool guidance — agentmemory does not read or write it + +### Tradeoffs + +| Dimension | Claude (MEMORY.md bridge) | OpenCode (direct injection) | +|---|---|---| +| Freshness | Stale between syncs | Always current (fetched at call time) | +| Visibility | Human-readable file in repo | In-memory injection only | +| Simplicity | Two moving parts (bridge + file) | One step (API → system prompt) | +| Team sharing | File is git-trackable, CI-friendly | Memory shared via agentmemory server API | +| Integration | Any tool can read MEMORY.md | Requires OpenCode plugin SDK | + +### Why OpenCode goes direct + +agentmemory already persists everything in SQLite (`data/state_store.db`). Adding an intermediate MEMORY.md file would duplicate data, introduce sync lag, and require the model to re-parse structured context from markdown. Direct injection delivers the same data with lower latency and zero staleness — the agent always sees what agentmemory knows right now. + +## Slash commands + +- `/recall ` — Search past observations and lessons +- `/remember ` — Save an insight to long-term memory + +## Session instruction injection + +Agentmemory usage instructions are injected into the system prompt on the first turn of every session via `experimental.chat.system.transform` (alongside memory context from `/context`). This is functionally equivalent to Claude Code's skills mechanism — the agent learns which `agentmemory_memory_*` tools to use and when, without needing separate skill invocations. + +## What's not covered (vs Claude Code plugin) + +| Claude feature | Reason | +|---|---| +| SubagentStop | OpenCode's `SubtaskPart` type has no completion/result fields; subtask lifecycle ends are not exposed as distinct events in the OpenCode SDK | +| TaskCompleted | No team/teammate concept in OpenCode; `todo.updated` captures task state changes as a partial equivalent | +| Stop | `session.compacted` event handler exists; `experimental.session.compacting` injection hook defined in SDK but Go binary (v1.14.41) doesn't wire it — will auto-activate when upstream implements it | +| Skills (remember/recall/forget/session-history) | Covered by injected system instructions via `experimental.chat.system.transform` — agent receives usage guidance on first turn | +| Consolidation pipeline (crystals/auto + consolidate-pipeline) | Now called on `session.deleted` — mirrors Claude's `CONSOLIDATION_ENABLED=true` behavior | +| Claude MEMORY.md bridge | OpenCode-specific; OpenCode uses its own AGENTS.md mechanism, not Claude's MEMORY.md | + +All other Claude Code hooks have direct or pipeline equivalents in this plugin. 12 of 12 Claude hook types covered. diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts new file mode 100644 index 0000000000000000000000000000000000000000..056d53d38d2b3e9fd78b2af0492e31d80addf299 --- /dev/null +++ b/plugin/opencode/agentmemory-capture.ts @@ -0,0 +1,687 @@ +import type { Plugin } from "@opencode-ai/plugin"; + +const API = process.env.AGENTMEMORY_URL || "http://localhost:3111"; +const FILE_TOOLS = new Set(["Read", "Write", "Edit", "Glob", "Grep"]); +const FILE_KEYS = ["filePath", "file_path", "path", "file", "pattern"]; +const MAX_STASHED_FILES = 20; + +const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1"; +const SECRET = process.env.AGENTMEMORY_SECRET || ""; + +function authHeaders(): Record { + const headers: Record = { "Content-Type": "application/json" }; + if (SECRET) headers["Authorization"] = `Bearer ${SECRET}`; + return headers; +} + +async function post(path: string, body: Record, timeoutMs = 5000): Promise { + try { + await fetch(`${API}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + if (DEBUG) console.error(`[agentmemory] POST ${path} failed:`, (e as Error).message); + } +} + +async function postJson(path: string, body: Record): Promise { + try { + const res = await fetch(`${API}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(5000), + }); + return res.ok ? await res.json() : null; + } catch (e) { + if (DEBUG) console.error(`[agentmemory] POST ${path} failed:`, (e as Error).message); + return null; + } +} + +async function observe( + sessionId: string, + hookType: string, + data: Record, +): Promise { + await post("/observe", { + hookType, + sessionId, + project: projectPath, + cwd: projectPath, + timestamp: new Date().toISOString(), + data, + }); +} + +let activeSessionId: string | null = null; +let pendingConfig: Record | null = null; +let projectPath: string | null = null; +const stashedFiles = new Map>(); +const seenSubtaskIds = new Map>(); +const seenToolCallIds = new Map>(); +const contextInjectedSessions = new Set(); +// cache the context returned by POST /session/start so the chat +// system-transform hook can inject it without a second /context fetch. +// Auto-injection now happens at session.created (immediately) AND at +// the first prompt_submit (fallback for older OpenCode builds that +// don't implement experimental.chat.system.transform). +const startContextCache = new Map(); + +function stashFor(sid: string): Set { + let s = stashedFiles.get(sid); + if (!s) { s = new Set(); stashedFiles.set(sid, s); } + return s; +} + +function subtaskSetFor(sid: string): Set { + let s = seenSubtaskIds.get(sid); + if (!s) { s = new Set(); seenSubtaskIds.set(sid, s); } + return s; +} + +function toolCallSetFor(sid: string): Set { + let s = seenToolCallIds.get(sid); + if (!s) { s = new Set(); seenToolCallIds.set(sid, s); } + return s; +} + +function pruneSessionMaps(sid: string): void { + stashedFiles.delete(sid); + seenSubtaskIds.delete(sid); + seenToolCallIds.delete(sid); +} + +function safeSlice(v: unknown, max: number): string { + if (typeof v === "string") return v.slice(0, max); + if (v == null) return ""; + try { return JSON.stringify(v).slice(0, max); } catch { return ""; } +} + +const AGENTMEMORY_INSTRUCTIONS = ` +You have access to agentmemory for persistent cross-session memory. Use these tools proactively. + +CORE TOOLS: + +memory_save — Save an insight, decision, or fact to long-term memory. + Required: content (text), concepts (2-5 comma-separated keywords), type (pattern/preference/architecture/bug/workflow/fact) + Optional: files (comma-separated paths) + Use when: user says "remember this", after discovering a bug, after making an architectural decision, after learning a project convention. + +memory_recall — Search past observations by keywords. + Use when: user says "recall", "what did we do", "do you remember", or needs context from past sessions. + +memory_smart_search — Hybrid semantic+keyword search with progressive disclosure. + Use when: you need the most relevant past context, fuzzy/conceptual searches, or recall doesn't find what you need. + +memory_sessions — List recent sessions with status and observation counts. + Use when: user asks about session/past history, "what did we work on". + +memory_file_history — Get past observations about specific files (across all sessions). + Use when: you're about to edit a file and want to know its history, common pitfalls, or past edits. + +memory_lesson_save — Save a lesson learned (what worked, what to avoid). + Use when: you discover a pattern that could help future sessions avoid mistakes. + +memory_lesson_recall — Search lessons by query. Returns lessons sorted by confidence. + Use when: before making a decision, check if past lessons apply. + +memory_governance_delete — Delete specific memories. Requires explicit user confirmation. + Use when: user says "forget this", "delete that memory". + +memory_patterns — Detect recurring patterns across sessions. + Use when: you want to understand project-level trends over time. + +memory_consolidate — Run the 4-tier memory consolidation pipeline. + Use when: you want to compress and organize accumulated session observations. + +All memory tools start with \`agentmemory_memory_\`. Use the exact names as they appear in your tool list. Tool results are JSON. Always check what was returned before presenting to the user. +`; + +function extractFilePaths(args: Record): string[] { + const files: string[] = []; + for (const key of FILE_KEYS) { + const val = args[key]; + if (typeof val === "string" && val.length > 0) { + files.push(val); + } + } + return files; +} + +function extractErrorMessage(err: unknown): string { + if (typeof err === "string") return err; + if (err && typeof err === "object") { + const e = err as Record; + if (typeof e.message === "string") return e.message; + if (e.data && typeof e.data === "object") { + const d = e.data as Record; + if (typeof d.message === "string") return d.message; + } + if (typeof e.name === "string") return e.name; + try { return JSON.stringify(err); } catch { return ""; } + } + return String(err ?? ""); +} + +export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { + projectPath = ctx.worktree || ctx.project?.id || process.cwd(); + + return { + event: async ({ event }) => { + const type = event.type; + const props = (event as any).properties || {}; + + // ── session.created ── + if (type === "session.created") { + const info = props.info as Record | undefined; + activeSessionId = (info?.id as string) || props.sessionID || null; + if (!activeSessionId) return; + stashedFiles.set(activeSessionId, new Set()); + seenSubtaskIds.delete(activeSessionId); + seenToolCallIds.delete(activeSessionId); + contextInjectedSessions.delete(activeSessionId); + // Snapshot the session id locally — `activeSessionId` is mutable + // and another `session.created` event during the await could + // rebind it, causing context to be cached against the wrong key. + const sessionId = activeSessionId; + const startResult = await postJson("/session/start", { + sessionId, + title: info?.title ?? null, + parentID: info?.parentID ?? null, + version: info?.version ?? null, + project: projectPath, + cwd: projectPath, + }); + // cache the context returned at session/start so the + // chat.system.transform hook injects it without a second fetch. + const startCtx = (startResult as any)?.context; + if (typeof startCtx === "string" && startCtx.length > 0) { + startContextCache.set(sessionId, startCtx); + } + if (pendingConfig) { + await observe(sessionId, "config_loaded", pendingConfig); + pendingConfig = null; + } + } + + // ── session.idle ── (summarize handled in session.status idle branch) + + // ── session.status ── + if (type === "session.status") { + const status = props.status as Record | undefined; + const sid = props.sessionID || activeSessionId; + if (!sid || !status) return; + if (status.type === "idle") { + await post("/summarize", { sessionId: sid }); + } + await observe(sid, "session_status", { + status_type: status.type, + attempt: status.attempt ?? null, + message: safeSlice(status.message, 2000), + }); + } + + // ── session.compacted ── + if (type === "session.compacted") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await post("/summarize", { sessionId: sid }); + await observe(sid, "session_compacted", {}); + } + } + + // ── session.updated ── + if (type === "session.updated") { + const info = props.info as Record | undefined; + const sid = (info?.id as string) || props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "session_updated", { + title: info?.title ?? null, + parentID: info?.parentID ?? null, + additions: (info?.summary as any)?.additions ?? null, + deletions: (info?.summary as any)?.deletions ?? null, + files: (info?.summary as any)?.files ?? null, + }); + } + + // ── session.diff ── + if (type === "session.diff") { + const sid = props.sessionID || activeSessionId; + if (!sid || !Array.isArray(props.diff)) return; + const diffs = props.diff as Array>; + await observe(sid, "session_diff", { + files: diffs.map(d => d.file), + additions: diffs.reduce((s, d) => s + ((d.additions as number) || 0), 0), + deletions: diffs.reduce((s, d) => s + ((d.deletions as number) || 0), 0), + diffs: diffs.slice(0, 50), + }); + } + + // ── session.deleted ── + if (type === "session.deleted") { + const sid = props.info?.id || props.sessionID || activeSessionId; + if (!sid) { + if (DEBUG) console.error("[agentmemory] session.deleted with no session ID"); + return; + } + await post("/session/end", { sessionId: sid }); + post("/crystals/auto", { olderThanDays: 7 }, 30000); + post("/consolidate-pipeline", { tier: "all", force: true }, 30000); + if (sid === activeSessionId) activeSessionId = null; + stashedFiles.delete(sid); + startContextCache.delete(sid); + seenSubtaskIds.delete(sid); + seenToolCallIds.delete(sid); + contextInjectedSessions.delete(sid); + } + + // ── session.error ── + if (type === "session.error") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "post_tool_failure", { + tool_name: "session.error", + tool_input: "", + tool_output: safeSlice(props.error, 8000), + }); + } + } + + // ── message.updated ── + if (type === "message.updated") { + const info = props.info as Record | undefined; + if (!info) return; + + if (info.role === "assistant") { + const sid = props.sessionID || (info.sessionID as string) || activeSessionId; + if (!sid) return; + const tokens = info.tokens as Record | undefined; + const error = info.error ? extractErrorMessage(info.error) : null; + await observe(sid, "assistant_message", { + messageID: info.id, + parentID: info.parentID, + modelID: info.modelID, + providerID: info.providerID, + mode: info.mode, + cost: info.cost ?? 0, + tokens: { + input: tokens?.input ?? 0, + output: tokens?.output ?? 0, + reasoning: tokens?.reasoning ?? 0, + cache_read: (tokens?.cache as any)?.read ?? 0, + cache_write: (tokens?.cache as any)?.write ?? 0, + }, + finish: info.finish ?? null, + error, + duration_ms: (info.time && typeof (info.time as any).completed === "number") + ? (info.time as any).completed - ((info.time as any).created || 0) + : null, + }); + } + } + + // ── message.removed ── + if (type === "message.removed") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "message_removed", { + messageID: props.messageID, + }); + } + } + + // ── message.part.updated ── + if (type === "message.part.updated") { + const part = props.part as Record | undefined; + if (!part) return; + const sid = (part.sessionID as string) || props.sessionID || activeSessionId; + if (!sid) return; + + if (part.type === "subtask") { + const subtaskId = part.id as string; + if (!subtaskId) return; + const subtaskSet = subtaskSetFor(sid); + if (subtaskSet.has(subtaskId)) return; + subtaskSet.add(subtaskId); + await observe(sid, "subagent_start", { + subtask_id: part.id, + agent: part.agent, + prompt: safeSlice(part.prompt, 4000), + description: safeSlice(part.description, 2000), + }); + return; + } + + if (part.type === "tool") { + const state = part.state as Record | undefined; + if (!state) return; + const callId = part.callID as string; + if (!callId) return; + const toolName = part.tool as string; + + if (state.status === "completed") { + const callSet = toolCallSetFor(sid); + if (callSet.has(callId)) return; + callSet.add(callId); + const st = state as Record; + const rawTime = (st.time as any) || {}; + const startTime = typeof rawTime.start === "number" ? rawTime.start : null; + const endTime = typeof rawTime.end === "number" ? rawTime.end : null; + await observe(sid, "post_tool_use", { + tool_name: toolName, + call_id: callId, + tool_input: safeSlice(st.input, 4000), + tool_output: safeSlice(st.output, 8000), + title: st.title ?? null, + metadata: st.metadata || {}, + duration_ms: (startTime != null && endTime != null) ? endTime - startTime : null, + attachments: Array.isArray(st.attachments) + ? (st.attachments as Array>).map(a => a.filename || a.url) + : [], + }); + } else if (state.status === "error") { + const callSet = toolCallSetFor(sid); + if (callSet.has(callId)) return; + callSet.add(callId); + const st = state as Record; + const rawTime = (st.time as any) || {}; + const startTime = typeof rawTime.start === "number" ? rawTime.start : null; + const endTime = typeof rawTime.end === "number" ? rawTime.end : null; + await observe(sid, "post_tool_failure", { + tool_name: toolName, + call_id: callId, + tool_input: safeSlice(st.input, 4000), + tool_output: safeSlice(st.error, 8000), + duration_ms: (startTime != null && endTime != null) ? endTime - startTime : null, + }); + } + return; + } + + if (part.type === "step-finish") { + await observe(sid, "step_finish", { + messageID: part.messageID, + reason: part.reason ?? null, + cost: (part as any).cost ?? 0, + input_tokens: ((part as any).tokens?.input as number) ?? 0, + output_tokens: ((part as any).tokens?.output as number) ?? 0, + reasoning_tokens: ((part as any).tokens?.reasoning as number) ?? 0, + }); + return; + } + + if (part.type === "reasoning") { + await observe(sid, "reasoning", { + messageID: part.messageID, + text: safeSlice((part as any).text, 4000), + }); + return; + } + + if (part.type === "file") { + const filename = (part as any).filename || (part as any).url || null; + if (filename) stashFor(sid).add(filename); + return; + } + + if (part.type === "patch") { + await observe(sid, "patch_applied", { + messageID: part.messageID, + hash: (part as any).hash, + files: (part as any).files || [], + }); + return; + } + + if (part.type === "compaction") { + await observe(sid, "compaction_event", { + messageID: part.messageID, + auto: (part as any).auto ?? false, + }); + return; + } + + if (part.type === "agent") { + await observe(sid, "agent_selected", { + messageID: part.messageID, + name: (part as any).name, + }); + return; + } + + if (part.type === "retry") { + await observe(sid, "retry_attempt", { + messageID: part.messageID, + attempt: (part as any).attempt, + error: safeSlice((part as any).error, 2000), + }); + return; + } + } + + // ── file.edited ── + if (type === "file.edited") { + const sid = props.sessionID || activeSessionId; + if (sid && typeof props.file === "string" && props.file.length > 0) { + const stash = stashFor(sid); + stash.add(props.file); + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const f of keep) stash.add(f); + } + } + } + + // ── permission.updated ── + if (type === "permission.updated") { + const sid = props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "notification", { + notification_type: "permission_prompt", + permission: props.type || "unknown", + pattern: Array.isArray(props.pattern) + ? props.pattern.join(", ") + : (props.pattern || ""), + tool_call_id: props.callID || null, + title: props.title || props.type || "", + metadata: props.metadata || {}, + }); + } + + // ── permission.replied ── + if (type === "permission.replied") { + const sid = props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "permission_replied", { + permission_id: props.permissionID || props.requestID || "", + response: props.response || props.reply || "", + }); + } + + // ── todo.updated ── + if (type === "todo.updated") { + const sid = props.sessionID || activeSessionId; + const todos = Array.isArray(props.todos) ? props.todos.slice(0, 100) : []; + if (!sid || todos.length === 0) return; + const completed = todos.filter((t: any) => t.status === "completed"); + const active = todos.filter((t: any) => t.status !== "completed"); + await observe(sid, "task_completed", { + completed: completed.map((t: any) => ({ content: t.content, priority: t.priority })), + in_progress: active.map((t: any) => ({ content: t.content, priority: t.priority })), + total: todos.length, + }); + } + + // ── command.executed ── + if (type === "command.executed") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "command_executed", { + name: props.name, + arguments: props.arguments || "", + }); + } + } + }, + + // ── chat.message ── + "chat.message": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + const parts = output.parts || []; + const files = parts + .filter((p: any) => p.type === "file") + .map((p: any) => p.filename || p.url) + .filter(Boolean); + for (const f of files) { + const stash = stashFor(sid); + stash.add(f); + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const k of keep) stash.add(k); + } + } + + const textParts = parts.filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored); + const userText = textParts.map((p: any) => p.text || "").join("\n"); + + await observe(sid, "prompt_submit", { + agent: input.agent ?? null, + model: input.model ?? null, + variant: input.variant ?? null, + prompt: userText.slice(0, 8000), + files: files.slice(0, 20), + parts_summary: parts.map((p: any) => p.type).filter(Boolean), + }); + }, + + // ── chat.params ── + "chat.params": async (input, output) => { + if (!input.model || !output) return; + const sid = input.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "llm_params", { + agent: input.agent, + model: `${input.model.providerID}/${input.model.id}`, + provider_url: input.model.api?.url ?? null, + temperature: output.temperature, + topP: output.topP, + max_output_tokens: input.model.limit?.output ?? null, + context_limit: input.model.limit?.context ?? null, + cost_1k_input: input.model.cost?.input ?? 0, + cost_1k_output: input.model.cost?.output ?? 0, + }); + }, + + // ── tool.execute.before ── + "tool.execute.before": async (input, output) => { + if (!FILE_TOOLS.has(input.tool)) return; + const sid = input.sessionID || activeSessionId; + if (!sid) return; + const args = output.args as Record | undefined; + if (!args) return; + const stash = stashFor(sid); + for (const fp of extractFilePaths(args)) { + stash.add(fp); + } + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const f of keep) stash.add(f); + } + }, + + // ── experimental.chat.system.transform ── + "experimental.chat.system.transform": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + + if (!contextInjectedSessions.has(sid)) { + if (!Array.isArray(output.system)) return; + output.system.push(AGENTMEMORY_INSTRUCTIONS); + // prefer the context already fetched at session.created; + // fall back to a fresh /context call if the cache missed (e.g. + // session resumed across plugin reloads). + let ctx = startContextCache.get(sid); + if (typeof ctx !== "string" || ctx.length === 0) { + const result = await postJson("/context", { + sessionId: sid, + project: projectPath, + }); + ctx = (result as any)?.context; + } else { + startContextCache.delete(sid); + } + if (typeof ctx === "string" && ctx.length > 0) { + output.system.push(ctx); + } + contextInjectedSessions.add(sid); + } + + const stash = stashFor(sid); + if (stash.size === 0) return; + const files = [...stash].slice(0, 10); + + const enrichResult = await postJson("/enrich", { + sessionId: sid, + files, + toolName: "enrich_inject", + }); + + const enrichCtx = (enrichResult as any)?.context; + if (typeof enrichCtx === "string" && enrichCtx.length > 0) { + if (Array.isArray(output.system)) { + output.system.push(enrichCtx); + } + for (const f of files) stash.delete(f); + } + }, + + // ── experimental.session.compacting (WIP) ── + "experimental.session.compacting": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + + const result = await postJson("/context", { + sessionId: sid, + project: projectPath, + }); + const ctx = (result as any)?.context; + if (typeof ctx === "string" && ctx.length > 0) { + if (Array.isArray(output.context)) { + output.context.push(ctx); + } + } + }, + + // ── config ── + config: async (input) => { + const payload: Record = { + theme: input.theme ?? null, + model: input.model ?? null, + autoupdate: input.autoupdate ?? null, + agents: typeof input.agent === "object" && input.agent !== null && !Array.isArray(input.agent) + ? Object.keys(input.agent as Record) + : Array.isArray(input.agent) ? input.agent : [], + mcp_servers: typeof input.mcp === "object" && input.mcp !== null && !Array.isArray(input.mcp) + ? Object.keys(input.mcp as Record) + : Array.isArray(input.mcp) ? input.mcp : [], + providers: typeof input.provider === "object" && input.provider !== null && !Array.isArray(input.provider) + ? Object.keys(input.provider as Record) + : Array.isArray(input.provider) ? input.provider : [], + permission: input.permission ?? null, + }; + if (activeSessionId) { + await observe(activeSessionId, "config_loaded", payload); + } else { + pendingConfig = payload; + } + }, + }; +}; diff --git a/plugin/opencode/commands/recall.md b/plugin/opencode/commands/recall.md new file mode 100644 index 0000000000000000000000000000000000000000..de01f0884ca35641d852159be189288861e5238e --- /dev/null +++ b/plugin/opencode/commands/recall.md @@ -0,0 +1,19 @@ +Search past session observations and lessons for relevant context. Wrap the `memory_smart_search` and `memory_lesson_recall` MCP tools. + +## Usage + +``` +/recall [query] +``` + +## Instructions + +1. Call `memory_smart_search` with the query and `limit: 10` (hybrid BM25 + vector + graph search). +2. Call `memory_lesson_recall` with the same query and `limit: 5` (lesson search). +3. Combine results and present to the user: + - Group by session + - Show type, title, and narrative for each observation + - Highlight high-importance (>= 7) observations + - Show lessons separately with confidence scores +4. If no results, suggest 2-3 alternative search terms. +5. **Never hallucinate results.** Only present what the MCP tools actually return. diff --git a/plugin/opencode/commands/remember.md b/plugin/opencode/commands/remember.md new file mode 100644 index 0000000000000000000000000000000000000000..196fc0043aa2a215aee7c7c8592aebd83fefb18f --- /dev/null +++ b/plugin/opencode/commands/remember.md @@ -0,0 +1,19 @@ +Explicitly save an insight, decision, or learning to agentmemory for future sessions. Wraps the `memory_save` MCP tool. + +## Usage + +``` +/remember [what to remember] +``` + +## Instructions + +1. Analyze what needs to be remembered — extract the core insight, decision, or fact. +2. Extract 2-5 searchable concepts (lowercased keyword phrases). Prefer specific terms ("jwt-refresh-rotation" over "auth"). +3. Extract relevant file paths the memory references. +4. Call `memory_save` with: + - `content` — full text to remember (preserve user's phrasing) + - `concepts` — extracted concept list + - `files` — extracted file list (empty array if none) + - `type` — choose from: pattern, preference, architecture, bug, workflow, fact +5. Confirm the save and show the concepts tagged so the user knows retrieval terms. diff --git a/plugin/opencode/plugin.json b/plugin/opencode/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..1472752e934a79c8f77b3d601f973dfdd94e0bfe --- /dev/null +++ b/plugin/opencode/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "agentmemory-capture", + "version": "0.9.20", + "description": "OpenCode plugin for agentmemory — full Claude Code hook parity: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool lifecycle (ToolPart states with timing), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline, permissions, task tracking (w/ priority), commands, config & model tracking. 22 hooks, 2 slash commands.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory" +} diff --git a/plugin/plugin.json b/plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..9d0751a7abcc75fc433ad968087cff0385a96d63 --- /dev/null +++ b/plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 15 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": "skills/", + "mcpServers": ".mcp.copilot.json", + "hooks": "hooks/hooks.copilot.json" +} diff --git a/plugin/scripts/diagnostics.mjs b/plugin/scripts/diagnostics.mjs new file mode 100644 index 0000000000000000000000000000000000000000..96d6dada8445c0ca755a4ee926fded0563cc6628 --- /dev/null +++ b/plugin/scripts/diagnostics.mjs @@ -0,0 +1,551 @@ +//#region src/state/schema.ts +const KV = { + sessions: "mem:sessions", + observations: (sessionId) => `mem:obs:${sessionId}`, + memories: "mem:memories", + summaries: "mem:summaries", + config: "mem:config", + metrics: "mem:metrics", + health: "mem:health", + embeddings: (obsId) => `mem:emb:${obsId}`, + bm25Index: "mem:index:bm25", + relations: "mem:relations", + profiles: "mem:profiles", + claudeBridge: "mem:claude-bridge", + graphNodes: "mem:graph:nodes", + graphEdges: "mem:graph:edges", + semantic: "mem:semantic", + procedural: "mem:procedural", + teamShared: (teamId) => `mem:team:${teamId}:shared`, + teamUsers: (teamId, userId) => `mem:team:${teamId}:users:${userId}`, + teamProfile: (teamId) => `mem:team:${teamId}:profile`, + audit: "mem:audit", + actions: "mem:actions", + actionEdges: "mem:action-edges", + leases: "mem:leases", + routines: "mem:routines", + routineRuns: "mem:routine-runs", + signals: "mem:signals", + checkpoints: "mem:checkpoints", + mesh: "mem:mesh", + sketches: "mem:sketches", + facets: "mem:facets", + sentinels: "mem:sentinels", + crystals: "mem:crystals" +}; + +//#endregion +//#region src/state/keyed-mutex.ts +const locks = /* @__PURE__ */ new Map(); +function withKeyedLock(key, fn) { + const next = (locks.get(key) ?? Promise.resolve()).then(fn, fn); + const cleanup = next.then(() => {}, () => {}); + locks.set(key, cleanup); + cleanup.then(() => { + if (locks.get(key) === cleanup) locks.delete(key); + }); + return next; +} + +//#endregion +//#region src/functions/diagnostics.ts +const ALL_CATEGORIES = [ + "actions", + "leases", + "sentinels", + "sketches", + "signals", + "sessions", + "memories", + "mesh" +]; +const TWENTY_FOUR_HOURS_MS = 1440 * 60 * 1e3; +const ONE_HOUR_MS = 3600 * 1e3; +function registerDiagnosticsFunction(sdk, kv) { + sdk.registerFunction("mem::diagnose", async (data) => { + const categories = data.categories && data.categories.length > 0 ? data.categories.filter((c) => ALL_CATEGORIES.includes(c)) : ALL_CATEGORIES; + const checks = []; + const now = Date.now(); + if (categories.includes("actions")) { + const actions = await kv.list(KV.actions); + const allEdges = await kv.list(KV.actionEdges); + const leases = await kv.list(KV.leases); + const actionMap = new Map(actions.map((a) => [a.id, a])); + for (const action of actions) { + if (action.status === "active") { + if (!leases.some((l) => l.actionId === action.id && l.status === "active" && new Date(l.expiresAt).getTime() > now)) checks.push({ + name: `active-no-lease:${action.id}`, + category: "actions", + status: "warn", + message: `Action "${action.title}" is active but has no active lease`, + fixable: false + }); + } + if (action.status === "blocked") { + const deps = allEdges.filter((e) => e.sourceActionId === action.id && e.type === "requires"); + if (deps.length > 0) { + if (deps.every((d) => { + const target = actionMap.get(d.targetActionId); + return target && target.status === "done"; + })) checks.push({ + name: `blocked-deps-done:${action.id}`, + category: "actions", + status: "fail", + message: `Action "${action.title}" is blocked but all dependencies are done`, + fixable: true + }); + } + } + if (action.status === "pending") { + const deps = allEdges.filter((e) => e.sourceActionId === action.id && e.type === "requires"); + if (deps.length > 0) { + if (deps.some((d) => { + const target = actionMap.get(d.targetActionId); + return !target || target.status !== "done"; + })) checks.push({ + name: `pending-unsatisfied-deps:${action.id}`, + category: "actions", + status: "fail", + message: `Action "${action.title}" is pending but has unsatisfied dependencies`, + fixable: true + }); + } + } + } + if (!checks.some((c) => c.category === "actions" && c.status !== "pass")) checks.push({ + name: "actions-ok", + category: "actions", + status: "pass", + message: `All ${actions.length} actions are consistent`, + fixable: false + }); + } + if (categories.includes("leases")) { + const leases = await kv.list(KV.leases); + const actions = await kv.list(KV.actions); + const actionIds = new Set(actions.map((a) => a.id)); + let leaseIssues = 0; + for (const lease of leases) { + if (lease.status === "active" && new Date(lease.expiresAt).getTime() <= now) { + checks.push({ + name: `expired-lease:${lease.id}`, + category: "leases", + status: "fail", + message: `Lease ${lease.id} for action ${lease.actionId} expired at ${lease.expiresAt}`, + fixable: true + }); + leaseIssues++; + } + if (!actionIds.has(lease.actionId)) { + checks.push({ + name: `orphaned-lease:${lease.id}`, + category: "leases", + status: "fail", + message: `Lease ${lease.id} references non-existent action ${lease.actionId}`, + fixable: true + }); + leaseIssues++; + } + } + if (leaseIssues === 0) checks.push({ + name: "leases-ok", + category: "leases", + status: "pass", + message: `All ${leases.length} leases are healthy`, + fixable: false + }); + } + if (categories.includes("sentinels")) { + const sentinels = await kv.list(KV.sentinels); + const actions = await kv.list(KV.actions); + const actionIds = new Set(actions.map((a) => a.id)); + let sentinelIssues = 0; + for (const sentinel of sentinels) { + if (sentinel.status === "watching" && sentinel.expiresAt && new Date(sentinel.expiresAt).getTime() <= now) { + checks.push({ + name: `expired-sentinel:${sentinel.id}`, + category: "sentinels", + status: "fail", + message: `Sentinel "${sentinel.name}" expired at ${sentinel.expiresAt}`, + fixable: true + }); + sentinelIssues++; + } + for (const actionId of sentinel.linkedActionIds) if (!actionIds.has(actionId)) { + checks.push({ + name: `sentinel-missing-action:${sentinel.id}:${actionId}`, + category: "sentinels", + status: "warn", + message: `Sentinel "${sentinel.name}" references non-existent action ${actionId}`, + fixable: false + }); + sentinelIssues++; + } + } + if (sentinelIssues === 0) checks.push({ + name: "sentinels-ok", + category: "sentinels", + status: "pass", + message: `All ${sentinels.length} sentinels are healthy`, + fixable: false + }); + } + if (categories.includes("sketches")) { + const sketches = await kv.list(KV.sketches); + let sketchIssues = 0; + for (const sketch of sketches) if (sketch.status === "active" && new Date(sketch.expiresAt).getTime() <= now) { + checks.push({ + name: `expired-sketch:${sketch.id}`, + category: "sketches", + status: "fail", + message: `Sketch "${sketch.title}" expired at ${sketch.expiresAt}`, + fixable: true + }); + sketchIssues++; + } + if (sketchIssues === 0) checks.push({ + name: "sketches-ok", + category: "sketches", + status: "pass", + message: `All ${sketches.length} sketches are healthy`, + fixable: false + }); + } + if (categories.includes("signals")) { + const signals = await kv.list(KV.signals); + let signalIssues = 0; + for (const signal of signals) if (signal.expiresAt && new Date(signal.expiresAt).getTime() <= now) { + checks.push({ + name: `expired-signal:${signal.id}`, + category: "signals", + status: "fail", + message: `Signal from "${signal.from}" expired at ${signal.expiresAt}`, + fixable: true + }); + signalIssues++; + } + if (signalIssues === 0) checks.push({ + name: "signals-ok", + category: "signals", + status: "pass", + message: `All ${signals.length} signals are healthy`, + fixable: false + }); + } + if (categories.includes("sessions")) { + const sessions = await kv.list(KV.sessions); + let sessionIssues = 0; + for (const session of sessions) if (session.status === "active" && now - new Date(session.startedAt).getTime() > TWENTY_FOUR_HOURS_MS) { + checks.push({ + name: `abandoned-session:${session.id}`, + category: "sessions", + status: "warn", + message: `Session ${session.id} has been active for over 24 hours`, + fixable: false + }); + sessionIssues++; + } + if (sessionIssues === 0) checks.push({ + name: "sessions-ok", + category: "sessions", + status: "pass", + message: `All ${sessions.length} sessions are healthy`, + fixable: false + }); + } + if (categories.includes("memories")) { + const memories = await kv.list(KV.memories); + const memoryIds = new Set(memories.map((m) => m.id)); + const supersededBy = /* @__PURE__ */ new Map(); + let memoryIssues = 0; + for (const memory of memories) if (memory.supersedes && memory.supersedes.length > 0) for (const sid of memory.supersedes) { + if (!memoryIds.has(sid)) { + checks.push({ + name: `memory-missing-supersedes:${memory.id}:${sid}`, + category: "memories", + status: "warn", + message: `Memory "${memory.title}" supersedes non-existent memory ${sid}`, + fixable: false + }); + memoryIssues++; + } + supersededBy.set(sid, memory.id); + } + for (const memory of memories) if (memory.isLatest && supersededBy.has(memory.id)) { + checks.push({ + name: `memory-stale-latest:${memory.id}`, + category: "memories", + status: "fail", + message: `Memory "${memory.title}" has isLatest=true but is superseded by ${supersededBy.get(memory.id)}`, + fixable: true + }); + memoryIssues++; + } + if (memoryIssues === 0) checks.push({ + name: "memories-ok", + category: "memories", + status: "pass", + message: `All ${memories.length} memories are consistent`, + fixable: false + }); + } + if (categories.includes("mesh")) { + const peers = await kv.list(KV.mesh); + let meshIssues = 0; + for (const peer of peers) { + if (peer.lastSyncAt && now - new Date(peer.lastSyncAt).getTime() > ONE_HOUR_MS) { + checks.push({ + name: `stale-peer:${peer.id}`, + category: "mesh", + status: "warn", + message: `Peer "${peer.name}" last synced over 1 hour ago`, + fixable: false + }); + meshIssues++; + } + if (peer.status === "error") { + checks.push({ + name: `error-peer:${peer.id}`, + category: "mesh", + status: "warn", + message: `Peer "${peer.name}" is in error state`, + fixable: false + }); + meshIssues++; + } + } + if (meshIssues === 0) checks.push({ + name: "mesh-ok", + category: "mesh", + status: "pass", + message: `All ${peers.length} mesh peers are healthy`, + fixable: false + }); + } + return { + success: true, + checks, + summary: { + pass: checks.filter((c) => c.status === "pass").length, + warn: checks.filter((c) => c.status === "warn").length, + fail: checks.filter((c) => c.status === "fail").length, + fixable: checks.filter((c) => c.fixable).length + } + }; + }); + sdk.registerFunction("mem::heal", async (data) => { + const dryRun = data.dryRun ?? false; + const categories = data.categories && data.categories.length > 0 ? data.categories.filter((c) => ALL_CATEGORIES.includes(c)) : ALL_CATEGORIES; + let fixed = 0; + let skipped = 0; + const details = []; + const now = Date.now(); + if (categories.includes("actions")) { + const actions = await kv.list(KV.actions); + const allEdges = await kv.list(KV.actionEdges); + const actionMap = new Map(actions.map((a) => [a.id, a])); + for (const action of actions) { + if (action.status === "blocked") { + const deps = allEdges.filter((e) => e.sourceActionId === action.id && e.type === "requires"); + if (deps.length > 0) { + if (deps.every((d) => { + const target = actionMap.get(d.targetActionId); + return target && target.status === "done"; + })) { + if (dryRun) { + details.push(`[dry-run] Would unblock action "${action.title}" (${action.id})`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:action:${action.id}`, async () => { + const fresh = await kv.get(KV.actions, action.id); + if (!fresh || fresh.status !== "blocked") return false; + const freshDeps = (await kv.list(KV.actionEdges)).filter((e) => e.sourceActionId === fresh.id && e.type === "requires"); + const freshActions = await kv.list(KV.actions); + const freshMap = new Map(freshActions.map((a) => [a.id, a])); + if (!freshDeps.every((d) => { + const target = freshMap.get(d.targetActionId); + return target && target.status === "done"; + })) return false; + fresh.status = "pending"; + fresh.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + await kv.set(KV.actions, fresh.id, fresh); + return true; + })) { + details.push(`Unblocked action "${action.title}" (${action.id})`); + fixed++; + } else skipped++; + } + } + } + if (action.status === "pending") { + const deps = allEdges.filter((e) => e.sourceActionId === action.id && e.type === "requires"); + if (deps.length > 0) { + if (deps.some((d) => { + const target = actionMap.get(d.targetActionId); + return !target || target.status !== "done"; + })) { + if (dryRun) { + details.push(`[dry-run] Would block action "${action.title}" (${action.id})`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:action:${action.id}`, async () => { + const fresh = await kv.get(KV.actions, action.id); + if (!fresh || fresh.status !== "pending") return false; + const freshDeps = (await kv.list(KV.actionEdges)).filter((e) => e.sourceActionId === fresh.id && e.type === "requires"); + const freshActions = await kv.list(KV.actions); + const freshMap = new Map(freshActions.map((a) => [a.id, a])); + if (!freshDeps.some((d) => { + const target = freshMap.get(d.targetActionId); + return !target || target.status !== "done"; + })) return false; + fresh.status = "blocked"; + fresh.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + await kv.set(KV.actions, fresh.id, fresh); + return true; + })) { + details.push(`Blocked action "${action.title}" (${action.id})`); + fixed++; + } else skipped++; + } + } + } + } + } + if (categories.includes("leases")) { + const leases = await kv.list(KV.leases); + const actions = await kv.list(KV.actions); + const actionIds = new Set(actions.map((a) => a.id)); + for (const lease of leases) { + if (lease.status === "active" && new Date(lease.expiresAt).getTime() <= now) { + if (dryRun) { + details.push(`[dry-run] Would expire lease ${lease.id} for action ${lease.actionId}`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:action:${lease.actionId}`, async () => { + const fresh = await kv.get(KV.leases, lease.id); + if (!fresh || fresh.status !== "active" || new Date(fresh.expiresAt).getTime() > Date.now()) return false; + fresh.status = "expired"; + await kv.set(KV.leases, fresh.id, fresh); + const action = await kv.get(KV.actions, fresh.actionId); + if (action && action.status === "active" && action.assignedTo === fresh.agentId) { + action.status = "pending"; + action.assignedTo = void 0; + action.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + await kv.set(KV.actions, action.id, action); + } + return true; + })) { + details.push(`Expired lease ${lease.id} for action ${lease.actionId}`); + fixed++; + } else skipped++; + continue; + } + if (!actionIds.has(lease.actionId)) { + if (dryRun) { + details.push(`[dry-run] Would delete orphaned lease ${lease.id}`); + fixed++; + continue; + } + await kv.delete(KV.leases, lease.id); + details.push(`Deleted orphaned lease ${lease.id}`); + fixed++; + } + } + } + if (categories.includes("sentinels")) { + const sentinels = await kv.list(KV.sentinels); + for (const sentinel of sentinels) if (sentinel.status === "watching" && sentinel.expiresAt && new Date(sentinel.expiresAt).getTime() <= now) { + if (dryRun) { + details.push(`[dry-run] Would expire sentinel "${sentinel.name}" (${sentinel.id})`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:sentinel:${sentinel.id}`, async () => { + const fresh = await kv.get(KV.sentinels, sentinel.id); + if (!fresh || fresh.status !== "watching") return false; + if (!fresh.expiresAt || new Date(fresh.expiresAt).getTime() > Date.now()) return false; + fresh.status = "expired"; + await kv.set(KV.sentinels, fresh.id, fresh); + return true; + })) { + details.push(`Expired sentinel "${sentinel.name}" (${sentinel.id})`); + fixed++; + } else skipped++; + } + } + if (categories.includes("sketches")) { + const sketches = await kv.list(KV.sketches); + for (const sketch of sketches) if (sketch.status === "active" && new Date(sketch.expiresAt).getTime() <= now) { + if (dryRun) { + details.push(`[dry-run] Would discard expired sketch "${sketch.title}" (${sketch.id})`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:sketch:${sketch.id}`, async () => { + const fresh = await kv.get(KV.sketches, sketch.id); + if (!fresh || fresh.status !== "active" || new Date(fresh.expiresAt).getTime() > Date.now()) return false; + const allEdges = await kv.list(KV.actionEdges); + const actionIdSet = new Set(fresh.actionIds); + for (const edge of allEdges) if (actionIdSet.has(edge.sourceActionId) || actionIdSet.has(edge.targetActionId)) await kv.delete(KV.actionEdges, edge.id); + for (const actionId of fresh.actionIds) await kv.delete(KV.actions, actionId); + fresh.status = "discarded"; + fresh.discardedAt = (/* @__PURE__ */ new Date()).toISOString(); + await kv.set(KV.sketches, fresh.id, fresh); + return true; + })) { + details.push(`Discarded expired sketch "${sketch.title}" (${sketch.id})`); + fixed++; + } else skipped++; + } + } + if (categories.includes("signals")) { + const signals = await kv.list(KV.signals); + for (const signal of signals) if (signal.expiresAt && new Date(signal.expiresAt).getTime() <= now) { + if (dryRun) { + details.push(`[dry-run] Would delete expired signal ${signal.id}`); + fixed++; + continue; + } + await kv.delete(KV.signals, signal.id); + details.push(`Deleted expired signal ${signal.id}`); + fixed++; + } + } + if (categories.includes("memories")) { + const memories = await kv.list(KV.memories); + const supersededBy = /* @__PURE__ */ new Map(); + for (const memory of memories) if (memory.supersedes && memory.supersedes.length > 0) for (const sid of memory.supersedes) supersededBy.set(sid, memory.id); + for (const memory of memories) if (memory.isLatest && supersededBy.has(memory.id)) { + if (dryRun) { + details.push(`[dry-run] Would set isLatest=false on memory "${memory.title}" (${memory.id})`); + fixed++; + continue; + } + if (await withKeyedLock(`mem:memory:${memory.id}`, async () => { + const fresh = await kv.get(KV.memories, memory.id); + if (!fresh || !fresh.isLatest) return false; + fresh.isLatest = false; + fresh.updatedAt = (/* @__PURE__ */ new Date()).toISOString(); + await kv.set(KV.memories, fresh.id, fresh); + return true; + })) { + details.push(`Set isLatest=false on memory "${memory.title}" (${memory.id})`); + fixed++; + } else skipped++; + } + } + return { + success: true, + fixed, + skipped, + details + }; + }); +} + +//#endregion +export { registerDiagnosticsFunction }; +//# sourceMappingURL=diagnostics.mjs.map \ No newline at end of file diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3967158c92d0f23824d191c5a7b3ecf0c19b8a7d --- /dev/null +++ b/plugin/scripts/notification.mjs @@ -0,0 +1,76 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/notification.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const notificationType = data.notification_type ?? data.notificationType; + if (notificationType !== "permission_prompt") return; + const rawSessionId = data.session_id ?? data.sessionId; + const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown"; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "notification", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + notification_type: notificationType, + title: data.title, + message: data.message + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=notification.mjs.map \ No newline at end of file diff --git a/plugin/scripts/post-commit.mjs b/plugin/scripts/post-commit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8552cd614eef25a55664b674dc76f5f92391ce61 --- /dev/null +++ b/plugin/scripts/post-commit.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +//#region src/hooks/post-commit.ts +const exec = promisify(execFile); +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +const TIMEOUT_MS = 1500; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function git(args, cwd) { + try { + const { stdout } = await exec("git", args, { + cwd, + timeout: 1500 + }); + return stdout.trim(); + } catch { + return null; + } +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data = {}; + if (input.trim()) try { + data = JSON.parse(input); + } catch {} + if (isSdkChildContext(data)) return; + const cwd = data.cwd || process.env["AGENTMEMORY_CWD"] || process.cwd(); + const sessionId = data.session_id || process.env["AGENTMEMORY_SESSION_ID"] || void 0; + const sha = process.env["AGENTMEMORY_COMMIT_SHA"] || await git(["rev-parse", "HEAD"], cwd); + if (!sha) return; + const branch = await git([ + "rev-parse", + "--abbrev-ref", + "HEAD" + ], cwd); + const repo = await git([ + "config", + "--get", + "remote.origin.url" + ], cwd); + const message = await git([ + "log", + "-1", + "--pretty=%B", + sha + ], cwd); + const author = await git([ + "log", + "-1", + "--pretty=%an <%ae>", + sha + ], cwd); + const authoredAt = await git([ + "log", + "-1", + "--pretty=%aI", + sha + ], cwd); + const filesRaw = await git([ + "diff-tree", + "--no-commit-id", + "--name-only", + "-r", + sha + ], cwd); + const files = filesRaw ? filesRaw.split("\n").filter(Boolean) : void 0; + const body = { + sessionId, + sha, + branch: branch || void 0, + repo: repo || void 0, + message: message || void 0, + author: author || void 0, + authoredAt: authoredAt || void 0, + files + }; + try { + await fetch(`${REST_URL}/agentmemory/session/commit`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(TIMEOUT_MS) + }); + } catch {} +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=post-commit.mjs.map \ No newline at end of file diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6fdad8d9d97bdd5d8850eae767e1c157258a1a6b --- /dev/null +++ b/plugin/scripts/post-tool-failure.mjs @@ -0,0 +1,77 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/post-tool-failure.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + if (data.is_interrupt || data.isInterrupt) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + const toolName = data.tool_name ?? data.toolName; + const toolInput = data.tool_input ?? data.toolArgs; + const error = data.error ?? data.errorMessage; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_failure", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + tool_name: toolName, + tool_input: typeof toolInput === "string" ? toolInput.slice(0, 4e3) : JSON.stringify(toolInput ?? "").slice(0, 4e3), + error: typeof error === "string" ? error.slice(0, 4e3) : JSON.stringify(error ?? "").slice(0, 4e3) + } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=post-tool-failure.mjs.map \ No newline at end of file diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b4aef9c942283f9446ceaec3c8291efaf0651cb8 --- /dev/null +++ b/plugin/scripts/post-tool-use.mjs @@ -0,0 +1,122 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/post-tool-use.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + const toolName = data.tool_name ?? data.toolName; + const toolInput = data.tool_input ?? data.toolArgs; + const { imageData, cleanOutput } = extractImageData(toolOutput(data)); + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "post_tool_use", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + tool_name: toolName, + tool_input: toolInput, + tool_output: truncate(cleanOutput, 8e3), + ...imageData ? { image_data: imageData } : {} + } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +function toolOutput(data) { + if (data.tool_response !== void 0) return data.tool_response; + if (data.tool_output !== void 0) return data.tool_output; + const result = data.tool_result ?? data.toolResult; + if (typeof result === "object" && result !== null) { + const obj = result; + return obj.text_result_for_llm ?? obj.textResultForLlm ?? result; + } + return result; +} +function isBase64Image(val) { + return typeof val === "string" && (val.startsWith("data:image/") || val.startsWith("iVBORw0KGgo") || val.startsWith("/9j/")); +} +function extractImageData(output) { + if (isBase64Image(output)) return { + imageData: output, + cleanOutput: "[image data extracted]" + }; + if (typeof output === "object" && output !== null && !Array.isArray(output)) { + const obj = output; + let imageData; + const clean = {}; + for (const [key, val] of Object.entries(obj)) if (!imageData && isBase64Image(val)) { + imageData = val; + clean[key] = "[image data extracted]"; + } else clean[key] = val; + return { + imageData, + cleanOutput: clean + }; + } + return { + imageData: void 0, + cleanOutput: output + }; +} +function truncate(value, max) { + if (typeof value === "string" && value.length > max) return value.slice(0, max) + "\n[...truncated]"; + if (typeof value === "object" && value !== null) { + const str = JSON.stringify(value); + if (str.length > max) return str.slice(0, max) + "...[truncated]"; + return value; + } + return value; +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=post-tool-use.mjs.map \ No newline at end of file diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0afdcb0b4e0c3fb47058bf43c1fd6e95f088f542 --- /dev/null +++ b/plugin/scripts/pre-compact.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/pre-compact.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + const project = resolveProject(data.cwd); + if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") try { + await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({}), + signal: AbortSignal.timeout(5e3) + }); + } catch {} + try { + const res = await fetch(`${REST_URL}/agentmemory/context`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + project, + budget: 1500 + }), + signal: AbortSignal.timeout(5e3) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) process.stdout.write(result.context); + } + } catch {} +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=pre-compact.mjs.map \ No newline at end of file diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d70c166ed2a70e617e920115251bfe199f83ed23 --- /dev/null +++ b/plugin/scripts/pre-tool-use.mjs @@ -0,0 +1,84 @@ +#!/usr/bin/env node +//#region src/hooks/pre-tool-use.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + if (!INJECT_CONTEXT) return; + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const toolName = typeof data.tool_name === "string" ? data.tool_name : typeof data.toolName === "string" ? data.toolName : void 0; + if (!toolName) return; + const normalizedToolName = toolName.toLowerCase(); + if (![ + "edit", + "write", + "create", + "read", + "view", + "glob", + "grep" + ].includes(normalizedToolName)) return; + const rawToolInput = data.tool_input ?? data.toolArgs; + const toolInput = typeof rawToolInput === "object" && rawToolInput !== null && !Array.isArray(rawToolInput) ? rawToolInput : {}; + const files = []; + const fileKeys = normalizedToolName === "grep" ? ["path", "file"] : [ + "file_path", + "path", + "file", + "pattern" + ]; + for (const key of fileKeys) { + const val = toolInput[key]; + if (typeof val === "string" && val.length > 0) files.push(val); + } + if (files.length === 0) return; + const terms = []; + if (normalizedToolName === "grep" || normalizedToolName === "glob") { + const pattern = toolInput["pattern"]; + if (typeof pattern === "string" && pattern.length > 0) terms.push(pattern); + } + const rawSessionId = data.session_id || data.sessionId; + const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown"; + const project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : void 0; + try { + const res = await fetch(`${REST_URL}/agentmemory/enrich`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + files, + terms, + toolName, + ...project !== void 0 && { project } + }), + signal: AbortSignal.timeout(2e3) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) process.stdout.write(result.context); + } + } catch {} +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=pre-tool-use.mjs.map \ No newline at end of file diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1a4147e6ab91e77a48b284445d09ecaf6a7b902e --- /dev/null +++ b/plugin/scripts/prompt-submit.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/prompt-submit.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "prompt_submit", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { prompt: data.prompt ?? data.userPrompt } + }), + signal: AbortSignal.timeout(3e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=prompt-submit.mjs.map \ No newline at end of file diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs new file mode 100644 index 0000000000000000000000000000000000000000..019149c3093725f63d259d5bdffc822cee1cdf96 --- /dev/null +++ b/plugin/scripts/session-end.mjs @@ -0,0 +1,60 @@ +#!/usr/bin/env node +//#region src/hooks/session-end.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(3e4) + }).catch(() => {}); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + fetch(`${REST_URL}/agentmemory/crystals/auto`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ olderThanDays: 0 }), + signal: AbortSignal.timeout(6e4) + }).catch(() => {}); + fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + tier: "all", + force: true + }), + signal: AbortSignal.timeout(12e4) + }).catch(() => {}); + } + if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: "POST", + headers: authHeaders(), + signal: AbortSignal.timeout(3e4) + }).catch(() => {}); + setTimeout(() => process.exit(0), 1500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=session-end.mjs.map \ No newline at end of file diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs new file mode 100644 index 0000000000000000000000000000000000000000..51b70eb4c253c86c9272db5e6a4acf7fa117cdda --- /dev/null +++ b/plugin/scripts/session-start.mjs @@ -0,0 +1,87 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/session-start.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +const INJECT_TIMEOUT_MS = 1500; +const REGISTER_TIMEOUT_MS = 800; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || `ses_${Date.now().toString(36)}`; + const cwd = data.cwd || process.cwd(); + const project = resolveProject(data.cwd); + const url = `${REST_URL}/agentmemory/session/start`; + const init = { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + project, + cwd + }) + }; + if (!INJECT_CONTEXT) { + fetch(url, { + ...init, + signal: AbortSignal.timeout(REGISTER_TIMEOUT_MS) + }).catch(() => {}); + return; + } + try { + const res = await fetch(url, { + ...init, + signal: AbortSignal.timeout(INJECT_TIMEOUT_MS) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) process.stdout.write(result.context); + } + } catch {} +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=session-start.mjs.map \ No newline at end of file diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..03d30c64f3210ab88d16ddf27d44f9719e91b129 --- /dev/null +++ b/plugin/scripts/stop.mjs @@ -0,0 +1,44 @@ +#!/usr/bin/env node +//#region src/hooks/stop.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + fetch(`${REST_URL}/agentmemory/summarize`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(12e4) + }).catch(() => {}); + fetch(`${REST_URL}/agentmemory/session/end`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ sessionId }), + signal: AbortSignal.timeout(5e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 1500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=stop.mjs.map \ No newline at end of file diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2359a1c62ffbf55a41e9daa002b96fe247d142cf --- /dev/null +++ b/plugin/scripts/subagent-start.mjs @@ -0,0 +1,75 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/subagent-start.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +const TIMEOUT_MS = 800; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + const agentId = data.agent_id || data.agentName; + const agentType = data.agent_type || data.agentDisplayName || data.agentName; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "subagent_start", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + agent_id: agentId, + agent_type: agentType + } + }), + signal: AbortSignal.timeout(TIMEOUT_MS) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=subagent-start.mjs.map \ No newline at end of file diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2ba1b002c9bf0ba98ce91f61378d3d51fcdc82d3 --- /dev/null +++ b/plugin/scripts/subagent-stop.mjs @@ -0,0 +1,76 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/subagent-stop.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || data.sessionId || "unknown"; + const agentId = data.agent_id || data.agentName; + const agentType = data.agent_type || data.agentDisplayName || data.agentName; + const lastMsg = typeof data.last_assistant_message === "string" ? data.last_assistant_message.slice(0, 4e3) : ""; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "subagent_stop", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + agent_id: agentId, + agent_type: agentType, + last_message: lastMsg + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=subagent-stop.mjs.map \ No newline at end of file diff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjs new file mode 100644 index 0000000000000000000000000000000000000000..478f0688e8af7433a1733790936d7d2c27213efe --- /dev/null +++ b/plugin/scripts/task-completed.mjs @@ -0,0 +1,75 @@ +#!/usr/bin/env node +import { execSync } from "node:child_process"; +import { basename } from "node:path"; + +//#region src/hooks/_project.ts +function resolveProject(cwd) { + const explicit = process.env["AGENTMEMORY_PROJECT_NAME"]; + if (explicit && explicit.trim()) return explicit.trim(); + const dir = cwd && cwd.trim() ? cwd : process.cwd(); + try { + const top = execSync("git rev-parse --show-toplevel", { + cwd: dir, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + timeout: 500 + }).toString().trim(); + if (top) return basename(top); + } catch {} + return basename(dir); +} + +//#endregion +//#region src/hooks/task-completed.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || "unknown"; + fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "task_completed", + sessionId, + project: resolveProject(data.cwd), + cwd: data.cwd || process.cwd(), + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + task_id: data.task_id, + task_subject: data.task_subject, + task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "", + teammate_name: data.teammate_name, + team_name: data.team_name + } + }), + signal: AbortSignal.timeout(2e3) + }).catch(() => {}); + setTimeout(() => process.exit(0), 500).unref(); +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=task-completed.mjs.map \ No newline at end of file diff --git a/plugin/skills/_shared/TROUBLESHOOTING.md b/plugin/skills/_shared/TROUBLESHOOTING.md new file mode 100644 index 0000000000000000000000000000000000000000..ee082d0ceccc8784c89b4190924b111ba53e27b1 --- /dev/null +++ b/plugin/skills/_shared/TROUBLESHOOTING.md @@ -0,0 +1,38 @@ +# Troubleshooting agentmemory skills + +Shared recovery steps for all user-invocable agentmemory skills. Each skill's +Troubleshooting section points here instead of duplicating the block. + +## "MCP tool not available" + +If a `memory_*` MCP tool does not appear, the stdio MCP shim never started. +Walk these in order: + +1. Run `/plugin list` in the host and confirm `agentmemory` shows as enabled. +2. Restart the host. The plugin's `.mcp.json` is only read on startup, so a + freshly installed or re-enabled plugin will not register tools mid-session. +3. Check `/mcp` and confirm the `agentmemory` server shows a live connection. + +## REST fallback + +When the MCP tools stay unavailable but the daemon is running, call the REST +API directly: + +1. Set `AGENTMEMORY_URL` to the daemon base URL (default `http://localhost:3111`). +2. Add `Authorization: Bearer $AGENTMEMORY_SECRET` ONLY when `AGENTMEMORY_SECRET` + is set. The default localhost daemon is open and rejects a stray header. + +Endpoint map by skill: + +| Skill | REST call | +| --------------- | --------------------------------------------------------------- | +| remember | `POST /agentmemory/remember` | +| recall | `POST /agentmemory/smart-search` | +| recap | `GET /agentmemory/sessions` + `POST /agentmemory/smart-search` | +| handoff | `GET /agentmemory/sessions` + `POST /agentmemory/smart-search` | +| session-history | `GET /agentmemory/sessions` | +| commit-context | `GET /agentmemory/session/by-commit?sha=` | +| commit-history | `GET /agentmemory/commits` (URL-encode every query param) | + +The daemon reads `.mcp.json` on startup only, so any port or auth change needs a +restart before either transport sees it. diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..7be767134a15a143530a968929562c603a344a10 --- /dev/null +++ b/plugin/skills/agentmemory-agents/REFERENCE.md @@ -0,0 +1,27 @@ +# agentmemory connect adapters reference + +Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing an adapter. + + +`agentmemory connect ` wires the memory server into a host agent. 17 adapters: + +| Agent | Name | Protocol | +| --- | --- | --- | +| Antigravity | `antigravity` | Using MCP via mcp_config.json. Antigravity replaces Gemini CLI (sunset 2026-06-18). | +| Claude Code | `claude-code` | Using MCP. Hooks are also available, see docs/claude-code.md. | +| Cline | `cline` | Using MCP via ~/.cline/mcp.json (CLI). VS Code users: add the same block via Cline Settings → MCP Servers → Edit JSON. | +| Codex CLI | `codex` | Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430. | +| Continue | `continue` | Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml). | +| GitHub Copilot CLI | `copilot-cli` | Using MCP. Install the plugin too for full hooks/skills coverage. | +| Cursor | `cursor` | Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath. | +| Droid (Factory.ai) | `droid` | Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. | +| Gemini CLI | `gemini-cli` | Using MCP (the only protocol Gemini CLI speaks). Memory bridge runs at :3111 underneath. | +| Hermes Agent | `hermes` | Using MCP. Hooks are also available, see docs/hermes.md. | +| Kiro | `kiro` | Using MCP via ~/.kiro/settings/mcp.json (user-level). Workspace overrides live in .kiro/settings/mcp.json. | +| OpenClaw | `openclaw` | Using MCP. Hooks are also available, see docs/openclaw.md. | +| OpenHuman | `openhuman` | Using native hooks (REST API at :3111). MCP not required. | +| pi | `pi` | Using native hooks (REST API at :3111). MCP not required. | +| Qwen Code | `qwen` | Using MCP via ~/.qwen/settings.json. Qwen Code's hook system can also be wired separately, see docs. | +| Warp | `warp` | Using MCP via ~/.warp/.mcp.json. Skills auto-discover from .claude/skills/ if the Claude Code plugin is also installed. | +| Zed | `zed` | Using MCP via ~/.config/zed/settings.json (key: context_servers). | + diff --git a/plugin/skills/agentmemory-agents/SKILL.md b/plugin/skills/agentmemory-agents/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..e4cda491580da7006c485315a9f9cbb864cf5e43 --- /dev/null +++ b/plugin/skills/agentmemory-agents/SKILL.md @@ -0,0 +1,34 @@ +--- +name: agentmemory-agents +description: How agentmemory wires into host coding agents via the connect command. Use when installing agentmemory into a specific agent, when asked which agents are supported, or when a connect adapter writes the wrong config path. +user-invocable: false +--- + +`agentmemory connect ` merges the memory server into a host agent's config and preserves any existing servers. REST is the underlying protocol; for MCP-only hosts the adapter wires the stdio MCP bridge. + +## Quick start + +```bash +agentmemory connect claude-code # or cursor, codex, gemini-cli, ... +``` + +After wiring, restart the host or run its MCP reload (for example `/mcp` in Claude Code) so it picks up the server. Then confirm the agent lists agentmemory's tools. + +## Workflow + +1. Detect the calling agent. If unknown, default to `claude-code`. +2. Run `agentmemory connect ` using a name from the table in REFERENCE.md. +3. Verify: the host should show the full tool set with a server running. Only 7 tools means the MCP shim could not reach a server (see ../_shared/TROUBLESHOOTING.md). + +## Notes + +- The action skills (remember, recall, and the rest) are installed separately with `npx skills add rohitg00/agentmemory`. `connect` makes tools available; skills teach the agent when to use them. +- Windows: use WSL2. Native Windows runs the server but `connect` is not supported there. + +## See also + +- agentmemory-mcp-tools, agentmemory-rest-api, agentmemory-hooks. + +## Reference + +The full adapter list with display names and protocol notes lives in REFERENCE.md, generated from `src/cli/connect/`. diff --git a/plugin/skills/agentmemory-architecture/SKILL.md b/plugin/skills/agentmemory-architecture/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..431c26031a7c521b9c7d175a11ef1de964cc7033 --- /dev/null +++ b/plugin/skills/agentmemory-architecture/SKILL.md @@ -0,0 +1,33 @@ +--- +name: agentmemory-architecture +description: How agentmemory is built, the iii engine primitives it runs on, its storage model, ports, and the viewer. Use when reasoning about how memory is stored or retrieved end to end, when extending the system, or when answering how agentmemory works under the hood. +user-invocable: false +--- + +agentmemory is a memory server for coding agents. It runs locally, captures observations, indexes them for hybrid retrieval, and serves them back over REST and MCP. It is built on the iii engine. + +## iii primitives + +Everything is a function, a trigger, or worker state on the iii engine. There is no separate plugin system; the worker registers functions (`mem::*`) and HTTP triggers (`api::*`) and the engine routes calls. agentmemory does not bypass iii; new capability is a new function plus a trigger. + +## Retrieval model + +Recall is hybrid: BM25 keyword search plus vector similarity plus graph expansion over linked concepts. The default install needs no API key because embeddings run on-device and BM25 needs none. An LLM provider only adds richer summaries and auto-injection, both opt-in. + +## Storage and lifecycle + +Memories carry content, concepts, files, importance, and timestamps, grouped into sessions and optionally linked to commits. A lifecycle of capture, compress, consolidate, and forget keeps the store useful over time rather than letting it grow unbounded. + +## Ports + +REST is the anchor at 3111. Streams = N+1 (3112), viewer = N+2 (3113), engine = N+46023 (49134). `--instance N` shifts the whole block by N*100. + +## Viewer + +A real-time web viewer at `http://localhost:3113` shows memory building as sessions run. Useful for demos and for confirming capture is working. + +## See also + +- agentmemory-mcp-tools and agentmemory-rest-api for the surfaces. +- agentmemory-hooks for automatic capture. +- agentmemory-config for ports and feature flags. diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..08c873a44460b0c1da30c120644a351b22594be2 --- /dev/null +++ b/plugin/skills/agentmemory-config/REFERENCE.md @@ -0,0 +1,42 @@ +# agentmemory configuration reference + +Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded. + + +Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 34 recognized variables: + +- `AGENTMEMORY_AGENT_SCOPE` +- `AGENTMEMORY_ALLOW_AGENT_SDK` +- `AGENTMEMORY_AUTO_COMPRESS` +- `AGENTMEMORY_COMMIT_SHA` +- `AGENTMEMORY_COPILOT_MCP_BLOCK` +- `AGENTMEMORY_CWD` +- `AGENTMEMORY_DEBUG` +- `AGENTMEMORY_DROP_STALE_INDEX` +- `AGENTMEMORY_EXPORT_ROOT` +- `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS` +- `AGENTMEMORY_FORCE_PROXY` +- `AGENTMEMORY_GRAPH_WEIGHT` +- `AGENTMEMORY_III_CONFIG` +- `AGENTMEMORY_III_VERSION` +- `AGENTMEMORY_IMAGE_EMBEDDINGS` +- `AGENTMEMORY_IMAGE_STORE_MAX_BYTES` +- `AGENTMEMORY_INJECT_CONTEXT` +- `AGENTMEMORY_LLM_TIMEOUT_MS` +- `AGENTMEMORY_MCP_BLOCK` +- `AGENTMEMORY_PROBE_TIMEOUT_MS` +- `AGENTMEMORY_PROJECT_NAME` +- `AGENTMEMORY_PROVIDER` +- `AGENTMEMORY_REFLECT` +- `AGENTMEMORY_SDK_CHILD` +- `AGENTMEMORY_SECRET` +- `AGENTMEMORY_SESSION_ID` +- `AGENTMEMORY_SLOTS` +- `AGENTMEMORY_SUPPRESS_COST_WARNING` +- `AGENTMEMORY_TOOLS` +- `AGENTMEMORY_URL` +- `AGENTMEMORY_USE_DOCKER` +- `AGENTMEMORY_VERBOSE` +- `AGENTMEMORY_VIEWER_HOST` +- `AGENTMEMORY_VIEWER_URL` + diff --git a/plugin/skills/agentmemory-config/SKILL.md b/plugin/skills/agentmemory-config/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..aea78c9bab2d3e0d1c3da04e594753ad209936c6 --- /dev/null +++ b/plugin/skills/agentmemory-config/SKILL.md @@ -0,0 +1,37 @@ +--- +name: agentmemory-config +description: agentmemory configuration, environment variables, ports, and feature flags. Use when enabling a feature, changing ports, setting an API key, configuring auth, or explaining why a feature is off by default. +user-invocable: false +--- + +agentmemory reads configuration from the environment and from `~/.agentmemory/.env` (one `KEY=value` per line, no `export` prefix). Restart the server after changing it. + +## Quick start + +Enable richer memory and set a provider key in `~/.agentmemory/.env`: + +```env +ANTHROPIC_API_KEY=sk-ant-... +AGENTMEMORY_AUTO_COMPRESS=true +AGENTMEMORY_INJECT_CONTEXT=true +``` + +## Defaults worth knowing + +- No API key is required. Without one, agentmemory runs zero-LLM with BM25 plus local embeddings. +- Token-spending features ship OFF on purpose: `AGENTMEMORY_AUTO_COMPRESS` (LLM summaries) and `AGENTMEMORY_INJECT_CONTEXT` (auto context injection) both cost tokens proportional to tool-use frequency. +- Tool visibility: `AGENTMEMORY_TOOLS=all` (default) or `core` for the lean set. +- Auth: set `AGENTMEMORY_SECRET` to require `Authorization: Bearer` on the REST API. + +## Ports + +REST is the anchor at 3111. Streams = N+1 (3112), viewer = N+2 (3113), engine = N+46023 (49134). Relocate the whole block with `--port ` or `--instance `. + +## See also + +- agentmemory-rest-api for how the secret is used. +- agentmemory-architecture for the port quartet rationale. + +## Reference + +The full recognized-variable list lives in REFERENCE.md, generated by scanning `src/`. diff --git a/plugin/skills/agentmemory-hooks/REFERENCE.md b/plugin/skills/agentmemory-hooks/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..2cf2dcec7da84b7ad4dd1b2fd404a495b780d77e --- /dev/null +++ b/plugin/skills/agentmemory-hooks/REFERENCE.md @@ -0,0 +1,20 @@ +# agentmemory hooks reference + +Generated from `plugin/hooks/hooks.json`. Do not edit the block below by hand; run `npm run skills:gen` after changing the hook registration. + + +The Claude Code plugin registers hooks on 12 lifecycle events to capture observations automatically: + +- `Notification` +- `PostToolUse` +- `PostToolUseFailure` +- `PreCompact` +- `PreToolUse` +- `SessionEnd` +- `SessionStart` +- `Stop` +- `SubagentStart` +- `SubagentStop` +- `TaskCompleted` +- `UserPromptSubmit` + diff --git a/plugin/skills/agentmemory-hooks/SKILL.md b/plugin/skills/agentmemory-hooks/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b8127f3feaff5d3748074cc206e66323a1b84d96 --- /dev/null +++ b/plugin/skills/agentmemory-hooks/SKILL.md @@ -0,0 +1,39 @@ +--- +name: agentmemory-hooks +description: The agentmemory plugin hooks that capture observations automatically across the agent session lifecycle. Use when explaining how memory gets captured without manual saves, when debugging missing observations, or when tuning what gets recorded. +user-invocable: false +--- + +The Claude Code plugin registers lifecycle hooks so memory is captured automatically. You do not have to call `memory_save` for routine work; the hooks observe tool use, prompts, and session boundaries and write observations for you. + +## Quick start + +Install the plugin and the hooks register themselves: + +```bash +/plugin marketplace add rohitg00/agentmemory +/plugin install agentmemory +``` + +Watch observations land live at `http://localhost:3113`. + +## What the hooks do + +- Session start and end frame each unit of work and let `handoff` resume it. +- Tool-use hooks capture what changed and why, the raw material for `recall` and `recap`. +- Prompt-submit captures intent. Pre-compact preserves context before the host trims it. +- A post-commit hook links commits to sessions, which powers `commit-context` and `commit-history`. + +## Important + +- Capture is on by default and is zero-LLM. Turning observations into LLM summaries (`AGENTMEMORY_AUTO_COMPRESS`) and injecting them back into context (`AGENTMEMORY_INJECT_CONTEXT`) are separate opt-ins because they spend tokens. +- If observations are missing, confirm the plugin is enabled and the server is running. See ../_shared/TROUBLESHOOTING.md. + +## See also + +- agentmemory-config for the capture and injection flags. +- The handoff, recap, and session-history skills consume what these hooks record. + +## Reference + +The exact registered hook events live in REFERENCE.md, generated from `plugin/hooks/hooks.json`. diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..0c556fc77feb95efc267d3f0bf283e8b226f9496 --- /dev/null +++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md @@ -0,0 +1,65 @@ +# agentmemory MCP tools reference + +Generated from `src/mcp/tools-registry.ts`. Do not edit the block below by hand; run `npm run skills:gen` after changing the registry. + + +agentmemory exposes 53 MCP tools. 8 are in the lean core set (`--tools core` or `AGENTMEMORY_TOOLS=core`); the rest load with `--tools all` (default). + +| Tool | Core | Parameters | Purpose | +| --- | --- | --- | --- | +| `memory_action_create` | | `title`*: string, `description`: string, `priority`: number, `project`: string, `tags`: string, `parentId`: string, `requires`: string | Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other. | +| `memory_action_update` | | `actionId`*: string, `status`: string, `result`: string, `priority`: number | Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions. | +| `memory_audit` | | `operation`: string, `limit`: number | View the audit trail of memory operations. | +| `memory_checkpoint` | | `operation`*: string, `name`: string, `checkpointId`: string, `status`: string, `type`: string, `linkedActionIds`: string | Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress. | +| `memory_claude_bridge_sync` | | `direction`*: string | Sync memory state to/from Claude Code's native MEMORY.md file. | +| `memory_commit_lookup` | | `sha`*: string | Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions. | +| `memory_commits` | | `branch`: string, `repo`: string, `limit`: number | List recent commits linked to agent sessions, optionally filtered by branch or repo. | +| `memory_compress_file` | | `filePath`*: string | Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing. | +| `memory_consolidate` | yes | `tier`: string | Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural). | +| `memory_crystallize` | | `actionIds`*: string, `project`: string, `sessionId`: string | Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons. | +| `memory_diagnose` | yes | `categories`: string | Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state. | +| `memory_export` | | none | Export all memory data as JSON. | +| `memory_facet_query` | | `matchAll`: string, `matchAny`: string, `targetType`: string | Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend. | +| `memory_facet_tag` | | `targetId`*: string, `targetType`*: string, `dimension`*: string, `value`*: string | Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization. | +| `memory_file_history` | | `files`*: string, `sessionId`: string | Get past observations about specific files. | +| `memory_frontier` | | `project`: string, `agentId`: string, `limit`: number | Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies. | +| `memory_governance_delete` | | `memoryIds`*: string, `reason`: string | Delete specific memories with audit trail. | +| `memory_graph_query` | | `startNodeId`: string, `nodeType`: string, `maxDepth`: number, `query`: string | Query the knowledge graph for entities and relationships. | +| `memory_heal` | | `categories`: string, `dryRun`: string | Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data. | +| `memory_insight_list` | | `project`: string, `minConfidence`: number, `limit`: number | List synthesized insights, higher-order observations derived from patterns across memories, lessons, and crystals. | +| `memory_lease` | | `actionId`*: string, `agentId`*: string, `operation`*: string, `result`: string, `ttlMs`: number | Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing. | +| `memory_lesson_recall` | | `query`*: string, `project`: string, `minConfidence`: number, `limit`: number | Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions. | +| `memory_lesson_save` | yes | `content`*: string, `context`: string, `confidence`: number, `project`: string, `tags`: string | Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson. | +| `memory_mesh_sync` | | `peerId`: string, `direction`: string | Sync memories and actions with peer agentmemory instances for multi-agent collaboration. | +| `memory_next` | | `project`: string, `agentId`: string | Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score. | +| `memory_obsidian_export` | | `vaultDir`: string, `types`: string | Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view. | +| `memory_patterns` | | `project`: string | Detect recurring patterns across sessions. | +| `memory_profile` | | `project`*: string, `refresh`: string | User/project profile with top concepts and file patterns. | +| `memory_recall` | yes | `query`*: string, `limit`: number, `format`: string, `token_budget`: number | Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before. | +| `memory_reflect` | yes | `project`: string, `maxClusters`: number | Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights. | +| `memory_relations` | | `memoryId`*: string, `maxHops`: number, `minConfidence`: number | Query the memory relationship graph. | +| `memory_routine_run` | | `routineId`*: string, `project`: string, `initiatedBy`: string | Instantiate a frozen workflow routine, creating actions for each step with proper dependencies. | +| `memory_save` | yes | `content`*: string, `type`: string, `concepts`: string, `files`: string, `project`: string | Explicitly save an important insight, decision, or pattern to long-term memory. | +| `memory_sentinel_create` | | `name`*: string, `type`*: string, `config`: string, `linkedActionIds`: string, `expiresInMs`: number | Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered. | +| `memory_sentinel_trigger` | | `sentinelId`*: string, `result`: string | Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions. | +| `memory_sessions` | yes | none | List recent sessions with their status and observation counts. | +| `memory_signal_read` | | `agentId`*: string, `unreadOnly`: string, `threadId`: string, `limit`: number | Read messages for an agent. Marks delivered messages as read. | +| `memory_signal_send` | | `from`*: string, `to`: string, `content`*: string, `type`: string, `replyTo`: string | Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration. | +| `memory_sketch_create` | | `title`*: string, `description`: string, `expiresInMs`: number, `project`: string | Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded. | +| `memory_sketch_promote` | | `sketchId`*: string, `project`: string | Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official. | +| `memory_slot_append` | | `label`*: string, `text`*: string | Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit, agent must compact via memory_slot_replace first. | +| `memory_slot_create` | | `label`*: string, `content`: string, `sizeLimit`: number, `description`: string, `pinned`: string, `scope`: string | Create a new slot. Reject if a slot with the same label already exists. | +| `memory_slot_delete` | | `label`*: string | Delete a slot. Seeded default slots can be deleted unless marked readOnly. | +| `memory_slot_get` | | `label`*: string | Read a single slot by label. | +| `memory_slot_list` | | none | List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions. | +| `memory_slot_replace` | | `label`*: string, `content`*: string | Replace slot content in place. Fails if content exceeds sizeLimit. | +| `memory_smart_search` | yes | `query`*: string, `expandIds`: string, `limit`: number | Hybrid semantic+keyword search with progressive disclosure. | +| `memory_snapshot_create` | | `message`: string | Create a git-versioned snapshot of current memory state. | +| `memory_team_feed` | | `limit`: number | Get recent shared items from all team members. | +| `memory_team_share` | | `itemId`*: string, `itemType`*: string | Share a memory or observation with team members. | +| `memory_timeline` | | `anchor`*: string, `project`: string, `before`: number, `after`: number | Chronological observations around an anchor point. | +| `memory_verify` | | `id`*: string | Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores. | +| `memory_vision_search` | | `queryText`: string, `queryImageRef`: string, `queryImageBase64`: string, `topK`: number, `sessionId`: string | Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true. | + +`*` marks required parameters. + diff --git a/plugin/skills/agentmemory-mcp-tools/SKILL.md b/plugin/skills/agentmemory-mcp-tools/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..00445ef3b4d3566a42682397d69e64a0d38ba7db --- /dev/null +++ b/plugin/skills/agentmemory-mcp-tools/SKILL.md @@ -0,0 +1,39 @@ +--- +name: agentmemory-mcp-tools +description: Map of every agentmemory MCP tool, what each does, and its parameters. Use when choosing which memory tool to call, when a tool name or argument is unclear, or when answering what agentmemory can do via MCP. +user-invocable: false +--- + +agentmemory exposes its full capability set as MCP tools. This skill is the index: it tells you which tool to reach for and where to find exact parameters. + +## Quick start + +Save then recall: + +1. `memory_save` with `content` (the insight), `concepts` (comma-separated keywords), `files` (comma-separated paths). +2. `memory_smart_search` with `query` and `limit` to retrieve it later. This runs hybrid BM25 plus vector plus graph-expanded search. + +## Tool families + +- Capture: `memory_save`, `memory_observe` flows, `memory_compress_file`. +- Retrieve: `memory_smart_search`, `memory_recall`, `memory_file_history`, `memory_timeline`, `memory_vision_search`. +- Sessions and commits: `memory_sessions`, `memory_commits`, `memory_commit_lookup`. +- Knowledge and graph: `memory_lesson_save`, `memory_lesson_recall`, `memory_graph_query`, `memory_relations`, `memory_patterns`, `memory_crystallize`. +- Structured slots: `memory_slot_create`, `memory_slot_append`, `memory_slot_get`, `memory_slot_list`, `memory_slot_replace`, `memory_slot_delete`. +- Governance and health: `memory_governance_delete`, `memory_audit`, `memory_verify`, `memory_heal`, `memory_diagnose`. + +## Workflow + +1. Pick the narrowest tool for the task. Prefer `memory_smart_search` for open recall, `memory_recall` when you already have a focused query, `memory_sessions` for session listings. +2. Look up exact parameter names and which are required in REFERENCE.md before calling. +3. Pass only documented fields. REST handlers whitelist fields and drop unknown ones. + +## See also + +- agentmemory-rest-api for the HTTP equivalents. +- agentmemory-config for tool-visibility and feature flags. +- The user-invocable action skills (remember, recall, recap, handoff, forget) wrap the most common tools. + +## Reference + +Full tool table with parameters and the core-set marking lives in REFERENCE.md, generated from source so it never drifts. diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..d36171defe5cdcd6692bd799bbb14e3eda77a44f --- /dev/null +++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md @@ -0,0 +1,129 @@ +# agentmemory REST API reference + +Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run `npm run skills:gen` after changing the registered endpoints. + + +The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open. + +117 registered endpoints: + +| Method | Path | +| --- | --- | +| POST | `/agentmemory/actions` | +| POST | `/agentmemory/actions/edges` | +| GET | `/agentmemory/actions/get` | +| POST | `/agentmemory/actions/update` | +| GET | `/agentmemory/audit` | +| POST | `/agentmemory/auto-forget` | +| GET | `/agentmemory/branch/detect` | +| GET | `/agentmemory/branch/sessions` | +| GET | `/agentmemory/branch/worktrees` | +| POST | `/agentmemory/cascade-update` | +| POST | `/agentmemory/checkpoints` | +| POST | `/agentmemory/checkpoints/resolve` | +| GET | `/agentmemory/claude-bridge/read` | +| POST | `/agentmemory/claude-bridge/sync` | +| GET | `/agentmemory/commits` | +| POST | `/agentmemory/compress-file` | +| GET | `/agentmemory/config/flags` | +| POST | `/agentmemory/consolidate` | +| POST | `/agentmemory/consolidate-pipeline` | +| POST | `/agentmemory/context` | +| GET | `/agentmemory/crystals` | +| POST | `/agentmemory/crystals/auto` | +| POST | `/agentmemory/crystals/create` | +| POST | `/agentmemory/diagnostics` | +| GET | `/agentmemory/diagnostics/followup` | +| POST | `/agentmemory/diagnostics/heal` | +| POST | `/agentmemory/enrich` | +| POST | `/agentmemory/evict` | +| POST | `/agentmemory/evolve` | +| GET | `/agentmemory/export` | +| POST | `/agentmemory/facets` | +| POST | `/agentmemory/facets/query` | +| POST | `/agentmemory/facets/remove` | +| GET | `/agentmemory/facets/stats` | +| POST | `/agentmemory/file-context` | +| POST | `/agentmemory/flow/compress` | +| POST | `/agentmemory/forget` | +| GET | `/agentmemory/frontier` | +| POST | `/agentmemory/generate-rules` | +| POST | `/agentmemory/governance/bulk-delete` | +| DELETE | `/agentmemory/governance/memories` | +| POST | `/agentmemory/graph/build` | +| POST | `/agentmemory/graph/extract` | +| POST | `/agentmemory/graph/query` | +| POST | `/agentmemory/graph/reset` | +| POST | `/agentmemory/graph/snapshot-rebuild` | +| GET | `/agentmemory/graph/stats` | +| GET | `/agentmemory/health` | +| POST | `/agentmemory/import` | +| GET | `/agentmemory/insights` | +| POST | `/agentmemory/insights/search` | +| POST | `/agentmemory/leases/acquire` | +| POST | `/agentmemory/leases/release` | +| POST | `/agentmemory/leases/renew` | +| POST | `/agentmemory/lessons` | +| POST | `/agentmemory/lessons/search` | +| POST | `/agentmemory/lessons/strengthen` | +| GET | `/agentmemory/livez` | +| GET | `/agentmemory/memories` | +| GET | `/agentmemory/memories/:id` | +| GET | `/agentmemory/mesh/export` | +| POST | `/agentmemory/mesh/peers` | +| POST | `/agentmemory/mesh/receive` | +| POST | `/agentmemory/mesh/sync` | +| POST | `/agentmemory/migrate` | +| GET | `/agentmemory/next` | +| GET | `/agentmemory/observations` | +| POST | `/agentmemory/observe` | +| POST | `/agentmemory/obsidian/export` | +| POST | `/agentmemory/patterns` | +| GET | `/agentmemory/procedural` | +| GET | `/agentmemory/profile` | +| POST | `/agentmemory/reflect` | +| POST | `/agentmemory/relations` | +| POST | `/agentmemory/remember` | +| POST | `/agentmemory/replay/import-jsonl` | +| GET | `/agentmemory/replay/load` | +| GET | `/agentmemory/replay/sessions` | +| POST | `/agentmemory/routines` | +| POST | `/agentmemory/routines/run` | +| GET | `/agentmemory/routines/status` | +| POST | `/agentmemory/search` | +| GET | `/agentmemory/semantic` | +| POST | `/agentmemory/sentinels` | +| POST | `/agentmemory/sentinels/cancel` | +| POST | `/agentmemory/sentinels/check` | +| POST | `/agentmemory/sentinels/trigger` | +| GET | `/agentmemory/session/by-commit` | +| POST | `/agentmemory/session/commit` | +| POST | `/agentmemory/session/end` | +| POST | `/agentmemory/session/start` | +| GET | `/agentmemory/sessions` | +| GET | `/agentmemory/signals` | +| POST | `/agentmemory/signals/send` | +| POST | `/agentmemory/sketches` | +| POST | `/agentmemory/sketches/add` | +| POST | `/agentmemory/sketches/discard` | +| POST | `/agentmemory/sketches/gc` | +| POST | `/agentmemory/sketches/promote` | +| GET | `/agentmemory/slot` | +| POST | `/agentmemory/slot/append` | +| POST | `/agentmemory/slot/reflect` | +| POST | `/agentmemory/slot/replace` | +| GET | `/agentmemory/slots` | +| POST | `/agentmemory/smart-search` | +| POST | `/agentmemory/snapshot/create` | +| POST | `/agentmemory/snapshot/restore` | +| GET | `/agentmemory/snapshots` | +| POST | `/agentmemory/summarize` | +| GET | `/agentmemory/team/feed` | +| GET | `/agentmemory/team/profile` | +| POST | `/agentmemory/team/share` | +| POST | `/agentmemory/timeline` | +| POST | `/agentmemory/verify` | +| GET | `/agentmemory/viewer` | +| POST | `/agentmemory/vision-embed` | +| POST | `/agentmemory/vision-search` | + diff --git a/plugin/skills/agentmemory-rest-api/SKILL.md b/plugin/skills/agentmemory-rest-api/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..898e94a6af5281a8c55e9ab31c93beed40745a4a --- /dev/null +++ b/plugin/skills/agentmemory-rest-api/SKILL.md @@ -0,0 +1,43 @@ +--- +name: agentmemory-rest-api +description: The agentmemory HTTP REST API surface, the primary protocol for talking to the memory server. Use when calling agentmemory over HTTP, when MCP is unavailable and you need a fallback, or when integrating a host that does not speak MCP. +user-invocable: false +--- + +REST is agentmemory's primary surface. MCP is a bridge on top of it. Every memory operation has an HTTP endpoint under `http://localhost:3111/agentmemory/*`. + +## Quick start + +```bash +# liveness +curl -fsS http://localhost:3111/agentmemory/livez + +# save +curl -X POST http://localhost:3111/agentmemory/remember \ + -H "Content-Type: application/json" \ + -d '{"content":"chose JWT refresh rotation","concepts":["jwt-refresh-rotation"]}' + +# recall +curl -X POST http://localhost:3111/agentmemory/smart-search \ + -H "Content-Type: application/json" \ + -d '{"query":"auth token strategy","limit":5}' +``` + +## Auth + +By default localhost is open and no auth is needed. When `AGENTMEMORY_SECRET` is set, every request needs `Authorization: Bearer $AGENTMEMORY_SECRET`. See agentmemory-config. + +## Conventions + +- Save returns `201`, reads return `200`, validation errors return `400`. +- Handlers whitelist body fields and drop unknown ones, so passing extra keys is safe but ignored. +- The port is configurable with `--port` or `--instance`; streams, viewer, and engine derive from it. + +## See also + +- agentmemory-mcp-tools for the MCP equivalents. +- agentmemory-config for the port quartet and the secret. + +## Reference + +The full endpoint list with methods lives in REFERENCE.md, generated from `src/triggers/api.ts`. diff --git a/plugin/skills/commit-context/EXAMPLES.md b/plugin/skills/commit-context/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..a0fe52cb80027cc39b82f4592c443c90a1845c92 --- /dev/null +++ b/plugin/skills/commit-context/EXAMPLES.md @@ -0,0 +1,71 @@ +# commit-context worked examples + +## 1. Line range with a linked session + +User: "Why is this retry loop here?" (pointing at lines 40-52 of refresh.ts) + +Find the SHA: + +```bash +git blame -L 40,52 src/auth/refresh.ts +# 9a1b2c3d (dev 2026-06-07) ... retry on revoked token +``` + +Look it up: + +```json +memory_commit_lookup { "sha": "9a1b2c3d4e5f60718293a4b5c6d7e8f901234567" } +``` + +Response: + +```json +{ + "commit": { "sha": "9a1b2c3d...", "short": "9a1b2c3", "branch": "main", + "author": "dev", "message": "rotate refresh tokens" }, + "sessions": [ { "id": "7f3a9c21", "project": "app", "observationCount": 14, + "summary": "Reworked refresh rotation" } ] +} +``` + +Present: + +> `9a1b2c3` on `main` by dev: "rotate refresh tokens". Linked to session +> `7f3a9c2` "Auth refresh rework" (14 obs). The retry loop handles a token +> revoked mid-flight, per the session's high-importance observations. + +## 2. Function lookup, commit predates linking + +User: "What was the agent doing when it wrote validateScope?" + +```bash +git log -L :validateScope:src/auth/scope.ts -n 1 +# 1122aabb ... +``` + +```json +memory_commit_lookup { "sha": "1122aabbccddeeff00112233445566778899aabb" } +``` + +Response: + +```json +{ "commit": null } +``` + +Present: + +> `1122aab` predates agent session linking, so there is no recorded session. +> From `git show`: it added `validateScope` to enforce per-token scopes. I can +> show the full diff if useful. + +## 3. Bare path + +User: "Give me context on src/middleware/limit.ts." + +```bash +git log -n 1 -- src/middleware/limit.ts +``` + +Take the SHA, run `memory_commit_lookup`, present commit plus linked session in +the same shape as example 1. diff --git a/plugin/skills/commit-context/SKILL.md b/plugin/skills/commit-context/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..fa782ef5aac466bcb3aad1e60c423e1030ff31b2 --- /dev/null +++ b/plugin/skills/commit-context/SKILL.md @@ -0,0 +1,64 @@ +--- +name: commit-context +description: Trace a file, function, or line back to the agent session that produced its current commit. Use when the user asks "why is this code here", "what was the agent doing when this changed", "who wrote this", or wants context on a specific location in the codebase. +argument-hint: "[file, function, or line]" +user-invocable: true +--- + +The user wants commit context for: $ARGUMENTS + +## Quick start + +```bash +git blame -L 40,52 src/auth/refresh.ts # -> SHA 9a1b2c3d +``` + +```json +memory_commit_lookup { "sha": "9a1b2c3d4e5f60718293a4b5c6d7e8f901234567" } +``` + +Expected output: + +```text +9a1b2c3 on main by dev: "rotate refresh tokens" +Linked session 7f3a9c2 "Auth refresh rework", 14 obs. +``` + +## Why + +Report only what git and the lookup return. When the lookup gives `commit: null`, +the commit predates session linking; do not invent intent. + +## Workflow + +1. Find the SHA: `git blame -L , ` for a line range; + `git log -L ::` for a function; `git log -n 1 -- ` for a + bare path. +2. Look it up: `memory_commit_lookup { "sha": "" }`. +3. Present the commit (sha, short sha, branch, author, message), the linked + session(s) (id, project, started/ended, observation count, summary), and the + importance >= 7 observations via `memory_recall` when available. + +## Anti-patterns + +WRONG: lookup returns `{ "commit": null }`, you narrate "the agent was +refactoring auth" from the diff alone. + +RIGHT: "This commit predates session linking, so there is no recorded agent +session. From `git show`: it changed token rotation in refresh.ts." + +## Checklist + +- SHA came from git blame/log, not a guess. +- `commit: null` reported as "predates linking", no fabricated session. +- Session details quote the lookup response verbatim. +- No intent claimed beyond what observations state. + +## See also + +- `commit-history`: list many agent-linked commits at once. +- `recall`: dig deeper into the linked session's observations. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_commit_lookup` is not available. diff --git a/plugin/skills/commit-history/EXAMPLES.md b/plugin/skills/commit-history/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..d04a6bb6a1786d03697e0023f4f775a345d35bc7 --- /dev/null +++ b/plugin/skills/commit-history/EXAMPLES.md @@ -0,0 +1,71 @@ +# commit-history worked examples + +## 1. Branch filter + +User: "Show agent commits on main." + +Invocation: + +```json +memory_commits { "branch": "main", "limit": 100 } +``` + +Response: + +```json +{ + "commits": [ + { "short": "9a1b2c3", "branch": "main", "authoredAt": "2026-06-07T09:12:00Z", + "message": "rotate refresh tokens", "sessionIds": ["7f3a9c21"], + "observationCount": 14, "files": 3 }, + { "short": "b21d004", "branch": "main", "authoredAt": "2026-06-05T14:40:00Z", + "message": "rate limiter audit", "sessionIds": ["b21d004e"], + "observationCount": 9, "files": 1 } + ] +} +``` + +Present: + +> - `9a1b2c3` main 2026-06-07 "rotate refresh tokens", session `7f3a9c2` (14 obs, 3 files) +> - `b21d004` main 2026-06-05 "rate limiter audit", session `b21d004` (9 obs, 1 file) + +## 2. Bare number as limit + +User: "commit-history 5" + +Treat `5` as the limit: + +```json +memory_commits { "limit": 5 } +``` + +Render the five newest linked commits in the same format. + +## 3. Empty result + +User: "Show agent commits on release-2.0." + +```json +memory_commits { "branch": "release-2.0", "limit": 100 } +``` + +Response: + +```json +{ "commits": [] } +``` + +Present: + +> No agent-linked commits on `release-2.0`. Drop the branch filter to see all +> linked commits, or try a different branch. + +REST fallback for this same call, with encoding: + +```http +GET /agentmemory/commits?branch=release-2.0&limit=100 +``` + +Build it with `URLSearchParams` so a branch like `feat/a&b` becomes +`feat%2Fa%26b` rather than breaking the query. diff --git a/plugin/skills/commit-history/SKILL.md b/plugin/skills/commit-history/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b05c00369918a70c372b6698340617d61e290cdd --- /dev/null +++ b/plugin/skills/commit-history/SKILL.md @@ -0,0 +1,62 @@ +--- +name: commit-history +description: List recent git commits linked to agent sessions, optionally filtered by branch or repo. Use when the user asks "show agent commits", "what has the agent shipped", "list linked commits", or wants commits with their session context. +argument-hint: "[branch=... repo=... limit=...]" +user-invocable: true +--- + +The user wants a list of agent-linked commits. Filter args: $ARGUMENTS + +## Quick start + +```json +memory_commits { "branch": "main", "limit": 20 } +``` + +Expected output: + +```text +9a1b2c3 main 2026-06-07 "rotate refresh tokens" · session 7f3a9c2 (14 obs) +b21d004 main 2026-06-05 "rate limiter audit" · session b21d004 (9 obs) +``` + +## Why + +Render only the commits the tool returned, newest first. An empty result means +the filter matched nothing, not that work is missing. + +## Workflow + +1. Parse `$ARGUMENTS` for `branch=`, `repo=`, + `limit=`. A bare numeric token is the limit. Defaults: no branch, no repo, + limit 100, max 500. +2. Call `memory_commits` with the parsed filters. +3. Render reverse-chronologically: short sha, branch, authored timestamp, first + line of the message, linked session id(s) (first 8) with observation counts, + and file count when `files` is present. +4. Empty result: tell the user the filter matched nothing and suggest dropping + the branch or repo filter. + +## Anti-patterns + +WRONG (REST fallback): concatenate `?branch=` + raw branch name, so a name with +`?`, `&`, or `#` corrupts the query string. + +RIGHT: URL-encode every value with `URLSearchParams`/`encodeURIComponent` before +appending to `GET /agentmemory/commits`. + +## Checklist + +- Filters parsed; bare number treated as limit; limit capped at 500. +- Output is reverse-chronological. +- Session ids and observation counts come straight from the response. +- REST fallback URL-encodes branch, repo, and limit. + +## See also + +- `commit-context`: drill into one commit's session. +- `recall`: search the observations behind a linked session. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_commits` is not available. diff --git a/plugin/skills/forget/EXAMPLES.md b/plugin/skills/forget/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..c391bda000abfae3780df311bd988b07d22c8fde --- /dev/null +++ b/plugin/skills/forget/EXAMPLES.md @@ -0,0 +1,75 @@ +# forget worked examples + +## 1. Delete a leaked secret + +User: "Forget that note where I pasted the API key." + +Search: + +```json +memory_smart_search { "query": "api key", "limit": 20 } +``` + +Response: + +```json +{ + "results": [ + { "id": "abc12345", "sessionId": "7f3a9c21", "title": "Pasted staging API key", + "narrative": "STAGING_KEY=sk-live-..." } + ] +} +``` + +Present and gate: + +> Found 1 match: +> - `abc12345` (session `7f3a9c2`) "Pasted staging API key" +> +> Delete this memory? (yes/no) + +After the user says yes: + +```json +memory_governance_delete { "memoryIds": ["abc12345"], "reason": "user privacy request" } +``` + +Response: + +```json +{ "deleted": 1 } +``` + +Present: + +> Deleted 1 memory (`abc12345`). + +## 2. Drop a whole session's observations + +User: "Delete everything from the throwaway spike session." + +Search, identify the session, then collect every memory id in it: + +```json +memory_smart_search { "query": "spike prototype throwaway", "limit": 20 } +``` + +Response has 4 results all with `sessionId: c98f1100`. Show all four, get a yes, +then pass every id: + +```json +memory_governance_delete { + "memoryIds": ["m1", "m2", "m3", "m4"], + "reason": "drop throwaway spike session" +} +``` + +Never send `{ "sessionId": "c98f1100" }`; the MCP deletes by memory id only. + +## 3. User declines + +User: "Actually, on second thought, keep them." + +Do not call delete. Confirm: + +> Understood, nothing deleted. The 4 memories from session `c98f110` are intact. diff --git a/plugin/skills/forget/SKILL.md b/plugin/skills/forget/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..32ec5396d00af0f7dd2adc497979085e7c9bb123 --- /dev/null +++ b/plugin/skills/forget/SKILL.md @@ -0,0 +1,66 @@ +--- +name: forget +description: Delete specific observations from agentmemory after showing them and getting explicit confirmation. Use when the user says "forget this", "delete memory", "remove that note", or wants to scrub specific data for privacy. +argument-hint: "[what to forget - session ID, file path, or search term]" +user-invocable: true +--- + +The user wants to remove data from agentmemory: $ARGUMENTS + +## Quick start + +```json +memory_smart_search { "query": "old api key in config", "limit": 20 } +``` + +Show the matches, get a yes, then: + +```json +memory_governance_delete { "memoryIds": ["abc12345", "def67890"], "reason": "user privacy request" } +``` + +Expected output: + +```text +Found 2 matching memories. Confirmed. Deleted 2 memories. +``` + +## Why + +This is destructive and irreversible. Show exactly what will be deleted and get +an explicit yes before calling delete. Delete by memory ID, never a bare session. + +## Workflow + +1. Search with `memory_smart_search`, the user's text as `query`, `limit: 20`. +2. Show what matched: session ids, memory ids, titles. Ask for explicit + confirmation. Do not proceed on silence or a vague "sure, whatever". +3. On confirmation, call `memory_governance_delete` with `memoryIds` (array or + comma-separated string) and optional `reason` (default `plugin skill request`). +4. To drop a whole session, collect every memory id in that session from the + search results and pass them all. The MCP does not accept a bare `sessionId`. +5. Report the deletion count back. + +## Anti-patterns + +WRONG: search returns matches, you immediately call `memory_governance_delete` +without showing them or waiting for a yes. + +RIGHT: list the matches, ask "Delete these 2? (yes/no)", and only delete after +an explicit yes. + +## Checklist + +- Matches were shown to the user before any delete. +- An explicit yes was received, not assumed. +- `memoryIds` holds real ids from the search, never a bare `sessionId`. +- Final message states the actual count deleted. + +## See also + +- `remember`: the write side; forget is its undo. +- `recall`: find the exact memory id before deleting. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_smart_search` or `memory_governance_delete` is not available. diff --git a/plugin/skills/handoff/EXAMPLES.md b/plugin/skills/handoff/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..11e1d58460325596f5392d724e4ab71a8431579e --- /dev/null +++ b/plugin/skills/handoff/EXAMPLES.md @@ -0,0 +1,56 @@ +# handoff worked examples + +## 1. Resume with an open question + +User: "Where were we?" + +Project cwd: `/Users/dev/app`. Invocation: + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "cwd": "/Users/dev/app", "title": "Auth refresh rework", + "status": "completed", "startedAt": "2026-06-07T09:00:00Z", + "summary": "Reworked refresh rotation. Open: should logout revoke all device tokens?", + "concepts": ["jwt-refresh-rotation", "logout"] } + ] +} +``` + +Pull supporting context: + +```json +memory_recall { "query": "jwt-refresh-rotation logout", "limit": 10 } +``` + +Present: + +> Resuming `7f3a9c2` "Auth refresh rework". +> **Open question:** should logout revoke all device tokens or just the current one? +> Touched `auth/refresh.ts`, `auth/logout.ts`. Refresh rotation is done. +> **Next step:** decide the revoke scope, then finish `auth/logout.ts`. + +## 2. Sibling-repo guard + +Project cwd: `/Users/dev/repo-a`. Sessions include one with `cwd: +/Users/dev/repo-a-staging`. + +A raw prefix would match `repo-a-staging`. The boundary check rejects it because +`/Users/dev/repo-a-staging` does not equal `/Users/dev/repo-a` and does not start +with `/Users/dev/repo-a/`. Pick the real `repo-a` session instead, or fall back +to the most recent session overall if none matches. + +## 3. Empty session + +User: "Resume." + +If the matched session has zero observations: + +> The most recent session `c98f110` for this project has no recorded +> observations. Nothing to hand off. Want to start fresh from the current state? diff --git a/plugin/skills/handoff/SKILL.md b/plugin/skills/handoff/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3b4e51492559fa3a21828e69e7bbf8eb04ce7ce6 --- /dev/null +++ b/plugin/skills/handoff/SKILL.md @@ -0,0 +1,68 @@ +--- +name: handoff +description: Resume the most recent agent session for the current working directory, leading with any unanswered question. Use when the user says "where were we", "resume", "handoff", "pick up where I left off", or starts a session with no fresh context. +argument-hint: "[optional cwd override]" +user-invocable: true +--- + +The user wants to resume work. Optional cwd override: $ARGUMENTS + +## Quick start + +```json +memory_sessions { "limit": 20 } +``` + +Pick the most recent session whose `cwd` matches this project, then: +`memory_recall { "query": "", "limit": 10 }`. + +Expected output: + +```text +Resuming 7f3a9c2 "Auth refresh rework". +Open question: should logout revoke all device tokens or just the current one? +Next step: decide revoke scope, then update auth/logout.ts. +``` + +## Why + +Match the session by directory boundary, not raw prefix, so a sibling repo never +gets mistaken for this one. Never invent observations for an empty session. + +## Workflow + +1. Resolve the project path: if `$ARGUMENTS` is given, normalize it to absolute + (`path.resolve(process.cwd(), $ARGUMENTS)`); else use the cwd. +2. Call `memory_sessions`. Pick the most recent session whose normalized `cwd` + matches by directory boundary: equality, OR `cwd.startsWith(projectPath + sep)`, + OR `projectPath.startsWith(cwd + sep)`. Prefer `completed` over `abandoned`. + No match: fall back to the single most recent session overall. +3. If the session ended on an unanswered user-facing question, surface it FIRST. + Look in `summary` or recent `conversation` observations whose `narrative` + ends in `?`. +4. Summarize: title/summary, key files, key decisions or errors, using + `memory_recall` on the top concepts, limit 10. +5. End with one concrete "next step?" pointer. + +## Anti-patterns + +WRONG: `session.cwd.startsWith(projectPath)` matches `/repo-a-staging` when the +project is `/repo-a`, resuming the wrong repo's session. + +RIGHT: `session.cwd === projectPath || session.cwd.startsWith(projectPath + sep)`, +a directory-boundary check that cannot cross sibling repos. + +## Checklist + +- cwd override resolved to an absolute, normalized path. +- Match used a directory-boundary check, not a raw prefix. +- Unanswered question (if any) leads the response. +- Empty session is reported plainly, with an offer to start fresh. + +## See also + +- `recap`, `session-history`, `recall`: same session data, broader views. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` or `memory_recall` is not available. diff --git a/plugin/skills/recall/EXAMPLES.md b/plugin/skills/recall/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..8e58c56dc450e20f1b3a2d7b59dd358ecf9db07b --- /dev/null +++ b/plugin/skills/recall/EXAMPLES.md @@ -0,0 +1,74 @@ +# recall worked examples + +## 1. Hit on a past decision + +User: "Did we ever decide how to cache sessions?" + +Invocation: + +```json +memory_smart_search { "query": "session caching decision", "limit": 10 } +``` + +Response: + +```json +{ + "results": [ + { "sessionId": "7f3a9c21", "type": "decision", "title": "Drop Redis for iii state store", + "narrative": "We decided to drop Redis and use the iii-engine state store for session caching.", + "importance": 8 } + ] +} +``` + +Present: + +> Yes. In session `7f3a9c21` you decided to drop Redis and use the iii-engine +> state store for session caching (importance 8). + +## 2. Multiple results across sessions + +User: "Recall anything about the rate limiter." + +Invocation: + +```json +memory_smart_search { "query": "rate limiter", "limit": 10 } +``` + +Response: + +```json +{ + "results": [ + { "sessionId": "b21d004e", "type": "code", "title": "limit.ts counts per-IP", + "narrative": "Rate limiter counts per-IP, not per-user.", "importance": 6 }, + { "sessionId": "c98f1100", "type": "conversation", "title": "Discussed sliding window", + "narrative": "Considered a sliding-window limiter, deferred.", "importance": 4 } + ] +} +``` + +Present them grouped by session, leading with the per-IP code note. + +## 3. No results + +User: "Recall the GraphQL schema migration." + +Invocation: + +```json +memory_smart_search { "query": "graphql schema migration", "limit": 10 } +``` + +Response: + +```json +{ "results": [] } +``` + +Present: + +> No memories matched that. Try `schema change`, `graphql`, or `migration` as +> narrower terms, or `recap this week` to scan recent sessions. diff --git a/plugin/skills/recall/SKILL.md b/plugin/skills/recall/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..00f71fc2e5f737503ae241c025f1bb2af73f2f65 --- /dev/null +++ b/plugin/skills/recall/SKILL.md @@ -0,0 +1,60 @@ +--- +name: recall +description: Search agentmemory for past observations, sessions, and learnings about a topic using hybrid BM25 plus vector plus graph search. Use when the user says "recall", "what did we do about", "did we ever", "have we seen", or needs context from past sessions. +argument-hint: "[search query]" +user-invocable: true +--- + +The user wants to recall past context about: $ARGUMENTS + +## Quick start + +```json +memory_smart_search { "query": "jwt refresh token rotation", "limit": 10 } +``` + +Expected output: + +```text +2 results across 2 sessions. +[importance 8] decision · "Rotate refresh tokens on every use" (session 7f3a9c21) +[importance 5] code · "limit.ts counts per-IP" (session b21d004e) +``` + +## Why + +Only surface what the tool returned. Never fabricate an observation, a session +id, or an importance score. If nothing comes back, say so. + +## Workflow + +1. Call `memory_smart_search` with the user's text as `query` and `limit: 10`. + Pass `project` when the user scopes to a specific repo. +2. Group results by session. +3. For each observation show its type, title, and narrative. +4. Lead with the high-signal observations (importance >= 7). +5. If zero results, suggest 2-3 alternative search terms and stop. Do not guess. + +## Anti-patterns + +WRONG: results are empty, so you write "We probably discussed token expiry last +week" from assumption. + +RIGHT: "No memories matched that query. Try `refresh token`, `session expiry`, +or `auth rotation`." + +## Checklist + +- Every observation shown came from the tool response. +- Results grouped by session, high-importance first. +- Empty results trigger alternative-term suggestions, not invention. +- No session id or score was paraphrased or rounded. + +## See also + +- `remember`: the write side; recall retrieves what it stores. +- `recap`, `handoff`, `session-history`: session-scoped views of the same data. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_smart_search` is not available. diff --git a/plugin/skills/recap/EXAMPLES.md b/plugin/skills/recap/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..4426c8cb4c7992050f051873ba256736c61e5fd6 --- /dev/null +++ b/plugin/skills/recap/EXAMPLES.md @@ -0,0 +1,60 @@ +# recap worked examples + +## 1. This week + +User: "Recap this week." + +Window: last 7 days. Invocation: + +```json +memory_sessions { "limit": 30 } +``` + +Response (after filtering to cwd and the 7-day window): + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "cwd": "/Users/dev/app", "title": "Auth refresh rework", + "startedAt": "2026-06-07T09:00:00Z", "observationCount": 14, "status": "completed", + "concepts": ["jwt-refresh-rotation", "auth-flow"] }, + { "id": "b21d004e", "cwd": "/Users/dev/app", "title": "Rate limiter audit", + "startedAt": "2026-06-05T14:00:00Z", "observationCount": 9, "status": "completed", + "concepts": ["rate-limiter", "per-ip-bug"] } + ] +} +``` + +Per session, pull highlights: + +```json +memory_recall { "query": "jwt-refresh-rotation auth-flow", "limit": 3 } +``` + +Present: + +> **2026-06-07** +> - `7f3a9c2` Auth refresh rework, 14 obs, completed +> - [8] Rotate refresh tokens on every use +> +> **2026-06-05** +> - `b21d004e` Rate limiter audit, 9 obs, completed +> - [7] limit.ts counts per-IP, not per-user +> +> 2 sessions across 2 days, 23 observations. + +## 2. Bare number + +User: "recap 3" + +Treat as `last 3`. Call `memory_sessions { "limit": 3 }`, group by date, same format. + +## 3. Empty window + +User: "Recap today." + +If `memory_sessions` returns no session whose `startedAt` is today and whose +`cwd` matches: + +> No sessions today for this project. The most recent was yesterday, `7f3a9c2` +> Auth refresh rework. Want a recap of that instead? diff --git a/plugin/skills/recap/SKILL.md b/plugin/skills/recap/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b3ea5e9c133a0506ac87107fb9422202e22f48fe --- /dev/null +++ b/plugin/skills/recap/SKILL.md @@ -0,0 +1,63 @@ +--- +name: recap +description: Summarize the last N agent sessions for the current project, grouped by date, with highlight observations per session. Use when the user asks "recap", "what have we been doing", "today", "this week", or wants a rollup of recent work. +argument-hint: "[last N | today | this week]" +user-invocable: true +--- + +The user wants a recap. Time window args: $ARGUMENTS + +## Quick start + +```json +memory_sessions { "limit": 30 } +``` + +Then per surviving session: `memory_recall { "query": "", "limit": 3 }`. + +Expected output: + +```text +2026-06-07 + 7f3a9c2 · "Auth refresh rework" · 14 obs · completed + - [8] Rotate refresh tokens on every use +3 sessions across 2 days, 41 observations. +``` + +## Why + +Only summarize sessions and observations the tools returned. An empty window is +a real answer, not a prompt to invent activity. + +## Workflow + +1. Parse `$ARGUMENTS`: `today` = current local date; `this week` = last 7 days; + `last ` or bare numeric = most recent N; empty = `last 10`. +2. Call `memory_sessions`, filter to the current project (match `cwd` against the + working directory), apply the window, sort by `startedAt` descending. +3. Group survivors by local calendar date (YYYY-MM-DD). +4. Per session list id (first 8), title or first prompt, observation count, + status. Indent 2-3 highlights (importance >= 7) from `memory_recall`. +5. End with "N sessions across M days, K observations." + +## Anti-patterns + +WRONG: window is empty, so you summarize "a productive week of auth work" from +memory of the conversation. + +RIGHT: "No sessions in the last 7 days for this project." + +## Checklist + +- Window parsed correctly from the argument. +- Sessions filtered to the current project's cwd. +- Highlights come from `memory_recall`, not paraphrase. +- Totals line reflects the actual counts shown. + +## See also + +- `handoff`, `session-history`, `recall`: same session data, different lens. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` or `memory_recall` is not available. diff --git a/plugin/skills/remember/EXAMPLES.md b/plugin/skills/remember/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..e220cb79a0a37a58d6b1e41de8979f6c4ba49a01 --- /dev/null +++ b/plugin/skills/remember/EXAMPLES.md @@ -0,0 +1,67 @@ +# remember worked examples + +## 1. Saving a decision + +User: "Remember that we decided to drop Redis and use the iii-engine state store for session caching." + +Invocation: + +```json +memory_save { + "content": "We decided to drop Redis and use the iii-engine state store for session caching to remove a moving part.", + "concepts": "session-caching, iii-state-store, dropped-redis", + "files": "" +} +``` + +Response: + +```json +{ "id": "7f3a9c21", "concepts": ["session-caching", "iii-state-store", "dropped-redis"], "saved": true } +``` + +Present: + +> Saved. Tagged it `session-caching`, `iii-state-store`, `dropped-redis`, so a +> later recall on caching or Redis will surface this decision. + +## 2. Saving a code-specific gotcha + +User: "Save this: the rate limiter in middleware/limit.ts counts per-IP, not per-user, so logged-in users on shared IPs collide." + +Invocation: + +```json +memory_save { + "content": "The rate limiter in middleware/limit.ts counts per-IP, not per-user, so logged-in users on shared IPs collide.", + "concepts": "rate-limiter, per-ip-bug, shared-ip-collision", + "files": "src/middleware/limit.ts" +} +``` + +Response: + +```json +{ "id": "b21d004e", "concepts": ["rate-limiter", "per-ip-bug", "shared-ip-collision"], "saved": true } +``` + +Present: + +> Saved memory `b21d004e` referencing `src/middleware/limit.ts`. Concepts: +> `rate-limiter`, `per-ip-bug`, `shared-ip-collision`. + +## 3. Vague request, no files + +User: "Remember this for later." + +Ask once for the substance, then save: + +```json +memory_save { + "content": "Staging deploys must run the migration job before the app rollout, never after.", + "concepts": "staging-deploy, migration-ordering, rollout-sequence", + "files": "" +} +``` + +Present the confirmation with the concepts echoed back. diff --git a/plugin/skills/remember/SKILL.md b/plugin/skills/remember/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..83e950d6e7f8e1feb2dd40c566e5146cd0c29efb --- /dev/null +++ b/plugin/skills/remember/SKILL.md @@ -0,0 +1,61 @@ +--- +name: remember +description: Save an insight, decision, or learning to agentmemory's long-term storage with searchable concept tags. Use when the user says "remember this", "save this", "note that", "don't forget", or wants to preserve knowledge for future sessions. +argument-hint: "[what to remember]" +user-invocable: true +--- + +The user wants to save this to long-term memory: $ARGUMENTS + +## Quick start + +```json +memory_save { + "content": "We rotate JWT refresh tokens on every use; the old token is revoked server-side in auth/refresh.ts.", + "concepts": "jwt-refresh-rotation, token-revocation, auth-flow", + "files": "src/auth/refresh.ts" +} +``` + +Expected output: + +```text +Saved memory abc12345 with 3 concepts: jwt-refresh-rotation, token-revocation, auth-flow. +``` + +## Why + +A memory is only as useful as the terms that retrieve it. Tag with specific +concepts so a future `recall` finds it, and preserve the user's own phrasing. + +## Workflow + +1. Pull the core insight, decision, or fact out of `$ARGUMENTS`. +2. Extract 2-5 lowercased concept phrases. Prefer specific over generic + (`jwt-refresh-rotation` beats `auth`). +3. Extract referenced file paths (absolute or repo-relative). Empty if none. +4. Call `memory_save` with `content`, `concepts` (comma-separated string), and + `files` (comma-separated string). +5. Confirm the save and echo the concepts so the user knows the retrieval terms. + +## Anti-patterns + +WRONG: `concepts: "stuff, code, notes"` (generic tags nothing can find later). + +RIGHT: `concepts: "jwt-refresh-rotation, token-revocation"` (specific, retrievable). + +## Checklist + +- Content preserves the user's phrasing, not a paraphrase. +- Concepts are specific, lowercased, 2-5 items. +- File paths are real references, not guesses. +- Confirmation echoes the exact concepts tagged. + +## See also + +- `recall`: retrieve what you save here (the pair to this skill). +- `forget`: remove a memory you saved by mistake. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_save` is not available. diff --git a/plugin/skills/session-history/EXAMPLES.md b/plugin/skills/session-history/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..e58654f62482a130edab2ba608f3a2af3e70c2ea --- /dev/null +++ b/plugin/skills/session-history/EXAMPLES.md @@ -0,0 +1,59 @@ +# session-history worked examples + +## 1. Standard timeline + +User: "Show me the session history." + +Invocation: + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "project": "app", "startedAt": "2026-06-07T09:00:00Z", + "status": "completed", "observationCount": 14, + "summary": "Reworked refresh rotation", + "highlights": [ { "type": "decision", "title": "Rotate refresh tokens on every use" } ] }, + { "id": "b21d004e", "project": "app", "startedAt": "2026-06-05T14:00:00Z", + "status": "completed", "observationCount": 9, + "highlights": [ { "type": "code", "title": "limit.ts counts per-IP" } ] } + ] +} +``` + +Present: + +> - `7f3a9c2` app, 2026-06-07 09:00, completed, 14 obs +> - decision: Rotate refresh tokens on every use (summary: Reworked refresh rotation) +> - `b21d004` app, 2026-06-05 14:00, completed, 9 obs +> - code: limit.ts counts per-IP + +## 2. Session with no observations + +If a returned session has `observationCount: 0`, list it but say so: + +> - `c98f110` app, 2026-06-04 11:00, abandoned, 0 obs (no recorded work) + +## 3. Empty history + +User: "What did we do last time?" + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ "sessions": [] } +``` + +Present: + +> No recorded sessions yet for this project. Once you work with memory capture +> on, they will show here. Use `remember` to save a note now. diff --git a/plugin/skills/session-history/SKILL.md b/plugin/skills/session-history/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..dd5147981a5a3813b6679557d067d58b85de420e --- /dev/null +++ b/plugin/skills/session-history/SKILL.md @@ -0,0 +1,61 @@ +--- +name: session-history +description: Show what happened in recent past sessions on this project as a clean timeline. Use when the user asks "what did we do last time", "session history", "past sessions", or wants an overview of previous work. +user-invocable: true +--- + +The user wants an overview of recent sessions on this project. + +## Quick start + +```json +memory_sessions { "limit": 20 } +``` + +Expected output: + +```text +7f3a9c2 · app · 2026-06-07 09:00 · completed · 14 obs + - decision: Rotate refresh tokens on every use +b21d004 · app · 2026-06-05 14:00 · completed · 9 obs + - code: limit.ts counts per-IP +``` + +## Why + +Only show sessions and observations the tool returned. An empty history is a +real answer, never a cue to invent past work. + +## Workflow + +1. Call `memory_sessions` with `limit: 20` for a meaningful window. +2. Present in reverse chronological order: session id (first 8), project, start + time, status. +3. For sessions with observations, show the key highlights (type plus title). +4. Note the total observation count per session. +5. When a session summary exists, surface its title and the key decisions. + +## Anti-patterns + +WRONG: the tool returns two sessions, you describe "several sessions of steady +progress" and add ones you remember from the conversation. + +RIGHT: show exactly the two sessions returned, each with its real id, status, and +observation count. + +## Checklist + +- Every session shown came from the tool response. +- Order is reverse-chronological. +- Per-session observation counts match the response. +- No session or highlight was invented or merged. + +## See also + +- `recap`: same data grouped by date with highlights. +- `handoff`: jump straight into the most recent session. +- `recall`: search across all sessions by topic. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` is not available. diff --git a/plugin/skills/write-agentmemory-skill/SKILL.md b/plugin/skills/write-agentmemory-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d46a1910c21e7c0dc79a5edb65d2d99efad586d1 --- /dev/null +++ b/plugin/skills/write-agentmemory-skill/SKILL.md @@ -0,0 +1,40 @@ +--- +name: write-agentmemory-skill +description: The house format and rules for writing or updating an agentmemory skill. Use when adding a new skill, restructuring an existing one, or reviewing a skill contribution for consistency. +user-invocable: false +--- + +agentmemory skills follow one tiered format so they stay skimmable, accurate, and current. Match it exactly. + +## Directory layout + +```text +plugin/skills// + SKILL.md (required, under 100 lines) + REFERENCE.md (optional, dense facts; auto-generate data tables) + EXAMPLES.md (optional, worked transcripts) +``` + +## SKILL.md rules + +- Frontmatter: `name`, `description`, optional `argument-hint`, and `user-invocable`. Set `user-invocable: true` only for skills the user runs as a slash command; reference and knowledge skills are `false`. +- Description is two sentences and the only thing the agent sees when deciding to load the skill. Sentence one states the capability. Sentence two starts "Use when" and lists concrete triggers. Keep it distinct from sibling skills, under 1024 chars, third person. +- Body order: Quick start (one concrete example), Why (the governing principle), Workflow (numbered steps with decision gates), Anti-patterns (a WRONG vs RIGHT callout for the top mistake), Checklist, See also (cross-link siblings), Reference or Troubleshooting pointer. +- Stay under 100 lines. Move dense facts to REFERENCE.md and examples to EXAMPLES.md. +- Cross-references link one level deep only. Shared recovery steps live in `../_shared/TROUBLESHOOTING.md`, never inlined. + +## Keep it current + +Facts that exist in source (tool names and parameters, REST endpoints, env vars, connect adapters, hook events) are generated, never hand-typed. Edit the source, then run `npm run skills:gen`. CI runs `npm run skills:check` and fails on drift, so generated tables cannot fall behind the code. + +## Style + +No external or competitor product names. No emojis. No em-dashes. No filler. State the thing and stop. + +## Checklist + +- Description has a "Use when" sentence with real triggers. +- SKILL.md is under 100 lines. +- No time-sensitive claims and no duplicated troubleshooting block. +- Concrete example present; generated facts come from the generator. +- Cross-links resolve and go one level deep. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8a4607b84825d98552cd25c63c1dce2e6e471fa4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +flask>=3.0.0 +flask-sock>=0.7.0 +pymysql>=1.1.0 +requests>=2.31.0 +websockets>=12.0 +python-dateutil>=2.8.2 +huggingface_hub>=0.20.0 + diff --git a/scratch_diff.txt b/scratch_diff.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a09e53fce71ceee83bec41f55ceaa6504de27d1 --- /dev/null +++ b/scratch_diff.txt @@ -0,0 +1,689 @@ +=== Diff for src/app.py === +--- agentmemory/src/app.py ++++ agentmemory-python/src/app.py +@@ -34,7 +34,7 @@ + from db import StateKV + import search + import functions +-from functions import KV ++from functions import KV, query_audit + + app = Flask(__name__) + # Enable CORS for all routes (important for client scripts connecting locally) +@@ -358,42 +358,6 @@ + sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) + return jsonify({"success": True, "sessions": sessions}), 200 + +-@app.route("/agentmemory/replay/load", methods=["GET"]) +-def api_replay_load(): +- auth_err = check_auth() +- if auth_err: +- return auth_err +- +- session_id = request.args.get("sessionId") +- if not session_id: +- return jsonify({"error": "sessionId is required"}), 400 +- +- session = kv.get(KV.sessions, session_id) +- obs = kv.list(KV.observations(session_id)) +- +- import replay_import +- timeline = replay_import.project_timeline(obs) +- return jsonify({"success": True, "timeline": timeline, "session": session}), 200 +- +-@app.route("/agentmemory/replay/import-jsonl", methods=["POST"]) +-def api_replay_import_jsonl(): +- auth_err = check_auth() +- if auth_err: +- return auth_err +- +- try: +- body = request.get_json(force=True) or {} +- path = body.get("path") +- max_files = body.get("maxFiles") +- +- import replay_import +- res = replay_import.import_jsonl_data(kv, path=path, max_files=max_files) +- +- status_code = 200 if res.get("success", True) else 400 +- return jsonify(res), status_code +- except Exception as e: +- return jsonify({"error": str(e), "success": False}), 500 +- + @app.route("/agentmemory/session/start", methods=["POST"]) + def api_session_start(): + auth_err = check_auth() +@@ -895,12 +859,292 @@ + auth_err = check_auth() + if auth_err: + return auth_err +- ++ + project = request.args.get("project") + if not project: +- return jsonify({"error": "project query param is required"}), 400 ++ sessions = kv.list(KV.sessions) ++ projects = sorted(set(s.get("project", "") for s in sessions if s.get("project"))) ++ return jsonify({"projects": projects, "success": True}), 200 ++ + res = functions.get_project_profile(kv, project) ++ ++ # Stored profile may lack topConcepts/topFiles — compute from observations if empty ++ if not res.get("topConcepts") and not res.get("topFiles"): ++ import re as _re, json as _j, os.path as _osp ++ from collections import Counter ++ sessions = kv.list(KV.sessions) ++ project_sessions = [s for s in sessions if s.get("project") == project] ++ concept_counts = Counter() ++ file_counts = Counter() ++ ++ def _harvest_file(path, fc, cc): ++ if not isinstance(path, str) or not path: ++ return ++ fc[path] += 1 ++ # dirname components → concepts ++ parts = _re.split(r'[\\/]', path) ++ fname = parts[-1] if parts else "" ++ # dir components (skip drive letters, temp paths) ++ skip = {"tmp", "temp", "claude", "appdata", "local", "users", "windows"} ++ for part in parts[:-1]: ++ p = part.lower().strip() ++ if p and len(p) > 2 and p not in skip and not _re.match(r'^[a-z]:|^\.|^--', p): ++ cc[p] += 1 ++ # file stem → concept ++ stem = _osp.splitext(fname)[0] ++ if stem and len(stem) > 2: ++ cc[stem.lower()] += 1 ++ # extension → technology concept ++ ext = _osp.splitext(fname)[1].lstrip(".") ++ if ext in ("py", "ts", "js", "jsx", "tsx", "go", "rs", "java", "cs", "cpp"): ++ cc[ext] += 1 ++ ++ for s in project_sessions: ++ sid = s.get("id", "") ++ if not sid: ++ continue ++ for o in kv.list(KV.observations(sid)): ++ # top-level concepts / files ++ for c in (o.get("concepts") or []): ++ if isinstance(c, str) and c: ++ concept_counts[c] += 1 ++ for f in (o.get("files") or []): ++ _harvest_file(f, file_counts, concept_counts) ++ # toolName → concept ++ tn = o.get("toolName") ++ if tn: ++ concept_counts[tn] += 1 ++ # toolInput path fields ++ ti = o.get("toolInput") ++ if isinstance(ti, str): ++ try: ti = _j.loads(ti) ++ except Exception: ti = {} ++ if isinstance(ti, dict): ++ for fk in ("path", "file_path", "file", "filename"): ++ _harvest_file(ti.get(fk, ""), file_counts, concept_counts) ++ # narrative may be JSON string with path/tool info ++ narr = o.get("narrative") or o.get("raw") or "" ++ if isinstance(narr, str) and narr.startswith("{"): ++ try: ++ nd = _j.loads(narr) ++ if isinstance(nd, dict): ++ tn2 = nd.get("toolName") or nd.get("tool_name") ++ if tn2: concept_counts[tn2] += 1 ++ for fk in ("path", "file_path", "file", "filename"): ++ _harvest_file(nd.get(fk, ""), file_counts, concept_counts) ++ except Exception: ++ pass ++ ++ # memories for this project ++ for m in kv.list(KV.memories): ++ if m.get("project") == project: ++ for c in (m.get("concepts") or []): ++ if c: concept_counts[c] += 1 ++ for f in (m.get("files") or []): ++ _harvest_file(f, file_counts, concept_counts) ++ ++ res["topConcepts"] = [{"concept": c, "frequency": n} for c, n in concept_counts.most_common(20)] ++ res["topFiles"] = [{"file": f, "frequency": n} for f, n in file_counts.most_common(20)] ++ res["sessionCount"] = len(project_sessions) ++ + return jsonify(res), 200 ++ ++# ===================================================================== ++# Missing endpoints the JS viewer calls ++# ===================================================================== ++ ++@app.route("/agentmemory/memories", methods=["GET"]) ++def api_memories_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ ++ latest_only = request.args.get("latest", "false").lower() == "true" ++ limit = int(request.args.get("limit", "500")) ++ all_mems = kv.list(KV.memories) ++ if latest_only: ++ all_mems = [m for m in all_mems if m.get("isLatest") is not False] ++ all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True) ++ return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200 ++ ++@app.route("/agentmemory/graph/stats", methods=["GET"]) ++def api_graph_stats(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ nodes = kv.list(KV.graphNodes) ++ edges = kv.list(KV.graphEdges) ++ return jsonify({"nodes": len(nodes), "edges": len(edges), "success": True}), 200 ++ ++@app.route("/agentmemory/semantic", methods=["GET"]) ++def api_semantic_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ items = kv.list(KV.semantic) ++ return jsonify({"items": items, "total": len(items)}), 200 ++ ++@app.route("/agentmemory/procedural", methods=["GET"]) ++def api_procedural_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ items = kv.list(KV.procedural) ++ return jsonify({"items": items, "total": len(items)}), 200 ++ ++@app.route("/agentmemory/crystals", methods=["GET"]) ++def api_crystals_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ items = kv.list(KV.crystals) ++ return jsonify({"crystals": items, "total": len(items)}), 200 ++ ++@app.route("/agentmemory/actions", methods=["GET"]) ++def api_actions_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ limit = int(request.args.get("limit", "200")) ++ status = request.args.get("status") ++ items = kv.list(KV.actions) ++ if status: ++ items = [a for a in items if a.get("status") == status] ++ items.sort(key=lambda a: a.get("updatedAt", ""), reverse=True) ++ return jsonify({"actions": items[:limit], "total": len(items)}), 200 ++ ++@app.route("/agentmemory/actions", methods=["POST"]) ++def api_action_create(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ try: ++ body = request.get_json(force=True) or {} ++ action_id = functions.generate_id("act") ++ from datetime import datetime, timezone ++ now = datetime.now(timezone.utc).isoformat() ++ action = { ++ "id": action_id, ++ "title": body.get("title", ""), ++ "description": body.get("description"), ++ "priority": body.get("priority", 0), ++ "status": body.get("status", "pending"), ++ "tags": body.get("tags", []), ++ "sessionId": body.get("sessionId"), ++ "createdAt": now, ++ "updatedAt": now, ++ } ++ kv.set(KV.actions, action_id, action) ++ return jsonify({"action": action, "success": True}), 200 ++ except Exception as e: ++ return jsonify({"error": str(e)}), 400 ++ ++@app.route("/agentmemory/actions/", methods=["PATCH"]) ++def api_action_update(action_id): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ try: ++ body = request.get_json(force=True) or {} ++ existing = kv.get(KV.actions, action_id) ++ if not existing: ++ return jsonify({"error": "not found"}), 404 ++ from datetime import datetime, timezone ++ existing.update({k: v for k, v in body.items() if k not in ("id", "createdAt")}) ++ existing["updatedAt"] = datetime.now(timezone.utc).isoformat() ++ kv.set(KV.actions, action_id, existing) ++ return jsonify({"action": existing, "success": True}), 200 ++ except Exception as e: ++ return jsonify({"error": str(e)}), 400 ++ ++@app.route("/agentmemory/frontier", methods=["GET"]) ++def api_frontier(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ items = kv.list(KV.actions) ++ frontier = [a for a in items if a.get("status") in ("pending", "active")] ++ frontier.sort(key=lambda a: (-(a.get("priority") or 0), a.get("createdAt", ""))) ++ return jsonify({"frontier": frontier[:50], "total": len(frontier)}), 200 ++ ++@app.route("/agentmemory/insights", methods=["GET"]) ++def api_insights_list(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ limit = int(request.args.get("limit", "200")) ++ items = kv.list(KV.insights) ++ items.sort(key=lambda x: x.get("createdAt", ""), reverse=True) ++ return jsonify({"insights": items[:limit], "total": len(items)}), 200 ++ ++@app.route("/agentmemory/replay/load", methods=["GET"]) ++def api_replay_load(): ++ auth_err = check_auth() ++ if auth_err: ++ return auth_err ++ session_id = request.args.get("sessionId") ++ if not session_id: ++ return jsonify({"error": "sessionId required"}), 400 ++ session = kv.get(KV.sessions, session_id) ++ if not session: ++ return jsonify({"error": "session not found"}), 404 ++ obs = kv.list(KV.observations(session_id)) ++ obs.sort(key=lambda o: o.get("timestamp", "")) ++ ++ from dateutil import parser as dtparser ++ session_start = session.get("startedAt", "") ++ try: ++ t0_ms = dtparser.parse(session_start).timestamp() * 1000 if session_start else None ++ except Exception: ++ t0_ms = None ++ ++ _hook_kind = { ++ "prompt_submit": "prompt", ++ "post_tool_use": "tool_call", ++ "post_tool_failure": "tool_error", ++ "subagent_stop": "response", ++ "task_completed": "response", ++ "notification": "response", ++ } ++ ++ events = [] ++ for o in obs: ++ ts = o.get("timestamp", "") ++ try: ++ t_ms = dtparser.parse(ts).timestamp() * 1000 if ts else 0 ++ except Exception: ++ t_ms = 0 ++ offset_ms = max(0, t_ms - t0_ms) if t0_ms is not None else t_ms ++ ++ hook = o.get("hookType", "") ++ kind = _hook_kind.get(hook, "prompt") ++ ++ # obs fields are top-level (no data wrapper) ++ tool_name = o.get("toolName") ++ tool_input = o.get("toolInput") ++ tool_output = o.get("toolOutput") ++ ++ label = (o.get("userPrompt") or ++ o.get("narrative") or o.get("title") or o.get("summary") or ++ tool_name or ++ (o.get("raw") or "")[:80] or hook) ++ if isinstance(label, str): ++ label = label[:120] ++ ++ events.append({ ++ "kind": kind, ++ "label": label, ++ "offsetMs": offset_ms, ++ "ts": ts, ++ "body": o.get("narrative") or o.get("raw") or o.get("summary") or "", ++ "toolName": tool_name, ++ "toolInput": tool_input, ++ "toolOutput": tool_output, ++ }) ++ ++ total_ms = (events[-1]["offsetMs"] + 1000) if events else 0 ++ timeline = {"events": events, "eventCount": len(events), "totalDurationMs": total_ms} ++ return jsonify({"session": session, "timeline": timeline, "success": True}), 200 + + @app.route("/agentmemory/auto-forget", methods=["POST"]) + def api_auto_forget(): +@@ -1191,6 +1435,311 @@ + return jsonify({"error": str(e)}), 500 + + # ===================================================================== ++# Agent Discovery Endpoint (/agent.md and /auth.md) ++# ===================================================================== ++ ++AGENT_MD_TEMPLATE = """# AgentMemory — Agent Connection Guide ++ ++> This document is auto-generated. Fetch it fresh each session so you always have current values. ++ ++## 1. Server ++ ++| Field | Value | ++|-------|-------| ++| Base URL | `http://127.0.0.1:{port}` | ++| API prefix | `/agentmemory` | ++| Liveness | `GET http://127.0.0.1:{port}/agentmemory/livez` (no auth) | ++| Auth required | `{auth_required}` | ++| Auth header | `Authorization: Bearer ` | ++ ++{auth_note} ++ ++--- ++ ++## 2. Quick-Start: Minimum Viable Session ++ ++Do these in order at the start of every session: ++ ++``` ++1. POST /agentmemory/session/start ← register yourself ++2. POST /agentmemory/context ← inject past memory into your system prompt ++ ... do work, call observe after each tool use ... ++3. POST /agentmemory/session/end ← mark session complete ++``` ++ ++### 2a. Start a session ++ ++```http ++POST /agentmemory/session/start ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "sessionId": "", ++ "project": "", ++ "cwd": "", ++ "agentId": "", ++ "title": "" ++}} ++``` ++ ++Response includes `context` — paste it into your system prompt before answering. ++ ++### 2b. Compile context (also works mid-session) ++ ++```http ++POST /agentmemory/context ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "sessionId": "", ++ "project": "", ++ "budget": 2000 ++}} ++``` ++ ++Returns `context` string wrapped in `` tags. Insert verbatim. ++ ++### 2c. Log an observation (call after every significant tool use) ++ ++```http ++POST /agentmemory/agent/observe ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "agentId": "", ++ "sessionId": "", ++ "project": "", ++ "cwd": "", ++ "text": "", ++ "type": "tool | command | thought | error | result | conversation | other", ++ "title": "" ++}} ++``` ++ ++### 2d. Save a long-term memory (decisions, patterns, preferences) ++ ++```http ++POST /agentmemory/agent/remember ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "agentId": "", ++ "project": "", ++ "content": "", ++ "type": "fact | preference | architecture | bug | workflow | pattern", ++ "concepts": "auth, jwt, middleware", ++ "files": "src/middleware/auth.ts, tests/auth.test.ts" ++}} ++``` ++ ++### 2e. End session ++ ++```http ++POST /agentmemory/session/end ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "sessionId": "" ++}} ++``` ++ ++--- ++ ++## 3. MCP Tools (JSON-RPC style) ++ ++Call via: `POST /agentmemory/mcp/tools` ++ ++```http ++POST /agentmemory/mcp/tools ++Content-Type: application/json ++{auth_header_example} ++ ++{{ ++ "name": "", ++ "arguments": {{ ... }} ++}} ++``` ++ ++| Tool | Required args | Description | ++|------|---------------|-------------| ++| `memory_recall` | `query` | BM25+vector hybrid search over all past observations | ++| `memory_smart_search` | `query` | Same as recall with progressive disclosure | ++| `memory_save` | `content` | Save long-term memory (type, concepts, files optional) | ++| `memory_sessions` | — | List recent sessions with observation counts | ++| `memory_timeline` | `anchor` | Observations around a date or keyword anchor | ++| `memory_profile` | `project` | Top concepts, files, conventions for a project | ++| `memory_lesson_save` | `content` | Save a lesson (auto-strengthens duplicates) | ++| `memory_lesson_recall` | `query` | Search lessons scored by confidence + recency | ++| `agent_observe` | `agentId`, `sessionId`, `project`, `text` | Log an observation (same as REST) | ++| `agent_remember` | `agentId`, `content`, `project` | Save memory (same as REST) | ++ ++Get full schemas: `GET /agentmemory/mcp/tools` ++ ++--- ++ ++## 4. Full REST Endpoint Reference ++ ++All endpoints require `Authorization: Bearer ` when auth is enabled. ++Prefix every path with `http://127.0.0.1:{port}`. ++ ++### Session Management ++ ++| Method | Path | Key body fields | Notes | ++|--------|------|-----------------|-------| ++| `POST` | `/agentmemory/session/start` | `sessionId`, `project`, `cwd`, `agentId` | Returns `session` + `context` | ++| `POST` | `/agentmemory/session/end` | `sessionId` | Marks status=completed | ++| `GET` | `/agentmemory/sessions` | — | List all sessions | ++| `GET` | `/agentmemory/observations?sessionId=` | — | Observations for a session | ++| `POST` | `/agentmemory/session/commit` | `sha`, `sessionId`, `branch`, `message` | Link a git commit to a session | ++| `GET` | `/agentmemory/session/by-commit?sha=` | — | Sessions linked to a commit | ++| `GET` | `/agentmemory/commits` | `branch`, `repo`, `limit` | List tracked commits | ++ ++### Observations ++ ++| Method | Path | Key body fields | Notes | ++|--------|------|-----------------|-------| ++| `POST` | `/agentmemory/observe` | `sessionId`, `hookType`, `timestamp`, `data` | Raw hook payload | ++| `POST` | `/agentmemory/agent/observe` | `agentId`, `sessionId`, `project`, `text`, `type` | Simplified agent endpoint | ++ ++`hookType` values: `post_tool_use`, `post_tool_failure`, `prompt_submit`, `subagent_stop`, `task_completed`, `notification` ++ ++### Memory ++ ++| Method | Path | Key body fields | Notes | ++|--------|------|-----------------|-------| ++| `POST` | `/agentmemory/remember` | `content`, `type`, `concepts[]`, `files[]`, `project` | Supersedes similar memories automatically | ++| `POST` | `/agentmemory/agent/remember` | `agentId`, `content`, `project`, `type`, `concepts`, `files` | Simplified agent endpoint | ++| `POST` | `/agentmemory/forget` | `memoryId` OR `sessionId` [+ `observationIds[]`] | Delete memory/session/observations | ++| `POST` | `/agentmemory/evolve` | `memoryId`, `newContent`, `newTitle` | Version a memory (creates new, marks old superseded) | ++| `POST` | `/agentmemory/search` | `query`, `limit` | Hybrid BM25+vector search | ++| `POST` | `/agentmemory/context` | `sessionId`, `project`, `budget` | Compile context block for injection | ++ ++Memory `type` values: `fact`, `preference`, `architecture`, `bug`, `workflow`, `pattern` ++ ++### Lessons ++ ++| Method | Path | Key body fields | Notes | ++|--------|------|-----------------|-------| ++| `POST` | `/agentmemory/lessons` | `content`, `context`, `project`, `confidence`, `tags[]` | Create/strengthen (duplicate = auto-reinforce) | ++| `GET` | `/agentmemory/lessons` | `project`, `minConfidence`, `limit` | List lessons | ++| `POST` | `/agentmemory/lessons/search` | `query`, `project`, `limit` | Keyword search scored by confidence×recency | ++| `POST` | `/agentmemory/lessons/strengthen` | `lessonId` | Manually reinforce a lesson (+0.1 confidence) | ++ ++### Memory Slots (Pinned Context) ++ ++Slots are named text buffers injected into every context compilation. ++ ++| Method | Path | Key body/query fields | Notes | ++|--------|------|-----------------------|-------| ++| `GET` | `/agentmemory/slots` | — | List all slots | ++| `GET` | `/agentmemory/slot?label=` | — | Get single slot | ++| `POST` | `/agentmemory/slot` | `label`, `content`, `scope`, `sizeLimit`, `pinned` | Create slot | ++| `POST` | `/agentmemory/slot/append` | `label`, `text` | Append text to slot | ++| `POST` | `/agentmemory/slot/replace` | `label`, `content` | Replace slot content | ++| `DELETE` | `/agentmemory/slot?label=` | — | Delete slot | ++| `POST` | `/agentmemory/slot/reflect` | `sessionId`, `maxObservations` | Auto-populate slots from session observations | ++ ++Default slot labels: `persona`, `user_preferences`, `tool_guidelines`, `project_context`, `guidance`, `pending_items`, `session_patterns`, `self_notes` ++ ++### Knowledge Graph & Analytics ++ ++| Method | Path | Key body/query fields | Notes | ++|--------|------|-----------------------|-------| ++| `GET` | `/agentmemory/relations` | — | List all knowledge graph edges | ++| `POST` | `/agentmemory/relations` | `sourceId`, `targetId`, `type` | Add a relation edge | ++| `POST` | `/agentmemory/timeline` | `anchor`, `project`, `before`, `after` | Observations around anchor | ++| `GET` | `/agentmemory/profile?project=` | — | Project profile (top concepts/files) | ++| `GET` | `/agentmemory/audit` | `operation`, `limit` | Audit log | ++| `GET` | `/agentmemory/profile` | `project` (optional) | Project profile; omit `project` to list all known projects | ++| `GET` | `/agentmemory/actions` | `limit`, `status` | List actions | ++| `POST` | `/agentmemory/actions` | `title`, `description`, `priority`, `tags[]`, `status` | Create action | ++| `PATCH`| `/agentmemory/actions/` | any action fields | Update action | ++| `GET` | `/agentmemory/frontier` | — | Pending+active actions sorted by priority | ++| `GET` | `/agentmemory/insights` | `limit` | List insights | ++| `GET` | `/agentmemory/replay/sessions` | — | Sessions list for replay | ++| `GET` | `/agentmemory/replay/load?sessionId=` | — | Full session + ordered observations for replay | ++| `POST` | `/agentmemory/auto-forget` | `dryRun` | Evict stale observations | ++ ++### Health & Config ++ ++| Method | Path | Auth | Notes | ++|--------|------|------|-------| ++| `GET` | `/agentmemory/livez` | No | Liveness check | ++| `GET` | `/agentmemory/health` | Yes | Full health + version | ++| `GET` | `/agentmemory/config/flags` | Yes | Feature flags (graph, consolidation, compression) | ++ ++--- ++ ++## 5. WebSocket Live Stream ++ ++``` ++ws://127.0.0.1:{port}/stream/mem-live/viewer ++``` ++ ++Connect to receive real-time events. Message types: ++- `raw_observation` — raw hook payload as received ++- `compressed_observation` — after synthetic compression + indexing ++ ++No auth on the WebSocket endpoint. ++ ++--- ++ ++## 6. Agent Identity & Scope Isolation ++ ++Set `AGENT_ID` env var on the server to scope all read operations to a single agent. ++Set `AGENTMEMORY_AGENT_SCOPE=isolated` to enforce per-agent isolation. ++ ++Always pass `agentId` in every request body — it's stored on every observation/memory and enables per-agent filtering via `?agentId=` on list endpoints. ++ ++--- ++ ++## 7. Secrets Are Redacted ++ ++Any text containing API keys, Bearer tokens, passwords, or JWTs is automatically redacted to `[REDACTED_SECRET]` before storage. Wrap sensitive blocks in `...` tags to force redaction. ++ ++--- ++ ++*Generated by agentmemory v{version} — `GET /agent.md` to refresh* ++""" ++ ++@app.route("/agent.md", methods=["GET"]) ++@app.route("/auth.md", methods=["GET"]) ++def agent_discovery(): ++ port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111"))) ++ secret = os.getenv("AGENTMEMORY_SECRET") ++ auth_required = "yes" if secret else "no" ++ ++ if secret: ++ auth_note = ( ++ "> **Auth is enabled.** Add `Authorization: Bearer ` to every request.\n" ++ "> The secret is set via `AGENTMEMORY_SECRET` env var in `~/.agentmemory/.env`." ++ ) ++ auth_header_example = 'Authorization: Bearer ' ++ else: ++ auth_note = ( ++ "> **Auth is disabled.** No `Authorization` header needed — all endpoints are open." ++ ) ++ auth_header_example = '' ++ ++ md = AGENT_MD_TEMPLATE.format( ++ port=port, ++ auth_required=auth_required, ++ auth_note=auth_note, ++ auth_header_example=auth_header_example, ++ version="0.9.8", ++ ) ++ ++ response = make_response(md) ++ response.headers["Content-Type"] = "text/markdown; charset=utf-8" ++ response.headers["Cache-Control"] = "no-cache" ++ return response ++ ++# ===================================================================== + # Lifecycle Helpers + # ===================================================================== + + + +=== Diff for src/viewer/index.html === +--- agentmemory/src/viewer/index.html ++++ agentmemory-python/src/viewer/index.html +@@ -1039,15 +1039,15 @@ + var wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + var REST, WS_URL, WS_DIRECT_URL, wsPort; + if (paramPort) { +- var resolvedPort = parseInt(paramPort) === 3111 ? '3113' : paramPort; ++ var resolvedPort = paramPort; + REST = window.location.protocol + '//' + window.location.hostname + ':' + resolvedPort; +- wsPort = params.get('wsPort') || String(parseInt(resolvedPort) - 1); ++ wsPort = params.get('wsPort') || resolvedPort; + WS_URL = wsProto + '//' + window.location.hostname + ':' + wsPort; + WS_DIRECT_URL = WS_URL + '/stream/mem-live/viewer'; + } else if (locPort) { +- var resolvedPort = parseInt(locPort) === 3111 ? '3113' : locPort; ++ var resolvedPort = locPort; + REST = window.location.protocol + '//' + window.location.hostname + ':' + resolvedPort; +- wsPort = params.get('wsPort') || String(parseInt(resolvedPort) - 1); ++ wsPort = params.get('wsPort') || resolvedPort; + WS_URL = wsProto + '//' + window.location.hostname + ':' + wsPort; + WS_DIRECT_URL = WS_URL + '/stream/mem-live/viewer'; + } else { + + diff --git a/scratch_test_import.py b/scratch_test_import.py new file mode 100644 index 0000000000000000000000000000000000000000..16a52e927527660f1b6f3ccadb5f3827800cd7f6 --- /dev/null +++ b/scratch_test_import.py @@ -0,0 +1,27 @@ +import os +import requests + +def load_env(): + home = os.path.expanduser("~") + env_path = os.path.join(home, ".agentmemory", ".env") + if os.path.exists(env_path): + with open(env_path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + if "=" in line: + k, v = line.split("=", 1) + os.environ[k.strip()] = v.strip().strip('"').strip("'") + +load_env() +token = os.getenv("AGENTMEMORY_SECRET") +headers = {"Authorization": f"Bearer {token}"} if token else {} + +print(f"Testing route with token: {token[:4]}..." if token else "Testing route with no token...") +r = requests.post("http://127.0.0.1:3111/agentmemory/replay/import-jsonl", json={}, headers=headers) +print("Status code:", r.status_code) +try: + print("Response JSON:", r.json()) +except Exception: + print("Response text:", r.text[:300]) diff --git a/scripts/backfill-imported-sessions.sh b/scripts/backfill-imported-sessions.sh new file mode 100644 index 0000000000000000000000000000000000000000..a247a57e11d7ac26a37959f57a9fb8cde223291c --- /dev/null +++ b/scripts/backfill-imported-sessions.sh @@ -0,0 +1,259 @@ +#!/usr/bin/env bash +# Backfill memory artifacts for sessions imported via `agentmemory import-jsonl`. +# +# The import path only persists Session + Observation rows (via synthetic, +# zero-LLM compression) and the deterministic crystal/lesson derivation. +# It does NOT call mem::summarize, so the semantic/procedural/reflect tiers +# of the consolidation pipeline have nothing to roll up. +# +# This script walks every session tagged `jsonl-import` and: +# 1. POSTs /agentmemory/summarize per session (LLM call) +# 2. POSTs /agentmemory/consolidate-pipeline once at the end +# +# Graph extraction (/agentmemory/graph/extract) is intentionally skipped — +# its API takes a per-observation payload, which is cost-prohibitive for +# bulk imports. `reflect` falls back to a no-graph clustering mode. +# +# Usage: +# scripts/backfill-imported-sessions.sh --dry-run +# scripts/backfill-imported-sessions.sh --limit 5 +# scripts/backfill-imported-sessions.sh # process all + +set -euo pipefail + +URL="${AGENTMEMORY_URL:-http://localhost:3111}" +DRY_RUN=0 +LIMIT=0 # 0 = no limit +ONLY_TAG="jsonl-import" +SKIP_CONSOLIDATE=0 +SKIP_AGENTS=0 # drop sessions whose project starts with "agent-" +MAX_OBS=0 # 0 = no cap; skip sessions with more observations than this +DEBUG_ON_ERROR=0 # on failure, dump session metadata + obs to DEBUG_DIR +DEBUG_DIR="${AGENTMEMORY_DEBUG_DIR:-./agentmemory-debug}" +PROJECT_PATTERN="" # jq test() regex against .project; "" means no filter + +# Cost-estimate knobs (defaults tuned for DeepSeek V4 Flash on DeepInfra: +# $0.14 / 1M input, $0.28 / 1M output). Override via env if needed. +COST_IN_PER_1M="${AGENTMEMORY_COST_IN_PER_1M:-0.14}" +COST_OUT_PER_1M="${AGENTMEMORY_COST_OUT_PER_1M:-0.28}" +# Rough token weight per compressed observation, derived from inspecting +# real synthetic-compression payloads in the kv store (mostly 100-300 tok, +# heavy-tailed). Override if your sessions are unusually verbose. +TOKENS_PER_OBS="${AGENTMEMORY_TOKENS_PER_OBS:-200}" +# Reserved per-call output budget (XML summary is small). +TOKENS_OUT_PER_SESSION="${AGENTMEMORY_TOKENS_OUT_PER_SESSION:-500}" + +while [[ $# -gt 0 ]]; do + case "$1" in + --dry-run) DRY_RUN=1; shift ;; + --limit) LIMIT="${2:?--limit needs a number}"; shift 2 ;; + --tag) ONLY_TAG="${2:?--tag needs a value (use empty string for all)}"; shift 2 ;; + --skip-consolidate) SKIP_CONSOLIDATE=1; shift ;; + --skip-agents) SKIP_AGENTS=1; shift ;; + --max-obs) MAX_OBS="${2:?--max-obs needs a number}"; shift 2 ;; + --debug-on-error) DEBUG_ON_ERROR=1; shift ;; + --project-pattern) PROJECT_PATTERN="${2:?--project-pattern needs a regex}"; shift 2 ;; + -h|--help) + sed -n '2,28p' "$0" + exit 0 ;; + *) echo "unknown flag: $1" >&2; exit 2 ;; + esac +done + +for bin in curl jq; do + command -v "$bin" >/dev/null || { echo "missing dependency: $bin" >&2; exit 1; } +done + +# Curl timeout profiles. Metadata reads (livez, sessions list, observations +# pull for debug dumps) should fail fast and retry transient blips. The LLM +# work calls (summarize, consolidate) intentionally have no --retry and a +# wide --max-time: each call can legitimately take minutes for chunked +# summarize on large sessions, and retrying a half-finished LLM job is +# expensive both in dollars and in duplicated server-side work. +META_CURL_OPTS=(--connect-timeout 10 --max-time 30 --retry 2 --retry-delay 1) +WORK_CURL_OPTS=(--connect-timeout 10 --max-time 1800) + +echo "agentmemory backfill — server: $URL" +[[ "$DRY_RUN" == 1 ]] && echo "DRY RUN: no POSTs will be made." + +# --- liveness --- +if ! curl -fsS "${META_CURL_OPTS[@]}" "$URL/agentmemory/livez" >/dev/null; then + echo "server not reachable at $URL (try: npx @agentmemory/agentmemory)" >&2 + exit 1 +fi + +# --- collect session ids --- +sessions_json="$(curl -fsS "${META_CURL_OPTS[@]}" "$URL/agentmemory/sessions")" +filter='.sessions[] | select(.status=="completed")' +if [[ -n "$ONLY_TAG" ]]; then + filter+=" | select((.tags // []) | index(\"$ONLY_TAG\"))" +fi +if [[ "$SKIP_AGENTS" == 1 ]]; then + filter+=' | select((.project // "") | startswith("agent-") | not)' +fi +if [[ -n "$PROJECT_PATTERN" ]]; then + # jq's test() applies a regex against the project string. + filter+=" | select((.project // \"\") | test(\"$PROJECT_PATTERN\"))" +fi +if [[ "$MAX_OBS" -gt 0 ]]; then + filter+=" | select((.observationCount // 0) <= $MAX_OBS)" +fi +filter+=' | "\(.id)\t\(.observationCount // 0)\t\(.project // "")"' + +rows=() +while IFS= read -r line; do + rows+=("$line") +done < <(echo "$sessions_json" | jq -r "$filter") +total="${#rows[@]}" + +if [[ "$total" -eq 0 ]]; then + echo "no sessions matched (tag='$ONLY_TAG'); nothing to do." + exit 0 +fi + +if [[ "$LIMIT" -gt 0 && "$LIMIT" -lt "$total" ]]; then + rows=("${rows[@]:0:$LIMIT}") +fi + +echo "matched $total session(s); will process ${#rows[@]}." +total_obs=0 +for row in "${rows[@]}"; do + obs="$(cut -f2 <<<"$row")" + total_obs=$(( total_obs + obs )) +done +est_in=$(( total_obs * TOKENS_PER_OBS + ${#rows[@]} * 500 )) +est_out=$(( ${#rows[@]} * TOKENS_OUT_PER_SESSION )) +est_cost="$(awk -v i="$est_in" -v o="$est_out" -v ci="$COST_IN_PER_1M" -v co="$COST_OUT_PER_1M" \ + 'BEGIN { printf "%.2f", (i*ci + o*co) / 1000000 }')" + +echo "≈ ${#rows[@]} summarize LLM calls (one per session, covering $total_obs observations)" +printf '≈ %d input tok + %d output tok → $%s (rates: in=$%s/1M out=$%s/1M, %s tok/obs)\n' \ + "$est_in" "$est_out" "$est_cost" "$COST_IN_PER_1M" "$COST_OUT_PER_1M" "$TOKENS_PER_OBS" +echo + +if [[ "$DRY_RUN" == 1 ]]; then + printf '%-40s %10s %s\n' "session" "obs" "project" + for row in "${rows[@]}"; do + id="$(cut -f1 <<<"$row")" + obs="$(cut -f2 <<<"$row")" + proj="$(cut -f3 <<<"$row")" + printf '%-40s %10s %s\n' "$id" "$obs" "$proj" + done + echo + echo "(dry run) next steps if you re-run without --dry-run:" + echo " for each session above: POST $URL/agentmemory/summarize {sessionId}" + if [[ "$SKIP_CONSOLIDATE" == 0 ]]; then + echo " then: POST $URL/agentmemory/consolidate-pipeline {}" + fi + exit 0 +fi + +# --- summarize loop --- +if [[ "$DEBUG_ON_ERROR" == 1 ]]; then + mkdir -p "$DEBUG_DIR" + echo "debug mode: failed calls will dump to $DEBUG_DIR/" + echo +fi + +dump_failure() { + local id="$1" obs="$2" resp="$3" + # Replace anything outside [A-Za-z0-9._-] with `_` before joining with + # DEBUG_DIR. Session IDs from the API are UUIDs in practice, but the + # server doesn't enforce that — a hostile or buggy id containing `/` or + # `..` would otherwise escape the debug directory. + local safe_id + safe_id="$(printf '%s' "$id" | tr -c 'A-Za-z0-9._-' '_')" + local file="$DEBUG_DIR/${safe_id}.json" + # Pull the raw observations (what would have gone into the prompt) so the + # operator can reconstruct the upstream payload locally. We also compute + # narrative size stats so size-related rejections are immediately visible. + # Stream observations through stdin (avoids exec-arg overflow on + # multi-thousand-obs sessions — macOS argv ceiling is ~256k). + # `--get --data-urlencode` percent-encodes the session id so special + # characters can't corrupt the query string. + curl -fsS "${META_CURL_OPTS[@]}" --get \ + --data-urlencode "sessionId=$id" \ + "$URL/agentmemory/observations" \ + | jq \ + --arg id "$id" \ + --argjson obsCount "$obs" \ + --arg url "$URL/agentmemory/summarize" \ + --argjson response "$resp" \ + '. as $root + | .observations as $obs + | { + sessionId: $id, + observationCount: $obsCount, + request: { url: $url, method: "POST", body: { sessionId: $id } }, + response: $response, + observations: $obs, + stats: { + totalNarrativeBytes: ($obs | map(.narrative // "" | length) | add // 0), + maxNarrativeBytes: ($obs | map(.narrative // "" | length) | max // 0), + titleHistogram: ($obs | group_by(.title) | map({title: .[0].title, count: length}) | sort_by(-.count)) + } + }' >"$file" + echo " → $file" +} + +ok=0; skipped=0; failed=0 +i=0 +for row in "${rows[@]}"; do + i=$(( i + 1 )) + id="$(cut -f1 <<<"$row")" + obs="$(cut -f2 <<<"$row")" + + body="$(jq -nc --arg id "$id" '{sessionId:$id}')" + resp="$(curl -sS "${WORK_CURL_OPTS[@]}" -X POST "$URL/agentmemory/summarize" \ + -H 'content-type: application/json' --data "$body" || echo '{"success":false,"error":"curl_failed"}')" + # iii's HTTP layer occasionally returns non-JSON (HTML 5xx, empty body + # on timeout, etc.). Validate before parsing so `set -e` doesn't abort + # the whole backfill loop on a single bad response. + if jq -e . >/dev/null 2>&1 <<<"$resp"; then + status="$(jq -r '.success // false' <<<"$resp")" + err="$(jq -r '.error // ""' <<<"$resp")" + title="$(jq -r '.summary.title // ""' <<<"$resp")" + else + status="false" + err="invalid_json_response" + title="" + fi + + if [[ "$status" == "true" ]]; then + ok=$(( ok + 1 )) + printf '[%3d/%3d] OK %s obs=%-5s %s\n' "$i" "${#rows[@]}" "$id" "$obs" "$title" + elif [[ "$err" == "no_observations" || "$err" == "no_provider" ]]; then + skipped=$(( skipped + 1 )) + printf '[%3d/%3d] SKIP %s obs=%-5s %s\n' "$i" "${#rows[@]}" "$id" "$obs" "$err" + else + failed=$(( failed + 1 )) + printf '[%3d/%3d] FAIL %s obs=%-5s %s\n' "$i" "${#rows[@]}" "$id" "$obs" "$err" + [[ "$DEBUG_ON_ERROR" == 1 ]] && dump_failure "$id" "$obs" "$resp" + fi +done + +echo +echo "summarize: ok=$ok skipped=$skipped failed=$failed" + +# --- consolidate --- +if [[ "$SKIP_CONSOLIDATE" == 1 ]]; then + echo "skipping consolidate-pipeline (--skip-consolidate)" + exit 0 +fi + +if [[ "$ok" -eq 0 ]]; then + echo "no summaries produced; skipping consolidate-pipeline." + exit 0 +fi + +echo +echo "running consolidate-pipeline …" +resp="$(curl -sS "${WORK_CURL_OPTS[@]}" -X POST "$URL/agentmemory/consolidate-pipeline" \ + -H 'content-type: application/json' --data '{}' || echo '{"success":false,"error":"curl_failed"}')" +if jq -e . >/dev/null 2>&1 <<<"$resp"; then + echo "$resp" | jq . +else + echo "consolidate-pipeline returned non-JSON (likely a timeout or upstream error):" + printf '%s\n' "$resp" | head -c 500 + echo +fi diff --git a/scripts/check-env-example.mjs b/scripts/check-env-example.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ae5ea857a8d92946baa6b967a9f05ffedc8c1f63 --- /dev/null +++ b/scripts/check-env-example.mjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node +// +// Sync-check: every env var read by `src/` MUST be documented in +// `.env.example`. Runs in CI as a soft guard rail — keeps `.env.example` +// from drifting behind real config-surface additions. +// +// Usage: +// node scripts/check-env-example.mjs +// +// Returns 0 when in sync, 1 with a diff when out of sync. + +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { join } from "node:path"; + +const ROOT = new URL("..", import.meta.url).pathname; +const SRC = join(ROOT, "src"); +const ENV_FILE = join(ROOT, ".env.example"); + +// Env vars read by the runtime but NOT user-facing config — these are +// either process-injected (HOME, PATH, USERPROFILE), set by the build / +// wrapper (NODE_*, npm_*), or set by tests (VITEST, *_TEST_*). Skipping +// them keeps `.env.example` a documented config surface rather than an +// inventory of every getenv anywhere in the codebase. +const RUNTIME_ONLY = new Set([ + "HOME", + "PATH", + "USERPROFILE", + "NODE_ENV", + "AGENTMEMORY_SDK_CHILD", +]); + +// Walk src/ for .ts / .mts / .mjs / .js files (excluding `.d.ts` declarations +// and dotfile dirs / node_modules). test/ lives outside src/ so it never enters. +function walk(dir) { + const out = []; + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + const s = statSync(full); + if (s.isDirectory()) { + if (entry === "node_modules" || entry.startsWith(".")) continue; + out.push(...walk(full)); + } else if (/\.(ts|mts|mjs|js)$/.test(entry) && !entry.endsWith(".d.ts")) { + out.push(full); + } + } + return out; +} + +// Multiple patterns: +// process.env["KEY"] — direct access +// env["KEY"] — local alias inside detectProvider, etc. +// getEnvVar("KEY") — helper from src/config.ts +// env: ProcessEnv → env.KEY — caught as `env["KEY"]` only; if you add +// a dotted-access path, extend the regex. +const PATTERNS = [ + // Direct map index: process.env["KEY"], env["KEY"], getMergedEnv()["KEY"]. + // The trailing `]\s*` form covers `…)["KEY"]` and `…env["KEY"]`. + /\[\s*"([A-Z][A-Z0-9_]+)"\s*\]/g, + /getEnvVar\(\s*"([A-Z][A-Z0-9_]+)"\s*\)/g, +]; +const used = new Set(); +for (const file of walk(SRC)) { + const text = readFileSync(file, "utf8"); + for (const pat of PATTERNS) { + pat.lastIndex = 0; + let m; + while ((m = pat.exec(text)) !== null) { + const name = m[1]; + if (!RUNTIME_ONLY.has(name)) used.add(name); + } + } +} + +const envText = readFileSync(ENV_FILE, "utf8"); +const documented = new Set(); +for (const line of envText.split("\n")) { + const m = line.match(/^#?\s*([A-Z][A-Z0-9_]+)=/); + if (m) documented.add(m[1]); +} + +const missing = [...used].filter((k) => !documented.has(k)).sort(); +const orphan = [...documented].filter((k) => !used.has(k)).sort(); + +if (missing.length === 0 && orphan.length === 0) { + console.log(`env-example: in sync (${used.size} keys documented)`); + process.exit(0); +} + +if (missing.length > 0) { + console.error( + `env-example: MISSING from .env.example — add documentation for these keys:`, + ); + for (const k of missing) console.error(` - ${k}`); +} +if (orphan.length > 0) { + console.error( + `env-example: ORPHAN in .env.example — no longer read by src/, remove or move to runtime-only allowlist:`, + ); + for (const k of orphan) console.error(` - ${k}`); +} +process.exit(1); diff --git a/scripts/skills/check.ts b/scripts/skills/check.ts new file mode 100644 index 0000000000000000000000000000000000000000..860e1e780940bb65a484212ebd22a3c392a88661 --- /dev/null +++ b/scripts/skills/check.ts @@ -0,0 +1,80 @@ +import { readFileSync, readdirSync, existsSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(HERE, "..", ".."); +const SKILLS = join(ROOT, "plugin", "skills"); + +const errors: string[] = []; +const MAX_LINES = 100; +const DUP_MARKER = "/plugin list"; + +function parseFrontmatter(text: string): Record | null { + if (!text.startsWith("---")) return null; + const end = text.indexOf("\n---", 3); + if (end === -1) return null; + const body = text.slice(3, end); + const out: Record = {}; + for (const line of body.split("\n")) { + const m = /^([a-zA-Z_-]+):\s*(.*)$/.exec(line.trim()); + if (m) out[m[1]] = m[2]; + } + return out; +} + +const dirs = readdirSync(SKILLS, { withFileTypes: true }) + .filter((e) => e.isDirectory() && !e.name.startsWith("_")) + .map((e) => e.name); + +for (const name of dirs) { + const skillFile = join(SKILLS, name, "SKILL.md"); + if (!existsSync(skillFile)) { + errors.push(`${name}: missing SKILL.md`); + continue; + } + const text = readFileSync(skillFile, "utf8"); + const rel = `plugin/skills/${name}/SKILL.md`; + + const fm = parseFrontmatter(text); + if (!fm) { + errors.push(`${rel}: missing or malformed frontmatter`); + } else { + if (!fm.name) errors.push(`${rel}: frontmatter missing 'name'`); + if (fm.name && fm.name !== name) errors.push(`${rel}: frontmatter name '${fm.name}' != dir '${name}'`); + if (!fm.description) errors.push(`${rel}: frontmatter missing 'description'`); + else { + if (!/use when/i.test(fm.description)) errors.push(`${rel}: description must contain a "Use when ..." trigger sentence`); + if (fm.description.length > 1024) errors.push(`${rel}: description exceeds 1024 chars`); + } + } + + const lines = text.split("\n").length; + if (lines > MAX_LINES) errors.push(`${rel}: ${lines} lines (max ${MAX_LINES}); move detail into REFERENCE.md or EXAMPLES.md`); + + const body = fm ? text.slice(text.indexOf("\n---", 3) + 4) : text; + if (body.includes(DUP_MARKER)) { + errors.push(`${rel}: inlines the shared troubleshooting block; reference ../_shared/TROUBLESHOOTING.md instead`); + } +} + +if (!existsSync(join(SKILLS, "_shared", "TROUBLESHOOTING.md"))) { + errors.push(`_shared/TROUBLESHOOTING.md is missing`); +} + +const pluginJson = join(ROOT, "plugin", "plugin.json"); +if (existsSync(pluginJson)) { + const desc = (JSON.parse(readFileSync(pluginJson, "utf8")).description as string) ?? ""; + const m = /(\d+)\s+skills/.exec(desc); + if (!m) errors.push(`plugin/plugin.json: description should state the skill count as "N skills"`); + else if (Number(m[1]) !== dirs.length) { + errors.push(`plugin/plugin.json: description says ${m[1]} skills but ${dirs.length} skill dirs exist`); + } +} + +if (errors.length) { + console.error("Skill lint failed:"); + for (const e of errors) console.error(` - ${e}`); + process.exit(1); +} +console.log(`Skill lint passed: ${dirs.length} skills checked.`); diff --git a/scripts/skills/generate.ts b/scripts/skills/generate.ts new file mode 100644 index 0000000000000000000000000000000000000000..44ccf941a3355d8e7e1c8056bb91ec06e6e3b88e --- /dev/null +++ b/scripts/skills/generate.ts @@ -0,0 +1,170 @@ +import { readFileSync, writeFileSync, readdirSync, existsSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { getAllTools, ESSENTIAL_TOOLS } from "../../src/mcp/tools-registry.js"; +import { ADAPTERS } from "../../src/cli/connect/index.js"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(HERE, "..", ".."); +const SKILLS = join(ROOT, "plugin", "skills"); +const SRC = join(ROOT, "src"); + +const check = process.argv.includes("--check"); + +function clean(s: string): string { + return s.replace(/\s*[—–]\s*/g, ", "); +} + +function block(key: string, body: string): { open: string; close: string; full: string } { + const open = ``; + const close = ``; + return { open, close, full: `${open}\n${body.trim()}\n${close}` }; +} + +function applyBlock(file: string, key: string, body: string): void { + const { open, close, full } = block(key, body); + const existing = existsSync(file) ? readFileSync(file, "utf8") : ""; + let next: string; + if (existing.includes(open) && existing.includes(close)) { + const start = existing.indexOf(open); + const end = existing.indexOf(close) + close.length; + next = existing.slice(0, start) + full + existing.slice(end); + } else if (existing.trim()) { + next = `${existing.trimEnd()}\n\n${full}\n`; + } else { + next = `${full}\n`; + } + if (check) { + if (existing !== next) { + console.error(`DRIFT: ${file.replace(ROOT + "/", "")} (AUTOGEN:${key} out of date — run \`npm run skills:gen\`)`); + process.exitCode = 1; + } + return; + } + if (existing !== next) { + writeFileSync(file, next); + console.log(`wrote AUTOGEN:${key} -> ${file.replace(ROOT + "/", "")}`); + } +} + +function walk(dir: string, out: string[] = []): string[] { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, e.name); + if (e.isDirectory()) { + if (e.name === "node_modules" || e.name === "dist") continue; + walk(full, out); + } else if (e.name.endsWith(".ts")) { + out.push(full); + } + } + return out; +} + +function mdEscape(s: string): string { + return clean(s.replace(/\|/g, "\\|").replace(/\n/g, " ")).trim(); +} + +function tools(): string { + const all = getAllTools(); + const lines = [ + `agentmemory exposes ${all.length} MCP tools. ${ESSENTIAL_TOOLS.size} are in the lean core set (\`--tools core\` or \`AGENTMEMORY_TOOLS=core\`); the rest load with \`--tools all\` (default).`, + "", + "| Tool | Core | Parameters | Purpose |", + "| --- | --- | --- | --- |", + ]; + for (const t of all.sort((a, b) => a.name.localeCompare(b.name))) { + const required = new Set(t.inputSchema.required ?? []); + const params = Object.entries(t.inputSchema.properties ?? {}) + .map(([n, s]) => `\`${n}\`${required.has(n) ? "*" : ""}: ${s.type}`) + .join(", ") || "none"; + const core = ESSENTIAL_TOOLS.has(t.name) ? "yes" : ""; + lines.push(`| \`${t.name}\` | ${core} | ${mdEscape(params)} | ${mdEscape(t.description)} |`); + } + lines.push("", "`*` marks required parameters."); + return lines.join("\n"); +} + +function rest(): string { + const text = readFileSync(join(SRC, "triggers", "api.ts"), "utf8"); + const found: { path: string; method: string }[] = []; + const re = /api_path:\s*"([^"]+)"/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) { + const path = m[1]; + const win = text.slice(Math.max(0, m.index - 140), m.index + 140); + const mm = /http_method:\s*"([A-Z]+)"/.exec(win); + found.push({ path, method: mm ? mm[1] : "POST" }); + } + const seen = new Set(); + const rows = found + .filter((e) => (seen.has(e.path) ? false : (seen.add(e.path), true))) + .sort((a, b) => a.path.localeCompare(b.path)); + const lines = [ + `The REST API is the primary surface. All paths are under \`http://localhost:3111\` (override with \`--port\`). When \`AGENTMEMORY_SECRET\` is set, send \`Authorization: Bearer $AGENTMEMORY_SECRET\`; localhost is otherwise open.`, + "", + `${rows.length} registered endpoints:`, + "", + "| Method | Path |", + "| --- | --- |", + ...rows.map((e) => `| ${e.method} | \`${e.path}\` |`), + ]; + return lines.join("\n"); +} + +function env(): string { + const files = walk(SRC); + const vars = new Set(); + for (const f of files) { + const text = readFileSync(f, "utf8"); + const re = /AGENTMEMORY_[A-Z0-9_]+/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) { + if (!m[0].endsWith("__")) vars.add(m[0]); + } + } + const sorted = [...vars].sort(); + const lines = [ + `Configuration is read from the environment and from \`~/.agentmemory/.env\` (no \`export\` prefix). ${sorted.length} recognized variables:`, + "", + ...sorted.map((v) => `- \`${v}\``), + ]; + return lines.join("\n"); +} + +function agents(): string { + const lines = [ + `\`agentmemory connect \` wires the memory server into a host agent. ${ADAPTERS.length} adapters:`, + "", + "| Agent | Name | Protocol |", + "| --- | --- | --- |", + ]; + for (const a of [...ADAPTERS].sort((x, y) => x.name.localeCompare(y.name))) { + const note = (a.protocolNote ?? "").replace(/^[→\s]+/, ""); + lines.push(`| ${mdEscape(a.displayName)} | \`${a.name}\` | ${mdEscape(note) || "MCP"} |`); + } + return lines.join("\n"); +} + +function hooks(): string { + const file = join(ROOT, "plugin", "hooks", "hooks.json"); + const json = JSON.parse(readFileSync(file, "utf8")) as { hooks?: Record }; + const events = Object.keys(json.hooks ?? {}).sort(); + const lines = [ + `The Claude Code plugin registers hooks on ${events.length} lifecycle events to capture observations automatically:`, + "", + ...events.map((e) => `- \`${e}\``), + ]; + return lines.join("\n"); +} + +applyBlock(join(SKILLS, "agentmemory-mcp-tools", "REFERENCE.md"), "tools", tools()); +applyBlock(join(SKILLS, "agentmemory-rest-api", "REFERENCE.md"), "rest", rest()); +applyBlock(join(SKILLS, "agentmemory-config", "REFERENCE.md"), "env", env()); +applyBlock(join(SKILLS, "agentmemory-agents", "REFERENCE.md"), "agents", agents()); +applyBlock(join(SKILLS, "agentmemory-hooks", "REFERENCE.md"), "hooks", hooks()); + +if (check && process.exitCode) { + console.error("\nSkill reference docs are stale. Run: npm run skills:gen"); +} else if (!check) { + console.log("skills reference generation complete"); +} diff --git a/setup-venv.ps1 b/setup-venv.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..1f76eccbd41de71de448c263b4603ac3cf641968 --- /dev/null +++ b/setup-venv.ps1 @@ -0,0 +1,14 @@ +# Creates .venv in the project directory and installs all dependencies +$venvDir = ".venv" + +if (-not (Test-Path $venvDir)) { + Write-Host "Creating virtual environment..." + python -m venv $venvDir +} + +Write-Host "Installing dependencies..." +& "$venvDir\Scripts\pip.exe" install -r requirements.txt + +Write-Host "" +Write-Host "Done. Activate with:" +Write-Host " .\.venv\Scripts\Activate.ps1" diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/app.py b/src/app.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9355546c1aea88d1e6906efb24c84c1fa887ab --- /dev/null +++ b/src/app.py @@ -0,0 +1,1976 @@ +import os +import sys +import json +import hmac +import secrets +import base64 +import threading +from flask import Flask, request, jsonify, make_response, send_from_directory +from flask_sock import Sock + +# Load environment variables from ~/.agentmemory/.env if it exists +def load_env(): + home = os.path.expanduser("~") + env_path = os.path.join(home, ".agentmemory", ".env") + if os.path.exists(env_path): + try: + with open(env_path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + if "=" in line: + k, v = line.split("=", 1) + k = k.strip() + v = v.strip().strip('"').strip("'") + os.environ[k] = v + print(f"[config] Loaded environment from {env_path}") + except Exception as e: + print(f"[config] Error reading env file: {e}") + +load_env() + +import datetime + +def datetime_now_iso() -> str: + return datetime.datetime.utcnow().isoformat() + "Z" + +# Import local modules +from db import StateKV +import search +import functions +from functions import KV, query_audit + +app = Flask(__name__) +# Enable CORS for all routes (important for client scripts connecting locally) +@app.after_request +def after_request(response): + origin = request.headers.get("Origin") + if origin: + parsed_origin = origin.lower() + is_allowed = False + if parsed_origin in ("null", "vscode-webview://"): + is_allowed = True + elif parsed_origin.startswith("http://localhost:") or parsed_origin == "http://localhost": + is_allowed = True + elif parsed_origin.startswith("http://127.0.0.1:") or parsed_origin == "http://127.0.0.1": + is_allowed = True + elif parsed_origin.startswith("vscode-webview://"): + is_allowed = True + elif parsed_origin.startswith("chrome-extension://"): + is_allowed = True + + if is_allowed: + response.headers["Access-Control-Allow-Origin"] = origin + response.headers["Access-Control-Allow-Credentials"] = "true" + response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization") + response.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + return response + +sock = Sock(app) + +# Global instances +kv = None +embedding_provider = None +persistence = None + +def init_app(): + global kv, embedding_provider, persistence + + # 1. Initialize DB + kv = StateKV() + + # 2. Initialize Embedding Provider if API key is available + api_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY") + if api_key: + try: + embedding_provider = search.GeminiEmbeddingProvider(api_key) + functions.set_embedding_provider(embedding_provider) + print(f"[search] Embedding provider active: gemini (768 dims)") + except Exception as e: + print(f"[search] Error initializing embedding provider: {e}") + else: + print(f"[search] No GEMINI_API_KEY found, running in BM25-only mode.") + + # 3. Persistence & load indexes + persistence = functions.IndexPersistence(kv, functions._bm25_index, functions._vector_index if api_key else None) + functions.set_index_persistence(persistence) + + loaded = persistence.load() + print(f"[persistence] Load results: BM25 index={loaded['bm25']}, Vector index={loaded['vector']}") + + # 4. Rebuild index if empty + if functions._bm25_index.size == 0: + print("[persistence] Search index is empty. Rebuilding in background thread...") + def run_rebuild(): + try: + count = functions.rebuild_index(kv) + print(f"[persistence] Rebuild completed: indexed {count} items.") + except Exception as ex: + print(f"[persistence] Rebuild failed: {ex}") + t = threading.Thread(target=run_rebuild, daemon=True) + t.start() + + # 5. Start background worker loops + import time + def run_auto_forget_loop(): + time.sleep(10) + while True: + try: + if os.getenv("AUTO_FORGET_ENABLED") != "false": + print("[scheduler] Running auto_forget sweep...") + res = functions.auto_forget(kv, dry_run=False) + print(f"[scheduler] auto_forget sweep completed: {res}") + except Exception as e: + print(f"[scheduler] auto_forget loop error: {e}") + time.sleep(3600) + + def run_consolidation_loop(): + time.sleep(15) + while True: + try: + print("[scheduler] Running lesson_decay_sweep...") + decay_res = functions.lesson_decay_sweep(kv) + print(f"[scheduler] lesson_decay_sweep completed: {decay_res}") + + if functions.is_consolidation_enabled(): + print("[scheduler] Running consolidation...") + cons_res = functions.consolidate(kv) + print(f"[scheduler] consolidation completed: {cons_res}") + except Exception as e: + print(f"[scheduler] consolidation/decay loop error: {e}") + time.sleep(86400) + + t_forget = threading.Thread(target=run_auto_forget_loop, daemon=True) + t_forget.start() + + t_consolidate = threading.Thread(target=run_consolidation_loop, daemon=True) + t_consolidate.start() + +# ===================================================================== +# Auth Middleware +# ===================================================================== + +def timing_safe_compare(a: str, b: str) -> bool: + return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8")) + +def check_auth(): + secret = os.getenv("AGENTMEMORY_SECRET") + if not secret: + return None + auth = request.headers.get("Authorization") or request.headers.get("authorization") + if not auth or not auth.startswith("Bearer "): + return jsonify({"error": "unauthorized"}), 401 + + provided_token = auth[7:].strip() + if not timing_safe_compare(provided_token, secret): + return jsonify({"error": "unauthorized"}), 401 + return None + +# ===================================================================== +# WebSocket Streaming +# ===================================================================== + +active_websockets = set() + +@sock.route("/stream/mem-live/viewer") +def stream_viewer(ws): + secret = os.getenv("AGENTMEMORY_SECRET") + if secret: + token = request.args.get("token") or request.args.get("secret") + if not token or not timing_safe_compare(token, secret): + ws.close(1008) + return + + active_websockets.add(ws) + try: + while True: + data = ws.receive() + if data is None: + break + except Exception: + pass + finally: + active_websockets.discard(ws) + +def broadcast_to_viewers(payload): + msg = json.dumps(payload) + for ws in list(active_websockets): + try: + ws.send(msg) + except Exception: + active_websockets.discard(ws) + +# Register broadcaster in functions +functions.set_stream_broadcaster(broadcast_to_viewers) + +# ===================================================================== +# Viewer Routes +# ===================================================================== + +@app.route("/") +@app.route("/viewer") +@app.route("/agentmemory/viewer") +def serve_viewer(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + base_dir = os.path.dirname(os.path.abspath(__file__)) + template_path = os.path.join(base_dir, "viewer", "index.html") + with open(template_path, "r", encoding="utf-8") as f: + template = f.read() + + nonce = base64.urlsafe_b64encode(secrets.token_bytes(16)).decode("utf-8").rstrip("=") + html = template.replace("__AGENTMEMORY_VIEWER_NONCE__", nonce).replace("__AGENTMEMORY_VERSION__", "0.9.8") + + csp = "; ".join([ + "default-src 'none'", + "base-uri 'none'", + "frame-ancestors 'none'", + "object-src 'none'", + "form-action 'none'", + f"script-src 'nonce-{nonce}'", + "script-src-attr 'none'", + "style-src 'unsafe-inline'", + "connect-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*", + "img-src 'self' data:", + "font-src 'self'", + ]) + + res = make_response(html) + res.headers["Content-Type"] = "text/html; charset=utf-8" + res.headers["Content-Security-Policy"] = csp + res.headers["Cache-Control"] = "no-cache" + return res + except Exception as e: + return f"Viewer not found: {e}", 404 + +@app.route("/favicon.svg") +def serve_favicon(): + base_dir = os.path.dirname(os.path.abspath(__file__)) + return send_from_directory(os.path.join(base_dir, "viewer"), "favicon.svg") + +# ===================================================================== +# REST REST API Endpoints +# ===================================================================== + +@app.route("/agentmemory/livez", methods=["GET"]) +def livez(): + port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111"))) + return jsonify({ + "status": "ok", + "service": "agentmemory", + "viewerPort": port, + "viewerSkipped": False + }) + +@app.route("/agentmemory/config/flags", methods=["GET"]) +def config_flags(): + auth_err = check_auth() + if auth_err: + return auth_err + + provider_kind = "llm" if embedding_provider else "noop" + embedding_prov = "gemini" if embedding_provider else "none" + + flags = [ + { + "key": "GRAPH_EXTRACTION_ENABLED", + "label": "Knowledge graph extraction", + "enabled": functions.is_graph_extraction_enabled(), + "default": False, + "affects": ["Graph", "Dashboard"], + "needsLlm": True, + "description": "Extracts entities and relations from observations into a knowledge graph.", + "enableHow": "Set GRAPH_EXTRACTION_ENABLED=true and restart.", + "docsHref": "https://github.com/rohitg00/agentmemory#knowledge-graph" + }, + { + "key": "CONSOLIDATION_ENABLED", + "label": "Memory consolidation", + "enabled": functions.is_consolidation_enabled(), + "default": False, + "affects": ["Dashboard", "Memories", "Crystals"], + "needsLlm": True, + "description": "Periodically summarizes sessions into semantic facts + procedures.", + "enableHow": "Set CONSOLIDATION_ENABLED=true and restart.", + "docsHref": "https://github.com/rohitg00/agentmemory#consolidation" + }, + { + "key": "AGENTMEMORY_AUTO_COMPRESS", + "label": "LLM-powered observation compression", + "enabled": functions.is_auto_compress_enabled(), + "default": False, + "affects": ["Memories", "Timeline"], + "needsLlm": True, + "description": "Every observation is compressed by the LLM for richer summaries. OFF uses synthetic compression.", + "enableHow": "Set AGENTMEMORY_AUTO_COMPRESS=true.", + "docsHref": "https://github.com/rohitg00/agentmemory/issues/138" + } + ] + return jsonify({ + "version": "0.9.8", + "provider": provider_kind, + "embeddingProvider": embedding_prov, + "flags": flags + }) + +@app.route("/agentmemory/health", methods=["GET"]) +def health(): + return jsonify(functions.health_check(kv)) + +@app.route("/agentmemory/observe", methods=["POST"]) +def api_observe(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.observe(kv, body) + return jsonify(res), 201 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/agent/observe", methods=["POST"]) +def api_agent_observe(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + agent_id = body.get("agentId") + session_id = body.get("sessionId") + project = body.get("project") + cwd = body.get("cwd") or "" + text = body.get("text") or "" + obs_type = body.get("type") or "other" + title = body.get("title") or f"agent_{obs_type}" + image_data = body.get("imageData") + + if not session_id or not project: + return jsonify({"error": "sessionId and project are required"}), 400 + + timestamp = datetime_now_iso() + + data_payload = { + "tool_name": title, + "tool_input": text, + "tool_output": text, + } + if image_data: + data_payload["imageBase64"] = image_data + + payload = { + "sessionId": session_id, + "project": project, + "cwd": cwd, + "hookType": "post_tool_use", + "timestamp": timestamp, + "data": data_payload + } + if agent_id: + payload["agentId"] = agent_id + + res = functions.observe(kv, payload) + return jsonify(res), 201 + except Exception as e: + return jsonify({"error": str(e)}), 400 + + +@app.route("/agentmemory/context", methods=["POST"]) +def api_context(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.context(kv, body) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/search", methods=["POST"]) +def api_search(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + query = body.get("query") + if not query or not query.strip(): + return jsonify({"error": "query is required"}), 400 + limit = body.get("limit") or 10 + + # smart search / hybrid search query + res = functions._hybrid_search.search(query, limit) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/replay/sessions", methods=["GET"]) +def api_replay_sessions(): + auth_err = check_auth() + if auth_err: + return auth_err + + sessions = kv.list(KV.sessions) + sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) + return jsonify({"success": True, "sessions": sessions}), 200 + +@app.route("/agentmemory/session/start", methods=["POST"]) +def api_session_start(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + session_id = body.get("sessionId") + project = body.get("project") + cwd = body.get("cwd") + if not session_id or not project or not cwd: + return jsonify({"error": "sessionId, project, and cwd are required"}), 400 + + title = body.get("title") + agent_id = body.get("agentId") or functions.get_agent_id() + + session = { + "id": session_id, + "project": project, + "cwd": cwd, + "startedAt": datetime_now_iso(), + "status": "active", + "observationCount": 0 + } + if title: + session["summary"] = title[:200] + session["firstPrompt"] = title[:200] + if agent_id: + session["agentId"] = agent_id + + functions.create_session(kv, session) + + # Compile initial context + ctx = functions.context(kv, {"sessionId": session_id, "project": project}) + + # Commit to Dolt + functions.commit_if_enabled(kv, f"Start session {session_id[:8]}", agent_id) + + return jsonify({"session": session, "context": ctx.get("context", "")}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/session/end", methods=["POST"]) +def api_session_end(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + session_id = body.get("sessionId") + if not session_id: + return jsonify({"error": "sessionId is required"}), 400 + + functions.end_session(kv, session_id) + + # Commit to Dolt + sess = functions.get_session(kv, session_id) or {} + agent_id = sess.get("agentId") + functions.commit_if_enabled(kv, f"End session {session_id[:8]}", agent_id) + + return jsonify({"success": True}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/session/commit", methods=["POST"]) +def api_session_commit(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + sha = body.get("sha") + if not sha: + return jsonify({"error": "sha is required"}), 400 + + session_id = body.get("sessionId") + branch = body.get("branch") + repo = body.get("repo") + message = body.get("message") + author = body.get("author") + authored_at = body.get("authoredAt") + files = body.get("files") + + existing = kv.get(KV.commits, sha) or {} + session_ids = set(existing.get("sessionIds", [])) + if session_id: + session_ids.add(session_id) + + link = { + "sha": sha, + "shortSha": sha[:7], + "branch": branch or existing.get("branch"), + "repo": repo or existing.get("repo"), + "message": message or existing.get("message"), + "author": author or existing.get("author"), + "authoredAt": authored_at or existing.get("authoredAt"), + "files": files or existing.get("files"), + "sessionIds": list(session_ids), + "linkedAt": existing.get("linkedAt") or datetime_now_iso() + } + kv.set(KV.commits, sha, link) + + if session_id: + sess = functions.get_session(kv, session_id) + if sess: + commit_shas = set(sess.get("commitShas", [])) + commit_shas.add(sha) + sess["commitShas"] = list(commit_shas) + functions.create_session(kv, sess) + + return jsonify({"commit": link}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/session/by-commit", methods=["GET"]) +def api_session_by_commit(): + auth_err = check_auth() + if auth_err: + return auth_err + + sha = request.args.get("sha") + if not sha: + return jsonify({"error": "sha query param required"}), 400 + + link = kv.get(KV.commits, sha) + if not link: + return jsonify({"error": "no sessions linked to this commit"}), 404 + + sessions = [] + for sid in link.get("sessionIds", []): + sess = functions.get_session(kv, sid) + if sess: + sessions.append(sess) + return jsonify({"commit": link, "sessions": sessions}), 200 + +@app.route("/agentmemory/commits", methods=["GET"]) +def api_commits(): + auth_err = check_auth() + if auth_err: + return auth_err + + branch = request.args.get("branch") + repo = request.args.get("repo") + limit = int(request.args.get("limit", "100")) + + all_links = kv.list(KV.commits) + filtered = all_links + if branch: + filtered = [c for c in filtered if c.get("branch") == branch] + if repo: + filtered = [c for c in filtered if c.get("repo") == repo] + + filtered.sort(key=lambda c: c.get("linkedAt", ""), reverse=True) + return jsonify({"commits": filtered[:limit]}), 200 + +@app.route("/agentmemory/sessions", methods=["GET"]) +def api_sessions(): + auth_err = check_auth() + if auth_err: + return auth_err + + sessions = functions.list_sessions(kv) + agent_id = request.args.get("agentId") + if agent_id and agent_id != "*": + sessions = [s for s in sessions if s.get("agentId") == agent_id] + elif functions.is_agent_scope_isolated(): + env_aid = functions.get_agent_id() + if env_aid: + sessions = [s for s in sessions if s.get("agentId") == env_aid] + + return jsonify({"sessions": sessions}), 200 + +@app.route("/agentmemory/observations", methods=["GET"]) +def api_observations(): + auth_err = check_auth() + if auth_err: + return auth_err + + session_id = request.args.get("sessionId") + if not session_id: + return jsonify({"error": "sessionId is required"}), 400 + + obs = kv.list(KV.observations(session_id)) + obs.sort(key=lambda o: o.get("timestamp", "")) + agent_id = request.args.get("agentId") + if agent_id and agent_id != "*": + obs = [o for o in obs if o.get("agentId") == agent_id] + elif functions.is_agent_scope_isolated(): + env_aid = functions.get_agent_id() + if env_aid: + obs = [o for o in obs if o.get("agentId") == env_aid] + + return jsonify({"observations": obs}), 200 + +@app.route("/agentmemory/remember", methods=["POST"]) +def api_remember(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.remember(kv, body) + return jsonify(res), 201 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/agent/remember", methods=["POST"]) +def api_agent_remember(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + content = body.get("content") + if not content: + return jsonify({"error": "content is required"}), 400 + + agent_id = body.get("agentId") + project = body.get("project") + mem_type = body.get("type") or "fact" + + concepts = body.get("concepts") or [] + if isinstance(concepts, str): + concepts = [c.strip() for c in concepts.split(",") if c.strip()] + + files = body.get("files") or [] + if isinstance(files, str): + files = [f.strip() for f in files.split(",") if f.strip()] + + payload = { + "content": content, + "type": mem_type, + "concepts": concepts, + "files": files, + "project": project + } + if agent_id: + payload["agentId"] = agent_id + + res = functions.remember(kv, payload) + return jsonify(res), 201 + except Exception as e: + return jsonify({"error": str(e)}), 400 + + +@app.route("/agentmemory/forget", methods=["POST"]) +def api_forget(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.forget(kv, body) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +# ===================================================================== +# Lessons Learned Endpoints +# ===================================================================== + +@app.route("/agentmemory/lessons", methods=["GET"]) +def api_lessons_list(): + auth_err = check_auth() + if auth_err: + return auth_err + + project = request.args.get("project") + source = request.args.get("source") + min_conf = float(request.args.get("minConfidence", "0")) + limit = int(request.args.get("limit", "50")) + + res = functions.lesson_list(kv, { + "project": project, + "source": source, + "minConfidence": min_conf, + "limit": limit + }) + return jsonify(res), 200 + +@app.route("/agentmemory/lessons", methods=["POST"]) +def api_lessons_save(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.lesson_save(kv, body) + return jsonify(res), 201 if res.get("action") == "created" else 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/lessons/search", methods=["POST"]) +def api_lessons_search(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.lesson_recall(kv, body) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/lessons/strengthen", methods=["POST"]) +def api_lessons_strengthen(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + lesson_id = body.get("lessonId") + if not lesson_id: + return jsonify({"error": "lessonId is required"}), 400 + res = functions.lesson_strengthen(kv, lesson_id) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +# ===================================================================== +# Memory Slots Endpoints +# ===================================================================== + +@app.route("/agentmemory/slots", methods=["GET"]) +def api_slots_list(): + auth_err = check_auth() + if auth_err: + return auth_err + + return jsonify(functions.slot_list(kv)), 200 + +@app.route("/agentmemory/slot", methods=["GET"]) +def api_slots_get(): + auth_err = check_auth() + if auth_err: + return auth_err + + label = request.args.get("label") + if not label: + return jsonify({"error": "label required"}), 400 + res = functions.slot_get(kv, label) + status = 200 if res.get("success") else 404 + return jsonify(res), status + +@app.route("/agentmemory/slot", methods=["POST"]) +def api_slots_create(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.slot_create(kv, body) + status = 201 if res.get("success") else 400 + return jsonify(res), status + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/slot/append", methods=["POST"]) +def api_slots_append(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + label = body.get("label") + text = body.get("text") + if not label or not text: + return jsonify({"error": "label and text required"}), 400 + res = functions.slot_append(kv, label, text) + status = 200 if res.get("success") else 400 + return jsonify(res), status + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/slot/replace", methods=["POST"]) +def api_slots_replace(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + label = body.get("label") + content = body.get("content") + if not label or content is None: + return jsonify({"error": "label and content required"}), 400 + res = functions.slot_replace(kv, label, content) + status = 200 if res.get("success") else 400 + return jsonify(res), status + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/slot", methods=["DELETE"]) +def api_slots_delete(): + auth_err = check_auth() + if auth_err: + return auth_err + + label = request.args.get("label") + if not label: + return jsonify({"error": "label query param required"}), 400 + res = functions.slot_delete(kv, label) + status = 200 if res.get("success") else 404 + return jsonify(res), status + +@app.route("/agentmemory/slot/reflect", methods=["POST"]) +def api_slots_reflect(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + session_id = body.get("sessionId") + if not session_id: + return jsonify({"error": "sessionId required"}), 400 + max_obs = body.get("maxObservations") or 50 + res = functions.slot_reflect(kv, session_id, max_obs) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +# ===================================================================== +# Audit, Relations, Evolve, Timeline, Profile +# ===================================================================== + +@app.route("/agentmemory/audit", methods=["GET"]) +def api_audit(): + auth_err = check_auth() + if auth_err: + return auth_err + + op = request.args.get("operation") + limit = int(request.args.get("limit", "50")) + res = query_audit(kv, {"operation": op, "limit": limit}) + return jsonify({"entries": res, "success": True}), 200 + +@app.route("/agentmemory/relations", methods=["GET"]) +def api_relations_list(): + auth_err = check_auth() + if auth_err: + return auth_err + + rels = functions.get_relations(kv) + return jsonify({"relations": rels}), 200 + +@app.route("/agentmemory/relations", methods=["POST"]) +def api_relations_add(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.add_relation(kv, body) + return jsonify(res), 201 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/evolve", methods=["POST"]) +def api_evolve(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.evolve_memory(kv, body) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/timeline", methods=["POST"]) +def api_timeline(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + res = functions.timeline(kv, body) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/profile", methods=["GET"]) +def api_profile(): + auth_err = check_auth() + if auth_err: + return auth_err + + project = request.args.get("project") + if not project: + sessions = kv.list(KV.sessions) + projects = sorted(set(s.get("project", "") for s in sessions if s.get("project"))) + return jsonify({"projects": projects, "success": True}), 200 + + res = functions.get_project_profile(kv, project) + + # Stored profile may lack topConcepts/topFiles — compute from observations if empty + if not res.get("topConcepts") and not res.get("topFiles"): + import re as _re, json as _j, os.path as _osp + from collections import Counter + sessions = kv.list(KV.sessions) + project_sessions = [s for s in sessions if s.get("project") == project] + concept_counts = Counter() + file_counts = Counter() + + def _harvest_file(path, fc, cc): + if not isinstance(path, str) or not path: + return + fc[path] += 1 + # dirname components → concepts + parts = _re.split(r'[\\/]', path) + fname = parts[-1] if parts else "" + # dir components (skip drive letters, temp paths) + skip = {"tmp", "temp", "claude", "appdata", "local", "users", "windows"} + for part in parts[:-1]: + p = part.lower().strip() + if p and len(p) > 2 and p not in skip and not _re.match(r'^[a-z]:|^\.|^--', p): + cc[p] += 1 + # file stem → concept + stem = _osp.splitext(fname)[0] + if stem and len(stem) > 2: + cc[stem.lower()] += 1 + # extension → technology concept + ext = _osp.splitext(fname)[1].lstrip(".") + if ext in ("py", "ts", "js", "jsx", "tsx", "go", "rs", "java", "cs", "cpp"): + cc[ext] += 1 + + for s in project_sessions: + sid = s.get("id", "") + if not sid: + continue + for o in kv.list(KV.observations(sid)): + # top-level concepts / files + for c in (o.get("concepts") or []): + if isinstance(c, str) and c: + concept_counts[c] += 1 + for f in (o.get("files") or []): + _harvest_file(f, file_counts, concept_counts) + # toolName → concept + tn = o.get("toolName") + if tn: + concept_counts[tn] += 1 + # toolInput path fields + ti = o.get("toolInput") + if isinstance(ti, str): + try: ti = _j.loads(ti) + except Exception: ti = {} + if isinstance(ti, dict): + for fk in ("path", "file_path", "file", "filename"): + _harvest_file(ti.get(fk, ""), file_counts, concept_counts) + # narrative may be JSON string with path/tool info + narr = o.get("narrative") or o.get("raw") or "" + if isinstance(narr, str) and narr.startswith("{"): + try: + nd = _j.loads(narr) + if isinstance(nd, dict): + tn2 = nd.get("toolName") or nd.get("tool_name") + if tn2: concept_counts[tn2] += 1 + for fk in ("path", "file_path", "file", "filename"): + _harvest_file(nd.get(fk, ""), file_counts, concept_counts) + except Exception: + pass + + # memories for this project + for m in kv.list(KV.memories): + if m.get("project") == project: + for c in (m.get("concepts") or []): + if c: concept_counts[c] += 1 + for f in (m.get("files") or []): + _harvest_file(f, file_counts, concept_counts) + + res["topConcepts"] = [{"concept": c, "frequency": n} for c, n in concept_counts.most_common(20)] + res["topFiles"] = [{"file": f, "frequency": n} for f, n in file_counts.most_common(20)] + res["sessionCount"] = len(project_sessions) + + return jsonify(res), 200 + +# ===================================================================== +# Missing endpoints the JS viewer calls +# ===================================================================== + +@app.route("/agentmemory/memories", methods=["GET"]) +def api_memories_list(): + auth_err = check_auth() + if auth_err: + return auth_err + + latest_only = request.args.get("latest", "false").lower() == "true" + limit = int(request.args.get("limit", "500")) + all_mems = kv.list(KV.memories) + if latest_only: + all_mems = [m for m in all_mems if m.get("isLatest") is not False] + all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True) + return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200 + +@app.route("/agentmemory/graph/stats", methods=["GET"]) +def api_graph_stats(): + auth_err = check_auth() + if auth_err: + return auth_err + nodes = kv.list(KV.graphNodes) + edges = kv.list(KV.graphEdges) + return jsonify({"nodes": len(nodes), "edges": len(edges), "success": True}), 200 + +@app.route("/agentmemory/semantic", methods=["GET"]) +def api_semantic_list(): + auth_err = check_auth() + if auth_err: + return auth_err + items = kv.list(KV.semantic) + return jsonify({"items": items, "total": len(items)}), 200 + +@app.route("/agentmemory/procedural", methods=["GET"]) +def api_procedural_list(): + auth_err = check_auth() + if auth_err: + return auth_err + items = kv.list(KV.procedural) + return jsonify({"items": items, "total": len(items)}), 200 + +@app.route("/agentmemory/crystals", methods=["GET"]) +def api_crystals_list(): + auth_err = check_auth() + if auth_err: + return auth_err + items = kv.list(KV.crystals) + return jsonify({"crystals": items, "total": len(items)}), 200 + +@app.route("/agentmemory/actions", methods=["GET"]) +def api_actions_list(): + auth_err = check_auth() + if auth_err: + return auth_err + limit = int(request.args.get("limit", "200")) + status = request.args.get("status") + items = kv.list(KV.actions) + if status: + items = [a for a in items if a.get("status") == status] + items.sort(key=lambda a: a.get("updatedAt", ""), reverse=True) + return jsonify({"actions": items[:limit], "total": len(items)}), 200 + +@app.route("/agentmemory/actions", methods=["POST"]) +def api_action_create(): + auth_err = check_auth() + if auth_err: + return auth_err + try: + body = request.get_json(force=True) or {} + action_id = functions.generate_id("act") + from datetime import datetime, timezone + now = datetime.now(timezone.utc).isoformat() + action = { + "id": action_id, + "title": body.get("title", ""), + "description": body.get("description"), + "priority": body.get("priority", 0), + "status": body.get("status", "pending"), + "tags": body.get("tags", []), + "sessionId": body.get("sessionId"), + "createdAt": now, + "updatedAt": now, + } + kv.set(KV.actions, action_id, action) + return jsonify({"action": action, "success": True}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/actions/", methods=["PATCH"]) +def api_action_update(action_id): + auth_err = check_auth() + if auth_err: + return auth_err + try: + body = request.get_json(force=True) or {} + existing = kv.get(KV.actions, action_id) + if not existing: + return jsonify({"error": "not found"}), 404 + from datetime import datetime, timezone + allowed_fields = {"title", "description", "priority", "status", "tags", "sessionId"} + updates = {k: v for k, v in body.items() if k in allowed_fields} + existing.update(updates) + existing["updatedAt"] = datetime.now(timezone.utc).isoformat() + kv.set(KV.actions, action_id, existing) + return jsonify({"action": existing, "success": True}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/frontier", methods=["GET"]) +def api_frontier(): + auth_err = check_auth() + if auth_err: + return auth_err + items = kv.list(KV.actions) + frontier = [a for a in items if a.get("status") in ("pending", "active")] + frontier.sort(key=lambda a: (-(a.get("priority") or 0), a.get("createdAt", ""))) + return jsonify({"frontier": frontier[:50], "total": len(frontier)}), 200 + +@app.route("/agentmemory/insights", methods=["GET"]) +def api_insights_list(): + auth_err = check_auth() + if auth_err: + return auth_err + limit = int(request.args.get("limit", "200")) + items = kv.list(KV.insights) + items.sort(key=lambda x: x.get("createdAt", ""), reverse=True) + return jsonify({"insights": items[:limit], "total": len(items)}), 200 + +@app.route("/agentmemory/replay/load", methods=["GET"]) +def api_replay_load(): + auth_err = check_auth() + if auth_err: + return auth_err + session_id = request.args.get("sessionId") + if not session_id: + return jsonify({"error": "sessionId required"}), 400 + session = kv.get(KV.sessions, session_id) + if not session: + return jsonify({"error": "session not found"}), 404 + obs = kv.list(KV.observations(session_id)) + obs.sort(key=lambda o: o.get("timestamp", "")) + + from dateutil import parser as dtparser + session_start = session.get("startedAt", "") + try: + t0_ms = dtparser.parse(session_start).timestamp() * 1000 if session_start else None + except Exception: + t0_ms = None + + _hook_kind = { + "prompt_submit": "prompt", + "post_tool_use": "tool_call", + "post_tool_failure": "tool_error", + "subagent_stop": "response", + "task_completed": "response", + "notification": "response", + } + + events = [] + for o in obs: + ts = o.get("timestamp", "") + try: + t_ms = dtparser.parse(ts).timestamp() * 1000 if ts else 0 + except Exception: + t_ms = 0 + offset_ms = max(0, t_ms - t0_ms) if t0_ms is not None else t_ms + + hook = o.get("hookType", "") + kind = _hook_kind.get(hook, "prompt") + + # obs fields are top-level (no data wrapper) + tool_name = o.get("toolName") + tool_input = o.get("toolInput") + tool_output = o.get("toolOutput") + + label = (o.get("userPrompt") or + o.get("narrative") or o.get("title") or o.get("summary") or + tool_name or + (o.get("raw") or "")[:80] or hook) + if isinstance(label, str): + label = label[:120] + + events.append({ + "kind": kind, + "label": label, + "offsetMs": offset_ms, + "ts": ts, + "body": o.get("narrative") or o.get("raw") or o.get("summary") or "", + "toolName": tool_name, + "toolInput": tool_input, + "toolOutput": tool_output, + }) + + total_ms = (events[-1]["offsetMs"] + 1000) if events else 0 + timeline = {"events": events, "eventCount": len(events), "totalDurationMs": total_ms} + return jsonify({"session": session, "timeline": timeline, "success": True}), 200 + +@app.route("/agentmemory/replay/import-jsonl", methods=["POST"]) +def api_replay_import_jsonl(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + path = body.get("path") + max_files = body.get("maxFiles") + + import replay_import + res = replay_import.import_jsonl_data(kv, path=path, max_files=max_files) + + status_code = 200 if res.get("success", True) else 400 + return jsonify(res), status_code + except Exception as e: + return jsonify({"error": str(e), "success": False}), 500 + +@app.route("/agentmemory/auto-forget", methods=["POST"]) +def api_auto_forget(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + dry_run = body.get("dryRun", False) + res = functions.auto_forget(kv, dry_run) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/consolidate", methods=["POST"]) +def api_consolidate(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + project = body.get("project") + min_obs = body.get("minObservations") + res = functions.consolidate(kv, project=project, min_observations=min_obs) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/consolidate-pipeline", methods=["POST"]) +def api_consolidate_pipeline(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + res = functions.consolidate(kv) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 400 + +@app.route("/agentmemory/dolt/commits", methods=["GET"]) +def api_dolt_commits(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + limit = int(request.args.get("limit", "50")) + conn = kv._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "SELECT commit_hash, committer, email, date, message FROM dolt_log ORDER BY date DESC LIMIT %s", + (limit,) + ) + rows = cursor.fetchall() + commits = [] + for r in rows: + commits.append({ + "sha": r["commit_hash"], + "shortSha": r["commit_hash"][:7], + "agent": r["committer"], + "email": r["email"], + "date": r["date"].isoformat() + "Z" if isinstance(r["date"], datetime.datetime) else str(r["date"]), + "message": r["message"] + }) + return jsonify({"success": True, "commits": commits}), 200 + finally: + conn.close() + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/agentmemory/second-brain", methods=["GET"]) +def api_get_second_brain(): + auth_err = check_auth() + if auth_err: + return auth_err + + brain_dir = os.getenv("SECOND_BRAIN_DIR", "D:\\Downloads\\Projects\\Other Projects\\Know about me\\second-brain") + if not os.path.exists(brain_dir): + return jsonify({"error": "Second brain directory not found", "path": brain_dir}), 404 + + file_param = request.args.get("file") + if file_param: + safe_name = os.path.basename(file_param) + if not safe_name.endswith(".md"): + return jsonify({"error": "Only markdown files are allowed"}), 400 + file_path = os.path.join(brain_dir, safe_name) + if not os.path.exists(file_path): + return jsonify({"error": f"File {safe_name} not found"}), 404 + try: + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + return jsonify({"file": safe_name, "content": content}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + + try: + files = [] + for name in os.listdir(brain_dir): + if name.endswith(".md") and os.path.isfile(os.path.join(brain_dir, name)): + file_path = os.path.join(brain_dir, name) + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + files.append({ + "name": name, + "size": os.path.getsize(file_path), + "content": content + }) + return jsonify({"success": True, "path": brain_dir, "files": files}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/agentmemory/second-brain", methods=["POST"]) +def api_update_second_brain(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + file_name = body.get("file") + content = body.get("content") + + if not file_name or content is None: + return jsonify({"error": "file and content are required"}), 400 + + safe_name = os.path.basename(file_name) + if not safe_name.endswith(".md"): + return jsonify({"error": "Only markdown files are allowed"}), 400 + + brain_dir = os.getenv("SECOND_BRAIN_DIR", "D:\\Downloads\\Projects\\Other Projects\\Know about me\\second-brain") + if not os.path.exists(brain_dir): + os.makedirs(brain_dir, exist_ok=True) + + file_path = os.path.join(brain_dir, safe_name) + + content = functions.strip_private_data(content) + + with open(file_path, "w", encoding="utf-8") as f: + f.write(content) + + functions.commit_if_enabled(kv, f"Update second-brain file: {safe_name}", "user") + + return jsonify({"success": True, "file": safe_name, "size": len(content)}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + +# ===================================================================== +# MCP Server Integration (JSON-RPC) +# ===================================================================== + +@app.route("/agentmemory/mcp/tools", methods=["GET"]) +def mcp_tools_list(): + auth_err = check_auth() + if auth_err: + return auth_err + + # Return core tools supported by our python daemon + tools = [ + { + "name": "memory_recall", + "description": "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query keywords"}, + "limit": {"type": "number", "description": "Max results to return (default 10)"} + }, + "required": ["query"] + } + }, + { + "name": "memory_save", + "description": "Explicitly save an important insight, decision, or pattern to long-term memory.", + "inputSchema": { + "type": "object", + "properties": { + "content": {"type": "string", "description": "The insight or decision to remember"}, + "type": {"type": "string", "description": "Memory type: pattern, preference, architecture, bug, workflow, or fact"}, + "concepts": {"type": "string", "description": "Comma-separated key concepts"}, + "files": {"type": "string", "description": "Comma-separated relevant file paths"}, + "project": {"type": "string", "description": "Canonical project identifier"} + }, + "required": ["content"] + } + }, + { + "name": "memory_sessions", + "description": "List recent sessions with their status and observation counts.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "memory_smart_search", + "description": "Hybrid semantic+keyword search with progressive disclosure.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query"}, + "limit": {"type": "number", "description": "Max results (default 10)"} + }, + "required": ["query"] + } + }, + { + "name": "memory_timeline", + "description": "Chronological observations around an anchor point.", + "inputSchema": { + "type": "object", + "properties": { + "anchor": {"type": "string", "description": "Anchor point date or keyword"}, + "project": {"type": "string", "description": "Filter by project path"} + }, + "required": ["anchor"] + } + }, + { + "name": "memory_profile", + "description": "User/project profile with top concepts and file patterns.", + "inputSchema": { + "type": "object", + "properties": { + "project": {"type": "string", "description": "Project path"} + }, + "required": ["project"] + } + }, + { + "name": "memory_lesson_save", + "description": "Save a lesson learned from this session.", + "inputSchema": { + "type": "object", + "properties": { + "content": {"type": "string", "description": "The lesson learned"}, + "context": {"type": "string", "description": "When/where this lesson applies"}, + "project": {"type": "string", "description": "Project this lesson is about"} + }, + "required": ["content"] + } + }, + { + "name": "memory_lesson_recall", + "description": "Search lessons by query. Returns lessons sorted by confidence and recency.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query"}, + "project": {"type": "string", "description": "Filter by project"} + }, + "required": ["query"] + } + }, + { + "name": "agent_observe", + "description": "Log a direct observation, thought, command execution, or action from the agent's active execution.", + "inputSchema": { + "type": "object", + "properties": { + "agentId": {"type": "string", "description": "ID/Name of the agent logging this (e.g. 'antigravity')"}, + "sessionId": {"type": "string", "description": "Active session ID"}, + "project": {"type": "string", "description": "Canonical project path/identifier"}, + "text": {"type": "string", "description": "The observation log, thought, or content"}, + "type": {"type": "string", "description": "Observation type: thought, command, tool, error, result, conversation, other"}, + "title": {"type": "string", "description": "A short summary title for the observation"}, + "cwd": {"type": "string", "description": "Current working directory"} + }, + "required": ["agentId", "sessionId", "project", "text"] + } + }, + { + "name": "agent_remember", + "description": "Explicitly save a key insight, fact, user preference, or architecture decision to long-term memory.", + "inputSchema": { + "type": "object", + "properties": { + "agentId": {"type": "string", "description": "ID/Name of the agent (e.g. 'antigravity')"}, + "content": {"type": "string", "description": "The memory content/insight"}, + "project": {"type": "string", "description": "Canonical project path/identifier"}, + "type": {"type": "string", "description": "Memory type: fact, preference, bug, workflow, architecture"}, + "concepts": {"type": "string", "description": "Comma-separated key concepts"}, + "files": {"type": "string", "description": "Comma-separated relevant file paths"} + }, + "required": ["agentId", "content", "project"] + } + } + ] + return jsonify({"tools": tools}), 200 + + +@app.route("/agentmemory/mcp/tools", methods=["POST"]) +def mcp_tools_call(): + auth_err = check_auth() + if auth_err: + return auth_err + + try: + body = request.get_json(force=True) or {} + name = body.get("name") + args = body.get("arguments") or {} + if not name: + return jsonify({"error": "name is required"}), 400 + + print(f"[mcp] Calling tool {name} with args: {args}") + text_out = "" + + if name == "memory_recall": + q = args.get("query") + limit = int(args.get("limit") or 10) + res = functions._hybrid_search.search(q, limit) + text_out = json.dumps(res, indent=2) + + elif name == "memory_save": + content = args.get("content") + concepts = args.get("concepts", "").split(",") if args.get("concepts") else [] + files = args.get("files", "").split(",") if args.get("files") else [] + res = functions.remember(kv, { + "content": content, + "type": args.get("type") or "fact", + "concepts": [c.strip() for c in concepts if c.strip()], + "files": [f.strip() for f in files if f.strip()], + "project": args.get("project") + }) + text_out = json.dumps(res) + + elif name == "memory_sessions": + sessions = functions.list_sessions(kv) + text_out = json.dumps({"sessions": sessions}, indent=2) + + elif name == "memory_smart_search": + q = args.get("query") + limit = int(args.get("limit") or 10) + res = functions._hybrid_search.search(q, limit) + text_out = json.dumps(res, indent=2) + + elif name == "memory_timeline": + res = functions.timeline(kv, { + "anchor": args.get("anchor"), + "project": args.get("project") + }) + text_out = json.dumps(res, indent=2) + + elif name == "memory_profile": + res = functions.get_project_profile(kv, args.get("project")) + text_out = json.dumps(res, indent=2) + + elif name == "memory_lesson_save": + res = functions.lesson_save(kv, { + "content": args.get("content"), + "context": args.get("context"), + "project": args.get("project") + }) + text_out = json.dumps(res) + + elif name == "memory_lesson_recall": + res = functions.lesson_recall(kv, { + "query": args.get("query"), + "project": args.get("project") + }) + text_out = json.dumps(res, indent=2) + + elif name == "agent_observe": + agent_id = args.get("agentId") + session_id = args.get("sessionId") + project = args.get("project") + text = args.get("text") + obs_type = args.get("type") or "other" + title = args.get("title") or f"agent_{obs_type}" + cwd = args.get("cwd") or "" + + if not agent_id or not session_id or not project or not text: + return jsonify({"error": "agentId, sessionId, project, and text are required"}), 400 + + payload = { + "sessionId": session_id, + "project": project, + "cwd": cwd, + "hookType": "post_tool_use", + "timestamp": datetime_now_iso(), + "agentId": agent_id, + "data": { + "tool_name": title, + "tool_input": text, + "tool_output": text, + } + } + res = functions.observe(kv, payload) + text_out = json.dumps(res) + + elif name == "agent_remember": + agent_id = args.get("agentId") + content = args.get("content") + project = args.get("project") + mem_type = args.get("type") or "fact" + concepts = args.get("concepts", "").split(",") if args.get("concepts") else [] + files = args.get("files", "").split(",") if args.get("files") else [] + + if not agent_id or not content or not project: + return jsonify({"error": "agentId, content, and project are required"}), 400 + + payload = { + "content": content, + "type": mem_type, + "concepts": [c.strip() for c in concepts if c.strip()], + "files": [f.strip() for f in files if f.strip()], + "project": project, + "agentId": agent_id + } + res = functions.remember(kv, payload) + text_out = json.dumps(res) + + else: + return jsonify({"error": f"unknown tool: {name}"}), 400 + + + return jsonify({ + "content": [ + {"type": "text", "text": text_out} + ] + }), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + +# ===================================================================== +# Agent Discovery Endpoint (/agent.md and /auth.md) +# ===================================================================== + +AGENT_MD_TEMPLATE = """# AgentMemory — Agent Connection Guide + +> This document is auto-generated. Fetch it fresh each session so you always have current values. + +## 1. Server + +| Field | Value | +|-------|-------| +| Base URL | `http://127.0.0.1:{port}` | +| API prefix | `/agentmemory` | +| Liveness | `GET http://127.0.0.1:{port}/agentmemory/livez` (no auth) | +| Auth required | `{auth_required}` | +| Auth header | `Authorization: Bearer ` | + +{auth_note} + +--- + +## 2. Quick-Start: Minimum Viable Session + +Do these in order at the start of every session: + +``` +1. POST /agentmemory/session/start ← register yourself +2. POST /agentmemory/context ← inject past memory into your system prompt + ... do work, call observe after each tool use ... +3. POST /agentmemory/session/end ← mark session complete +``` + +### 2a. Start a session + +```http +POST /agentmemory/session/start +Content-Type: application/json +{auth_header_example} + +{{ + "sessionId": "", + "project": "", + "cwd": "", + "agentId": "", + "title": "" +}} +``` + +Response includes `context` — paste it into your system prompt before answering. + +### 2b. Compile context (also works mid-session) + +```http +POST /agentmemory/context +Content-Type: application/json +{auth_header_example} + +{{ + "sessionId": "", + "project": "", + "budget": 2000 +}} +``` + +Returns `context` string wrapped in `` tags. Insert verbatim. + +### 2c. Log an observation (call after every significant tool use) + +```http +POST /agentmemory/agent/observe +Content-Type: application/json +{auth_header_example} + +{{ + "agentId": "", + "sessionId": "", + "project": "", + "cwd": "", + "text": "", + "type": "tool | command | thought | error | result | conversation | other", + "title": "" +}} +``` + +### 2d. Save a long-term memory (decisions, patterns, preferences) + +```http +POST /agentmemory/agent/remember +Content-Type: application/json +{auth_header_example} + +{{ + "agentId": "", + "project": "", + "content": "", + "type": "fact | preference | architecture | bug | workflow | pattern", + "concepts": "auth, jwt, middleware", + "files": "src/middleware/auth.ts, tests/auth.test.ts" +}} +``` + +### 2e. End session + +```http +POST /agentmemory/session/end +Content-Type: application/json +{auth_header_example} + +{{ + "sessionId": "" +}} +``` + +--- + +## 3. MCP Tools (JSON-RPC style) + +Call via: `POST /agentmemory/mcp/tools` + +```http +POST /agentmemory/mcp/tools +Content-Type: application/json +{auth_header_example} + +{{ + "name": "", + "arguments": {{ ... }} +}} +``` + +| Tool | Required args | Description | +|------|---------------|-------------| +| `memory_recall` | `query` | BM25+vector hybrid search over all past observations | +| `memory_smart_search` | `query` | Same as recall with progressive disclosure | +| `memory_save` | `content` | Save long-term memory (type, concepts, files optional) | +| `memory_sessions` | — | List recent sessions with observation counts | +| `memory_timeline` | `anchor` | Observations around a date or keyword anchor | +| `memory_profile` | `project` | Top concepts, files, conventions for a project | +| `memory_lesson_save` | `content` | Save a lesson (auto-strengthens duplicates) | +| `memory_lesson_recall` | `query` | Search lessons scored by confidence + recency | +| `agent_observe` | `agentId`, `sessionId`, `project`, `text` | Log an observation (same as REST) | +| `agent_remember` | `agentId`, `content`, `project` | Save memory (same as REST) | + +Get full schemas: `GET /agentmemory/mcp/tools` + +--- + +## 4. Full REST Endpoint Reference + +All endpoints require `Authorization: Bearer ` when auth is enabled. +Prefix every path with `http://127.0.0.1:{port}`. + +### Session Management + +| Method | Path | Key body fields | Notes | +|--------|------|-----------------|-------| +| `POST` | `/agentmemory/session/start` | `sessionId`, `project`, `cwd`, `agentId` | Returns `session` + `context` | +| `POST` | `/agentmemory/session/end` | `sessionId` | Marks status=completed | +| `GET` | `/agentmemory/sessions` | — | List all sessions | +| `GET` | `/agentmemory/observations?sessionId=` | — | Observations for a session | +| `POST` | `/agentmemory/session/commit` | `sha`, `sessionId`, `branch`, `message` | Link a git commit to a session | +| `GET` | `/agentmemory/session/by-commit?sha=` | — | Sessions linked to a commit | +| `GET` | `/agentmemory/commits` | `branch`, `repo`, `limit` | List tracked commits | + +### Observations + +| Method | Path | Key body fields | Notes | +|--------|------|-----------------|-------| +| `POST` | `/agentmemory/observe` | `sessionId`, `hookType`, `timestamp`, `data` | Raw hook payload | +| `POST` | `/agentmemory/agent/observe` | `agentId`, `sessionId`, `project`, `text`, `type` | Simplified agent endpoint | + +`hookType` values: `post_tool_use`, `post_tool_failure`, `prompt_submit`, `subagent_stop`, `task_completed`, `notification` + +### Memory + +| Method | Path | Key body fields | Notes | +|--------|------|-----------------|-------| +| `POST` | `/agentmemory/remember` | `content`, `type`, `concepts[]`, `files[]`, `project` | Supersedes similar memories automatically | +| `POST` | `/agentmemory/agent/remember` | `agentId`, `content`, `project`, `type`, `concepts`, `files` | Simplified agent endpoint | +| `POST` | `/agentmemory/forget` | `memoryId` OR `sessionId` [+ `observationIds[]`] | Delete memory/session/observations | +| `POST` | `/agentmemory/evolve` | `memoryId`, `newContent`, `newTitle` | Version a memory (creates new, marks old superseded) | +| `POST` | `/agentmemory/search` | `query`, `limit` | Hybrid BM25+vector search | +| `POST` | `/agentmemory/context` | `sessionId`, `project`, `budget` | Compile context block for injection | + +Memory `type` values: `fact`, `preference`, `architecture`, `bug`, `workflow`, `pattern` + +### Lessons + +| Method | Path | Key body fields | Notes | +|--------|------|-----------------|-------| +| `POST` | `/agentmemory/lessons` | `content`, `context`, `project`, `confidence`, `tags[]` | Create/strengthen (duplicate = auto-reinforce) | +| `GET` | `/agentmemory/lessons` | `project`, `minConfidence`, `limit` | List lessons | +| `POST` | `/agentmemory/lessons/search` | `query`, `project`, `limit` | Keyword search scored by confidence×recency | +| `POST` | `/agentmemory/lessons/strengthen` | `lessonId` | Manually reinforce a lesson (+0.1 confidence) | + +### Memory Slots (Pinned Context) + +Slots are named text buffers injected into every context compilation. + +| Method | Path | Key body/query fields | Notes | +|--------|------|-----------------------|-------| +| `GET` | `/agentmemory/slots` | — | List all slots | +| `GET` | `/agentmemory/slot?label=` | — | Get single slot | +| `POST` | `/agentmemory/slot` | `label`, `content`, `scope`, `sizeLimit`, `pinned` | Create slot | +| `POST` | `/agentmemory/slot/append` | `label`, `text` | Append text to slot | +| `POST` | `/agentmemory/slot/replace` | `label`, `content` | Replace slot content | +| `DELETE` | `/agentmemory/slot?label=` | — | Delete slot | +| `POST` | `/agentmemory/slot/reflect` | `sessionId`, `maxObservations` | Auto-populate slots from session observations | + +Default slot labels: `persona`, `user_preferences`, `tool_guidelines`, `project_context`, `guidance`, `pending_items`, `session_patterns`, `self_notes` + +### Knowledge Graph & Analytics + +| Method | Path | Key body/query fields | Notes | +|--------|------|-----------------------|-------| +| `GET` | `/agentmemory/relations` | — | List all knowledge graph edges | +| `POST` | `/agentmemory/relations` | `sourceId`, `targetId`, `type` | Add a relation edge | +| `POST` | `/agentmemory/timeline` | `anchor`, `project`, `before`, `after` | Observations around anchor | +| `GET` | `/agentmemory/profile?project=` | — | Project profile (top concepts/files) | +| `GET` | `/agentmemory/audit` | `operation`, `limit` | Audit log | +| `GET` | `/agentmemory/profile` | `project` (optional) | Project profile; omit `project` to list all known projects | +| `GET` | `/agentmemory/actions` | `limit`, `status` | List actions | +| `POST` | `/agentmemory/actions` | `title`, `description`, `priority`, `tags[]`, `status` | Create action | +| `PATCH`| `/agentmemory/actions/` | any action fields | Update action | +| `GET` | `/agentmemory/frontier` | — | Pending+active actions sorted by priority | +| `GET` | `/agentmemory/insights` | `limit` | List insights | +| `GET` | `/agentmemory/replay/sessions` | — | Sessions list for replay | +| `GET` | `/agentmemory/replay/load?sessionId=` | — | Full session + ordered observations for replay | +| `POST` | `/agentmemory/auto-forget` | `dryRun` | Evict stale observations | + +### Health & Config + +| Method | Path | Auth | Notes | +|--------|------|------|-------| +| `GET` | `/agentmemory/livez` | No | Liveness check | +| `GET` | `/agentmemory/health` | Yes | Full health + version | +| `GET` | `/agentmemory/config/flags` | Yes | Feature flags (graph, consolidation, compression) | + +--- + +## 5. WebSocket Live Stream + +``` +ws://127.0.0.1:{port}/stream/mem-live/viewer +``` + +Connect to receive real-time events. Message types: +- `raw_observation` — raw hook payload as received +- `compressed_observation` — after synthetic compression + indexing + +No auth on the WebSocket endpoint. + +--- + +## 6. Agent Identity & Scope Isolation + +Set `AGENT_ID` env var on the server to scope all read operations to a single agent. +Set `AGENTMEMORY_AGENT_SCOPE=isolated` to enforce per-agent isolation. + +Always pass `agentId` in every request body — it's stored on every observation/memory and enables per-agent filtering via `?agentId=` on list endpoints. + +--- + +## 7. Secrets Are Redacted + +Any text containing API keys, Bearer tokens, passwords, or JWTs is automatically redacted to `[REDACTED_SECRET]` before storage. Wrap sensitive blocks in `...` tags to force redaction. + +--- + +*Generated by agentmemory v{version} — `GET /agent.md` to refresh* +""" + +@app.route("/agent.md", methods=["GET"]) +@app.route("/auth.md", methods=["GET"]) +def agent_discovery(): + auth_err = check_auth() + if auth_err: + return auth_err + port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111"))) + secret = os.getenv("AGENTMEMORY_SECRET") + auth_required = "yes" if secret else "no" + + if secret: + auth_note = ( + "> **Auth is enabled.** Add `Authorization: Bearer ` to every request.\n" + "> The secret is set via `AGENTMEMORY_SECRET` env var in `~/.agentmemory/.env`." + ) + auth_header_example = 'Authorization: Bearer ' + else: + auth_note = ( + "> **Auth is disabled.** No `Authorization` header needed — all endpoints are open." + ) + auth_header_example = '' + + md = AGENT_MD_TEMPLATE.format( + port=port, + auth_required=auth_required, + auth_note=auth_note, + auth_header_example=auth_header_example, + version="0.9.8", + ) + + response = make_response(md) + response.headers["Content-Type"] = "text/markdown; charset=utf-8" + response.headers["Cache-Control"] = "no-cache" + return response + +# ===================================================================== +# Lifecycle Helpers +# ===================================================================== + +if __name__ == "__main__": + init_app() + # Default Flask server settings + port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111"))) + # Listen on all interfaces (required for container deployments like HF Spaces) + print(f"[main] Starting Flask daemon on port {port}...") + app.run(host="0.0.0.0", port=port, debug=False) diff --git a/src/db.py b/src/db.py new file mode 100644 index 0000000000000000000000000000000000000000..605cd14b50b41d2cf28469badda11e74f1edcbef --- /dev/null +++ b/src/db.py @@ -0,0 +1,225 @@ +import os +import json +import pymysql +import urllib.parse +from typing import Dict, Any, List, Optional, TypeVar, Union + +T = TypeVar("T") + +class StateKV: + def __init__(self): + self.host = os.getenv("DOLT_HOST", "127.0.0.1") + self.port = int(os.getenv("DOLT_PORT", "3306")) + self.user = os.getenv("DOLT_USER", "root") + self.password = os.getenv("DOLT_PASSWORD", "") + self.database = os.getenv("DOLT_DATABASE", "agentmemory") + + self._init_db() + + def _get_conn(self) -> pymysql.connections.Connection: + return pymysql.connect( + host=self.host, + port=self.port, + user=self.user, + password=self.password, + database=self.database, + charset="utf8mb4", + cursorclass=pymysql.cursors.DictCursor, + autocommit=True + ) + + def _init_db(self): + try: + # First, check connection and create database if not exists + conn = pymysql.connect( + host=self.host, + port=self.port, + user=self.user, + password=self.password, + charset="utf8mb4", + autocommit=True + ) + try: + with conn.cursor() as cursor: + cursor.execute(f"CREATE DATABASE IF NOT EXISTS {self.database}") + finally: + conn.close() + + # Now connect to database and initialize schema + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute(""" + CREATE TABLE IF NOT EXISTS kv_store ( + scope VARCHAR(255) NOT NULL, + `key` VARCHAR(255) NOT NULL, + value LONGTEXT NOT NULL, + PRIMARY KEY (scope, `key`) + ) + """) + try: + cursor.execute("CREATE INDEX idx_kv_scope ON kv_store(scope)") + except Exception as e: + # Index might already exist, ignore error 1061 / 1105 (duplicate key name) + if hasattr(e, 'args') and len(e.args) > 0 and (e.args[0] in (1061, 1105) or "Duplicate key name" in str(e)): + pass + else: + raise e + finally: + conn.close() + print(f"[db] Dolt database '{self.database}' initialized successfully.") + except Exception as e: + print(f"[db] WARNING initializing Dolt database: {e}") + print(f"[db] Please ensure your Dolt SQL Server is running on {self.host}:{self.port}") + # Do not raise error to allow the app to boot, though subsequent operations will fail if Dolt is off. + + def get(self, scope: str, key: str) -> Optional[Any]: + try: + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "SELECT value FROM kv_store WHERE scope = %s AND `key` = %s", + (scope, key) + ) + row = cursor.fetchone() + if row: + return json.loads(row["value"]) + return None + finally: + conn.close() + except Exception as e: + print(f"[db] get failed (scope={scope}, key={key}): {e}") + return None + + def set(self, scope: str, key: str, value: Any) -> Any: + try: + conn = self._get_conn() + try: + serialized = json.dumps(value) + with conn.cursor() as cursor: + cursor.execute( + "REPLACE INTO kv_store (scope, `key`, value) VALUES (%s, %s, %s)", + (scope, key, serialized) + ) + return value + finally: + conn.close() + except Exception as e: + print(f"[db] set failed (scope={scope}, key={key}): {e}") + return value + + def delete(self, scope: str, key: str) -> bool: + try: + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "DELETE FROM kv_store WHERE scope = %s AND `key` = %s", + (scope, key) + ) + affected = cursor.rowcount + return affected > 0 + finally: + conn.close() + except Exception as e: + print(f"[db] delete failed (scope={scope}, key={key}): {e}") + return False + + def list(self, scope: str) -> List[Any]: + try: + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "SELECT value FROM kv_store WHERE scope = %s", + (scope,) + ) + rows = cursor.fetchall() + return [json.loads(row["value"]) for row in rows] + finally: + conn.close() + except Exception as e: + print(f"[db] list failed (scope={scope}): {e}") + return [] + + def update(self, scope: str, key: str, ops: List[Dict[str, Any]]) -> Optional[Any]: + try: + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "SELECT value FROM kv_store WHERE scope = %s AND `key` = %s FOR UPDATE", + (scope, key) + ) + row = cursor.fetchone() + obj = json.loads(row["value"]) if row else {} + if not isinstance(obj, dict): + obj = {} + + for op in ops: + op_type = op.get("type") + path = op.get("path") + val = op.get("value") + + if not path: + continue + + if op_type == "set": + if "." in path: + parts = path.split(".") + curr = obj + for part in parts[:-1]: + if part not in curr or not isinstance(curr[part], dict): + curr[part] = {} + curr = curr[part] + curr[parts[-1]] = val + else: + obj[path] = val + elif op_type == "delete": + if "." in path: + parts = path.split(".") + curr = obj + for part in parts[:-1]: + if part not in curr or not isinstance(curr[part], dict): + break + curr = curr[part] + else: + curr.pop(parts[-1], None) + else: + obj.pop(path, None) + + serialized = json.dumps(obj) + cursor.execute( + "REPLACE INTO kv_store (scope, `key`, value) VALUES (%s, %s, %s)", + (scope, key, serialized) + ) + return obj + finally: + conn.close() + except Exception as e: + print(f"[db] update failed (scope={scope}, key={key}): {e}") + return None + + def commit_version(self, message: str, agent_id: str) -> Optional[str]: + author_name = agent_id or "unknown-agent" + author_email = f"{author_name}@agentmemory.ai" + author_str = f"{author_name} <{author_email}>" + + try: + conn = self._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute("CALL dolt_add('-A')") + cursor.execute("CALL dolt_commit('-m', %s, '--author', %s)", (message, author_str)) + row = cursor.fetchone() + if row: + val = list(row.values())[0] if isinstance(row, dict) else row[0] + print(f"[dolt commit] Created commit: {val}") + return val + return None + finally: + conn.close() + except Exception as e: + print(f"[dolt commit] Failed: {e}") + return None diff --git a/src/functions.py b/src/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..f60d306478dd9a70770fc0be599e410dc6b48b51 --- /dev/null +++ b/src/functions.py @@ -0,0 +1,1996 @@ +import os +import re +import time +import uuid +import json +import hashlib +import datetime +from typing import Dict, Any, List, Optional, Tuple, Set +from db import StateKV +from search import ( + SearchIndex, + VectorIndex, + GeminiEmbeddingProvider, + HybridSearch, + base64_to_float32, + float32_to_base64 +) + +# ===================================================================== +# Global Variables / Module State +# ===================================================================== +_bm25_index = SearchIndex() +_vector_index = VectorIndex() +_embedding_provider = None +_hybrid_search = HybridSearch(_bm25_index, _vector_index, None, None) +_index_persistence = None +_stream_broadcaster = None # Callable: (payload) -> None + +# Default scopes matching schema.ts +class KV: + sessions = "mem:sessions" + memories = "mem:memories" + summaries = "mem:summaries" + config = "mem:config" + metrics = "mem:metrics" + health = "mem:health" + bm25Index = "mem:index:bm25" + relations = "mem:relations" + profiles = "mem:profiles" + claudeBridge = "mem:claude-bridge" + graphNodes = "mem:graph:nodes" + graphEdges = "mem:graph:edges" + graphSnapshot = "mem:graph:snapshot" + graphNameIndex = "mem:graph:name-index" + graphEdgeKey = "mem:graph:edge-key" + graphNodeDegree = "mem:graph:node-degree" + semantic = "mem:semantic" + procedural = "mem:procedural" + audit = "mem:audit" + actions = "mem:actions" + actionEdges = "mem:action-edges" + leases = "mem:leases" + routines = "mem:routines" + routineRuns = "mem:routine-runs" + signals = "mem:signals" + checkpoints = "mem:checkpoints" + mesh = "mem:mesh" + sketches = "mem:sketches" + facets = "mem:facets" + sentinels = "mem:sentinels" + crystals = "mem:crystals" + lessons = "mem:lessons" + insights = "mem:insights" + graphEdgeHistory = "mem:graph:edge-history" + retentionScores = "mem:retention" + accessLog = "mem:access" + imageRefs = "mem:image-refs" + slots = "mem:slots" + globalSlots = "mem:slots:global" + commits = "mem:commits" + recentSearches = "mem:recent-searches" + + @staticmethod + def observations(session_id: str) -> str: + return f"mem:obs:{session_id}" + + @staticmethod + def team_shared(team_id: str) -> str: + return f"mem:team:{team_id}:shared" + + @staticmethod + def team_users(team_id: str, user_id: str) -> str: + return f"mem:team:{team_id}:users:{user_id}" + + @staticmethod + def team_profile(team_id: str) -> str: + return f"mem:team:{team_id}:profile" + + @staticmethod + def enriched_chunks(session_id: str) -> str: + return f"mem:enriched:{session_id}" + + @staticmethod + def latent_embeddings(obs_id: str) -> str: + return f"mem:latent:{obs_id}" + +# ===================================================================== +# Core Helpers & Utilities +# ===================================================================== + +def generate_id(prefix: str) -> str: + t = int(time.time() * 1000) + chars = "0123456789abcdefghijklmnopqrstuvwxyz" + ts_str = "" + while t > 0: + ts_str = chars[t % 36] + ts_str + t //= 36 + if not ts_str: + ts_str = "0" + rand = uuid.uuid4().hex[:12] + return f"{prefix}_{ts_str}_{rand}" + +def fingerprint_id(prefix: str, content: str) -> str: + h = hashlib.sha256(content.strip().lower().encode('utf-8')).hexdigest() + return f"{prefix}_{h[:16]}" + +def jaccard_similarity(a: str, b: str) -> float: + tokens_a = [t for t in a.split() if len(t) > 2] + tokens_b = [t for t in b.split() if len(t) > 2] + set_a = set(tokens_a) + set_b = set(tokens_b) + if not set_a and not set_b: + return 1.0 + if not set_a or not set_b: + return 0.0 + intersection = len(set_a.intersection(set_b)) + union = len(set_a.union(set_b)) + return intersection / union + +# ===================================================================== +# Privacy & Data Scrubbing +# ===================================================================== + +PRIVATE_TAG_RE = re.compile(r'[\s\S]*?', re.IGNORECASE) + +SECRET_PATTERN_SOURCES = [ + re.compile(r'(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["\']?[A-Za-z0-9_\-/.+]{20,}["\']?', re.IGNORECASE), + re.compile(r'Bearer\s+[A-Za-z0-9._\-+/=]{20,}', re.IGNORECASE), + re.compile(r'sk-proj-[A-Za-z0-9\-_]{20,}', re.IGNORECASE), + re.compile(r'(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}', re.IGNORECASE), + re.compile(r'sk-ant-[A-Za-z0-9\-_]{20,}', re.IGNORECASE), + re.compile(r'gh[pus]_[A-Za-z0-9]{36,}', re.IGNORECASE), + re.compile(r'github_pat_[A-Za-z0-9_]{22,}', re.IGNORECASE), + re.compile(r'xoxb-[A-Za-z0-9\-]+', re.IGNORECASE), + re.compile(r'AKIA[0-9A-Z]{16}', re.IGNORECASE), + re.compile(r'AIza[A-Za-z0-9\-_]{35}', re.IGNORECASE), + re.compile(r'eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}', re.IGNORECASE), + re.compile(r'npm_[A-Za-z0-9]{36}', re.IGNORECASE), + re.compile(r'glpat-[A-Za-z0-9\-_]{20,}', re.IGNORECASE), + re.compile(r'dop_v1_[A-Za-z0-9]{64}', re.IGNORECASE), +] + +def strip_private_data(input_str: str) -> str: + result = PRIVATE_TAG_RE.sub("[REDACTED]", input_str) + for pattern in SECRET_PATTERN_SOURCES: + result = pattern.sub("[REDACTED_SECRET]", result) + return result + +# ===================================================================== +# Audit Log System +# ===================================================================== + +def record_audit( + kv: StateKV, + operation: str, + function_id: str, + target_ids: List[str], + details: Dict[str, Any] = {}, + quality_score: Optional[float] = None, + user_id: Optional[str] = None, +) -> Dict[str, Any]: + entry = { + "id": generate_id("aud"), + "timestamp": datetime.datetime.utcnow().isoformat() + "Z", + "operation": operation, + "userId": user_id, + "functionId": function_id, + "targetIds": target_ids, + "details": details, + "qualityScore": quality_score, + } + kv.set(KV.audit, entry["id"], entry) + return entry + +def safe_audit( + kv: StateKV, + operation: str, + function_id: str, + target_ids: List[str], + details: Dict[str, Any] = {}, + quality_score: Optional[float] = None, + user_id: Optional[str] = None, +) -> None: + try: + record_audit(kv, operation, function_id, target_ids, details, quality_score, user_id) + except Exception as e: + print(f"[audit] Failed to write audit: {e}") + +def query_audit( + kv: StateKV, + filter_opts: Optional[Dict[str, Any]] = None +) -> List[Dict[str, Any]]: + all_entries = kv.list(KV.audit) + entries = sorted(all_entries, key=lambda x: x.get("timestamp", ""), reverse=True) + if not filter_opts: + return entries[:100] + + op = filter_opts.get("operation") + if op: + entries = [e for e in entries if e.get("operation") == op] + + import dateutil.parser + + date_from = filter_opts.get("dateFrom") + if date_from: + try: + dt_from = dateutil.parser.parse(date_from).replace(tzinfo=None) + filtered_entries = [] + for e in entries: + ts = e.get("timestamp") + if ts: + try: + dt_ts = dateutil.parser.parse(ts).replace(tzinfo=None) + if dt_ts >= dt_from: + filtered_entries.append(e) + except Exception: + pass + entries = filtered_entries + except Exception: + pass + + date_to = filter_opts.get("dateTo") + if date_to: + try: + dt_to = dateutil.parser.parse(date_to).replace(tzinfo=None) + filtered_entries = [] + for e in entries: + ts = e.get("timestamp") + if ts: + try: + dt_ts = dateutil.parser.parse(ts).replace(tzinfo=None) + if dt_ts <= dt_to: + filtered_entries.append(e) + except Exception: + pass + entries = filtered_entries + except Exception: + pass + + limit = filter_opts.get("limit", 100) + return entries[:limit] + +# ===================================================================== +# Image Store System +# ===================================================================== + +IMAGES_DIR = os.path.join(os.path.expanduser("~"), ".agentmemory", "images") + +def get_max_bytes() -> int: + return int(os.getenv("AGENTMEMORY_IMAGE_STORE_MAX_BYTES", 500 * 1024 * 1024)) + +def is_managed_image_path(file_path: str) -> bool: + if not file_path: + return False + resolved = os.path.abspath(file_path) + normalized_images_dir = os.path.abspath(IMAGES_DIR) + return resolved.startswith(normalized_images_dir + os.sep) or resolved == normalized_images_dir + +def save_image_to_disk(base64_data: str) -> Tuple[str, int]: + if not base64_data: + return "", 0 + + if not os.path.exists(IMAGES_DIR): + os.makedirs(IMAGES_DIR, exist_ok=True) + + clean_base64 = base64_data + ext = "png" + + if base64_data.startswith("data:image/"): + comma_idx = base64_data.find(",") + if comma_idx != -1: + meta = base64_data[:comma_idx] + if "jpeg" in meta or "jpg" in meta: + ext = "jpg" + elif "webp" in meta: + ext = "webp" + elif "gif" in meta: + ext = "gif" + clean_base64 = base64_data[comma_idx + 1:] + elif base64_data.startswith("/9j/"): + ext = "jpg" + + h = hashlib.sha256(clean_base64.encode('utf-8')).hexdigest() + file_path = os.path.join(IMAGES_DIR, f"{h}.{ext}") + + if os.path.exists(file_path): + return file_path, 0 + + import base64 + buffer = base64.b64decode(clean_base64) + with open(file_path, "wb") as f: + f.write(buffer) + + size = os.path.getsize(file_path) + return file_path, size + +def delete_image(file_path: Optional[str]) -> int: + if not file_path or not is_managed_image_path(file_path): + return 0 + try: + if os.path.exists(file_path): + size = os.path.getsize(file_path) + os.remove(file_path) + return size + except Exception as e: + print(f"[agentmemory] Failed to delete image context: {e}") + return 0 + +def touch_image(file_path: str) -> None: + if not file_path or not is_managed_image_path(file_path): + return + try: + if os.path.exists(file_path): + os.utime(file_path, None) + except Exception: + pass + +# ===================================================================== +# Index Persistence System (JSON Sharded) +# ===================================================================== + +class IndexPersistence: + def __init__(self, kv: StateKV, bm25: SearchIndex, vector: Optional[VectorIndex]): + self.kv = kv + self.bm25 = bm25 + self.vector = vector + + def schedule_save(self) -> None: + self.save() + + def save(self) -> None: + try: + self.save_sharded_index( + json.dumps(self.bm25.serialize_data()), + "data:manifest", + "data", + "mem:index:bm25:bm25:" + ) + if self.vector: + self.save_sharded_index( + json.dumps(self.vector.serialize_data()), + "vectors:manifest", + "vectors", + "mem:index:bm25:vectors:" + ) + except Exception as e: + print(f"[index persistence] failed to save index: {e}") + + def save_sharded_index(self, serialized: str, manifest_key: str, legacy_key: str, scope_prefix: str) -> None: + previous = self.kv.get(KV.bm25Index, manifest_key) + generation = generate_id("idx") + chunk_chars = 2000000 + shards = [] + chunks = [] + + offset = 0 + shard_idx = 0 + while offset < len(serialized): + scope = f"{scope_prefix}{generation}:{str(shard_idx).zfill(5)}" + chunk = serialized[offset:offset + chunk_chars] + shards.append({"scope": scope, "key": "data", "chars": len(chunk)}) + chunks.append(chunk) + offset += chunk_chars + shard_idx += 1 + + for shard, chunk in zip(shards, chunks): + self.kv.set(shard["scope"], shard["key"], chunk) + + next_manifest = { + "v": 1, + "generation": generation, + "shards": shards, + "chars": len(serialized) + } + + self.kv.set(KV.bm25Index, manifest_key, next_manifest) + self.kv.delete(KV.bm25Index, legacy_key) + + # Cleanup ALL obsolete shards starting with scope_prefix that are NOT in the current shards + try: + conn = self.kv._get_conn() + try: + with conn.cursor() as cursor: + cursor.execute( + "SELECT DISTINCT scope FROM kv_store WHERE scope LIKE %s", + (scope_prefix + "%",) + ) + rows = cursor.fetchall() + current_scopes = {s["scope"] for s in shards} + to_delete = [] + for row in rows: + scope_name = row["scope"] + if scope_name not in current_scopes: + to_delete.append(scope_name) + + if to_delete: + for i in range(0, len(to_delete), 50): + chunk_delete = to_delete[i:i + 50] + format_strings = ','.join(['%s'] * len(chunk_delete)) + cursor.execute( + f"DELETE FROM kv_store WHERE scope IN ({format_strings})", + tuple(chunk_delete) + ) + finally: + conn.close() + except Exception as ex: + print(f"[index persistence] error cleaning up obsolete shards: {ex}") + + if previous and isinstance(previous, dict) and previous.get("v") == 1 and isinstance(previous.get("shards"), list): + current_shards = {(s["scope"], s["key"]) for s in shards} + for old_shard in previous["shards"]: + if (old_shard["scope"], old_shard["key"]) not in current_shards: + self.kv.delete(old_shard["scope"], old_shard["key"]) + + def load(self) -> Dict[str, Any]: + bm25_data = self.load_sharded_data("data", "data:manifest") + bm25_loaded = False + if bm25_data: + try: + self.bm25.restore_from_data(json.loads(bm25_data)) + bm25_loaded = True + except Exception as e: + print(f"[index persistence] failed to restore BM25: {e}") + + vector_loaded = False + if self.vector: + vector_data = self.load_sharded_data("vectors", "vectors:manifest") + if vector_data: + try: + self.vector.restore_from_data(json.loads(vector_data)) + vector_loaded = True + except Exception as e: + print(f"[index persistence] failed to restore vectors: {e}") + + return {"bm25": bm25_loaded, "vector": vector_loaded} + + def load_sharded_data(self, legacy_key: str, manifest_key: str) -> Optional[str]: + manifest = self.kv.get(KV.bm25Index, manifest_key) + if manifest and isinstance(manifest, dict) and manifest.get("v") == 1: + shards = manifest.get("shards", []) + chunks = [] + for shard in shards: + chunk = self.kv.get(shard["scope"], shard["key"]) + if chunk is None: + return None + chunks.append(chunk) + return "".join(chunks) + + legacy = self.kv.get(KV.bm25Index, legacy_key) + if isinstance(legacy, str): + return legacy + return None + +# ===================================================================== +# Vector Index / Embedding Helpers +# ===================================================================== + +def clip_embed_input(text: str) -> str: + EMBED_MAX_CHARS = 16000 + if len(text) <= EMBED_MAX_CHARS: + return text + return text[:EMBED_MAX_CHARS] + +def get_agent_id() -> Optional[str]: + return os.getenv("AGENT_ID") or None + +def commit_if_enabled(kv: StateKV, message: str, agent_id: Optional[str]) -> Optional[str]: + if os.getenv("DOLT_AUTO_COMMIT") == "false": + return None + return kv.commit_version(message, agent_id or "unknown-agent") + + +def is_agent_scope_isolated() -> bool: + return os.getenv("AGENTMEMORY_AGENT_SCOPE") == "isolated" + +def is_auto_compress_enabled() -> bool: + return os.getenv("AGENTMEMORY_AUTO_COMPRESS") == "true" + +def is_slots_enabled() -> bool: + return os.getenv("AGENTMEMORY_SLOTS") == "true" + +def is_reflect_enabled() -> bool: + return os.getenv("AGENTMEMORY_REFLECT") == "true" + +def is_graph_extraction_enabled() -> bool: + return os.getenv("GRAPH_EXTRACTION_ENABLED") == "true" + +def is_consolidation_enabled() -> bool: + val = os.getenv("CONSOLIDATION_ENABLED") + if val in ("false", "0"): + return False + if val in ("true", "1"): + return True + return bool(os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")) + +def vector_index_add_guarded( + obs_id: str, + session_id: str, + text: str, + context: Dict[str, Any] +) -> bool: + vi = _vector_index + ep = _embedding_provider + if not vi or not ep: + return False + try: + clipped = clip_embed_input(text) + embedding = ep.embed(clipped) + if len(embedding) != ep.dimensions: + print(f"[vector-index] Dimension mismatch: expected {ep.dimensions}, got {len(embedding)}") + return False + vi.add(obs_id, session_id, embedding) + return True + except Exception as e: + print(f"[vector-index] Embed failed: {e}") + return False + +# ===================================================================== +# Observation System (Observe, Synthetic Compression) +# ===================================================================== + +def extract_image(d: Any) -> Optional[str]: + if not d: + return None + if isinstance(d, str): + if d.startswith("data:image/") or d.startswith("iVBORw0KGgo") or d.startswith("/9j/"): + return d + return None + if isinstance(d, dict): + for k in ["image_data", "image_path", "imageBase64", "imagePath"]: + if isinstance(d.get(k), str): + return d[k] + for key, val in d.items(): + match = extract_image(val) + if match: + return match + return None + +def infer_type(tool_name: Optional[str], hook_type: str) -> str: + if hook_type == "post_tool_failure": + return "error" + if hook_type == "prompt_submit": + return "conversation" + if hook_type in ("subagent_stop", "task_completed"): + return "subagent" + if hook_type == "notification": + return "notification" + + if not tool_name: + return "other" + + n = re.sub(r'([a-z])([A-Z])', r'\1_\2', tool_name) + n = re.sub(r'[-\s]+', '_', n).lower() + + def has_word(word: str) -> bool: + return bool(re.search(rf"(^|_){word}(_|$)", n)) or n == word or n.endswith(word) or n.startswith(word) + + if any(has_word(w) for w in ["fetch", "http", "web"]): + return "web_fetch" + if any(has_word(w) for w in ["grep", "search", "glob", "find"]): + return "search" + if any(has_word(w) for w in ["bash", "shell", "exec", "run"]): + return "command_run" + if any(has_word(w) for w in ["edit", "update", "patch", "replace"]): + return "file_edit" + if any(has_word(w) for w in ["write", "create"]): + return "file_write" + if any(has_word(w) for w in ["read", "view"]): + return "file_read" + if any(has_word(w) for w in ["task", "agent"]): + return "subagent" + return "other" + +def extract_files(input_data: Any) -> List[str]: + if not input_data or not isinstance(input_data, dict): + return [] + out = set() + for key in ["file_path", "filepath", "path", "filePath", "file", "pattern"]: + v = input_data.get(key) + if isinstance(v, str) and 0 < len(v) < 512: + out.add(v) + return list(out) + +def stringify_for_narrative(v: Any) -> str: + if v is None: + return "" + if isinstance(v, str): + return v + try: + return json.dumps(v) + except Exception: + return str(v) + +def build_synthetic_compression(raw: Dict[str, Any]) -> Dict[str, Any]: + tool_name = raw.get("toolName") or raw.get("hookType") + input_str = stringify_for_narrative(raw.get("toolInput")) + output_str = stringify_for_narrative(raw.get("toolOutput")) + prompt_str = raw.get("userPrompt") or "" + + parts = [s for s in [prompt_str, input_str, output_str] if len(s) > 0] + narrative = " | ".join(parts) + if len(narrative) > 400: + narrative = narrative[:399] + "\u2026" + + title = tool_name or "observation" + if len(title) > 80: + title = title[:79] + "\u2026" + + subtitle = None + if input_str: + subtitle = input_str + if len(subtitle) > 120: + subtitle = subtitle[:119] + "\u2026" + + res = { + "id": raw["id"], + "sessionId": raw["sessionId"], + "timestamp": raw["timestamp"], + "type": infer_type(raw.get("toolName"), raw["hookType"]), + "title": title, + "subtitle": subtitle, + "facts": [], + "narrative": narrative, + "concepts": [], + "files": extract_files(raw.get("toolInput")), + "importance": 5, + "confidence": 0.3, + } + for k in ["modality", "imageData", "agentId"]: + if raw.get(k) is not None: + res[k] = raw[k] + return res + +def observe(kv: StateKV, payload: Dict[str, Any]) -> Dict[str, Any]: + session_id = payload.get("sessionId") + hook_type = payload.get("hookType") + timestamp = payload.get("timestamp") + + if not session_id or not hook_type or not timestamp: + raise ValueError("Invalid payload: sessionId, hookType, and timestamp are required") + + obs_id = generate_id("obs") + sanitized_data = payload.get("data") + try: + json_str = json.dumps(payload.get("data")) + sanitized = strip_private_data(json_str) + sanitized_data = json.loads(sanitized) + except Exception: + sanitized_data = strip_private_data(str(payload.get("data"))) + + raw = { + "id": obs_id, + "sessionId": session_id, + "timestamp": timestamp, + "hookType": hook_type, + "raw": sanitized_data, + } + + extracted_img = extract_image(sanitized_data) + if isinstance(sanitized_data, dict): + if hook_type in ("post_tool_use", "post_tool_failure"): + raw["toolName"] = sanitized_data.get("tool_name") + raw["toolInput"] = sanitized_data.get("tool_input") + raw["toolOutput"] = sanitized_data.get("tool_output") or sanitized_data.get("error") + if hook_type == "prompt_submit": + raw["userPrompt"] = sanitized_data.get("prompt") + if extracted_img: + raw["modality"] = "mixed" if (raw.get("toolInput") or raw.get("toolOutput") or raw.get("userPrompt")) else "image" + elif isinstance(sanitized_data, str) and extracted_img: + raw["modality"] = "image" + + max_obs = int(os.getenv("MAX_OBS_PER_SESSION", "500")) + if max_obs > 0: + existing = kv.list(KV.observations(session_id)) + if len(existing) >= max_obs: + raise ValueError(f"Session observation limit reached ({max_obs})") + + existing_session = kv.get(KV.sessions, session_id) + inherited_agent_id = existing_session.get("agentId") if existing_session else get_agent_id() + if inherited_agent_id: + raw["agentId"] = inherited_agent_id + + if extracted_img and (extracted_img.startswith("data:image/") or extracted_img.startswith("iVBORw0KGgo") or extracted_img.startswith("/9j/")): + try: + file_path, bytes_written = save_image_to_disk(extracted_img) + raw["imageData"] = file_path + + # Increment image ref count + img_refs = kv.get(KV.imageRefs, file_path) or 0 + kv.set(KV.imageRefs, file_path, img_refs + 1) + except Exception as ex: + print(f"[image store] failed: {ex}") + + # Set raw observation + kv.set(KV.observations(session_id), obs_id, raw) + + # Stream raw observation + broadcast_stream({ + "type": "raw_observation", + "sessionId": session_id, + "data": { + "type": "raw", + "observation": raw, + "sessionId": session_id + } + }) + + if existing_session: + updates = [ + {"type": "set", "path": "updatedAt", "value": datetime.datetime.utcnow().isoformat() + "Z"}, + {"type": "set", "path": "observationCount", "value": (existing_session.get("observationCount") or 0) + 1} + ] + if not existing_session.get("firstPrompt") and isinstance(raw.get("userPrompt"), str): + trimmed = " ".join(raw["userPrompt"].split()).strip() + if trimmed: + updates.append({"type": "set", "path": "firstPrompt", "value": trimmed[:200]}) + kv.update(KV.sessions, session_id, updates) + else: + project = payload.get("project") or "unknown" + cwd = payload.get("cwd") or os.getcwd() + trimmed_prompt = None + if isinstance(raw.get("userPrompt"), str): + trimmed_prompt = " ".join(raw["userPrompt"].split()).strip()[:200] + ts = datetime.datetime.utcnow().isoformat() + "Z" + new_sess = { + "id": session_id, + "project": project, + "cwd": cwd, + "startedAt": payload.get("timestamp") or ts, + "updatedAt": ts, + "status": "active", + "observationCount": 1, + } + if inherited_agent_id: + new_sess["agentId"] = inherited_agent_id + if trimmed_prompt: + new_sess["firstPrompt"] = trimmed_prompt + kv.set(KV.sessions, session_id, new_sess) + + # Perform synthetic compression (we default to synthetic) + synthetic = build_synthetic_compression(raw) + for k in ["hookType", "raw", "toolName", "toolInput", "toolOutput", "userPrompt"]: + if k in raw: + synthetic[k] = raw[k] + kv.set(KV.observations(session_id), obs_id, synthetic) + _bm25_index.add(synthetic) + + comb_text = synthetic["title"] + " " + (synthetic.get("narrative") or "") + vector_index_add_guarded(synthetic["id"], synthetic["sessionId"], comb_text, {"kind": "synthetic", "logId": synthetic["id"]}) + + if _index_persistence: + _index_persistence.schedule_save() + + # Stream compressed observation + broadcast_stream({ + "type": "compressed_observation", + "sessionId": session_id, + "data": { + "type": "compressed", + "observation": synthetic, + "sessionId": session_id + } + }) + + # Commit to Dolt + commit_if_enabled(kv, f"Observe: {synthetic.get('title', 'observation')} in session {session_id[:8]}", synthetic.get("agentId")) + + return {"observationId": obs_id} + + +# ===================================================================== +# Memory System (Remember, Forget, Evolve) +# ===================================================================== + +def memory_to_observation(memory: Dict[str, Any]) -> Dict[str, Any]: + return { + "id": memory["id"], + "sessionId": memory.get("sessionIds", ["memory"])[0] if memory.get("sessionIds") else "memory", + "timestamp": memory["createdAt"], + "type": "decision", + "title": memory["title"], + "facts": [memory["content"]], + "narrative": memory["content"], + "concepts": memory.get("concepts", []), + "files": memory.get("files", []), + "importance": memory.get("strength", 7), + } + +def remember(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + content = data.get("content") + if not content or not content.strip(): + raise ValueError("content is required") + content = strip_private_data(content) + + concepts = data.get("concepts") or [] + files = data.get("files") or [] + source_obs = data.get("sourceObservationIds") or [] + ttl_days = data.get("ttlDays") + mem_type = data.get("type") or "fact" + project = data.get("project") + if project: + project = project.strip() + + now = datetime.datetime.utcnow().isoformat() + "Z" + existing_memories = kv.list(KV.memories) + superseded_id = None + superseded_version = 1 + superseded_memory = None + lower_content = content.lower() + + for existing in existing_memories: + if existing.get("isLatest") is False: + continue + if project and existing.get("project") and existing["project"] != project: + continue + similarity = jaccard_similarity(lower_content, existing.get("content", "").lower()) + if similarity > 0.7: + superseded_id = existing["id"] + superseded_version = existing.get("version") or 1 + superseded_memory = existing + break + + call_agent_id = data.get("agentId") or get_agent_id() + new_mem = { + "id": generate_id("mem"), + "createdAt": now, + "updatedAt": now, + "type": mem_type, + "title": content[:80], + "content": content, + "concepts": concepts, + "files": files, + "sessionIds": [], + "strength": 7, + "version": superseded_version + 1 if superseded_id else 1, + "parentId": superseded_id, + "supersedes": [superseded_id] if superseded_id else [], + "sourceObservationIds": [i for i in source_obs if i], + "isLatest": True, + } + if call_agent_id: + new_mem["agentId"] = call_agent_id + if project: + new_mem["project"] = project + + if ttl_days and isinstance(ttl_days, (int, float)) and ttl_days > 0: + forget_time = datetime.datetime.utcnow() + datetime.timedelta(days=ttl_days) + new_mem["forgetAfter"] = forget_time.isoformat() + "Z" + + if superseded_memory: + superseded_memory["isLatest"] = False + kv.set(KV.memories, superseded_memory["id"], superseded_memory) + + kv.set(KV.memories, new_mem["id"], new_mem) + + try: + _bm25_index.add(memory_to_observation(new_mem)) + except Exception as ex: + print(f"[bm25] memory add failed: {ex}") + + comb_text = new_mem["title"] + " " + new_mem["content"] + vector_index_add_guarded(new_mem["id"], "memory", comb_text, {"kind": "memory", "logId": new_mem["id"]}) + + if _index_persistence: + _index_persistence.schedule_save() + + # Commit to Dolt + commit_if_enabled(kv, f"Remember: {new_mem.get('title', '')}", new_mem.get("agentId")) + + return {"success": True, "memory": new_mem} + + +def forget(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + memory_id = data.get("memoryId") + session_id = data.get("sessionId") + obs_ids = data.get("observationIds") or [] + deleted = 0 + deleted_mem_ids = [] + deleted_obs_ids = [] + deleted_session = False + + if memory_id: + mem = kv.get(KV.memories, memory_id) + kv.delete(KV.memories, memory_id) + if mem and mem.get("imageRef"): + ref = mem["imageRef"] + refs = kv.get(KV.imageRefs, ref) or 0 + if refs > 0: + kv.set(KV.imageRefs, ref, refs - 1) + _bm25_index.remove(memory_id) + if _vector_index: + _vector_index.remove(memory_id) + deleted_mem_ids.append(memory_id) + deleted += 1 + + if session_id and obs_ids: + for oid in obs_ids: + obs = kv.get(KV.observations(session_id), oid) + kv.delete(KV.observations(session_id), oid) + if obs: + img = obs.get("imageData") or obs.get("imageRef") + if img: + refs = kv.get(KV.imageRefs, img) or 0 + if refs > 0: + kv.set(KV.imageRefs, img, refs - 1) + _bm25_index.remove(oid) + if _vector_index: + _vector_index.remove(oid) + deleted_obs_ids.append(oid) + deleted += 1 + + if session_id and not obs_ids and not memory_id: + obs_list = kv.list(KV.observations(session_id)) + for obs in obs_list: + kv.delete(KV.observations(session_id), obs["id"]) + img = obs.get("imageData") or obs.get("imageRef") + if img: + refs = kv.get(KV.imageRefs, img) or 0 + if refs > 0: + kv.set(KV.imageRefs, img, refs - 1) + _bm25_index.remove(obs["id"]) + if _vector_index: + _vector_index.remove(obs["id"]) + deleted_obs_ids.append(obs["id"]) + deleted += 1 + kv.delete(KV.sessions, session_id) + kv.delete(KV.summaries, session_id) + deleted_session = True + deleted += 2 + + if deleted > 0: + if _index_persistence: + _index_persistence.schedule_save() + safe_audit( + kv, + "forget", + "mem::forget", + deleted_mem_ids + deleted_obs_ids, + { + "sessionId": session_id, + "deleted": deleted, + "memoriesDeleted": len(deleted_mem_ids), + "observationsDeleted": len(deleted_obs_ids), + "sessionDeleted": deleted_session, + "reason": "user-initiated forget" + } + ) + + # Commit to Dolt + agent_id = data.get("agentId") or get_agent_id() + commit_if_enabled(kv, f"Forget: memory_id={memory_id} session_id={session_id}", agent_id) + + return {"success": True, "deleted": deleted} + + +# ===================================================================== +# Prompt Context Compilation System +# ===================================================================== + +def estimate_tokens(text: str) -> int: + return int(len(text) / 3) + +def escape_xml_attr(s: str) -> str: + return s.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">") + +def context(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + session_id = data.get("sessionId") + project = data.get("project") + budget = data.get("budget") or int(os.getenv("TOKEN_BUDGET", "2000")) + + if not session_id or not project: + raise ValueError("sessionId and project are required") + + blocks = [] + + # 1. Pinned Slots + pinned_slots = list_pinned_slots(kv) + slot_content = render_pinned_context(pinned_slots) + if slot_content: + blocks.append({ + "type": "memory", + "content": slot_content, + "tokens": estimate_tokens(slot_content), + "recency": int(time.time() * 1000) + }) + + # 2. Profile + profile = kv.get(KV.profiles, project) + if profile: + profile_parts = [] + if profile.get("topConcepts"): + profile_parts.append( + "Concepts: " + ", ".join([c["concept"] for c in profile["topConcepts"][:8]]) + ) + if profile.get("topFiles"): + profile_parts.append( + "Key files: " + ", ".join([f["file"] for f in profile["topFiles"][:5]]) + ) + if profile.get("conventions"): + profile_parts.append("Conventions: " + "; ".join(profile["conventions"])) + if profile.get("commonErrors"): + profile_parts.append("Common errors: " + "; ".join(profile["commonErrors"][:3])) + + if profile_parts: + profile_content = f"## Project Profile\n" + "\n".join(profile_parts) + blocks.append({ + "type": "memory", + "content": profile_content, + "tokens": estimate_tokens(profile_content), + "recency": int(time.time() * 1000) + }) + + # 3. Lessons + lessons = kv.list(KV.lessons) + relevant_lessons = [ + l for l in lessons + if not l.get("deleted") and (not l.get("project") or l["project"] == project) + ] + # Score lessons + def lesson_score(l): + factor = 1.5 if l.get("project") == project else 1.0 + return factor * l.get("confidence", 0.5) + + relevant_lessons.sort(key=lesson_score, reverse=True) + relevant_lessons = relevant_lessons[:10] + + if relevant_lessons: + items = [] + for l in relevant_lessons: + desc = f"- ({l['confidence']:.2f}) {l['content']}" + if l.get("context"): + desc += f" — {l['context']}" + items.append(desc) + lessons_content = "## Lessons Learned\n" + "\n".join(items) + blocks.append({ + "type": "memory", + "content": lessons_content, + "tokens": estimate_tokens(lessons_content), + "recency": int(time.time() * 1000) + }) + + # 4. Sessions & Summaries + all_sessions = kv.list(KV.sessions) + sessions = [ + s for s in all_sessions + if s.get("project") == project and s["id"] != session_id + ] + sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) + sessions = sessions[:10] + + for s in sessions: + summary = kv.get(KV.summaries, s["id"]) + if summary: + content = f"## {summary.get('title', 'Session summary')}\n{summary.get('narrative', '')}\n" \ + f"Decisions: {'; '.join(summary.get('keyDecisions', []))}\n" \ + f"Files: {', '.join(summary.get('filesModified', []))}" + blocks.append({ + "type": "summary", + "content": content, + "tokens": estimate_tokens(content), + "recency": int(time.time() * 1000) + }) + else: + # Fallback to important observations + obs_list = kv.list(KV.observations(s["id"])) + important = [o for o in obs_list if o.get("title") and o.get("importance", 0) >= 5] + if important: + important.sort(key=lambda o: o.get("importance", 0), reverse=True) + top = important[:5] + items = [f"- [{o.get('type')}] {o.get('title')}: {o.get('narrative')}" for o in top] + content = f"## Session {s['id'][:8]} ({s.get('startedAt')})\n" + "\n".join(items) + blocks.append({ + "type": "observation", + "content": content, + "tokens": estimate_tokens(content), + "recency": int(time.time() * 1000) + }) + + blocks.sort(key=lambda b: b.get("recency", 0), reverse=True) + + header = f'' + footer = "" + used_tokens = estimate_tokens(header) + estimate_tokens(footer) + + selected = [] + for b in blocks: + if used_tokens + b["tokens"] > budget: + continue + selected.append(b["content"]) + used_tokens += b["tokens"] + + if not selected: + return {"context": "", "blocks": 0, "tokens": 0} + + res_context = f"{header}\n" + "\n\n".join(selected) + f"\n{footer}" + return {"context": res_context, "blocks": len(selected), "tokens": used_tokens} + +# ===================================================================== +# Memory Slots System +# ===================================================================== + +DEFAULT_SLOTS = [ + { + "label": "persona", + "content": "", + "sizeLimit": 1000, + "description": "How the agent should see itself: role, tone, behavioural guidelines.", + "pinned": True, + "readOnly": False, + "scope": "global", + }, + { + "label": "user_preferences", + "content": "", + "sizeLimit": 2000, + "description": "Coding style, tool preferences, naming conventions, and other habits the user wants preserved across sessions.", + "pinned": True, + "readOnly": False, + "scope": "global", + }, + { + "label": "tool_guidelines", + "content": "", + "sizeLimit": 1500, + "description": "Rules the agent should follow when picking or sequencing tools (e.g. prefer X over Y, never run Z without confirmation).", + "pinned": True, + "readOnly": False, + "scope": "global", + }, + { + "label": "project_context", + "content": "", + "sizeLimit": 3000, + "description": "Architecture decisions, codebase conventions, build/test commands, and cross-cutting constraints for the current project.", + "pinned": True, + "readOnly": False, + "scope": "project", + }, + { + "label": "guidance", + "content": "", + "sizeLimit": 1500, + "description": "Active advice for the next session: what to focus on, what to avoid, open risks.", + "pinned": True, + "readOnly": False, + "scope": "project", + }, + { + "label": "pending_items", + "content": "", + "sizeLimit": 2000, + "description": "Unfinished work, explicit TODOs, and promises made but not yet delivered.", + "pinned": True, + "readOnly": False, + "scope": "project", + }, + { + "label": "session_patterns", + "content": "", + "sizeLimit": 1500, + "description": "Recurring behaviours and common struggles observed across recent sessions.", + "pinned": False, + "readOnly": False, + "scope": "project", + }, + { + "label": "self_notes", + "content": "", + "sizeLimit": 1500, + "description": "Free-form notes the agent keeps for itself: hypotheses, dead ends, things to revisit.", + "pinned": False, + "readOnly": False, + "scope": "project", + }, +] + +def seed_defaults(kv: StateKV) -> None: + now = datetime.datetime.utcnow().isoformat() + "Z" + for tmpl in DEFAULT_SLOTS: + scope = tmpl["scope"] + target = KV.globalSlots if scope == "global" else KV.slots + existing = kv.get(target, tmpl["label"]) + if existing: + continue + slot = dict(tmpl) + slot["createdAt"] = now + slot["updatedAt"] = now + kv.set(target, tmpl["label"], slot) + +def list_pinned_slots(kv: StateKV) -> List[Dict[str, Any]]: + p_slots = kv.list(KV.slots) + g_slots = kv.list(KV.globalSlots) + merged = {} + for s in g_slots: + merged[s["label"]] = s + for s in p_slots: + merged[s["label"]] = s + pinned = [s for s in merged.values() if s.get("pinned") and s.get("content", "").strip()] + pinned.sort(key=lambda s: s["label"]) + return pinned + +def render_pinned_context(slots: List[Dict[str, Any]]) -> str: + if not slots: + return "" + lines = ["# agentmemory pinned slots", ""] + for s in slots: + lines.append(f"## {s['label']}") + lines.append(s["content"].strip()) + lines.append("") + return "\n".join(lines) + +def slot_list(kv: StateKV) -> Dict[str, Any]: + p_slots = kv.list(KV.slots) + g_slots = kv.list(KV.globalSlots) + merged = {} + for s in g_slots: + merged[s["label"]] = s + for s in p_slots: + merged[s["label"]] = s + slots = sorted(list(merged.values()), key=lambda s: s["label"]) + return {"success": True, "slots": slots} + +def slot_get(kv: StateKV, label: str) -> Dict[str, Any]: + project = kv.get(KV.slots, label) + if project: + return {"success": True, "slot": project, "scope": "project"} + global_s = kv.get(KV.globalSlots, label) + if global_s: + return {"success": True, "slot": global_s, "scope": "global"} + return {"success": False, "error": "slot not found"} + +def slot_create(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + label = data.get("label") + if not label or not re.match(r'^[a-z][a-z0-9_]*$', label): + return {"success": False, "error": "label required (lowercase, starts with letter, [a-z0-9_])"} + + scope = data.get("scope") or "project" + if scope not in ("project", "global"): + return {"success": False, "error": "scope must be 'project' or 'global'"} + + limit = data.get("sizeLimit") or 2000 + if not isinstance(limit, int) or limit < 1 or limit > 20000: + return {"success": False, "error": "sizeLimit must be an integer between 1 and 20000"} + + content = strip_private_data(data.get("content") or "") + if len(content) > limit: + return {"success": False, "error": f"content exceeds sizeLimit ({len(content)} > {limit})"} + + description = data.get("description") or "" + pinned = data.get("pinned", True) + + target_kv = KV.globalSlots if scope == "global" else KV.slots + existing = kv.get(target_kv, label) + if existing: + return {"success": False, "error": f"slot already exists in {scope} scope"} + + now = datetime.datetime.utcnow().isoformat() + "Z" + slot = { + "label": label, + "content": content, + "sizeLimit": limit, + "description": description, + "pinned": pinned, + "readOnly": False, + "scope": scope, + "createdAt": now, + "updatedAt": now, + } + kv.set(target_kv, label, slot) + safe_audit(kv, "slot_create", "mem::slot-create", [label], {"scope": scope, "sizeLimit": limit, "pinned": pinned}) + + # Commit to Dolt + agent_id = data.get("agentId") or get_agent_id() + commit_if_enabled(kv, f"Create slot: {label}", agent_id) + + return {"success": True, "slot": slot} + +def slot_append(kv: StateKV, label: str, text: str, agent_id: Optional[str] = None) -> Dict[str, Any]: + res = slot_get(kv, label) + if not res.get("success"): + return {"success": False, "error": "slot not found"} + + slot = res["slot"] + scope = res["scope"] + target_kv = KV.globalSlots if scope == "global" else KV.slots + + if slot.get("readOnly"): + return {"success": False, "error": "slot is read-only"} + + content = slot.get("content") or "" + sep = "\n" if content and not content.endswith("\n") else "" + next_content = content + sep + strip_private_data(text) + + limit = slot.get("sizeLimit") or 2000 + if len(next_content) > limit: + return { + "success": False, + "error": f"append would exceed sizeLimit ({len(next_content)} > {limit})", + "currentSize": len(content), + "sizeLimit": limit + } + + slot["content"] = next_content + slot["updatedAt"] = datetime.datetime.utcnow().isoformat() + "Z" + kv.set(target_kv, label, slot) + + safe_audit(kv, "slot_append", "mem::slot-append", [label], {"scope": scope, "added": len(text), "total": len(next_content)}) + + # Commit to Dolt + commit_if_enabled(kv, f"Append slot: {label}", agent_id or get_agent_id()) + + return {"success": True, "slot": slot, "size": len(next_content)} + +def slot_replace(kv: StateKV, label: str, content: str, agent_id: Optional[str] = None) -> Dict[str, Any]: + res = slot_get(kv, label) + if not res.get("success"): + return {"success": False, "error": "slot not found"} + + slot = res["slot"] + scope = res["scope"] + target_kv = KV.globalSlots if scope == "global" else KV.slots + + if slot.get("readOnly"): + return {"success": False, "error": "slot is read-only"} + + content = strip_private_data(content) + limit = slot.get("sizeLimit") or 2000 + if len(content) > limit: + return { + "success": False, + "error": f"content exceeds sizeLimit ({len(content)} > {limit})", + "sizeLimit": limit + } + + before_len = len(slot.get("content") or "") + slot["content"] = content + slot["updatedAt"] = datetime.datetime.utcnow().isoformat() + "Z" + kv.set(target_kv, label, slot) + + safe_audit(kv, "slot_replace", "mem::slot-replace", [label], {"scope": scope, "before": before_len, "after": len(content)}) + + # Commit to Dolt + commit_if_enabled(kv, f"Replace slot: {label}", agent_id or get_agent_id()) + + return {"success": True, "slot": slot, "size": len(content)} + +def slot_delete(kv: StateKV, label: str, agent_id: Optional[str] = None) -> Dict[str, Any]: + res = slot_get(kv, label) + if not res.get("success"): + return {"success": False, "error": "slot not found"} + + slot = res["slot"] + scope = res["scope"] + target_kv = KV.globalSlots if scope == "global" else KV.slots + + if slot.get("readOnly"): + return {"success": False, "error": "slot is read-only"} + + kv.delete(target_kv, label) + safe_audit(kv, "slot_delete", "mem::slot-delete", [label], {"scope": scope, "size": len(slot.get("content") or "")}) + + # Commit to Dolt + commit_if_enabled(kv, f"Delete slot: {label}", agent_id or get_agent_id()) + + return {"success": True} + + +def slot_reflect(kv: StateKV, session_id: str, max_obs: int = 50) -> Dict[str, Any]: + observations = kv.list(KV.observations(session_id)) + if not observations: + return {"success": True, "applied": 0, "reason": "no observations for session"} + + recent = sorted(observations, key=lambda x: x.get("timestamp", ""), reverse=True)[:max_obs] + + pending_lines = [] + pattern_counts = {} + files = set() + + for obs in recent: + title = (obs.get("title") or "").lower() + narrative = (obs.get("narrative") or "").lower() + if "todo" in narrative or "todo" in title: + pending_lines.append(f"- {obs.get('title') or obs['id']}") + if obs.get("type") == "error": + pattern_counts["errors"] = pattern_counts.get("errors", 0) + 1 + if obs.get("type") == "command_run": + pattern_counts["commands"] = pattern_counts.get("commands", 0) + 1 + for f in obs.get("files") or []: + files.add(f) + + applied = 0 + now = datetime.datetime.utcnow().isoformat() + "Z" + + if pending_lines: + res = slot_get(kv, "pending_items") + if res.get("success"): + slot = res["slot"] + scope = res["scope"] + target_kv = scopeKv = KV.globalSlots if scope == "global" else KV.slots + already = set((slot.get("content") or "").split("\n")) + fresh = [l for l in pending_lines if l not in already] + if fresh: + sep = "\n" if slot.get("content") and not slot["content"].endswith("\n") else "" + next_content = (slot.get("content") or "") + sep + "\n".join(fresh) + limit = slot.get("sizeLimit") or 2000 + if len(next_content) > limit: + next_content = next_content[-limit:] + slot["content"] = next_content + slot["updatedAt"] = now + kv.set(target_kv, "pending_items", slot) + applied += 1 + + if pattern_counts: + res = slot_get(kv, "session_patterns") + if res.get("success"): + slot = res["slot"] + scope = res["scope"] + target_kv = KV.globalSlots if scope == "global" else KV.slots + summary = [f"last reflection: {now}"] + for k, v in pattern_counts.items(): + summary.append(f"- {k}: {v} in last {len(recent)} observations") + next_content = "\n".join(summary) + limit = slot.get("sizeLimit") or 2000 + if len(next_content) > limit: + next_content = next_content[:limit] + slot["content"] = next_content + slot["updatedAt"] = now + kv.set(target_kv, "session_patterns", slot) + applied += 1 + + if files: + res = slot_get(kv, "project_context") + if res.get("success"): + slot = res["slot"] + scope = res["scope"] + target_kv = KV.globalSlots if scope == "global" else KV.slots + already = slot.get("content") or "" + fresh = [f for f in files if f not in already][:20] + if fresh: + header_line = "Files touched in recent sessions:" if not already else "" + sep = "\n" if already and not already.endswith("\n") else "" + lines = [already] + if header_line: + lines.append(header_line) + for f in fresh: + lines.append(f"- {f}") + next_content = sep.join([l for l in lines if l]) + limit = slot.get("sizeLimit") or 2000 + if len(next_content) > limit: + next_content = next_content[-limit:] + slot["content"] = next_content + slot["updatedAt"] = now + kv.set(target_kv, "project_context", slot) + applied += 1 + + if applied > 0: + safe_audit(kv, "slot_reflect", "mem::slot-reflect", [session_id], {"observationCount": len(recent), "slotsUpdated": applied}) + commit_if_enabled(kv, f"Slot reflect: updated {applied} slots in session {session_id[:8]}", "system") + + return {"success": True, "applied": applied, "observationsReviewed": len(recent)} + + +# ===================================================================== +# Lessons Learned System +# ===================================================================== + +def reinforce_lesson(lesson: Dict[str, Any]) -> None: + now = datetime.datetime.utcnow().isoformat() + "Z" + lesson["reinforcements"] = lesson.get("reinforcements", 0) + 1 + conf = lesson.get("confidence", 0.5) + lesson["confidence"] = min(1.0, conf + 0.1 * (1 - conf)) + lesson["lastReinforcedAt"] = now + lesson["updatedAt"] = now + +def lesson_save(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + content = data.get("content") + if not content or not content.strip(): + return {"success": False, "error": "content is required"} + content = strip_private_data(content) + context_str = strip_private_data(data.get("context") or "") + + agent_id = data.get("agentId") or get_agent_id() + fp = fingerprint_id("lsn", content) + existing = kv.get(KV.lessons, fp) + + if existing and not existing.get("deleted"): + reinforce_lesson(existing) + if context_str and not existing.get("context"): + existing["context"] = context_str + kv.set(KV.lessons, existing["id"], existing) + safe_audit(kv, "lesson_strengthen", "mem::lesson-save", [existing["id"]]) + + # Commit to Dolt + commit_if_enabled(kv, f"Strengthen lesson: {existing.get('content', '')[:60]}", agent_id) + + return {"success": True, "action": "strengthened", "lesson": existing} + + confidence = data.get("confidence") + if not isinstance(confidence, (int, float)) or confidence < 0 or confidence > 1: + confidence = 0.5 + + now = datetime.datetime.utcnow().isoformat() + "Z" + lesson = { + "id": fp, + "content": content.strip(), + "context": context_str.strip(), + "confidence": confidence, + "reinforcements": 0, + "source": data.get("source") or "manual", + "sourceIds": data.get("sourceIds") or [], + "project": data.get("project"), + "tags": data.get("tags") or [], + "createdAt": now, + "updatedAt": now, + "decayRate": 0.05, + } + kv.set(KV.lessons, lesson["id"], lesson) + safe_audit(kv, "lesson_save", "mem::lesson-save", [lesson["id"]]) + + # Commit to Dolt + commit_if_enabled(kv, f"Create lesson: {lesson['content'][:60]}", agent_id) + + return {"success": True, "action": "created", "lesson": lesson} + + +def lesson_list(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + limit = data.get("limit") or 50 + min_confidence = data.get("minConfidence") or 0.0 + all_lessons = kv.list(KV.lessons) + + lessons = [ + l for l in all_lessons + if not l.get("deleted") and l.get("confidence", 0.5) >= min_confidence + ] + + project = data.get("project") + if project: + lessons = [l for l in lessons if l.get("project") == project] + source = data.get("source") + if source: + lessons = [l for l in lessons if l.get("source") == source] + + lessons.sort(key=lambda x: x.get("confidence", 0.5), reverse=True) + return {"success": True, "lessons": lessons[:limit]} + +def lesson_recall(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + query = data.get("query") + if not query or not query.strip(): + return {"success": False, "error": "query is required"} + + query_lower = query.lower() + min_confidence = data.get("minConfidence") or 0.1 + limit = data.get("limit") or 10 + + all_lessons = kv.list(KV.lessons) + lessons = [ + l for l in all_lessons + if not l.get("deleted") and l.get("confidence", 0.5) >= min_confidence + ] + + project = data.get("project") + if project: + lessons = [l for l in lessons if l.get("project") == project] + + scored = [] + terms = [t for t in query_lower.split() if len(t) > 1] + + for l in lessons: + text = f"{l.get('content', '')} {l.get('context', '')} {' '.join(l.get('tags') or [])}".lower() + match_count = sum(1 for t in terms if t in text) + if match_count == 0: + continue + + relevance = match_count / len(terms) + baseline = l.get("lastReinforcedAt") or l.get("createdAt") + import dateutil.parser + dt = dateutil.parser.parse(baseline) + days = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) - dt.replace(tzinfo=datetime.timezone.utc)).total_seconds() / (3600 * 24) + recency_boost = 1 / (1 + days * 0.01) + score = l.get("confidence", 0.5) * relevance * recency_boost + scored.append({"lesson": l, "score": score}) + + scored.sort(key=lambda x: x["score"], reverse=True) + results = [] + for s in scored[:limit]: + item = dict(s["lesson"]) + item["score"] = round(s["score"], 3) + results.append(item) + + safe_audit(kv, "lesson_recall", "mem::lesson-recall", [], {"query": query, "resultCount": len(results)}) + return {"success": True, "lessons": results} + +def lesson_strengthen(kv: StateKV, lesson_id: str) -> Dict[str, Any]: + lesson = kv.get(KV.lessons, lesson_id) + if not lesson or lesson.get("deleted"): + return {"success": False, "error": "lesson not found"} + + reinforce_lesson(lesson) + kv.set(KV.lessons, lesson["id"], lesson) + safe_audit(kv, "lesson_strengthen", "mem::lesson-strengthen", [lesson["id"]]) + + # Commit to Dolt + commit_if_enabled(kv, f"Strengthen lesson: {lesson.get('content', '')[:60]}", get_agent_id()) + + return {"success": True, "lesson": lesson} + +def lesson_decay_sweep(kv: StateKV) -> Dict[str, Any]: + all_lessons = kv.list(KV.lessons) + decayed = 0 + soft_deleted = 0 + now = datetime.datetime.utcnow() + timestamp = now.isoformat() + "Z" + + for l in all_lessons: + if l.get("deleted"): + continue + baseline_str = l.get("lastDecayedAt") or l.get("lastReinforcedAt") or l["createdAt"] + import dateutil.parser + dt = dateutil.parser.parse(baseline_str) + weeks = (now.replace(tzinfo=datetime.timezone.utc) - dt.replace(tzinfo=datetime.timezone.utc)).total_seconds() / (3600 * 24 * 7) + if weeks < 1.0: + continue + + decay = l.get("decayRate", 0.05) * weeks + new_conf = max(0.05, l.get("confidence", 0.5) - decay) + + if new_conf != l.get("confidence"): + before = l.get("confidence", 0.5) + l["confidence"] = round(new_conf, 3) + l["lastDecayedAt"] = timestamp + l["updatedAt"] = timestamp + + if l["confidence"] <= 0.1 and l.get("reinforcements", 0) == 0: + l["deleted"] = True + soft_deleted += 1 + else: + decayed += 1 + + kv.set(KV.lessons, l["id"], l) + safe_audit(kv, "lesson_strengthen", "mem::lesson-decay-sweep", [l["id"]], { + "action": "soft-delete" if l.get("deleted") else "decay", + "actor": "system", + "reason": "decay-sweep", + "before": {"confidence": before, "deleted": False}, + "after": {"confidence": l["confidence"], "deleted": bool(l.get("deleted"))} + }) + + if decayed > 0 or soft_deleted > 0: + commit_if_enabled(kv, f"Lesson decay sweep: decayed {decayed}, soft-deleted {soft_deleted}", "system") + + return {"success": True, "decayed": decayed, "softDeleted": soft_deleted, "total": len(all_lessons)} + + +# ===================================================================== +# Database Rebuilder (Index Bootstrapper) +# ===================================================================== + +def rebuild_index(kv: StateKV) -> int: + _bm25_index.clear() + if _vector_index: + _vector_index.clear() + + # Backfill BM25 with observations + sessions = kv.list(KV.sessions) + total_indexed = 0 + + for sess in sessions: + sid = sess.get("id") + if not sid: + continue + obs_list = kv.list(KV.observations(sid)) + for obs in obs_list: + # Only index compressed (non-raw) observations + if obs.get("title") and obs.get("narrative"): + _bm25_index.add(obs) + comb_text = obs["title"] + " " + obs["narrative"] + vector_index_add_guarded(obs["id"], sid, comb_text, {"kind": "observation", "logId": obs["id"]}) + total_indexed += 1 + + # Backfill BM25 with memories + memories = kv.list(KV.memories) + for mem in memories: + if mem.get("isLatest") is False: + continue + if not mem.get("title") or not mem.get("content"): + continue + converted = memory_to_observation(mem) + _bm25_index.add(converted) + comb_text = mem["title"] + " " + mem["content"] + vector_index_add_guarded(mem["id"], "memory", comb_text, {"kind": "memory", "logId": mem["id"]}) + total_indexed += 1 + + if _index_persistence and total_indexed > 0: + _index_persistence.schedule_save() + + return total_indexed + +# ===================================================================== +# Advanced Function Stubs / CRUD Operations +# ===================================================================== + +def list_sessions(kv: StateKV) -> List[Dict[str, Any]]: + sessions = kv.list(KV.sessions) + sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) + return sessions + +def get_session(kv: StateKV, session_id: str) -> Optional[Dict[str, Any]]: + return kv.get(KV.sessions, session_id) + +def create_session(kv: StateKV, session: Dict[str, Any]) -> Dict[str, Any]: + kv.set(KV.sessions, session["id"], session) + return session + +def end_session(kv: StateKV, session_id: str) -> bool: + now = datetime.datetime.utcnow().isoformat() + "Z" + kv.update(KV.sessions, session_id, [ + {"type": "set", "path": "endedAt", "value": now}, + {"type": "set", "path": "status", "value": "completed"} + ]) + return True + +def timeline(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + # Simple timeline query returning observations sorted by timestamp + anchor = data.get("anchor") + project = data.get("project") + before = data.get("before") or 10 + after = data.get("after") or 10 + + sessions = kv.list(KV.sessions) + if project: + sessions = [s for s in sessions if s.get("project") == project] + + all_obs = [] + for s in sessions: + all_obs.extend(kv.list(KV.observations(s["id"]))) + + # sort by timestamp + all_obs.sort(key=lambda x: x.get("timestamp", "")) + + anchor_idx = -1 + for idx, obs in enumerate(all_obs): + if obs["id"] == anchor or obs.get("timestamp", "") >= (anchor or ""): + anchor_idx = idx + break + + if anchor_idx == -1: + anchor_idx = len(all_obs) // 2 + + start = max(0, anchor_idx - before) + end = min(len(all_obs), anchor_idx + after + 1) + + return { + "success": True, + "observations": all_obs[start:end], + "anchorIndex": anchor_idx - start + } + +def get_project_profile(kv: StateKV, project: str) -> Dict[str, Any]: + prof = kv.get(KV.profiles, project) + if not prof: + prof = { + "project": project, + "topConcepts": [], + "topFiles": [], + "conventions": [], + "commonErrors": [], + "updatedAt": datetime.datetime.utcnow().isoformat() + "Z" + } + return prof + +def set_project_profile(kv: StateKV, project: str, profile: Dict[str, Any]) -> Dict[str, Any]: + profile["updatedAt"] = datetime.datetime.utcnow().isoformat() + "Z" + kv.set(KV.profiles, project, profile) + + # Commit to Dolt + commit_if_enabled(kv, f"Set project profile for {project}", get_agent_id()) + + return profile + +def get_relations(kv: StateKV) -> List[Dict[str, Any]]: + return kv.list(KV.relations) + +def add_relation(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + rel = { + "id": generate_id("rel"), + "sourceId": data["sourceId"], + "targetId": data["targetId"], + "type": data["type"], + "createdAt": datetime.datetime.utcnow().isoformat() + "Z" + } + kv.set(KV.relations, rel["id"], rel) + + # Commit to Dolt + agent_id = data.get("agentId") or get_agent_id() + commit_if_enabled(kv, f"Add relation {rel['type']} between {rel['sourceId']} and {rel['targetId']}", agent_id) + + return rel + +def evolve_memory(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: + # Update memory content and create a new version + mem_id = data["memoryId"] + new_content = data["newContent"] + new_title = data.get("newTitle") + + existing = kv.get(KV.memories, mem_id) + if not existing: + raise ValueError("Memory not found") + + existing["isLatest"] = False + kv.set(KV.memories, existing["id"], existing) + + now = datetime.datetime.utcnow().isoformat() + "Z" + new_mem = dict(existing) + new_mem["id"] = generate_id("mem") + new_mem["content"] = new_content + if new_title: + new_mem["title"] = new_title + else: + new_mem["title"] = new_content[:80] + new_mem["version"] = existing.get("version", 1) + 1 + new_mem["parentId"] = existing["id"] + new_mem["supersedes"] = [existing["id"]] + new_mem["createdAt"] = now + new_mem["updatedAt"] = now + new_mem["isLatest"] = True + + kv.set(KV.memories, new_mem["id"], new_mem) + + # Re-index + try: + _bm25_index.add(memory_to_observation(new_mem)) + _bm25_index.remove(existing["id"]) + except Exception: + pass + + comb_text = new_mem["title"] + " " + new_mem["content"] + vector_index_add_guarded(new_mem["id"], "memory", comb_text, {"kind": "memory", "logId": new_mem["id"]}) + if _vector_index: + _vector_index.remove(existing["id"]) + + if _index_persistence: + _index_persistence.schedule_save() + + # Commit to Dolt + agent_id = data.get("agentId") or get_agent_id() or new_mem.get("agentId") + commit_if_enabled(kv, f"Evolve memory {new_mem['id']} (v{new_mem['version']}): {new_mem['title']}", agent_id) + + return {"success": True, "memory": new_mem} + +def auto_forget(kv: StateKV, dry_run: bool = False) -> Dict[str, Any]: + now_dt = datetime.datetime.utcnow() + now_str = now_dt.isoformat() + "Z" + evicted_memories = [] + evicted_observations = [] + + # 1. Evict expired memories + memories = kv.list(KV.memories) + for mem in memories: + forget_after = mem.get("forgetAfter") + if forget_after: + try: + import dateutil.parser + fa_dt = dateutil.parser.parse(forget_after) + if fa_dt.tzinfo: + fa_dt = fa_dt.replace(tzinfo=None) + if fa_dt < now_dt: + evicted_memories.append(mem["id"]) + except Exception as e: + print(f"[auto_forget] Failed to parse forgetAfter '{forget_after}': {e}") + + # 2. Evict low-value old observations (importance <= 2, age > 180 days) + sessions = kv.list(KV.sessions) + for sess in sessions: + sid = sess.get("id") + if not sid: + continue + obs_list = kv.list(KV.observations(sid)) + for obs in obs_list: + importance = obs.get("importance") + ts = obs.get("timestamp") + if importance is not None and ts: + try: + import dateutil.parser + ts_dt = dateutil.parser.parse(ts) + if ts_dt.tzinfo: + ts_dt = ts_dt.replace(tzinfo=None) + age_days = (now_dt - ts_dt).days + if importance <= 2 and age_days > 180: + evicted_observations.append((sid, obs["id"])) + except Exception as e: + print(f"[auto_forget] Failed to parse timestamp '{ts}': {e}") + + if not dry_run: + for mem_id in evicted_memories: + mem = kv.get(KV.memories, mem_id) + kv.delete(KV.memories, mem_id) + if mem and mem.get("imageRef"): + ref = mem["imageRef"] + refs = kv.get(KV.imageRefs, ref) or 0 + if refs > 0: + kv.set(KV.imageRefs, ref, refs - 1) + _bm25_index.remove(mem_id) + if _vector_index: + _vector_index.remove(mem_id) + + for sid, obs_id in evicted_observations: + obs = kv.get(KV.observations(sid), obs_id) + kv.delete(KV.observations(sid), obs_id) + if obs: + img = obs.get("imageData") or obs.get("imageRef") + if img: + refs = kv.get(KV.imageRefs, img) or 0 + if refs > 0: + kv.set(KV.imageRefs, img, refs - 1) + _bm25_index.remove(obs_id) + if _vector_index: + _vector_index.remove(obs_id) + + if evicted_memories or evicted_observations: + if _index_persistence: + _index_persistence.schedule_save() + safe_audit( + kv, + "auto_forget", + "mem::auto_forget", + evicted_memories + [oid for _, oid in evicted_observations], + { + "evictedMemoriesCount": len(evicted_memories), + "evictedObservationsCount": len(evicted_observations), + "dryRun": False + } + ) + commit_if_enabled(kv, f"Auto forget: evicted {len(evicted_memories)} memories, {len(evicted_observations)} observations", "system") + + return { + "success": True, + "evictedMemories": evicted_memories, + "evictedObservations": [oid for _, oid in evicted_observations], + "evicted": len(evicted_memories) + len(evicted_observations), + "dryRun": dry_run + } + +def health_check(kv: StateKV) -> Dict[str, Any]: + db_status = "connected" + try: + conn = kv._get_conn() + conn.close() + except Exception: + db_status = "disconnected" + return { + "status": "healthy" if db_status == "connected" else "degraded", + "service": "agentmemory", + "version": "0.9.8", + "database": "dolt", + "databaseStatus": db_status + } + +def consolidate(kv: StateKV, project: Optional[str] = None, min_observations: int = 10) -> Dict[str, Any]: + # Mock consolidation pipeline run + return {"consolidated": 0, "totalObservations": 0, "success": True} + +# Setup persistence helper wire-ups +def set_index_persistence(persistence: IndexPersistence) -> None: + global _index_persistence + _index_persistence = persistence + +def set_embedding_provider(provider) -> None: + global _embedding_provider, _hybrid_search + _embedding_provider = provider + _hybrid_search = HybridSearch( + _bm25_index, + _vector_index, + _embedding_provider, + None + ) + +def set_stream_broadcaster(broadcaster) -> None: + global _stream_broadcaster + _stream_broadcaster = broadcaster + +def broadcast_stream(payload: Dict[str, Any]) -> None: + if _stream_broadcaster: + try: + _stream_broadcaster(payload) + except Exception as e: + print(f"[broadcaster] Failed: {e}") diff --git a/src/import_data.py b/src/import_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6a3186b0d47435b555550769e4b2408f331db9 --- /dev/null +++ b/src/import_data.py @@ -0,0 +1,84 @@ +import os +import json +import urllib.parse +import sys + +# Append local path so we can import StateKV +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from db import StateKV + +def import_old_data(old_db_path: str, kv: StateKV) -> bool: + if not os.path.exists(old_db_path): + print(f"[import] Error: Path {old_db_path} does not exist.") + return False + + print(f"[import] Starting migration from: {old_db_path}") + count = 0 + + for filename in os.listdir(old_db_path): + if not filename.endswith(".bin"): + continue + if not filename.startswith("mem%3A"): + continue + + # URL decode the scope name (e.g. mem%3Asessions.bin -> mem:sessions) + decoded_name = urllib.parse.unquote(filename) + scope = decoded_name[:-4] if decoded_name.endswith(".bin") else decoded_name + + filepath = os.path.join(old_db_path, filename) + try: + with open(filepath, "rb") as f: + data = f.read() + + if not data: + continue + + # Find the last matching JSON curly brace to strip binary padding/footers + try: + last_brace = data.rindex(b'}') + json_str = data[:last_brace+1].decode("utf-8") + records = json.loads(json_str) + except Exception as e: + print(f"[import] Skipping {filename}: could not parse JSON ({e})") + continue + + print(f"[import] Scope '{scope}': found {len(records)} items. Migrating...") + + for key, val in records.items(): + kv.set(scope, key, val) + count += 1 + + except Exception as e: + print(f"[import] Failed to process {filename}: {e}") + + if count > 0: + print("[import] Creating Dolt version commit...") + kv.commit_version("Import legacy AgentMemory database from Hugging Face", "system") + + print(f"[import] Finished! Migrated {count} total records into Dolt SQL.") + return True + + +if __name__ == "__main__": + # Prioritize the restored HF data in the user's home folder, falling back to local workspace data + home_path = os.path.expanduser(os.path.join("~", ".agentmemory", "state_store.db")) + workspace_path = r"d:\Downloads\Projects\Other Projects\agentmemory\agentmemory\data\state_store.db" + + if os.path.exists(home_path): + default_path = home_path + print(f"[import] Found restored HF data at: {default_path}") + else: + default_path = workspace_path + print(f"[import] HF data not found at home path, falling back to workspace: {default_path}") + + # Allow custom path via command line argument + if len(sys.argv) > 1: + default_path = sys.argv[1] + print(f"[import] Overriding path with CLI argument: {default_path}") + + # Initialize connection + print(f"[import] Initializing Dolt StateKV...") + kv = StateKV() + + import_old_data(default_path, kv) + diff --git a/src/mcp_stdio.py b/src/mcp_stdio.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7c4de5393fee1e4b316e588dfb639faeb08ab2 --- /dev/null +++ b/src/mcp_stdio.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +""" +stdio MCP wrapper — bridges Claude Code's MCP stdio protocol to the +agentmemory Flask HTTP API running on localhost. + +Usage: python mcp_stdio.py +""" +import sys +import json +import requests + +BASE = "http://127.0.0.1:3111/agentmemory" +SECRET = None # set via AGENTMEMORY_SECRET env var if auth enabled + +import os +_secret = os.getenv("AGENTMEMORY_SECRET") + +def headers(): + h = {"Content-Type": "application/json"} + if _secret: + h["Authorization"] = f"Bearer {_secret}" + return h + +def send(msg): + line = json.dumps(msg, separators=(",", ":")) + sys.stdout.write(line + "\n") + sys.stdout.flush() + +def handle(req): + method = req.get("method", "") + req_id = req.get("id") + params = req.get("params") or {} + + if method == "initialize": + send({ + "jsonrpc": "2.0", "id": req_id, + "result": { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "agentmemory-local", "version": "0.9.8"} + } + }) + + elif method == "initialized": + pass # notification — no response + + elif method == "ping": + send({"jsonrpc": "2.0", "id": req_id, "result": {}}) + + elif method == "tools/list": + try: + r = requests.get(f"{BASE}/mcp/tools", headers=headers(), timeout=5) + tools = r.json().get("tools", []) + send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}}) + except Exception as e: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32000, "message": f"agentmemory unreachable: {e}"}}) + + elif method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + try: + r = requests.post(f"{BASE}/mcp/tools", + headers=headers(), + json={"name": name, "arguments": args}, + timeout=30) + result = r.json() + # MCP expects content array + if "content" not in result: + result = {"content": [{"type": "text", "text": json.dumps(result)}]} + send({"jsonrpc": "2.0", "id": req_id, "result": result}) + except Exception as e: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32000, "message": str(e)}}) + + elif req_id is not None: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32601, "message": "Method not found"}}) + + +def main(): + for raw_line in sys.stdin: + raw_line = raw_line.strip() + if not raw_line: + continue + try: + req = json.loads(raw_line) + except json.JSONDecodeError: + continue + try: + handle(req) + except Exception as e: + req_id = req.get("id") if isinstance(req, dict) else None + if req_id is not None: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32603, "message": f"Internal error: {e}"}}) + +if __name__ == "__main__": + main() diff --git a/src/replay_import.py b/src/replay_import.py new file mode 100644 index 0000000000000000000000000000000000000000..9694cd5f63fc09755201bed387bb386c8e2ddc5e --- /dev/null +++ b/src/replay_import.py @@ -0,0 +1,607 @@ +import os +import re +import json +import hashlib +import datetime +from typing import List, Dict, Any, Tuple + +# Constants +MAX_FILES_DEFAULT = 200 +MAX_FILES_UPPER_BOUND = 1000 + +SENSITIVE_PATH_PATTERNS = [ + re.compile(r"(^|[\\/_.-])secret([\\/_.-]|s?$)", re.IGNORECASE), + re.compile(r"(^|[\\/_.-])credentials?([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/_.-])private[_-]?key([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/])\.env(\.[\w-]+)?$", re.IGNORECASE), + re.compile(r"(^|[\\/_.-])id_rsa([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/])auth[_-]?token([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/])bearer[_-]?token([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/])access[_-]?token([\\/_.-]|$)", re.IGNORECASE), + re.compile(r"(^|[\\/])api[_-]?token([\\/_.-]|$)", re.IGNORECASE), +] + +LESSON_PATTERNS = [ + re.compile(r"\b(always|never|don'?t|do not|make sure|remember to|note:|caveat:|warning:)\b[^.\n]{10,200}[.!\n]", re.IGNORECASE), + re.compile(r"\b(prefer|avoid)\s[^.\n]{10,200}[.!\n]", re.IGNORECASE), +] + +def generate_id(prefix: str) -> str: + import uuid + return f"{prefix}_{uuid.uuid4().hex}" + +def fingerprint_id(prefix: str, content: str) -> str: + # Hash content for stable ID (similar to TS fingerprintId) + h = hashlib.sha256(content.strip().encode("utf-8")).hexdigest() + return f"{prefix}_{h[:32]}" + +def is_sensitive(path: str) -> bool: + return any(pattern.search(path) for pattern in SENSITIVE_PATH_PATTERNS) + +def derive_project(cwd: str) -> str: + if not cwd: + return "unknown" + parts = [p for p in re.split(r'[\\/]', cwd) if p] + return parts[-1] if parts else "unknown" + +def to_text(content: Any) -> str: + if isinstance(content, str): + return content + if not isinstance(content, list): + return "" + parts = [] + for item in content: + if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str): + parts.append(item["text"]) + return "\n".join(parts) + +def extract_tool_uses(content: Any) -> List[Dict[str, Any]]: + if not isinstance(content, list): + return [] + out = [] + for item in content: + if isinstance(item, dict) and item.get("type") == "tool_use": + out.append({ + "id": item.get("id", ""), + "name": item.get("name", "unknown"), + "input": item.get("input") + }) + return out + +def extract_tool_results(content: Any) -> List[Dict[str, Any]]: + if not isinstance(content, list): + return [] + out = [] + for item in content: + if isinstance(item, dict) and item.get("type") == "tool_result": + out.append({ + "toolUseId": item.get("tool_use_id", ""), + "output": item.get("content"), + "isError": item.get("is_error") is True + }) + return out + +def parse_jsonl_text(text: str, fallback_session_id: str = None) -> Dict[str, Any]: + lines = [l for l in text.split("\n") if l.strip()] + entries = [] + for line in lines: + try: + parsed = json.loads(line) + if isinstance(parsed, dict): + entries.append(parsed) + except Exception: + pass + + session_id = "" + cwd = "" + first_ts = "" + last_ts = "" + observations = [] + + for entry in entries: + if entry.get("sessionId") and not session_id: + session_id = entry["sessionId"] + if entry.get("cwd") and not cwd: + cwd = entry["cwd"] + + ts = entry.get("timestamp") or datetime.datetime.utcnow().isoformat() + "Z" + if not first_ts: + first_ts = ts + last_ts = ts + + msg = entry.get("message") or {} + role = msg.get("role") + content = msg.get("content") + + if entry.get("type") == "user" and role == "user": + tool_results = extract_tool_results(content) + if tool_results: + for result in tool_results: + observations.append({ + "id": generate_id("obs"), + "sessionId": session_id or "imported", + "timestamp": ts, + "hookType": "post_tool_failure" if result["isError"] else "post_tool_use", + "toolName": None, + "toolInput": {"toolUseId": result["toolUseId"]}, + "toolOutput": result["output"], + "raw": entry + }) + else: + txt = to_text(content) + if txt.strip(): + observations.append({ + "id": generate_id("obs"), + "sessionId": session_id or "imported", + "timestamp": ts, + "hookType": "prompt_submit", + "userPrompt": txt, + "raw": entry + }) + elif entry.get("type") == "assistant" and role == "assistant": + txt = to_text(content) + tools = extract_tool_uses(content) + if txt.strip(): + observations.append({ + "id": generate_id("obs"), + "sessionId": session_id or "imported", + "timestamp": ts, + "hookType": "stop", + "assistantResponse": txt, + "raw": entry + }) + for tool in tools: + observations.append({ + "id": generate_id("obs"), + "sessionId": session_id or "imported", + "timestamp": ts, + "hookType": "pre_tool_use", + "toolName": tool["name"], + "toolInput": tool["input"], + "raw": {"toolUseId": tool["id"], "entry": entry} + }) + + effective_session_id = session_id or fallback_session_id or generate_id("sess") + for obs in observations: + if obs["sessionId"] == "imported": + obs["sessionId"] = effective_session_id + + now_iso = datetime.datetime.utcnow().isoformat() + "Z" + return { + "sessionId": effective_session_id, + "project": derive_project(cwd), + "cwd": cwd or os.getcwd(), + "startedAt": first_ts or now_iso, + "endedAt": last_ts or now_iso, + "observations": observations + } + +def derive_crystal_and_lessons( + kv, + session_id: str, + project: str, + raw_obs: List[Dict[str, Any]], + compressed: List[Dict[str, Any]], + first_prompt: str = None +) -> None: + from functions import KV + + if not raw_obs: + return + created_at = datetime.datetime.utcnow().isoformat() + "Z" + + files = set() + tools = set() + for c in compressed: + for f in c.get("files", []): + files.add(f) + if c.get("type") and c.get("type") != "conversation" and c.get("title"): + tools.add(c["title"]) + + assistant_texts = [] + user_prompts = [] + for r in raw_obs: + if isinstance(r.get("assistantResponse"), str) and r["assistantResponse"].strip(): + assistant_texts.append(r["assistantResponse"]) + if isinstance(r.get("userPrompt"), str) and r["userPrompt"].strip(): + user_prompts.append(r["userPrompt"]) + + lesson_matches = {} + for text in (assistant_texts + user_prompts)[:200]: + for pat in LESSON_PATTERNS: + for m in pat.finditer(text): + if len(lesson_matches) >= 40: + break + snippet = re.sub(r"\s+", " ", m.group(0)).strip() + if 20 <= len(snippet) <= 220: + key = snippet.lower() + if key not in lesson_matches: + lesson_matches[key] = snippet + + lesson_entries = list(lesson_matches.values())[:20] + lesson_ids = [] + for content in lesson_entries: + lesson_id = fingerprint_id("lesson", content.lower()) + try: + existing = kv.get(KV.lessons, lesson_id) + if existing: + existing_sources = existing.get("sourceIds", []) + merged_sources = existing_sources if session_id in existing_sources else (existing_sources + [session_id]) + existing_tags = existing.get("tags", []) + merged_tags = existing_tags if "auto-import" in existing_tags else (existing_tags + ["auto-import"]) + + existing["sourceIds"] = merged_sources + existing["tags"] = merged_tags + existing["reinforcements"] = existing.get("reinforcements", 0) + 1 + existing["updatedAt"] = created_at + existing["lastReinforcedAt"] = created_at + kv.set(KV.lessons, lesson_id, existing) + else: + lesson = { + "id": lesson_id, + "content": content, + "context": first_prompt or project, + "confidence": 0.4, + "reinforcements": 0, + "source": "consolidation", + "sourceIds": [session_id], + "project": project, + "tags": ["auto-import"], + "createdAt": created_at, + "updatedAt": created_at, + "decayRate": 0.05 + } + kv.set(KV.lessons, lesson_id, lesson) + lesson_ids.append(lesson_id) + except Exception: + pass + + crystal_id = fingerprint_id("crystal", session_id) + if first_prompt: + narrative_preview = first_prompt[:300] + else: + previews = [] + for c in compressed[:5]: + p = c.get("narrative") or c.get("title") + if p: + previews.append(p) + narrative_preview = (" · ".join(previews))[:300] + + try: + existing_crystal = kv.get(KV.crystals, crystal_id) or {} + crystal = { + "id": crystal_id, + "narrative": narrative_preview or f"Session {session_id[:12]} ({len(raw_obs)} observations)", + "keyOutcomes": list(tools)[:8], + "filesAffected": list(files)[:20], + "lessons": lesson_ids, + "sourceActionIds": existing_crystal.get("sourceActionIds", []), + "sessionId": session_id, + "project": project, + "createdAt": existing_crystal.get("createdAt", created_at) + } + kv.set(KV.crystals, crystal_id, crystal) + except Exception: + pass + +def find_jsonl_files(root: str, limit=200) -> Tuple[List[str], bool, int, bool]: + out = [] + discovered = 0 + walked = 0 + traversal_cap = max(limit * 50, 50000) + + for dirpath, dirnames, filenames in os.walk(root): + if walked >= traversal_cap: + break + + # skip symlinks or hidden directories + dirnames[:] = [d for d in dirnames if not d.startswith('.') and not os.path.islink(os.path.join(dirpath, d))] + + for name in filenames: + walked += 1 + if walked >= traversal_cap: + break + if name.endswith(".jsonl"): + full = os.path.join(dirpath, name) + if not os.path.islink(full): + discovered += 1 + if len(out) < limit: + out.append(full) + + traversal_capped = walked >= traversal_cap + truncated = discovered > len(out) or traversal_capped + return out, truncated, discovered, traversal_capped + +def import_jsonl_data(kv, path: str = None, max_files: int = None) -> Dict[str, Any]: + from functions import KV, build_synthetic_compression, IndexPersistence, _bm25_index, _vector_index + + default_root = os.path.expanduser(os.path.join("~", ".claude", "projects")) + raw_path = path or default_root + + expanded = os.path.expanduser(raw_path) + abs_path = os.path.abspath(expanded) + + if is_sensitive(abs_path): + return {"success": False, "error": "refusing to process sensitive-looking path"} + if os.path.islink(abs_path): + return {"success": False, "error": "symlinks are not supported"} + if not os.path.exists(abs_path): + return {"success": False, "error": "path not found"} + + limit = max_files if isinstance(max_files, int) and max_files > 0 else MAX_FILES_DEFAULT + limit = min(limit, MAX_FILES_UPPER_BOUND) + + files = [] + truncated = False + discovered = 0 + traversal_capped = False + + if os.path.isdir(abs_path): + files, truncated, discovered, traversal_capped = find_jsonl_files(abs_path, limit) + elif os.path.isfile(abs_path) and abs_path.endswith(".jsonl"): + files = [abs_path] + discovered = 1 + else: + return {"success": False, "error": "path must be a .jsonl file or directory"} + + if not files: + return { + "success": True, + "imported": 0, + "sessionIds": [], + "observations": 0, + "discovered": discovered, + "truncated": truncated, + "traversalCapped": traversal_capped, + "maxFiles": limit, + "maxFilesUpperBound": MAX_FILES_UPPER_BOUND + } + + session_ids = [] + observation_count = 0 + + for file in files: + if is_sensitive(file): + continue + if os.path.islink(file): + continue + + try: + with open(file, "r", encoding="utf-8", errors="ignore") as f: + text = f.read() + except Exception as e: + print(f"[import-jsonl] Failed to read {file}: {e}") + continue + + parsed = parse_jsonl_text(text, generate_id("sess")) + if not parsed["observations"]: + continue + + first_prompt_obs = None + for o in parsed["observations"]: + if isinstance(o.get("userPrompt"), str) and o["userPrompt"].strip(): + first_prompt_obs = o + break + + first_prompt = None + if first_prompt_obs: + first_prompt = re.sub(r"\s+", " ", first_prompt_obs["userPrompt"]).strip()[:200] + + existing = kv.get(KV.sessions, parsed["sessionId"]) + if existing: + existing["observationCount"] = existing.get("observationCount", 0) + len(parsed["observations"]) + if parsed["endedAt"] > existing.get("endedAt", ""): + existing["endedAt"] = parsed["endedAt"] + if existing.get("status") == "active": + existing["status"] = "completed" + + existing_tags = existing.get("tags", []) + if "jsonl-import" not in existing_tags: + existing["tags"] = existing_tags + ["jsonl-import"] + if not existing.get("firstPrompt") and first_prompt: + existing["firstPrompt"] = first_prompt + if not existing.get("id"): + existing["id"] = parsed["sessionId"] + + kv.set(KV.sessions, parsed["sessionId"], existing) + else: + session = { + "id": parsed["sessionId"], + "project": parsed["project"], + "cwd": parsed["cwd"], + "startedAt": parsed["startedAt"], + "endedAt": parsed["endedAt"], + "status": "completed", + "observationCount": len(parsed["observations"]), + "tags": ["jsonl-import"], + "firstPrompt": first_prompt + } + kv.set(KV.sessions, session["id"], session) + + from functions import _bm25_index, vector_index_add_guarded + compressed = [] + for obs in parsed["observations"]: + synthetic = build_synthetic_compression(obs) + compressed.append(synthetic) + kv.set(KV.observations(parsed["sessionId"]), obs["id"], synthetic) + + # Index + _bm25_index.add(synthetic) + comb_text = synthetic["title"] + " " + (synthetic.get("narrative") or "") + vector_index_add_guarded(synthetic["id"], synthetic["sessionId"], comb_text, {"kind": "synthetic", "logId": synthetic["id"]}) + + observation_count += len(parsed["observations"]) + session_ids.append(parsed["sessionId"]) + + derive_crystal_and_lessons( + kv, + parsed["sessionId"], + parsed["project"], + parsed["observations"], + compressed, + first_prompt + ) + + # Save the updated persistence state + import functions + if functions._index_persistence: + try: + functions._index_persistence.save() + except Exception as e: + print(f"[import-jsonl] Warning saving index persistence: {e}") + + # Audit trail + try: + from functions import log_audit + log_audit(kv, "import", "mem::replay::import-jsonl", f"Imported {len(session_ids)} sessions: {','.join(session_ids[:3])}...") + except Exception: + pass + + # Dolt commit if enabled + try: + kv.commit_version(f"Import {len(session_ids)} Claude Code sessions from JSONL", "system") + except Exception: + pass + + return { + "success": True, + "imported": len(files), + "sessionIds": session_ids, + "observations": observation_count, + "discovered": discovered, + "truncated": truncated, + "traversalCapped": traversal_capped, + "maxFiles": limit, + "maxFilesUpperBound": MAX_FILES_UPPER_BOUND + } + +def kind_from_hook(obs: Dict[str, Any]) -> str: + ht = obs.get("hookType") + if ht == "session_start": + return "session_start" + elif ht == "session_end": + return "session_end" + elif ht == "prompt_submit": + return "prompt" + elif ht == "stop": + return "response" if obs.get("assistantResponse") else "hook" + elif ht == "pre_tool_use": + return "tool_call" + elif ht == "post_tool_use": + return "tool_result" + elif ht == "post_tool_failure": + return "tool_error" + else: + return "hook" + +def label_for(obs: Dict[str, Any], kind: str) -> str: + if kind == "prompt": + val = obs.get("userPrompt") or "User prompt" + return val[:79] + "…" if len(val) > 80 else val + elif kind == "response": + val = obs.get("assistantResponse") or "Assistant response" + return val[:79] + "…" if len(val) > 80 else val + elif kind == "tool_call": + return f"{obs.get('toolName') or 'tool'} ▸ call" + elif kind == "tool_result": + return f"{obs.get('toolName') or 'tool'} ▸ result" + elif kind == "tool_error": + return f"{obs.get('toolName') or 'tool'} ▸ error" + elif kind == "session_start": + return "Session start" + elif kind == "session_end": + return "Session end" + else: + return obs.get("hookType") or "" + +def estimate_duration_ms(event: Dict[str, Any]) -> int: + body = event.get("body") or "" + tool_input = event.get("toolInput") or "" + tool_output = event.get("toolOutput") or "" + + chars = len(body) + if isinstance(tool_input, str): + chars += len(tool_input) + elif tool_input is not None: + chars += len(json.dumps(tool_input)) + + if isinstance(tool_output, str): + chars += len(tool_output) + elif tool_output is not None: + chars += len(json.dumps(tool_output)) + + if chars == 0: + return 300 + ms = round((chars / 40) * 1000) + return max(300, min(20000, ms)) + +def project_timeline(observations: List[Dict[str, Any]]) -> Dict[str, Any]: + if not observations: + now = datetime.datetime.utcnow().isoformat() + "Z" + return { + "sessionId": "", + "startedAt": now, + "endedAt": now, + "totalDurationMs": 0, + "eventCount": 0, + "events": [] + } + + sorted_obs = sorted(observations, key=lambda o: o.get("timestamp", "")) + started_at = sorted_obs[0].get("timestamp", "") + + try: + import dateutil.parser + start_dt = dateutil.parser.isoparse(started_at) + start_ms = start_dt.timestamp() * 1000 + except Exception: + start_ms = 0 + + events = [] + synthetic_offset = 0 + all_same_ts = all(o.get("timestamp") == started_at for o in sorted_obs) + + for obs in sorted_obs: + kind = kind_from_hook(obs) + body = obs.get("userPrompt") if kind == "prompt" else (obs.get("assistantResponse") if kind == "response" else None) + + try: + import dateutil.parser + obs_dt = dateutil.parser.isoparse(obs.get("timestamp", "")) + obs_ms = obs_dt.timestamp() * 1000 + offset_ms = int(max(0, obs_ms - start_ms)) if not all_same_ts else synthetic_offset + except Exception: + offset_ms = synthetic_offset + + event = { + "id": obs.get("id"), + "sessionId": obs.get("sessionId"), + "ts": obs.get("timestamp"), + "offsetMs": offset_ms, + "durationMs": 0, + "kind": kind, + "label": label_for(obs, kind), + "body": body, + "toolName": obs.get("toolName"), + "toolInput": obs.get("toolInput"), + "toolOutput": obs.get("toolOutput") + } + event["durationMs"] = estimate_duration_ms(event) + events.append(event) + synthetic_offset += event["durationMs"] + + if not events: + total_duration_ms = 0 + else: + last = events[-1] + total_duration_ms = last["offsetMs"] + last["durationMs"] + + return { + "sessionId": sorted_obs[0].get("sessionId"), + "startedAt": started_at, + "endedAt": sorted_obs[-1].get("timestamp"), + "totalDurationMs": total_duration_ms, + "eventCount": len(events), + "events": events + } + diff --git a/src/search.py b/src/search.py new file mode 100644 index 0000000000000000000000000000000000000000..1955a2f6b407bd1868c7b5d9e29b1ecfc675929a --- /dev/null +++ b/src/search.py @@ -0,0 +1,741 @@ +import re +import math +import json +import base64 +import array +import urllib.request +import urllib.parse +from typing import Dict, Any, List, Optional, Tuple, Set + +# ===================================================================== +# Custom Porter-like Stemmer (Ported from stemmer.ts) +# ===================================================================== + +step2map = { + "ational": "ate", "tional": "tion", "enci": "ence", "anci": "ance", + "izer": "ize", "iser": "ise", "abli": "able", "alli": "al", + "entli": "ent", "eli": "e", "ousli": "ous", "ization": "ize", + "isation": "ise", "ation": "ate", "ator": "ate", "alism": "al", + "iveness": "ive", "fulness": "ful", "ousness": "ous", "aliti": "al", + "iviti": "ive", "biliti": "ble", +} + +step3map = { + "icate": "ic", "ative": "", "alize": "al", "alise": "al", + "iciti": "ic", "ical": "ic", "ful": "", "ness": "", +} + +def _has_vowel(s: str) -> bool: + return any(c in "aeiou" for c in s) + +def _measure(s: str) -> int: + # Reduce non-vowels (excluding y) to C, vowels (+y) to V + reduced = "" + for c in s: + if c in "aeiouy": + if not reduced or reduced[-1] != "V": + reduced += "V" + else: + if not reduced or reduced[-1] != "C": + reduced += "C" + # count "VC" patterns + return len(re.findall(r"VC", reduced)) + +def _ends_double_consonant(s: str) -> bool: + return len(s) >= 2 and s[-1] == s[-2] and s[-1] not in "aeiou" + +def _ends_cvc(s: str) -> bool: + if len(s) < 3: + return False + c1, v, c2 = s[-3], s[-2], s[-1] + return c1 not in "aeiou" and v in "aeiou" and c2 not in "aeiouwxy" + +def stem(word: str) -> str: + if len(word) <= 2: + return word + + w = word + + # Step 1a + if w.endswith("sses"): + w = w[:-2] + elif w.endswith("ies"): + w = w[:-2] + elif not w.endswith("ss") and w.endswith("s"): + w = w[:-1] + + # Step 1b + if w.endswith("eed"): + if _measure(w[:-3]) > 0: + w = w[:-1] + elif w.endswith("ed") and _has_vowel(w[:-2]): + w = w[:-2] + if w.endswith("at") or w.endswith("bl") or w.endswith("iz"): + w += "e" + elif _ends_double_consonant(w) and not w.endswith(("l", "s", "z")): + w = w[:-1] + elif _measure(w) == 1 and _ends_cvc(w): + w += "e" + elif w.endswith("ing") and _has_vowel(w[:-3]): + w = w[:-3] + if w.endswith("at") or w.endswith("bl") or w.endswith("iz"): + w += "e" + elif _ends_double_consonant(w) and not w.endswith(("l", "s", "z")): + w = w[:-1] + elif _measure(w) == 1 and _ends_cvc(w): + w += "e" + + # Step 1c + if w.endswith("y") and _has_vowel(w[:-1]): + w = w[:-1] + "i" + + # Step 2 + for suffix, replacement in step2map.items(): + if w.endswith(suffix): + base = w[:-len(suffix)] + if _measure(base) > 0: + w = base + replacement + break + + # Step 3 + for suffix, replacement in step3map.items(): + if w.endswith(suffix): + base = w[:-len(suffix)] + if _measure(base) > 0: + w = base + replacement + break + + # Step 4 + suffixes_step4 = ( + "al", "ance", "ence", "er", "ic", "able", "ible", "ant", "ement", + "ment", "ent", "tion", "sion", "ou", "ism", "ate", "iti", "ous", + "ive", "ize", "ise" + ) + if w.endswith(suffixes_step4): + # find matching suffix length + match = re.search(r"(ement|ment|tion|sion|ance|ence|able|ible|ism|ate|iti|ous|ive|ize|ise|ant|ent|al|er|ic|ou)$", w) + if match: + suffix_len = len(match.group(1)) + base = w[:-suffix_len] + if _measure(base) > 1: + w = base + + # Step 5a + if w.endswith("e"): + base = w[:-1] + if _measure(base) > 1 or (_measure(base) == 1 and not _ends_cvc(base)): + w = base + + # Step 5b + if _ends_double_consonant(w) and w.endswith("l") and _measure(w[:-1]) > 1: + w = w[:-1] + + return w + +# ===================================================================== +# Synonym Map (Ported from synonyms.ts) +# ===================================================================== + +SYNONYM_GROUPS = [ + ["auth", "authentication", "authn", "authenticating"], + ["authz", "authorization", "authorizing"], + ["db", "database", "datastore"], + ["perf", "performance", "latency", "throughput", "slow", "bottleneck"], + ["optim", "optimization", "optimizing", "optimise", "query-optimization"], + ["k8s", "kubernetes", "kube"], + ["config", "configuration", "configuring", "setup"], + ["deps", "dependencies", "dependency"], + ["env", "environment"], + ["fn", "function"], + ["impl", "implementation", "implementing"], + ["msg", "message", "messaging"], + ["repo", "repository"], + ["req", "request"], + ["res", "response"], + ["ts", "typescript"], + ["js", "javascript"], + ["pg", "postgres", "postgresql"], + ["err", "error", "errors"], + ["api", "endpoint", "endpoints"], + ["ci", "continuous-integration"], + ["cd", "continuous-deployment"], + ["test", "testing", "tests"], + ["doc", "documentation", "docs"], + ["infra", "infrastructure"], + ["deploy", "deployment", "deploying"], + ["cache", "caching", "cached"], + ["log", "logging", "logs"], + ["monitor", "monitoring"], + ["observe", "observability"], + ["sec", "security", "secure"], + ["validate", "validation", "validating"], + ["migrate", "migration", "migrations"], + ["debug", "debugging"], + ["container", "containerization", "docker"], + ["crash", "crashloop", "crashloopbackoff"], + ["webhook", "webhooks", "callback"], + ["middleware", "mw"], + ["paginate", "pagination"], + ["serialize", "serialization"], + ["encrypt", "encryption"], + ["hash", "hashing"], +] + +synonymMap: Dict[str, Set[str]] = {} +for group in SYNONYM_GROUPS: + stemmed = [stem(t.lower()) for t in group] + for s in stemmed: + if s not in synonymMap: + synonymMap[s] = set() + for other in stemmed: + if other != s: + synonymMap[s].add(other) + +def get_synonyms(stemmed_term: str) -> List[str]: + return list(synonymMap.get(stemmed_term, [])) + +# ===================================================================== +# CJK Segmenter (Ported from cjk-segmenter.ts) +# ===================================================================== + +CJK_RE = re.compile(r'[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]') +CJK_RUN_RE = re.compile(r'[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]+') +HANGUL_RE = re.compile(r'[\uac00-\ud7a3]') +KANA_RE = re.compile(r'[\u3040-\u309f\u30a0-\u30ff]') +HANGUL_BLOCK_RE = re.compile(r'[가-힯]+') + +jieba_loaded = False +jieba_instance = None + +def get_jieba(): + global jieba_loaded, jieba_instance + if jieba_loaded: + return jieba_instance + jieba_loaded = True + try: + import jieba + jieba_instance = jieba + except ImportError: + print("[search] Install jieba to improve Chinese word segmentation (pip install jieba)") + return jieba_instance + +def has_cjk(text: str) -> bool: + return bool(CJK_RE.search(text)) + +def segment_cjk(text: str) -> List[str]: + if not has_cjk(text): + return [text] + + out: List[str] = [] + cursor = 0 + + for match in CJK_RUN_RE.finditer(text): + start = match.start() + run = match.group(0) + end = match.end() + + if start > cursor: + piece = text[cursor:start].strip() + if piece: + out.append(piece) + + if HANGUL_RE.search(run): + # Hangul: split by blocks + out.extend(HANGUL_BLOCK_RE.findall(run)) + elif KANA_RE.search(run): + # Japanese Kana fallback: split every character + out.extend(list(run)) + else: + # Chinese Han: use jieba if available + jb = get_jieba() + if jb: + out.extend([t.strip() for t in jb.cut(run, cut_all=False) if t.strip()]) + else: + out.extend(list(run)) + + cursor = end + + if cursor < len(text): + trailing = text[cursor:].strip() + if trailing: + out.append(trailing) + + return out + +# ===================================================================== +# SearchIndex (BM25 - Ported from search-index.ts) +# ===================================================================== + +class SearchIndex: + def __init__(self): + self.entries: Dict[str, Dict[str, Any]] = {} + self.inverted_index: Dict[str, Set[str]] = {} + self.doc_term_counts: Dict[str, Dict[str, int]] = {} + self.total_doc_length = 0 + self.sorted_terms: Optional[List[str]] = None + + self.k1 = 1.2 + self.b = 0.75 + + def add(self, obs: Dict[str, Any]) -> None: + obs_id = obs.get("id") + if not obs_id: + return + + terms = self.extract_terms(obs) + term_freq: Dict[str, int] = {} + term_count = 0 + + for term in terms: + term_freq[term] = term_freq.get(term, 0) + 1 + term_count += 1 + + self.entries[obs_id] = { + "obsId": obs_id, + "sessionId": obs.get("sessionId", ""), + "termCount": term_count, + } + self.doc_term_counts[obs_id] = term_freq + self.total_doc_length += term_count + + for term in term_freq.keys(): + if term not in self.inverted_index: + self.inverted_index[term] = set() + self.inverted_index[term].add(obs_id) + + self.sorted_terms = None + + def has(self, id: str) -> bool: + return id in self.entries + + def remove(self, id: str) -> None: + entry = self.entries.get(id) + if not entry: + return + + term_freq = self.doc_term_counts.get(id) + if term_freq: + for term in term_freq.keys(): + posting_list = self.inverted_index.get(term) + if posting_list: + posting_list.discard(id) + if not posting_list: + self.inverted_index.pop(term, None) + self.doc_term_counts.pop(id, None) + + self.total_doc_length = max(0, self.total_doc_length - entry["termCount"]) + self.entries.pop(id, None) + self.sorted_terms = None + + def search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]: + raw_terms = self.tokenize(query.lower()) + if not raw_terms: + return [] + + N = len(self.entries) + if N == 0: + return [] + avg_doc_len = self.total_doc_length / N + + query_terms: List[Dict[str, Any]] = [] + seen = set() + for term in raw_terms: + if term not in seen: + seen.add(term) + query_terms.append({"term": term, "weight": 1.0}) + for syn in get_synonyms(term): + if syn not in seen: + seen.add(syn) + query_terms.append({"term": syn, "weight": 0.7}) + + scores: Dict[str, float] = {} + sorted_terms = self.get_sorted_terms() + + for q_item in query_terms: + term = q_item["term"] + weight = q_item["weight"] + + matching_docs = self.inverted_index.get(term) + if matching_docs: + df = len(matching_docs) + idf = math.log((N - df + 0.5) / (df + 0.5) + 1) + + for obs_id in matching_docs: + entry = self.entries[obs_id] + doc_terms = self.doc_term_counts.get(obs_id, {}) + tf = doc_terms.get(term, 0) + doc_len = entry["termCount"] + + numerator = tf * (self.k1 + 1) + denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len)) + bm25_score = idf * (numerator / denominator) * weight + + scores[obs_id] = scores.get(obs_id, 0.0) + bm25_score + + # Prefix matching (binary search) + start_idx = self.lower_bound(sorted_terms, term) + for si in range(start_idx, len(sorted_terms)): + index_term = sorted_terms[si] + if not index_term.startswith(term): + break + if index_term == term: + continue + + obs_ids = self.inverted_index.get(index_term, set()) + prefix_df = len(obs_ids) + prefix_idf = math.log((N - prefix_df + 0.5) / (prefix_df + 0.5) + 1) * 0.5 + + for obs_id in obs_ids: + entry = self.entries[obs_id] + doc_terms = self.doc_term_counts.get(obs_id, {}) + tf = doc_terms.get(index_term, 0) + doc_len = entry["termCount"] + numerator = tf * (self.k1 + 1) + denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len)) + scores[obs_id] = scores.get(obs_id, 0.0) + prefix_idf * (numerator / denominator) * weight + + results = [] + for obs_id, score in scores.items(): + entry = self.entries[obs_id] + results.append({ + "obsId": obs_id, + "sessionId": entry["sessionId"], + "score": score + }) + + results.sort(key=lambda x: x["score"], reverse=True) + return results[:limit] + + @property + def size(self) -> int: + return len(self.entries) + + def clear(self) -> None: + self.entries.clear() + self.inverted_index.clear() + self.doc_term_counts.clear() + self.total_doc_length = 0 + self.sorted_terms = None + + def restore_from_data(self, data: Dict[str, Any]) -> None: + self.clear() + if not data: + return + + for k, v in data.get("entries", []): + self.entries[k] = v + for term, ids in data.get("inverted", []): + self.inverted_index[term] = set(ids) + for id_, counts in data.get("docTerms", []): + self.doc_term_counts[id_] = dict(counts) + self.total_doc_length = int(data.get("totalDocLength", 0)) + + def serialize_data(self) -> Dict[str, Any]: + entries = list(self.entries.items()) + inverted = [(term, list(ids)) for term, ids in self.inverted_index.items()] + doc_terms = [(id_, list(counts.items())) for id_, counts in self.doc_term_counts.items()] + return { + "v": 2, + "entries": entries, + "inverted": inverted, + "docTerms": doc_terms, + "totalDocLength": self.total_doc_length, + } + + def extract_terms(self, obs: Dict[str, Any]) -> List[str]: + parts = [ + obs.get("title", ""), + obs.get("subtitle", "") or "", + obs.get("narrative", "") or "", + " ".join(obs.get("facts", []) or []), + " ".join(obs.get("concepts", []) or []), + " ".join(obs.get("files", []) or []), + obs.get("type", ""), + ] + return self.tokenize(" ".join(parts).lower()) + + def tokenize(self, text: str) -> List[str]: + # Strip special characters except valid separators + cleaned = re.sub(r'[^\w\s/.\\-_]', ' ', text) + out = [] + for raw in cleaned.split(): + if len(raw) < 2: + continue + if has_cjk(raw): + for seg in segment_cjk(raw): + if len(seg) >= 1: + out.append(seg) + else: + out.append(stem(raw)) + return out + + def get_sorted_terms(self) -> List[str]: + if not self.sorted_terms: + self.sorted_terms = sorted(self.inverted_index.keys()) + return self.sorted_terms + + def lower_bound(self, arr: List[str], target: str) -> int: + lo = 0 + hi = len(arr) + while lo < hi: + mid = (lo + hi) // 2 + if arr[mid] < target: + lo = mid + 1 + else: + hi = mid + return lo + +# ===================================================================== +# VectorIndex (Cosine Similarity - Ported from vector-index.ts) +# ===================================================================== + +def float32_to_base64(floats: List[float]) -> str: + arr = array.array('f', floats) + return base64.b64encode(arr.tobytes()).decode('utf-8') + +def base64_to_float32(b64: str) -> List[float]: + arr = array.array('f') + arr.frombytes(base64.b64decode(b64)) + return list(arr) + +def cosine_similarity(a: List[float], b: List[float]) -> float: + if len(a) != len(b) or len(a) == 0: + return 0.0 + dot = 0.0 + norm_a = 0.0 + norm_b = 0.0 + for x, y in zip(a, b): + dot += x * y + norm_a += x * x + norm_b += y * y + denom = math.sqrt(norm_a) * math.sqrt(norm_b) + return dot / denom if denom != 0.0 else 0.0 + +class VectorIndex: + def __init__(self): + self.vectors: Dict[str, Dict[str, Any]] = {} + + def add(self, obs_id: str, session_id: str, embedding: List[float]) -> None: + self.vectors[obs_id] = {"embedding": embedding, "sessionId": session_id} + + def remove(self, obs_id: str) -> None: + self.vectors.pop(obs_id, None) + + def search(self, query: List[float], limit: int = 20) -> List[Dict[str, Any]]: + results = [] + for obs_id, entry in self.vectors.items(): + score = cosine_similarity(query, entry["embedding"]) + results.append({ + "obsId": obs_id, + "sessionId": entry["sessionId"], + "score": score + }) + + results.sort(key=lambda x: x["score"], reverse=True) + return results[:limit] + + @property + def size(self) -> int: + return len(self.vectors) + + def validate_dimensions(self, expected: int) -> Tuple[List[Dict[str, Any]], Set[int]]: + mismatches = [] + seen_dimensions = set() + for obs_id, entry in self.vectors.items(): + dim = len(entry["embedding"]) + seen_dimensions.add(dim) + if dim != expected: + mismatches.append({"obsId": obs_id, "dim": dim}) + return mismatches, seen_dimensions + + def clear(self) -> None: + self.vectors.clear() + + def serialize_data(self) -> List[Any]: + data = [] + for obs_id, entry in self.vectors.items(): + data.append([ + obs_id, + { + "embedding": float32_to_base64(entry["embedding"]), + "sessionId": entry["sessionId"] + } + ]) + return data + + def restore_from_data(self, data: List[Any]) -> None: + self.clear() + if not isinstance(data, list): + return + for row in data: + try: + if not isinstance(row, list) or len(row) < 2: + continue + obs_id, entry = row + if not isinstance(obs_id, str) or not isinstance(entry, dict): + continue + emb_b64 = entry.get("embedding") + sess_id = entry.get("sessionId") + if not isinstance(emb_b64, str) or not isinstance(sess_id, str): + continue + self.vectors[obs_id] = { + "embedding": base64_to_float32(emb_b64), + "sessionId": sess_id + } + except Exception: + continue + +# ===================================================================== +# Gemini Embedding Client (Urllib POST completion) +# ===================================================================== + +class GeminiEmbeddingProvider: + def __init__(self, api_key: str): + self.name = "gemini" + self.dimensions = 768 + self.api_key = api_key + self.model = "models/gemini-embedding-001" + self.api_url = f"https://generativelanguage.googleapis.com/v1beta/{self.model}:batchEmbedContents" + + def embed(self, text: str) -> List[float]: + results = self.embed_batch([text]) + return results[0] + + def embed_batch(self, texts: List[str]) -> List[List[float]]: + results: List[List[float]] = [] + batch_limit = 100 + + for i in range(0, len(texts), batch_limit): + chunk = texts[i:i + batch_limit] + + payload = { + "requests": [ + { + "model": self.model, + "content": {"parts": [{"text": t}]}, + "outputDimensionality": self.dimensions, + } + for t in chunk + ] + } + + req_data = json.dumps(payload).encode("utf-8") + url = f"{self.api_url}?key={self.api_key}" + + req = urllib.request.Request( + url, + data=req_data, + headers={"Content-Type": "application/json"}, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=30.0) as response: + resp_data = json.loads(response.read().decode("utf-8")) + + for emb in resp_data.get("embeddings", []): + values = emb.get("values", []) + results.append(self._l2_normalize(values)) + except Exception as e: + raise RuntimeError(f"Gemini embedding batch call failed: {e}") + + return results + + def _l2_normalize(self, vec: List[float]) -> List[float]: + sum_sq = sum(x * x for x in vec) + norm = math.sqrt(sum_sq) + if norm == 0: + return vec + return [x / norm for x in vec] + +# ===================================================================== +# HybridSearch (Triple Stream - Ported from hybrid-search.ts) +# ===================================================================== + +class HybridSearch: + def __init__( + self, + bm25: SearchIndex, + vector: Optional[VectorIndex], + embedding_provider: Optional[GeminiEmbeddingProvider], + kv: Any, + bm25_weight: float = 0.4, + vector_weight: float = 0.6, + graph_weight: float = 0.3 + ): + self.bm25 = bm25 + self.vector = vector + self.embedding_provider = embedding_provider + self.kv = kv + self.bm25_weight = bm25_weight + self.vector_weight = vector_weight + self.graph_weight = graph_weight + + def search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]: + # Triple-stream search combining BM25, vectors, and graph weights + bm25_results = self.bm25.search(query, limit * 2) + + vector_results: List[Dict[str, Any]] = [] + if self.vector and self.embedding_provider and self.vector.size > 0: + try: + query_embedding = self.embedding_provider.embed(query) + vector_results = self.vector.search(query_embedding, limit * 2) + except Exception: + pass # Fallback to BM25 + + # Build scores mapping + scores: Dict[str, Dict[str, Any]] = {} + RRF_K = 60 + + for idx, r in enumerate(bm25_results): + obs_id = r["obsId"] + scores[obs_id] = { + "bm25Rank": idx + 1, + "vectorRank": float("inf"), + "sessionId": r["sessionId"], + "bm25Score": r["score"], + "vectorScore": 0.0, + "graphScore": 0.0, + } + + for idx, r in enumerate(vector_results): + obs_id = r["obsId"] + if obs_id in scores: + scores[obs_id]["vectorRank"] = idx + 1 + scores[obs_id]["vectorScore"] = r["score"] + else: + scores[obs_id] = { + "bm25Rank": float("inf"), + "vectorRank": idx + 1, + "sessionId": r["sessionId"], + "bm25Score": 0.0, + "vectorScore": r["score"], + "graphScore": 0.0, + } + + has_vector = len(vector_results) > 0 + + effective_bm25_w = self.bm25_weight + effective_vector_w = self.vector_weight if has_vector else 0.0 + + total_w = effective_bm25_w + effective_vector_w + if total_w > 0: + effective_bm25_w /= total_w + effective_vector_w /= total_w + + combined = [] + for obs_id, s in scores.items(): + combined.append({ + "obsId": obs_id, + "sessionId": s["sessionId"], + "bm25Score": s["bm25Score"], + "vectorScore": s["vectorScore"], + "graphScore": s["graphScore"], + "combinedScore": ( + effective_bm25_w * (1.0 / (RRF_K + s["bm25Rank"])) + + effective_vector_w * (1.0 / (RRF_K + s["vectorRank"])) + ) + }) + + combined.sort(key=lambda x: x["combinedScore"], reverse=True) + return combined[:limit] diff --git a/src/viewer/favicon.svg b/src/viewer/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..3ef799f78497e6784fcbca7c17cb1c7925df487f --- /dev/null +++ b/src/viewer/favicon.svg @@ -0,0 +1 @@ +AM diff --git a/src/viewer/index.html b/src/viewer/index.html new file mode 100644 index 0000000000000000000000000000000000000000..889d585c7941153eed87349407ce941caef33d5f --- /dev/null +++ b/src/viewer/index.html @@ -0,0 +1,4462 @@ + + + + + + agentmemory viewer + + + + + +
+ +

agentmemory

+ v__AGENTMEMORY_VERSION__ +
+
+ + + live updates off +
+
+ +
+ + + + + + + + + + + + + +
+ +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + diff --git a/start.sh b/start.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d9917d8e4e537ce8c4c72debc76922d4d9b3b8f --- /dev/null +++ b/start.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Note: no set -e — sync failures must not kill the container + +# Create agentmemory data directories +mkdir -p /home/user/.agentmemory/dolt + +# ============================================================================= +# Persistent storage via HF Dataset repo +# Secrets to set in HF Space settings: +# HF_TOKEN — write access to the dataset repo +# GEMINI_API_KEY — powers graph, embeddings, compression, crystals +# AGENTMEMORY_DATASET_REPO — optional override (default: Yash030/agentmemory-data) +# ============================================================================= +export AGENTMEMORY_DATASET_REPO="${AGENTMEMORY_DATASET_REPO:-Yash030/agentmemory-data}" + +echo "[start] Restoring data from HF Dataset..." +python3 /app/sync.py restore + +# Background sync loop — backs up every 5 minutes +( + while true; do + sleep 300 + python3 /app/sync.py backup + done +) & + +# Generate HMAC secret on first boot, persist it so it survives dataset restore +HMAC_FILE="/home/user/.agentmemory/.hmac" +if [ ! -s "$HMAC_FILE" ]; then + SECRET="$(openssl rand -hex 32)" + printf '%s\n' "$SECRET" > "$HMAC_FILE" + chmod 600 "$HMAC_FILE" + echo "================================================================" + echo "agentmemory: generated HMAC secret on first boot" + echo "AGENTMEMORY_SECRET=$SECRET" + echo "Copy this to your Space secrets as AGENTMEMORY_SECRET." + echo "It will not be printed again." + echo "================================================================" +fi +export AGENTMEMORY_SECRET="${AGENTMEMORY_SECRET:-$(cat "$HMAC_FILE")}" + +# Write .env config for the daemon so it is loaded by src/app.py +cat > /home/user/.agentmemory/.env <