#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat: recall quality, provenance, keyless graph, and connector parity (#1205)
Rohit Ghumare696cf7abb8cb
diff --git a/.env.example b/.env.exampleindex 77ca0f3a..9d346ea1 100644--- a/.env.example+++ b/.env.example@@ -26,22 +26,24 @@# 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_API_KEY=sk-... # Activates both the OpenAI-compatible LLM provider (DeepSeek, SiliconFlow, vLLM, LM Studio, Ollama via `/v1`) and OpenAI embeddings. Set OPENAI_API_KEY_FOR_LLM=false to scope it to embeddings only.# OPENAI_BASE_URL=https://api.openai.com # Override for OpenAI-compatible providers+# OPENAI_MODEL=gpt-5.6-luna # Default OpenAI-compatible chat model+# OPENAI_API_KEY_FOR_LLM=false # Skip OpenAI auto-detection for LLM; key stays active for embeddings# ANTHROPIC_API_KEY=sk-ant-...-# ANTHROPIC_MODEL=claude-sonnet-4-20250514 # Default Anthropic model+# ANTHROPIC_MODEL=claude-sonnet-5 # 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)+# GEMINI_MODEL=gemini-3.7-flash # Default Gemini model (current stable Flash)# OPENROUTER_API_KEY=sk-or-...-# OPENROUTER_MODEL=anthropic/claude-sonnet-4-20250514+# OPENROUTER_MODEL=anthropic/claude-sonnet-5# MINIMAX_API_KEY=...-# MINIMAX_MODEL=MiniMax-M2.7+# MINIMAX_MODEL=MiniMax-M3# MAX_TOKENS=4096 # Cap LLM completion tokens for compression / summarise calls@@ -111,6 +113,13 @@# 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++# Local reasoning models only: set to 1 to ask the model to skip its+# hidden thinking pass during graph extraction. Extraction runs several+# times faster; relation quality can drop slightly. Leave unset to let+# the model think (default).+# AGENTMEMORY_LLM_NOTHINK=1+# 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).@@ -119,7 +128,7 @@# 6. CLI / runtime knobs# ------------------------------------------------------------------------------# AGENTMEMORY_TOOLS=all # core (7 tools, default) | all (51 tools) — surface exposed to MCP clients+# AGENTMEMORY_TOOLS=core # all (54 tools, default) | core (8 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)diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e877b7fc..89da6725 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,11 +4,9 @@ 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.29] — 2026-08-15-## [0.9.29] — 2026-08-02--Patch release: the `.env` file now actually applies everywhere, imports become searchable, consolidation runs on session stop, twelve MCP-only agents get activated on connect, and every capture surface finally agrees on what "project" means. No breaking changes; read the upgrade notes below for four behavior changes you will notice.+Release wave in two parts. Recall quality: hybrid ranking reaches the primary recall path, lessons get a real index, every record learns where it came from, the knowledge graph populates keyless, and agent scoping threads through all save paths — plus connector parity for pi and Codex, a new DeepSeek Harness connector, current provider model defaults, and a viewer clarity pass. Foundation: the `.env` file now applies everywhere, imports become searchable, consolidation runs on session stop, twelve MCP-only agents get activated on connect, and every capture surface agrees on what "project" means. No breaking changes; read the upgrade notes for behavior changes you will notice.### Upgrade notes@@ -19,6 +17,14 @@ Patch release: the `.env` file now actually applies everywhere, imports become s### Added+- **Write-time provenance on every record.** Each observation and memory carries an immutable origin block (channel `user` / `agent` / `tool` / `import` / `shared`, detail, capturedAt) stamped at capture, save, and import, and inherited through both compression paths. The base for trust-aware retrieval and ingest screening.+- **`similarTo` advisory hint on save.** `mem::remember` reports a near-miss similarity match (0.4 to 0.7) back to the caller so agents can spot near-duplicates without the write being blocked.+- **`AGENTMEMORY_LLM_NOTHINK=1`** (opt-in): asks local reasoning models to skip their hidden thinking pass during graph extraction. Extraction runs faster; relation quality can drop slightly. Default behavior unchanged; documented in `.env.example`.+- **Keyless graph extraction.** `mem::graph-extract` always runs a deterministic structural pass first: files and concepts on compressed observations become nodes, and co-occurrence within an observation becomes a `related_to` edge. The graph now populates without any LLM key; `GRAPH_EXTRACTION_ENABLED` plus a provider key gates only the LLM pass that layers typed relations (fixes, depends_on, causes) on top. Session end fires extraction unconditionally.+- **pi extension: capture parity with the Claude Code plugin.** Session registration on start (after the health check populates reachability, so it fires on the first session of a fresh process), prompt capture on submit (deduped in a 5-minute client window against auto-retry re-submissions; stored with user-channel provenance), per-tool observations from `tool_result` (server `inferType` classifies command_run / file_edit / file_read; `AGENTMEMORY_TOOL_OBSERVE=0` opts out), turn capture slices raised 500/4000 → 8000/8000, `memory_save` scoped to the current project instead of the global bucket, session end + one cross-session consolidate run on real quit only (`/new`, `/resume`, `/fork`, reloads excluded; no client-side summarize call — `session/end` already fans out the summary, avoiding the double-summarize the Stop hook had), status checks accept `status: "ok"`, and the status refresh no longer throws a stale-context error when the session is replaced mid-health-check. Live-verified on pi v0.84.2: prompt + turn observations landed and the session closed as `completed` on quit. Codex executes only hooks with a recorded `trusted_hash` and shows its "Hooks need review" approval prompt exclusively in the interactive TUI, so a `codex exec`-only workflow left the freshly installed hooks silently inert. `connect codex --with-hooks` now warns to launch `codex` once and choose "Trust all and continue" (and to re-approve after upgrades, since refreshed paths change the hash). Found by live-testing the documented flow end to end.+- **`connect pi` actually installs.** The pi adapter was a stub that printed manual copy instructions because `integrations/` never shipped in the npm package. The extension source now ships, and `connect pi` copies it into `~/.pi/agent/extensions/agentmemory/`, which pi auto-discovers — no settings.json edit, `/reload` picks it up live. Idempotent by content compare; `--force` and stale copies refresh with a backup. `integrations/pi` is also a proper pi package now (`pi-package` keyword, `pi.extensions` manifest, peer deps on `@earendil-works/pi-coding-agent` + `typebox`; private, local installs only — `pi install ./integrations/pi` from a checkout), and the extension's type import moved off the renamed upstream package name.+- **DeepSeek Harness connector.** `agentmemory connect dsh` appends an `@deepseek-ai/dsh-mcp-client` row to the home-level `$DSH_HOME/cordis.patch.yml`, the machine-local patch layer every Harness profile loads. `--with-hooks` adds full auto-capture: the bundled Claude Code hook scripts run through Harness's first-party `@deepseek-ai/dsh-hooks-claude-code` bridge (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop) via a manifest written to `$DSH_HOME/agentmemory.hooks.json` with absolute script paths. Idempotent, `--force` replaces the rows, honors `DSH_HOME`.+- **Viewer clarity pass.** Two-pane session explorer (list beside a sticky detail panel on wide screens), dashboard stat cards that navigate to their tabs, memory and lesson rows that expand to the full stored record with raw JSON and origin provenance, type-clustered graph layout with label collision avoidance when relations are sparse, health notes translated from machine slugs into sentences, honest zero states for consolidation and graph, and the official icon as the favicon.- `--data-dir` flag and `AGENTMEMORY_DATA_DIR` so iii-engine state lives outside repositories, with gated legacy `./data` adoption and Docker-volume preservation (#314)- Native hooks adapter for Droid via `~/.factory/hooks.json`, reusing the bundled hook scripts (#1130)- Native hooks adapter for Antigravity CLI (agy) via a stdin bridge that normalizes agy's hook payloads onto the bundled hook scripts, with an explicit PreToolUse allow decision (#1146, thanks @berthojoris)@@ -28,8 +34,23 @@ Patch release: the `.env` file now actually applies everywhere, imports become s- `AGENTMEMORY_PROJECT_NAME` override in the OpenCode plugin (#1125)- Provider fetches retry 429/503 honoring `Retry-After` under a total-elapsed budget capped below the iii invocation timeout (#1136)+### Changed++- **Provider default models bumped to current generations.** OpenAI `gpt-4o-mini` → `gpt-5.6-luna`, Anthropic `claude-sonnet-4-20250514` (deprecated upstream, retires 2026-06-15) → `claude-sonnet-5`, Gemini `gemini-2.5-flash` → `gemini-3.7-flash` (current stable Flash), MiniMax `MiniMax-M2.7` → `MiniMax-M3`, OpenRouter `anthropic/claude-sonnet-4-20250514` → `anthropic/claude-sonnet-5`. The premium-model cost warning now also matches OpenAI's Sol flagship tier, and its cheap-alternative hint leads with `deepseek/deepseek-v4-flash-0731`. Explicit `*_MODEL` env overrides are unaffected. Embedding defaults are unchanged (`text-embedding-3-small`, `gemini-embedding-001`, local MiniLM are all current). README local-model picks refreshed to the Qwen 3 / gpt-oss / DeepSeek R1 generation.+- Local embeddings migrate from `@xenova/transformers` to `@huggingface/transformers` v4 with Node 22+ support; CI now tests Node 20, 22, 24, and 26 (#479, #1096)+### Fixed+- **Hybrid ranking on the primary recall path.** `mem::search` (behind `memory_recall`) now ranks through the full BM25 + vector + graph fusion when the vector index is populated; it was keyword-only while only smart-search got hybrid ranking. Fusion weights normalize per item over the streams that actually ranked it, with an explicit cross-stream agreement bonus, replacing the every-enabled-stream denominator that permanently penalized single-stream hits. Result order is deterministic (score, best rank, id).+- **Indexed lesson recall.** Lessons get a dedicated in-memory BM25 index built lazily from one KV list and maintained incrementally on save, delete, and decay; recall previously listed and substring-scanned the whole corpus per query. A record cache beside the index takes recall to zero KV round-trips.+- **Superseded versions leave recall.** Superseded memory versions are removed from the BM25 and vector indexes; the version chain stays in KV for history, but recall no longer returns an outdated fact as if current. `mem::remember` also finds supersession candidates through the search index (top 50) instead of walking every memory per save, with a full-scan fallback while the index is cold.+- **`agentId` threads through every save path** ([#1159](https://github.com/rohitg00/agentmemory/issues/1159), [#1160](https://github.com/rohitg00/agentmemory/issues/1160), [#1197](https://github.com/rohitg00/agentmemory/issues/1197)). REST `/agentmemory/remember` forwards `agentId` instead of dropping it; `memoryToObservation()` carries the memory's `agentId` into the search-index shape so saved memories are visible to agent-scoped search; the MCP `memory_save` schema exposes `agentId` and the standalone stdio package forwards both `agentId` and `project`.+- **Per-session project attribution in the OpenCode plugin** ([#1188](https://github.com/rohitg00/agentmemory/issues/1188)). Project and cwd resolve from each session's own directory at `session.created` (pruned on session end) instead of module-level state that filed every session in a multi-directory OpenCode process under whichever repo loaded the plugin first.+- **Prompt dedup no longer swallows prompts** ([#1173](https://github.com/rohitg00/agentmemory/issues/1173)). Hooks hash the payload when `tool_input` is absent, so prompt_submit, notification, and lifecycle events dedup on content instead of collapsing onto one shared key that silently dropped every prompt after the first in a TTL window.+- **Stop hook no longer summarizes twice** ([#1203](https://github.com/rohitg00/agentmemory/issues/1203)). The direct `/agentmemory/summarize` POST is gone; `/session/end` already fans out `event::session::stopped`, which runs `mem::summarize`.+- **Safe Docker-mode stop** ([#1151](https://github.com/rohitg00/agentmemory/issues/1151)). The CLI refuses to adopt or signal Docker/VM port holders (com.docker.backend, vpnkit, colima) as the native engine unless `--force`; Docker-mode teardown is scoped to agentmemory's own compose services instead of an unscoped `down`; the native worker is reaped before Docker teardown instead of deleting `worker.pid` with the process still running.+- **Viewer live stream and freshness.** The stream WebSocket target resolves from `/agentmemory/livez` (new `streamsPort` field) instead of viewerPort-1 arithmetic, which pointed at the wrong server whenever the viewer bound a fallback port and silently degraded live updates to polling. Tab data refetches on entry (with a freshness gate), so a memory saved by the agent appears without a hard reload.+- **Hermetic tests** ([#1178](https://github.com/rohitg00/agentmemory/issues/1178)). HOME/USERPROFILE are isolated for the whole vitest run so suites stop reading the developer's real `~/.agentmemory/.env`.- Boot hydrates `~/.agentmemory/.env` into `process.env`, closing the class of "env var in .env is ignored" bugs (#1136)- Imported and replayed observations are indexed into BM25 and the vector index, so imports are searchable (#1072, via #1136)- Snapshot timer actually runs, non-positive intervals clamp to the default, and snapshot creation is serialized across timer, REST, and MCP (#1006, via #1136)@@ -47,10 +68,6 @@ Patch release: the `.env` file now actually applies everywhere, imports become s- Viewer surfaces health status from non-2xx health responses (#1046)- Documented REST endpoint count matches the registered routes again (130)-### Changed--- Local embeddings migrate from `@xenova/transformers` to `@huggingface/transformers` v4 with Node 22+ support; CI now tests Node 20, 22, 24, and 26 (#479, #1096)-## [0.9.28] — 2026-07-19Patch release: hardens the hook runner against malformed payloads and closes a cross-agent context leak. No breaking changes; drop-in upgrade.diff --git a/README.md b/README.mdindex a716d8f1..83fec8e0 100644--- a/README.md+++ b/README.md@@ -1,5 +1,5 @@<p align="center">- <img src="assets/banner.png" alt="agentmemory — Persistent memory for AI coding agents" width="720" />+ <img src="assets/banner.png" alt="agentmemory: persistent memory for AI coding agents" width="720" /></p><p align="center">@@ -30,7 +30,7 @@</p><p align="center">- <a href="https://gist.github.com/rohitg00/2067ab416f7bbe447c1977edaaa681e2"><img src="https://img.shields.io/badge/Viral%20GitHub%20Gist-1.3k%20stars%20%2F%20182%20forks-FF6B35?style=for-the-badge&logo=github&logoColor=white&labelColor=1a1a1a" alt="Design doc: 1.3k stars / 182 forks on the gist" /></a>+ <a href="https://gist.github.com/rohitg00/2067ab416f7bbe447c1977edaaa681e2"><img src="https://img.shields.io/badge/Viral%20GitHub%20Gist-1.6k%20stars%20%2F%20230%20forks-FF6B35?style=for-the-badge&logo=github&logoColor=white&labelColor=1a1a1a" alt="Design doc: 1.6k stars / 230 forks on the gist" /></a></p><p align="center">@@ -50,7 +50,7 @@<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="54 MCP tools" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-hooks.svg"><img src="assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-deps.svg"><img src="assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>- <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="1,596+ tests passing" height="38" /></picture>+ <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="1,648+ tests passing" height="38" /></picture></p><p align="center">@@ -66,7 +66,6 @@<a href="#how-it-works">How It Works</a> •<a href="#mcp-server">MCP</a> •<a href="#real-time-viewer">Viewer</a> •- <a href="#iii-console">iii Console</a> •<a href="#powered-by-iii">Powered by iii</a> •<a href="#configuration">Config</a> •<a href="#api">API</a>@@ -76,34 +75,58 @@## Install-Fastest path if you use a coding agent: hand it this one instruction and it installs, wires, and verifies agentmemory end to end.+One command:-> Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md+```bash+npx @agentmemory/agentmemory+```++The first run is an interactive setup: pick the agents to wire (Claude Code, Cursor, Codex, Gemini CLI, OpenCode, ...), pick an LLM provider or stay keyless, and it seeds the config, starts the memory server on `:3111`, and offers to install globally so the bare `agentmemory` command works everywhere afterwards.-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.+Then prove recall works and give your agent its skills:```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+agentmemory demo --serve # seed sample sessions + watch recall find them+npx skills add rohitg00/agentmemory -y # 15 native skills so your agent knows when to reach for memory```-Or via `npx` (no install):+Prefer to let a coding agent do the whole thing? Hand it one instruction:++> Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md++Wire more agents any time with `agentmemory connect <agent>` — 20 adapters listed at [Works with every agent](#works-with-every-agent). Full command reference at [Quick Start](#quick-start).++<details>+<summary><strong>Windows</strong></summary>++The fast path is WSL2. Native Windows engine setup is manual (about 10 to 20 minutes) and `agentmemory connect` is currently unsupported there. See the [Windows notes](#windows) for the step-by-step.++</details>++<details>+<summary><strong>Global install / EACCES</strong></summary>```bash-npx @agentmemory/agentmemory+npm install -g @agentmemory/agentmemory+# If you hit EACCES on macOS/Linux system Node installs:+sudo npm install -g @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.+</details>++<details>+<summary><strong>npx serves an old version</strong></summary>++npx caches per version. Force the latest with `npx -y @agentmemory/agentmemory@latest`, or clear the cache once with `rm -rf ~/.npm/_npx` (macOS/Linux; on Windows delete `%LOCALAPPDATA%\npm-cache\_npx`).-Already running your own `iii` engine? agentmemory pins iii-engine v0.11.2 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest` — it installs and runs the pinned v0.11.2 in `~/.agentmemory/bin`, leaving your own `iii` untouched.+</details>++<details>+<summary><strong>Already running your own iii engine</strong></summary>-Full options at [Quick Start](#quick-start) below. Agent-specific wiring at [Works with every agent](#works-with-every-agent).+agentmemory pins iii-engine v0.11.2 and won't attach to a different version (the worker can't speak another engine's protocol). Stop the other engine, then run `npx -y @agentmemory/agentmemory@latest`. It installs and runs the pinned v0.11.2 in `~/.agentmemory/bin`, leaving your own `iii` untouched.++</details>---@@ -218,7 +241,7 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agenYou 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*.+**What changes:** Session 1 you set up JWT auth. Session 2 you ask for rate limiting. The agent already knows your auth uses jose middleware in `src/middleware/auth.ts`, your tests cover token validation, and you chose jose over jsonwebtoken for Edge compatibility, with no re-explaining and no copy-pasting.```bashnpx @agentmemory/agentmemory@@ -250,7 +273,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).| **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).+100% top-5 hit rate at the **P@5 math ceiling** for this corpus (0.240, see scorecard). Hybrid retrieves every gold session; grep misses 1 of 2 gold on the multi-session temporal query. Lift is **recall + temporal**, not aggregate precision. This benchmark is small and gold-sparse; the larger LongMemEval-S below differentiates better. Full per-type breakdown + correction note: [`docs/benchmarks/2026-05-20-coding-agent-life-v1.md`](docs/benchmarks/2026-05-20-coding-agent-life-v1.md).**LongMemEval-S** (ICLR 2025, 500 questions)@@ -275,9 +298,9 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).</tr></table>-> 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.+> Embedding model: `all-MiniLM-L6-v2` (local, free, no API key). Full reports: [`benchmark/LONGMEMEVAL.md`](benchmark/LONGMEMEVAL.md), [`benchmark/QUALITY.md`](benchmark/QUALITY.md), [`benchmark/SCALE.md`](benchmark/SCALE.md). Competitor comparison: [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md) covering agentmemory vs mem0, Letta, Khoj, supermemory, TencentDB Agent Memory, MemPalace, Zep/Graphiti, Cognee, Hippo.-**Reproduce locally:** [`eval/README.md`](eval/README.md) — 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/).+**Reproduce locally:** [`eval/README.md`](eval/README.md), an adapter-pluggable harness for LongMemEval `_s` (public 500-Q) + `coding-agent-life-v1` (in-house 15-session corpus). Grep / vector / agentmemory adapters score side-by-side, NDJSON output, published scorecards land in [`docs/benchmarks/`](docs/benchmarks/).**Pairs with [codegraph](https://github.com/colbymchenry/codegraph), [Understand Anything](https://github.com/Lum1104/Understand-Anything), and [Graphify](https://github.com/safishamsi/graphify).** Code-graph indexing, multi-agent build pipelines, and broader knowledge graphs across docs / PDFs / images / videos. agentmemory remembers the work; those three projects light up the rest of the context layer. Recipes + question-routing table: [`docs/recipes/pairings.md`](docs/recipes/pairings.md).@@ -289,10 +312,11 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<tr><th></th><th>agentmemory</th>-<th>mem0 (58K ⭐)</th>-<th>Letta / MemGPT (23K ⭐)</th>-<th>Khoj (35K ⭐)</th>-<th>supermemory (26K ⭐)</th>+<th>mem0 (63K ⭐)</th>+<th>Letta / MemGPT (24K ⭐)</th>+<th>Khoj (36K ⭐)</th>+<th>supermemory (29K ⭐)</th>+<th>TencentDB Agent Memory (22K ⭐)</th><th>MemPalace (54K ⭐)</th><th>oracleagentmemory</th><th>Hippo</th>@@ -305,6 +329,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Full agent runtime</td><td>Personal AI</td><td>Memory API + app</td>+<td>Team memory hub (LLM proxy)</td><td>Vector memory (OSS)</td><td>Memory engine (Oracle DB)</td><td>Memory system</td>@@ -317,6 +342,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>83.2% (LoCoMo)</td><td>N/A</td><td>Self-reported</td>+<td>PersonaMem 76% (self-reported)</td><td>~96.6% (self-reported)</td><td>94.4% (self-reported)</td><td>N/A</td>@@ -329,6 +355,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Agent self-edits</td><td>Manual</td><td>API-side extraction</td>+<td>Proxy interception (base-URL swap)</td><td>Manual</td><td>API extraction</td><td>Manual</td>@@ -341,6 +368,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Vector (archival)</td><td>Semantic</td><td>Vector + RAG</td>+<td>4 asset types (Chat / Skill / Wiki / CodeGraph)</td><td>Vector-only</td><td>Vector + semantic</td><td>Decay-weighted</td>@@ -353,6 +381,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Within Letta runtime only</td><td>No</td><td>No</td>+<td>Team roles + shared assets</td><td>No</td><td>Scoped only</td><td>Multi-agent shared</td>@@ -365,6 +394,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>High (must use Letta)</td><td>Standalone</td><td>None</td>+<td>Proxy fronts every model call</td><td>None</td><td>Oracle Database</td><td>None</td>@@ -377,6 +407,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Postgres + vector DB</td><td>Multiple</td><td>Managed cloud</td>+<td>Docker stack (Core + Hub + Proxy)</td><td>Vector store</td><td>Oracle AI Database</td><td>None</td>@@ -389,6 +420,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Agent-managed</td><td>Manual</td><td>Auto-forget</td>+<td>Manual review; auto-routing in progress</td><td>None</td><td>Not stated</td><td>Decay + consolidation</td>@@ -401,6 +433,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Core memory in context</td><td>Varies</td><td>Cloud pricing</td>+<td>Not stated</td><td>No token budget</td><td>LLM-backed (varies)</td><td>Varies</td>@@ -413,6 +446,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Cloud dashboard</td><td>Web UI</td><td>Cloud dashboard</td>+<td>Hub web UI</td><td>No</td><td>No</td><td>No</td>@@ -425,6 +459,7 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).<td>Optional</td><td>Yes</td><td>No (cloud-only)</td>+<td>Yes (Docker)</td><td>Yes</td><td>Yes (Oracle DB)</td><td>Yes</td>@@ -432,7 +467,16 @@ Latest release notes: [CHANGELOG.md](CHANGELOG.md).</tr></table>-<sub>Benchmark note: only agentmemory's R@5 is our own measured result (LongMemEval-S, reproducible from <a href="benchmark/COMPARISON.md"><code>benchmark/COMPARISON.md</code></a>). The mem0 and Letta figures are their published LoCoMo numbers (a different dataset); the MemPalace, supermemory, and oracleagentmemory figures are vendor self-reported claims we have not independently reproduced (oracleagentmemory's run used GPT-5.5 against an Oracle AI Database). Shown side by side for ballpark only, not a head-to-head on identical data. Star counts are approximate and drift over time.</sub>+<sub>Benchmark note: only agentmemory's R@5 is our own measured result (LongMemEval-S, reproducible from <a href="benchmark/COMPARISON.md"><code>benchmark/COMPARISON.md</code></a>). The mem0 and Letta figures are their published LoCoMo numbers (a different dataset); the MemPalace, supermemory, TencentDB (PersonaMem), and oracleagentmemory figures are vendor self-reported claims we have not independently reproduced (oracleagentmemory's run used GPT-5.5 against an Oracle AI Database). Shown side by side for ballpark only, not a head-to-head on identical data. Star counts are approximate and drift over time.</sub>++**Newer entrants** worth knowing, compared in depth in [`benchmark/COMPARISON.md`](benchmark/COMPARISON.md):++| System | ⭐ | Angle |+|--------|---|-------|+| Zep / Graphiti | 30K | Temporal knowledge graph; strongest published temporal-query results (LongMemEval 63.8%), but graph builds asynchronously so fresh facts can lag |+| Cognee | 30K | Document-to-knowledge-graph ingestion, Python-only, built for structured entity extraction rather than session capture |++None of these auto-capture from coding-agent hooks, ship a local-first viewer, or run keyless — the combination agentmemory is built around.---@@ -450,39 +494,27 @@ npx @agentmemory/agentmemorynpx @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.+`demo` seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs semantic searches against them. You'll see it find "N+1 query fix" when you search "database performance optimization", which keyword matching cannot do.Open `http://localhost:3113` to watch the memory build live.-### Recommended: install globally+### Everyday commands-`npx` caches per-version. If you ran `npx @agentmemory/[email protected]` 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:+Install and setup live in [Install](#install) above (the first run walks you through it). Day to day:```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 # start the serveragentmemory stop # tear it down-agentmemory remove # uninstall everything we created-agentmemory connect claude-code # wire one agent+agentmemory connect <agent> # wire another agentagentmemory doctor # interactive diagnostics + fix prompts+agentmemory remove # uninstall everything we created```-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).+Every session agentmemory records is replayable. Open the viewer, pick the **Replay** tab, and scrub through the timeline: prompts, tool calls, tool results, and responses render as discrete events with play/pause, speed control (0.5x to 4x), and keyboard shortcuts (space to toggle, arrows to step).-Already have older Claude Code JSONL transcripts you want to bring in?+To bring in older Claude Code JSONL transcripts:```bash# Import everything under the default ~/.claude/projects@@ -492,7 +524,7 @@ npx @agentmemory/agentmemory import-jsonlnpx @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.+Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions, with no side-channel servers. Each imported transcript is indexed for search, stamped with origin channel `import`, and mined for a session crystal and lessons.> **Heads-up if you rely on `import-jsonl` as your primary capture path:** Claude Code's `cleanupPeriodDays` (in `~/.claude/settings.json`, default **30**) auto-deletes JSONL transcripts older than that window from `~/.claude/projects/`. If you install agentmemory fresh on a months-old Claude Code history, anything older than 30 days is already gone before the first import. Either run `import-jsonl` on a cron, raise `cleanupPeriodDays` to something higher, or wire the auto-capture hooks (the default plugin install path) so each turn lands in agentmemory while the session is live and the JSONL cleanup stops mattering.@@ -635,7 +667,7 @@ This is **complementary** to `agentmemory connect <agent>`:- `agentmemory connect <agent>` writes the MCP server config so the tools are available.- `npx skills add rohitg00/agentmemory` installs the skills so the agent knows when to call them.-For the few agents the skills CLI doesn't cover yet (Zed v1.3.x and below), drop the 15 SKILL.md files under the agent's native skill directory yourself — same format works everywhere.+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; the same format works everywhere.#### Standard MCP block@@ -652,7 +684,7 @@ The agentmemory entry is the **same MCP server block** across every host that us}```-**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.+**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 ||---|---|---|@@ -665,21 +697,22 @@ The agentmemory entry is the **same MCP server block** across every host that us| **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. |+| **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. Project attribution is per-session, so one OpenCode process spanning several repositories files each session under its own project. Two slash commands (`/recall`, `/remember`). Copy `plugin/opencode/` into your OpenCode workspace and add the plugin entry to `opencode.json`. See [`plugin/opencode/README.md`](plugin/opencode/README.md) for the full hook table + gap analysis. |+| **pi** | `~/.pi/agent/extensions/agentmemory` | `agentmemory connect pi` installs the bundled extension into pi's auto-discovery directory (recall on agent start, capture on agent end, `memory_search` / `memory_save` / `memory_health` tools, `/agentmemory-status`). `/reload` in a running pi picks it up. [`integrations/pi`](integrations/pi/) is also a pi package (`pi install ./integrations/pi` from a checkout). || **Hermes Agent** | `~/.hermes/config.yaml` | 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`. |+| **Qwen Code** | `~/.qwen/settings.json` | `agentmemory connect qwen` writes the standard `mcpServers` block. Hook payload is field-compatible with Claude Code, so the existing 12-hook scripts work without modification; wire them via the `hooks` section in the same `settings.json`. || **Antigravity** (replaces Gemini CLI) | `mcp_config.json` (in Antigravity's User dir) | `agentmemory connect antigravity` writes the standard `mcpServers` block. macOS: `~/Library/Application Support/Antigravity/User/`. Linux: `~/.config/Antigravity/User/`. Use after the 2026-06-18 Gemini CLI sunset. |-| **Antigravity CLI** (`agy`) | `~/.gemini/config/mcp_config.json` | `agentmemory connect antigravity-cli` — the `agy` CLI keeps its own config under `~/.gemini/`, separate from the Antigravity IDE above. Pass `--with-hooks` for native auto-capture via `~/.gemini/config/hooks.json`. |+| **Antigravity CLI** (`agy`) | `~/.gemini/config/mcp_config.json` | `agentmemory connect antigravity-cli`. The `agy` CLI keeps its own config under `~/.gemini/`, separate from the Antigravity IDE above. Pass `--with-hooks` for native auto-capture via `~/.gemini/config/hooks.json`. || **Kiro** | `~/.kiro/settings/mcp.json` | `agentmemory connect kiro` writes the user-level config. Workspace overrides go in `.kiro/settings/mcp.json` next to your code. |-| **Warp** | `~/.warp/.mcp.json` | `agentmemory connect warp` writes the standard `mcpServers` block. Warp also auto-discovers skills from `.claude/skills/` — once the Claude Code plugin is installed the 8 agentmemory skills (`remember`, `recall`, `recap`, `handoff`, `forget`, `commit-context`, `commit-history`, `session-history`) appear natively in Warp's slash-command palette. |+| **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`. |+| **Continue.dev** | `~/.continue/config.yaml` (preferred) or `config.json` (legacy) | `agentmemory connect continue` creates `config.yaml` from scratch when neither exists, or modifies existing `config.json`. **If you already have `config.yaml`** the adapter prints the exact block to paste under `mcpServers:`; it won't silently rewrite your yaml because preserving comments and anchors safely needs a YAML parser the package doesn't ship. Continue uses array form (not object) for `mcpServers`. || **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. || **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `<repo>/.factory/mcp.json`. Pass `--with-hooks` for native auto-capture. |-| **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`). |+| **DeepSeek Harness** | `$DSH_HOME/cordis.patch.yml` | `agentmemory connect dsh` appends an `@deepseek-ai/dsh-mcp-client` row to the home-level patch layer every Harness profile loads; tools register as `mcp__agentmemory__*`. Pass `--with-hooks` to also wire auto-capture: the bundled Claude Code hook scripts run through Harness's first-party `@deepseek-ai/dsh-hooks-claude-code` bridge (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop) via a manifest written to `$DSH_HOME/agentmemory.hooks.json`. Defaults to `~/.dsh` when `DSH_HOME` is unset. |+| **Goose** | Goose MCP settings UI | Same `mcpServers` block; use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). || **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. || **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. |@@ -687,7 +720,7 @@ The agentmemory entry is the **same MCP server block** across every host that us### 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.+agentmemory registers its core operations as iii functions (`mem::remember`, `mem::observe`, `mem::context`, `mem::smart-search`, `mem::forget`). Any language with an iii SDK can call them directly over `ws://localhost:49134`, with no separate REST client per language.```bashpip install iii-sdk # Python@@ -718,7 +751,7 @@ npm install && npm run build && npm startThis starts agentmemory with a local `iii-engine` if `iii` is already installed, or falls back to Docker Compose if Docker is available. REST, streams, and the viewer bind to `127.0.0.1` by default.-Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`** — `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=<version>` if you've migrated to the sandbox model manually.+Install `iii-engine` manually. **agentmemory currently pins `iii-engine` to `v0.11.2`**. `v0.11.6` introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet. Pin lifts once the refactor lands. Override with `AGENTMEMORY_III_VERSION=<version>` if you've migrated to the sandbox model manually.- **macOS arm64:** `mkdir -p ~/.local/bin && curl -fsSL https://github.com/iii-hq/iii/releases/download/iii/v0.11.2/iii-aarch64-apple-darwin.tar.gz | tar -xz -C ~/.local/bin && chmod +x ~/.local/bin/iii`- **macOS x64:** swap `aarch64-apple-darwin` for `x86_64-apple-darwin`@@ -730,9 +763,9 @@ Or use Docker (the bundled `docker-compose.yml` pulls `iiidev/iii:0.11.2`). Full### 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:+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):**+**Option A: prebuilt Windows binary (recommended)**```powershell# 1. Open https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.11.2 in your browser@@ -751,7 +784,7 @@ iii --versionnpx -y @agentmemory/agentmemory```-**Option B — Docker Desktop:**+**Option B: Docker Desktop**```powershell# 1. Install Docker Desktop for Windows@@ -760,7 +793,7 @@ npx -y @agentmemory/agentmemorynpx -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:+**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:```powershellnpx -y @agentmemory/agentmemory mcp@@ -772,12 +805,12 @@ npx -y @agentmemory/mcp| Symptom | Fix ||---|---|-| `iii-engine process started` then `did not become ready within 15s` | Engine crashed on startup — re-run with `--verbose`, check stderr |+| `iii-engine process started` then `did not become ready within 15s` | Engine crashed on startup; re-run with `--verbose`, check stderr || `Could not start iii-engine` | Neither `iii.exe` nor Docker is installed. See Option A or B above || Port conflict | `netstat -ano \| findstr :3111` to see what's bound, then kill it or use `--port <N>` || Docker fallback skipped even though Docker is installed | Make sure Docker Desktop is actually running (system tray icon) |-> Note: the iii **engine** is a prebuilt binary, not a cargo crate — don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods, all pinned to v0.11.2: the prebuilt v0.11.2 binary above, the upstream sh install script **with the version pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), and the Docker image `iiidev/iii:0.11.2`. A bare `install.sh | sh` installs the **latest** engine, which agentmemory does not support — always pass `VERSION=0.11.2`. Easiest of all: just run `npx @agentmemory/agentmemory`, which fetches the pinned engine into `~/.agentmemory/bin` for you.+> Note: the iii **engine** is a prebuilt binary, not a cargo crate, so don't try to `cargo install` it. (The iii **SDKs** are published on crates.io, npm, and PyPI, but agentmemory doesn't need them.) Supported engine install methods, all pinned to v0.11.2: the prebuilt v0.11.2 binary above, the upstream sh install script **with the version pin** `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=0.11.2 sh` (macOS/Linux), and the Docker image `iiidev/iii:0.11.2`. A bare `install.sh | sh` installs the **latest** engine, which agentmemory does not support; always pass `VERSION=0.11.2`. Easiest of all: just run `npx @agentmemory/agentmemory`, which fetches the pinned engine into `~/.agentmemory/bin` for you.---@@ -786,7 +819,7 @@ npx -y @agentmemory/mcpOne-click templates for managed hosts. Each one ships a self-containedDockerfile that pulls `@agentmemory/agentmemory` from npm and copiesthe iii engine binary in from the official `iiidev/iii` Docker Hub-image — no pre-built agentmemory image required. Persistent storage+image; no pre-built agentmemory image required. Persistent storagemounts at `/data`; the first-boot entrypoint overwrites thenpm-bundled iii config (which binds `127.0.0.1`) with a deploy-tunedone that binds `0.0.0.0` and uses absolute `/data` paths, generates@@ -803,25 +836,25 @@ Render's one-click deploy button requires `render.yaml` at the repository root,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+- [`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,+- [`deploy/railway`](./deploy/railway/README.md): Hobby plan flat fee,volume in the dashboard.-- [`deploy/render`](./deploy/render/README.md) — Blueprint flow,+- [`deploy/render`](./deploy/render/README.md): Blueprint flow,automatic disk snapshots on paid plans.-- [`deploy/coolify`](./deploy/coolify/README.md) — self-hosted on your+- [`deploy/coolify`](./deploy/coolify/README.md): self-hosted on yourown VPS via [Coolify](https://coolify.io/self-hosted); same DockerCompose stack, you own the host and the data.Only port `3111` is published. The viewer on `3113` stays bound to-loopback inside the container — every template's README documents the+loopback inside the container; every template's README documents theSSH-tunnel pattern for reaching it.---<h2 id="why-agentmemory"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-why.svg"><img src="assets/tags/section-why.svg" alt="Why agentmemory" height="32" /></picture></h2>-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.+Every coding agent forgets everything when the session ends, and each new session starts with you re-explaining your stack. agentmemory runs in the background and removes that step.```textSession 1: "Add auth to the API"@@ -839,7 +872,7 @@ Session 2: "Now add rate limiting"### 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.+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 ||---|---|---|@@ -879,7 +912,7 @@ SessionStart hook fires### 4-Tier Memory Consolidation-Inspired by how human brains process memory — not unlike sleep consolidation.+Modeled on how human brains process memory, including sleep consolidation.| Tier | What | Analogy ||------|------|---------|@@ -908,9 +941,13 @@ Memories decay over time (Ebbinghaus curve). Frequently accessed memories streng| Capability | Description ||---|---|-| **Automatic capture** | Every tool use recorded via hooks — zero manual effort |+| **Automatic capture** | Every tool use recorded via hooks, no manual effort || **Semantic search** | BM25 + vector + knowledge graph with RRF fusion || **Memory evolution** | Versioning, supersession, relationship graphs |+| **Recall hygiene** | Superseded memory versions leave the search indexes; the version chain in KV keeps full history |+| **Near-duplicate hints** | Saves report an advisory `similarTo` match when new content closely resembles an existing memory |+| **Per-agent scoping** | `agentId` threads through save and recall across REST, MCP, and the search index, in shared or isolated mode |+| **Write-time provenance** | Every observation and memory carries an immutable origin channel (user, agent, tool, import, or shared) stamped at capture, save, and import || **Auto-forgetting** | TTL expiry, contradiction detection, importance eviction || **Privacy first** | API keys, secrets, `<private>` tags stripped before storage || **Self-healing** | Circuit breaker, provider fallback chain, health monitoring |@@ -934,6 +971,8 @@ Triple-stream retrieval combining three signals:Fused with Reciprocal Rank Fusion (RRF, k=60) and session-diversified (max 3 results per session).+Hybrid ranking applies to the primary recall path, not just `smart-search`: `mem::search` (behind `memory_recall`) ranks through the same BM25 + vector + graph fusion once the vector index is populated. Lesson recall runs on a dedicated in-memory BM25 index instead of scanning the whole corpus per query. Superseded memory versions are excluded from every recall path; the version chain keeps their history.+BM25 tokenizes Greek, Cyrillic, Hebrew, Arabic, and accented Latin out of the box. For Chinese / Japanese / Korean memories, install the optional segmenters (`npm install @node-rs/jieba tiny-segmenter`) to split CJK runs into word-level tokens; without them, agentmemory soft-falls to whole-run tokenization and prints a one-time hint on stderr.### Embedding providers@@ -957,33 +996,38 @@ npm install @huggingface/transformers<h2 id="mcp-server"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-mcp.svg"><img src="assets/tags/section-mcp.svg" alt="MCP Server" height="32" /></picture></h2>-54 tools, 6 resources, 3 prompts, and 15 skills, the most comprehensive MCP memory toolkit for any agent.+54 tools, 6 resources, 3 prompts, and 15 skills.-> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 54-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag — setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`.+> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 54-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag; setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`.### 54 Tools+Three tool surfaces, smallest to largest: `AGENTMEMORY_TOOLS=core` trims visibility to 8 essentials (`memory_save`, `memory_recall`, `memory_consolidate`, `memory_smart_search`, `memory_sessions`, `memory_diagnose`, `memory_lesson_save`, `memory_reflect`); the base set below is the registry's 14 foundational tools; the default (`AGENTMEMORY_TOOLS=all`) exposes all 54.+<details>-<summary>Core tools (always available)</summary>+<summary>Base tools (14)</summary>| 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_patterns` | Detect recurring patterns || `memory_sessions` | List recent sessions |+| `memory_smart_search` | Hybrid semantic + keyword search |+| `memory_vision_search` | Search image observations || `memory_timeline` | Chronological observations || `memory_profile` | Project profile (concepts, files, patterns) || `memory_export` | Export all memory data || `memory_relations` | Query relationship graph |+| `memory_commit_lookup` | Sessions behind a git commit |+| `memory_commits` | Commits recorded for a session |</details><details>-<summary>Extended tools (54 total — set AGENTMEMORY_TOOLS=all)</summary>+<summary>Extended tools (54 total, the default surface)</summary>| Tool | Description ||------|-------------|@@ -1021,14 +1065,16 @@ npm install @huggingface/transformers</details>-### 6 Resources · 3 Prompts · 4 Skills+### 6 Resources · 3 Prompts · 15 Skills| Type | Name | Description ||------|------|-------------|| Resource | `agentmemory://status` | Health, session count, memory count || Resource | `agentmemory://project/{name}/profile` | Per-project intelligence |+| Resource | `agentmemory://project/{name}/recent` | Recent observations for a project || Resource | `agentmemory://memories/latest` | Latest 10 active memories || Resource | `agentmemory://graph/stats` | Knowledge graph statistics |+| Resource | `agentmemory://team/{id}/profile` | Shared team profile || Prompt | `recall_context` | Search + return context messages || Prompt | `session_handoff` | Handoff data between agents || Prompt | `detect_patterns` | Analyze recurring patterns |@@ -1037,9 +1083,11 @@ npm install @huggingface/transformers| Skill | `/session-history` | Recent session summaries || Skill | `/forget` | Delete observations/sessions |+The table shows the four core skills. The full set is 8 invocable skills plus 7 reference skills; see the Native skills section above.+### Standalone MCP-Run without the full server — for any MCP client. Either of these works:+Run without the full server, for any MCP client. Either of these works:```bashnpx -y @agentmemory/agentmemory mcp # canonical (always available)@@ -1090,7 +1138,7 @@ cp plugin/opencode/commands/*.md ~/.config/opencode/commands/<h2 id="real-time-viewer"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-viewer.svg"><img src="assets/tags/section-viewer.svg" alt="Real-Time Viewer" height="32" /></picture></h2>-Auto-starts on port `3113`. Live observation stream, session explorer, memory browser, knowledge graph visualization, and health dashboard.+Auto-starts on port `3113`. Live observation stream with a stream status indicator, a two-pane session explorer (list beside a sticky detail panel on wide screens), memory and lesson rows that expand to the full stored record including raw JSON and origin provenance, a knowledge graph that clusters nodes by type while relations are sparse, session replay, and a health dashboard.```bashopen http://localhost:3113@@ -1102,19 +1150,19 @@ The viewer server binds to `127.0.0.1` by default. The REST-served `/agentmemory<h2 id="iii-console"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-viewer.svg"><img src="assets/tags/section-viewer.svg" alt="iii Console" height="32" /></picture></h2>-The viewer at `:3113` shows what your agent **remembered**. The [iii console](https://iii.dev/docs/console) shows what your agent **did** — every memory op as an OpenTelemetry trace, every KV entry editable, every function invocable, every stream tappable. Two windows on the same memory: one product-shaped, one engine-shaped.+The viewer at `:3113` shows what your agent **remembered**. The [iii console](https://iii.dev/docs/console) shows what your agent **did**: every memory op as an OpenTelemetry trace, every KV entry editable, every function invocable, every stream tappable. Two windows on the same memory: one product-shaped, one engine-shaped.Watch a `memory_smart_search` fire and see the BM25 scan → embedding lookup → RRF fusion → reranker as a waterfall. Edit a stuck consolidation timer in the KV browser. Replay a `PostToolUse` hook with a tweaked payload. Pin the WebSocket stream and watch observations land live.-agentmemory ships this for free because every function call and trigger fires through iii — nothing custom, nothing to instrument.+agentmemory ships this for free because every function call and trigger fires through iii; nothing custom, nothing to instrument.<p align="center">- <img src="assets/iii-console/workers.png" alt="iii console Workers page — connected workers including agentmemory instances with live function counts and runtime metadata" width="720" />+ <img src="assets/iii-console/workers.png" alt="iii console Workers page: connected workers including agentmemory instances with live function counts and runtime metadata" width="720" /><br/>- <em>Workers page: every connected worker — including agentmemory itself — with PID, function count, runtime, and last-seen.</em>+ <em>Workers page: every connected worker, including agentmemory itself, with PID, function count, runtime, and last-seen.</em></p>-**Already installed.** The console ships with `iii` — no separate installer.+**Already installed.** The console ships with `iii`; no separate installer.**Launch alongside agentmemory:**@@ -1139,15 +1187,15 @@ iii console --port 3114 \| 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. |+| **Workers** | See every connected worker and its live metrics, including the agentmemory worker itself. |+| **Functions** | Invoke any of agentmemory's functions directly with a JSON payload; handy for testing `memory.recall`, `memory.consolidate`, `graph.query` without wiring a client. |+| **Triggers** | Replay HTTP, cron, event, and state triggers: fire the consolidation cron manually, retry an HTTP route, emit a state change. |+| **States** | KV browser with full CRUD over sessions, memory slots, lifecycle timers, and the embeddings index; edit values in place. || **Streams** | Live WebSocket monitor for memory writes, hook events, and observation updates as they flow through iii streams. || **Queues** | Durable queue topics + dead-letter management. Replay or drop failed embedding / compression jobs. || **Traces** | OpenTelemetry waterfall / flame / service-breakdown views. Filter by `trace_id` to see exactly which functions, DB calls, and embedding requests a single `memory.search` produced. || **Logs** | Structured OTEL logs filtered and correlated to trace/span IDs. |-| **Config** | Runtime configuration — see exactly which workers, providers, and ports your engine is running with. |+| **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. |<p align="center">@@ -1158,17 +1206,17 @@ iii console --port 3114 \**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.+`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.+> **Heads-up:** no auth is enforced on the console itself; keep it bound to `127.0.0.1` (the default) and never expose it publicly.---<h2 id="powered-by-iii"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-architecture.svg"><img src="assets/tags/section-architecture.svg" alt="Powered by iii" height="32" /></picture></h2>-agentmemory is **already a running [iii](https://iii.dev) instance**. Three primitives — worker, function, trigger — compose the runtime; KV state, streams, and OTEL traces come from iii-state, iii-stream, and iii-observability workers that ship with iii. You didn't install Postgres, Redis, Express, pm2, or Prometheus, because iii replaces them.+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.@@ -1184,19 +1232,19 @@ iii worker add iii-database # swap in a SQL-backed state adapteriii 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.+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-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-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.+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@@ -1209,7 +1257,7 @@ Full registry: [workers.iii.dev](https://workers.iii.dev). Every worker there co| Prometheus / Grafana | iii OTEL + health monitor || Custom plugin systems | `iii worker add <name>` |-**175 source files · ~39,200 LOC · 1,596+ tests · 261 functions · 52 KV scopes** — all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.+**182 source files · ~41,600 LOC · 1,619 tests · 264 functions · 50 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself.---@@ -1226,18 +1274,18 @@ agentmemory auto-detects from your environment. By default, no LLM calls are mad| 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` |+| OpenAI API | `OPENAI_API_KEY` | Default `gpt-5.6-luna`, override with `OPENAI_MODEL` || **Local (Ollama / LM Studio / vLLM / llama.cpp)** | `OPENAI_API_KEY=local` + `OPENAI_BASE_URL=http://localhost:11434/v1` (Ollama) or `http://localhost:1234/v1` (LM Studio) + `OPENAI_MODEL=<your model>` | Anything OpenAI-API-compatible. Zero cost, runs on your hardware. See [Local models](#local-models-ollama--lm-studio--vllm) below. |-| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions — used to cause unbounded Stop-hook recursion so it is no longer the default. |+| Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions; it used to cause unbounded Stop-hook recursion, so it is no longer the default. |### Local models (Ollama / LM Studio / vLLM)-agentmemory talks to any OpenAI-API-compatible server, so anything that exposes `/v1/chat/completions` works without code changes. No paid keys, no cloud, no rate limits — runs entirely on your hardware.+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 pull qwen3:8b # or qwen3:4b, gpt-oss:20b, qwen3-coder:30b, etc.ollama serve```@@ -1245,34 +1293,37 @@ ollama serve# ~/.agentmemory/.envOPENAI_API_KEY=ollama # any non-empty string; Ollama ignores itOPENAI_BASE_URL=http://localhost:11434/v1-OPENAI_MODEL=qwen2.5-coder:7b+OPENAI_MODEL=qwen3:8b```**LM Studio** (default port `1234`):-Open LM Studio → Local Server tab → Start Server. Pick any chat model from the picker (Qwen 2.5 Coder, Llama 3.2, DeepSeek, etc.).+Open LM Studio → Local Server tab → Start Server. Pick any chat model from the picker (Qwen 3, gpt-oss, DeepSeek R1, etc.).```env# ~/.agentmemory/.envOPENAI_API_KEY=lmstudio # any non-empty string; LM Studio ignores itOPENAI_BASE_URL=http://localhost:1234/v1-OPENAI_MODEL=qwen2.5-coder-7b-instruct # match the model name from LM Studio+OPENAI_MODEL=qwen3-8b # match the model name from LM Studio```-**vLLM / llama.cpp / Text Generation Inference**: same shape — point `OPENAI_BASE_URL` at whatever URL your server exposes, set `OPENAI_MODEL` to a name your server will accept.+**vLLM / llama.cpp / Text Generation Inference**: same shape. Point `OPENAI_BASE_URL` at whatever URL your server exposes and set `OPENAI_MODEL` to a name your server will accept.**Model picks for memory work**: compression and summarization are short tasks (<2K tokens in, <500 tokens out) where a 7B instruct model is plenty. Recommendations:| Model | Size | Why ||-------|------|-----|-| `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 |+| `qwen3:8b` | ~5.2 GB | Balanced default on a 16 GB machine; strong at extraction and tool-shaped text |+| `qwen3:4b` | ~2.6 GB | Smallest sane option; fine for compression, weaker for graph extraction |+| `qwen3-coder:30b` | ~19 GB | Best local pick for code-shaped sessions (30B MoE, 3.3B active) on 24-32 GB hardware |+| `gpt-oss:20b` | ~14 GB | Strong general model that fits 16 GB RAM |+| `deepseek-r1:8b` | ~5.2 GB | Reasoning distill; slower but cleaner extractions |++Qwen 3 models think by default and can burn the whole token budget on reasoning before any output. Set `AGENTMEMORY_LLM_NOTHINK=1` to append `/no_think` to graph-extraction prompts, and raise `MAX_TOKENS` (16384 works) if extractions come back empty.Reasoning-class models (`o1`-style with `<think>` blocks) can return empty `content` with a `reasoning` field your local server may not surface. If extractions come back blank, switch to a non-reasoning model first. The `OPENAI_REASONING_EFFORT=none` env can also disable thinking on Ollama Cloud thinking models that mirror the OpenAI reasoning schema.-Local embeddings ship out of the box via `@huggingface/transformers` — `EMBEDDING_PROVIDER=local` (default) gives you `Xenova/all-MiniLM-L6-v2` (384-dim) entirely on-device. No extra config needed.+Local embeddings ship out of the box via `@huggingface/transformers`: `EMBEDDING_PROVIDER=local` (default) gives you `Xenova/all-MiniLM-L6-v2` (384-dim) entirely on-device. No extra config needed.### Cost-aware model selection@@ -1280,18 +1331,20 @@ Background compression runs on every observation, so model choice meaningfully c| Tier | Model | Input / 1M | Output / 1M | Cost for the captured 35h | Notes ||------|-------|------------|-------------|---------------------------|-------|+| Recommended | `deepseek/deepseek-v4-flash-0731` | $0.07 | $0.14 | ~$0.07 (est.) | Latest DeepSeek; cheapest recommended pick for compression workloads. || Recommended | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Solid compression + summarization quality at ~10× lower cost than Sonnet. |-| Recommended | `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. |+| Premium | `anthropic/claude-sonnet-5` | $3.00 | $15.00 | ~$5.02 (est.) | Same list price as the measured Sonnet 4.6 run; $2/$10 intro pricing through 2026-08-31. |+| Premium | `openai/gpt-5.6-sol` | $5.00 | $30.00 | ~$9 (est.) | Flagship tier; expensive for always-on background work. |+| Avoid | `anthropic/claude-opus-5` | $5.00 | $25.00 | ~$8.40 (est.) | Flagship-class model; overspend for compression. |++Measured rows come from the captured run; (est.) rows scale the same token mix by each model's list price.agentmemory prints a runtime warning when `OPENROUTER_MODEL` matches a premium-tier pattern. Set `AGENTMEMORY_SUPPRESS_COST_WARNING=1` to silence once you've made an informed choice.-Quality vs cost tradeoff for memory work: compression is a summarization task with relatively loose quality bars (the agent re-reads the summary, not the user). DeepSeek-V4-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.+Quality vs cost tradeoff for memory work: compression is a summarization task with relatively loose quality bars (the agent re-reads the summary, not the user). DeepSeek V4 Flash / V4 Pro / Qwen3-Coder land within rounding error of Sonnet on this task while costing 10-70× less. Save the premium-tier models for queries you read directly.-Sources: [OpenRouter pricing for 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/).+Sources: [OpenRouter pricing for Claude Sonnet 5](https://openrouter.ai/anthropic/claude-sonnet-5), [DeepSeek V4 Flash](https://openrouter.ai/deepseek/deepseek-v4-flash-0731), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).### Multi-agent memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)@@ -1315,7 +1368,7 @@ What gets tagged when `AGENT_ID` is set: `Session.agentId`, `RawObservation.agenWhat gets filtered in isolated mode: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Each endpoint accepts `?agentId=<role>` to override per-request, and `?agentId=*` to opt out of the env scope entirely. `/memories` also accepts `?includeOrphans=true` to surface pre-AGENT_ID memories whose `agentId` is undefined.-Per-call override at the SDK / REST layer: every mutating endpoint (`/session/start`, `/remember`) accepts an `agentId` field in the request body that wins over the env. Useful for runtimes routing many roles through one server process.+Per-call override at the SDK / REST layer: every mutating endpoint (`/session/start`, `/remember`) accepts an `agentId` field in the request body that wins over the env. Useful for runtimes routing many roles through one server process. The MCP `memory_save` tool exposes the same `agentId` field, the standalone stdio server forwards both `agentId` and `project`, and saved memories carry `agentId` into the search index, so agent-scoped search covers memories as well as observations.When `AGENT_ID` is unset, memory remains unscoped (legacy behavior, no tags, no filters).@@ -1328,7 +1381,7 @@ agentmemory + iii-engine bind four ports by default. If a restart fails with `po| `3111` | agentmemory | REST API + MCP HTTP + `/agentmemory/health` + `/agentmemory/livez` | `III_REST_PORT` || `3112` | iii-engine | Internal streams worker (consumed by agentmemory + viewer) | `III_STREAMS_PORT` || `3113` | agentmemory | Real-time viewer (`http://localhost:3113`) | `AGENTMEMORY_VIEWER_PORT` |-| `49134` | iii-engine | WebSocket — workers register here, OTel telemetry flows over it | `III_ENGINE_URL` (full URL, default `ws://localhost:49134`) |+| `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:@@ -1343,7 +1396,7 @@ netstat -ano | findstr ":3111 :3112 :3113 :49134"taskkill /F /PID <pid>```-`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful shutdown. The manual cleanup above is only for the post-crash case where neither pidfile is left behind.+`agentmemory stop` reaps both the worker and the engine pidfile cleanly on graceful shutdown. In Docker mode it tears down only agentmemory's own compose services and reaps the native worker before the Docker teardown; the CLI also refuses to adopt or signal Docker or VM port holders (Docker backend, vpnkit, colima) as the native engine unless `--force` is passed. The manual cleanup above is only for the post-crash case where neither pidfile is left behind.### Config File@@ -1393,7 +1446,7 @@ Create `~/.agentmemory/.env`:# # 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_MODEL=gpt-5.6-luna # 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@@ -1479,6 +1532,10 @@ Create `~/.agentmemory/.env`:# Observations are still captured via# PostToolUse regardless of this flag.# GRAPH_EXTRACTION_ENABLED=false+# AGENTMEMORY_LLM_NOTHINK=1 # Local reasoning models only: ask the+ # model to skip its hidden thinking pass+ # during graph extraction. Faster runs;+ # relation quality can drop slightly.# CONSOLIDATION_ENABLED=false # on by default when an LLM provider is configured# LESSON_DECAY_ENABLED=true# OBSIDIAN_AUTO_EXPORT=false@@ -1491,7 +1548,7 @@ Create `~/.agentmemory/.env`:# USER_ID=# TEAM_MODE=private-# Tool visibility: "core" (8 tools, lean fallback) or "all" (54 tools)+# Tool visibility: "all" (54 tools, default) or "core" (8 tools, lean)# AGENTMEMORY_TOOLS=core```@@ -1533,7 +1590,7 @@ Full endpoint list: [`src/triggers/api.ts`](src/triggers/api.ts)```bashnpm run dev # Hot reloadnpm run build # Production build-npm test # 1,596+ tests+npm test # 1,619 testsnpm run test:integration # API tests (requires running services)```diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.mdindex 332519b4..906780a4 100644--- a/READMEs/README.de-DE.md+++ b/READMEs/README.de-DE.md@@ -1215,7 +1215,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.mdindex af7e7b35..858bc6ad 100644--- a/READMEs/README.es-ES.md+++ b/READMEs/README.es-ES.md@@ -1208,7 +1208,7 @@ Crea `~/.agentmemory/.env`:# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.mdindex f3952260..22be0937 100644--- a/READMEs/README.fr-FR.md+++ b/READMEs/README.fr-FR.md@@ -1215,7 +1215,7 @@ Créez `~/.agentmemory/.env` :# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.mdindex dc6f8d9f..ef3ca378 100644--- a/READMEs/README.hi-IN.md+++ b/READMEs/README.hi-IN.md@@ -1218,7 +1218,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.mdindex bca18961..aad9ac2d 100644--- a/READMEs/README.ja-JP.md+++ b/READMEs/README.ja-JP.md@@ -1218,7 +1218,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.mdindex 7bd90050..962ddea1 100644--- a/READMEs/README.ko-KR.md+++ b/READMEs/README.ko-KR.md@@ -1199,7 +1199,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.mdindex e56fd799..e8ae60b3 100644--- a/READMEs/README.pt-BR.md+++ b/READMEs/README.pt-BR.md@@ -1208,7 +1208,7 @@ Crie `~/.agentmemory/.env`:# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.mdindex 0e112f70..1983de9e 100644--- a/READMEs/README.ru-RU.md+++ b/READMEs/README.ru-RU.md@@ -1215,7 +1215,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.mdindex 4b68acc7..4347d06a 100644--- a/READMEs/README.tr-TR.md+++ b/READMEs/README.tr-TR.md@@ -1219,7 +1219,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.mdindex e7b50d52..26e31284 100644--- a/READMEs/README.zh-CN.md+++ b/READMEs/README.zh-CN.md@@ -1216,7 +1216,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.mdindex ce87e241..de9ce0f8 100644--- a/READMEs/README.zh-TW.md+++ b/READMEs/README.zh-TW.md@@ -1216,7 +1216,7 @@ CONSOLIDATION_ENABLED=true# # 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_MODEL=gpt-5.6-luna # 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 shoulddiff --git a/assets/agents/pi.svg b/assets/agents/pi.svgindex 3d40fc0e..3dd7d06b 100644--- a/assets/agents/pi.svg+++ b/assets/agents/pi.svg@@ -1,5 +1,6 @@<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">+ <rect width="800" height="800" rx="160" fill="#101010"/><path fill="#ffffff" fill-rule="evenodd" d="M165.29 165.29H517.36diff --git a/assets/tags/light/section-competitors.svg b/assets/tags/light/section-competitors.svgindex 63d12841..8b3b826e 100644--- a/assets/tags/light/section-competitors.svg+++ b/assets/tags/light/section-competitors.svg@@ -12,5 +12,5 @@<rect x="0" y="0" width="320" height="44" rx="8" fill="url(#bg)" stroke="#E5E7EB" stroke-width="1"/><rect x="0" y="0" width="6" height="44" rx="3" fill="url(#accent)"/><text x="22" y="20" fill="#0F172A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="13" font-weight="800" letter-spacing="2.2" text-rendering="geometricPrecision">VS COMPETITORS</text>- <text x="22" y="34" fill="#64748B" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="10" font-weight="500" letter-spacing="0.2" text-rendering="geometricPrecision">Mem0 · Letta · Khoj · Hippo · claude-mem</text>+ <text x="22" y="34" fill="#64748B" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="10" font-weight="500" letter-spacing="0.2" text-rendering="geometricPrecision">Mem0 · Letta · Zep · TencentDB · more</text></svg>\ No newline at end of filediff --git a/assets/tags/light/stat-tests.svg b/assets/tags/light/stat-tests.svgindex b8f386db..f4675bd9 100644--- a/assets/tags/light/stat-tests.svg+++ b/assets/tags/light/stat-tests.svg@@ -1,5 +1,5 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 1596+">+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 1648+"><rect x="0" y="0" width="140" height="48" rx="10" fill="#FFFFFF" stroke="#E5E7EB" stroke-width="1"/>- <text x="70" y="24" fill="#16A34A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">1596+</text>+ <text x="70" y="24" fill="#16A34A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">1648+</text><text x="70" y="38" fill="#64748B" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="9" font-weight="600" text-anchor="middle" letter-spacing="1.5">TESTS PASSING</text></svg>diff --git a/assets/tags/section-competitors.svg b/assets/tags/section-competitors.svgindex 90761e86..5a0dfdc0 100644--- a/assets/tags/section-competitors.svg+++ b/assets/tags/section-competitors.svg@@ -12,5 +12,5 @@<rect x="0" y="0" width="320" height="44" rx="8" fill="url(#bg)" stroke="#2A2A2A" stroke-width="1"/><rect x="0" y="0" width="6" height="44" rx="3" fill="url(#accent)"/><text x="22" y="20" fill="#FFFFFF" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="13" font-weight="800" letter-spacing="2.2" text-rendering="geometricPrecision">VS COMPETITORS</text>- <text x="22" y="34" fill="#9CA3AF" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="10" font-weight="500" letter-spacing="0.2" text-rendering="geometricPrecision">Mem0 · Letta · Khoj · Hippo · claude-mem</text>+ <text x="22" y="34" fill="#9CA3AF" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="10" font-weight="500" letter-spacing="0.2" text-rendering="geometricPrecision">Mem0 · Letta · Zep · TencentDB · more</text></svg>\ No newline at end of filediff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svgindex 8a4637dd..a7599939 100644--- a/assets/tags/stat-tests.svg+++ b/assets/tags/stat-tests.svg@@ -1,5 +1,5 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 1596+">+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 48" fill="none" role="img" aria-label="TESTS PASSING: 1648+"><rect x="0" y="0" width="140" height="48" rx="10" fill="#1A1A1A" stroke="#2A2A2A" stroke-width="1"/>- <text x="70" y="24" fill="#00D26A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">1596+</text>+ <text x="70" y="24" fill="#00D26A" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="18" font-weight="900" text-anchor="middle" letter-spacing="-0.3">1648+</text><text x="70" y="38" fill="#9CA3AF" font-family='ui-sans-serif, -apple-system, "Segoe UI", Inter, system-ui, sans-serif' font-size="9" font-weight="600" text-anchor="middle" letter-spacing="1.5">TESTS PASSING</text></svg>diff --git a/benchmark/COMPARISON.md b/benchmark/COMPARISON.mdindex 8914c98b..207ca0f6 100644--- a/benchmark/COMPARISON.md+++ b/benchmark/COMPARISON.md@@ -121,6 +121,22 @@ This isn't a "agentmemory wins everything" page. Different tools solve different- Multi-agent shared memory as a primary feature- "Forget by default, earn persistence through use" philosophy+**Choose TencentDB Agent Memory if you want:**+- Team-level shared memory: conversations, docs, and code turned into four asset types (Chat Memory, Skill, Wiki, CodeGraph) with team roles and ownership+- Zero-integration capture via an LLM proxy (point the agent's base URL at it; no hooks or MCP required)+- CodeGraph impact analysis (symbols, call relationships) alongside memory+- Note: the proxy sits in front of every model call, deployment is a multi-service Docker stack (Core + Hub + Proxy), the published benchmark is PersonaMem (76%, self-reported), and automated memory routing is still in progress per their README++**Choose Zep / Graphiti if you want:**+- A temporal knowledge graph: facts carry a time dimension, so "what was true when" is a first-class query+- The strongest published temporal-query results (LongMemEval 63.8%)+- Note: graph construction runs in the background, so freshly ingested facts can take time to become retrievable, and per-conversation memory footprint is reported to run far above extraction-based systems++**Choose Cognee if you want:**+- Knowledge-graph construction from documents and structured data before query time+- Entity-relationship extraction as the primary product rather than session capture+- Note: Python-only, and built for document ingestion rather than coding-agent memory+---## Running Your Own Benchmarksdiff --git a/integrations/pi/index.ts b/integrations/pi/index.tsindex e6ad648d..24e71f3c 100644--- a/integrations/pi/index.ts+++ b/integrations/pi/index.ts@@ -1,4 +1,4 @@-import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import { Type } from "typebox";import path from "node:path";import crypto from "node:crypto";@@ -89,6 +89,7 @@ async function callAgentMemory<T>(method?: "GET" | "POST";body?: unknown;baseUrl?: string;+ timeoutMs?: number;},): Promise<T | null> {const baseUrl = normalizeBaseUrl(options?.baseUrl || process.env.AGENTMEMORY_URL || DEFAULT_URL);@@ -105,6 +106,7 @@ async function callAgentMemory<T>(method,headers,body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,+ signal: options?.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined,});if (!response.ok) return null;return (await response.json()) as T;@@ -149,14 +151,49 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {let lastPrompt = "";let lastHealthOk = false;+ const toolObserveEnabled = process.env.AGENTMEMORY_TOOL_OBSERVE !== "0";++ // Skips the round-trip when an auto-retry re-submits an identical prompt.+ const DEDUP_WINDOW_MS = 5 * 60 * 1000;+ const recentHashes = new Map<string, number>();+ function isDuplicate(data: string): boolean {+ const hash = crypto.createHash("sha256").update(data).digest("hex");+ const now = Date.now();+ const prev = recentHashes.get(hash);+ if (prev !== undefined && now - prev < DEDUP_WINDOW_MS) return true;+ if (recentHashes.size > 500) {+ for (const [key, ts] of recentHashes) {+ if (now - ts >= DEDUP_WINDOW_MS) recentHashes.delete(key);+ }+ }+ recentHashes.set(hash, now);+ return false;+ }+async function getHealth() {return await callAgentMemory<HealthResponse>("health", { method: "GET" });}async function refreshStatus(ctx: { ui: { setStatus: (key: string, text: string) => void } }) {+ // Bind before the await: ctx goes stale if the session is replaced.+ let setStatus: (key: string, text: string) => void;+ try {+ const ui = ctx.ui;+ setStatus = ui.setStatus.bind(ui);+ } catch {+ return;+ }const health = await getHealth();- lastHealthOk = !!health && (health.status === "healthy" || health.health?.status === "healthy");- ctx.ui.setStatus("agentmemory", lastHealthOk ? "🧠 agentmemory" : "🧠 agentmemory off");+ lastHealthOk =+ !!health &&+ (health.status === "ok" ||+ health.status === "healthy" ||+ health.health?.status === "healthy");+ try {+ setStatus("agentmemory", lastHealthOk ? "🧠 agentmemory" : "🧠 agentmemory off");+ } catch {+ // status is best-effort+ }}pi.registerCommand("agentmemory-status", {@@ -209,7 +246,7 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {}),async execute(_toolCallId, params) {const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", {- body: { query: params.query, limit: params.limit ?? 5 },+ body: { query: params.query, limit: params.limit ?? 5, project: currentProject },});const results = result?.results || [];return {@@ -234,7 +271,7 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {}),async execute(_toolCallId, params) {const result = await callAgentMemory<Record<string, unknown>>("remember", {- body: { content: params.content, type: params.type || "fact" },+ body: { content: params.content, type: params.type || "fact", project: currentProject },});if (!result) {return {@@ -255,6 +292,12 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {currentCwd = process.cwd();currentProject = resolveProjectName(currentCwd);await refreshStatus(ctx);+ // After refreshStatus: that is where lastHealthOk is first populated.+ if (lastHealthOk) {+ await callAgentMemory("session/start", {+ body: { sessionId, project: currentProject, cwd: currentCwd },+ });+ }});pi.on("before_agent_start", async (event, ctx) => {@@ -263,8 +306,21 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {lastPrompt = event.prompt?.trim() || "";if (!lastPrompt) return;+ if (lastHealthOk && !isDuplicate(`prompt_submit:${sessionId}:${lastPrompt}`)) {+ void callAgentMemory("observe", {+ body: {+ hookType: "prompt_submit",+ sessionId,+ project: currentProject,+ cwd: currentCwd,+ timestamp: new Date().toISOString(),+ data: { prompt: lastPrompt },+ },+ });+ }+const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", {- body: { query: lastPrompt, limit: 5 },+ body: { query: lastPrompt, limit: 5, project: currentProject },});const results = result?.results || [];const recallBlock = results.length@@ -280,6 +336,39 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {};});+ pi.on("tool_result", (event) => {+ if (!toolObserveEnabled || !lastHealthOk || !sessionId) return;+ const toolName = event.toolName;+ if (!toolName) return;+ let input = "";+ try {+ input = typeof event.input === "string" ? event.input : JSON.stringify(event.input ?? {});+ } catch {+ // non-serializable+ }+ let output = "";+ try {+ output = typeof event.content === "string" ? event.content : JSON.stringify(event.content ?? "");+ } catch {+ // non-serializable+ }+ void callAgentMemory("observe", {+ body: {+ hookType: "post_tool_use",+ sessionId,+ project: currentProject,+ cwd: currentCwd,+ timestamp: new Date().toISOString(),+ data: {+ tool_name: toolName,+ tool_input: input.slice(0, 8000),+ tool_output: output.slice(0, 8000),+ ...(event.isError ? { tool_error: true } : {}),+ },+ },+ });+ });+pi.on("agent_end", async (event) => {if (!lastHealthOk || !lastPrompt) return;const assistantText = getLastAssistantText(event.messages as unknown[]);@@ -293,10 +382,22 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {timestamp: new Date().toISOString(),data: {tool_name: "conversation",- tool_input: lastPrompt.slice(0, 500),- tool_output: assistantText.slice(0, 4000),+ tool_input: lastPrompt.slice(0, 8000),+ tool_output: assistantText.slice(0, 8000),},},});});++ pi.on("session_shutdown", async (event) => {+ // /new, /resume, /fork and reloads fire this too; only quit ends the session.+ if (event.reason !== "quit") return;+ if (!lastHealthOk || !sessionId) return;+ // session/end already fans out the summary server-side (#1203).+ await callAgentMemory("session/end", {+ body: { sessionId },+ timeoutMs: 5_000,+ });+ void callAgentMemory("consolidate", { body: {} });+ });}diff --git a/integrations/pi/package.json b/integrations/pi/package.jsonindex eec302de..fdc37b3b 100644--- a/integrations/pi/package.json+++ b/integrations/pi/package.json@@ -1,5 +1,32 @@{"name": "agentmemory-pi-extension",+ "version": "0.1.0","private": true,- "type": "module"+ "description": "agentmemory extension for the pi coding agent: memory recall on agent start, capture on agent end, memory_search / memory_save / memory_health tools, /agentmemory-status command",+ "type": "module",+ "license": "Apache-2.0",+ "keywords": [+ "pi-package",+ "agentmemory",+ "memory"+ ],+ "repository": {+ "type": "git",+ "url": "https://github.com/rohitg00/agentmemory.git",+ "directory": "integrations/pi"+ },+ "files": [+ "index.ts",+ "security.ts",+ "README.md"+ ],+ "pi": {+ "extensions": [+ "./index.ts"+ ]+ },+ "peerDependencies": {+ "@earendil-works/pi-coding-agent": "*",+ "typebox": "*"+ }}diff --git a/package.json b/package.jsonindex 79b716c9..ed9b5325 100644--- a/package.json+++ b/package.json@@ -45,6 +45,7 @@"files": ["dist/","plugin/",+ "integrations/pi/","iii-config.yaml","iii-config.docker.yaml","docker-compose.yml",diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.tsindex 1a1d0426..f54fc6be 100644--- a/plugin/opencode/agentmemory-capture.ts+++ b/plugin/opencode/agentmemory-capture.ts@@ -52,11 +52,12 @@ async function observe(hookType: string,data: Record<string, unknown>,): Promise<void> {+ const proj = projectFor(sessionId);await post("/observe", {hookType,sessionId,- project: projectName,- cwd: projectCwd,+ project: proj.name,+ cwd: proj.cwd,timestamp: new Date().toISOString(),data,});@@ -64,27 +65,45 @@ async function observe(let activeSessionId: string | null = null;let pendingConfig: Record<string, unknown> | null = null;-// projectName is the canonical scope (same resolution order as the hooks'-// resolveProject: env override, git toplevel basename, cwd basename) so-// OpenCode sessions land in the same project bucket as every other agent on-// the repo. projectCwd keeps the full path for the cwd field.-let projectName: string | null = null;-let projectCwd: string | null = null;+// Default scope resolved at plugin init (same resolution order as the hooks'+// resolveProject: env override, git toplevel basename, cwd basename). In a+// long-lived OpenCode process serving multiple directories these defaults are+// only a fallback — attribution is per-session via sessionProjects, resolved+// from each session's own directory at session.created. Module-level-only+// state recorded home-directory sessions under whatever repo loaded first.+let defaultProjectName: string | null = null;+let defaultProjectCwd: string | null = null;+const sessionProjects = new Map<string, { name: string; cwd: string }>();++function projectFor(sessionId: string): { name: string | null; cwd: string | null } {+ const p = sessionProjects.get(sessionId);+ return p ?? { name: defaultProjectName, cwd: defaultProjectCwd };+}++const projectNameCache = new Map<string, string>();function resolveProjectName(dir: string): string {const explicit = process.env.AGENTMEMORY_PROJECT_NAME?.trim();if (explicit) return explicit;+ const cached = projectNameCache.get(dir);+ if (cached !== undefined) return cached;try {const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {cwd: dir,stdio: ["ignore", "pipe", "ignore"],encoding: "utf8",}).trim();- if (top) return basename(top);+ if (top) {+ const name = basename(top);+ projectNameCache.set(dir, name);+ return name;+ }} catch {// not a git repo, fall through}- return basename(dir) || dir;+ const fallback = basename(dir) || dir;+ projectNameCache.set(dir, fallback);+ return fallback;}const stashedFiles = new Map<string, Set<string>>();const seenSubtaskIds = new Map<string, Set<string>>();@@ -119,6 +138,7 @@ function pruneSessionMaps(sid: string): void {stashedFiles.delete(sid);seenSubtaskIds.delete(sid);seenToolCallIds.delete(sid);+ sessionProjects.delete(sid);}function safeSlice(v: unknown, max: number): string {@@ -194,8 +214,8 @@ function extractErrorMessage(err: unknown): string {}export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {- projectCwd = ctx.worktree || ctx.project?.id || process.cwd();- projectName = resolveProjectName(projectCwd);+ defaultProjectCwd = ctx.worktree || ctx.project?.id || process.cwd();+ defaultProjectName = resolveProjectName(defaultProjectCwd);return {event: async ({ event }) => {@@ -215,13 +235,28 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {// and another `session.created` event during the await could// rebind it, causing context to be cached against the wrong key.const sessionId = activeSessionId;+ // Attribute this session to its own directory when the event+ // carries one; a multi-directory OpenCode process otherwise+ // records every session under whichever repo loaded the plugin.+ const sessionDir =+ typeof info?.directory === "string" && info.directory+ ? info.directory+ : defaultProjectCwd;+ let proj: { name: string | null; cwd: string | null };+ if (sessionDir) {+ const entry = { cwd: sessionDir, name: resolveProjectName(sessionDir) };+ sessionProjects.set(sessionId, entry);+ proj = entry;+ } else {+ proj = projectFor(sessionId);+ }const startResult = await postJson("/session/start", {sessionId,title: info?.title ?? null,parentID: info?.parentID ?? null,version: info?.version ?? null,- project: projectName,- cwd: projectCwd,+ project: proj.name,+ cwd: proj.cwd,});// cache the context returned at session/start so the// chat.system.transform hook injects it without a second fetch.@@ -299,10 +334,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {post("/crystals/auto", { olderThanDays: 7 }, 30000);post("/consolidate-pipeline", { tier: "all", force: true }, 30000);if (sid === activeSessionId) activeSessionId = null;- stashedFiles.delete(sid);+ pruneSessionMaps(sid);startContextCache.delete(sid);- seenSubtaskIds.delete(sid);- seenToolCallIds.delete(sid);contextInjectedSessions.delete(sid);}@@ -639,7 +672,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {if (typeof ctx !== "string" || ctx.length === 0) {const result = await postJson("/context", {sessionId: sid,- project: projectName,+ project: projectFor(sid).name,});ctx = (result as any)?.context;} else {@@ -677,7 +710,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {const result = await postJson("/context", {sessionId: sid,- project: projectName,+ project: projectFor(sid).name,});const ctx = (result as any)?.context;if (typeof ctx === "string" && ctx.length > 0) {diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjsindex 0b1c43b0..41fda645 100755--- a/plugin/scripts/stop.mjs+++ b/plugin/scripts/stop.mjs@@ -24,12 +24,6 @@ async function main() {if (!data || typeof data !== "object") 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(),diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.mdindex 8943cfa4..a137de96 100644--- a/plugin/skills/agentmemory-agents/REFERENCE.md+++ b/plugin/skills/agentmemory-agents/REFERENCE.md@@ -3,7 +3,7 @@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.<!-- AUTOGEN:agents START - generated by scripts/skills/generate.ts, do not edit by hand -->-`agentmemory connect <agent>` wires the memory server into a host agent. 19 adapters:+`agentmemory connect <agent>` wires the memory server into a host agent. 20 adapters:| Agent | Name | Protocol || --- | --- | --- |@@ -16,13 +16,14 @@ Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand;| 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. Pass --with-hooks to also install the native ~/.factory/hooks.json auto-capture hooks. |+| DeepSeek Harness | `dsh` | Using MCP via $DSH_HOME/cordis.patch.yml (the home-level patch layer every profile loads). Tools appear as mcp__agentmemory__*. Pass --with-hooks to also wire auto-capture through Harness's Claude Code hook bridge. || 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 https://github.com/rohitg00/agentmemory/tree/main/integrations/hermes. || 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 https://github.com/rohitg00/agentmemory/tree/main/integrations/openclaw. || OpenCode | `opencode` | Using MCP via ~/.config/opencode/opencode.json (top-level `mcp` key). For full auto-capture, also install the bundled plugin in plugin/opencode/. || OpenHuman | `openhuman` | Using native hooks (REST API at :3111). MCP not required. |-| pi | `pi` | Using native hooks (REST API at :3111). MCP not required. |+| pi | `pi` | Using native lifecycle hooks against the REST API at :3111 (recall on agent start, capture on agent end, memory tools). 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-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.mdindex cbd485d3..d12aaed7 100644--- a/plugin/skills/agentmemory-config/REFERENCE.md+++ b/plugin/skills/agentmemory-config/REFERENCE.md@@ -3,7 +3,7 @@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.<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 36 recognized variables:+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 37 recognized variables:- `AGENTMEMORY_AGENT_SCOPE`- `AGENTMEMORY_ALLOW_AGENT_SDK`@@ -24,6 +24,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e- `AGENTMEMORY_IMAGE_EMBEDDINGS`- `AGENTMEMORY_IMAGE_STORE_MAX_BYTES`- `AGENTMEMORY_INJECT_CONTEXT`+- `AGENTMEMORY_LLM_NOTHINK`- `AGENTMEMORY_LLM_TIMEOUT_MS`- `AGENTMEMORY_MCP_BLOCK`- `AGENTMEMORY_PROBE_TIMEOUT_MS`diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.mdindex b6b18583..b2a78fe5 100644--- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md+++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md@@ -40,7 +40,7 @@ agentmemory exposes 54 MCP tools. 8 are in the lean core set (`--tools core` or| `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_save` | yes | `content`*: string, `type`: string, `concepts`: string, `files`: string, `project`: string, `agentId`: 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. |diff --git a/src/cli.ts b/src/cli.tsindex 918e011c..8bbdda93 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -830,6 +830,18 @@ function adoptRunningEngine(): void {const pids = findEnginePidsByPort(getRestPort());const enginePid = pids[0];+ if (enginePid) {+ // A Docker-forwarded port is held by the VM/proxy process+ // (com.docker.backend, vpnkit, ...), not the engine. Adopting it+ // as kind:"native" would make a later `stop` SIGTERM that process.+ const comm = pidCommand(enginePid);+ if (isForeignPortHolder(comm)) {+ vlog(+ `adoptRunningEngine: refusing to adopt pid ${enginePid} (${comm}) — not the iii engine binary`,+ );+ return;+ }+ }if (enginePid && !existingPid) {writeEnginePidfile(enginePid);}@@ -2363,6 +2375,12 @@ async function runDemoBody(base: string) {sQuery.stop("Search complete");+ // Only claim the semantic-recall win when the search actually hit.+ // Without an embedding key this query returns 0 hits, and asserting+ // success over a visibly failed search reads as a lie.+ const semanticHits =+ results.find((r) => r.query === "database performance optimization")+ ?.hits ?? 0;const lines = [`Project: ${demoProject}`,`Sessions: ${sessions.length} seeded (${totalObs} observations)`,@@ -2373,8 +2391,16 @@ async function runDemoBody(base: string) {` ${c.dim("→")} ${c.ok(`${r.hits} hit(s)`)}, top: ${r.topTitle.slice(0, 60)}`,]),"",- c.accent(`Notice: searching "database performance optimization"`),- c.accent(`found the N+1 query fix — keyword matching can't do that.`),+ ...(semanticHits > 0+ ? [+ c.accent(`Notice: searching "database performance optimization"`),+ c.accent(`found the N+1 query fix — keyword matching can't do that.`),+ ]+ : [+ c.dim(`Note: "database performance optimization" found nothing —`),+ c.dim(`semantic recall needs an embedding provider key (e.g.`),+ c.dim(`OPENAI_API_KEY or GEMINI_API_KEY in ~/.agentmemory/.env).`),+ ]),"",`Viewer: ${c.url(getViewerUrl())}`,`Clean up with: ${c.dim(`curl -X DELETE "${base}/agentmemory/sessions?project=${demoProject}"`)}`,@@ -2542,6 +2568,40 @@ async function signalAndWait(return !pidAlive(pid);}+// Shared worker-reap: SIGTERM with a grace window sized for the worker's+// shutdown flush (index snapshots land via the engine, so the worker must+// die before the engine does, with time to commit).+async function stopWorkerPid(pid: number, graceMs: number): Promise<boolean> {+ const s = p.spinner();+ s.start(`Stopping agentmemory worker (pid ${pid})... [flushing state]`);+ const ok = await signalAndWait(pid, "SIGTERM", graceMs);+ s.stop(ok ? `Stopped worker pid ${pid}` : `Failed to stop worker pid ${pid}`);+ return ok;+}++function pidCommand(pid: number): string {+ if (IS_WINDOWS) return "";+ try {+ return execFileSync("ps", ["-p", String(pid), "-o", "comm="], {+ encoding: "utf-8",+ stdio: ["ignore", "pipe", "ignore"],+ }).trim();+ } catch {+ return "";+ }+}++// Positive identity beats a denylist: the engine is always the `iii`+// binary (spawned from PATH or ~/.agentmemory/bin), so anything else+// holding the port — Docker's proxy, an ssh forward, a stray dev+// server — must not be adopted or signaled. A denylist of known VM+// stacks failed open for every name it didn't know.+function isForeignPortHolder(comm: string): boolean {+ if (!comm) return false;+ const base = comm.split("/").pop() || comm;+ return base !== "iii" && !base.startsWith("iii-");+}+function findEnginePidsByPort(port: number): number[] {if (IS_WINDOWS) return [];const lsof = whichBinary("lsof");@@ -2581,15 +2641,52 @@ async function stopDockerEngine(composeFile: string, port: number): Promise<void);process.exit(1);}- const ok = runCommand(dockerBin, ["compose", "-f", composeFile, "down"], {- label: `docker compose -f ${composeFile} down`,- });- clearEnginePidfile();- clearEngineState();- clearWorkerPidfile();- if (!ok) {++ // Reap the native worker first so its shutdown flush (BM25/vector+ // snapshots via iii state::set) lands while the engine is still up —+ // same ordering as the native stop path. Previously the worker pidfile+ // was cleared without ever signaling the process, leaking a worker on+ // every Docker-mode stop.+ const workerPid = readWorkerPidfile();+ let workerStopped = true;+ if (workerPid) {+ workerStopped = await stopWorkerPid(workerPid, 5000);+ }++ // Scope teardown to agentmemory's own services. A bare `down` against a+ // user-owned compose file tears down every service in it. `rm -s -f`+ // stops and removes only the named containers.+ let composeText = "";+ try {+ composeText = readFileSync(composeFile, "utf-8");+ } catch {+ composeText = "";+ }+ const ownServices = ["iii-engine", "iii-init"].filter((svc) =>+ new RegExp(`^\\s+${svc}:`, "m").test(composeText),+ );+ if (ownServices.length === 0) {+ p.log.error(+ `${composeFile} does not define the agentmemory services (iii-engine/iii-init). Refusing to run an unscoped \`docker compose down\` against it — that would tear down every service in the file.\n\nStop the engine service manually:\n docker compose -f ${composeFile} stop <service>`,+ );+ process.exit(1);+ }+ const ok = runCommand(+ dockerBin,+ ["compose", "-f", composeFile, "rm", "-s", "-f", ...ownServices],+ {+ label: `docker compose -f ${composeFile} rm -s -f ${ownServices.join(" ")}`,+ },+ );+ // Clear each piece of state only after its shutdown succeeded, so a+ // failed stop stays retryable.+ if (workerStopped) clearWorkerPidfile();+ if (ok) {+ clearEnginePidfile();+ clearEngineState();+ } else {p.log.error(- `docker compose down failed. The engine may still be running on :${port}. Inspect with:\n docker compose -f ${composeFile} ps`,+ `docker compose rm failed. The engine may still be running on :${port}. Inspect with:\n docker compose -f ${composeFile} ps`,);process.exit(1);}@@ -2704,14 +2801,19 @@ async function runStop(): Promise<void> {// persists. Worker SIGTERM grace bumped 3s -> 5s to give a large// index a real chance to commit before the engine goes away.for (const pid of workerCandidates) {- const s = p.spinner();- s.start(`Stopping agentmemory worker (pid ${pid})... [flushing state]`);- const ok = await signalAndWait(pid, "SIGTERM", 5000);- s.stop(ok ? `Stopped worker pid ${pid}` : `Failed to stop worker pid ${pid}`);- if (!ok) allStopped = false;+ if (!(await stopWorkerPid(pid, 5000))) allStopped = false;}+ const skippedForeign: Array<{ pid: number; comm: string }> = [];for (const pid of candidates) {if (workerCandidates.has(pid)) continue;+ // Last-line guard against a stale/poisoned pidfile or a Docker+ // port-forward holding :port — signaling com.docker.backend kills+ // Docker Desktop's whole backend.+ const comm = pidCommand(pid);+ if (!force && isForeignPortHolder(comm)) {+ skippedForeign.push({ pid, comm });+ continue;+ }const s = p.spinner();s.start(`Stopping iii-engine (pid ${pid})...`);const ok = await signalAndWait(pid, "SIGTERM", 3000);@@ -2722,6 +2824,15 @@ async function runStop(): Promise<void> {clearEnginePidfile();clearEngineState();clearWorkerPidfile();+ if (skippedForeign.length > 0) {+ const list = skippedForeign+ .map((sf) => ` pid ${sf.pid} ${sf.comm}`)+ .join("\n");+ p.log.error(+ `Refused to signal process(es) holding :${port} that are not the iii engine:\n${list}\n\nIf the engine runs in Docker, stop it there:\n docker compose ps && docker compose rm -s -f <service>\n\nOr re-run with --force to signal them anyway.`,+ );+ process.exit(1);+ }if (!allStopped) {p.log.error("One or more processes survived SIGKILL. Investigate with `ps`.");process.exit(1);diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.tsindex 3dbc1882..d0290f85 100644--- a/src/cli/connect/codex.ts+++ b/src/cli/connect/codex.ts@@ -169,8 +169,11 @@ function installCodexHooks(opts: ConnectOptions): ConnectResult {writeJsonAtomic(CODEX_HOOKS, merged);logInstalled("Codex hooks (workaround for openai/codex#16430)", CODEX_HOOKS);+ p.log.warn(+ "Codex runs only trusted hooks: launch `codex` (the TUI) once and choose \"Trust all and continue\" at the \"Hooks need review\" prompt. `codex exec` never shows the prompt, so hooks stay inert until then.",+ );p.log.info(- "User-scope hooks reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect codex --with-hooks` after upgrading agentmemory to refresh them.",+ "User-scope hooks reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect codex --with-hooks` after upgrading agentmemory to refresh them, then re-approve in the TUI.",);return {diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.tsnew file mode 100644index 00000000..4f2979fa--- /dev/null+++ b/src/cli/connect/dsh.ts@@ -0,0 +1,148 @@+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import * as p from "@clack/prompts";+import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";+import {+ backupFile,+ logAlreadyWired,+ logBackup,+ logInstalled,+ readJsonSafe,+ writeJsonAtomic,+ writeTextAtomic,+} from "./util.js";+import {+ buildMergedHooks,+ findPluginRoot,+ type HookManifest,+} from "./codex-hooks.js";++// Rows land in the home-level cordis.patch.yml, the patch layer every+// Harness profile loads; the hooks row reuses the bundled Claude Code+// hook scripts through Harness's own bridge plugin.++function dshHome(): string {+ return process.env["DSH_HOME"] || join(homedir(), ".dsh");+}++// Harness env values are literal strings; no ${VAR:-default} interpolation.+const MCP_BLOCK = `- insert:+ - id: agentmemory+ name: '@deepseek-ai/dsh-mcp-client'+ config:+ transport: stdio+ serverName: agentmemory+ command: npx+ args: ['-y', '@agentmemory/mcp']+ env:+ AGENTMEMORY_URL: http://localhost:3111+`;++const MCP_MARKER = "serverName: agentmemory";+const HOOKS_MARKER = "id: agentmemory-hooks";++function hooksBlock(hooksConfigPath: string): string {+ return `- insert:+ - id: agentmemory-hooks+ name: '@deepseek-ai/dsh-hooks-claude-code'+ config:+ configPath: ${JSON.stringify(hooksConfigPath)}+`;+}++// Drop the managed top-level block containing `marker`.+function stripBlock(content: string, marker: string): string {+ if (!content.includes(marker)) return content;+ const lines = content.split("\n");+ const markerIdx = lines.findIndex((l) => l.includes(marker));+ let start = markerIdx;+ while (start > 0 && !lines[start].startsWith("- ")) start--;+ let end = markerIdx + 1;+ while (end < lines.length && !lines[end].startsWith("- ")) end++;+ return lines+ .slice(0, start)+ .concat(lines.slice(end))+ .join("\n")+ .replace(/\n+$/, "\n");+}++function appendBlock(content: string, block: string): string {+ const base = content.replace(/\n+$/, "\n");+ return base.trim() ? `${base}\n${block}` : block;+}++function installHooksFile(home: string): string {+ const hooksPath = join(home, "agentmemory.hooks.json");+ const pluginRoot = findPluginRoot();+ const existing = readJsonSafe<HookManifest>(hooksPath);+ const merged = buildMergedHooks(existing, pluginRoot, "hooks.codex.json");+ writeJsonAtomic(hooksPath, merged);+ return hooksPath;+}++export const adapter: ConnectAdapter = {+ name: "dsh",+ displayName: "DeepSeek Harness",+ docs: "https://github.com/rohitg00/agentmemory#other-agents",+ protocolNote:+ "→ Using MCP via $DSH_HOME/cordis.patch.yml (the home-level patch layer every profile loads). Tools appear as mcp__agentmemory__*. Pass --with-hooks to also wire auto-capture through Harness's Claude Code hook bridge.",+ category: "native",+ detect(): boolean {+ return existsSync(dshHome());+ },+ async install(opts: ConnectOptions): Promise<ConnectResult> {+ const home = dshHome();+ const configPath = join(home, "cordis.patch.yml");+ const existing = existsSync(configPath)+ ? readFileSync(configPath, "utf-8")+ : "";++ const wantHooks = opts.withHooks === true;+ const hasMcp = existing.includes(MCP_MARKER);+ const hasHooks = existing.includes(HOOKS_MARKER);++ if (hasMcp && (!wantHooks || hasHooks) && !opts.force) {+ logAlreadyWired(this.displayName, configPath);+ return { kind: "already-wired", mutatedPath: configPath };+ }++ if (opts.dryRun) {+ p.log.info(+ `[dry-run] Would append the agentmemory mcp-client row${wantHooks ? " and the hooks-claude-code row" : ""} to ${configPath}`,+ );+ return { kind: "installed", mutatedPath: configPath };+ }++ let backupPath: string | undefined;+ if (existsSync(configPath)) {+ backupPath = backupFile(configPath, this.name, "yml");+ logBackup(backupPath);+ } else {+ mkdirSync(dirname(configPath), { recursive: true });+ }++ let next = stripBlock(existing, MCP_MARKER);+ next = appendBlock(next, MCP_BLOCK);++ if (wantHooks) {+ const hooksPath = installHooksFile(home);+ next = stripBlock(next, HOOKS_MARKER);+ next = appendBlock(next, hooksBlock(hooksPath));+ p.log.info(`Hook manifest: ${hooksPath}`);+ }++ writeTextAtomic(configPath, next);++ const written = readFileSync(configPath, "utf-8");+ if (!written.includes(MCP_MARKER) || (wantHooks && !written.includes(HOOKS_MARKER))) {+ p.log.error(+ `Verification failed: ${configPath} did not contain the agentmemory rows after write.`,+ );+ return { kind: "skipped", reason: "verification-failed" };+ }++ logInstalled(this.displayName, configPath);+ return { kind: "installed", mutatedPath: configPath, backupPath };+ },+};diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.tsindex a0256c7a..c2c5edec 100644--- a/src/cli/connect/index.ts+++ b/src/cli/connect/index.ts@@ -12,6 +12,7 @@ import { adapter as codex } from "./codex.js";import { adapter as continueDev } from "./continue.js";import { adapter as cursor } from "./cursor.js";import { adapter as droid } from "./droid.js";+import { adapter as dsh } from "./dsh.js";import { adapter as geminiCli } from "./gemini-cli.js";import { adapter as hermes } from "./hermes.js";import { adapter as kiro } from "./kiro.js";@@ -38,6 +39,7 @@ export const ADAPTERS: readonly ConnectAdapter[] = [continueDev,zed,droid,+ dsh,opencode,openclaw,hermes,diff --git a/src/cli/connect/pi.ts b/src/cli/connect/pi.tsindex 3056d31d..63c06491 100644--- a/src/cli/connect/pi.ts+++ b/src/cli/connect/pi.ts@@ -1,12 +1,36 @@-import { existsSync } from "node:fs";+import { existsSync, mkdirSync, readFileSync } from "node:fs";import { homedir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import * as p from "@clack/prompts";import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";+import { findPluginRoot } from "./codex-hooks.js";+import {+ backupFile,+ logAlreadyWired,+ logBackup,+ logInstalled,+ writeTextAtomic,+} from "./util.js";++// pi auto-discovers ~/.pi/agent/extensions/*/index.ts, so installing is a+// copy of the bundled extension; no settings.json edit.const PI_DIR = join(homedir(), ".pi");const PI_EXT_DIR = join(PI_DIR, "agent", "extensions", "agentmemory");const DOCS = "https://github.com/rohitg00/agentmemory/tree/main/integrations/pi";+const EXT_FILES = ["index.ts", "security.ts"] as const;++function findPiSourceDir(): string | null {+ let packageRoot: string;+ try {+ packageRoot = dirname(findPluginRoot());+ } catch {+ return null;+ }+ const dir = join(packageRoot, "integrations", "pi");+ const complete = EXT_FILES.every((f) => existsSync(join(dir, f)));+ return complete ? dir : null;+}export const adapter: ConnectAdapter = {name: "pi",@@ -14,34 +38,67 @@ export const adapter: ConnectAdapter = {category: "native",docs: DOCS,protocolNote:- "→ Using native hooks (REST API at :3111). MCP not required.",+ "→ Using native lifecycle hooks against the REST API at :3111 (recall on agent start, capture on agent end, memory tools). MCP not required.",detect(): boolean {return existsSync(PI_DIR);},- async install(_opts: ConnectOptions): Promise<ConnectResult> {- p.log.warn(- "pi uses a TypeScript extension file. Automated copy + register isn't implemented yet — manual install required.",+ async install(opts: ConnectOptions): Promise<ConnectResult> {+ const sourceDir = findPiSourceDir();+ if (!sourceDir) {+ p.log.error(+ "Bundled pi extension not found (integrations/pi missing from the install) — reinstall agentmemory.",+ );+ return { kind: "skipped", reason: "bundled-extension-missing" };+ }+ const sources = EXT_FILES.map((f) => ({+ name: f,+ content: readFileSync(join(sourceDir, f), "utf-8"),+ target: join(PI_EXT_DIR, f),+ }));++ const upToDate = sources.every(+ (s) => existsSync(s.target) && readFileSync(s.target, "utf-8") === s.content,);- p.note(- [- "Run these from the agentmemory repo root:",- "",- ` mkdir -p ${PI_EXT_DIR}`,- ` cp integrations/pi/index.ts ${PI_EXT_DIR}/index.ts`,- ` cp integrations/pi/security.ts ${PI_EXT_DIR}/security.ts`,- "",- "Then add to ~/.pi/agent/settings.json:",- ' { "extensions": ["~/.pi/agent/extensions/agentmemory"] }',- "",- `Full guide: ${DOCS}`,- ].join("\n"),- "pi manual install",+ if (upToDate && !opts.force) {+ logAlreadyWired(this.displayName, PI_EXT_DIR);+ return { kind: "already-wired", mutatedPath: PI_EXT_DIR };+ }++ if (opts.dryRun) {+ p.log.info(+ `[dry-run] Would install the pi extension (${EXT_FILES.join(", ")}) into ${PI_EXT_DIR}`,+ );+ return { kind: "installed", mutatedPath: PI_EXT_DIR };+ }++ let backupPath: string | undefined;+ for (const s of sources) {+ if (existsSync(s.target) && readFileSync(s.target, "utf-8") !== s.content) {+ const backup = backupFile(s.target, `${this.name}-${s.name.replace(/\.ts$/, "")}`, "ts");+ logBackup(backup);+ backupPath ??= backup;+ }+ }++ mkdirSync(PI_EXT_DIR, { recursive: true });+ for (const s of sources) {+ writeTextAtomic(s.target, s.content);+ }++ const verified = sources.every(+ (s) => existsSync(s.target) && readFileSync(s.target, "utf-8") === s.content,+ );+ if (!verified) {+ p.log.error(`Verification failed: ${PI_EXT_DIR} does not match the bundled extension.`);+ return { kind: "skipped", reason: "verification-failed" };+ }++ logInstalled(this.displayName, PI_EXT_DIR);+ p.log.info(+ "pi auto-discovers the extension on next launch; a running pi picks it up with /reload. Verify with /agentmemory-status.",);- return {- kind: "stub",- reason: "ts-extension-copy-not-implemented",- };+ return { kind: "installed", mutatedPath: PI_EXT_DIR, backupPath };},};diff --git a/src/cli/connect/types.ts b/src/cli/connect/types.tsindex 7266cf60..eedd76f5 100644--- a/src/cli/connect/types.ts+++ b/src/cli/connect/types.ts@@ -5,8 +5,10 @@ export type ConnectOptions = {* When true, adapters that ship a native hook config alongside MCP* additionally write it: Codex (`~/.codex/hooks.json`, workaround for* openai/codex#16430), Claude Code (`~/.claude/settings.json`, workaround- * for #508), and Droid (`~/.factory/hooks.json`, its native hooks- * config). No-op for adapters without a hooks installer.+ * for #508), Droid (`~/.factory/hooks.json`, its native hooks config),+ * and DeepSeek Harness (`$DSH_HOME/agentmemory.hooks.json` plus a+ * hooks-claude-code patch row). No-op for adapters without a hooks+ * installer.*/withHooks?: boolean;/**diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.tsindex 580cd4ee..c47b7f40 100644--- a/src/cli/connect/util.ts+++ b/src/cli/connect/util.ts@@ -90,9 +90,13 @@ export function readJsonSafe<T = unknown>(path: string): T | null {}export function writeJsonAtomic(path: string, value: unknown): void {+ writeTextAtomic(path, `${JSON.stringify(value, null, 2)}\n`);+}++export function writeTextAtomic(path: string, content: string): void {mkdirSync(dirname(path), { recursive: true });const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf-8");+ writeFileSync(tmp, content, "utf-8");renameSync(tmp, path);}diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.tsindex 6d049355..926cdbea 100644--- a/src/cli/onboarding.ts+++ b/src/cli/onboarding.ts@@ -53,7 +53,7 @@ const PROVIDERS: { value: string; label: string; envKey: string | null }[] = [{ value: "openai", label: "OpenAI — gpt", envKey: "OPENAI_API_KEY" },{ value: "gemini", label: "Google — gemini", envKey: "GEMINI_API_KEY" },{ value: "openrouter", label: "OpenRouter — multi-model", envKey: "OPENROUTER_API_KEY" },- { value: "minimax", label: "MiniMax — minimax-m1", envKey: "MINIMAX_API_KEY" },+ { value: "minimax", label: "MiniMax — MiniMax-M3", envKey: "MINIMAX_API_KEY" },{ value: "skip", label: "Skip — BM25-only mode (no LLM key)", envKey: null },];diff --git a/src/config.ts b/src/config.tsindex d27c39e4..426ca20c 100644--- a/src/config.ts+++ b/src/config.ts@@ -90,7 +90,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {if (hasRealValue(env["OPENAI_API_KEY"]) && env["OPENAI_API_KEY_FOR_LLM"] !== "false") {return {provider: "openai",- model: env["OPENAI_MODEL"] || "gpt-4o-mini",+ model: env["OPENAI_MODEL"] || "gpt-5.6-luna",maxTokens,baseURL: env["OPENAI_BASE_URL"],};@@ -100,7 +100,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {if (hasRealValue(env["MINIMAX_API_KEY"])) {return {provider: "minimax",- model: env["MINIMAX_MODEL"] || "MiniMax-M2.7",+ model: env["MINIMAX_MODEL"] || "MiniMax-M3",maxTokens,};}@@ -108,7 +108,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {if (hasRealValue(env["ANTHROPIC_API_KEY"])) {return {provider: "anthropic",- model: env["ANTHROPIC_MODEL"] || "claude-sonnet-4-20250514",+ model: env["ANTHROPIC_MODEL"] || "claude-sonnet-5",maxTokens,baseURL: env["ANTHROPIC_BASE_URL"],};@@ -122,13 +122,12 @@ function detectProvider(env: Record<string, string>): ProviderConfig {}return {provider: "gemini",- model: env["GEMINI_MODEL"] || "gemini-2.5-flash",+ model: env["GEMINI_MODEL"] || "gemini-3.7-flash",maxTokens,};}if (hasRealValue(env["OPENROUTER_API_KEY"])) {- const model =- env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514";+ const model = env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-5";// warn when the configured OpenRouter model is in the// premium tier and likely to burn money on background compression.// Captured workload data shows ~$5/35h on claude-sonnet-4 vs@@ -136,7 +135,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {// Heuristic match avoids hard-coding a pricing table.if (!warnPremiumModelShown &&- /sonnet|opus|gpt-4o(?!.*mini)|gpt-4-turbo/i.test(model) &&+ /sonnet|opus|gpt-5\.\d+-sol|gpt-4o(?!.*mini)|gpt-4-turbo/i.test(model) &&env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "1" &&env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "true") {@@ -145,7 +144,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {`[agentmemory] OPENROUTER_MODEL=${model} is in the premium tier. ` +`Background compression on this model can cost $5+/day under active use. ` +`Cheaper alternatives with comparable quality for memory compression: ` +- `deepseek/deepseek-v4-pro, deepseek/deepseek-chat, qwen/qwen3-coder. ` ++ `deepseek/deepseek-v4-flash-0731, deepseek/deepseek-v4-pro, qwen/qwen3-coder. ` +`See README "Cost-aware model selection" for the full table. ` +`Set AGENTMEMORY_SUPPRESS_COST_WARNING=1 to silence.\n`,);@@ -181,7 +180,7 @@ function detectProvider(env: Record<string, string>): ProviderConfig {);return {provider: "agent-sdk",- model: "claude-sonnet-4-20250514",+ model: "claude-sonnet-5",maxTokens,};}diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.tsindex 28d17e97..14f757ce 100644--- a/src/functions/compress-synthetic.ts+++ b/src/functions/compress-synthetic.ts@@ -102,5 +102,6 @@ export function buildSyntheticCompression(if (raw.modality) result.modality = raw.modality;if (raw.imageData) result.imageData = raw.imageData;if (raw.agentId) result.agentId = raw.agentId;+ if (raw.origin) result.origin = raw.origin;return result;}diff --git a/src/functions/compress.ts b/src/functions/compress.tsindex 0569555e..c2019e7d 100644--- a/src/functions/compress.ts+++ b/src/functions/compress.ts@@ -166,6 +166,7 @@ export function registerCompressFunction(...(imageDescription ? { imageDescription } : {}),...(data.raw.imageData ? { imageRef: data.raw.imageData } : {}),...(data.raw.agentId ? { agentId: data.raw.agentId } : {}),+ ...(data.raw.origin ? { origin: data.raw.origin } : {}),};await kv.set(diff --git a/src/functions/export-import.ts b/src/functions/export-import.tsindex 23854a97..7bdabf61 100644--- a/src/functions/export-import.ts+++ b/src/functions/export-import.ts@@ -24,6 +24,7 @@ import type {ExportPagination,AccessLogExport,} from "../types.js";+import { importOrigin } from "../types.js";import { normalizeAccessLog } from "./access-tracker.js";import { KV } from "../state/schema.js";import { checkPayloadFrameSize } from "../state/frame-guard.js";@@ -31,6 +32,7 @@ import { StateKV } from "../state/kv.js";import { VERSION } from "../version.js";import { recordAudit } from "./audit.js";import { indexRecords } from "./search.js";+import { resetLessonIndex } from "./lessons.js";import { logger } from "../logger.js";// Bounded-concurrency chunk size for the import delete/write loops. A@@ -365,6 +367,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {await kv.list<Lesson>(KV.lessons).catch(() => []),(l) => kv.delete(KV.lessons, l.id),);+ resetLessonIndex();await runChunked(await kv.list<Insight>(KV.insights).catch(() => []),(i) => kv.delete(KV.insights, i.id),@@ -428,6 +431,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {return;}}+ o.origin = importOrigin(o.origin, o.timestamp);await kv.set(KV.observations(sessionId), o.id, o);stats.observations++;indexObs.push(o);@@ -448,6 +452,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {if (!Array.isArray(memory.sessionIds)) {memory.sessionIds = [];}+ memory.origin = importOrigin(memory.origin, memory.createdAt);await kv.set(KV.memories, memory.id, memory);stats.memories++;indexMems.push(memory);@@ -607,6 +612,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {}await kv.set(KV.lessons, lesson.id, lesson);});+ resetLessonIndex();}if (importData.insights) {await runChunked(importData.insights, async (insight) => {diff --git a/src/functions/graph.ts b/src/functions/graph.tsindex 86332a30..76340d60 100644--- a/src/functions/graph.ts+++ b/src/functions/graph.ts@@ -13,6 +13,7 @@ import {GRAPH_EXTRACTION_SYSTEM,buildGraphExtractionPrompt,} from "../prompts/graph-extraction.js";+import { isGraphExtractionEnabled } from "../config.js";import { recordAudit } from "./audit.js";import { logger } from "../logger.js";@@ -450,6 +451,92 @@ function parseGraphXml(return { nodes, edges };}+const HEURISTIC_EDGE_WEIGHT = 0.4;+const MAX_HEURISTIC_EDGES_PER_OBS = 12;++export function extractGraphHeuristics(+ observations: CompressedObservation[],+): { nodes: GraphNode[]; edges: GraphEdge[] } {+ const now = new Date().toISOString();+ const nodes: GraphNode[] = [];+ const nodeByKey = new Map<string, GraphNode>();+ const edges: GraphEdge[] = [];+ const edgeByPair = new Map<string, GraphEdge>();++ const nodeFor = (+ type: GraphNode["type"],+ name: string,+ obsId: string,+ ): GraphNode | null => {+ const trimmed = name.trim();+ if (!trimmed) return null;+ const key = `${type} ${trimmed.toLowerCase()}`;+ let node = nodeByKey.get(key);+ if (!node) {+ node = {+ id: generateId("gn"),+ type,+ name: trimmed,+ properties: {},+ sourceObservationIds: [obsId],+ createdAt: now,+ };+ nodeByKey.set(key, node);+ nodes.push(node);+ } else if (!node.sourceObservationIds.includes(obsId)) {+ node.sourceObservationIds.push(obsId);+ }+ return node;+ };++ for (const obs of observations) {+ let budget = MAX_HEURISTIC_EDGES_PER_OBS;+ const link = (a: GraphNode | null, b: GraphNode | null): void => {+ if (!a || !b || a.id === b.id) return;+ const pair = a.id < b.id ? `${a.id}|${b.id}` : `${b.id}|${a.id}`;+ const existing = edgeByPair.get(pair);+ if (existing) {+ if (!existing.sourceObservationIds.includes(obs.id)) {+ existing.sourceObservationIds.push(obs.id);+ }+ return;+ }+ if (budget <= 0) return;+ budget -= 1;+ const edge: GraphEdge = {+ id: generateId("ge"),+ type: "related_to",+ sourceNodeId: a.id,+ targetNodeId: b.id,+ weight: HEURISTIC_EDGE_WEIGHT,+ sourceObservationIds: [obs.id],+ createdAt: now,+ };+ edgeByPair.set(pair, edge);+ edges.push(edge);+ };++ const fileNodes = (obs.files ?? []).map((f) =>+ nodeFor("file", f, obs.id),+ );+ const conceptNodes = (obs.concepts ?? []).map((c) =>+ nodeFor("concept", c, obs.id),+ );++ for (const concept of conceptNodes) {+ for (const file of fileNodes) link(concept, file);+ }+ for (let i = 0; i + 1 < conceptNodes.length; i++) {+ link(conceptNodes[i], conceptNodes[i + 1]);+ }+ for (let i = 0; i + 1 < fileNodes.length; i++) {+ link(fileNodes[i], fileNodes[i + 1]);+ }+ }++ return { nodes, edges };+}+// Shared persistence for a batch of extracted/imported nodes and edges.// Factored out of mem::graph-extract so structural importers (graphify)// reuse the exact same name-index upsert, degree bookkeeping, and snapshot@@ -597,31 +684,60 @@ export function registerGraphFunction(kv: StateKV,provider: MemoryProvider,): void {- sdk.registerFunction("mem::graph-extract",+ sdk.registerFunction("mem::graph-extract",async (data: { observations: CompressedObservation[] }) => {if (!data.observations || data.observations.length === 0) {return { success: false, error: "No observations provided" };}- const prompt = buildGraphExtractionPrompt(- data.observations.map((o) => ({- title: o.title,- narrative: o.narrative,- concepts: o.concepts,- files: o.files,- type: o.type,- })),- );+ const obsIds = data.observations.map((o) => o.id);+ let nodes: GraphNode[] = [];+ let edges: GraphEdge[] = [];try {- const response = await provider.compress(- GRAPH_EXTRACTION_SYSTEM,- prompt,+ const heuristic = extractGraphHeuristics(data.observations);+ nodes = heuristic.nodes;+ edges = heuristic.edges;+ } catch (err) {+ logger.warn("heuristic graph extraction failed", {+ error: err instanceof Error ? err.message : String(err),+ });+ }++ const llmEnabled =+ isGraphExtractionEnabled() && !provider.name.includes("noop");+ let llmError: string | undefined;+ if (llmEnabled) {+ const prompt = buildGraphExtractionPrompt(+ data.observations.map((o) => ({+ title: o.title,+ narrative: o.narrative,+ concepts: o.concepts,+ files: o.files,+ type: o.type,+ })),);+ try {+ const response = await provider.compress(+ GRAPH_EXTRACTION_SYSTEM,+ prompt,+ );+ const parsed = parseGraphXml(response, obsIds);+ nodes = nodes.concat(parsed.nodes);+ edges = edges.concat(parsed.edges);+ } catch (err) {+ llmError = err instanceof Error ? err.message : String(err);+ logger.error("LLM graph extraction failed", { error: llmError });+ }+ }- const obsIds = data.observations.map((o) => o.id);- const { nodes, edges } = parseGraphXml(response, obsIds);+ if (nodes.length === 0 && edges.length === 0) {+ return llmError+ ? { success: false, error: llmError }+ : { success: true, nodesAdded: 0, edgesAdded: 0 };+ }+ try {const { newNodeCount, newEdgeCount } = await persistGraphDelta(kv,nodes,@@ -639,6 +755,7 @@ export function registerGraphFunction(edges: edges.length,newNodes: newNodeCount,newEdges: newEdgeCount,+ llm: llmEnabled && !llmError,});return {success: true,diff --git a/src/functions/lessons.ts b/src/functions/lessons.tsindex 0314298c..d0a4a21e 100644--- a/src/functions/lessons.ts+++ b/src/functions/lessons.ts@@ -2,8 +2,56 @@ import type { ISdk } from "iii-sdk";import type { StateKV } from "../state/kv.js";import { KV, fingerprintId } from "../state/schema.js";import type { Lesson } from "../types.js";+import { SearchIndex } from "../state/search-index.js";+import { lessonToObservation } from "../state/memory-utils.js";import { recordAudit } from "./audit.js";+// Dedicated BM25 index for lessons, with the full records cached+// alongside it. Recall previously listed every lesson from KV and+// substring-matched per query — O(corpus) per call with no term+// weighting. Index and record cache are built lazily from one KV list+// (the same cost a single recall used to pay) and kept current+// incrementally on save/delete/decay. Confidence x recency reranking+// stays exactly as before — the index only replaces the relevance term,+// and the record cache keeps recall at zero KV round-trips.+let lessonIndex: SearchIndex | null = null;+const lessonRecords = new Map<string, Lesson>();+let lessonIndexBuild: Promise<void> | null = null;+let lessonIndexGeneration = 0;++export function resetLessonIndex(): void {+ lessonIndexGeneration++;+ lessonIndex = null;+ lessonRecords.clear();+}++function noteLessonMutation(): void {+ if (!lessonIndex && lessonIndexBuild) resetLessonIndex();+}++async function ensureLessonIndex(kv: StateKV): Promise<SearchIndex> {+ if (lessonIndex) return lessonIndex;+ if (!lessonIndexBuild) {+ const generation = lessonIndexGeneration;+ lessonIndexBuild = (async () => {+ const idx = new SearchIndex();+ const all = await kv.list<Lesson>(KV.lessons);+ if (generation !== lessonIndexGeneration) return;+ for (const l of all) {+ if (!l.deleted) {+ idx.add(lessonToObservation(l));+ lessonRecords.set(l.id, l);+ }+ }+ lessonIndex = idx;+ })().finally(() => {+ lessonIndexBuild = null;+ });+ }+ await lessonIndexBuild;+ return lessonIndex ?? ensureLessonIndex(kv);+}+function reinforceLesson(lesson: Lesson): void {const now = new Date().toISOString();lesson.reinforcements++;@@ -35,10 +83,18 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {if (existing && !existing.deleted) {reinforceLesson(existing);+ let indexedTextChanged = false;if (data.context && !existing.context) {existing.context = data.context;+ indexedTextChanged = true;}await kv.set(KV.lessons, existing.id, existing);+ lessonRecords.set(existing.id, existing);+ if (indexedTextChanged && lessonIndex) {+ lessonIndex.remove(existing.id);+ lessonIndex.add(lessonToObservation(existing));+ }+ noteLessonMutation();try {await recordAudit(kv, "lesson_strengthen", "mem::lesson-save", [@@ -77,6 +133,9 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {};await kv.set(KV.lessons, lesson.id, lesson);+ lessonRecords.set(lesson.id, lesson);+ if (lessonIndex) lessonIndex.add(lessonToObservation(lesson));+ noteLessonMutation();try {await recordAudit(kv, "lesson_save", "mem::lesson-save", [lesson.id]);@@ -97,41 +156,38 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {return { success: false, error: "query is required" };}- const query = data.query.toLowerCase();const minConfidence = data.minConfidence ?? 0.1;const limit = data.limit ?? 10;- let lessons = await kv.list<Lesson>(KV.lessons);-- lessons = lessons.filter(- (l) => !l.deleted && l.confidence >= minConfidence,- );-- if (data.project) {- lessons = lessons.filter((l) => l.project === data.project);+ const idx = await ensureLessonIndex(kv);+ const filtering = !!data.project || minConfidence > 0.1;+ const fetchLimit = filtering+ ? Math.max(limit * 10, 100)+ : Math.max(limit * 5, 50);+ const hits = idx.search(data.query, fetchLimit);+ const maxHit = hits.length > 0 ? hits[0].score : 0;++ const scored: Array<{ lesson: Lesson; score: number }> = [];+ for (let i = 0; i < hits.length; i++) {+ const l = lessonRecords.get(hits[i].obsId);+ if (!l || l.deleted || l.confidence < minConfidence) continue;+ if (data.project && l.project !== data.project) continue;++ const relevance = maxHit > 0 ? hits[i].score / maxHit : 0;+ const daysSinceReinforced = l.lastReinforcedAt+ ? (Date.now() - new Date(l.lastReinforcedAt).getTime()) /+ (1000 * 60 * 60 * 24)+ : (Date.now() - new Date(l.createdAt).getTime()) /+ (1000 * 60 * 60 * 24);+ const recencyBoost = 1 / (1 + daysSinceReinforced * 0.01);+ scored.push({ lesson: l, score: l.confidence * relevance * recencyBoost });}- const scored = lessons- .map((l) => {- const text = `${l.content} ${l.context} ${l.tags.join(" ")}`.toLowerCase();- const terms = query.split(/\s+/).filter((t) => t.length > 1);- const matchCount = terms.filter((t) => text.includes(t)).length;- if (matchCount === 0) return null;-- const relevance = matchCount / terms.length;- const daysSinceReinforced = l.lastReinforcedAt- ? (Date.now() - new Date(l.lastReinforcedAt).getTime()) /- (1000 * 60 * 60 * 24)- : (Date.now() - new Date(l.createdAt).getTime()) /- (1000 * 60 * 60 * 24);- const recencyBoost = 1 / (1 + daysSinceReinforced * 0.01);- const score = l.confidence * relevance * recencyBoost;-- return { lesson: l, score };- })- .filter(Boolean) as Array<{ lesson: Lesson; score: number }>;-- scored.sort((a, b) => b.score - a.score);+ scored.sort(+ (a, b) =>+ b.score - a.score ||+ (a.lesson.id < b.lesson.id ? -1 : a.lesson.id > b.lesson.id ? 1 : 0),+ );try {await recordAudit(kv, "lesson_recall", "mem::lesson-recall", [], {@@ -192,6 +248,8 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {reinforceLesson(lesson);await kv.set(KV.lessons, lesson.id, lesson);+ lessonRecords.set(lesson.id, lesson);+ noteLessonMutation();try {await recordAudit(kv, "lesson_strengthen", "mem::lesson-strengthen", [@@ -218,6 +276,9 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {lesson.updatedAt = new Date().toISOString();await kv.set(KV.lessons, lesson.id, lesson);+ lessonRecords.delete(lesson.id);+ if (lessonIndex) lessonIndex.remove(lesson.id);+ noteLessonMutation();try {await recordAudit(kv, "lesson_delete", "mem::lesson-delete", [@@ -285,6 +346,15 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {}await Promise.all(dirty.map((l) => kv.set(KV.lessons, l.id, l)));+ for (const l of dirty) {+ if (l.deleted) {+ lessonRecords.delete(l.id);+ if (lessonIndex) lessonIndex.remove(l.id);+ } else {+ lessonRecords.set(l.id, l);+ }+ }+ if (dirty.length > 0) noteLessonMutation();await Promise.all(auditEvents.map((event) =>recordAudit(kv, "lesson_strengthen", "mem::lesson-decay-sweep", [event.id], {diff --git a/src/functions/observe.ts b/src/functions/observe.tsindex 8ad4ba0f..c1c9f499 100644--- a/src/functions/observe.ts+++ b/src/functions/observe.ts@@ -1,5 +1,7 @@import { TriggerAction, type ISdk } from "iii-sdk";-import type { RawObservation, HookPayload } from "../types.js";+import type { RawObservation, HookPayload, Origin } from "../types.js";++const TOOL_HOOKS = new Set(["pre_tool_use", "post_tool_use", "post_tool_failure"]);import { KV, STREAM, generateId } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { stripPrivateData } from "./privacy.js";@@ -63,15 +65,24 @@ export function registerObserveFunction(let dedupHash: string | undefined;if (dedupMap) {- const d =- typeof payload.data === "object" && payload.data !== null- ? (payload.data as Record<string, unknown>)- : {};+ const dataIsObject =+ typeof payload.data === "object" && payload.data !== null;+ const d = dataIsObject+ ? (payload.data as Record<string, unknown>)+ : {};const toolName = (d["tool_name"] as string) || payload.hookType;+ // Hash the full payload when tool_input is absent so distinct+ // events never collapse onto one key.+ const dedupInput =+ d["tool_input"] !== undefined+ ? d["tool_input"]+ : dataIsObject+ ? d+ : payload.data;dedupHash = dedupMap.computeHash(payload.sessionId,toolName,- d["tool_input"],+ dedupInput,);if (dedupMap.isDuplicate(dedupHash)) {return { deduplicated: true, sessionId: payload.sessionId };@@ -87,12 +98,19 @@ export function registerObserveFunction(sanitizedRaw = stripPrivateData(String(payload.data));}+ let originChannel: Origin["channel"] = "agent";+ if (payload.hookType === "prompt_submit") originChannel = "user";+ else if (TOOL_HOOKS.has(payload.hookType)) originChannel = "tool";const raw: RawObservation = {id: obsId,sessionId: payload.sessionId,timestamp: payload.timestamp,hookType: payload.hookType,raw: sanitizedRaw,+ origin: {+ channel: originChannel,+ capturedAt: payload.timestamp,+ },};let extractedImage: string | undefined;@@ -106,6 +124,7 @@ export function registerObserveFunction(raw.toolName = d["tool_name"] as string | undefined;raw.toolInput = d["tool_input"];raw.toolOutput = d["tool_output"] || d["error"];+ if (raw.origin && raw.toolName) raw.origin.detail = raw.toolName;}if (payload.hookType === "prompt_submit") {raw.userPrompt = d["prompt"] as string | undefined;diff --git a/src/functions/remember.ts b/src/functions/remember.tsindex 759fddb5..94222694 100644--- a/src/functions/remember.ts+++ b/src/functions/remember.ts@@ -6,7 +6,7 @@ import { withKeyedLock } from "../state/keyed-mutex.js";import { memoryToObservation } from "../state/memory-utils.js";import { deleteAccessLog } from "./access-tracker.js";import { recordAudit } from "./audit.js";-import { getSearchIndex, vectorIndexAddGuarded, vectorIndexRemove, flushIndexSave } from "./search.js";+import { getSearchIndex, isMemoryIndexReady, vectorIndexAddGuarded, vectorIndexRemove, flushIndexSave } from "./search.js";import { getAgentId } from "../config.js";import { logger } from "../logger.js";@@ -69,12 +69,51 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {: undefined;return withKeyedLock("mem:remember", async () => {- const existingMemories = await kv.list<Memory>(KV.memories);+ // Candidate generation: query the BM25 index with the new content+ // and Jaccard-compare only the top hits, instead of walking the+ // full memory corpus on every save. The index receives every+ // memory at save time and is rebuilt at boot, so it covers the+ // corpus whenever it is non-empty; a cold, never-queried index+ // falls back to the full scan so supersession never silently+ // stops working.+ const idx = getSearchIndex();+ let candidateMemories: Memory[];+ try {+ if (isMemoryIndexReady() && idx.size > 0) {+ // 50 hits, not 20: the shared index also holds observations,+ // which occupy slots but never resolve to memories below. A+ // >0.7-Jaccard duplicate shares most tokens with the query so+ // it ranks near the top regardless. Only mem_-prefixed ids can+ // resolve in KV.memories, so skip the guaranteed-miss lookups.+ const hits = idx+ .search(data.content, 50)+ .filter((h) => h.obsId.startsWith("mem_"));+ const loaded = await Promise.all(+ hits.map((h) =>+ kv.get<Memory>(KV.memories, h.obsId).catch(() => null),+ ),+ );+ candidateMemories = loaded.filter((m): m is Memory => m !== null);+ } else {+ candidateMemories = await kv.list<Memory>(KV.memories);+ }+ } catch (err) {+ // Candidate generation is an optimization; a failure here must+ // never block the save itself.+ logger.warn("supersession candidate lookup failed, using full scan", {+ error: err instanceof Error ? err.message : JSON.stringify(err),+ });+ candidateMemories = await kv.list<Memory>(KV.memories);+ }let supersededId: string | undefined;let supersededVersion = 1;let supersededMemory: Memory | undefined;+ // Track the closest sub-threshold match: not similar enough to+ // supersede, but similar enough that the caller may want to+ // consolidate. Reported back as a hint; never acted on here.+ let nearMatch: { id: string; title: string; similarity: number } | undefined;const lowerContent = data.content.toLowerCase();- for (const existing of existingMemories) {+ for (const existing of candidateMemories) {if (existing.isLatest === false) continue;// Never supersede a memory that belongs to a different project.// Both sides must have an explicit project for the guard to engage;@@ -93,6 +132,12 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {supersededMemory = existing;break;}+ if (+ similarity > 0.4 &&+ (!nearMatch || similarity > nearMatch.similarity)+ ) {+ nearMatch = { id: existing.id, title: existing.title, similarity };+ }}// stamp the agent role on the memory so future recall can@@ -122,6 +167,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {(id): id is string => typeof id === "string" && id.length > 0,),isLatest: true,+ origin: { channel: "agent", capturedAt: now },...(callAgentId ? { agentId: callAgentId } : {}),...(project !== undefined && { project }),};@@ -133,6 +179,14 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {if (supersededMemory) {supersededMemory.isLatest = false;await kv.set(KV.memories, supersededMemory.id, supersededMemory);+ // The superseded version stays in KV (the viewer's version+ // chain reads it there) but leaves both search indexes:+ // recall returning an outdated fact as if current is worse+ // than returning nothing.+ try {+ getSearchIndex().remove(supersededMemory.id);+ } catch {}+ vectorIndexRemove(supersededMemory.id);}await kv.set(KV.memories, memory.id, memory);@@ -171,7 +225,20 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {type: memory.type,project: memory.project,});- return { success: true, memory };+ // similarTo is advisory only: a close-but-not-superseding match+ // the caller may want to consolidate via memory_update/forget.+ return {+ success: true,+ memory,+ ...(nearMatch && !supersededId+ ? {+ similarTo: {+ ...nearMatch,+ similarity: Math.round(nearMatch.similarity * 100) / 100,+ },+ }+ : {}),+ };});},);diff --git a/src/functions/replay.ts b/src/functions/replay.tsindex e9185050..246a6d61 100644--- a/src/functions/replay.ts+++ b/src/functions/replay.ts@@ -9,9 +9,11 @@ import type {RawObservation,Session,} from "../types.js";+import { importOrigin } from "../types.js";import type { StateKV } from "../state/kv.js";import { KV, generateId, fingerprintId } from "../state/schema.js";import { parseJsonlText } from "../replay/jsonl-parser.js";+import { resetLessonIndex } from "./lessons.js";import { projectTimeline, type Timeline } from "../replay/timeline.js";import { safeAudit } from "./audit.js";import { buildSyntheticCompression } from "./compress-synthetic.js";@@ -157,6 +159,7 @@ async function deriveCrystalAndLessons(lessonIds.push(lessonId);} catch {}}+ if (lessonIds.length > 0) resetLessonIndex();// Content-addressed on sessionId so re-importing the same session// upserts the crystal in place instead of creating a new one.@@ -436,6 +439,11 @@ export function registerReplayFunctions(sdk: ISdk, kv: StateKV): void {await Promise.all(parsed.observations.map(async (obs) => {const synthetic = buildSyntheticCompression(obs);+ synthetic.origin = importOrigin(+ synthetic.origin,+ synthetic.timestamp,+ "jsonl",+ );compressed.push(synthetic);await kv.set(KV.observations(parsed.sessionId), obs.id, synthetic);}),diff --git a/src/functions/search.ts b/src/functions/search.tsindex 9bcda6ae..95082895 100644--- a/src/functions/search.ts+++ b/src/functions/search.ts@@ -14,6 +14,22 @@ let index: SearchIndex | null = nulllet vectorIndex: VectorIndex | null = nulllet currentEmbeddingProvider: EmbeddingProvider | null = null+// Hybrid ranking hook for mem::search. Wired by index.ts once the+// hybrid searcher exists (it is constructed after this module's+// registration runs). When set and the vector index has entries,+// mem::search ranks candidates through the full BM25+vector+graph+// fusion instead of BM25 alone — previously only mem::smart-search got+// hybrid ranking while the primary recall surface stayed keyword-only.+type HybridRanker = (+ query: string,+ limit: number,+) => Promise<Array<{ observation: CompressedObservation; sessionId: string; combinedScore: number }>>+let hybridRanker: HybridRanker | null = null++export function setHybridRanker(fn: HybridRanker | null): void {+ hybridRanker = fn+}+// Dedupes the lazy cold-start rebuild kicked off from the mem::search// request path. A full rebuildIndex walks every observation across every// session, so N concurrent queries against an empty index would each@@ -23,6 +39,11 @@ let currentEmbeddingProvider: EmbeddingProvider | null = null// duplicates. The boot-time rebuild in index.ts is unaffected.let rebuildPromise: Promise<number> | null = null+let memoryIndexReady = false+export function isMemoryIndexReady(): boolean {+ return memoryIndexReady+}+export function getSearchIndex(): SearchIndex {if (!index) index = new SearchIndex()return index@@ -290,6 +311,7 @@ export async function indexRecords(export async function rebuildIndex(kv: StateKV): Promise<number> {const idx = getSearchIndex()idx.clear()+ memoryIndexReady = false// BM25 clear above wipes stale doc entries; the vector index has the// symmetric concern — memories/observations deleted between runs@@ -302,8 +324,10 @@ export async function rebuildIndex(kv: StateKV): Promise<number> {// entries vanish from BM25 on every restart even after the live-write// fix in remember.ts.let memories: Memory[] = []+ let memoriesLoaded = falsetry {memories = await kv.list<Memory>(KV.memories)+ memoriesLoaded = true} catch (err) {logger.warn('rebuildIndex: failed to load memories', {error: err instanceof Error ? err.message : String(err),@@ -337,6 +361,7 @@ export async function rebuildIndex(kv: StateKV): Promise<number> {}indexed += await indexRecords([], memories)+ if (memoriesLoaded) memoryIndexReady = truereturn indexed}@@ -448,7 +473,33 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {// rank lower than cross-agent ones in the hybrid score.const filtering = !!(projectFilter || cwdFilter || filterAgentId)const fetchLimit = filtering ? Math.max(effectiveLimit * 10, 100) : effectiveLimit- const results = idx.search(query, fetchLimit)+ // Hybrid results carry the observation the ranker already loaded,+ // so the load pass below doesn't refetch every record it just+ // enriched.+ let results: Array<{+ obsId: string+ sessionId: string+ score: number+ observation?: CompressedObservation+ }>+ if (hybridRanker && vectorIndex && vectorIndex.size > 0) {+ try {+ const hybrid = await hybridRanker(query, fetchLimit)+ results = hybrid.map((r) => ({+ obsId: r.observation.id,+ sessionId: r.sessionId,+ score: r.combinedScore,+ observation: r.observation,+ }))+ } catch (err) {+ logger.warn("hybrid ranking failed, falling back to keyword search", {+ error: err instanceof Error ? err.message : String(err),+ })+ results = idx.search(query, fetchLimit)+ }+ } else {+ results = idx.search(query, fetchLimit)+ }// Resolve session -> project/cwd once per sessionId we touch.const sessionCache = new Map<string, Session | null>()@@ -522,6 +573,7 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {// sessionId, so the observation key never exists (#265).const obsResults = await Promise.all(candidates.map(async (r) => {+ if (r.observation) return r.observationconst obs = await kv.get<CompressedObservation>(KV.observations(r.sessionId), r.obsId).catch(() => null)diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex 5eacd12e..4f666781 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -40,13 +40,7 @@ async function main() {const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";- fetch(`${REST_URL}/agentmemory/summarize`, {- method: "POST",- headers: authHeaders(),- body: JSON.stringify({ sessionId }),- signal: AbortSignal.timeout(120000),- }).catch(() => {});-+ // session/end already fans out the summary server-side (#1203).fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",headers: authHeaders(),diff --git a/src/index.ts b/src/index.tsindex 198a6dc3..26e5a634 100644--- a/src/index.ts+++ b/src/index.ts@@ -39,6 +39,7 @@ import {setVectorIndex,setEmbeddingProvider,setIndexPersistence,+ setHybridRanker,} from "./functions/search.js";import { registerContextFunction } from "./functions/context.js";import { registerSummarizeFunction } from "./functions/summarize.js";@@ -272,11 +273,11 @@ async function main() {);}- if (isGraphExtractionEnabled()) {- registerGraphFunction(sdk, kv, provider);- registerGraphImportFunction(sdk, kv);- bootLog(`Knowledge graph: extraction enabled`);- }+ registerGraphFunction(sdk, kv, provider);+ registerGraphImportFunction(sdk, kv);+ bootLog(+ `Knowledge graph: structural extraction on (LLM relations ${isGraphExtractionEnabled() ? "enabled" : "off"})`,+ );registerConsolidationPipelineFunction(sdk, kv, provider);bootLog(`Consolidation pipeline: registered (CONSOLIDATION_ENABLED=${isConsolidationEnabled() ? "true" : "false"})`);@@ -386,9 +387,10 @@ async function main() {graphWeight,);- registerSmartSearchFunction(sdk, kv, (query, limit) =>- hybridSearch.search(query, limit),- );+ const hybridRanker = (query: string, limit: number) =>+ hybridSearch.search(query, limit);+ registerSmartSearchFunction(sdk, kv, hybridRanker);+ setHybridRanker(hybridRanker);registerRecentSearchesSweepFunction(sdk, kv);registerApiTriggers(sdk, kv, secret, metricsStore, provider);diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 13240003..ef26427a 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -186,6 +186,10 @@ export function registerMcpEndpoints(typeof args.project === "string" && args.project.trim().length > 0? args.project.trim(): undefined;+ const saveAgentId =+ typeof args.agentId === "string" && args.agentId.trim().length > 0+ ? (args.agentId as string).trim()+ : undefined;const result = await sdk.trigger({ function_id: "mem::remember", payload: {content: args.content,@@ -193,6 +197,7 @@ export function registerMcpEndpoints(concepts,files,...(project !== undefined && { project }),+ ...(saveAgentId !== undefined && { agentId: saveAgentId }),} });return {status_code: 200,diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.tsindex 1ace150b..4a896724 100644--- a/src/mcp/standalone.ts+++ b/src/mcp/standalone.ts@@ -99,6 +99,8 @@ interface Validated {type?: string;concepts?: string[];files?: string[];+ project?: string;+ agentId?: string;query?: string;limit?: number;format?: string;@@ -122,6 +124,15 @@ function validate(toolName: string, args: Record<string, unknown>): Validated {v.type = (args["type"] as string) || "fact";v.concepts = normalizeList(args["concepts"]);v.files = normalizeList(args["files"]);+ // The tool schema exposes project (and now agentId); dropping them+ // here silently broke project/agent scoping through the stdio+ // package specifically.+ if (typeof args["project"] === "string" && args["project"].trim()) {+ v.project = args["project"].trim();+ }+ if (typeof args["agentId"] === "string" && args["agentId"].trim()) {+ v.agentId = args["agentId"].trim();+ }return v;}case "memory_recall":@@ -180,6 +191,8 @@ async function handleProxy(type: v.type,concepts: v.concepts,files: v.files,+ ...(v.project !== undefined && { project: v.project }),+ ...(v.agentId !== undefined && { agentId: v.agentId }),}),});return textResponse(result);diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.tsindex 464cb3b0..1225b4ce 100644--- a/src/mcp/tools-registry.ts+++ b/src/mcp/tools-registry.ts@@ -83,6 +83,12 @@ export const CORE_TOOLS: McpToolDef[] = ["started. Do not use filesystem paths or ad-hoc display names — those " +"change across machines and will silently break project scoping.",},+ agentId: {+ type: "string",+ description:+ "Agent identity to scope this memory to. When set, agent-scoped recall " ++ "and search only surface it for the same agentId. Omit for shared memory.",+ },},required: ["content"],},diff --git a/src/prompts/graph-extraction.ts b/src/prompts/graph-extraction.tsindex 4f1049c1..cb6d47ad 100644--- a/src/prompts/graph-extraction.ts+++ b/src/prompts/graph-extraction.ts@@ -31,5 +31,9 @@ export function buildGraphExtractionPrompt(`[${i + 1}] Type: ${o.type}\nTitle: ${o.title}\nNarrative: ${o.narrative}\nConcepts: ${(o.concepts ?? []).join(", ")}\nFiles: ${(o.files ?? []).join(", ")}`,).join("\n\n");- return `Extract entities and relationships from these observations:\n\n${items}`;+ // Some local models default to a hidden reasoning pass that consumes+ // most of the token budget before any output. The suffix is their+ // documented soft switch to skip it; other models ignore the token.+ const noThink = process.env.AGENTMEMORY_LLM_NOTHINK === "1" ? "\n/no_think" : "";+ return `Extract entities and relationships from these observations:\n\n${items}${noThink}`;}diff --git a/src/providers/index.ts b/src/providers/index.tsindex 0ec3feba..0ecef149 100644--- a/src/providers/index.ts+++ b/src/providers/index.ts@@ -35,19 +35,17 @@ function requireEnvVar(key: string): string {function defaultModelFor(providerType: ProviderConfig["provider"]): string {switch (providerType) {case "openai":- return getEnvVar("OPENAI_MODEL") || "gpt-4o-mini";+ return getEnvVar("OPENAI_MODEL") || "gpt-5.6-luna";case "anthropic":- return getEnvVar("ANTHROPIC_MODEL") || "claude-sonnet-4-20250514";+ return getEnvVar("ANTHROPIC_MODEL") || "claude-sonnet-5";case "gemini":- return getEnvVar("GEMINI_MODEL") || "gemini-2.5-flash";+ return getEnvVar("GEMINI_MODEL") || "gemini-3.7-flash";case "openrouter":- return (- getEnvVar("OPENROUTER_MODEL") || "anthropic/claude-sonnet-4-20250514"- );+ return getEnvVar("OPENROUTER_MODEL") || "anthropic/claude-sonnet-5";case "minimax":- return getEnvVar("MINIMAX_MODEL") || "MiniMax-M2.7";+ return getEnvVar("MINIMAX_MODEL") || "MiniMax-M3";case "agent-sdk":- return "claude-sonnet-4-20250514";+ return "claude-sonnet-5";case "noop":default:return "noop";diff --git a/src/providers/minimax.ts b/src/providers/minimax.tsindex 72fc9ec9..77c0dcd2 100644--- a/src/providers/minimax.ts+++ b/src/providers/minimax.ts@@ -10,8 +10,8 @@ import { fetchWithTimeout } from './_fetch.js'** Required env vars (loaded from ~/.agentmemory/.env or process.env):* MINIMAX_API_KEY — your MiniMax API key- * MINIMAX_MODEL — model name (default: MiniMax-M2.7)- * MAX_TOKENS — max output tokens (default: 800; MiniMax-M2.7 needs ≤800)+ * MINIMAX_MODEL — model name (default: MiniMax-M3)+ * MAX_TOKENS — max output tokens (default: 4096)** Optional:* MINIMAX_BASE_URL — base URL without path (default: https://api.minimax.io/anthropic)diff --git a/src/providers/openai.ts b/src/providers/openai.tsindex 438b2f4e..31ee158e 100644--- a/src/providers/openai.ts+++ b/src/providers/openai.ts@@ -9,7 +9,7 @@ import {normalizeBaseUrl,} from "./_openai-shared.js";-const DEFAULT_MODEL = "gpt-4o-mini";+const DEFAULT_MODEL = "gpt-5.6-luna";const DEFAULT_TIMEOUT_MS = 60_000;/**@@ -29,7 +29,7 @@ const DEFAULT_TIMEOUT_MS = 60_000;* Optional:* OPENAI_BASE_URL — base URL without path (default: https://api.openai.com).* Azure: https://<resource>.openai.azure.com/openai/deployments/<deployment>- * OPENAI_MODEL — model name (default: gpt-4o-mini)+ * OPENAI_MODEL — model name (default: gpt-5.6-luna)* OPENAI_API_VERSION — Azure api-version query param (default: 2024-08-01-preview)* OPENAI_TIMEOUT_MS — outbound fetch timeout in ms (OpenAI-scoped alias,* takes precedence over AGENTMEMORY_LLM_TIMEOUT_MSdiff --git a/src/state/hybrid-search.ts b/src/state/hybrid-search.tsindex d234a3ef..dc762a6e 100644--- a/src/state/hybrid-search.ts+++ b/src/state/hybrid-search.ts@@ -70,7 +70,11 @@ export class HybridSearch {}return Array.from(merged.values())- .sort((a, b) => b.combinedScore - a.combinedScore)+ .sort(+ (a, b) =>+ b.combinedScore - a.combinedScore ||+ (a.obsId < b.obsId ? -1 : a.obsId > b.obsId ? 1 : 0),+ ).slice(0, limit);}@@ -191,35 +195,50 @@ export class HybridSearch {}});- const hasVector = vectorResults.length > 0;- const hasGraph = graphResults.length > 0;-- let effectiveBm25W = this.bm25Weight;- let effectiveVectorW = hasVector ? this.vectorWeight : 0;- let effectiveGraphW = hasGraph ? this.graphWeight : 0;-- const totalW = effectiveBm25W + effectiveVectorW + effectiveGraphW;- if (totalW > 0) {- effectiveBm25W /= totalW;- effectiveVectorW /= totalW;- effectiveGraphW /= totalW;- }+ // Normalize once per query by the best attainable weighted score over+ // the streams that produced results, so configured stream weights+ // survive for single-stream hits and a silent stream carries no penalty.+ const AGREEMENT_BONUS = 0.05;+ const activeWeight =+ (bm25Results.length > 0 ? this.bm25Weight : 0) ++ (vectorResults.length > 0 ? this.vectorWeight : 0) ++ (graphResults.length > 0 ? this.graphWeight : 0);+ const maxAttainable = activeWeight * (1 / (RRF_K + 1));+ const ranked = Array.from(scores.entries()).map(([obsId, s]) => {+ const wB = Number.isFinite(s.bm25Rank) ? this.bm25Weight : 0;+ const wV = Number.isFinite(s.vectorRank) ? this.vectorWeight : 0;+ const wG = Number.isFinite(s.graphRank) ? this.graphWeight : 0;+ const matchedStreams =+ (wB > 0 ? 1 : 0) + (wV > 0 ? 1 : 0) + (wG > 0 ? 1 : 0);+ const weighted =+ wB * (1 / (RRF_K + s.bm25Rank)) ++ wV * (1 / (RRF_K + s.vectorRank)) ++ wG * (1 / (RRF_K + s.graphRank));+ const rrf = maxAttainable > 0 ? weighted / maxAttainable : 0;+ return {+ obsId,+ s,+ combinedScore: rrf * (1 + AGREEMENT_BONUS * (matchedStreams - 1)),+ minRank: Math.min(s.bm25Rank, s.vectorRank, s.graphRank),+ };+ });- const combined = Array.from(scores.entries()).map(([obsId, s]) => ({+ ranked.sort(+ (a, b) =>+ b.combinedScore - a.combinedScore ||+ a.minRank - b.minRank ||+ (a.obsId < b.obsId ? -1 : a.obsId > b.obsId ? 1 : 0),+ );+ const combined = ranked.map(({ obsId, s, combinedScore }) => ({obsId,sessionId: s.sessionId,bm25Score: s.bm25Score,vectorScore: s.vectorScore,graphScore: s.graphScore,graphContext: s.graphContext,- combinedScore:- effectiveBm25W * (1 / (RRF_K + s.bm25Rank)) +- effectiveVectorW * (1 / (RRF_K + s.vectorRank)) +- effectiveGraphW * (1 / (RRF_K + s.graphRank)),+ combinedScore,}));- combined.sort((a, b) => b.combinedScore - a.combinedScore);-const retrievalDepth = Math.max(limit, 20);const rerankWindow = 20;const diversified = this.diversifyBySession(combined, retrievalDepth);diff --git a/src/state/memory-utils.ts b/src/state/memory-utils.tsindex aa0bcc5b..9bc5b16a 100644--- a/src/state/memory-utils.ts+++ b/src/state/memory-utils.ts@@ -1,4 +1,4 @@-import type { CompressedObservation, Memory } from "../types.js";+import type { CompressedObservation, Lesson, Memory } from "../types.js";// Wraps a Memory record in the CompressedObservation shape that// SearchIndex / VectorIndex / enrichment paths consume. Memories share@@ -20,5 +20,27 @@ export function memoryToObservation(memory: Memory): CompressedObservation {concepts: memory.concepts,files: memory.files,importance: memory.strength,+ // Carry the owning agent through so agent-scoped search filters see+ // memories, not just raw observations. Dropping it made every memory+ // invisible to any agentId-scoped query.+ ...(memory.agentId ? { agentId: memory.agentId } : {}),+ };+}++// Same adapter for lessons, kept beside memoryToObservation so a new+// CompressedObservation field has one obvious place to be threaded+// through both record kinds.+export function lessonToObservation(l: Lesson): CompressedObservation {+ return {+ id: l.id,+ sessionId: "lesson",+ timestamp: l.createdAt,+ type: "decision",+ title: l.content.slice(0, 120),+ facts: [l.content],+ narrative: l.context || "",+ concepts: l.tags,+ files: [],+ importance: l.confidence,};}diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex 7560e873..56fad4f0 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -23,6 +23,7 @@ import {detectLlmProviderKind,getAgentId,isAgentScopeIsolated,+ loadConfig,} from "../config.js";type Response = {@@ -164,10 +165,23 @@ export function registerApiTriggers(},);+ // Shared instance metadata for livez and health so the two never+ // drift. streamsPort lets the viewer resolve its stream WebSocket+ // target from the server instead of port arithmetic, which broke+ // whenever the viewer bound a fallback port. Config is boot-static,+ // so read it once instead of rebuilding the merged env per request.+ const bootStreamsPort = loadConfig().streamsPort;+ const instanceInfo = () => ({+ service: "agentmemory",+ viewerPort: getBoundViewerPort(),+ viewerSkipped: getViewerSkipped(),+ streamsPort: bootStreamsPort,+ });+sdk.registerFunction("api::liveness",async (): Promise<Response> => ({status_code: 200,- body: { status: "ok", service: "agentmemory", viewerPort: getBoundViewerPort(), viewerSkipped: getViewerSkipped() },+ body: { status: "ok", ...instanceInfo() },}),);sdk.registerTrigger({@@ -268,8 +282,7 @@ export function registerApiTriggers(health: health || null,functionMetrics,circuitBreaker,- viewerPort: getBoundViewerPort(),- viewerSkipped: getViewerSkipped(),+ ...instanceInfo(),},};},@@ -1002,6 +1015,7 @@ export function registerApiTriggers(ttlDays?: number;sourceObservationIds?: string[];project?: string;+ agentId?: string;}>,): Promise<Response> => {const authErr = checkAuth(req, secret);@@ -1029,6 +1043,9 @@ export function registerApiTriggers(...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }),...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }),...(req.body.project !== undefined && { project: req.body.project }),+ ...(typeof req.body.agentId === "string" && req.body.agentId.trim()+ ? { agentId: req.body.agentId.trim() }+ : {}),},});return { status_code: 201, body: result };diff --git a/src/triggers/events.ts b/src/triggers/events.tsindex 65db7035..bbf15db3 100644--- a/src/triggers/events.ts+++ b/src/triggers/events.ts@@ -7,7 +7,6 @@ import {getAgentId,getConsolidationCooldownMs,isConsolidationEnabled,- isGraphExtractionEnabled,} from "../config.js";import { logger } from "../logger.js";@@ -108,25 +107,20 @@ export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {if (isReflectEnabled()) {fireVoid("mem::slot-reflect", { sessionId: data.sessionId });}- if (isGraphExtractionEnabled()) {- try {- const observations = await kv.list<CompressedObservation>(- KV.observations(data.sessionId),- );- const compressed = observations.filter((o) => o.title);- if (compressed.length > 0) {- sdk.trigger({- function_id: "mem::graph-extract",- payload: { observations: compressed },- action: TriggerAction.Void(),- });- }- } catch (err) {- logger.warn("graph-extract trigger failed", {- sessionId: data.sessionId,- error: err instanceof Error ? err.message : String(err),- });+ // Unconditional: mem::graph-extract gates its LLM pass internally.+ try {+ const observations = await kv.list<CompressedObservation>(+ KV.observations(data.sessionId),+ );+ const compressed = observations.filter((o) => o.title);+ if (compressed.length > 0) {+ fireVoid("mem::graph-extract", { observations: compressed });}+ } catch (err) {+ logger.warn("graph-extract trigger failed", {+ sessionId: data.sessionId,+ error: err instanceof Error ? err.message : String(err),+ });}// Crystals + lessons consolidation. The stop lifecycle is the single// source of truth: event::session::stopped fires for ALL agents (thediff --git a/src/types.ts b/src/types.tsindex 2f3f0285..1118b3f9 100644--- a/src/types.ts+++ b/src/types.ts@@ -27,6 +27,23 @@ export interface CommitLink {linkedAt: string;}+// Immutable write-time provenance: which trust boundary the content+// crossed, inherited by derived records.+export interface Origin {+ channel: "user" | "agent" | "tool" | "import" | "shared";+ detail?: string;+ capturedAt: string;+}++export function importOrigin(+ existing: Origin | undefined,+ capturedAt: string,+ detail?: string,+): Origin {+ if (existing) return existing;+ return { channel: "import", capturedAt, ...(detail ? { detail } : {}) };+}+export interface RawObservation {id: string;sessionId: string;@@ -41,6 +58,7 @@ export interface RawObservation {modality?: "text" | "image" | "mixed";imageData?: string;agentId?: string;+ origin?: Origin;}export interface CompressedObservation {@@ -61,6 +79,7 @@ export interface CompressedObservation {imageDescription?: string;modality?: "text" | "image" | "mixed";agentId?: string;+ origin?: Origin;}export type ObservationType =@@ -102,6 +121,7 @@ export interface Memory {imageData?: string;agentId?: string;project?: string;+ origin?: Origin;}export interface SessionSummary {diff --git a/src/viewer/favicon.svg b/src/viewer/favicon.svgindex 3ef799f7..68b00c10 100644--- a/src/viewer/favicon.svg+++ b/src/viewer/favicon.svg@@ -1 +1,35 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="10" fill="#111111"/><text x="32" y="41" text-anchor="middle" font-family="Arial,sans-serif" font-size="24" font-weight="700" fill="#2D6A4F">AM</text></svg>+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">+ <defs>+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#FF6B35"/>+ <stop offset="100%" stop-color="#FF8F5E"/>+ </linearGradient>+ </defs>++ <rect width="64" height="64" rx="14" fill="#1A1A1A"/>++ <!-- 4 memory tiers -->+ <rect x="14" y="40" width="36" height="5" rx="2.5" fill="#333" opacity="0.5"/>+ <rect x="14" y="33" width="36" height="5" rx="2.5" fill="#444" opacity="0.6"/>+ <rect x="14" y="26" width="36" height="5" rx="2.5" fill="#555" opacity="0.7"/>+ <rect x="14" y="19" width="36" height="5" rx="2.5" fill="url(#g)"/>++ <!-- Active nodes on hot layer -->+ <circle cx="22" cy="21.5" r="1.8" fill="#fff"/>+ <circle cx="32" cy="21.5" r="1.8" fill="#fff"/>+ <circle cx="42" cy="21.5" r="1.8" fill="#fff"/>++ <!-- Retrieval lines converging up -->+ <line x1="22" y1="19" x2="32" y2="12" stroke="#FF6B35" stroke-width="1" opacity="0.7"/>+ <line x1="32" y1="19" x2="32" y2="12" stroke="#FF6B35" stroke-width="1" opacity="0.5"/>+ <line x1="42" y1="19" x2="32" y2="12" stroke="#FF6B35" stroke-width="1" opacity="0.7"/>++ <!-- Retrieval point -->+ <circle cx="32" cy="11" r="3" fill="url(#g)"/>+ <circle cx="32" cy="11" r="5" fill="none" stroke="#FF6B35" stroke-width="0.8" opacity="0.3"/>++ <!-- Fading dots on lower tiers -->+ <circle cx="25" cy="28.5" r="1" fill="#888" opacity="0.4"/>+ <circle cx="39" cy="28.5" r="1" fill="#888" opacity="0.4"/>+ <circle cx="32" cy="35.5" r="0.8" fill="#666" opacity="0.3"/>+</svg>diff --git a/src/viewer/index.html b/src/viewer/index.htmlindex 3efe4342..de47f4f5 100644--- a/src/viewer/index.html+++ b/src/viewer/index.html@@ -50,22 +50,21 @@--font-mono: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;}html[data-theme="dark"] {- --bg: #1a1a1e;- --bg-alt: #232328;- --bg-subtle: #1f1f24;- --bg-inset: #2a2a30;- --border: #444;- --border-light: #3a3a42;- --border-heavy: #ccc;- --ink: #eee;- --ink-secondary: #ccc;- --ink-muted: #999;- --ink-faint: #777;+ --bg: #121316;+ --bg-alt: #1a1c20;+ --bg-subtle: #17181b;+ --bg-inset: #222428;+ --border: #33363b;+ --border-light: #26282c;+ --border-heavy: #c9cbd1;+ --ink: #eef0f3;+ --ink-secondary: #c6c9ce;+ --ink-muted: #94979d;+ --ink-faint: #6d7076;+ --accent: #f2555a;+ --accent-light: #ff7a70;--cream: #2a2520;}- html[data-theme="dark"] body {- background-image: radial-gradient(circle, #3a3a42 0.5px, transparent 0.5px);- }html[data-theme="dark"] .graph-tooltip {background: rgba(30,30,35,0.92);border-color: rgba(255,255,255,0.1);@@ -80,6 +79,16 @@color: var(--bg);}* { margin: 0; padding: 0; box-sizing: border-box; }+ #bg-dither {+ position: fixed;+ inset: 0;+ width: 100%;+ height: 100%;+ z-index: 0;+ pointer-events: none;+ opacity: 0.5;+ }+ .app-header, .tab-bar, .view, .flags-banner, footer, .app-footer { position: relative; z-index: 1; }body {font-family: var(--font-body);background: var(--bg);@@ -89,8 +98,6 @@height: 100vh;display: flex;flex-direction: column;- background-image: radial-gradient(circle, #D4D4CF 0.5px, transparent 0.5px);- background-size: 16px 16px;}::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: var(--bg); }@@ -139,6 +146,11 @@align-items: center;gap: 12px;}+ @media (max-width: 720px) {+ .app-header { flex-wrap: wrap; row-gap: 6px; padding: 10px 16px; }+ .app-header .dateline { display: none; }+ .view { overflow-x: auto; }+ }.ws-status {font-size: 10px;padding: 3px 10px;@@ -158,7 +170,11 @@display: inline-block;}.ws-status.connected { border-color: var(--green); color: var(--green); }- .ws-status.connected::before { background: var(--green); }+ .ws-status.connected::before { background: var(--green); animation: live-pulse 2.4s ease-in-out infinite; }+ @keyframes live-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.35; }+ }.ws-status.disconnected { border-color: var(--ink-faint); color: var(--ink-faint); }.ws-status.disconnected::before { background: var(--ink-faint); }@@ -195,7 +211,15 @@}.view { display: none; flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 24px; }- .view.active { display: block; }+ .view.active { display: block; animation: view-in 160ms ease-out; }+ @keyframes view-in {+ from { opacity: 0; transform: translateY(4px); }+ to { opacity: 1; transform: translateY(0); }+ }+ @media (prefers-reduced-motion: reduce) {+ .view.active { animation: none; }+ .ws-status.connected::before { animation: none; }+ }.stats-grid {display: grid;@@ -211,6 +235,14 @@border-bottom: 1px solid var(--border-light);}.stat-card:last-child { border-right: none; }+ .stat-card[data-action] {+ cursor: pointer;+ transition: background 0.15s ease-out;+ }+ .stat-card[data-action]:hover { background: var(--bg-alt); }+ .stat-card[data-action]:hover .label { color: var(--accent); }+ .stat-card[data-action]:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }+ .stat-card[data-action]:active { background: var(--bg-inset); }.stat-card .label {font-size: 9px;color: var(--ink-muted);@@ -294,6 +326,7 @@border-collapse: collapse;font-size: 13px;font-family: var(--font-body);+ font-variant-numeric: tabular-nums;}th {text-align: left;@@ -333,7 +366,7 @@align-items: center;flex-wrap: wrap;}- .toolbar input, .toolbar select {+ .toolbar input, .toolbar select, .search-input {background: var(--bg);border: 1px solid var(--border);color: var(--ink);@@ -342,13 +375,13 @@outline: none;font-family: var(--font-ui);}- .toolbar input:focus, .toolbar select:focus {+ .toolbar input:focus, .toolbar select:focus, .search-input:focus {border-color: var(--ink);box-shadow: 2px 2px 0px 0px var(--border);}.toolbar input { flex: 1; min-width: 200px; }- .btn {+ .btn, .toolbar button {background: var(--bg);border: 1px solid var(--border);color: var(--ink);@@ -361,8 +394,8 @@text-transform: uppercase;letter-spacing: 0.06em;}- .btn:hover { box-shadow: 3px 3px 0px 0px var(--border); transform: translate(-1px, -1px); }- .btn:active { box-shadow: none; transform: translate(0, 0); }+ .btn:hover, .toolbar button:hover { box-shadow: 3px 3px 0px 0px var(--border); transform: translate(-1px, -1px); }+ .btn:active, .toolbar button:active { box-shadow: none; transform: translate(0, 0); }.btn-danger { border-color: var(--accent); color: var(--accent); }.btn-danger:hover { background: var(--accent); color: white; box-shadow: 3px 3px 0px 0px var(--border); }.btn-primary { background: var(--ink); color: var(--bg); border-color: var(--ink); }@@ -370,7 +403,8 @@.graph-container {display: flex;- height: calc(100vh - 130px);+ height: calc(100vh - 178px);+ min-height: 460px;margin: -24px;border-top: 1px solid var(--border-light);}@@ -523,18 +557,36 @@}.tag.file-tag { border-color: var(--green); color: var(--green); }+ /* Two-pane sessions: list left, detail pinned right on wide screens.+ The detail panel previously rendered below the full list — selecting+ a session on any real corpus put the response off-screen. */+ .sessions-layout {+ display: grid;+ grid-template-columns: minmax(300px, 400px) minmax(0, 1fr);+ gap: 20px;+ align-items: start;+ }+ .sessions-layout #session-detail { position: sticky; top: 0; min-width: 0; }+ .sessions-layout #session-detail .detail-panel { margin-top: 0; }+ @media (max-width: 1100px) {+ .sessions-layout { grid-template-columns: 1fr; }+ .sessions-layout #session-detail { position: static; }+ }.session-list { display: flex; flex-direction: column; gap: 0; }.session-item {background: var(--bg);border: 1px solid var(--border-light);border-bottom: none;+ border-left: 3px solid transparent;padding: 14px 20px;cursor: pointer;- transition: background 0.1s;+ transition: background 0.15s ease-out, border-color 0.15s ease-out;}.session-item:last-child { border-bottom: 1px solid var(--border-light); }- .session-item:hover { background: var(--bg-alt); }- .session-item.selected { background: var(--bg-alt); border-left: 3px solid var(--accent); }+ .session-item:hover { background: var(--bg-alt); border-left-color: var(--border-light); }+ .session-item:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }+ .session-item:active { background: var(--bg-inset); }+ .session-item.selected { background: var(--bg-alt); border-left-color: var(--accent); }.session-item .session-top {display: flex;justify-content: space-between;@@ -975,6 +1027,7 @@</style></head><body>+ <canvas id="bg-dither" aria-hidden="true"></canvas><div class="app-header"><a class="brand" href="#dashboard" data-tab-link="dashboard" aria-label="Open dashboard"><h1>agentmemory</h1>@@ -1112,12 +1165,12 @@activeTab: 'dashboard',dashboard: { loaded: false, health: null, sessions: [], memories: [], graphStats: null, recentAudit: [], lessons: [], crystals: [] },graph: { loaded: false, nodes: [], edges: [], stats: null, filters: {}, selectedNode: null, queryError: null, truncated: false, totalNodes: 0, totalEdges: 0 },- memories: { loaded: false, items: [], search: '', typeFilter: '' },+ memories: { loaded: false, items: [], search: '', typeFilter: '', selectedId: null },timeline: { loaded: false, observations: [], sessionId: '', minImportance: 0, page: 0, pageSize: 50 },sessions: { loaded: false, items: [], selectedId: null },audit: { loaded: false, entries: [], opFilter: '' },activity: { loaded: false, observations: [], sessions: [], typeFilter: '' },- lessons: { loaded: false, items: [], search: '' },+ lessons: { loaded: false, items: [], search: '', selectedId: null },actions: { loaded: false, items: [], frontier: [], statusFilter: '', search: '' },crystals: { loaded: false, items: [], search: '', lessonMap: {} },profile: { loaded: false, projects: [], selectedProject: '', data: null },@@ -1141,6 +1194,45 @@if (!ts) return '';try { return new Date(ts).toLocaleTimeString(); } catch { return ts; }}+ // Observation subtitles are often the raw tool input serialized as+ // JSON ('{"file_path":"src/x.ts"}'). Pull the human-meaningful field+ // out for display; anything unparseable renders as-is.+ // Health alerts/notes arrive as compact machine slugs+ // (memory_heap_tight_93%_rss111mb). Translate the known families+ // into sentences; unknown slugs render as-is.+ function humanizeHealthFlag(f) {+ var m;+ if ((m = /^memory_heap_tight_(\d+)%_rss(\d+)mb$/.exec(f)))+ return 'Heap is running tight: ' + m[1] + '% of allocated heap in use (process memory ' + m[2] + ' MB). Informational — Node grows the heap on demand.';+ if ((m = /^memory_(warn|critical)_(\d+)%_rss(\d+)mb$/.exec(f)))+ return 'Memory ' + (m[1] === 'critical' ? 'critically high' : 'elevated') + ': ' + m[2] + '% of heap in use, process memory ' + m[3] + ' MB.';+ if ((m = /^cpu_(warn|critical)_(\d+)%$/.exec(f)))+ return 'CPU ' + (m[1] === 'critical' ? 'critically high' : 'elevated') + ': ' + m[2] + '%.';+ if ((m = /^event_loop_lag_(warn|critical)_(\d+)ms$/.exec(f)))+ return 'Event loop ' + (m[1] === 'critical' ? 'severely delayed' : 'delayed') + ': ' + m[2] + ' ms behind. The worker is busy or blocked.';+ if (f === 'connection_reconnecting')+ return 'Engine connection lost — reconnecting.';+ if ((m = /^connection_(.+)$/.exec(f)))+ return 'Engine connection state: ' + m[1] + '.';+ return f;+ }++ function humanizeSubtitle(s) {+ if (typeof s !== 'string') return '';+ var t = s.trim();+ if (!t.startsWith('{')) return s;+ try {+ var o = JSON.parse(t);+ if (o && typeof o === 'object') {+ var keys = ['file_path', 'filepath', 'filePath', 'path', 'file', 'command', 'pattern', 'url', 'query', 'prompt'];+ for (var i = 0; i < keys.length; i++) {+ if (typeof o[keys[i]] === 'string' && o[keys[i]].length > 0) return o[keys[i]];+ }+ }+ } catch (_) {}+ return s;+ }+function truncate(s, n) {if (!s) return '';return s.length > n ? s.slice(0, n) + '...' : s;@@ -1150,7 +1242,15 @@}function shortSessionId(s, n) {var id = sessionId(s);- return id ? id.slice(0, n || 8) : '';+ if (!id) return '';+ var max = n || 8;+ if (id.length <= max) return id;+ // Session ids share a long common prefix (demo_msuaboq7_...); the+ // distinguishing part is the tail. Keep head + tail so truncated+ // ids stay tellable apart in lists and dropdowns.+ var tail = 6;+ var head = Math.max(2, max - tail - 1);+ return id.slice(0, head) + '…' + id.slice(-tail);}function sessionDisplayName(s) {var project = s && s.project ? String(s.project).split('/').pop() : '';@@ -1335,26 +1435,41 @@loadTab(tab);}+ // Per-tab freshness stamps. Tabs refetch on entry (the loaded-once+ // model went stale the moment anything wrote through the API), but a+ // short window stops rapid tab flipping from re-issuing the full+ // fan-out (dashboard alone is ~10 requests) on every click.+ var tabFetchedAt = {};+ var TAB_FRESH_MS = 5000;+async function loadTab(tab) {+ var now = Date.now();+ if (tab !== 'replay' && tabFetchedAt[tab] && now - tabFetchedAt[tab] < TAB_FRESH_MS) {+ return;+ }+ tabFetchedAt[tab] = now;switch(tab) {- case 'dashboard': if (!state.dashboard.loaded) await loadDashboard(); break;- case 'graph': if (!state.graph.loaded) await loadGraph(); break;- case 'memories': if (!state.memories.loaded) await loadMemories(); break;- case 'timeline': if (!state.timeline.loaded) await loadTimeline(); break;- case 'sessions': if (!state.sessions.loaded) await loadSessions(); break;- case 'lessons': if (!state.lessons.loaded) await loadLessons(); break;- case 'actions': if (!state.actions.loaded) await loadActions(); break;- case 'crystals': if (!state.crystals.loaded) await loadCrystals(); break;- case 'audit': if (!state.audit.loaded) await loadAudit(); break;- case 'activity': if (!state.activity.loaded) await loadActivity(); break;- case 'profile': if (!state.profile.loaded) await loadProfile(); break;+ case 'dashboard': await loadDashboard(); break;+ case 'graph': await loadGraph(); break;+ case 'memories': await loadMemories(); break;+ case 'timeline': await loadTimeline(); break;+ case 'sessions': await loadSessions(); break;+ case 'lessons': await loadLessons(); break;+ case 'actions': await loadActions(); break;+ case 'crystals': await loadCrystals(); break;+ case 'audit': await loadAudit(); break;+ case 'activity': await loadActivity(); break;+ case 'profile': await loadProfile(); break;+ // Replay stays fetch-once: reloading it would reset playback+ // timer and cursor state mid-session; its toolbar has an explicit+ // Refresh button instead.case 'replay': if (!state.replay.loaded) await loadReplay(); break;}}async function loadDashboard() {var el = document.getElementById('view-dashboard');- el.innerHTML = '<div class="loading">Loading dashboard...</div>';+ if (!state.dashboard.loaded) el.innerHTML = '<div class="loading">Loading dashboard...</div>';try {var results = await Promise.all([api('health', { readErrorBody: true }),@@ -1428,13 +1543,13 @@'</div>';}html += '<div class="stats-grid">';- html += '<div class="stat-card"><div class="label">Sessions</div><div class="value">' + d.sessions.length + '</div><div class="sub">' + activeSessions + ' active</div></div>';- html += '<div class="stat-card"><div class="label">Memories</div><div class="value">' + d.memories.length + '</div><div class="sub">latest versions</div></div>';+ html += '<div class="stat-card" data-action="goto-tab" data-tab="sessions" role="link" tabindex="0"><div class="label">Sessions</div><div class="value">' + d.sessions.length + '</div><div class="sub">' + activeSessions + ' active</div></div>';+ html += '<div class="stat-card" data-action="goto-tab" data-tab="memories" role="link" tabindex="0"><div class="label">Memories</div><div class="value">' + d.memories.length + '</div><div class="sub">latest versions</div></div>';var lessonCount = (d.lessons || []).length;var crystalCount = (d.crystals || []).length;- html += '<div class="stat-card"><div class="label">Lessons</div><div class="value">' + lessonCount + '</div><div class="sub">confidence-scored</div></div>';- html += '<div class="stat-card"><div class="label">Crystals</div><div class="value">' + crystalCount + '</div><div class="sub">action digests</div></div>';- html += '<div class="stat-card"><div class="label">Graph Nodes</div><div class="value">' + nodeCount + '</div><div class="sub">' + edgeCount + ' edges</div></div>';+ html += '<div class="stat-card" data-action="goto-tab" data-tab="lessons" role="link" tabindex="0"><div class="label">Lessons</div><div class="value">' + lessonCount + '</div><div class="sub">confidence-scored</div></div>';+ html += '<div class="stat-card" data-action="goto-tab" data-tab="crystals" role="link" tabindex="0"><div class="label">Crystals</div><div class="value">' + crystalCount + '</div><div class="sub">action digests</div></div>';+ html += '<div class="stat-card" data-action="goto-tab" data-tab="graph" role="link" tabindex="0"><div class="label">Graph Nodes</div><div class="value">' + nodeCount + '</div><div class="sub">' + edgeCount + ' edges</div></div>';html += '<div class="stat-card"><div class="label">Health</div><div class="value"><div class="health-bar"><span class="health-dot ' + dotClass + '"></span> ' + esc(healthStatus) + '</div></div>';html += '<div class="sub">' + esc(snap.connectionState || 'unknown') + '</div></div>';var totalCalls = fMetrics.reduce(function(a, m) { return a + (m.totalCalls || 0); }, 0);@@ -1495,7 +1610,8 @@if (snap.alerts && snap.alerts.length > 0) {html += '<div class="card" style="margin-bottom:16px;border-color:var(--accent);border-width:2px;"><div class="card-title" style="color:var(--accent);border-bottom-color:var(--accent);">Alerts (' + snap.alerts.length + ')</div>';- snap.alerts.forEach(function(al) {+ snap.alerts.forEach(function(alRaw) {+ var al = humanizeHealthFlag(alRaw);html += '<div style="font-size:12px;color:var(--accent);padding:4px 0;border-bottom:1px solid var(--border-light);font-family:var(--font-ui);">' + esc(al) + '</div>';});html += '</div>';@@ -1504,7 +1620,7 @@if (snap.notes && snap.notes.length > 0) {html += '<div class="card" style="margin-bottom:16px;"><div class="card-title" style="color:var(--ink-muted);">Notes (' + snap.notes.length + ')</div>';snap.notes.forEach(function(n) {- html += '<div style="font-size:12px;color:var(--ink-muted);padding:4px 0;border-bottom:1px solid var(--border-light);font-family:var(--font-ui);">' + esc(n) + '</div>';+ html += '<div style="font-size:12px;color:var(--ink-muted);padding:4px 0;border-bottom:1px solid var(--border-light);font-family:var(--font-ui);">' + esc(humanizeHealthFlag(n)) + '</div>';});html += '</div>';}@@ -1638,6 +1754,9 @@html += '<div class="consolidation-row"><span class="cl">Semantic facts</span><span class="cv">' + semFacts.length + '</span></div>';html += '<div class="consolidation-row"><span class="cl">Procedures</span><span class="cv">' + procItems.length + '</span></div>';html += '<div class="consolidation-row"><span class="cl">Relations</span><span class="cv">' + relItems.length + '</span></div>';+ if (semFacts.length === 0 && procItems.length === 0 && relItems.length === 0) {+ html += '<div style="font-size:12px;color:var(--ink-faint);margin-top:8px;line-height:1.5;">Consolidation distills session observations into durable facts and repeatable procedures. It runs on a schedule when <code>CONSOLIDATION_ENABLED=true</code> and an LLM provider key are set, or on demand via <code>memory_consolidate</code>.</div>';+ }html += '</div>';if (relItems.length > 0) {@@ -1695,9 +1814,24 @@var results = await Promise.all([apiPost('graph/query', { limit: GRAPH_INITIAL_LIMIT }),- apiGet('graph/stats')+ api('graph/stats', { readErrorBody: true })]);var queryResult = results[0];+ var statsResult = results[1];+ if (statsResult && statsResult.error && statsResult.flag) {+ // 503 with a structured body = the feature is off, not broken.+ // Rendering this as "query failed / Retry" sends users hunting+ // through server logs for an error that isn't one.+ state.graph.disabledInfo = statsResult;+ state.graph.queryError = null;+ state.graph.nodes = [];+ state.graph.edges = [];+ state.graph.stats = {};+ state.graph.loaded = true;+ renderGraphSidebar();+ return;+ }+ state.graph.disabledInfo = null;if (queryResult === null) {// api() returns null only on non-2xx or a transport error; an// empty graph would come back as { nodes: [], edges: [] }.@@ -1764,6 +1898,17 @@var html = '';+ if (state.graph.disabledInfo) {+ html += '<div style="margin:8px 0;padding:10px 12px;border:1px solid var(--border);background:var(--bg-alt);font-size:12px;color:var(--ink);line-height:1.5;">';+ html += '<div style="font-weight:600;margin-bottom:4px;">Knowledge graph is off</div>';+ html += '<div style="font-size:11px;color:var(--ink-muted);">' + esc(state.graph.disabledInfo.enableHow || 'Set ' + (state.graph.disabledInfo.flag || 'GRAPH_EXTRACTION_ENABLED') + '=true and restart.') + '</div>';+ if (state.graph.disabledInfo.docsHref) {+ html += '<a href="' + esc(state.graph.disabledInfo.docsHref) + '" target="_blank" rel="noopener" style="font-size:11px;">docs →</a>';+ }+ html += '</div>';+ sb.innerHTML = html;+ return;+ }// #753: error banner stays above the search box so a failed// graph/query doesn't read as "0 nodes".if (state.graph.queryError) {@@ -1796,7 +1941,10 @@html += '<label class="filter-item"><input type="checkbox" checked data-type="' + esc(type) + '"><span class="filter-dot" style="background:' + color + '"></span>' + esc(type) + '</label>';});- html += '<div class="graph-legend"><h3>Legend</h3>';+ if (state.graph.nodes.length > 0 && state.graph.edges.length === 0) {+ html += '<div style="margin:10px 0;padding:10px 12px;border:1px solid var(--border-light);background:var(--bg-subtle);font-size:11px;color:var(--ink-muted);line-height:1.5;">Entities extracted, no relations between them yet. Nodes are grouped by kind; edges appear as extraction sees entities acting on each other across more sessions (larger models find them faster).</div>';+ }+ html += '<div class="graph-legend" style="display:none"><h3>Legend</h3>';var shapeLabels = { rect: '▭', circle: '●', diamond: '◆', hexagon: '⬢' };var shownShapes = {};Object.keys(NODE_COLORS).forEach(function(type) {@@ -1856,21 +2004,38 @@edgeMap[e.targetNodeId] = (edgeMap[e.targetNodeId] || 0) + 1;});+ // With no (or few) edges a pure force layout is a meaningless+ // scatter. Anchor each type to its own cluster center so the+ // picture reads as "here is what memory knows, grouped by kind";+ // once real relations exist the edge springs dominate instead.+ var types = [];+ state.graph.nodes.forEach(function(n) {+ if (types.indexOf(n.type) === -1) types.push(n.type);+ });+ var typeCenters = {};+ types.forEach(function(t, ti) {+ var a = (2 * Math.PI * ti) / Math.max(types.length, 1) - Math.PI / 2;+ var cr = types.length > 1 ? Math.min(cw, ch) * 0.28 : 0;+ typeCenters[t] = { x: Math.cos(a) * cr, y: Math.sin(a) * cr };+ });+ graphSim.typeCenters = typeCenters;+ graphSim.clustered = state.graph.edges.length < state.graph.nodes.length / 2;+graphSim.nodes = state.graph.nodes.map(function(n, i) {- var angle = (2 * Math.PI * i) / Math.max(state.graph.nodes.length, 1);- var radius = Math.min(cw, ch) * 0.3;var deg = edgeMap[n.id] || 0;+ var c = typeCenters[n.type] || { x: 0, y: 0 };return {id: n.id, type: n.type, name: n.name, properties: n.properties,- x: Math.cos(angle) * radius + (Math.random() - 0.5) * 50,- y: Math.sin(angle) * radius + (Math.random() - 0.5) * 50,+ x: c.x + (Math.random() - 0.5) * 150,+ y: c.y + (Math.random() - 0.5) * 150,vx: 0, vy: 0,- r: Math.max(8, Math.min(22, 8 + deg * 2.5))+ r: Math.max(11, Math.min(22, 11 + deg * 2.5))};});graphSim.edges = state.graph.edges.slice();graphSim.running = true;graphSim.dragNode = null;+ graphSim.autoFitPending = true;setupGraphInteraction(canvas);runSimulation();@@ -2084,8 +2249,14 @@fx += (dx / dist) * force;fy += (dy / dist) * force;}- fx -= n.x * centerGravity;- fy -= n.y * centerGravity;+ if (graphSim.clustered && graphSim.typeCenters && graphSim.typeCenters[n.type]) {+ var tc = graphSim.typeCenters[n.type];+ fx += (tc.x - n.x) * 0.006;+ fy += (tc.y - n.y) * 0.006;+ } else {+ fx -= n.x * centerGravity;+ fy -= n.y * centerGravity;+ }var nvx = (n.vx + fx) * damping;var nvy = (n.vy + fy) * damping;// Velocity cap (#563): keep any single node from being launched@@ -2118,6 +2289,10 @@totalKineticEnergy += n.vx * n.vx + n.vy * n.vy;});+ if (graphSim.autoFitPending && graphSim.tickCount > 45) {+ graphSim.autoFitPending = false;+ fitGraphToView();+ }// park the simulation when the layout is quiet to save CPU.// Pick up again when a drag/interaction wakes the loop.var rmsVelocity = nodes.length > 0 ? Math.sqrt(totalKineticEnergy / nodes.length) : 0;@@ -2175,6 +2350,27 @@}}+ function fitGraphToView() {+ var canvas = graphSim.canvas;+ if (!canvas || graphSim.nodes.length === 0) return;+ var w = canvas.width / window.devicePixelRatio;+ var h = canvas.height / window.devicePixelRatio;+ var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ graphSim.nodes.forEach(function(n) {+ if (n.x < minX) minX = n.x;+ if (n.x > maxX) maxX = n.x;+ if (n.y < minY) minY = n.y;+ if (n.y > maxY) maxY = n.y;+ });+ var pad = 150;+ var spanX = (maxX - minX) + pad * 2;+ var spanY = (maxY - minY) + pad * 2;+ var z = Math.min(w / spanX, h / spanY);+ graphSim.zoom = Math.max(0.35, Math.min(1.4, z));+ graphSim.panX = w / 2 - ((minX + maxX) / 2) * graphSim.zoom;+ graphSim.panY = h / 2 - ((minY + maxY) / 2) * graphSim.zoom;+ }+function renderGraph() {var ctx = graphSim.ctx;var canvas = graphSim.canvas;@@ -2205,6 +2401,15 @@graphSim.nodes.forEach(function(n) { nodeMap[n.id] = n; });var searchActive = graphSearchTerm.length > 0;+ var drawnLabelRects = [];+ function labelFits(x, y, w2, h2) {+ for (var li = 0; li < drawnLabelRects.length; li++) {+ var r = drawnLabelRects[li];+ if (x < r.x + r.w && x + w2 > r.x && y < r.y + r.h && y + h2 > r.y) return false;+ }+ drawnLabelRects.push({ x: x, y: y, w: w2, h: h2 });+ return true;+ }var totalVisible = graphSim.nodes.filter(function(n) { return state.graph.filters[n.type]; }).length;var isDense = totalVisible > 40;var labelZoomThreshold = isDense ? 1.5 : 0.5;@@ -2303,7 +2508,7 @@var isSelected = selectedId === n.id;var isHovered = hoverNodeId === n.id;var matchesSearch = !searchActive || n.name.toLowerCase().includes(graphSearchTerm);- var isFocusFaded = focusNodeId && n.id !== focusNodeId && !graphSim.edges.some(function(ed) {+ var isFocusFaded = graphSim.edges.length > 0 && focusNodeId && n.id !== focusNodeId && !graphSim.edges.some(function(ed) {return (ed.sourceNodeId === focusNodeId && ed.targetNodeId === n.id) ||(ed.targetNodeId === focusNodeId && ed.sourceNodeId === n.id);});@@ -2356,6 +2561,7 @@var showLabel = matchesSearch && !isFocusFaded && (isSelected || isHovered ||(searchActive && matchesSearch) ||+ (totalVisible <= 30 && graphSim.zoom > 0.5) ||(!isDense && graphSim.zoom > labelZoomThreshold) ||(isDense && graphSim.zoom > labelZoomThreshold && n.r > 10));@@ -2370,7 +2576,13 @@var labelW = textW + (16 * zoomInv);var labelH = 20 * zoomInv;var labelY = n.y + n.r + (8 * zoomInv); // Top of the background pill-+ // Selected/hovered labels always win; others draw only into+ // free space so zoomed-out views degrade to fewer labels+ // instead of a pile of overlapping pills.+ if (!isSelected && !isHovered && !labelFits(n.x - labelW / 2, labelY, labelW, labelH)) {+ ctx.restore();+ return;+ }ctx.fillStyle = isDarkMode() ? 'rgba(30,30,35,0.92)' : 'rgba(255,255,255,0.92)';ctx.beginPath();ctx.roundRect ? ctx.roundRect(n.x - labelW / 2, labelY, labelW, labelH, 4 * zoomInv) : ctx.rect(n.x - labelW / 2, labelY, labelW, labelH);@@ -2401,7 +2613,7 @@async function loadMemories() {var el = document.getElementById('view-memories');- el.innerHTML = '<div class="loading">Loading memories...</div>';+ if (!state.memories.loaded) el.innerHTML = '<div class="loading">Loading memories...</div>';// cap at 2000 so the viewer remains responsive on large// corpora. Older endpoints returned the full unbounded list which// hit the iii invocation timeout and the UI fell through to 0.@@ -2484,7 +2696,8 @@var strength = Math.round(rawStrength <= 1 ? rawStrength * 100 : rawStrength * 10);if (strength > 100) strength = 100;var barColor = strength > 70 ? 'var(--green)' : strength > 40 ? 'var(--yellow)' : 'var(--red)';- html += '<tr>';+ var expanded = state.memories.selectedId === m.id;+ html += '<tr class="memory-row' + (expanded ? ' selected' : '') + '" data-action="select-memory" data-memory-id="' + esc(m.id) + '" role="button" tabindex="0" aria-expanded="' + (expanded ? 'true' : 'false') + '" style="cursor:pointer;">';var preview = (m.content || '').split('\n').slice(0, 2).join(' ').trim();var previewHtml = esc(truncate(preview, 150));if (search && search.length > 2) {@@ -2505,6 +2718,24 @@html += '<td style="font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">' + esc(formatTime(m.updatedAt)) + '</td>';html += '<td><button class="btn btn-danger" style="font-size:9px;padding:2px 8px;" data-action="delete-memory" data-memory-id="' + esc(m.id) + '" data-memory-title="' + esc(m.title || '') + '">Delete</button></td>';html += '</tr>';+ if (expanded) {+ html += '<tr class="memory-detail-row"><td colspan="6" style="background:var(--bg-alt);padding:14px 16px;">';+ html += '<div style="font-size:13px;color:var(--ink);white-space:pre-wrap;line-height:1.5;margin-bottom:10px;">' + esc(m.content || '') + '</div>';+ html += '<div style="display:flex;gap:16px;flex-wrap:wrap;font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);margin-bottom:10px;">';+ html += '<span>id: ' + esc(m.id) + '</span>';+ if (m.origin && m.origin.channel) {+ html += '<span>origin: ' + esc(m.origin.channel) + (m.origin.detail ? ' (' + esc(m.origin.detail) + ')' : '') + '</span>';+ }+ if (m.project) html += '<span>project: ' + esc(m.project) + '</span>';+ if (m.createdAt) html += '<span>created: ' + esc(formatTime(m.createdAt)) + '</span>';+ if (m.supersedes && m.supersedes.length > 0) html += '<span>supersedes: ' + esc(m.supersedes.join(', ')) + '</span>';+ if (m.files && m.files.length > 0) html += '<span>files: ' + esc(m.files.join(', ')) + '</span>';+ if (m.sessionIds && m.sessionIds.length > 0) html += '<span>sessions: ' + m.sessionIds.length + '</span>';+ html += '</div>';+ html += '<details><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary>';+ html += '<pre style="margin-top:8px;padding:10px;background:var(--bg);border:1px solid var(--border);font-size:11px;line-height:1.5;overflow-x:auto;">' + esc(JSON.stringify(m, null, 2)) + '</pre></details>';+ html += '</td></tr>';+ }});html += '</table>';}@@ -2546,13 +2777,19 @@async function loadTimeline() {var el = document.getElementById('view-timeline');- el.innerHTML = '<div class="loading">Loading timeline...</div>';+ if (!state.timeline.loaded) el.innerHTML = '<div class="loading">Loading timeline...</div>';var sessResult = await apiGet('sessions');var sessions = (sessResult && sessResult.sessions) || [];state.timeline.loaded = true;if (sessions.length > 0 && !state.timeline.sessionId) {- var sorted = sessions.slice().sort(function(a, b) { return (b.startedAt || '').localeCompare(a.startedAt || ''); });+ // Default to the session with the most observations — the newest+ // one is often a sparse just-started session, which made the tab+ // look empty on first open.+ var sorted = sessions.slice().sort(function(a, b) {+ return (b.observationCount || 0) - (a.observationCount || 0) ||+ (b.startedAt || '').localeCompare(a.startedAt || '');+ });var firstSelectable = sorted.find(function(s) { return sessionId(s); });state.timeline.sessionId = firstSelectable ? sessionId(firstSelectable) : '';}@@ -2692,7 +2929,7 @@html += '<span class="obs-time">' + esc(shortTime(o.timestamp)) + '</span>';html += '</div></div>';- if (o.subtitle) html += '<div class="obs-subtitle">' + esc(o.subtitle) + '</div>';+ if (o.subtitle) html += '<div class="obs-subtitle">' + esc(humanizeSubtitle(o.subtitle)) + '</div>';html += '<div style="margin-top:4px;">';html += '<span class="badge" style="border-color:' + typeColor + ';color:' + typeColor + ';margin-right:4px;">' + esc(type.replace(/_/g, ' ')) + '</span>';@@ -2772,7 +3009,7 @@async function loadActivity() {var el = document.getElementById('view-activity');- el.innerHTML = '<div class="loading">Loading activity...</div>';+ if (!state.activity.loaded) el.innerHTML = '<div class="loading">Loading activity...</div>';var results = await Promise.all([apiGet('sessions'),apiGet('audit?limit=200')@@ -2909,7 +3146,7 @@async function loadSessions() {var el = document.getElementById('view-sessions');- el.innerHTML = '<div class="loading">Loading sessions...</div>';+ if (!state.sessions.loaded) el.innerHTML = '<div class="loading">Loading sessions...</div>';var result = await apiGet('sessions');state.sessions.items = (result && result.sessions) || [];state.sessions.loaded = true;@@ -2922,7 +3159,7 @@return (b.startedAt || '').localeCompare(a.startedAt || '');});- var html = '<div class="session-list">';+ var html = '<div class="sessions-layout"><div class="session-list">';if (items.length === 0) {html += '<div class="empty-state"><div class="empty-icon">🗒</div><p>No sessions</p></div>';} else {@@ -2930,7 +3167,7 @@var statusBadge = s.status === 'active' ? 'badge-green' : s.status === 'completed' ? 'badge-blue' : 'badge-muted';var id = sessionId(s);var selected = id && state.sessions.selectedId === id;- html += '<div class="session-item' + (selected ? ' selected' : '') + '"' + (id ? ' data-action="select-session" data-session-id="' + esc(id) + '"' : '') + '>';+ html += '<div class="session-item' + (selected ? ' selected' : '') + '"' + (id ? ' data-action="select-session" data-session-id="' + esc(id) + '" role="button" tabindex="0" aria-expanded="' + (selected ? 'true' : 'false') + '"' : '') + '>';html += '<div class="session-top"><span class="session-project">' + esc(sessionDisplayName(s)) + '</span>';html += '<span class="badge ' + statusBadge + '">' + esc(s.status) + '</span></div>';var preview = s.firstPrompt || s.summary || '';@@ -2944,7 +3181,7 @@});}html += '</div>';- html += '<div id="session-detail"></div>';+ html += '<div id="session-detail"></div></div>';el.innerHTML = html;if (state.sessions.selectedId) renderSessionDetail();@@ -2953,6 +3190,18 @@function selectSession(id) {state.sessions.selectedId = state.sessions.selectedId === id ? null : id;renderSessions();+ // On the stacked layout (narrow screens) the detail renders below+ // the list; bring it into view. The wide two-pane layout keeps the+ // panel sticky beside the list, so no scroll is needed there.+ if (+ state.sessions.selectedId &&+ window.matchMedia('(max-width: 1100px)').matches+ ) {+ var panel = document.getElementById('session-detail');+ if (panel && panel.scrollIntoView) {+ panel.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+ }}async function renderSessionDetail() {@@ -3076,7 +3325,7 @@async function loadLessons() {var el = document.getElementById('view-lessons');- el.innerHTML = '<div class="loading">Loading lessons...</div>';+ if (!state.lessons.loaded) el.innerHTML = '<div class="loading">Loading lessons...</div>';var result = await apiGet('lessons');state.lessons.items = (result && result.lessons) || [];state.lessons.loaded = true;@@ -3108,16 +3357,17 @@html += '<div class="empty-state">' +'<div class="empty-icon">💡</div>' +'<div class="empty-title">No lessons yet</div>' +- '<div class="empty-lead">Lessons are confidence-scored pattern observations — things you corrected once that the agent should never do again. They persist across projects.</div>' ++ '<div class="empty-lead">Lessons are short imperative rules (always/never/prefer/avoid) learned from past work — things you corrected once that the agent should never repeat. Confidence grows when they hold and decays when unused.</div>' +'<pre class="empty-cmd"># Save a lesson explicitly\nmemory_lesson_save { rule, reason, confidence }\n\n# Or: Replay tab → Import JSONL auto-extracts lessons\n# from your past Claude Code sessions</pre>' +'<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#lessons" target="_blank" rel="noopener">Lesson decay & scoring →</a></div>' +'</div>';} else {- html += '<table><thead><tr><th>Lesson</th><th>Confidence</th><th>Reinforcements</th><th>Source</th><th>Project</th><th>Updated</th></tr></thead><tbody>';+ html += '<table><thead><tr><th>Lesson</th><th title="How battle-tested the rule is. Grows each time it is reinforced, decays weekly when unused.">Confidence</th><th title="Times the agent re-confirmed this rule.">Uses</th><th>Source</th><th>Project</th><th>Updated</th></tr></thead><tbody>';items.forEach(function(l) {var confPct = Math.round(l.confidence * 100);var confColor = confPct >= 70 ? 'var(--green)' : confPct >= 40 ? 'var(--yellow)' : 'var(--red)';- html += '<tr>';+ var expanded = state.lessons.selectedId === l.id;+ html += '<tr class="lesson-row' + (expanded ? ' selected' : '') + '" data-action="select-lesson" data-lesson-id="' + esc(l.id) + '" role="button" tabindex="0" aria-expanded="' + (expanded ? 'true' : 'false') + '" style="cursor:pointer;">';html += '<td style="max-width:400px;">' + esc(truncate(l.content, 120)) + (l.context ? '<div style="font-size:11px;color:var(--ink-faint);margin-top:2px;">' + esc(truncate(l.context, 80)) + '</div>' : '') + '</td>';html += '<td><div class="gauge" style="min-width:80px;"><div class="gauge-bar"><div class="gauge-fill" style="width:' + confPct + '%;background:' + confColor + '"></div></div><span class="gauge-value" style="font-size:11px;">' + confPct + '%</span></div></td>';html += '<td style="text-align:center;">' + (l.reinforcements || 0) + '</td>';@@ -3125,6 +3375,21 @@html += '<td style="font-size:12px;color:var(--ink-muted);">' + esc(l.project || '-') + '</td>';html += '<td style="font-size:12px;color:var(--ink-muted);">' + shortTime(l.updatedAt) + '</td>';html += '</tr>';+ if (expanded) {+ html += '<tr class="lesson-detail-row"><td colspan="6" style="background:var(--bg-alt);padding:14px 16px;">';+ html += '<div style="font-size:13px;color:var(--ink);white-space:pre-wrap;line-height:1.5;margin-bottom:8px;">' + esc(l.content) + '</div>';+ if (l.context) html += '<div style="font-size:12px;color:var(--ink-muted);margin-bottom:8px;"><span style="font-family:var(--font-ui);font-size:10px;text-transform:uppercase;letter-spacing:0.1em;">Why learned</span><br>' + esc(l.context) + '</div>';+ html += '<div style="display:flex;gap:16px;flex-wrap:wrap;font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);margin-bottom:8px;">';+ html += '<span>id: ' + esc(l.id) + '</span>';+ if (l.tags && l.tags.length) html += '<span>tags: ' + esc(l.tags.join(', ')) + '</span>';+ if (l.createdAt) html += '<span>learned: ' + esc(formatTime(l.createdAt)) + '</span>';+ if (l.lastReinforcedAt) html += '<span>last confirmed: ' + esc(formatTime(l.lastReinforcedAt)) + '</span>';+ if (l.sourceIds && l.sourceIds.length) html += '<span>from ' + l.sourceIds.length + ' session(s)</span>';+ html += '</div>';+ html += '<details><summary style="cursor:pointer;font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">raw record</summary>';+ html += '<pre style="margin-top:8px;padding:10px;background:var(--bg);border:1px solid var(--border);font-size:11px;line-height:1.5;overflow-x:auto;">' + esc(JSON.stringify(l, null, 2)) + '</pre></details>';+ html += '</td></tr>';+ }});html += '</tbody></table>';}@@ -3138,7 +3403,7 @@async function loadActions() {var el = document.getElementById('view-actions');- el.innerHTML = '<div class="loading">Loading actions...</div>';+ if (!state.actions.loaded) el.innerHTML = '<div class="loading">Loading actions...</div>';var results = await Promise.all([apiGet('actions'), apiGet('frontier')]);state.actions.items = (results[0] && results[0].actions) || [];state.actions.frontier = (results[1] && (results[1].frontier || results[1].actions)) || [];@@ -3149,6 +3414,10 @@function renderActions() {var el = document.getElementById('view-actions');var items = state.actions.items;+ var introCard = '<div class="card" style="margin-bottom:12px;padding:12px;background:var(--bg-subtle);">' ++ '<div style="font-size:13px;color:var(--ink-muted);line-height:1.5;">' ++ '<strong>Actions</strong> are follow-ups the agent surfaced during sessions — decisions to revisit, files to inspect, tasks blocked on input. Status flows pending → active → done/blocked; the <em>frontier</em> marks what is unblocked and ready to pick up next.' ++ '</div></div>';var search = state.actions.search.toLowerCase();var statusFilter = state.actions.statusFilter;var frontierIds = new Set((state.actions.frontier || []).map(function(a) { return a.id; }));@@ -3162,7 +3431,8 @@items = items.filter(function(a) { return a.status === statusFilter; });}- var html = '<div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;">';+ var html = introCard;+ html += '<div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;">';html += '<input id="actions-search" class="search-input" type="text" placeholder="Search actions..." value="' + esc(state.actions.search) + '" style="flex:1;min-width:200px" />';html += '<select id="actions-status-filter" style="padding:4px 8px;font-size:12px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--ink);">';html += '<option value="">All statuses</option>';@@ -3213,7 +3483,7 @@async function loadCrystals() {var el = document.getElementById('view-crystals');- el.innerHTML = '<div class="loading">Loading crystals...</div>';+ if (!state.crystals.loaded) el.innerHTML = '<div class="loading">Loading crystals...</div>';var results = await Promise.all([apiGet('crystals'), apiGet('lessons')]);state.crystals.items = (results[0] && results[0].crystals) || [];var lessonMap = {};@@ -3264,7 +3534,7 @@html += '<div class="empty-state">' +'<div class="empty-icon">💎</div>' +'<div class="empty-title">No crystals yet</div>' +- '<div class="empty-lead">Crystals are compressed action digests — the 3-line summary of what happened in a session. Generated from long conversations to give the next session fast context without re-reading everything.</div>' ++ '<div class="empty-lead">Crystals are frozen snapshots of completed work — one session’s narrative, key outcomes, files touched, and lessons surfaced, kept after raw observations are pruned so the next session gets fast context.</div>' +'<pre class="empty-cmd"># Auto: import a JSONL transcript\n# Replay tab → Import JSONL\n\n# Manual: crystallize a specific session\nmemory_crystallize { sessionId }</pre>' +'<div><a class="empty-link" href="https://github.com/rohitg00/agentmemory#crystals" target="_blank" rel="noopener">Crystal pipeline →</a></div>' +'</div>';@@ -3326,7 +3596,7 @@async function loadAudit() {var el = document.getElementById('view-audit');- el.innerHTML = '<div class="loading">Loading audit log...</div>';+ if (!state.audit.loaded) el.innerHTML = '<div class="loading">Loading audit log...</div>';var result = await apiGet('audit?limit=100');state.audit.entries = (result && result.entries) || [];state.audit.loaded = true;@@ -3450,7 +3720,7 @@html += '<div class="card"><div class="card-title">Top Concepts</div>';var concepts = p.topConcepts || [];if (concepts.length === 0) {- html += '<div style="font-size:13px;color:var(--ink-faint);font-style:italic;">No concepts yet</div>';+ html += '<div style="font-size:13px;color:var(--ink-faint);line-height:1.5;">No concepts yet. Concepts are tagged when observations are compressed by an LLM (<code>AGENTMEMORY_AUTO_COMPRESS=true</code> + provider key) or attached to saved memories.</div>';} else {var maxC = Math.max.apply(null, concepts.map(function(c) { return c.frequency; })) || 1;html += '<div class="bar-chart">';@@ -3859,6 +4129,17 @@}});fetchFlags();+ // Keyboard activation for role="button" cards (session items). Click+ // delegation alone leaves them unreachable for keyboard and AT users.+ document.addEventListener('keydown', function(e) {+ if (e.key !== 'Enter' && e.key !== ' ') return;+ if (!(e.target instanceof Element)) return;+ var card = e.target.closest('[data-action][role="button"], [data-action][role="link"]');+ if (!card) return;+ e.preventDefault();+ card.click();+ });+document.addEventListener('click', function(e) {if (!(e.target instanceof Element)) return;var target = e.target.closest('[data-action]');@@ -3939,6 +4220,27 @@if (sessionId) selectSession(sessionId);return;}+ if (action === 'goto-tab') {+ var gotoTab = target.getAttribute('data-tab');+ if (gotoTab) switchTab(gotoTab);+ return;+ }+ if (action === 'select-lesson') {+ var lsnId = target.getAttribute('data-lesson-id');+ if (lsnId) {+ state.lessons.selectedId = state.lessons.selectedId === lsnId ? null : lsnId;+ renderLessons();+ }+ return;+ }+ if (action === 'select-memory') {+ var memId = target.getAttribute('data-memory-id');+ if (memId) {+ state.memories.selectedId = state.memories.selectedId === memId ? null : memId;+ renderMemories();+ }+ return;+ }if (action === 'end-session') {var endSessionId = target.getAttribute('data-session-id');if (endSessionId) endSession(endSessionId);@@ -4188,8 +4490,83 @@});switchTab(tabFromRoute(), { replaceRoute: true });- connectWs();+ // Resolve the stream WebSocket target from the server before the first+ // connect. The old viewerPort-1 arithmetic breaks whenever the viewer+ // binds a fallback port (3113 taken → viewer on 3114 → 3113 is another+ // HTTP server, not the streams endpoint) — every retry then fails and+ // the viewer silently degrades to 10s polling.+ (async function initWs() {+ try {+ var live = await api('livez', { signal: AbortSignal.timeout(5000) });+ if (live && typeof live.streamsPort === 'number' && live.streamsPort > 0) {+ WS_URL = wsProto + '//' + window.location.hostname + ':' + live.streamsPort;+ WS_DIRECT_URL = WS_URL + '/stream/mem-live/viewer';+ }+ } catch (_) {}+ connectWs();+ })();startDashboardAutoRefresh();++ // Ambient background: an ordered-dither dot field that drifts very+ // slowly — the print-halftone cousin of the old static dot grid.+ // Renders at quarter resolution and ~12fps; a single static frame+ // under prefers-reduced-motion.+ (function ditherField() {+ var cv = document.getElementById('bg-dither');+ if (!cv || !cv.getContext) return;+ var ctx = cv.getContext('2d');+ var BAYER = [+ [0, 8, 2, 10],+ [12, 4, 14, 6],+ [3, 11, 1, 9],+ [15, 7, 13, 5]+ ];+ var CELL = 7;+ var t = 0;+ var reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;++ function dotColor() {+ return document.documentElement.getAttribute('data-theme') === 'dark'+ ? 'rgba(150, 154, 162, 0.16)'+ : 'rgba(90, 90, 84, 0.14)';+ }++ function draw() {+ var w = cv.width = Math.ceil(window.innerWidth / 2);+ var h = cv.height = Math.ceil(window.innerHeight / 2);+ ctx.clearRect(0, 0, w, h);+ ctx.fillStyle = dotColor();+ var cols = Math.ceil(w / CELL) + 1;+ var rows = Math.ceil(h / CELL) + 1;+ for (var y = 0; y < rows; y++) {+ for (var x = 0; x < cols; x++) {+ // Slow luminance swells drifting diagonally; the Bayer+ // threshold turns them into stable ordered-dither dots.+ var v =+ 0.5 ++ 0.5 *+ Math.sin(x * 0.11 + t * 0.013) *+ Math.cos(y * 0.13 - t * 0.011);+ if (v * 16 > BAYER[y % 4][x % 4] + 6.5) {+ ctx.fillRect(x * CELL, y * CELL, 1.4, 1.4);+ }+ }+ }+ }++ draw();+ if (!reduced) {+ setInterval(function () {+ t++;+ draw();+ }, 85);+ }+ window.addEventListener('resize', draw);+ new MutationObserver(draw).observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['data-theme']+ });+ })();</script></body></html>diff --git a/test/cli-connect.test.ts b/test/cli-connect.test.tsindex ce43ac83..2e9bc4ca 100644--- a/test/cli-connect.test.ts+++ b/test/cli-connect.test.ts@@ -52,6 +52,7 @@ describe("agentmemory connect — dispatcher", () => {"continue","cursor","droid",+ "dsh","gemini-cli","hermes","kiro",@@ -64,7 +65,7 @@ describe("agentmemory connect — dispatcher", () => {"zed",].sort(),);- expect(ADAPTERS.length).toBe(19);+ expect(ADAPTERS.length).toBe(20);});it("every adapter exposes detect() and install()", () => {@@ -496,9 +497,4 @@ describe("agentmemory connect — stub adapters log + return stub", () => {expect(result.kind).toBe("stub");});- it("pi adapter returns stub", async () => {- const { adapter } = await import("../src/cli/connect/pi.js");- const result = await adapter.install({ dryRun: false, force: false });- expect(result.kind).toBe("stub");- });});diff --git a/test/connect-dsh.test.ts b/test/connect-dsh.test.tsnew file mode 100644index 00000000..3ffcbbb2--- /dev/null+++ b/test/connect-dsh.test.ts@@ -0,0 +1,186 @@+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";+import {+ mkdtempSync,+ mkdirSync,+ rmSync,+ readFileSync,+ writeFileSync,+ existsSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++// DeepSeek Harness adapter: appends an @deepseek-ai/dsh-mcp-client row to+// the home-level $DSH_HOME/cordis.patch.yml, the machine-local patch layer+// every profile loads.++function freshHome(): string {+ return mkdtempSync(join(tmpdir(), "am-dsh-"));+}++describe("connect: DeepSeek Harness", () => {+ let home: string;+ const ORIG_HOME = process.env["HOME"];+ const ORIG_USERPROFILE = process.env["USERPROFILE"];+ const ORIG_DSH_HOME = process.env["DSH_HOME"];++ beforeEach(() => {+ home = freshHome();+ vi.resetModules();+ process.env["HOME"] = home;+ process.env["USERPROFILE"] = home;+ delete process.env["DSH_HOME"];+ });+ afterEach(() => {+ if (ORIG_HOME === undefined) delete process.env["HOME"];+ else process.env["HOME"] = ORIG_HOME;+ if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"];+ else process.env["USERPROFILE"] = ORIG_USERPROFILE;+ if (ORIG_DSH_HOME === undefined) delete process.env["DSH_HOME"];+ else process.env["DSH_HOME"] = ORIG_DSH_HOME;+ rmSync(home, { recursive: true, force: true });+ });++ it("does not detect when ~/.dsh/ is absent", async () => {+ const { adapter } = await import("../src/cli/connect/dsh.js");+ expect(adapter.detect()).toBe(false);+ });++ it("honors DSH_HOME over ~/.dsh", async () => {+ const custom = join(home, "custom-dsh");+ mkdirSync(custom, { recursive: true });+ process.env["DSH_HOME"] = custom;+ const { adapter } = await import("../src/cli/connect/dsh.js");+ expect(adapter.detect()).toBe(true);+ await adapter.install({ dryRun: false, force: false });+ expect(existsSync(join(custom, "cordis.patch.yml"))).toBe(true);+ });++ it("appends the mcp-client row to a fresh cordis.patch.yml", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch).toContain("- insert:");+ expect(patch).toContain("name: '@deepseek-ai/dsh-mcp-client'");+ expect(patch).toContain("serverName: agentmemory");+ expect(patch).toContain("transport: stdio");+ expect(patch).toContain("args: ['-y', '@agentmemory/mcp']");+ expect(patch).toContain("AGENTMEMORY_URL: http://localhost:3111");+ });++ it("preserves existing patch rows when appending", async () => {+ const dir = join(home, ".dsh");+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "cordis.patch.yml"),+ "- id: hmr\n disabled: true\n",+ "utf-8",+ );+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false });+ const patch = readFileSync(join(dir, "cordis.patch.yml"), "utf-8");+ expect(patch).toContain("- id: hmr");+ expect(patch).toContain("serverName: agentmemory");+ });++ it("is idempotent without --force", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false });+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("already-wired");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);+ });++ it("--force replaces the existing row instead of duplicating", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false });+ const result = await adapter.install({ dryRun: false, force: true });+ expect(result.kind).toBe("installed");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);+ expect(patch.match(/- insert:/g)).toHaveLength(1);+ });++ it("dry-run mutates nothing", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ const result = await adapter.install({ dryRun: true, force: false });+ expect(result.kind).toBe("installed");+ expect(existsSync(join(home, ".dsh", "cordis.patch.yml"))).toBe(false);+ });++ it("--with-hooks writes the manifest and the hooks-claude-code row", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ const result = await adapter.install({+ dryRun: false,+ force: false,+ withHooks: true,+ });+ expect(result.kind).toBe("installed");++ const hooksPath = join(home, ".dsh", "agentmemory.hooks.json");+ expect(existsSync(hooksPath)).toBe(true);+ const manifest = JSON.parse(readFileSync(hooksPath, "utf-8"));+ // Bridge-supported events from the bundled Claude Code shaped manifest.+ for (const ev of ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"]) {+ expect(manifest.hooks[ev]).toBeDefined();+ }+ // Commands are resolved to absolute paths, no env placeholders left.+ const flat = JSON.stringify(manifest);+ expect(flat).not.toContain("${CLAUDE_PLUGIN_ROOT}");++ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch).toContain("id: agentmemory-hooks");+ expect(patch).toContain("name: '@deepseek-ai/dsh-hooks-claude-code'");+ expect(patch).toContain(`configPath: ${JSON.stringify(hooksPath)}`);+ // MCP row still present alongside.+ expect(patch).toContain("serverName: agentmemory");+ });++ it("MCP-only install after --with-hooks keeps the hooks row intact", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false, withHooks: true });+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("already-wired");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch).toContain("id: agentmemory-hooks");+ expect(patch).toContain("serverName: agentmemory");+ });++ it("--with-hooks after MCP-only adds the hooks row without duplicating MCP", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false });+ const result = await adapter.install({+ dryRun: false,+ force: false,+ withHooks: true,+ });+ expect(result.kind).toBe("installed");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);+ expect(patch.match(/id: agentmemory-hooks/g)).toHaveLength(1);+ });++ it("--force --with-hooks replaces both rows without duplicating", async () => {+ mkdirSync(join(home, ".dsh"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/dsh.js");+ await adapter.install({ dryRun: false, force: false, withHooks: true });+ const result = await adapter.install({+ dryRun: false,+ force: true,+ withHooks: true,+ });+ expect(result.kind).toBe("installed");+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");+ expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);+ expect(patch.match(/id: agentmemory-hooks/g)).toHaveLength(1);+ });+});diff --git a/test/connect-pi.test.ts b/test/connect-pi.test.tsnew file mode 100644index 00000000..d7736199--- /dev/null+++ b/test/connect-pi.test.ts@@ -0,0 +1,133 @@+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";+import {+ mkdtempSync,+ mkdirSync,+ rmSync,+ readFileSync,+ readdirSync,+ writeFileSync,+ existsSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++// pi adapter: copies the bundled integrations/pi extension into+// ~/.pi/agent/extensions/agentmemory/, which pi auto-discovers via its+// */index.ts rule — no settings.json edit needed.++function freshHome(): string {+ return mkdtempSync(join(tmpdir(), "am-pi-"));+}++describe("connect: pi", () => {+ let home: string;+ const ORIG_HOME = process.env["HOME"];+ const ORIG_USERPROFILE = process.env["USERPROFILE"];++ beforeEach(() => {+ home = freshHome();+ vi.resetModules();+ process.env["HOME"] = home;+ process.env["USERPROFILE"] = home;+ });+ afterEach(() => {+ if (ORIG_HOME === undefined) delete process.env["HOME"];+ else process.env["HOME"] = ORIG_HOME;+ if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"];+ else process.env["USERPROFILE"] = ORIG_USERPROFILE;+ rmSync(home, { recursive: true, force: true });+ });++ const extDir = () => join(home, ".pi", "agent", "extensions", "agentmemory");++ it("does not detect when ~/.pi/ is absent", async () => {+ const { adapter } = await import("../src/cli/connect/pi.js");+ expect(adapter.detect()).toBe(false);+ });++ it("copies index.ts and security.ts into the auto-discovered extension dir", async () => {+ mkdirSync(join(home, ".pi"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/pi.js");+ expect(adapter.detect()).toBe(true);+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");++ const index = readFileSync(join(extDir(), "index.ts"), "utf-8");+ const security = readFileSync(join(extDir(), "security.ts"), "utf-8");+ expect(index).toContain("@earendil-works/pi-coding-agent");+ expect(index).toContain("./security.js");+ expect(security.length).toBeGreaterThan(0);+ expect(index).toBe(readFileSync("integrations/pi/index.ts", "utf-8"));+ });++ it("is idempotent when the installed copy matches", async () => {+ mkdirSync(join(home, ".pi"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/pi.js");+ await adapter.install({ dryRun: false, force: false });+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("already-wired");+ });++ it("refreshes a stale installed copy", async () => {+ mkdirSync(extDir(), { recursive: true });+ writeFileSync(join(extDir(), "index.ts"), "// stale\n", "utf-8");+ const { adapter } = await import("../src/cli/connect/pi.js");+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");+ expect(readFileSync(join(extDir(), "index.ts"), "utf-8")).toBe(+ readFileSync("integrations/pi/index.ts", "utf-8"),+ );+ });++ it("backs up every modified extension file before overwriting", async () => {+ mkdirSync(extDir(), { recursive: true });+ writeFileSync(join(extDir(), "index.ts"), "// stale index\n", "utf-8");+ writeFileSync(join(extDir(), "security.ts"), "// stale security\n", "utf-8");+ const { adapter } = await import("../src/cli/connect/pi.js");+ const result = await adapter.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");++ const backups = readdirSync(join(home, ".agentmemory", "backups"));+ const indexBackup = backups.find((f) => f.startsWith("pi-index-"));+ const securityBackup = backups.find((f) => f.startsWith("pi-security-"));+ expect(indexBackup).toBeDefined();+ expect(securityBackup).toBeDefined();+ expect(+ readFileSync(join(home, ".agentmemory", "backups", indexBackup!), "utf-8"),+ ).toBe("// stale index\n");+ expect(+ readFileSync(join(home, ".agentmemory", "backups", securityBackup!), "utf-8"),+ ).toBe("// stale security\n");+ });++ it("dry-run mutates nothing", async () => {+ mkdirSync(join(home, ".pi"), { recursive: true });+ const { adapter } = await import("../src/cli/connect/pi.js");+ const result = await adapter.install({ dryRun: true, force: false });+ expect(result.kind).toBe("installed");+ expect(existsSync(extDir())).toBe(false);+ });+});++describe("integrations/pi is a valid pi package", () => {+ it("package.json declares the pi manifest, keyword, and peer deps", () => {+ const pkg = JSON.parse(readFileSync("integrations/pi/package.json", "utf-8"));+ expect(pkg.keywords).toContain("pi-package");+ expect(pkg.pi.extensions).toEqual(["./index.ts"]);+ expect(pkg.peerDependencies["@earendil-works/pi-coding-agent"]).toBe("*");+ expect(pkg.peerDependencies["typebox"]).toBe("*");+ // Local pi package only — never published to npm.+ expect(pkg.private).toBe(true);+ });++ it("the npm package ships integrations/pi", () => {+ const root = JSON.parse(readFileSync("package.json", "utf-8"));+ expect(root.files).toContain("integrations/pi/");+ });++ it("extension imports the current pi core package name", () => {+ const index = readFileSync("integrations/pi/index.ts", "utf-8");+ expect(index).toContain("@earendil-works/pi-coding-agent");+ expect(index).not.toContain("@mariozechner/pi-coding-agent");+ });+});diff --git a/test/fallback-model-resolution.test.ts b/test/fallback-model-resolution.test.tsindex 91a82116..779d4b68 100644--- a/test/fallback-model-resolution.test.ts+++ b/test/fallback-model-resolution.test.ts@@ -106,11 +106,11 @@ describe("Fallback provider model resolution (#778)", () => {it("primary OpenAI + fallback Gemini: Gemini is built with GEMINI_MODEL, NOT the primary's model", () => {process.env.OPENAI_API_KEY = "sk-openai";process.env.GEMINI_API_KEY = "gemini-key";- process.env.GEMINI_MODEL = "gemini-2.5-flash";+ process.env.GEMINI_MODEL = "gemini-3.7-flash";const primary: ProviderConfig = {provider: "openai",- model: "gpt-4o-mini",+ model: "gpt-5.6-luna",maxTokens: 4096,};const fallback: FallbackConfig = { providers: ["gemini"] };@@ -119,9 +119,9 @@ describe("Fallback provider model resolution (#778)", () => {const openaiCall = captured.find((c) => c.provider === "openai");const geminiCall = captured.find((c) => c.provider === "gemini");- expect(openaiCall?.model).toBe("gpt-4o-mini");- expect(geminiCall?.model).toBe("gemini-2.5-flash");- expect(geminiCall?.model).not.toBe("gpt-4o-mini");+ expect(openaiCall?.model).toBe("gpt-5.6-luna");+ expect(geminiCall?.model).toBe("gemini-3.7-flash");+ expect(geminiCall?.model).not.toBe("gpt-5.6-luna");});it("Gemini fallback uses the documented default when GEMINI_MODEL is unset", () => {@@ -129,12 +129,12 @@ describe("Fallback provider model resolution (#778)", () => {process.env.GEMINI_API_KEY = "gemini-key";createFallbackProvider(- { provider: "openai", model: "gpt-4o-mini", maxTokens: 4096 },+ { provider: "openai", model: "gpt-5.6-luna", maxTokens: 4096 },{ providers: ["gemini"] },);const geminiCall = captured.find((c) => c.provider === "gemini");- expect(geminiCall?.model).toBe("gemini-2.5-flash");+ expect(geminiCall?.model).toBe("gemini-3.7-flash");});it("primary Anthropic + fallback OpenAI + Minimax: each fallback uses its own default", () => {@@ -146,7 +146,7 @@ describe("Fallback provider model resolution (#778)", () => {createFallbackProvider({provider: "anthropic",- model: "claude-sonnet-4-20250514",+ model: "claude-sonnet-5",maxTokens: 4096,},{ providers: ["openai", "minimax"] },@@ -155,10 +155,10 @@ describe("Fallback provider model resolution (#778)", () => {const openai = captured.find((c) => c.provider === "openai");const minimax = captured.find((c) => c.provider === "minimax");expect(openai?.model).toBe("gpt-5");- expect(minimax?.model).toBe("MiniMax-M2.7");+ expect(minimax?.model).toBe("MiniMax-M3");// Neither inherits the Anthropic model name.- expect(openai?.model).not.toBe("claude-sonnet-4-20250514");- expect(minimax?.model).not.toBe("claude-sonnet-4-20250514");+ expect(openai?.model).not.toBe("claude-sonnet-5");+ expect(minimax?.model).not.toBe("claude-sonnet-5");});it("env override on the fallback provider's MODEL var wins over the default", () => {@@ -167,7 +167,7 @@ describe("Fallback provider model resolution (#778)", () => {process.env.GEMINI_MODEL = "gemini-2.5-pro";createFallbackProvider(- { provider: "openai", model: "gpt-4o-mini", maxTokens: 4096 },+ { provider: "openai", model: "gpt-5.6-luna", maxTokens: 4096 },{ providers: ["gemini"] },);@@ -180,7 +180,7 @@ describe("Fallback provider model resolution (#778)", () => {process.env.OPENAI_API_KEY = "sk";createFallbackProvider(- { provider: "openai", model: "gpt-4o-mini", maxTokens: 4096 },+ { provider: "openai", model: "gpt-5.6-luna", maxTokens: 4096 },{ providers: ["openai", "gemini"] },);diff --git a/test/fetch-timeout.test.ts b/test/fetch-timeout.test.tsindex 03bf9580..f4a42867 100644--- a/test/fetch-timeout.test.ts+++ b/test/fetch-timeout.test.ts@@ -326,7 +326,7 @@ describe("Provider hang regression — MinimaxProvider", () => {});it("compress() aborts after timeout when upstream hangs", async () => {- const provider = new MinimaxProvider("test-key", "MiniMax-M2.7", 800);+ const provider = new MinimaxProvider("test-key", "MiniMax-M3", 800);await expect(provider.compress("system", "user")).rejects.toThrow();});});@@ -344,7 +344,7 @@ describe("Provider hang regression — OpenRouterProvider (covers Gemini LLM patit("compress() aborts after timeout when upstream hangs", async () => {const provider = new OpenRouterProvider("test-key",- "gemini-2.5-flash",+ "gemini-3.7-flash",1024,"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",);@@ -454,7 +454,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {it("OPENAI_TIMEOUT_MS alone aborts the OpenAI LLM call", async () => {process.env["OPENAI_TIMEOUT_MS"] = "30";- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);await expect(provider.compress("system", "user")).rejects.toThrow(/timed out after 30ms/,);@@ -462,7 +462,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {it("AGENTMEMORY_LLM_TIMEOUT_MS alone aborts the OpenAI LLM call", async () => {process.env["AGENTMEMORY_LLM_TIMEOUT_MS"] = "30";- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);await expect(provider.compress("system", "user")).rejects.toThrow(/timed out after 30ms/,);@@ -474,7 +474,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {// we'd time out at 5000ms and the test would hang past the 5s// vitest default. We assert the message ms to lock the precedence.process.env["AGENTMEMORY_LLM_TIMEOUT_MS"] = "5000";- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);await expect(provider.compress("system", "user")).rejects.toThrow(/timed out after 30ms/,);@@ -484,7 +484,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {// We don't actually wait 60s — the provider stores timeoutMs at// construction. Construct, then assert the bound via the error// message after the hang aborts at a tiny pre-set value.- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);// Access the resolved timeout via the constructed field name. The// class keeps `timeoutMs` private; reaching in via the index// access keeps the test on the public observed behaviour: the ms@@ -503,7 +503,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {// silently swallow.for (const bad of ["30ms", "1_000", "60s", "30abc", "-30", "0"]) {process.env["OPENAI_TIMEOUT_MS"] = bad;- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);const ms = (provider as unknown as { timeoutMs: number }).timeoutMs;expect(ms).toBe(60_000);delete process.env["OPENAI_TIMEOUT_MS"];@@ -547,7 +547,7 @@ describe("OpenAIProvider thinking-model fallback (#627)", () => {},],});- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);const out = await provider.compress("system", "user");expect(out).toBe("thinking-mode output");});@@ -556,7 +556,7 @@ describe("OpenAIProvider thinking-model fallback (#627)", () => {mockOpenAIResponse({choices: [{ message: { content: "", reasoning: "older shape" } }],});- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);const out = await provider.compress("system", "user");expect(out).toBe("older shape");});@@ -573,7 +573,7 @@ describe("OpenAIProvider thinking-model fallback (#627)", () => {},],});- const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);+ const provider = new OpenAIProvider("test-key", "gpt-5.6-luna", 1024);const out = await provider.compress("system", "user");expect(out).toBe("real content");});diff --git a/test/graph-heuristic-extract.test.ts b/test/graph-heuristic-extract.test.tsnew file mode 100644index 00000000..f3bfec80--- /dev/null+++ b/test/graph-heuristic-extract.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect } from "vitest";+import { readFileSync } from "node:fs";+import { extractGraphHeuristics } from "../src/functions/graph.js";+import type { CompressedObservation } from "../src/types.js";++function obs(+ id: string,+ files: string[],+ concepts: string[],+): CompressedObservation {+ return {+ id,+ sessionId: "ses_1",+ timestamp: new Date().toISOString(),+ type: "file_edit",+ title: `obs ${id}`,+ facts: [],+ narrative: "",+ concepts,+ files,+ importance: 0.5,+ };+}++describe("extractGraphHeuristics", () => {+ it("builds file and concept nodes from structured fields", () => {+ const { nodes } = extractGraphHeuristics([+ obs("o1", ["src/auth.ts"], ["authentication", "jwt"]),+ ]);+ const byType = new Map(nodes.map((n) => [`${n.type}:${n.name}`, n]));+ expect(byType.has("file:src/auth.ts")).toBe(true);+ expect(byType.has("concept:authentication")).toBe(true);+ expect(byType.has("concept:jwt")).toBe(true);+ });++ it("links concepts to files and consecutive siblings as related_to", () => {+ const { nodes, edges } = extractGraphHeuristics([+ obs("o1", ["a.ts", "b.ts"], ["caching"]),+ ]);+ expect(edges.every((e) => e.type === "related_to")).toBe(true);+ const names = new Map(nodes.map((n) => [n.id, n.name]));+ const pairs = edges.map(+ (e) => `${names.get(e.sourceNodeId)}|${names.get(e.targetNodeId)}`,+ );+ expect(pairs).toContain("caching|a.ts");+ expect(pairs).toContain("caching|b.ts");+ expect(pairs).toContain("a.ts|b.ts");+ });++ it("merges repeated entities across observations instead of duplicating", () => {+ const { nodes } = extractGraphHeuristics([+ obs("o1", ["src/auth.ts"], []),+ obs("o2", ["src/auth.ts"], []),+ ]);+ expect(nodes).toHaveLength(1);+ expect(nodes[0].sourceObservationIds).toEqual(["o1", "o2"]);+ });++ it("dedupes case-insensitively and skips blank names", () => {+ const { nodes } = extractGraphHeuristics([+ obs("o1", [], ["JWT", "jwt", " "]),+ ]);+ expect(nodes).toHaveLength(1);+ });++ it("caps edges per observation", () => {+ const many = obs(+ "o1",+ Array.from({ length: 10 }, (_, i) => `f${i}.ts`),+ Array.from({ length: 10 }, (_, i) => `c${i}`),+ );+ const { edges } = extractGraphHeuristics([many]);+ expect(edges.length).toBeLessThanOrEqual(12);+ });++ it("never emits self edges or duplicate pairs", () => {+ const { edges } = extractGraphHeuristics([+ obs("o1", ["a.ts"], ["a"]),+ obs("o2", ["a.ts"], ["a"]),+ ]);+ const seen = new Set<string>();+ for (const e of edges) {+ expect(e.sourceNodeId).not.toBe(e.targetNodeId);+ const key = [e.sourceNodeId, e.targetNodeId].sort().join("|");+ expect(seen.has(key)).toBe(false);+ seen.add(key);+ }+ });+});++// The structural pass must run keyless: session end always fires+// mem::graph-extract, and the function itself gates only the LLM pass+// on the flag plus a real provider.+describe("keyless graph extraction wiring", () => {+ it("event::session::stopped fires graph-extract without the flag gate", () => {+ const events = readFileSync("src/triggers/events.ts", "utf-8");+ const stopped = events.slice(events.indexOf("event::session::stopped"));+ const gate = stopped.indexOf("isGraphExtractionEnabled()");+ const fire = stopped.indexOf('fireVoid("mem::graph-extract"');+ expect(fire).toBeGreaterThan(-1);+ expect(gate === -1 || gate > fire).toBe(true);+ });++ it("graph functions register unconditionally so the trigger always resolves", () => {+ const index = readFileSync("src/index.ts", "utf-8");+ const reg = index.indexOf("registerGraphFunction(sdk, kv, provider)");+ expect(reg).toBeGreaterThan(-1);+ const before = index.slice(Math.max(0, reg - 200), reg);+ expect(before).not.toContain("isGraphExtractionEnabled()");+ });++ it("mem::graph-extract gates the LLM pass, not the heuristic pass", () => {+ const graph = readFileSync("src/functions/graph.ts", "utf-8");+ expect(graph).toMatch(/extractGraphHeuristics\(data\.observations\)/);+ expect(graph).toMatch(+ /isGraphExtractionEnabled\(\) && !provider\.name\.includes\("noop"\)/,+ );+ });+});diff --git a/test/graph.test.ts b/test/graph.test.tsindex da8b2665..aae56da6 100644--- a/test/graph.test.ts+++ b/test/graph.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach, vi } from "vitest";+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";vi.mock("../src/logger.js", () => ({logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },@@ -63,6 +63,9 @@ const mockProvider = {summarize: vi.fn(),};+// Structured fields stay empty so the deterministic heuristic pass+// contributes nothing and these tests keep exercising the LLM XML+// parse + persist path in isolation.const testObs: CompressedObservation = {id: "obs_1",sessionId: "ses_1",@@ -71,22 +74,29 @@ const testObs: CompressedObservation = {title: "Edit index file",facts: ["Modified main function"],narrative: "Updated index.ts with main function",- concepts: ["typescript", "entry-point"],- files: ["src/index.ts"],+ concepts: [],+ files: [],importance: 7,};describe("Graph Functions", () => {let sdk: ReturnType<typeof mockSdk>;let kv: ReturnType<typeof mockKV>;+ const ORIG_GRAPH_FLAG = process.env["GRAPH_EXTRACTION_ENABLED"];beforeEach(() => {sdk = mockSdk();kv = mockKV();vi.clearAllMocks();+ process.env["GRAPH_EXTRACTION_ENABLED"] = "true";registerGraphFunction(sdk as never, kv as never, mockProvider as never);});+ afterEach(() => {+ if (ORIG_GRAPH_FLAG === undefined) delete process.env["GRAPH_EXTRACTION_ENABLED"];+ else process.env["GRAPH_EXTRACTION_ENABLED"] = ORIG_GRAPH_FLAG;+ });+it("graph-extract creates nodes and edges from XML response", async () => {const result = (await sdk.trigger("mem::graph-extract", {observations: [testObs],diff --git a/test/helpers/mocks.ts b/test/helpers/mocks.tsindex a382e2ee..bc829ed5 100644--- a/test/helpers/mocks.ts+++ b/test/helpers/mocks.ts@@ -5,9 +5,21 @@ type Handler = (data: unknown) => Promise<unknown>;export function mockKV() {const store = new Map<string, Map<string, unknown>>();return {+ store,get: async <T>(scope: string, key: string): Promise<T | null> => {return (store.get(scope)?.get(key) as T) ?? null;},+ update: async (+ scope: string,+ key: string,+ updates: Array<{ path: string; value: unknown }>,+ ): Promise<void> => {+ const entries = store.get(scope);+ if (!entries) return;+ const value = (entries.get(key) as Record<string, unknown>) ?? {};+ for (const u of updates) value[u.path] = u.value;+ entries.set(key, value);+ },set: async <T>(scope: string, key: string, data: T): Promise<T> => {if (!store.has(scope)) store.set(scope, new Map());store.get(scope)!.set(key, data);@@ -23,9 +35,11 @@ export function mockKV() {};}-export function mockSdk() {+export function mockSdk(opts?: { looseTrigger?: boolean }) {const functions = new Map<string, Handler>();+ const looseTrigger = opts?.looseTrigger ?? false;return {+ fns: functions,registerFunction: (idOrOpts: string | { id: string },handler: Handler,@@ -46,7 +60,13 @@ export function mockSdk() {const payload =typeof idOrInput === "string" ? data : (idOrInput.payload as unknown);const fn = functions.get(id);- if (!fn) throw new Error(`No function: ${id}`);+ if (!fn) {+ // looseTrigger mirrors production fan-out where side-effect+ // triggers (cascade, events) may target functions another+ // module registers; tests exercising one module opt in.+ if (looseTrigger) return null;+ throw new Error(`No function: ${id}`);+ }return fn(payload);},};diff --git a/test/lesson-index-recall.test.ts b/test/lesson-index-recall.test.tsnew file mode 100644index 00000000..d9bb8f0f--- /dev/null+++ b/test/lesson-index-recall.test.ts@@ -0,0 +1,177 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { mockKV, mockSdk } from "./helpers/mocks.js";++vi.mock("../src/logger.js", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++async function setup() {+ vi.resetModules();+ const { registerLessonsFunctions, resetLessonIndex } = await import(+ "../src/functions/lessons.js"+ );+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerLessonsFunctions(sdk as never, kv as never);+ return { sdk, kv, resetLessonIndex };+}++function gateFirstLessonList(kv: { list: (scope: string) => Promise<unknown[]> }) {+ const origList = kv.list.bind(kv);+ let release!: () => void;+ const gate = new Promise<void>((r) => {+ release = r;+ });+ let gated = true;+ kv.list = async (scope: string) => {+ if (scope === "mem:lessons" && gated) {+ gated = false;+ await gate;+ }+ return origList(scope);+ };+ return release;+}++describe("lesson recall through the lesson index", () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it("recalls a saved lesson by keyword and preserves confidence ordering", async () => {+ const { sdk } = await setup();+ await sdk.trigger("mem::lesson-save", {+ content: "always run migrations inside a transaction",+ confidence: 0.9,+ tags: ["database"],+ });+ await sdk.trigger("mem::lesson-save", {+ content: "database migrations need a rollback script committed alongside",+ confidence: 0.3,+ tags: ["database"],+ });++ const res = (await sdk.trigger("mem::lesson-recall", {+ query: "database migrations",+ })) as { success: boolean; lessons: Array<{ content: string; score: number }> };++ expect(res.success).toBe(true);+ expect(res.lessons.length).toBe(2);+ expect(res.lessons[0].content).toContain("transaction");+ expect(res.lessons[0].score).toBeGreaterThan(res.lessons[1].score);+ });++ it("recalls lessons that existed before the index was built (lazy rebuild)", async () => {+ const { sdk, kv } = await setup();+ await kv.set("mem:lessons", "lsn_pre", {+ id: "lsn_pre",+ content: "verify wire payloads at the boundary before trusting them",+ context: "",+ confidence: 0.8,+ reinforcements: 2,+ source: "manual",+ sourceIds: [],+ tags: ["verification"],+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ decayRate: 0.05,+ });++ const res = (await sdk.trigger("mem::lesson-recall", {+ query: "wire payloads boundary",+ })) as { lessons: Array<{ id: string }> };++ expect(res.lessons.map((l) => l.id)).toContain("lsn_pre");+ });++ it("stops returning deleted lessons", async () => {+ const { sdk } = await setup();+ const saved = (await sdk.trigger("mem::lesson-save", {+ content: "prefer streaming responses over polling loops",+ confidence: 0.7,+ })) as { lesson: { id: string } };++ let res = (await sdk.trigger("mem::lesson-recall", {+ query: "streaming polling",+ })) as { lessons: Array<{ id: string }> };+ expect(res.lessons.map((l) => l.id)).toContain(saved.lesson.id);++ await sdk.trigger("mem::lesson-delete", { lessonId: saved.lesson.id });++ res = (await sdk.trigger("mem::lesson-recall", {+ query: "streaming polling",+ })) as { lessons: Array<{ id: string }> };+ expect(res.lessons.map((l) => l.id)).not.toContain(saved.lesson.id);+ });++ it("a save landing while the index build is in flight is not lost", async () => {+ const { sdk, kv } = await setup();+ await kv.set("mem:lessons", "lsn_early", {+ id: "lsn_early",+ content: "cache invalidation needs an explicit generation counter",+ context: "",+ confidence: 0.8,+ reinforcements: 0,+ source: "manual",+ sourceIds: [],+ tags: [],+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ decayRate: 0.05,+ });+ const release = gateFirstLessonList(kv as never);++ const pendingRecall = sdk.trigger("mem::lesson-recall", {+ query: "cache invalidation generation",+ });+ await new Promise((r) => setTimeout(r, 0));++ const saved = (await sdk.trigger("mem::lesson-save", {+ content: "cache invalidation generation counters beat timestamps",+ confidence: 0.9,+ })) as { success: boolean; lesson: { id: string } };+ expect(saved.success).toBe(true);++ release();+ await pendingRecall;++ const res = (await sdk.trigger("mem::lesson-recall", {+ query: "cache invalidation generation",+ })) as { lessons: Array<{ id: string }> };+ expect(res.lessons.map((l) => l.id)).toContain(saved.lesson.id);+ expect(res.lessons.map((l) => l.id)).toContain("lsn_early");+ });++ it("resetLessonIndex during an in-flight build discards the stale snapshot", async () => {+ const { sdk, kv, resetLessonIndex } = await setup();+ const release = gateFirstLessonList(kv as never);++ const pendingRecall = sdk.trigger("mem::lesson-recall", {+ query: "replayed lesson content",+ });+ await new Promise((r) => setTimeout(r, 0));++ await kv.set("mem:lessons", "lsn_replayed", {+ id: "lsn_replayed",+ content: "replayed lesson content arrives outside the lesson functions",+ context: "",+ confidence: 0.7,+ reinforcements: 0,+ source: "manual",+ sourceIds: [],+ tags: [],+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ decayRate: 0.05,+ });+ resetLessonIndex();++ release();+ await pendingRecall;++ const res = (await sdk.trigger("mem::lesson-recall", {+ query: "replayed lesson content",+ })) as { lessons: Array<{ id: string }> };+ expect(res.lessons.map((l) => l.id)).toContain("lsn_replayed");+ });+});diff --git a/test/minimax-provider.test.ts b/test/minimax-provider.test.tsindex 4167d4b3..d3f002f3 100644--- a/test/minimax-provider.test.ts+++ b/test/minimax-provider.test.ts@@ -14,7 +14,7 @@ describe("MinimaxProvider — base URL resolution (#285)", () => {it("defaults to https://api.minimax.io/anthropic (not the legacy minimaxi.com host)", () => {delete process.env["MINIMAX_BASE_URL"];- const provider = new MinimaxProvider("test-key", "MiniMax-M2.7", 800);+ const provider = new MinimaxProvider("test-key", "MiniMax-M3", 800);expect((provider as unknown as { baseUrl: string }).baseUrl).toBe("https://api.minimax.io/anthropic",);@@ -22,7 +22,7 @@ describe("MinimaxProvider — base URL resolution (#285)", () => {it("honors MINIMAX_BASE_URL via getEnvVar (merged ~/.agentmemory/.env + process.env)", () => {process.env["MINIMAX_BASE_URL"] = "https://custom.example.com/anthropic";- const provider = new MinimaxProvider("test-key", "MiniMax-M2.7", 800);+ const provider = new MinimaxProvider("test-key", "MiniMax-M3", 800);expect((provider as unknown as { baseUrl: string }).baseUrl).toBe("https://custom.example.com/anthropic",);diff --git a/test/observe-dedup-prompt.test.ts b/test/observe-dedup-prompt.test.tsnew file mode 100644index 00000000..efab851b--- /dev/null+++ b/test/observe-dedup-prompt.test.ts@@ -0,0 +1,114 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { mockKV, mockSdk } from "./helpers/mocks.js";++vi.mock("../src/logger.js", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++function observePayload(hookType: string, data: unknown) {+ return {+ sessionId: "ses_dedup_test",+ project: "/home/user/myrepo",+ cwd: "/home/user/myrepo",+ hookType,+ timestamp: new Date().toISOString(),+ data,+ };+}++describe("observe dedup for hooks without tool_input (#1173)", () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it("records consecutive prompt_submit observations with different prompts", async () => {+ const { registerObserveFunction } = await import("../src/functions/observe.js");+ const { DedupMap } = await import("../src/functions/dedup.js");+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerObserveFunction(sdk as never, kv as never, new DedupMap());++ const first = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", { prompt: "ship the helm chart" }),+ )) as { observationId?: string; deduplicated?: boolean };+ const second = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", { prompt: "now fix the failing test" }),+ )) as { observationId?: string; deduplicated?: boolean };++ expect(first.observationId).toBeTruthy();+ expect(second.deduplicated).toBeUndefined();+ expect(second.observationId).toBeTruthy();+ });++ it("records two prompt_submit observations whose data is distinct primitive strings", async () => {+ const { registerObserveFunction } = await import("../src/functions/observe.js");+ const { DedupMap } = await import("../src/functions/dedup.js");+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerObserveFunction(sdk as never, kv as never, new DedupMap());++ const first = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", "ship the helm chart"),+ )) as { observationId?: string; deduplicated?: boolean };+ const second = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", "now fix the failing test"),+ )) as { observationId?: string; deduplicated?: boolean };++ expect(first.observationId).toBeTruthy();+ expect(second.deduplicated).toBeUndefined();+ expect(second.observationId).toBeTruthy();+ });++ it("still dedups an identical prompt_submit within the TTL window", async () => {+ const { registerObserveFunction } = await import("../src/functions/observe.js");+ const { DedupMap } = await import("../src/functions/dedup.js");+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerObserveFunction(sdk as never, kv as never, new DedupMap());++ const payload = { prompt: "ship the helm chart" };+ const first = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", payload),+ )) as { observationId?: string };+ const second = (await sdk.trigger(+ "mem::observe",+ observePayload("prompt_submit", payload),+ )) as { deduplicated?: boolean };++ expect(first.observationId).toBeTruthy();+ expect(second.deduplicated).toBe(true);+ });++ it("keeps tool_input as the dedup key for tool hooks (response changes still dedup)", async () => {+ const { registerObserveFunction } = await import("../src/functions/observe.js");+ const { DedupMap } = await import("../src/functions/dedup.js");+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerObserveFunction(sdk as never, kv as never, new DedupMap());++ const first = (await sdk.trigger(+ "mem::observe",+ observePayload("post_tool_use", {+ tool_name: "Bash",+ tool_input: { command: "ls" },+ tool_response: "a.txt",+ }),+ )) as { observationId?: string };+ const second = (await sdk.trigger(+ "mem::observe",+ observePayload("post_tool_use", {+ tool_name: "Bash",+ tool_input: { command: "ls" },+ tool_response: "b.txt",+ }),+ )) as { deduplicated?: boolean };++ expect(first.observationId).toBeTruthy();+ expect(second.deduplicated).toBe(true);+ });+});diff --git a/test/remember-supersede-recall.test.ts b/test/remember-supersede-recall.test.tsnew file mode 100644index 00000000..3014f61c--- /dev/null+++ b/test/remember-supersede-recall.test.ts@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { mockKV, mockSdk } from "./helpers/mocks.js";++vi.mock("../src/logger.js", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++async function setup() {+ vi.resetModules();+ const search = await import("../src/functions/search.js");+ const { registerRememberFunction } = await import("../src/functions/remember.js");+ const sdk = mockSdk({ looseTrigger: true });+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);+ return { sdk, kv, search };+}++describe("mem::remember supersession and recall hygiene", () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it("removes the superseded version from the search index", async () => {+ const { sdk, search } = await setup();+ const first = (await sdk.trigger("mem::remember", {+ content: "the deploy pipeline uses blue green rollout with health gates",+ type: "architecture",+ })) as { memory: { id: string } };+ const idx = search.getSearchIndex();+ expect(idx.has(first.memory.id)).toBe(true);++ const second = (await sdk.trigger("mem::remember", {+ content: "the deploy pipeline uses blue green rollout with health gates always",+ type: "architecture",+ })) as { memory: { id: string; supersedes: string[] } };++ expect(second.memory.supersedes).toContain(first.memory.id);+ expect(idx.has(first.memory.id)).toBe(false);+ expect(idx.has(second.memory.id)).toBe(true);+ });++ it("reports a close-but-below-threshold match as similarTo without superseding", async () => {+ const { sdk } = await setup();+ const first = (await sdk.trigger("mem::remember", {+ content: "redis cache layer fronting the primary database for hot reads",+ type: "architecture",+ })) as { memory: { id: string } };++ const second = (await sdk.trigger("mem::remember", {+ content: "redis cache layer fronting the primary database misses cold writes entirely",+ type: "architecture",+ })) as {+ memory: { id: string; version: number };+ similarTo?: { id: string; similarity: number };+ };++ expect(second.memory.version).toBe(1);+ expect(second.similarTo).toBeDefined();+ expect(second.similarTo!.id).toBe(first.memory.id);+ expect(second.similarTo!.similarity).toBeGreaterThan(0.4);+ expect(second.similarTo!.similarity).toBeLessThanOrEqual(0.7);+ });++ it("still finds the supersession target through index-backed candidates", async () => {+ const { sdk } = await setup();+ for (let i = 0; i < 30; i++) {+ await sdk.trigger("mem::remember", {+ content: `unrelated filler memory number ${i} about topic-${i} with words w${i}a w${i}b`,+ type: "fact",+ });+ }+ const target = (await sdk.trigger("mem::remember", {+ content: "session tokens rotate every fifteen minutes via the auth broker",+ type: "workflow",+ })) as { memory: { id: string } };++ const update = (await sdk.trigger("mem::remember", {+ content: "session tokens rotate every fifteen minutes via the auth broker service",+ type: "workflow",+ })) as { memory: { supersedes: string[]; version: number } };++ expect(update.memory.supersedes).toContain(target.memory.id);+ expect(update.memory.version).toBe(2);+ });+});diff --git a/test/viewer-security.test.ts b/test/viewer-security.test.tsindex ff56734a..8db74b6d 100644--- a/test/viewer-security.test.ts+++ b/test/viewer-security.test.ts@@ -219,8 +219,8 @@ describe("viewer request handler DNS rebinding defence (e2e)", () => {// SVG payload must actually be SVG, not the proxied REST error body.expect(res.body).toMatch(/^<svg\b/);expect(res.body).toContain("</svg>");- // Sanity-check the artwork: rounded dark tile + green "AM" lettering.- expect(res.body).toContain('fill="#111111"');- expect(res.body).toContain(">AM<");+ // Sanity-check it is real SVG artwork, not an error page.+ expect(res.body).toContain('<svg');+ expect(res.body).toMatch(/<svg[^>]*viewBox="0 0 64 64"/);});});diff --git a/vitest.config.ts b/vitest.config.tsnew file mode 100644index 00000000..5a222242--- /dev/null+++ b/vitest.config.ts@@ -0,0 +1,21 @@+import { defineConfig } from "vitest/config";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { mkdtempSync } from "node:fs";++// Tests must never see the developer's real $HOME: config.ts reads+// ~/.agentmemory/.env underneath process.env, so asserted defaults would+// silently become whatever the local install happens to set — red on clean+// checkouts, green on machines whose .env masks a broken default. Point HOME+// at a throwaway directory for the whole run; tests that need home-dir state+// create their own sandbox and reset HOME themselves.+const testHome = mkdtempSync(join(tmpdir(), "agentmemory-test-home-"));++export default defineConfig({+ test: {+ env: {+ HOME: testHome,+ USERPROFILE: testHome,+ },+ },+});diff --git a/website/app/globals.css b/website/app/globals.cssindex 9996093e..d4722678 100644--- a/website/app/globals.css+++ b/website/app/globals.css@@ -1,16 +1,20 @@:root {- --abyss: #000000;- --iron: #181818;- --charcoal: #202020;- --ash: #7d7d7d;- --steel: #969696;- --mist: #e6e6e6;- --white: #ffffff;- --gold: #ffc000;- --gold-deep: #917300;- --gold-soft: #ffce3e;- --cyan: #29abe2;- --blue: #3860be;+ --canvas: #0a0a0a;+ --canvas-soft: #1a1c20;+ --canvas-card: #191919;+ --canvas-mid: #363a3f;+ --hairline: #212327;+ --ink: #ffffff;+ --ink-hover: #fafaf7;+ --body: #dadbdf;+ --mute: #7d8187;+ --sunset: #ff7a17;+ --sunset-soft: #ffc285;+ --breeze: #a0c3ec;+ --ok: #7fce9a;+ --radius-card: 8px;+ --radius-pill: 9999px;+ --border-ghost: rgba(255, 255, 255, 0.25);}* {@@ -21,9 +25,9 @@ html,body {margin: 0;padding: 0;- background: var(--abyss);- color: var(--white);- font-family: var(--font-archivo), "Helvetica Neue", Arial, sans-serif;+ background: var(--canvas);+ color: var(--body);+ font-family: var(--font-sans), Inter, system-ui, -apple-system, sans-serif;font-size: 16px;line-height: 1.5;-webkit-font-smoothing: antialiased;@@ -36,7 +40,7 @@ a {transition: color 160ms ease;}a:hover {- color: var(--blue);+ color: var(--ink);}button {@@ -47,9 +51,14 @@ button {color: inherit;}+:focus-visible {+ outline: 2px solid rgba(255, 255, 255, 0.55);+ outline-offset: 3px;+}+::selection {- background: var(--gold);- color: var(--abyss);+ background: var(--sunset);+ color: var(--canvas);}/* Reveal animation */@@ -73,18 +82,19 @@ button {}}-/* Buttons shared */+/* Buttons shared — pill shapes, quiet states */.btn {display: inline-flex;align-items: center;justify-content: center;- padding: 18px 28px;- font-size: 14.4px;- font-weight: 700;- letter-spacing: 0.2px;- text-transform: uppercase;+ gap: 8px;+ padding: 12px 24px;+ font-size: 14px;+ font-weight: 500;+ letter-spacing: 0;+ line-height: 20px;border: 1px solid transparent;- border-radius: 0;+ border-radius: var(--radius-pill);transition:background 200ms ease,color 200ms ease,@@ -93,30 +103,40 @@ button {cursor: pointer;}.btn--accent {- background: var(--gold);- color: var(--abyss);- padding: 22px 32px;- font-size: 16px;+ background: var(--ink);+ color: var(--canvas);+ border-color: var(--ink);+ padding: 14px 28px;}.btn--accent:hover {- background: var(--gold-deep);- color: var(--white);+ background: var(--ink-hover);+ border-color: var(--ink-hover);+ color: var(--canvas);+}+.btn--sunset {+ background: var(--sunset);+ color: var(--canvas);+ border-color: var(--sunset);+ padding: 14px 28px;+}+.btn--sunset:hover {+ background: #ff8b35;+ border-color: #ff8b35;+ color: var(--canvas);}.btn--ghost {background: transparent;- color: var(--white);- border-color: rgba(255, 255, 255, 0.5);- opacity: 0.85;+ color: var(--ink);+ border-color: var(--border-ghost);}.btn--ghost:hover {- background: rgba(255, 255, 255, 0.08);- border-color: var(--white);- color: var(--white);- opacity: 1;+ background: rgba(255, 255, 255, 0.06);+ border-color: var(--border-ghost);+ color: var(--ink);}.btn--small {- padding: 10px 14px;- font-size: 12px;+ padding: 8px 16px;+ font-size: 13px;}/* Shared section head */@@ -127,29 +147,27 @@ button {}.section-eyebrow {display: inline-block;+ font-family: var(--font-mono), ui-monospace, SFMono-Regular, Menlo, monospace;font-size: 12px;- letter-spacing: 0.96px;- color: var(--gold);+ letter-spacing: 1.4px;+ color: var(--mute);text-transform: uppercase;- margin-bottom: 16px;- padding: 6px 10px;- border: 1px solid var(--gold);+ margin-bottom: 20px;}.section-title {- font-size: clamp(32px, 5vw, 72px);- font-weight: 900;- line-height: 0.98;- letter-spacing: -0.01em;- margin: 0 0 24px;- text-transform: uppercase;+ font-size: clamp(34px, 4.6vw, 56px);+ font-weight: 400;+ line-height: 1.06;+ letter-spacing: -0.03em;+ color: var(--ink);+ margin: 0 0 20px;text-wrap: balance;}.section-lede {- max-width: 680px;+ max-width: 660px;font-size: 16px;- letter-spacing: 0.12px;- color: var(--steel);- text-transform: uppercase;+ line-height: 1.65;+ color: var(--body);margin: 0;}diff --git a/website/app/layout.tsx b/website/app/layout.tsxindex 95cb92ff..d7eca9db 100644--- a/website/app/layout.tsx+++ b/website/app/layout.tsx@@ -1,11 +1,10 @@import type { Metadata, Viewport } from "next";-import { Archivo, JetBrains_Mono } from "next/font/google";+import { Inter, JetBrains_Mono } from "next/font/google";import "./globals.css";-const archivo = Archivo({+const inter = Inter({subsets: ["latin"],- weight: ["400", "500", "700", "900"],- variable: "--font-archivo",+ variable: "--font-sans",display: "swap",});@@ -18,9 +17,9 @@ const jetbrains = JetBrains_Mono({export const metadata: Metadata = {metadataBase: new URL("https://agentmemory.dev"),- title: "AGENTMEMORY — PERSISTENT MEMORY FOR AI CODING AGENTS",+ title: "agentmemory: persistent memory for AI coding agents",description:- "The memory layer your coding agent should have had from day one. 95.2% retrieval R@5. 92% fewer tokens. 0 external databases. Works with every agent.",+ "Persistent memory for AI coding agents. Capture every session, recall it in the next one. Runs locally with zero external databases. Works with every MCP client.",icons: {icon: [{ url: "/icon.svg", type: "image/svg+xml" }],apple: "/icon.svg",@@ -41,7 +40,7 @@ export const metadata: Metadata = {};export const viewport: Viewport = {- themeColor: "#000000",+ themeColor: "#0a0a0a",width: "device-width",initialScale: 1,};@@ -52,7 +51,7 @@ export default function RootLayout({children: React.ReactNode;}) {return (- <html lang="en" className={`${archivo.variable} ${jetbrains.variable}`}>+ <html lang="en" className={`${inter.variable} ${jetbrains.variable}`}><body>{children}</body></html>);diff --git a/website/app/opengraph-image.tsx b/website/app/opengraph-image.tsxindex bff489cb..bdd5f403 100644--- a/website/app/opengraph-image.tsx+++ b/website/app/opengraph-image.tsx@@ -1,10 +1,12 @@import { ImageResponse } from "next/og";+import { getProjectMeta } from "@/lib/meta";-export const alt = "agentmemory — persistent memory for AI coding agents";+export const alt = "agentmemory: persistent memory for AI coding agents";export const size = { width: 1200, height: 630 };export const contentType = "image/png";export default function Image() {+ const meta = getProjectMeta();return new ImageResponse((<div@@ -15,8 +17,7 @@ export default function Image() {flexDirection: "column",justifyContent: "space-between",padding: "72px 80px",- background:- "radial-gradient(ellipse at 20% 0%, #1a1407 0%, #0a0a0a 55%, #000 100%)",+ background: "#0a0a0a",color: "#fff",fontFamily: "system-ui, -apple-system, sans-serif",}}@@ -26,19 +27,19 @@ export default function Image() {display: "flex",alignItems: "center",gap: 16,- fontSize: 20,+ fontSize: 18,letterSpacing: 3,- fontWeight: 700,- color: "#f3b840",+ fontWeight: 400,+ color: "#7d8187",textTransform: "uppercase",}}><divstyle={{- width: 14,- height: 14,- background: "#f3b840",- boxShadow: "0 0 24px #f3b840",+ width: 12,+ height: 12,+ borderRadius: 12,+ background: "#ff7a17",}}/><span>AGENTMEMORY</span>@@ -48,25 +49,25 @@ export default function Image() {<divstyle={{display: "flex",- flexDirection: "column",- fontSize: 128,- fontWeight: 900,- lineHeight: 0.95,- letterSpacing: -3,- textTransform: "uppercase",+ fontSize: 124,+ fontWeight: 400,+ lineHeight: 1,+ letterSpacing: -4,+ color: "#ffffff",}}>- <span>AGENT</span>- <span style={{ color: "#f3b840" }}>MEMORY</span>+ <span>agent</span>+ <span style={{ color: "#dadbdf" }}>memory</span></div><divstyle={{display: "flex",- fontSize: 32,- color: "#b8b8b8",- letterSpacing: 0.5,+ fontSize: 30,+ color: "#dadbdf",+ letterSpacing: 0,maxWidth: 900,- lineHeight: 1.35,+ lineHeight: 1.4,+ fontWeight: 400,}}>Persistent memory for AI coding agents. Runs locally. Zero external@@ -78,25 +79,25 @@ export default function Image() {style={{display: "flex",gap: 48,- fontSize: 22,- color: "#888",+ fontSize: 20,+ color: "#7d8187",letterSpacing: 2,textTransform: "uppercase",- fontWeight: 700,- borderTop: "1px solid #222",+ fontWeight: 400,+ borderTop: "1px solid #212327",paddingTop: 28,}}><div style={{ display: "flex", gap: 10 }}>- <span style={{ color: "#f3b840" }}>95.2%</span>- <span>RETRIEVAL R@5</span>+ <span style={{ color: "#ffffff" }}>{meta.mcpTools}</span>+ <span>MCP TOOLS</span></div><div style={{ display: "flex", gap: 10 }}>- <span style={{ color: "#f3b840" }}>92%</span>- <span>FEWER TOKENS</span>+ <span style={{ color: "#ffffff" }}>{meta.restEndpoints}</span>+ <span>REST ENDPOINTS</span></div><div style={{ display: "flex", gap: 10 }}>- <span style={{ color: "#f3b840" }}>0</span>+ <span style={{ color: "#ffffff" }}>0</span><span>EXTERNAL DBs</span></div></div>diff --git a/website/app/page.tsx b/website/app/page.tsxindex afb4a407..962ab7d5 100644--- a/website/app/page.tsx+++ b/website/app/page.tsx@@ -6,8 +6,8 @@ import { Primitives } from "@/components/Primitives";import { Features } from "@/components/Features";import { CommandCenter } from "@/components/CommandCenter";import { LiveTerminal } from "@/components/LiveTerminal";-import { Compare } from "@/components/Compare";import { Testimonials } from "@/components/Testimonials";+import { Compare } from "@/components/Compare";import { Agents } from "@/components/Agents";import { Install } from "@/components/Install";import { Footer } from "@/components/Footer";@@ -24,6 +24,7 @@ export default function Page() {<StatsmcpTools={meta.mcpTools}hooks={meta.hooks}+ restEndpoints={meta.restEndpoints}testsPassing={meta.testsPassing}/><Primitives />@@ -32,7 +33,7 @@ export default function Page() {mcpTools={meta.mcpTools}restEndpoints={meta.restEndpoints}/>- <CommandCenter />+ <CommandCenter restEndpoints={meta.restEndpoints} /><LiveTerminal mcpTools={meta.mcpTools} hooks={meta.hooks} /><Compare /><Testimonials />diff --git a/website/app/twitter-image.tsx b/website/app/twitter-image.tsxindex 7713fac7..eb297dbc 100644--- a/website/app/twitter-image.tsx+++ b/website/app/twitter-image.tsx@@ -1,4 +1,4 @@-export const alt = "agentmemory — persistent memory for AI coding agents";+export const alt = "agentmemory: persistent memory for AI coding agents";export const size = { width: 1200, height: 630 };export const contentType = "image/png";diff --git a/website/components/AgentInstall.module.css b/website/components/AgentInstall.module.cssindex 2cfb10cf..142c06c9 100644--- a/website/components/AgentInstall.module.css+++ b/website/components/AgentInstall.module.css@@ -6,19 +6,17 @@}.stepLabel {+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--gold);+ letter-spacing: 1.4px;+ color: var(--mute);text-transform: uppercase;- font-weight: 700;}.helper {margin: 0;- font-size: 12px;- letter-spacing: 0.12px;- color: var(--steel);- text-transform: uppercase;- line-height: 1.55;+ font-size: 13.5px;+ color: var(--body);+ line-height: 1.6;}.split {@@ -35,11 +33,11 @@min-width: 0;}.colHead {+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--gold);+ letter-spacing: 1.4px;+ color: var(--mute);text-transform: uppercase;- font-weight: 700;}.chips {display: grid;@@ -54,48 +52,46 @@align-items: flex-start;justify-content: center;gap: 4px;- padding: 14px 14px;- min-height: 62px;- background: var(--iron);- border: 1px solid var(--charcoal);- color: var(--white);+ padding: 12px 16px;+ min-height: 60px;+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ color: var(--ink);text-decoration: none;text-align: left;cursor: pointer;transition:background 180ms ease,- border-color 180ms ease,- color 180ms ease;+ border-color 180ms ease;}.chip:hover {- background: var(--charcoal);- border-color: var(--gold);+ background: var(--canvas-soft);+ border-color: var(--border-ghost);}.chipOk {- border-color: #29c864 !important;+ border-color: var(--ok) !important;}.chipOk .chipSub {- color: #29c864;+ color: var(--ok);}.chipLabel {- font-size: 13px;- font-weight: 900;+ font-size: 13.5px;+ font-weight: 500;letter-spacing: -0.01em;- text-transform: uppercase;- color: var(--white);+ color: var(--ink);}.chipSub {- font-size: 10px;- letter-spacing: 0.96px;- color: var(--ash);+ font-family: var(--font-mono);+ font-size: 9.5px;+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}.chipNote {margin: 4px 0 0;- font-size: 10.5px;- letter-spacing: 0.96px;- color: var(--ash);- text-transform: uppercase;+ font-size: 12px;+ color: var(--mute);line-height: 1.55;}@@ -105,8 +101,9 @@}.snippet {- border: 1px solid var(--charcoal);- background: var(--abyss);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ background: var(--canvas-card);overflow: hidden;}.snippetHead {@@ -115,20 +112,22 @@justify-content: space-between;gap: 12px;padding: 12px 20px;- background: var(--iron);- border-bottom: 1px solid var(--charcoal);+ background: var(--canvas-soft);+ border-bottom: 1px solid var(--hairline);}.snippetTitle {+ font-family: var(--font-mono);font-size: 11px;- font-weight: 700;- letter-spacing: 0.96px;- color: var(--gold);+ font-weight: 500;+ letter-spacing: 1.2px;+ color: var(--ink);text-transform: uppercase;}.snippetHint {+ font-family: var(--font-mono);font-size: 10px;- letter-spacing: 0.96px;- color: var(--ash);+ letter-spacing: 0.8px;+ color: var(--mute);text-transform: uppercase;}.code {@@ -137,63 +136,61 @@font-family: var(--font-mono);font-size: 13px;line-height: 1.6;- color: var(--white);+ color: var(--body);white-space: pre;overflow-x: auto;}.copyRow {padding: 12px 16px;- background: var(--iron);- border-top: 1px solid var(--charcoal);+ background: var(--canvas-soft);+ border-top: 1px solid var(--hairline);display: flex;justify-content: flex-end;}.copyBtn {- padding: 9px 14px;- font-size: 11px;- font-weight: 700;- letter-spacing: 0.96px;- text-transform: uppercase;- color: var(--abyss);- background: var(--gold);+ padding: 8px 18px;+ font-size: 12px;+ font-weight: 500;+ letter-spacing: 0.4px;+ color: var(--canvas);+ background: var(--ink);border: none;+ border-radius: var(--radius-pill);cursor: pointer;transition:background 200ms ease,color 200ms ease;}.copyBtn:hover {- background: var(--gold-deep);- color: var(--white);+ background: var(--ink-hover);}.copyBtnSmall {- padding: 6px 10px;- font-size: 10px;+ padding: 6px 12px;+ font-size: 11px;}.copyBtnOk {- background: #29c864 !important;- color: var(--abyss) !important;+ background: var(--ok) !important;+ color: var(--canvas) !important;}.moreToggle {align-self: start;- padding: 10px 14px;- font-size: 11px;- font-weight: 700;- letter-spacing: 0.96px;- color: var(--steel);+ padding: 9px 18px;+ font-size: 12px;+ font-weight: 500;+ color: var(--body);background: transparent;- border: 1px solid var(--charcoal);+ border: 1px solid var(--border-ghost);+ border-radius: var(--radius-pill);cursor: pointer;transition:color 180ms ease,- border-color 180ms ease;- text-transform: uppercase;+ background 180ms ease;}.moreToggle:hover {- color: var(--white);- border-color: var(--gold);+ color: var(--ink);+ background: rgba(255, 255, 255, 0.06);}.moreGrid {diff --git a/website/components/AgentInstall.tsx b/website/components/AgentInstall.tsxindex dd354348..da187b3f 100644--- a/website/components/AgentInstall.tsx+++ b/website/components/AgentInstall.tsx@@ -205,56 +205,56 @@ export function AgentInstall() {const chips: Chip[] = [{id: "cursor",- label: "CURSOR",+ label: "Cursor",kind: "deeplink",href: cursor,sub: "DEEPLINK",},{id: "vscode",- label: "VS CODE",+ label: "VS Code",kind: "deeplink",href: vscode,sub: "DEEPLINK",},{id: "claude-code",- label: "CLAUDE CODE",+ label: "Claude Code",kind: "copy",copyText: CLAUDE_CODE_CMD,sub: "COPY CMD",},{id: "copilot-cli",- label: "COPILOT CLI",+ label: "Copilot CLI",kind: "copy",copyText: COPILOT_CLI_CMD,sub: "COPY CMD",},{id: "codex",- label: "CODEX CLI",+ label: "Codex CLI",kind: "copy",copyText: CODEX_TOML,sub: "COPY TOML",},{id: "warp",- label: "WARP",+ label: "Warp",kind: "copy",copyText: WARP_CMD,sub: "COPY CMD",},{id: "claude-desktop",- label: "CLAUDE DESKTOP",+ label: "Claude Desktop",kind: "copy",copyText: UNIVERSAL_JSON,sub: "COPY JSON",},{id: "gemini",- label: "GEMINI CLI",+ label: "Gemini CLI",kind: "copy",copyText: UNIVERSAL_JSON,sub: "COPY JSON",@@ -263,10 +263,10 @@ export function AgentInstall() {return (<div className={styles.wrap}>- <div className={styles.stepLabel}>3. WIRE UP ANY AGENT</div>+ <div className={styles.stepLabel}>4. WIRE UP ANY AGENT</div><p className={styles.helper}>- ONE MCP JSON FITS ALMOST EVERYTHING. PICK YOUR AGENT ON THE LEFT, OR- PASTE THE UNIVERSAL CONFIG ON THE RIGHT.+ One MCP JSON fits almost everything. Pick your agent on the left, or+ paste the universal config on the right.</p><div className={styles.split}>@@ -278,14 +278,14 @@ export function AgentInstall() {))}</div><p className={styles.chipNote}>- CURSOR / VS CODE ARE ONE-CLICK VIA DEEPLINK. OTHERS COPY THE RIGHT- SNIPPET DIRECTLY TO YOUR CLIPBOARD.+ Cursor / VS Code are one-click via deeplink. Others copy the right+ snippet directly to your clipboard.</p></div><div className={styles.snippetCol}><Snippettitle="UNIVERSAL MCP JSON"- hint="WORKS FOR CLAUDE DESKTOP · CURSOR · CLINE · ROO · WINDSURF · GEMINI · WARP · DROID · KIRO · ANTIGRAVITY · QWEN — MERGE INTO EXISTING mcpServers"+ hint="WORKS FOR CLAUDE DESKTOP · CURSOR · CLINE · ROO · WINDSURF · GEMINI · WARP · DROID · KIRO · ANTIGRAVITY · QWEN · MERGE INTO EXISTING mcpServers"body={UNIVERSAL_JSON}/></div>@@ -296,19 +296,19 @@ export function AgentInstall() {aria-expanded={showMore}onClick={() => setShowMore((v) => !v)}>- {showMore ? "— HIDE OTHER SHAPES" : "+ OPENCODE · CLINE · CONTINUE · ZED · DROID · QWEN · ANTIGRAVITY · KIRO · HERMES · OPENCLAW · VS CODE"}+ {showMore ? "− Hide other shapes" : "+ OpenCode · Cline · Continue · Zed · Droid · Qwen · Antigravity · Kiro · Hermes · OpenClaw · VS Code"}</button>{showMore && (<div className={styles.moreGrid}><Snippettitle="OPENCODE"- hint="opencode.json — different shape (mcp key, command as array)"+ hint="opencode.json · different shape (mcp key, command as array)"body={OPENCODE_JSON}/><Snippettitle="VS CODE (mcp.json)"- hint=".vscode/mcp.json — uses servers key, not mcpServers"+ hint=".vscode/mcp.json · uses servers key, not mcpServers"body={VSCODE_MCP_JSON}/><Snippet@@ -318,12 +318,12 @@ export function AgentInstall() {/><Snippettitle="HERMES"- hint="integrations/hermes — plugin.yaml"+ hint="integrations/hermes · plugin.yaml"body={HERMES_YAML}/><Snippettitle="OPENCLAW"- hint="integrations/openclaw — plugin.yaml"+ hint="integrations/openclaw · plugin.yaml"body={OPENCLAW_YAML}/></div>diff --git a/website/components/Agents.module.css b/website/components/Agents.module.cssindex 4a8d228f..9aa4a516 100644--- a/website/components/Agents.module.css+++ b/website/components/Agents.module.css@@ -2,7 +2,7 @@padding: 112px 0 96px;}-/* Featured row: 4 first-party cards */+/* Featured row: first-party plugin cards */.featuredRow {max-width: 1440px;margin: 0 auto 56px;@@ -14,10 +14,11 @@.featured {position: relative;- background: var(--iron);- border: 1px solid var(--charcoal);+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);padding: 24px;- color: var(--white);+ color: var(--ink);text-decoration: none;display: flex;flex-direction: column;@@ -25,27 +26,12 @@min-height: 200px;transition:background 200ms ease,- border-color 200ms ease,- transform 200ms ease;+ border-color 200ms ease;overflow: hidden;}-.featured::before {- content: "";- position: absolute;- inset: 0 0 auto 0;- height: 3px;- background: var(--agent-accent, var(--gold));- transform: scaleX(0.2);- transform-origin: left;- transition: transform 240ms ease;-}.featured:hover {- background: var(--charcoal);- border-color: var(--agent-accent, var(--gold));- transform: translateY(-2px);-}-.featured:hover::before {- transform: scaleX(1);+ background: var(--canvas-soft);+ border-color: var(--border-ghost);}.featuredHead {@@ -54,15 +40,15 @@align-items: center;}.featuredLogo {- width: 56px;- height: 56px;+ width: 52px;+ height: 52px;display: flex;align-items: center;justify-content: center;- border-radius: 10px;+ border-radius: var(--radius-card);overflow: hidden;- background: var(--abyss);- border: 1px solid var(--charcoal);+ background: var(--canvas);+ border: 1px solid var(--hairline);flex-shrink: 0;}.featuredLogo img {@@ -77,42 +63,41 @@min-width: 0;}.featuredSub {+ font-family: var(--font-mono);font-size: 10px;- letter-spacing: 0.96px;- color: var(--agent-accent, var(--gold));+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;- font-weight: 700;}.featuredName {- font-size: 20px;- font-weight: 900;+ font-size: 18px;+ font-weight: 500;letter-spacing: -0.01em;- color: var(--white);+ color: var(--ink);}.featuredFrom {- font-size: 10.5px;- letter-spacing: 0.96px;- color: var(--ash);+ font-family: var(--font-mono);+ font-size: 10px;+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}.featuredPitch {margin: 0;- font-size: 12.5px;- letter-spacing: 0.12px;- color: var(--steel);- text-transform: uppercase;+ font-size: 13px;+ color: var(--body);line-height: 1.55;}.featuredArrow {position: absolute;top: 16px;right: 20px;- font-size: 18px;- color: var(--ash);+ font-size: 16px;+ color: var(--mute);transition: color 180ms ease, transform 180ms ease;}.featured:hover .featuredArrow {- color: var(--agent-accent, var(--gold));+ color: var(--ink);transform: translate(2px, -2px);}@@ -135,11 +120,11 @@}.fadeLeft {left: 0;- background: linear-gradient(90deg, var(--abyss) 0%, rgba(0, 0, 0, 0) 100%);+ background: linear-gradient(90deg, var(--canvas) 0%, rgba(10, 10, 10, 0) 100%);}.fadeRight {right: 0;- background: linear-gradient(270deg, var(--abyss) 0%, rgba(0, 0, 0, 0) 100%);+ background: linear-gradient(270deg, var(--canvas) 0%, rgba(10, 10, 10, 0) 100%);}.marquee {display: flex;@@ -164,10 +149,11 @@display: inline-flex;align-items: center;gap: 12px;- padding: 14px 18px;- background: var(--iron);- border: 1px solid var(--charcoal);- color: var(--white);+ padding: 12px 20px;+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-pill);+ color: var(--ink);text-decoration: none;flex-shrink: 0;transition:@@ -175,15 +161,15 @@background 180ms ease;}.tile:hover {- border-color: var(--agent-accent, var(--gold));- background: var(--charcoal);+ border-color: var(--border-ghost);+ background: var(--canvas-soft);}.tileLogo {- width: 40px;- height: 40px;- border-radius: 8px;+ width: 36px;+ height: 36px;+ border-radius: 50%;overflow: hidden;- background: var(--abyss);+ background: var(--canvas);flex-shrink: 0;object-fit: cover;}@@ -194,15 +180,15 @@}.tileName {font-size: 13.5px;- font-weight: 900;+ font-weight: 500;letter-spacing: -0.01em;- color: var(--white);- text-transform: uppercase;+ color: var(--ink);}.tileFrom {- font-size: 10px;- letter-spacing: 0.96px;- color: var(--ash);+ font-family: var(--font-mono);+ font-size: 9.5px;+ letter-spacing: 1px;+ color: var(--mute);text-transform: uppercase;}diff --git a/website/components/Agents.tsx b/website/components/Agents.tsxindex 0713e1ed..9ab4c80d 100644--- a/website/components/Agents.tsx+++ b/website/components/Agents.tsx@@ -31,7 +31,7 @@ const FEATURED: Agent[] = [logo: "https://svgl.app/library/github_dark.svg",accent: "#24292E",href: "https://docs.github.com/copilot/github-copilot-in-the-cli",- pitch: "11 hooks + MCP · framed stdio",+ pitch: "MCP + plugin hooks and skills",sub: "NATIVE PLUGIN",},{@@ -84,6 +84,16 @@ const FEATURED: Agent[] = [pitch: "Native Memory trait backend (Rust)",sub: "NATIVE BACKEND",},+ {+ id: "opencode",+ name: "OpenCode",+ from: "SST",+ logo: "/opencode.png",+ accent: "#F5A623",+ href: "https://github.com/rohitg00/agentmemory/tree/main/plugin/opencode",+ pitch: "Capture plugin with per-session project attribution",+ sub: "NATIVE PLUGIN",+ },];const MARQUEE: Agent[] = [@@ -167,6 +177,14 @@ const MARQUEE: Agent[] = [accent: "#615CED",href: "https://github.com/QwenLM/qwen-code",},+ {+ id: "dsh",+ name: "DeepSeek Harness",+ from: "DeepSeek",+ logo: "https://svgl.app/library/deepseek.svg",+ accent: "#4D6BFE",+ href: "https://github.com/deepseek-ai/deepseek-harness",+ },{id: "kiro",name: "Kiro",@@ -175,14 +193,6 @@ const MARQUEE: Agent[] = [accent: "#FF9900",href: "https://kiro.dev",},- {- id: "opencode",- name: "OpenCode",- from: "opencode-ai",- logo: "https://github.com/opencode-ai.png",- accent: "#22C55E",- href: "https://github.com/opencode-ai/opencode",- },{id: "roo",name: "Roo Code",@@ -232,7 +242,6 @@ function FeaturedCard({ a }: { a: Agent }) {href={a.href}target="_blank"rel="noopener"- style={{ ["--agent-accent" as string]: a.accent }}><div className={styles.featuredHead}><div className={styles.featuredLogo}>@@ -265,7 +274,6 @@ function MarqueeTile({ a }: { a: Agent }) {href={a.href}target="_blank"rel="noopener"- style={{ ["--agent-accent" as string]: a.accent }}><Imagesrc={a.logo}@@ -288,14 +296,15 @@ export function Agents() {return (<section className={styles.wrap} id="agents" aria-labelledby="agents-title"><header className="section-head">- <span className="section-eyebrow">WORKS WITH</span>+ <span className="section-eyebrow">Works with</span><h2 id="agents-title" className="section-title">- SEVEN NATIVE PLUGINS.<br />REST MCP-NATIVE.+ Seven native plugins.<br />Rest MCP-native.</h2><p className="section-lede">- NATIVE PLUGINS FOR CLAUDE CODE, COPILOT CLI, CODEX CLI, OPENCLAW,- HERMES, PI, AND OPENHUMAN. EVERY OTHER MCP CLIENT GETS IT FOR FREE.- `agentmemory connect <agent>` AUTO-WIRES THEM ALL.+ Native plugins for Claude Code, Copilot CLI, Codex CLI, OpenClaw,+ Hermes, pi, and OpenHuman. OpenCode gets a plugin that attributes+ each session to its own project. Every other MCP client gets it for+ free. `agentmemory connect <agent>` auto-wires them all.</p></header>diff --git a/website/components/CommandCenter.module.css b/website/components/CommandCenter.module.cssindex 86ef6e09..ef9b6fc2 100644--- a/website/components/CommandCenter.module.css+++ b/website/components/CommandCenter.module.css@@ -1,8 +1,7 @@.wrap {padding: 96px 0;- background: var(--iron);- border-top: 1px solid var(--charcoal);- border-bottom: 1px solid var(--charcoal);+ border-top: 1px solid var(--hairline);+ border-bottom: 1px solid var(--hairline);}.tabs {max-width: 1200px;@@ -11,45 +10,50 @@display: grid;grid-template-columns: repeat(4, 1fr);gap: 0;- border: 1px solid var(--charcoal);- background: var(--abyss);+}+.tabs > * {+ border: 1px solid var(--hairline);+ border-right: none;+}+.tabs > *:first-child {+ border-radius: var(--radius-card) 0 0 var(--radius-card);+}+.tabs > *:last-child {+ border-right: 1px solid var(--hairline);+ border-radius: 0 var(--radius-card) var(--radius-card) 0;}.tab {- padding: 18px 18px;+ padding: 16px 18px;text-align: left;display: flex;flex-direction: column;gap: 6px;- border-right: 1px solid var(--charcoal);+ background: var(--canvas-card);transition:background 200ms ease,color 200ms ease;cursor: pointer;- background: transparent;-}-.tab:last-child {- border-right: none;}.tab:hover {- background: var(--charcoal);+ background: var(--canvas-soft);}.tabActive {- background: var(--gold) !important;- color: var(--abyss) !important;+ background: var(--ink) !important;+ color: var(--canvas) !important;}.tabActive .tabSub {- color: rgba(0, 0, 0, 0.7) !important;+ color: rgba(10, 10, 10, 0.65) !important;}.tabLabel {- font-size: 16px;- font-weight: 900;+ font-size: 15px;+ font-weight: 500;letter-spacing: -0.01em;- text-transform: uppercase;}.tabSub {+ font-family: var(--font-mono);font-size: 10px;- letter-spacing: 0.96px;- color: var(--ash);+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}.panel {@@ -65,19 +69,16 @@padding-top: 8px;}.panelTitle {- font-size: clamp(24px, 2.4vw, 32px);- font-weight: 900;- letter-spacing: -0.01em;- text-transform: uppercase;+ font-size: clamp(24px, 2.4vw, 30px);+ font-weight: 400;+ letter-spacing: -0.02em;margin: 0 0 16px;- color: var(--white);+ color: var(--ink);}.panelBlurb {- font-size: 14px;- letter-spacing: 0.12px;- color: var(--mist);- text-transform: uppercase;- line-height: 1.6;+ font-size: 14.5px;+ color: var(--body);+ line-height: 1.65;margin: 0 0 24px;}.panelBullets {@@ -91,36 +92,37 @@display: flex;gap: 12px;align-items: flex-start;- font-size: 12px;- letter-spacing: 0.12px;- color: var(--steel);+ font-family: var(--font-mono);+ font-size: 11.5px;+ letter-spacing: 0.6px;+ color: var(--mute);text-transform: uppercase;line-height: 1.55;}.panelBullets span {- color: var(--gold);- font-weight: 700;+ color: var(--ink);margin-top: 1px;}.launch {margin: 0;- padding: 16px 18px;- background: var(--abyss);- border: 1px solid var(--charcoal);+ padding: 15px 18px;+ background: var(--canvas-soft);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);font-family: var(--font-mono);font-size: 13px;- color: var(--white);+ color: var(--ink);overflow-x: auto;white-space: nowrap;}.launchPrompt {- color: var(--gold);- font-weight: 700;+ color: var(--sunset);margin-right: 8px;}.panelFrame {- background: var(--abyss);- border: 1px solid var(--charcoal);+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);overflow: hidden;}.frameChrome {@@ -128,34 +130,30 @@align-items: center;gap: 8px;padding: 10px 14px;- background: var(--iron);- border-bottom: 1px solid var(--charcoal);+ background: var(--canvas-soft);+ border-bottom: 1px solid var(--hairline);}.dot {- width: 10px;- height: 10px;+ width: 9px;+ height: 9px;border-radius: 50%;display: inline-block;+ background: var(--canvas-mid);}-.red {- background: #ff5f57;-}-.yellow {- background: #febc2e;-}+.red,+.yellow,.green {- background: #28c840;+ background: var(--canvas-mid);}.frameTitle {margin-left: 8px;font-family: var(--font-mono);font-size: 11px;- color: var(--ash);- letter-spacing: 0.12px;- text-transform: uppercase;+ color: var(--mute);+ letter-spacing: 0.6px;}.frameShot {- background: var(--abyss);+ background: var(--canvas);min-height: 300px;}@@ -166,11 +164,25 @@.tabs {grid-template-columns: 1fr 1fr;}- .tab {- border-bottom: 1px solid var(--charcoal);+ .tabs > * {+ border: 1px solid var(--hairline);+ border-radius: 0;+ }+ .tabs > *:first-child {+ border-radius: var(--radius-card) 0 0 0;+ }+ .tabs > *:nth-child(2) {+ border-left: none;+ border-radius: 0 var(--radius-card) 0 0;+ }+ .tabs > *:nth-child(3) {+ border-top: none;+ border-radius: 0 0 0 var(--radius-card);}- .tab:nth-child(2n) {- border-right: none;+ .tabs > *:last-child {+ border-top: none;+ border-left: none;+ border-radius: 0 0 var(--radius-card) 0;}}@media (max-width: 640px) {diff --git a/website/components/CommandCenter.tsx b/website/components/CommandCenter.tsxindex 451a1d74..2c52c481 100644--- a/website/components/CommandCenter.tsx+++ b/website/components/CommandCenter.tsx@@ -7,13 +7,13 @@ import styles from "./CommandCenter.module.css";type Tab = "viewer" | "console" | "state" | "traces";const TABS: Array<{ id: Tab; label: string; sub: string }> = [- { id: "viewer", label: "VIEWER", sub: ":3113 · LIVE OBSERVATION STREAM" },- { id: "console", label: "iii CONSOLE", sub: ":3114 · ENGINE DASHBOARD" },- { id: "state", label: "STATE", sub: "RAW KV BROWSER + JSON EDITOR" },- { id: "traces", label: "TRACES", sub: "OTEL WATERFALL + FLAME" },+ { id: "viewer", label: "Viewer", sub: ":3113 · LIVE OBSERVATION STREAM" },+ { id: "console", label: "iii Console", sub: ":3114 · ENGINE DASHBOARD" },+ { id: "state", label: "State", sub: "RAW KV BROWSER + JSON EDITOR" },+ { id: "traces", label: "Traces", sub: "OTEL WATERFALL + FLAME" },];-const PANELS: Record<+function buildPanels(restEndpoints: number): Record<Tab,{title: string;@@ -23,70 +23,72 @@ const PANELS: Record<alt: string;launch: string;}-> = {- viewer: {- title: "SHIP-WITH VIEWER · PORT 3113",- blurb:- "The agentmemory server auto-starts a real-time viewer on port 3113. No install, no config. Everything the server sees, the viewer shows.",- bullets: [- "LIVE OBSERVATION STREAM · EVERY HOOK AS IT FIRES",- "SESSION EXPLORER · REPLAY ANY PAST SESSION",- "MEMORY BROWSER · FILTER BY PROJECT / TYPE / CONFIDENCE",- "KNOWLEDGE GRAPH VISUALIZATION · FORCE-DIRECTED",- "HEALTH DASHBOARD · HEAP / RSS / EVENT LOOP LAG",- ],- img: "/demo.gif",- alt: "agentmemory viewer live demo",- launch: "open http://localhost:3113",- },- console: {- title: "iii CONSOLE · FIRST-CLASS",- blurb:- "agentmemory runs on the iii engine, so the official iii console gives engine-level visibility: every function call, every worker, every queue, every trace. From v0.9.16 the agentmemory CLI prompts to install iii console alongside the engine. Launch on :3114 so the viewer keeps :3113.",- bullets: [- "REGISTERED FUNCTIONS · INVOKE ANY DIRECTLY WITH JSON",- "121 HTTP ENDPOINTS · REPLAY ANY REST CALL",- "WEBSOCKET STREAM MONITOR · WATCH FRAMES LIVE",- "OTEL EXPORTER = MEMORY (DEFAULT) · TRACES STAY LOCAL",- "NO AUTH · BIND TO 127.0.0.1 ONLY",- ],- img: "/dashboard.png",- alt: "iii console dashboard",- launch: "iii-console --port 3114 --engine-port 3111",- },- state: {- title: "RAW KV BROWSER",- blurb:- "Three-panel view of the key/value store behind every memory, session, retention score, audit row, and access log. Edit JSON in place.",- bullets: [- "SCOPED NAMESPACES · mem:memories / mem:sessions / mem:retention",- "JSON-NATIVE EDIT · NO MIGRATIONS",- "AUDIT ROW PER CHANGE · FORENSIC TRAIL",- "BACKED BY iii STATE ADAPTERS · IN-MEMORY OR FILE-BASED",- ],- img: "/states.png",- alt: "iii console state browser",- launch: "open http://localhost:3114/states",- },- traces: {- title: "OPENTELEMETRY OUT OF THE BOX",- blurb:- "iii-observability ships with exporter: memory, sampling_ratio: 1.0. Every memory operation emits a trace span + structured log. Swap to OTLP for Jaeger / Honeycomb / Tempo.",- bullets: [- "WATERFALL · FLAME · SERVICE BREAKDOWN · TRACE MAP",- "FILTER BY TRACE ID · SERVICE · DURATION",- "MEMORY SEARCH SPAN TREE · BM25 → VECTOR → GRAPH → RERANK",- "SWAP EXPORTER TO OTLP FOR PROD TELEMETRY",- ],- img: "/traces-waterfall.png",- alt: "iii console traces waterfall",- launch: "open http://localhost:3114/traces",- },-};+> {+ return {+ viewer: {+ title: "Ship-with viewer · port 3113",+ blurb:+ "The agentmemory server auto-starts a real-time viewer on port 3113. No install, no config. Tabs refresh live as hooks fire, and any past session replays in place.",+ bullets: [+ "LIVE OBSERVATION STREAM · EVERY HOOK AS IT FIRES",+ "SESSION EXPLORER · REPLAY ANY PAST SESSION",+ "MEMORY BROWSER · FILTER BY PROJECT / TYPE / CONFIDENCE",+ "KNOWLEDGE GRAPH VISUALIZATION · FORCE-DIRECTED",+ "HEALTH DASHBOARD · HEAP / RSS / EVENT LOOP LAG",+ ],+ img: "/demo.gif",+ alt: "agentmemory viewer live demo",+ launch: "open http://localhost:3113",+ },+ console: {+ title: "iii console · first-class",+ blurb:+ "agentmemory runs on the iii engine, so the official iii console gives engine-level visibility: every function call, every worker, every queue, every trace. From v0.9.16 the agentmemory CLI prompts to install iii console alongside the engine. Launch on :3114 so the viewer keeps :3113.",+ bullets: [+ "REGISTERED FUNCTIONS · INVOKE ANY DIRECTLY WITH JSON",+ `${restEndpoints} HTTP ENDPOINTS · REPLAY ANY REST CALL`,+ "WEBSOCKET STREAM MONITOR · WATCH FRAMES LIVE",+ "OTEL EXPORTER = MEMORY (DEFAULT) · TRACES STAY LOCAL",+ "NO AUTH · BIND TO 127.0.0.1 ONLY",+ ],+ img: "/dashboard.png",+ alt: "iii console dashboard",+ launch: "iii-console --port 3114 --engine-port 3111",+ },+ state: {+ title: "Raw KV browser",+ blurb:+ "Three-panel view of the key/value store behind every memory, session, retention score, audit row, and access log. Edit JSON in place.",+ bullets: [+ "SCOPED NAMESPACES · mem:memories / mem:sessions / mem:retention",+ "JSON-NATIVE EDIT · NO MIGRATIONS",+ "AUDIT ROW PER CHANGE · FORENSIC TRAIL",+ "BACKED BY iii STATE ADAPTERS · IN-MEMORY OR FILE-BASED",+ ],+ img: "/states.png",+ alt: "iii console state browser",+ launch: "open http://localhost:3114/states",+ },+ traces: {+ title: "OpenTelemetry out of the box",+ blurb:+ "iii-observability ships with exporter: memory, sampling_ratio: 1.0. Every memory operation emits a trace span + structured log. Swap to OTLP for any external tracing backend.",+ bullets: [+ "WATERFALL · FLAME · SERVICE BREAKDOWN · TRACE MAP",+ "FILTER BY TRACE ID · SERVICE · DURATION",+ "MEMORY SEARCH SPAN TREE · BM25 → VECTOR → GRAPH → RERANK",+ "SWAP EXPORTER TO OTLP FOR PROD TELEMETRY",+ ],+ img: "/traces-waterfall.png",+ alt: "iii console traces waterfall",+ launch: "open http://localhost:3114/traces",+ },+ };+}-export function CommandCenter() {+export function CommandCenter({ restEndpoints }: { restEndpoints: number }) {const [tab, setTab] = useState<Tab>("viewer");- const panel = PANELS[tab];+ const panel = buildPanels(restEndpoints)[tab];return (<section@@ -95,14 +97,14 @@ export function CommandCenter() {aria-labelledby="cc-title"><header className="section-head">- <span className="section-eyebrow">COMMAND CENTER</span>+ <span className="section-eyebrow">Command center</span><h2 id="cc-title" className="section-title">- TWO UIs.<br />ONE MEMORY RUNTIME.+ Two UIs.<br />One memory runtime.</h2><p className="section-lede">- AGENTMEMORY SHIPS A REAL-TIME VIEWER FOR YOUR MEMORIES AND AN- ENGINE-LEVEL CONSOLE FOR EVERY FUNCTION, TRIGGER, AND OTEL SPAN.- BOTH ARE FIRST-CLASS — INSTALLED INLINE BY THE CLI ON FIRST RUN.+ agentmemory ships a real-time viewer for your memories and an+ engine-level console for every function, trigger, and OTel span.+ Both are first-class, installed inline by the CLI on first run.</p></header><div className={styles.tabs} role="tablist" aria-label="Command center">diff --git a/website/components/Compare.module.css b/website/components/Compare.module.cssindex 2256bea9..d280a87f 100644--- a/website/components/Compare.module.css+++ b/website/components/Compare.module.css@@ -1,48 +1,58 @@.compare {padding: 96px 0;- background: var(--iron);- border-top: 1px solid var(--charcoal);- border-bottom: 1px solid var(--charcoal);+ border-top: 1px solid var(--hairline);+ border-bottom: 1px solid var(--hairline);}.table {max-width: 1100px;margin: 0 auto;padding: 0 40px;}+.table > .row:first-child {+ border-radius: var(--radius-card) var(--radius-card) 0 0;+}+.table > .row:last-child {+ border-radius: 0 0 var(--radius-card) var(--radius-card);+ border-bottom: 1px solid var(--hairline);+}.row {display: grid;grid-template-columns: 1.4fr 1.3fr 1fr 1fr 1fr;gap: 16px;- padding: 20px 24px;- border-bottom: 1px solid var(--charcoal);+ padding: 16px 24px;+ border: 1px solid var(--hairline);+ border-bottom: none;align-items: center;font-size: 14px;- letter-spacing: 0.12px;- word-break: break-word;+ overflow-wrap: anywhere;}.row > span {- color: var(--steel);- text-transform: uppercase;+ color: var(--body);}.row > span:first-child {- color: var(--white);- font-weight: 700;+ font-family: var(--font-mono);+ font-size: 11.5px;+ letter-spacing: 1.2px;+ text-transform: uppercase;+ color: var(--mute);}.head {- border-bottom-color: var(--gold);+ background: var(--canvas-soft);}.head span {+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--ash) !important;+ letter-spacing: 1.2px;+ text-transform: uppercase;+ color: var(--mute) !important;font-weight: 400 !important;}.head .mine {- color: var(--gold) !important;+ color: var(--ink) !important;}.mine {- color: var(--gold) !important;- font-weight: 700 !important;+ color: var(--ink) !important;+ font-weight: 500 !important;}@media (max-width: 1024px) {.row {diff --git a/website/components/Compare.tsx b/website/components/Compare.tsxindex d743850f..872e621d 100644--- a/website/components/Compare.tsx+++ b/website/components/Compare.tsx@@ -7,7 +7,7 @@ const ROWS = [["MCP TOOLS", "51", "12", "18", "9"],["AUTO-HOOKS", "12", "0", "0", "0"],["NATIVE PLUGINS", "6", "—", "—", "—"],- ["OPEN SOURCE", "YES (APACHE-2.0)", "YES", "YES", "YES"],+ ["OPEN SOURCE", "Yes (Apache-2.0)", "Yes", "Yes", "Yes"],];export function Compare() {@@ -16,11 +16,12 @@ export function Compare() {<header className="section-head"><span className="section-eyebrow">VS.</span><h2 id="cmp-title" className="section-title">- VS. THE FIELD.+ Vs. the field.</h2><p className="section-lede">- NUMBERS STRAIGHT FROM THE LONGMEMEVAL-S BENCHMARK AND EACH PROJECT'S- OWN DOCS. SHIP WHAT YOU WANT — WE JUST PICKED THE ONE WITH RECEIPTS.+ Numbers straight from the LongMemEval-S benchmark and each+ project's own docs. Ship what you want — we just picked the one+ with receipts.</p></header><div className={styles.table} role="table" aria-label="Comparison">diff --git a/website/components/FeaturedIn.module.css b/website/components/FeaturedIn.module.cssindex c26e59a1..07a3bbcb 100644--- a/website/components/FeaturedIn.module.css+++ b/website/components/FeaturedIn.module.css@@ -1,8 +1,8 @@.wrap {padding: 48px 0 56px;- background: var(--ink);- border-top: 1px solid var(--charcoal);- border-bottom: 1px solid var(--charcoal);+ background: var(--canvas);+ border-top: 1px solid var(--hairline);+ border-bottom: 1px solid var(--hairline);}.wrapCompact {padding: 36px 0 0;@@ -26,7 +26,7 @@font-family: var(--font-mono);font-size: 11px;letter-spacing: 2.4px;- color: var(--ash);+ color: var(--mute);text-transform: uppercase;display: flex;align-items: center;@@ -39,12 +39,12 @@content: "";flex: 0 0 80px;height: 1px;- background: var(--charcoal);+ background: var(--hairline);}.row {display: grid;grid-template-columns: repeat(4, 1fr);- gap: 20px;+ gap: 16px;width: 100%;max-width: 1100px;align-items: stretch;@@ -56,21 +56,21 @@gap: 14px;align-items: center;padding: 18px 22px;- border: 1px solid var(--charcoal);- background: var(--iron);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ background: var(--canvas-card);text-decoration: none;- color: var(--white);- transition: border-color 0.12s ease, transform 0.12s ease, background 0.12s ease;+ color: var(--ink);+ transition: border-color 0.15s ease, background 0.15s ease;min-height: 96px;}.cell:hover,.cell:focus-visible {- border-color: var(--gold);- transform: translateY(-1px);- background: #16161a;+ border-color: var(--border-ghost);+ background: var(--canvas-soft);}.cell:focus-visible {- outline: 2px solid var(--gold);+ outline: 2px solid rgba(255, 255, 255, 0.55);outline-offset: 2px;}.cellBadge {@@ -84,9 +84,9 @@.logo {width: 56px;height: 56px;- border-radius: 8px;+ border-radius: var(--radius-card);object-fit: cover;- background: var(--ink);+ background: var(--canvas);}.badgeImg {width: 100%;@@ -108,31 +108,28 @@min-width: 0;}.name {- font-family: var(--font-mono);font-size: 14px;- letter-spacing: 0.6px;- color: var(--white);- font-weight: 700;- text-transform: uppercase;+ font-weight: 500;+ color: var(--ink);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.sub {font-family: var(--font-mono);- font-size: 11px;+ font-size: 10.5px;letter-spacing: 0.8px;- color: var(--steel);+ color: var(--mute);text-transform: uppercase;}.arrow {font-family: var(--font-mono);- color: var(--ash);+ color: var(--mute);font-size: 14px;- transition: color 0.12s ease, transform 0.12s ease;+ transition: color 0.15s ease, transform 0.15s ease;}.cell:hover .arrow {- color: var(--gold);+ color: var(--ink);transform: translate(2px, -2px);}@media (max-width: 980px) {diff --git a/website/components/Features.module.css b/website/components/Features.module.cssindex d1306f6e..79bbe30d 100644--- a/website/components/Features.module.css+++ b/website/components/Features.module.css@@ -8,57 +8,53 @@list-style: none;display: grid;grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));- gap: 1px;- background: var(--charcoal);- border: 1px solid var(--charcoal);+ gap: 16px;}.tile {- background: var(--abyss);- padding: 32px 28px;- transition:- background 200ms ease,- transform 200ms ease;- min-height: 260px;+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ padding: 28px;+ transition: background 200ms ease;+ min-height: 240px;}.tile:hover {- background: var(--iron);- transform: translateY(-2px);+ background: var(--canvas-soft);}.kPill {display: inline-flex;align-items: baseline;gap: 8px;- padding: 6px 10px;- border: 1px solid var(--gold);+ padding: 5px 12px;+ border: 1px solid var(--hairline);+ border-radius: var(--radius-pill);margin-bottom: 20px;}.k {- font-size: 16px;- font-weight: 900;- color: var(--gold);- letter-spacing: -0.01em;+ font-family: var(--font-mono);+ font-size: 13px;+ font-weight: 500;+ color: var(--ink);}.unit {+ font-family: var(--font-mono);font-size: 10px;- letter-spacing: 0.96px;- color: var(--gold-soft);+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}.tileTitle {margin: 0 0 12px;- font-size: 20px;- font-weight: 900;+ font-size: 19px;+ font-weight: 500;letter-spacing: -0.01em;- text-transform: uppercase;- color: var(--white);+ color: var(--ink);}.tileText {margin: 0;- font-size: 13px;- color: var(--steel);- letter-spacing: 0.12px;- line-height: 1.6;- text-transform: none;+ font-size: 13.5px;+ color: var(--body);+ line-height: 1.65;}@media (max-width: 640px) {.grid {diff --git a/website/components/Features.tsx b/website/components/Features.tsxindex d6245807..55f259d5 100644--- a/website/components/Features.tsx+++ b/website/components/Features.tsx@@ -11,99 +11,99 @@ export function Features({ hooks, mcpTools, restEndpoints }: Props) {{k: `${hooks}`,unit: "AUTO-HOOKS",- title: "CAPTURE EVERYTHING",+ title: "Capture everything",text:- "Every PreToolUse, PostToolUse, SessionStart, Stop, and the rest fire into the memory pipeline without a line of glue code. Install the plugin, done.",+ "Every session start, prompt, tool call, and stop fires into the memory pipeline with no glue code. Install the plugin and capture begins.",},{k: `${mcpTools}`,unit: "MCP TOOLS",- title: "NATIVE MCP SURFACE",+ title: "Native MCP surface",text:- "memory_save, memory_recall, memory_smart_search, memory_sessions, governance, audit, export — full surface behind a single MCP server.",+ "memory_save, memory_recall, memory_smart_search, memory_sessions, governance, audit, export: the full surface behind a single MCP server. Saving a near-duplicate returns a similarTo hint instead of a second copy.",},{k: `${restEndpoints}`,unit: "REST ENDPOINTS",- title: "HTTP FIRST",+ title: "HTTP first",text:- "Every MCP tool has a REST twin under /agentmemory/*. Curl it. Fetch it from the browser. Proxy it from your own agent.",+ "Every MCP tool has a REST twin under /agentmemory/*. Curl it, fetch it from the browser, or proxy it from your own agent.",},{k: "BM25",unit: "+ VECTOR + GRAPH",- title: "TRIPLE-STREAM RECALL",+ title: "Hybrid recall",text:- "Hybrid retrieval pipes lexical, semantic, and relational scores through an on-device reranker. 95.2% R@5 on LongMemEval-S.",+ "The primary recall path ranks lexical, semantic, and graph scores together, reranked on device. Superseded versions stay out of results while their history stays queryable.",+ },+ {+ k: "5",+ unit: "ORIGIN CHANNELS",+ title: "Provenance built in",+ text:+ "Every record carries write-time provenance: user, agent, tool, import, or shared. Pass agentId through save and recall to scope memory per agent.",},{k: "AUTO",unit: "CONSOLIDATION",- title: "RAW → SEMANTIC",+ title: "Raw to semantic",text:- "Hourly sweep compresses observations into semantic memories, merges duplicates, decays stale rows with retention scoring, and emits a batched audit row.",+ "Activates with an LLM provider key. Consolidation runs on session stop: observations compress into semantic memories, duplicates merge, stale rows decay with retention scoring, and audit rows record the sweep.",},{k: "∞",unit: "REPLAY",- title: "JSONL SESSION IMPORT",+ title: "JSONL session import",text:- "Point agentmemory at a Claude Code JSONL transcript and it rehydrates the full session — observations, tool uses, timeline — into the store.",+ "Point agentmemory at a Claude Code JSONL transcript and it rehydrates the session, indexes it for search, and derives crystals and lessons from what it finds.",},{k: "GRAPH",unit: "EXTRACTION",- title: "KNOWLEDGE GRAPH",+ title: "Knowledge graph",+ text:+ "Entities and relations extract from observations when an LLM provider key is set and graph extraction is enabled. Query with /agentmemory/graph. Visualize in the viewer. Temporal edges supported.",+ },+ {+ k: "IDX",+ unit: "LESSON RECALL",+ title: "Lessons that resurface",text:- "Entities and relations extracted on compress. Query with /agentmemory/graph. Visualize in the viewer. Temporal edges supported.",+ "Save a lesson once, recall it by relevance later. Lessons live in a dedicated BM25 index with confidence and recency reranking, with save, recall, and delete over MCP and REST.",},{k: "MESH",unit: "FEDERATION",- title: "PEER-TO-PEER SYNC",+ title: "Peer-to-peer sync",text:- "Register another agentmemory node, push / pull memories over authenticated HTTPS. Bearer-token required; no silent syncs.",+ "Register another agentmemory node and push or pull memories over authenticated HTTPS. A bearer token is required; no silent syncs.",},{k: "MD",unit: "OBSIDIAN EXPORT",- title: "YOUR NOTES, HYDRATED",- text:- "Mirror memories to a sandboxed vault directory. Frontmatter-tagged markdown, ready for Obsidian's graph view.",- },- {- k: "5",- unit: "LLM PROVIDERS",- title: "BYO MODEL",- text:- "Claude subscription (default, zero config), Anthropic API, Gemini, MiniMax, OpenRouter. Detected from env.",- },- {- k: "OTEL",- unit: "OBSERVABILITY",- title: "TRACES + LOGS",+ title: "Your notes, hydrated",text:- "iii-observability worker on by default. Exporter: memory for local, OTLP for Jaeger / Honeycomb / Tempo. Every operation produces a span.",+ "Mirror memories to a sandboxed vault directory as frontmatter-tagged markdown, ready for Obsidian's graph view.",},{k: "0",unit: "EXTERNAL DBs",- title: "ONE PROCESS",+ title: "One process",text:- "Runs as a single Node process. No Redis, Kafka, Postgres, Qdrant, Neo4j. State lives on disk as JSON. That's the whole stack.",+ "Runs as a single Node process with zero external services. State lives on disk as JSON. agentmemory stop flushes indexes before exit, in Docker mode too.",},];return (<section className={styles.wrap} id="features" aria-labelledby="feat-title"><header className="section-head">- <span className="section-eyebrow">WHAT'S INSIDE</span>+ <span className="section-eyebrow">What's inside</span><h2 id="feat-title" className="section-title">- TWELVE THINGS YOU DID NOT WANT TO BUILD.+ Twelve things you did not want to build.</h2><p className="section-lede">- AGENTMEMORY IS NOT A LIBRARY OR A VECTOR STORE. IT'S A COMPLETE MEMORY- RUNTIME — CAPTURE, RECALL, CONSOLIDATE, OBSERVE, FEDERATE.+ agentmemory is not a library or a vector store. It is a complete+ memory runtime: capture, recall, consolidate, observe, federate.</p></header><ul className={styles.grid}>diff --git a/website/components/Footer.module.css b/website/components/Footer.module.cssindex 3c26a539..913a119d 100644--- a/website/components/Footer.module.css+++ b/website/components/Footer.module.css@@ -1,7 +1,7 @@.foot {padding: 48px 40px 32px;- background: var(--abyss);- border-top: 1px solid var(--charcoal);+ background: var(--canvas);+ border-top: 1px solid var(--hairline);}.row {max-width: 1440px;@@ -13,10 +13,10 @@flex-wrap: wrap;}.mark {- font-size: 20px;- font-weight: 900;- letter-spacing: -0.01em;- text-transform: uppercase;+ font-size: 18px;+ font-weight: 500;+ letter-spacing: -0.02em;+ color: var(--ink);}.links {display: flex;@@ -24,21 +24,19 @@flex-wrap: wrap;}.links a {- font-size: 13px;- letter-spacing: 0.12px;- text-transform: uppercase;- color: var(--steel);+ font-size: 14px;+ color: var(--body);}.links a:hover {- color: var(--gold);+ color: var(--ink);}.fine {max-width: 1440px;margin: 32px auto 0;+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--ash);- text-transform: uppercase;+ letter-spacing: 0.8px;+ color: var(--mute);}@media (max-width: 640px) {.foot {diff --git a/website/components/Footer.tsx b/website/components/Footer.tsxindex 886ec46f..e0280962 100644--- a/website/components/Footer.tsx+++ b/website/components/Footer.tsx@@ -5,7 +5,7 @@ export function Footer() {<footer className={styles.foot}><div className={styles.row}><a href="#top" className={styles.mark}>- AGENTMEMORY+ agentmemory</a><nav className={styles.links} aria-label="Footer"><a@@ -13,28 +13,28 @@ export function Footer() {target="_blank"rel="noopener">- SOURCE+ Source</a><ahref="https://github.com/rohitg00/agentmemory/blob/main/CHANGELOG.md"target="_blank"rel="noopener">- CHANGELOG+ Changelog</a><a href="https://iii.dev" target="_blank" rel="noopener">- RUNS ON iii+ Runs on iii</a><ahref="https://github.com/rohitg00/agentmemory/blob/main/LICENSE"target="_blank"rel="noopener">- APACHE-2.0+ Apache-2.0</a></nav></div>- <div className={styles.fine}>© 2026 AGENTMEMORY · BUILT IN THE OPEN</div>+ <div className={styles.fine}>© 2026 agentmemory · Built in the open</div></footer>);}diff --git a/website/components/GitHubStarButton.module.css b/website/components/GitHubStarButton.module.cssindex 7aced906..50f7b63f 100644--- a/website/components/GitHubStarButton.module.css+++ b/website/components/GitHubStarButton.module.css@@ -11,7 +11,7 @@}.label {- letter-spacing: 0.08em;+ letter-spacing: 0;}.count {@@ -19,12 +19,13 @@align-items: center;justify-content: center;min-width: 2.5ch;- padding: 0 6px;+ padding: 1px 8px;margin-left: 4px;- border-radius: 3px;+ border-radius: var(--radius-pill);background: rgba(255, 255, 255, 0.08);- color: var(--mist, #cfd2d1);+ color: var(--body);+ font-family: var(--font-mono);font-variant-numeric: tabular-nums;- font-size: 0.85em;+ font-size: 0.8em;letter-spacing: 0.04em;}diff --git a/website/components/GitHubStarButton.tsx b/website/components/GitHubStarButton.tsxindex 36171d82..4656af31 100644--- a/website/components/GitHubStarButton.tsx+++ b/website/components/GitHubStarButton.tsx@@ -74,7 +74,7 @@ export function GitHubStarButton({ repo, initialStars }: Props) {target="_blank"rel="noopener noreferrer"className={`btn btn--ghost ${styles.starBtn}`}- aria-label={`Star ${repo} on GitHub${stars !== null ? ` — ${stars.toLocaleString()} stars` : ""}`}+ aria-label={`Star ${repo} on GitHub${stars !== null ? `, ${stars.toLocaleString()} stars` : ""}`}><svgaria-hidden@@ -86,7 +86,7 @@ export function GitHubStarButton({ repo, initialStars }: Props) {><path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.75.75 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Z" /></svg>- <span className={styles.label}>STAR</span>+ <span className={styles.label}>Star</span>{stars !== null && <span className={styles.count}>{formatStars(stars)}</span>}</a>);diff --git a/website/components/Hero.module.css b/website/components/Hero.module.cssindex a4924801..5cea3ee7 100644--- a/website/components/Hero.module.css+++ b/website/components/Hero.module.css@@ -5,25 +5,18 @@align-items: center;justify-content: center;overflow: hidden;- padding: 110px 24px 72px;+ padding: 120px 24px 80px;+ background: var(--canvas);}.vignette {position: absolute;inset: 0;- background:- radial-gradient(- ellipse at center,- rgba(0, 0, 0, 0) 0%,- rgba(0, 0, 0, 0.7) 75%,- rgba(0, 0, 0, 0.95) 100%- ),- linear-gradient(- 180deg,- rgba(0, 0, 0, 0.3) 0%,- rgba(0, 0, 0, 0) 30%,- rgba(0, 0, 0, 0) 70%,- rgba(0, 0, 0, 0.4) 100%- );+ background: radial-gradient(+ ellipse at center,+ rgba(10, 10, 10, 0) 0%,+ rgba(10, 10, 10, 0.5) 78%,+ rgba(10, 10, 10, 0.9) 100%+ );}.content {@@ -37,25 +30,27 @@.chip {display: inline-block;- padding: 7px 13px;- font-size: 12px;- letter-spacing: 0.96px;- color: var(--gold-soft);- border: 1px solid var(--gold-soft);+ padding: 7px 16px;+ font-family: var(--font-mono);+ font-size: 11px;+ letter-spacing: 1.4px;+ color: var(--mute);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-pill);text-transform: uppercase;- margin-bottom: 22px;+ margin-bottom: 28px;}.title {- font-size: clamp(44px, 9vw, 124px);- font-weight: 900;- line-height: 0.94;- letter-spacing: -0.02em;+ font-size: clamp(52px, 9vw, 118px);+ font-weight: 400;+ line-height: 0.96;+ letter-spacing: -0.035em;+ color: var(--ink);margin: 0;- text-transform: uppercase;display: flex;justify-content: center;- gap: 0.05em;+ gap: 0;flex-wrap: wrap;}@@ -69,7 +64,7 @@animation-delay: 120ms;}.accent {- color: var(--gold);+ color: var(--body);}@keyframes slideIn {@@ -80,12 +75,10 @@}.lede {- max-width: 720px;- margin: 24px auto 32px;- font-size: clamp(13px, 1.2vw, 16px);- letter-spacing: 0.12px;- color: var(--mist);- text-transform: uppercase;+ max-width: 620px;+ margin: 28px auto 36px;+ font-size: clamp(15px, 1.3vw, 18px);+ color: var(--body);line-height: 1.6;}@@ -109,15 +102,14 @@min-height: 0;}.title {- flex-direction: column;- font-size: clamp(40px, 14vw, 72px);+ font-size: clamp(44px, 14vw, 72px);}.lede {margin: 20px auto 24px;}.chip {font-size: 10px;- padding: 6px 10px;- margin-bottom: 18px;+ padding: 6px 12px;+ margin-bottom: 20px;}}diff --git a/website/components/Hero.tsx b/website/components/Hero.tsxindex 4d8dc430..69b3fe94 100644--- a/website/components/Hero.tsx+++ b/website/components/Hero.tsx@@ -1,7 +1,7 @@import { MemoryGraph } from "./MemoryGraph";+import { FeaturedIn } from "./FeaturedIn";import { GitHubStarButton } from "./GitHubStarButton";import { HeroNpxCommand } from "./HeroNpxCommand";-import { FeaturedIn } from "./FeaturedIn";import { getProjectMeta } from "@/lib/meta";import { fetchRepoStats } from "@/lib/github";import styles from "./Hero.module.css";@@ -18,18 +18,19 @@ export async function Hero() {ZERO EXTERNAL DATABASES · v{meta.version}</div><h1 className={styles.title} id="hero-title">- <span className={styles.word}>AGENT</span>- <span className={`${styles.word} ${styles.accent}`}>MEMORY</span>+ <span className={styles.word}>agent</span>+ <span className={`${styles.word} ${styles.accent}`}>memory</span></h1><p className={styles.lede}>- THE MEMORY LAYER YOUR CODING AGENT SHOULD HAVE HAD FROM DAY ONE.- CAPTURE EVERY SESSION. RECALL IN MILLISECONDS. RUN ANYWHERE.+ Give your coding agent a memory that survives the session. 95.2%+ retrieval recall on LongMemEval-S with about 92% fewer input tokens+ than full-context replay, all on your own machine.</p><div className={styles.cta}><HeroNpxCommand /><div className={styles.ctaSecondary}><a href="#live" className="btn btn--ghost">- SEE IT MOVE+ See it move</a><GitHubStarButtonrepo="rohitg00/agentmemory"diff --git a/website/components/HeroNpxCommand.module.css b/website/components/HeroNpxCommand.module.cssindex 06081a0b..3449b664 100644--- a/website/components/HeroNpxCommand.module.css+++ b/website/components/HeroNpxCommand.module.css@@ -3,41 +3,39 @@grid-template-columns: auto 1fr auto;align-items: center;gap: 14px;- padding: 16px 22px;+ padding: 15px 24px;min-width: 460px;max-width: 100%;- background: var(--iron);- border: 1px solid var(--gold);- color: var(--white);+ background: var(--canvas-soft);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ color: var(--ink);font-family: var(--font-mono);- font-size: 16px;+ font-size: 15px;letter-spacing: 0.02em;cursor: pointer;- transition: background 0.12s ease, transform 0.12s ease, border-color 0.12s ease;+ transition: background 0.15s ease, border-color 0.15s ease;text-align: left;}.cmd:hover {- background: #1a1a1f;- transform: translateY(-1px);+ background: var(--canvas-card);+ border-color: var(--border-ghost);}.cmd:focus-visible {- outline: 2px solid var(--gold);+ outline: 2px solid rgba(255, 255, 255, 0.55);outline-offset: 3px;}.copied {- background: var(--gold);- color: var(--ink);- border-color: var(--gold);+ border-color: var(--ok);}.copied .hint {- color: var(--ink);+ color: var(--ok);}.prompt {- color: var(--gold);- font-weight: 700;+ color: var(--sunset);}.copied .prompt {- color: var(--ink);+ color: var(--ok);}.text {overflow: hidden;@@ -47,13 +45,10 @@.hint {font-size: 10px;letter-spacing: 1.4px;- color: var(--ash);+ color: var(--mute);text-transform: uppercase;padding-left: 12px;- border-left: 1px solid var(--charcoal);-}-.copied .hint {- border-left-color: rgba(0, 0, 0, 0.2);+ border-left: 1px solid var(--hairline);}@media (max-width: 640px) {.cmd {diff --git a/website/components/Install.module.css b/website/components/Install.module.cssindex ccd4846a..dd3b462f 100644--- a/website/components/Install.module.css+++ b/website/components/Install.module.css@@ -1,7 +1,6 @@.install {padding: 112px 0;- background: var(--iron);- border-top: 1px solid var(--charcoal);+ border-top: 1px solid var(--hairline);}.cards {max-width: 1000px;@@ -16,21 +15,22 @@gap: 10px;}.stepLabel {+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--gold);+ letter-spacing: 1.4px;+ color: var(--mute);text-transform: uppercase;- font-weight: 700;}.box {display: grid;grid-template-columns: auto minmax(0, 1fr) auto;gap: 16px;align-items: center;- padding: 22px 28px;- background: var(--abyss);- border: 1px solid var(--charcoal);- color: var(--mist);+ padding: 20px 26px;+ background: var(--canvas-soft);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ color: var(--body);font-family: var(--font-mono);font-size: 14px;text-align: left;@@ -42,30 +42,29 @@cursor: pointer;}.box:hover {- border-color: var(--gold);- background: var(--charcoal);+ border-color: var(--border-ghost);+ background: var(--canvas-card);}.boxCopied {- border-color: #29c864 !important;+ border-color: var(--ok) !important;}.boxCopied .hint {- color: #29c864;+ color: var(--ok);}.prompt {- color: var(--gold);- font-weight: 700;+ color: var(--sunset);}.cmd {- color: var(--white);+ color: var(--ink);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;min-width: 0;}.hint {- color: var(--ash);- font-size: 11px;- letter-spacing: 0.96px;+ color: var(--mute);+ font-size: 10.5px;+ letter-spacing: 1.2px;text-transform: uppercase;white-space: nowrap;}diff --git a/website/components/Install.tsx b/website/components/Install.tsxindex e671aa8e..af25eee2 100644--- a/website/components/Install.tsx+++ b/website/components/Install.tsx@@ -22,16 +22,16 @@ const SIMPLE: Cmd[] = [hint: "RUNS ON :3111 · VIEWER ON :3113",},{- label: "3. SEE SEMANTIC RECALL INSTANTLY",+ label: "3. RUN THE DEMO",cmd: "agentmemory demo",- hint: "SEEDS 3 SESSIONS · PROVES HYBRID SEARCH WORKS",+ hint: "SEEDS 3 SESSIONS · SHOWS HYBRID RECALL ON REAL DATA",},];const NPX_FALLBACK: Cmd = {- label: "PREFER ZERO-INSTALL? USE NPX",+ label: "ZERO-INSTALL PATH: NPX",cmd: "npx @agentmemory/agentmemory",- hint: "REPLACES STEPS 1+2 · USES NPX CACHE — SEE README FOR CAVEAT",+ hint: "REPLACES STEPS 1+2 · USES NPX CACHE · SEE README FOR CAVEAT",};function CopyBox({ label, cmd, hint }: Cmd) {@@ -71,13 +71,15 @@ export function Install() {return (<section className={styles.install} id="install" aria-labelledby="install-title"><header className="section-head">- <span className="section-eyebrow">SHIP IT</span>+ <span className="section-eyebrow">Ship it</span><h2 id="install-title" className="section-title">- ONE INSTALL.<br />ANY AGENT.+ One install.<br />Any agent.</h2><p className="section-lede">- RUNS ON YOUR MACHINE. DATA STAYS LOCAL. BRING YOUR CLAUDE SUBSCRIPTION- — OR POINT IT AT ANTHROPIC, GEMINI, MINIMAX, OR OPENROUTER.+ Runs on your machine. Data stays local. Capture and recall need no+ LLM key; add one for Anthropic, OpenAI, Gemini, MiniMax, or+ OpenRouter to activate consolidation, graph extraction, and LLM+ compression.</p></header><div className={styles.cards}>@@ -89,12 +91,12 @@ export function Install() {</div><div className={styles.cta}><a- className="btn btn--accent"+ className="btn btn--sunset"href="https://github.com/rohitg00/agentmemory#quick-start"target="_blank"rel="noopener">- READ THE QUICKSTART+ Read the quickstart</a><aclassName="btn btn--ghost"@@ -102,7 +104,7 @@ export function Install() {target="_blank"rel="noopener">- NPM PACKAGE+ npm package</a><aclassName="btn btn--ghost"@@ -110,7 +112,7 @@ export function Install() {target="_blank"rel="noopener">- INTEGRATIONS+ Integrations</a></div></section>diff --git a/website/components/LiveTerminal.module.css b/website/components/LiveTerminal.module.cssindex 08df6d39..a4c4a3eb 100644--- a/website/components/LiveTerminal.module.css+++ b/website/components/LiveTerminal.module.css@@ -10,65 +10,62 @@display: flex;align-items: center;gap: 8px;- background: var(--iron);+ background: var(--canvas-soft);padding: 12px 16px;- border: 1px solid var(--charcoal);+ border: 1px solid var(--hairline);border-bottom: none;+ border-radius: var(--radius-card) var(--radius-card) 0 0;}.dot {- width: 10px;- height: 10px;+ width: 9px;+ height: 9px;border-radius: 50%;display: inline-block;- background: var(--charcoal);-}-.red {- background: #ff5f57;-}-.yellow {- background: #febc2e;+ background: var(--canvas-mid);}+.red,+.yellow,.green {- background: #28c840;+ background: var(--canvas-mid);}.title {margin-left: 12px;font-family: var(--font-mono);font-size: 12px;- color: var(--steel);+ color: var(--mute);}.body {margin: 0;padding: 24px 24px 16px;- background: var(--abyss);- border: 1px solid var(--charcoal);+ background: var(--canvas-card);+ border: 1px solid var(--hairline);border-top: none;font-family: var(--font-mono);font-size: 13.5px;line-height: 1.7;- color: var(--mist);+ color: var(--body);white-space: pre-wrap;min-height: 360px;overflow: hidden;}.prompt {- color: var(--gold);+ color: var(--sunset);}.comment {- color: var(--ash);+ color: var(--mute);}.ok {- color: #29c864;+ color: var(--ok);}.val {- color: var(--cyan);+ color: var(--breeze);}.caret {display: inline-block;width: 8px;height: 1em;vertical-align: text-bottom;- background: var(--gold);+ background: var(--sunset);margin-left: 2px;animation: blink 1s steps(1) infinite;}@@ -81,16 +78,17 @@display: flex;justify-content: space-between;align-items: center;- background: var(--iron);+ background: var(--canvas-soft);padding: 12px 16px;- border: 1px solid var(--charcoal);+ border: 1px solid var(--hairline);border-top: none;+ border-radius: 0 0 var(--radius-card) var(--radius-card);}.status {font-family: var(--font-mono);font-size: 11px;- color: var(--steel);- letter-spacing: 0.96px;+ color: var(--mute);+ letter-spacing: 1.2px;text-transform: uppercase;}@media (max-width: 640px) {diff --git a/website/components/LiveTerminal.tsx b/website/components/LiveTerminal.tsxindex 71ea7325..3fae5a3d 100644--- a/website/components/LiveTerminal.tsx+++ b/website/components/LiveTerminal.tsx@@ -21,8 +21,8 @@ function buildScript(mcpTools: number, hooks: number): Seg[] {t: "typed",text: 'memory.recall({ query: "where did we land the retry logic?" })\n',},- { t: "comment", text: "// triple-stream retrieval: BM25 + vector + graph\n" },- { t: "ok", text: "✓ 3 memories · p50 18ms · reranked on device\n\n" },+ { t: "comment", text: "// hybrid retrieval: BM25 + vector + graph\n" },+ { t: "ok", text: "✓ 3 memories · reranked on device\n\n" },{ t: "plain", text: "→ " },{ t: "val", text: "src/retry.ts:47 · exponentialBackoff(max=5, jitter=true)\n" },{ t: "plain", text: "→ " },@@ -37,7 +37,7 @@ function buildScript(mcpTools: number, hooks: number): Seg[] {},{ t: "prompt", text: "$ " },{ t: "typed", text: "memory.consolidate({ project: 'pay-api' })\n" },- { t: "ok", text: "✓ 18 raw observations → 4 semantic memories · audit row emitted\n" },+ { t: "ok", text: "✓ raw observations → semantic memories · audit rows written\n" },];}@@ -126,9 +126,9 @@ export function LiveTerminal({return (<section className={styles.live} id="live" aria-labelledby="live-title"><header className="section-head">- <span className="section-eyebrow">LIVE</span>+ <span className="section-eyebrow">Live</span><h2 id="live-title" className="section-title">- MEMORY THAT TYPES BACK.+ Memory that types back.</h2></header><div className={styles.terminal} data-terminal>@@ -149,7 +149,7 @@ export function LiveTerminal({play();}}>- REPLAY+ Replay</button><span className={styles.status}>{status}</span></div>diff --git a/website/components/MemoryGraph.module.css b/website/components/MemoryGraph.module.cssindex 3ac8cee6..71b3110b 100644--- a/website/components/MemoryGraph.module.css+++ b/website/components/MemoryGraph.module.css@@ -10,10 +10,12 @@right: 40px;bottom: 56px;z-index: 3;- transition: transform 200ms ease;+ border-radius: var(--radius-pill);+ transition: opacity 200ms ease;+ opacity: 0.7;}.pause:hover {- transform: scale(1.08);+ opacity: 1;}.rail {@@ -22,13 +24,13 @@right: 40px;bottom: 24px;height: 1px;- background: rgba(255, 255, 255, 0.2);+ background: rgba(255, 255, 255, 0.14);}.rail span {display: block;height: 100%;width: 0;- background: var(--white);+ background: rgba(255, 255, 255, 0.55);transition: width 60ms linear;}diff --git a/website/components/MemoryGraph.tsx b/website/components/MemoryGraph.tsxindex 8f6f5b11..730e48a5 100644--- a/website/components/MemoryGraph.tsx+++ b/website/components/MemoryGraph.tsx@@ -3,15 +3,9 @@import { useEffect, useRef, useState } from "react";import styles from "./MemoryGraph.module.css";-interface Node {- x: number;- y: number;- vx: number;- vy: number;- r: number;- hot: boolean;-}-+// Ambient hero backdrop: a quiet dither field of drifting dots.+// Every dot stays under 0.13 alpha; prefers-reduced-motion renders a+// single static frame instead of animating.export function MemoryGraph() {const canvasRef = useRef<HTMLCanvasElement>(null);const [running, setRunning] = useState(true);@@ -25,9 +19,8 @@ export function MemoryGraph() {const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;let localRunning = running && !reduceMotion;- let nodes: Node[] = [];let rafId = 0;- let pulse = 0;+ let t = 0;const size = () => {const dpr = Math.max(1, window.devicePixelRatio || 1);@@ -38,69 +31,33 @@ export function MemoryGraph() {ctx.setTransform(dpr, 0, 0, dpr, 0, 0);};- const seed = () => {- const w = canvas.clientWidth;- const h = canvas.clientHeight;- const count = Math.min(52, Math.floor((w * h) / 22000));- nodes = new Array(count).fill(0).map(() => ({- x: Math.random() * w,- y: Math.random() * h,- vx: (Math.random() - 0.5) * 0.18,- vy: (Math.random() - 0.5) * 0.18,- r: 1.2 + Math.random() * 2.2,- hot: Math.random() < 0.25,- }));- };-const draw = () => {const w = canvas.clientWidth;const h = canvas.clientHeight;ctx.clearRect(0, 0, w, h);- for (const n of nodes) {- n.x += n.vx;- n.y += n.vy;- if (n.x < 0 || n.x > w) n.vx *= -1;- if (n.y < 0 || n.y > h) n.vy *= -1;- }-- const maxDist = 160;- ctx.lineWidth = 1;- for (let i = 0; i < nodes.length; i++) {- for (let j = i + 1; j < nodes.length; j++) {- const a = nodes[i];- const b = nodes[j];- const dx = a.x - b.x;- const dy = a.y - b.y;- const d = Math.hypot(dx, dy);- if (d > maxDist) continue;- const alpha = (1 - d / maxDist) * 0.35;- const hot = a.hot && b.hot;- ctx.strokeStyle = hot- ? `rgba(255, 192, 0, ${alpha.toFixed(3)})`- : `rgba(255, 255, 255, ${(alpha * 0.5).toFixed(3)})`;- ctx.beginPath();- ctx.moveTo(a.x, a.y);- ctx.lineTo(b.x, b.y);- ctx.stroke();- }- }-- for (const n of nodes) {- const r = n.r + (n.hot ? Math.sin(pulse + n.x) * 0.8 : 0);- ctx.fillStyle = n.hot ? "#FFC000" : "rgba(255,255,255,0.85)";- ctx.beginPath();- ctx.arc(n.x, n.y, Math.max(0.5, r), 0, Math.PI * 2);- ctx.fill();- if (n.hot) {- ctx.fillStyle = "rgba(255, 192, 0, 0.12)";- ctx.beginPath();- ctx.arc(n.x, n.y, r * 3.5, 0, Math.PI * 2);- ctx.fill();+ const spacing = 26;+ const cols = Math.ceil(w / spacing) + 2;+ const rows = Math.ceil(h / spacing) + 2;++ for (let gy = 0; gy < rows; gy++) {+ for (let gx = 0; gx < cols; gx++) {+ const x = gx * spacing;+ const y = gy * spacing;+ const wave =+ Math.sin(x * 0.011 + t * 0.5) ++ Math.sin(y * 0.014 - t * 0.32) ++ Math.sin((x + y) * 0.006 + t * 0.21);+ const a = Math.max(0, wave / 3) * 0.12;+ if (a < 0.012) continue;+ const dx = Math.sin(t * 0.12 + y * 0.02) * 5;+ const dy = Math.cos(t * 0.09 + x * 0.015) * 3;+ ctx.fillStyle = `rgba(255, 255, 255, ${a.toFixed(3)})`;+ ctx.fillRect(x + dx, y + dy, 1.5, 1.5);}}- pulse += 0.04;+ t += 0.016;};const tick = () => {@@ -111,12 +68,10 @@ export function MemoryGraph() {const onResize = () => {size();- seed();draw();};size();- seed();draw();if (localRunning) rafId = requestAnimationFrame(tick);window.addEventListener("resize", onResize);@@ -141,28 +96,6 @@ export function MemoryGraph() {return (<><canvas ref={canvasRef} className={styles.canvas} aria-hidden />- <button- className={styles.pause}- aria-label={running ? "Pause animation" : "Resume animation"}- onClick={() => setRunning((v) => !v)}- >- <svg viewBox="0 0 48 48" width="44" height="44" aria-hidden>- <polygon- points="24,2 44,13 44,35 24,46 4,35 4,13"- fill="none"- stroke="#fff"- strokeWidth="1.8"- />- {running ? (- <g>- <rect x="17" y="16" width="4" height="16" fill="#fff" />- <rect x="27" y="16" width="4" height="16" fill="#fff" />- </g>- ) : (- <polygon points="18,14 34,24 18,34" fill="#fff" />- )}- </svg>- </button><div className={styles.rail} aria-hidden><span ref={railRef} /></div>diff --git a/website/components/MobileNavToggle.module.css b/website/components/MobileNavToggle.module.cssindex 0b94a268..000d5542 100644--- a/website/components/MobileNavToggle.module.css+++ b/website/components/MobileNavToggle.module.css@@ -2,7 +2,8 @@display: none;width: 40px;height: 40px;- border: 1px solid var(--charcoal);+ border: 1px solid var(--border-ghost);+ border-radius: var(--radius-pill);align-items: center;justify-content: center;flex-direction: column;@@ -10,22 +11,22 @@}.bar {display: block;- width: 18px;- height: 2px;- background: var(--white);+ width: 16px;+ height: 1.5px;+ background: var(--ink);transition:transform 220ms ease,opacity 220ms ease;transform-origin: center;}.bar1 {- transform: translateY(6px) rotate(45deg) !important;+ transform: translateY(5.5px) rotate(45deg) !important;}.bar2 {opacity: 0;}.bar3 {- transform: translateY(-6px) rotate(-45deg) !important;+ transform: translateY(-5.5px) rotate(-45deg) !important;}.sheet {@@ -34,7 +35,7 @@/* Portaled to <body>, so this sits in the root stacking context. Keptbelow the nav (z-index: 100) so the brand + close button stay on top.Fully opaque so hero content can't bleed through. */- background: var(--abyss);+ background: var(--canvas);z-index: 95;opacity: 0;pointer-events: none;@@ -59,19 +60,19 @@margin: 0;}.list li {- border-bottom: 1px solid var(--charcoal);+ border-bottom: 1px solid var(--hairline);}.list a {display: block;padding: 18px 0;font-size: 26px;- font-weight: 900;- letter-spacing: -0.01em;- text-transform: uppercase;+ font-weight: 400;+ letter-spacing: -0.02em;+ color: var(--ink);transition: color 180ms ease, padding-left 180ms ease;}.list a:hover {- color: var(--gold);+ color: var(--body);padding-left: 8px;}.foot {@@ -80,16 +81,17 @@flex-wrap: wrap;gap: 14px 20px;padding-top: 20px;- border-top: 1px solid var(--charcoal);+ border-top: 1px solid var(--hairline);}.foot a {+ font-family: var(--font-mono);font-size: 12px;- letter-spacing: 0.96px;- color: var(--steel);+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}.foot a:hover {- color: var(--gold);+ color: var(--ink);}/* Must match the breakpoint that hides .links in Nav.module.css, or thediff --git a/website/components/Nav.module.css b/website/components/Nav.module.cssindex 93c44e95..14b00de4 100644--- a/website/components/Nav.module.css+++ b/website/components/Nav.module.css@@ -5,29 +5,28 @@grid-template-columns: auto 1fr auto;align-items: center;gap: 32px;- padding: 14px 32px;+ padding: 12px 32px;z-index: 100;- background: rgba(0, 0, 0, 0.85);+ background: rgba(10, 10, 10, 0.82);backdrop-filter: blur(10px);- border-bottom: 1px solid var(--charcoal);+ border-bottom: 1px solid var(--hairline);}.brand {display: inline-flex;align-items: center;gap: 10px;- color: var(--white);+ color: var(--ink);}.brandIcon {- width: 36px;- height: 36px;+ width: 32px;+ height: 32px;display: block;}.brandWord {- font-size: 17px;- font-weight: 900;- letter-spacing: -0.01em;- text-transform: uppercase;+ font-size: 16px;+ font-weight: 500;+ letter-spacing: -0.02em;}.links {@@ -36,18 +35,14 @@gap: 28px;}.link {- font-size: 12.5px;- font-weight: 700;- letter-spacing: 0.14px;- text-transform: uppercase;- color: var(--steel);+ font-size: 14px;+ font-weight: 400;+ color: var(--body);padding: 6px 2px;- border-bottom: 1px solid transparent;- transition: color 180ms ease, border-color 180ms ease;+ transition: color 180ms ease;}.link:hover {- color: var(--white);- border-bottom-color: var(--gold);+ color: var(--ink);}.right {@@ -61,42 +56,39 @@display: inline-flex;align-items: center;gap: 8px;- padding: 9px 14px;- border: 1px solid var(--charcoal);- background: var(--iron);- color: var(--white);- font-size: 12.5px;- letter-spacing: 0.12px;+ padding: 8px 16px;+ border: 1px solid var(--border-ghost);+ border-radius: var(--radius-pill);+ background: transparent;+ color: var(--ink);+ font-size: 13px;transition:border-color 180ms ease,background 180ms ease,color 180ms ease;}.gh:hover {- border-color: var(--gold);- background: var(--charcoal);- color: var(--white);+ background: rgba(255, 255, 255, 0.06);+ color: var(--ink);}.ghLabel {- font-weight: 700;- letter-spacing: 0.96px;- text-transform: uppercase;- font-size: 11px;+ font-weight: 500;+ font-size: 13px;}.ghDivider {width: 1px;height: 14px;- background: var(--charcoal);+ background: var(--hairline);}.ghCount {font-family: var(--font-mono);- font-weight: 900;- color: var(--white);+ font-size: 12px;+ color: var(--ink);}.cta {- padding: 10px 18px !important;- font-size: 12px !important;+ padding: 9px 18px !important;+ font-size: 13px !important;}@media (max-width: 1024px) {@@ -104,7 +96,7 @@gap: 20px;}.link {- font-size: 12px;+ font-size: 13px;}.ghLabel {display: none;@@ -122,7 +114,7 @@@media (max-width: 720px) {.nav {- padding: 12px 20px;+ padding: 10px 20px;gap: 16px;grid-template-columns: 1fr auto;}diff --git a/website/components/Nav.tsx b/website/components/Nav.tsxindex 419701ab..45158854 100644--- a/website/components/Nav.tsx+++ b/website/components/Nav.tsx@@ -5,13 +5,13 @@ import { MobileNavToggle } from "./MobileNavToggle";import styles from "./Nav.module.css";const SECTIONS = [- { href: "#stack", label: "STACK" },- { href: "#features", label: "FEATURES" },- { href: "#command-center", label: "CONTROL" },- { href: "#live", label: "DEMO" },- { href: "#compare", label: "VS" },- { href: "#install", label: "INSTALL" },- { href: "/docs", label: "DOCS" },+ { href: "#stack", label: "Stack" },+ { href: "#features", label: "Features" },+ { href: "#command-center", label: "Control" },+ { href: "#live", label: "Demo" },+ { href: "#agents", label: "Agents" },+ { href: "#install", label: "Install" },+ { href: "/docs", label: "Docs" },];export async function Nav() {@@ -27,7 +27,7 @@ export async function Nav() {aria-hiddenclassName={styles.brandIcon}/>- <span className={styles.brandWord}>AGENTMEMORY</span>+ <span className={styles.brandWord}>agentmemory</span></a><nav className={styles.links} aria-label="Sections">@@ -44,7 +44,7 @@ export async function Nav() {href="https://github.com/rohitg00/agentmemory"target="_blank"rel="noopener"- aria-label={`agentmemory on GitHub — ${stats.stars} stars`}+ aria-label={`agentmemory on GitHub, ${stats.stars} stars`}><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden><path@@ -52,18 +52,18 @@ export async function Nav() {d="M12 .5C5.648.5.5 5.648.5 12c0 5.087 3.292 9.397 7.862 10.921.575.108.782-.25.782-.555v-1.96c-3.197.695-3.873-1.544-3.873-1.544-.523-1.327-1.277-1.68-1.277-1.68-1.044-.713.08-.699.08-.699 1.154.08 1.76 1.184 1.76 1.184 1.025 1.757 2.688 1.25 3.344.956.104-.742.4-1.25.728-1.537-2.552-.29-5.235-1.276-5.235-5.675 0-1.254.448-2.279 1.182-3.083-.118-.291-.513-1.461.112-3.046 0 0 .965-.31 3.162 1.178a10.964 10.964 0 0 1 2.878-.387c.977.004 1.96.131 2.878.387 2.195-1.487 3.16-1.178 3.16-1.178.626 1.585.231 2.755.113 3.046.736.804 1.18 1.829 1.18 3.083 0 4.41-2.686 5.381-5.246 5.665.411.354.778 1.053.778 2.122v3.146c0 .307.205.668.787.555C20.213 21.394 23.5 17.086 23.5 12 23.5 5.648 18.352.5 12 .5Z"/></svg>- <span className={styles.ghLabel}>GITHUB</span>+ <span className={styles.ghLabel}>GitHub</span><span className={styles.ghDivider} aria-hidden /><svg viewBox="0 0 24 24" width="14" height="14" aria-hidden><pathd="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 1.48 8.279L12 19.245l-7.416 4.168 1.48-8.279L0 9.306l8.332-1.151z"- fill="#FFC000"+ fill="var(--sunset)"/></svg><span className={styles.ghCount}>{formatCompact(stats.stars)}</span></a><a href="#install" className={`${styles.cta} btn btn--accent`}>- INSTALL+ Install</a><MobileNavToggle sections={SECTIONS} stars={stats.stars} /></div>diff --git a/website/components/Primitives.module.css b/website/components/Primitives.module.cssindex 237f8a4b..958baad1 100644--- a/website/components/Primitives.module.css+++ b/website/components/Primitives.module.css@@ -4,65 +4,42 @@.grid {display: grid;grid-template-columns: repeat(3, 1fr);- gap: 1px;+ gap: 16px;max-width: 1440px;margin: 0 auto;padding: 0 40px;- background: var(--charcoal);- border: 1px solid var(--charcoal);}.card {- background: var(--abyss);- padding: 48px 32px;- transition:- background 250ms ease,- transform 250ms ease;- position: relative;- overflow: hidden;- min-height: 280px;-}-.card::before {- content: "";- position: absolute;- inset: 0;- background: linear-gradient(- 135deg,- rgba(255, 192, 0, 0) 0%,- rgba(255, 192, 0, 0) 50%,- rgba(255, 192, 0, 0.08) 100%- );- opacity: 0;- transition: opacity 250ms ease;+ background: var(--canvas-card);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ padding: 40px 32px;+ transition: background 200ms ease;+ min-height: 260px;}.card:hover {- background: var(--iron);- transform: translateY(-4px);-}-.card:hover::before {- opacity: 1;+ background: var(--canvas-soft);}.glyph {font-family: var(--font-mono);- font-size: 14px;- color: var(--gold);- letter-spacing: 0.2px;+ font-size: 13px;+ letter-spacing: 1.2px;+ color: var(--mute);margin-bottom: 32px;}.title {- font-size: 40px;- font-weight: 900;- line-height: 0.98;- letter-spacing: -0.01em;- margin: 0 0 24px;- text-transform: uppercase;+ font-size: 30px;+ font-weight: 400;+ line-height: 1.05;+ letter-spacing: -0.02em;+ color: var(--ink);+ margin: 0 0 18px;}.text {font-size: 14px;- letter-spacing: 0.12px;- color: var(--steel);- text-transform: uppercase;+ color: var(--body);margin: 0;- line-height: 1.6;+ line-height: 1.65;}@media (max-width: 1024px) {.grid {diff --git a/website/components/Primitives.tsx b/website/components/Primitives.tsxindex 946c648f..d423841c 100644--- a/website/components/Primitives.tsx+++ b/website/components/Primitives.tsx@@ -1,82 +1,45 @@-"use client";--import { useEffect, useRef } from "react";import styles from "./Primitives.module.css";const CARDS = [{glyph: "01",- title: "HOOKS",+ title: "Hooks",text:- "12 AUTO-CAPTURE HOOKS PIPED INTO EVERY CODING AGENT. EVERY TOOL CALL, EVERY PROMPT, EVERY STOP BECOMES A COMPRESSED OBSERVATION.",+ "12 auto-capture hooks piped into every coding agent. Every tool call, every prompt, every stop becomes a compressed observation, stamped with its origin and agent.",},{glyph: "02",- title: "RECALL",+ title: "Recall",text:- "TRIPLE-STREAM RETRIEVAL — BM25 + VECTOR + KNOWLEDGE GRAPH. RERANKED ON DEVICE. P50 UNDER 20MS ON A LAPTOP.",+ "Hybrid retrieval on the primary recall path: BM25, vector, and knowledge graph scores ranked together, reranked on device. Superseded versions stay out of results.",},{glyph: "03",- title: "CONSOLIDATE",+ title: "Consolidate",text:- "HOURLY SWEEPS COMPRESS RAW OBSERVATIONS INTO SEMANTIC MEMORIES. DUPLICATES MERGED. STALE ROWS DECAYED. AUDIT ROW EMITTED EVERY DELETE.",+ "With an LLM provider key, consolidation runs on session stop: raw observations compress into semantic memories, duplicates merge, stale rows decay, audit rows record it all.",},];export function Primitives() {- const gridRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;- if (reduce || !gridRef.current) return;- const cards = gridRef.current.querySelectorAll<HTMLElement>(- "[data-tilt]",- );- const handlers: Array<[HTMLElement, (e: MouseEvent) => void, () => void]> =- [];- cards.forEach((card) => {- const onMove = (e: MouseEvent) => {- const rect = card.getBoundingClientRect();- const px = (e.clientX - rect.left) / rect.width - 0.5;- const py = (e.clientY - rect.top) / rect.height - 0.5;- card.style.transform = `translateY(-4px) rotateX(${(-py * 4).toFixed(- 2,- )}deg) rotateY(${(px * 4).toFixed(2)}deg)`;- };- const onLeave = () => {- card.style.transform = "";- };- card.addEventListener("mousemove", onMove);- card.addEventListener("mouseleave", onLeave);- handlers.push([card, onMove, onLeave]);- });- return () => {- handlers.forEach(([el, m, l]) => {- el.removeEventListener("mousemove", m);- el.removeEventListener("mouseleave", l);- });- };- }, []);-return (<section className={styles.wrap} id="stack" aria-labelledby="prim-title"><header className="section-head">- <span className="section-eyebrow">THE STACK</span>+ <span className="section-eyebrow">The stack</span><h2 id="prim-title" className="section-title">- THREE LAYERS.+ Three layers.<br />- NO FRAMEWORK TAX.+ No framework tax.</h2><p className="section-lede">- BUILT ON THE iii ENGINE — EVERY MEMORY OPERATION IS A WORKER, A- FUNCTION, OR A TRIGGER. NO REDIS. NO KAFKA. NO POSTGRES. THE ENTIRE- RUNTIME IS ONE PROCESS.+ Built on the iii engine: every memory operation is a worker, a+ function, or a trigger. No external databases, queues, or vector+ stores. The entire runtime is one process.</p></header>- <div className={styles.grid} ref={gridRef}>+ <div className={styles.grid}>{CARDS.map((c) => (- <article key={c.glyph} className={styles.card} data-tilt>+ <article key={c.glyph} className={styles.card}><div className={styles.glyph}>{c.glyph}</div><h3 className={styles.title}>{c.title}</h3><p className={styles.text}>{c.text}</p>diff --git a/website/components/ScrollProgress.tsx b/website/components/ScrollProgress.tsxindex 84ce48d2..7ad05951 100644--- a/website/components/ScrollProgress.tsx+++ b/website/components/ScrollProgress.tsx@@ -40,7 +40,7 @@ export function ScrollProgress() {display: "block",height: "100%",width: 0,- background: "var(--gold)",+ background: "rgba(255, 255, 255, 0.35)",transition: "width 80ms linear",}}/>diff --git a/website/components/Stats.module.css b/website/components/Stats.module.cssindex 785574c5..64a858d0 100644--- a/website/components/Stats.module.css+++ b/website/components/Stats.module.css@@ -1,7 +1,7 @@.stats {- border-top: 1px solid var(--charcoal);- border-bottom: 1px solid var(--charcoal);- background: var(--iron);+ border-top: 1px solid var(--hairline);+ border-bottom: 1px solid var(--hairline);+ background: var(--canvas);}.row {display: grid;@@ -12,27 +12,29 @@.stat {padding: 48px 24px;text-align: center;- border-right: 1px solid var(--charcoal);+ border-right: 1px solid var(--hairline);transition: background 250ms ease;}.stat:last-child {border-right: none;}.stat:hover {- background: var(--charcoal);+ background: var(--canvas-card);}.num {- font-size: clamp(40px, 5vw, 64px);- font-weight: 900;+ font-size: clamp(38px, 4.6vw, 56px);+ font-weight: 400;line-height: 1;- color: var(--gold);- letter-spacing: -0.02em;+ color: var(--ink);+ letter-spacing: -0.03em;+ font-variant-numeric: tabular-nums;}.label {- margin-top: 12px;+ margin-top: 14px;+ font-family: var(--font-mono);font-size: 11px;- letter-spacing: 0.96px;- color: var(--steel);+ letter-spacing: 1.2px;+ color: var(--mute);text-transform: uppercase;}@@ -41,7 +43,7 @@grid-template-columns: repeat(3, 1fr);}.stat {- border-bottom: 1px solid var(--charcoal);+ border-bottom: 1px solid var(--hairline);}.stat:nth-child(3n) {border-right: none;@@ -55,14 +57,14 @@padding: 32px 12px;}.num {- font-size: 36px;+ font-size: 34px;}.label {font-size: 10px;- letter-spacing: 0.6px;+ letter-spacing: 0.8px;}.stat:nth-child(3n) {- border-right: 1px solid var(--charcoal);+ border-right: 1px solid var(--hairline);}.stat:nth-child(2n) {border-right: none;diff --git a/website/components/Stats.tsx b/website/components/Stats.tsxindex add662c3..b09cccce 100644--- a/website/components/Stats.tsx+++ b/website/components/Stats.tsx@@ -13,10 +13,12 @@ interface StatItem {export function Stats({mcpTools,hooks,+ restEndpoints,testsPassing,}: {mcpTools: number;hooks: number;+ restEndpoints: number;testsPassing: number;}) {const rootRef = useRef<HTMLDivElement>(null);@@ -25,7 +27,7 @@ export function Stats({{ target: 95.2, suffix: "%", label: "RETRIEVAL R@5 · LONGMEMEVAL-S", float: true },{ target: 92, suffix: "%", label: "FEWER INPUT TOKENS PER SESSION" },{ target: mcpTools, label: "MCP TOOLS" },- { target: hooks, label: "AUTOHOOKS" },+ { target: restEndpoints, label: "REST ENDPOINTS" },{ target: 0, label: "EXTERNAL DATABASES" },{ target: testsPassing, label: "TESTS PASSING" },];@@ -83,10 +85,10 @@ export function Stats({.forEach((el) => io.observe(el));return () => io.disconnect();- }, [mcpTools, hooks, testsPassing]);+ }, [mcpTools, hooks, restEndpoints, testsPassing]);return (- <section className={styles.stats} aria-label="Benchmarks">+ <section className={styles.stats} aria-label="By the numbers"><div className={styles.row} ref={rootRef}>{STATS.map((s) => (<article key={s.label} className={styles.stat} data-stat>diff --git a/website/components/Testimonials.module.css b/website/components/Testimonials.module.cssindex e53615bd..97fabfa6 100644--- a/website/components/Testimonials.module.css+++ b/website/components/Testimonials.module.css@@ -1,7 +1,7 @@.wrap {padding: 96px 0 96px;- background: var(--ink);- border-top: 1px solid var(--charcoal);+ background: var(--canvas);+ border-top: 1px solid var(--hairline);}.inner {max-width: 1100px;@@ -16,7 +16,7 @@font-family: var(--font-mono);font-size: 11px;letter-spacing: 2.4px;- color: var(--ash);+ color: var(--mute);text-transform: uppercase;display: flex;align-items: center;@@ -28,41 +28,38 @@content: "";flex: 0 0 60px;height: 1px;- background: var(--charcoal);+ background: var(--hairline);}.title {- font-family: var(--font-display, var(--font-mono));- font-size: clamp(40px, 6vw, 64px);- letter-spacing: -0.02em;- line-height: 1;- color: var(--white);+ font-size: clamp(38px, 5.4vw, 56px);+ letter-spacing: -0.03em;+ line-height: 1.02;+ color: var(--ink);text-align: center;- text-transform: uppercase;- font-weight: 800;+ font-weight: 400;margin: 0;}.accent {- color: var(--gold);+ color: var(--body);}.lede {- font-family: var(--font-mono);- font-size: 13px;- letter-spacing: 0.4px;- color: var(--steel);+ font-size: 15px;+ color: var(--body);text-align: center;margin: 0 0 8px;max-width: 560px;+ line-height: 1.6;}.sectionLabel {align-self: flex-start;font-family: var(--font-mono);font-size: 11px;letter-spacing: 2.4px;- color: var(--gold);+ color: var(--mute);text-transform: uppercase;margin-top: 32px;- padding-bottom: 4px;- border-bottom: 1px solid var(--charcoal);+ padding-bottom: 8px;+ border-bottom: 1px solid var(--hairline);width: 100%;}@@ -70,7 +67,7 @@.useCases {display: grid;grid-template-columns: repeat(2, 1fr);- gap: 24px;+ gap: 16px;width: 100%;}.useCaseCard {@@ -79,22 +76,21 @@flex-direction: column;gap: 20px;padding: 32px 30px 24px;- border: 1px solid var(--charcoal);- background: var(--iron);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ background: var(--canvas-card);text-decoration: none;- color: var(--white);- transition: border-color 0.12s ease, transform 0.12s ease,- background 0.12s ease;+ color: var(--ink);+ transition: border-color 0.15s ease, background 0.15s ease;min-height: 240px;}.useCaseCard:hover,.useCaseCard:focus-visible {- border-color: var(--gold);- transform: translateY(-2px);- background: #16161a;+ border-color: var(--border-ghost);+ background: var(--canvas-soft);}.useCaseCard:focus-visible {- outline: 2px solid var(--gold);+ outline: 2px solid rgba(255, 255, 255, 0.55);outline-offset: 2px;}.useCaseTag {@@ -103,17 +99,16 @@font-family: var(--font-mono);font-size: 10px;letter-spacing: 1.4px;- color: var(--gold);+ color: var(--body);text-transform: uppercase;- border: 1px solid var(--gold);- padding: 5px 10px;- background: rgba(255, 192, 0, 0.06);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-pill);+ padding: 5px 12px;}.useCaseQuote {- font-family: var(--font-sans, system-ui);font-size: 17px;line-height: 1.55;- color: var(--white);+ color: var(--ink);margin: 0;flex: 1;}@@ -122,7 +117,7 @@.grid {display: grid;grid-template-columns: repeat(4, 1fr);- gap: 18px;+ gap: 16px;width: 100%;}.card {@@ -131,29 +126,27 @@flex-direction: column;gap: 16px;padding: 24px 22px 20px;- border: 1px solid var(--charcoal);- background: var(--iron);+ border: 1px solid var(--hairline);+ border-radius: var(--radius-card);+ background: var(--canvas-card);text-decoration: none;- color: var(--white);- transition: border-color 0.12s ease, transform 0.12s ease,- background 0.12s ease;+ color: var(--ink);+ transition: border-color 0.15s ease, background 0.15s ease;min-height: 200px;}.card:hover,.card:focus-visible {- border-color: var(--gold);- transform: translateY(-2px);- background: #16161a;+ border-color: var(--border-ghost);+ background: var(--canvas-soft);}.card:focus-visible {- outline: 2px solid var(--gold);+ outline: 2px solid rgba(255, 255, 255, 0.55);outline-offset: 2px;}.quoteMark {- font-family: var(--font-display, serif);font-size: 32px;line-height: 0;- color: var(--gold);+ color: var(--mute);display: inline;margin-right: 4px;vertical-align: -4px;@@ -163,10 +156,9 @@vertical-align: -6px;}.quote {- font-family: var(--font-sans, system-ui);font-size: 14px;line-height: 1.55;- color: var(--white);+ color: var(--body);margin: 0;flex: 1;}@@ -176,27 +168,24 @@justify-content: space-between;gap: 12px;padding-top: 12px;- border-top: 1px solid var(--charcoal);+ border-top: 1px solid var(--hairline);}.name {- font-family: var(--font-mono);- font-size: 12px;- letter-spacing: 0.6px;- color: var(--white);- text-transform: uppercase;- font-weight: 700;+ font-size: 13px;+ font-weight: 500;+ color: var(--ink);}.source {font-family: var(--font-mono);font-size: 10px;letter-spacing: 0.8px;- color: var(--ash);+ color: var(--mute);text-transform: uppercase;- transition: color 0.12s ease;+ transition: color 0.15s ease;}.card:hover .source,.useCaseCard:hover .source {- color: var(--gold);+ color: var(--ink);}@media (max-width: 980px) {@@ -214,8 +203,4 @@.wrap {padding: 64px 0 64px;}- .badge {- width: 220px;- height: 47px;- }}diff --git a/website/components/Testimonials.tsx b/website/components/Testimonials.tsxindex c48f1b9b..2b472822 100644--- a/website/components/Testimonials.tsx+++ b/website/components/Testimonials.tsx@@ -79,7 +79,7 @@ export function Testimonials() {BUILDERS USING AGENTMEMORY</div><h2 className={styles.title}>- IN THE <span className={styles.accent}>WILD.</span>+ In the <span className={styles.accent}>wild.</span></h2><p className={styles.lede}>Verbatim from the Product Hunt launch thread. Each carddiff --git a/website/lib/generated-meta.json b/website/lib/generated-meta.jsonindex 8ebf1fd0..8119b296 100644--- a/website/lib/generated-meta.json+++ b/website/lib/generated-meta.json@@ -3,6 +3,6 @@"mcpTools": 54,"hooks": 12,"restEndpoints": 130,- "testsPassing": 1610,- "generatedAt": "2026-08-09T09:15:51.690Z"+ "testsPassing": 1646,+ "generatedAt": "2026-08-15T18:47:03.286Z"}diff --git a/website/next-env.d.ts b/website/next-env.d.tsindex 9edff1c7..ce4e94a6 100644--- a/website/next-env.d.ts+++ b/website/next-env.d.ts@@ -1,6 +1,7 @@/// <reference types="next" />/// <reference types="next/image-types/global" />import "./.next/types/routes.d.ts";+import "./.next/types/root-params.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/website/public/opencode.png b/website/public/opencode.pngnew file mode 100644index 00000000..9e58e0e0Binary files /dev/null and b/website/public/opencode.png differ