agentmemory 詳細教學
對應 repo: https://github.com/rohitg00/agentmemory(15.6k stars / 1.3k forks / v0.9.21,截至 2026-05-21)
1. 專案定位
1.1 它是什麼
agentmemory 是 跨 AI 編碼 agent 的持久記憶基礎設施。把所有 agent 對話 / 工具呼叫 / 失敗 / commit 自動 capture 到本地 server(port :3111),用 BM25 + Vector embedding + Knowledge Graph 三路混合檢索,並用 4-tier 整合(working → episodic → semantic → procedural)+ Ebbinghaus 衰減 模仿人類記憶曲線。同一份記憶在 9+ 個 agent 之間共用。
1.2 它解決什麼問題
- 「每次開新 session 都要重新解釋一遍」:agent 不會記得三天前你做了什麼決定 → agentmemory 自動 recall
- 「Mem0 / Letta 太重 / 太依賴外部 DB」:agentmemory 零外部 DB(內建 SQLite via iii-engine),單檔 npm 一條命令裝完
- 「Claude Code 跟 Cursor 是兩套記憶」:agentmemory 同一個 server,每個 agent 透過 MCP / REST 接同一份
- 「LongMemEval 上要 SOTA」:R@5 95.2% > Letta 83% / Mem0 68%(在公開可重現的 benchmark 上)
1.3 與其他 memory 系統的差異
| 系統 | R@5 | 自動 capture | 外部 DB | 跨 agent | 知識圖 | 即時 viewer |
|---|---|---|---|---|---|---|
| agentmemory | 95.2% | ✅ 12 hooks | ❌ 0 | ✅ MCP + REST | ✅ Entity + BFS | ✅ :3113 |
| MemPalace | 96.6% | — | — | — | — | — |
| Letta / MemGPT | 83.2% | ❌ agent 自編輯 | Postgres + vector | runtime 內 | ❌ | Cloud only |
| Mem0 | 68.5% | ❌ 手動 add() | Qdrant / pgvector | API call | ✅ Mem0g | Cloud only |
| Khoj | — | ❌ 手動 | 多個 | ❌ | Doc links | Web UI |
| claude-mem | — | ✅ 受限 | SQLite | Claude only | ❌ | ❌ |
1.4 適合誰用
- 使用多個 AI agent 的開發者:手上同時開 Claude Code + Cursor + Codex CLI 等
- 跨 session 工作的人:今天 plan、明天 implement、後天 review 都靠記憶
- 想要 self-hosted / privacy-first 記憶層:不想把對話上傳到 mem0 cloud
- 想做研究 / 跑 benchmark 的人:repo 內
benchmark/全套完整可重現 - 想學 iii-engine(三原語 actor 模型)的人:agentmemory 是最好的 iii-engine reference
2. 安裝指南
2.1 三種安裝方式
1# (A) 全域安裝(推薦,最簡單)
2npm install -g @agentmemory/agentmemory
3# 若 EACCES:sudo npm install -g @agentmemory/agentmemory
4# 確認:
5agentmemory --version
6agentmemory --help
7
8# (B) npx(無安裝,需處理 cache)
9npx @agentmemory/agentmemory@latest
10# 若版本不對:rm -rf ~/.npm/_npx # macOS/Linux
11# Windows: rmdir /s %LOCALAPPDATA%\npm-cache\_npx
12
13# (C) Docker compose(最隔離)
14git clone --depth 1 https://github.com/rohitg00/agentmemory
15cd agentmemory
16docker compose up
17# 起 iii-init (chown /data 給 UID 65532) + iii-engine v0.11.2
18# ports: 49134 (WS) / 3111 (REST) / 3112 (MCP) / 9464 (metrics)
2.2 接到各 agent
1# Claude Code
2agentmemory connect claude-code
3# 自動寫 ~/.claude/hooks.json + plugin 註冊
4
5# Cursor
6agentmemory connect cursor
7# 自動寫 .cursor/mcp.json
8
9# 其他
10agentmemory connect codex-cli
11agentmemory connect gemini-cli
12agentmemory connect opencode
13agentmemory connect hermes # 走 integrations/hermes/
14agentmemory connect openclaw # 走 integrations/openclaw/
15agentmemory connect pi
2.3 環境需求
- Node.js(v22+ 推薦;docker-compose 用 node:24)
- macOS / Linux / Windows
- 預設不需要任何雲端服務(embedding 用本地
all-MiniLM-L6-v2) - 選用:Anthropic / OpenAI / OpenRouter API key(讓 consolidation pipeline 用 LLM 提煉)
flowchart TB
A[使用者] -->|npm install -g| B[agentmemory CLI]
B -->|agentmemory| C[Memory server :3111]
B -->|agentmemory connect X| D[Wire agent X]
D -->|hooks.json / mcp.json| E[Agent 自動接 :3112 MCP / :3111 REST]
C -->|WebSocket :49134| F[iii-engine
State + Workers]
F --> G[(SQLite ./data/state_store.db)]
C -->|optional| H[Embedding
all-MiniLM-L6-v2]
C -->|optional| I[LLM provider
Anthropic/OpenAI/OpenRouter]
3. 核心架構解析
3.1 三層結構(iii-engine 三原語)
graph TB
subgraph "iii-engine (port 49134, distroless, UID 65532)"
E1[Worker]
E2[Function]
E3[Trigger]
E4[(SQLite state_store.db)]
E5[StateModule]
end
subgraph "agentmemory (port 3111 REST / 3112 MCP / 3113 viewer)"
AM_F[src/functions/* — 業務 functions
consolidation / search / graph / reflect]
AM_T[src/triggers/api.ts — REST endpoints]
AM_M[src/mcp/server.ts — 53 MCP tools]
AM_H[src/hooks/* — 12 lifecycle hooks]
AM_V[src/viewer/ — real-time UI]
end
subgraph "Agents"
CC[Claude Code]
CR[Cursor]
CX[Codex CLI]
GC[Gemini CLI]
OC[OpenCode]
OH[Hermes/OpenClaw/pi]
end
AM_F -->|sdk.registerFunction| E2
AM_T -->|sdk.registerTrigger| E3
E2 --> E5
E5 --> E4
CC & CR & CX & GC & OC & OH -->|hook fire| AM_H
CC & CR & CX & GC & OC & OH -->|MCP tools| AM_M
AM_M --> AM_F
AM_H --> AM_F
AM_V --> AM_T
3.2 12 個 lifecycle hooks
sequenceDiagram
participant U as 使用者
participant A as Agent (Claude Code)
participant H as agentmemory hooks
participant M as Memory server :3111
U->>A: 開啟 session
A->>H: SessionStart
H->>M: 寫 session metadata
U->>A: 「help me refactor X」
A->>H: PromptSubmit
H->>M: 寫 prompt
A->>H: PreToolUse(Edit)
H->>M: 記錄 tool intent
A->>A: 執行 Edit
A->>H: PostToolUse(Edit, result)
H->>M: 記錄 result + extract entities
Note over A,H: 若失敗:
A->>H: PostToolFailure
H->>M: 記錄失敗模式
Note over A,H: 若需壓縮:
A->>H: PreCompact
H->>M: 預先儲存 important 記憶
A->>H: TaskCompleted
H->>M: 寫 task summary
U->>A: git commit
A->>H: PostCommit
H->>M: 對應 commit SHA <-> session
U->>A: 關 session
A->>H: SessionEnd / Stop
H->>M: consolidation pipeline
M->>M: working → episodic → semantic → procedural
3.3 4-tier 記憶整合
flowchart LR
A[Working Memory
剛發生的事
新鮮、頻繁存取] -->|Ebbinghaus 衰減 + 重複觸發| B[Episodic Memory
具體事件
「2026-05-19 我做了 X」]
B -->|LLM 提煉 + 重複出現| C[Semantic Memory
抽象知識
「pattern A 用 X 解」]
C -->|skill-extract.ts| D[Procedural Memory
可重複執行的技能
「X 任務的標準做法是...」]
style A fill:#FFE4B5
style B fill:#B0E0E6
style C fill:#90EE90
style D fill:#DDA0DD
實作位置:
src/functions/consolidation-pipeline.ts— 主管 pipelinesrc/functions/sliding-window.ts— working memory 視窗src/functions/skill-extract.ts— semantic → procedural
3.4 三路混合檢索(hybrid-search)
src/state/hybrid-search.ts 的設計:
- BM25(lexical,無 embedding 也能跑)— SQLite FTS5
- Vector(semantic)—
all-MiniLM-L6-v2預設、無 API key - Knowledge Graph BFS(entity + relation 走訪)— 由
graph.ts/temporal-graph.ts建
flowchart TD
Q[recall query] --> BM[BM25 score]
Q --> VE[Vector cosine]
Q --> EG[Entity 抽取]
EG --> GBFS[Graph BFS 2-hop]
BM --> R[Reciprocal Rank Fusion]
VE --> R
GBFS --> R
R --> TOP[Top-K results + scores]
3.5 隱私守門(privacy filter)
src/auth.ts / src/state/ 在 store 之前會 strip secrets:
- API key / token / password 模式(regex matched)
.env/credentials.json內容- AWS access key / GitHub PAT 等已知 pattern
3.6 8 個內建 skill
1plugin/skills/
2├── remember/ # 主動寫一條重要記憶
3├── recall/ # 用 hybrid search 撈
4├── recap/ # LLM 摘要近期 sessions
5├── handoff/ # 跨 session 交接(給下一個 session 看的 brief)
6├── forget/ # 抹掉特定記憶(永久或暫時)
7├── commit-context/ # git commit 加上 session context
8├── commit-history/ # git history × session memory join
9└── session-history/ # 列 session timeline
4. Helper Scripts 詳細用法
4.1 agentmemory CLI 命令樹
| 命令 | 用途 |
|---|---|
agentmemory | 起 memory server on :3111 |
agentmemory demo | 種 sample sessions + 驗證 recall |
agentmemory connect <agent> | 自動接 agent(claude-code / codex / cursor / gemini-cli / opencode / hermes / openclaw / pi) |
agentmemory viewer | 開 :3113 即時 viewer |
agentmemory status | 看 server 狀態 |
agentmemory stop | 停 server |
agentmemory export <path> | 把全部記憶 export 成 JSON |
agentmemory import <path> | 從 JSON 還原 |
agentmemory migrate | 升版時跑 migration(schema bump) |
4.2 npm scripts(contributor 用)
1npm test # vitest(不含 integration)
2npm run test:integration # integration tests
3npm run test:all # 全部 950+ tests
4npm run bench:load # 100k 記錄 load test
5npm run eval:longmemeval # LongMemEval benchmark
6npm run eval:coding-life # coding-life benchmark
7npm run build # tsdown → dist/
8npm run dev # tsx watch
4.3 scripts/backfill-imported-sessions.sh
把已匯入的 session 重跑一次 consolidation pipeline(用於修舊資料)。
4.4 scripts/check-env-example.mjs
CI 用:確保 .env.example 涵蓋所有 source 內用到的 env var(10.7KB 的 example file 不會 drift)。
4.5 plugin/scripts/post-commit.mjs
Claude Code plugin hook:在 git commit 後把 commit SHA 對應到 session ID,讓 commit-history skill 可以 join。
4.6 一鍵部署
1deploy/
2├── coolify/ # docker-compose 變體
3├── fly/ # fly.toml
4├── railway/ # railway.json
5└── render/ # render.yaml
5. 應用場景
| 場景 | 怎麼用 |
|---|---|
| 每天用 Claude Code 寫程式 | install + agentmemory connect claude-code + 開 viewer 看記憶累積 |
| 想跨 Claude Code / Cursor / Codex 共用記憶 | 同一 server,三邊都接 |
| 想跨 session 不重複解釋專案結構 | session start 自動觸發 recall skill |
| 大型 monorepo 跑兩週的 feature | handoff skill 每晚生交接 brief,明天接 |
避免 pre-compact 時遺忘關鍵決策 | PreCompact hook 自動 preserve important 記憶 |
| 想看自己 memory 累積的長相 | agentmemory viewer 看 graph / tier 變化 / hooks 即時 |
| 想匯出記憶當研究素材 | agentmemory export memory.json + 自己 parse |
| 想跑自己的 benchmark | benchmark/ 全套(LongMemEval / scale / quality / real-embeddings) |
6. 資安掃描報告
掃描範圍:src/、plugin/、scripts/、docker-compose.yml、.env.example、SECURITY.md、CI workflows。
| 風險面 | 燈號 | 說明 |
|---|---|---|
| Shell injection(CLI / hooks) | 🟢 低 | plugin/scripts/post-commit.mjs:22 與 src/hooks/post-commit.ts:26 用 exec("git", args, {...}) 列表式(無 shell expansion) |
eval() / new Function() / child_process.exec | 🟢 低 | 多處 regex.exec() 都是 RegExp.prototype.exec(不是 shell),grep 看了全綠 |
| Secret 洩漏 | 🟢 低 | 內建 privacy filter 在 store 前 strip secrets;.env.example 全是 placeholder |
| Docker 容器權限 | 🟢 低 | iii-engine 跑在 UID 65332 non-root;distroless image;iii-init 只用 root 跑一次 chown |
| Port 暴露 | 🟢 低 | docker-compose.yml 所有 port bind 127.0.0.1(4 個 ports 都不對外) |
| LLM API key 處理 | 🟢 低 | 走 env var;不存進記憶(被 privacy filter 拒) |
| 第三方 LLM endpoint | 🟡 中 | 若啟用 LLM consolidation,會把使用者對話片段送 Anthropic / OpenAI / OpenRouter — 預設 noop provider 不發送;使用者要明確啟用 |
| 跨 agent 共用 → cross-tenant leakage | 🟡 中 | 同台機器多 agent 共用同 server 是設計;多 user 共用要做 auth(README 有提 auth.ts) |
| Hook 廣域性 | 🟡 中 | 12 個 hooks 全 session 都跑(這是它的賣點);但只寫到本地 SQLite,無 outbound call by default |
| MCP 工具暴露面 | 🟡 中 | 53 個 MCP tools 暴露到 :3112;server 只 listen 127.0.0.1 → 同機 root 可讀 — production 多用戶機要加 auth |
| SECURITY.md | 🟢 低 | 完整 GHSA flow + GPG email fallback + CVSS 3.1 + 30–90 天 disclosure |
| 依賴鏈 | 🟡 中 | TypeScript 大型 monorepo + workspaces,跟一般大型 npm 專案同等審查 |
| iii-engine pinned version | 🟢 低 | docker-compose 明確 pin v0.11.2 並有清楚 comment 說明為何不能往上 bump |
綜合燈號:🟢 / 🟡(核心無紅燈;多用戶 / production 部署要加 auth 層)
重點建議:
- 個人單機跑:直接用,零信任邊界外洩
- 團隊共用 server:開
auth.ts的 token-based auth,前面套 reverse proxy - 啟用 LLM consolidation 前確認對話內容適合送雲端
- 對 mission-critical 環境,禁用
agentmemory connect自動寫 hooks.json,改手動審查
7. FAQ
Q1:與其他 memory 系統相比的關鍵勝場? A:
- 自動 capture(12 hooks)— 其他多數要手動
add() - 零外部 DB — Mem0 要 Qdrant、Letta 要 Postgres+vector
- 跨 9+ agent 共用 — claude-mem 只 Claude Code
- benchmark 透明 — LongMemEval-S 公開可重現
- 隱私 filter built-in — 大部分競品沒做
Q2:iii-engine 是什麼? A:是另一個 OSS 專案(iii-hq/iii),提供 actor-like 「Worker / Function / Trigger」三原語 + StateModule(基於 SQLite)。agentmemory 把它當作 runtime。優點:所有狀態流經一個 engine,可觀測可重現。
Q3:為什麼 pin iii-engine 在 v0.11.2 不往上?
A:docker-compose.yml 註解明確:v0.11.6 改為「sandbox-everything via iii worker add」模型,agentmemory 還沒 refactor,bump 上去會出現 EPIPE 重連無限迴圈 + search 空 result。bump 要等 agentmemory 自己 refactor 完。
Q4:能完全離線跑嗎?
A:能。預設 embedding 用本地 all-MiniLM-L6-v2(透過 xenova / transformers.js),不打任何雲端 API。LLM consolidation 可關(noop provider)。
Q5:跨 agent 共用記憶會不會搞混 context?
A:每條記憶有 agent_id / session_id / project_id 標籤;recall 時可加 filter。建議:個人專案不分;多專案用 cwd 或 project_id 做 sub-scope。
Q6:v1.0.0 何時出?
A:看 ROADMAP.md;目前 0.9.21,迭代極快,預估 2026-06 內到 1.0。
Q7:適合什麼樣的人 fork? A:
- 想做「特定 agent 平台專屬」memory:fork → 改 plugin/
- 想加入領域知識(醫療 / 金融):fork → 改 consolidation prompts
- 想換 embedding 模型 / 加自家 LLM provider:fork → 加
src/providers/<name>.ts
Q8:跟 claude-mem 是同一個東西嗎?
A:不是。claude-mem 是另一個 OSS(46k stars,僅 Claude Code);agentmemory 是跨 agent。兩者可以併存:claude-mem 用於 Claude 自己的 session 連續性,agentmemory 用於跨 agent 共用記憶。本知識庫已透過 plugin 安裝了 claude-mem(看 /config/.claude/plugins/)。
Q9:那麼大的 README(1275 行 / 65KB)怎麼讀最快?
A:跳到 “How It Works” 與 “vs Competitors” 兩段;其餘是各 agent 的接線細節,用到再讀。或者直接讀 DESIGN.md(21KB)— 系統設計濃縮版。
8. 進階技巧
8.1 自訂 consolidation prompt
看 src/prompts/xml.ts:所有 consolidation 用的 prompt 都是 XML 格式(給 Claude 偏好)。要客製:fork → 改 prompts/
8.2 加自己的 LLM provider
複製 src/providers/openai.ts → 改 <name>.ts,實作 chat() + embed() 介面,註冊到 src/providers/index.ts 的 router。
8.3 自製 MCP tool
按 AGENTS.md 列的 7 步流程加(嚴格 consistency check):
src/mcp/tools-registry.ts加 tool 定義src/mcp/server.ts加 handler casesrc/triggers/api.ts加 REST endpointsrc/index.ts加 function 註冊 + log 行數test/mcp-standalone.test.ts改 tool 計數README.md改 tool 計數plugin/.claude-plugin/plugin.json改 description
漏一處 = build 失敗(CI 強制檢核)。
8.4 跨機器同步記憶
最簡:定期 agentmemory export memory.json + 同步到 Dropbox / iCloud / git → 另一台 agentmemory import memory.json。
進階:把 SQLite 檔放 NFS / 共用磁碟(要小心 lock contention)。
8.5 把 viewer 嵌進自家 dashboard
viewer 在 src/viewer/index.html(純 HTML + JS),可直接抄;或用 REST API(src/triggers/api.ts 列的 endpoints)做自己的 UI。
8.6 整合到本知識庫的 inbox
觸發 ai-save / ai-gh-save 時,可以加 hook:把 frontmatter 與正文也存進 agentmemory 的 semantic tier — 之後本 agent 在另一 session 就能 recall:「我們上次說 X repo 的設計品味是什麼?」
9. 整合進其他工作流
| 既有 skill | 整合方式 |
|---|---|
ai-gh-save | 已存 standard gh-save md 在 inbox/2026-05-21-github-rohitg00-agentmemory.md |
gh-tutorial-qd | 本檔產出 |
paper-qa-lite | agentmemory 內的 episodic 記憶可變成 RAG corpus(透過 export → md) |
claude-mem(已裝) | 兩者併存:claude-mem 為單一 Claude 連續;agentmemory 為跨 agent |
| 本知識庫的 inbox 整合 | 把 inbox/*.md 餵 agentmemory,semantic tier 自動成形 |
meeting-intel | 把過往 meeting briefs 進 agentmemory → 下次同廠商再來,recall 自動撈 |
patent-creator | 不適用(patent 機密邊界禁止外部寫入;agentmemory 走本地仍要 disable connect) |
10. 重點摘要 Checklist
- 15.6k stars / 1.3k forks / Apache-2.0 / v0.9.21
- LongMemEval-S R@5 95.2%(vs Letta 83% / Mem0 68%)
- 53 MCP tools + 12 lifecycle hooks + 8 skills
- 4-tier 整合(working / episodic / semantic / procedural)+ Ebbinghaus 衰減
- BM25 + Vector + Knowledge Graph 三路混合
- 零外部 DB(內建 SQLite via iii-engine)
- 跨 9+ agent(Claude Code / Cursor / Codex / Gemini / OpenCode / Hermes / OpenClaw / pi / any MCP)
- privacy filter built-in(強 strip secrets)
- real-time viewer on :3113
- 完整 SECURITY.md(GHSA + GPG fallback + CVSS)
- 950+ tests passing / 148KB CHANGELOG / 每天 ~20 PR
- 一鍵部署:Coolify / Fly / Railway / Render
- 資安綜合燈號:🟢 / 🟡(單機個人零紅;多用戶 production 要加 auth)
11. 進一步閱讀
- 官網:https://agent-memory.dev
- 設計 doc gist(1200 stars):https://gist.github.com/rohitg00/2067ab416f7bbe447c1977edaaa681e2
- iii-engine 母專案:https://github.com/iii-hq/iii
- LongMemEval benchmark(ICLR 2025):https://arxiv.org/abs/2410.10813
- COMPARISON.md(vs mem0 / Letta / Khoj / claude-mem / Hippo):
benchmark/COMPARISON.md - DESIGN.md(系統設計,21KB):本 repo
- 對應姊妹專案
mupt-ai/dari-docs(docs quality):inbox/2026-05-21-github-mupt-ai-dari-docs.md - 本知識庫先前 gh-save:
inbox/2026-05-21-github-ConardLi-garden-skills.md
Comments