agentmemory-persistent-memory
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseagentmemory-persistent-memory
agentmemory-persistent-memory
Skill by ara.so — AI Agent Skills collection.
agentmemory provides persistent memory for AI coding agents (Claude Code, Cursor, Gemini CLI, Codex, etc.) so they remember architecture decisions, preferences, bugs, and context across sessions. Built on the iii engine, it achieves 95.2% retrieval accuracy (R@5) and reduces token usage by 92% compared to pasting full context.
由ara.so提供的Skill——AI Agent技能合集。
agentmemory为AI编码Agent(Claude Code、Cursor、Gemini CLI、Codex等)提供持久化记忆功能,使其能够跨会话记住架构决策、偏好设置、问题记录以及上下文信息。它基于iii引擎构建,检索准确率(R@5)可达95.2%,与粘贴完整上下文相比,可减少92%的token消耗。
What It Does
功能特性
- Cross-session memory: Agent remembers previous conversations, decisions, and code patterns
- Zero setup: No external databases, runs locally
- Works everywhere: MCP server + native plugins for Claude Code, Codex, OpenClaw, Hermes, Cursor, and more
- Hybrid search: Combines embeddings + BM25 for accurate retrieval
- Auto-capture: 12 hooks automatically store context from agent actions
- Real-time viewer: Web UI to inspect and manage memories at http://localhost:3112
- 跨会话记忆:Agent可记住之前的对话内容、决策记录和代码模式
- 零配置启动:无需外部数据库,本地运行
- 多平台兼容:提供MCP服务器及原生插件,支持Claude Code、Codex、OpenClaw、Hermes、Cursor等多款Agent
- 混合搜索:结合向量嵌入与BM25算法实现精准检索
- 自动捕获:12个钩子自动存储Agent操作产生的上下文
- 实时可视化界面:通过http://localhost:3112访问Web UI,查看和管理记忆内容
Installation
安装方式
Global Installation (Recommended)
全局安装(推荐)
bash
undefinedbash
undefinedInstall globally to get the bare agentmemory
command
agentmemory全局安装后可直接使用agentmemory
命令
agentmemorynpm install -g @agentmemory/agentmemory
npm install -g @agentmemory/agentmemory
Start the memory server
启动记忆服务器
agentmemory
agentmemory
Server runs on http://localhost:3111 (API)
服务器API运行在http://localhost:3111
Viewer runs on http://localhost:3112 (UI)
可视化界面运行在http://localhost:3112
undefinedundefinednpx (No Install)
npx临时运行(无需安装)
bash
undefinedbash
undefinedRun without installing
无需安装直接运行
npx @agentmemory/agentmemory
npx @agentmemory/agentmemory
Force latest version if cache is stale
缓存过期时强制使用最新版本
npx -y @agentmemory/agentmemory@latest
undefinednpx -y @agentmemory/agentmemory@latest
undefinedProject-Level Installation
项目级安装
typescript
// package.json
{
"dependencies": {
"@agentmemory/agentmemory": "^0.9.16"
}
}typescript
// TypeScript/JavaScript usage
import { AgentMemory } from '@agentmemory/agentmemory';
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory'
});
await memory.start();typescript
// package.json
{
"dependencies": {
"@agentmemory/agentmemory": "^0.9.16"
}
}typescript
// TypeScript/JavaScript使用示例
import { AgentMemory } from '@agentmemory/agentmemory';
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory'
});
await memory.start();Quick Start
快速开始
1. Start the Server
1. 启动服务器
bash
agentmemoryOutput:
✓ agentmemory server running on http://localhost:3111
✓ Real-time viewer at http://localhost:3112
✓ MCP server ready for agent connectionsbash
agentmemory输出示例:
✓ agentmemory server running on http://localhost:3111
✓ Real-time viewer at http://localhost:3112
✓ MCP server ready for agent connections2. Connect Your Agent
2. 连接你的Agent
bash
undefinedbash
undefinedClaude Code
Claude Code
agentmemory connect claude-code
agentmemory connect claude-code
Codex CLI
Codex CLI
agentmemory connect codex
agentmemory connect codex
Cursor (via MCP)
Cursor(通过MCP)
agentmemory connect cursor
agentmemory connect cursor
Gemini CLI
Gemini CLI
agentmemory connect gemini-cli
agentmemory connect gemini-cli
Generic MCP for any agent
通用MCP连接任意Agent
agentmemory connect mcp
undefinedagentmemory connect mcp
undefined3. Demo Mode (Optional)
3. 演示模式(可选)
bash
undefinedbash
undefinedSeed sample sessions and test recall
导入示例会话并测试记忆召回
agentmemory demo
undefinedagentmemory demo
undefinedAgent-Specific Setup
各Agent专属配置
Claude Code
Claude Code
Native plugin with 12 auto-hooks:
bash
agentmemory connect claude-codeCreates :
~/.claude-code/plugins/agentmemory.jsonjson
{
"name": "agentmemory",
"memoryServer": "http://localhost:3111",
"hooks": {
"onStart": true,
"onCommand": true,
"onFileEdit": true,
"onSearch": true,
"onError": true,
"onDecision": true
}
}原生插件包含12个自动钩子:
bash
agentmemory connect claude-code该命令会创建文件:
~/.claude-code/plugins/agentmemory.jsonjson
{
"name": "agentmemory",
"memoryServer": "http://localhost:3111",
"hooks": {
"onStart": true,
"onCommand": true,
"onFileEdit": true,
"onSearch": true,
"onError": true,
"onDecision": true
}
}Cursor (via MCP)
Cursor(通过MCP)
bash
agentmemory connect cursorAdds to :
~/Library/Application Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.jsonjson
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"],
"env": {
"AGENTMEMORY_URL": "http://localhost:3111"
}
}
}
}bash
agentmemory connect cursor该命令会修改文件:
~/Library/Application Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.jsonjson
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"],
"env": {
"AGENTMEMORY_URL": "http://localhost:3111"
}
}
}
}Claude Desktop
Claude Desktop
Edit :
~/Library/Application Support/Claude/claude_desktop_config.jsonjson
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"]
}
}
}编辑文件:
~/Library/Application Support/Claude/claude_desktop_config.jsonjson
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"]
}
}
}Codex CLI
Codex CLI
bash
agentmemory connect codexCreates :
~/.codex/plugins/agentmemory.jsjavascript
module.exports = {
name: 'agentmemory',
memoryServer: 'http://localhost:3111',
hooks: ['onStart', 'onCommand', 'onFileEdit', 'onSearch', 'onError', 'onDecision']
};bash
agentmemory connect codex该命令会创建文件:
~/.codex/plugins/agentmemory.jsjavascript
module.exports = {
name: 'agentmemory',
memoryServer: 'http://localhost:3111',
hooks: ['onStart', 'onCommand', 'onFileEdit', 'onSearch', 'onError', 'onDecision']
};Core API Usage
核心API使用示例
TypeScript/JavaScript
TypeScript/JavaScript
typescript
import { AgentMemory } from '@agentmemory/agentmemory';
// Initialize
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory',
embeddingModel: 'all-MiniLM-L6-v2', // Local, free
enableViewer: true,
viewerPort: 3112
});
await memory.start();
// Store a memory
await memory.store({
sessionId: 'session-001',
content: 'User prefers JWT auth with jose library for Edge compatibility',
type: 'preference',
tags: ['auth', 'jwt', 'edge'],
confidence: 0.95
});
// Retrieve relevant memories
const results = await memory.search({
query: 'authentication setup',
sessionId: 'session-001',
limit: 5
});
console.log(results);
// [
// {
// content: 'User prefers JWT auth with jose library...',
// score: 0.92,
// type: 'preference',
// tags: ['auth', 'jwt', 'edge'],
// timestamp: '2026-05-16T10:30:00Z'
// }
// ]
// Store code context
await memory.storeCode({
sessionId: 'session-001',
filePath: 'src/middleware/auth.ts',
language: 'typescript',
summary: 'JWT middleware using jose, validates tokens on Edge runtime',
keyDecisions: [
'Chose jose over jsonwebtoken for Edge compatibility',
'Token expiry set to 7 days',
'Refresh tokens stored in httpOnly cookies'
]
});
// Recall at session start
const context = await memory.recallForSession('session-002');
console.log(context.relevantMemories);
// Agent automatically gets context from previous sessionstypescript
import { AgentMemory } from '@agentmemory/agentmemory';
// 初始化
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory',
embeddingModel: 'all-MiniLM-L6-v2', // 本地免费模型
enableViewer: true,
viewerPort: 3112
});
await memory.start();
// 存储一条记忆
await memory.store({
sessionId: 'session-001',
content: '用户偏好使用jose库实现JWT认证,以兼容Edge环境',
type: 'preference',
tags: ['auth', 'jwt', 'edge'],
confidence: 0.95
});
// 检索相关记忆
const results = await memory.search({
query: '认证设置',
sessionId: 'session-001',
limit: 5
});
console.log(results);
// [
// {
// content: '用户偏好使用jose库实现JWT认证...',
// score: 0.92,
// type: 'preference',
// tags: ['auth', 'jwt', 'edge'],
// timestamp: '2026-05-16T10:30:00Z'
// }
// ]
// 存储代码上下文
await memory.storeCode({
sessionId: 'session-001',
filePath: 'src/middleware/auth.ts',
language: 'typescript',
summary: '使用jose实现的JWT中间件,在Edge运行时验证令牌',
keyDecisions: [
'为兼容Edge环境选择jose而非jsonwebtoken',
'令牌过期时间设置为7天',
'刷新令牌存储在httpOnly Cookie中'
]
});
// 会话启动时召回上下文
const context = await memory.recallForSession('session-002');
console.log(context.relevantMemories);
// Agent会自动获取之前会话的上下文信息REST API
REST API
bash
undefinedbash
undefinedStore memory
存储记忆
curl -X POST http://localhost:3111/api/memory/store
-H "Content-Type: application/json"
-d '{ "sessionId": "session-001", "content": "User prefers TypeScript strict mode", "type": "preference", "tags": ["typescript", "config"], "confidence": 0.9 }'
-H "Content-Type: application/json"
-d '{ "sessionId": "session-001", "content": "User prefers TypeScript strict mode", "type": "preference", "tags": ["typescript", "config"], "confidence": 0.9 }'
curl -X POST http://localhost:3111/api/memory/store
-H "Content-Type: application/json"
-d '{ "sessionId": "session-001", "content": "用户偏好TypeScript严格模式", "type": "preference", "tags": ["typescript", "config"], "confidence": 0.9 }'
-H "Content-Type: application/json"
-d '{ "sessionId": "session-001", "content": "用户偏好TypeScript严格模式", "type": "preference", "tags": ["typescript", "config"], "confidence": 0.9 }'
Search memories
搜索记忆
curl -X POST http://localhost:3111/api/memory/search
-H "Content-Type: application/json"
-d '{ "query": "typescript configuration", "sessionId": "session-001", "limit": 5 }'
-H "Content-Type: application/json"
-d '{ "query": "typescript configuration", "sessionId": "session-001", "limit": 5 }'
curl -X POST http://localhost:3111/api/memory/search
-H "Content-Type: application/json"
-d '{ "query": "TypeScript配置", "sessionId": "session-001", "limit": 5 }'
-H "Content-Type: application/json"
-d '{ "query": "TypeScript配置", "sessionId": "session-001", "limit": 5 }'
Get session context
获取会话上下文
Delete memory
删除记忆
curl -X DELETE http://localhost:3111/api/memory/delete/mem_abc123xyz
curl -X DELETE http://localhost:3111/api/memory/delete/mem_abc123xyz
Health check
健康检查
undefinedundefinedMCP Server (Model Context Protocol)
MCP服务器(模型上下文协议)
agentmemory exposes 51 MCP tools for agent integration:
agentmemory提供51个MCP工具用于Agent集成:
Available Tools
可用工具
typescript
// Memory operations
- memory_store: Store new memory
- memory_search: Search memories by query
- memory_recall: Get context for session
- memory_update: Update existing memory
- memory_delete: Delete specific memory
- memory_list: List all memories (paginated)
// Session management
- session_create: Start new session
- session_get: Get session details
- session_list: List all sessions
- session_archive: Archive completed session
// Code context
- code_store: Store code snippet with context
- code_search: Search code memories
- code_link: Link memories to code files
// Preferences
- preference_set: Store user preference
- preference_get: Retrieve preference
- preference_list: List all preferences
// Knowledge graph
- graph_add_node: Add knowledge node
- graph_add_edge: Connect nodes
- graph_query: Query relationships
- graph_traverse: Walk knowledge graph
// Analytics
- stats_get: Get memory statistics
- stats_session: Session-level stats
- stats_recall_accuracy: Retrieval metricstypescript
// 记忆操作
- memory_store: 存储新记忆
- memory_search: 根据查询词搜索记忆
- memory_recall: 获取会话上下文
- memory_update: 更新已有记忆
- memory_delete: 删除指定记忆
- memory_list: 分页列出所有记忆
// 会话管理
- session_create: 启动新会话
- session_get: 获取会话详情
- session_list: 列出所有会话
- session_archive: 归档已完成会话
// 代码上下文
- code_store: 存储带上下文的代码片段
- code_search: 搜索代码相关记忆
- code_link: 将记忆与代码文件关联
// 偏好设置
- preference_set: 存储用户偏好
- preference_get: 检索用户偏好
- preference_list: 列出所有偏好
// 知识图谱
- graph_add_node: 添加知识节点
- graph_add_edge: 连接节点
- graph_query: 查询节点关系
- graph_traverse: 遍历知识图谱
// 分析统计
- stats_get: 获取记忆统计数据
- stats_session: 会话级统计
- stats_recall_accuracy: 检索准确率指标MCP Client Example
MCP客户端示例
typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const transport = new StdioClientTransport({
command: 'npx',
args: ['-y', '@agentmemory/agentmemory', 'mcp']
});
const client = new Client({
name: 'my-agent',
version: '1.0.0'
}, {
capabilities: {}
});
await client.connect(transport);
// Call MCP tool
const result = await client.request({
method: 'tools/call',
params: {
name: 'memory_store',
arguments: {
sessionId: 'session-001',
content: 'User wants error handling with Zod validation',
type: 'decision',
tags: ['error-handling', 'validation', 'zod']
}
}
});
console.log(result);typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const transport = new StdioClientTransport({
command: 'npx',
args: ['-y', '@agentmemory/agentmemory', 'mcp']
});
const client = new Client({
name: 'my-agent',
version: '1.0.0'
}, {
capabilities: {}
});
await client.connect(transport);
// 调用MCP工具
const result = await client.request({
method: 'tools/call',
params: {
name: 'memory_store',
arguments: {
sessionId: 'session-001',
content: '用户希望使用Zod验证处理错误',
type: 'decision',
tags: ['error-handling', 'validation', 'zod']
}
}
});
console.log(result);Configuration
配置说明
Environment Variables
环境变量
bash
undefinedbash
undefinedServer settings
服务器设置
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=./data/memory
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=./data/memory
Embedding model (local)
嵌入模型(本地)
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
Or use OpenAI embeddings (requires API key)
或使用OpenAI嵌入模型(需要API密钥)
OPENAI_API_KEY=your_openai_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_API_KEY=your_openai_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-small
Search tuning
搜索调优
AGENTMEMORY_HYBRID_ALPHA=0.7 # 0.7 = 70% embeddings, 30% BM25
AGENTMEMORY_MAX_RESULTS=10
AGENTMEMORY_HYBRID_ALPHA=0.7 # 0.7 = 70%向量嵌入,30% BM25
AGENTMEMORY_MAX_RESULTS=10
Memory lifecycle
记忆生命周期
AGENTMEMORY_AUTO_ARCHIVE_DAYS=30
AGENTMEMORY_MIN_CONFIDENCE=0.5
AGENTMEMORY_AUTO_ARCHIVE_DAYS=30
AGENTMEMORY_MIN_CONFIDENCE=0.5
Hooks (for Claude Code, Codex)
钩子配置(针对Claude Code、Codex)
AGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_HOOK_ON_FILE_EDIT=true
AGENTMEMORY_HOOK_ON_COMMAND=true
AGENTMEMORY_HOOK_ON_ERROR=true
undefinedAGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_HOOK_ON_FILE_EDIT=true
AGENTMEMORY_HOOK_ON_COMMAND=true
AGENTMEMORY_HOOK_ON_ERROR=true
undefinedConfiguration File
配置文件
Create :
agentmemory.config.jsonjson
{
"server": {
"port": 3111,
"viewerPort": 3112,
"dataDir": "./data/memory"
},
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2"
},
"search": {
"hybridAlpha": 0.7,
"maxResults": 10,
"minConfidence": 0.5
},
"lifecycle": {
"autoArchiveDays": 30,
"pruneInactive": true
},
"hooks": {
"onStart": true,
"onCommand": true,
"onFileEdit": true,
"onSearch": true,
"onError": true,
"onDecision": true
}
}Load config:
bash
agentmemory --config ./agentmemory.config.json创建文件:
agentmemory.config.jsonjson
{
"server": {
"port": 3111,
"viewerPort": 3112,
"dataDir": "./data/memory"
},
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2"
},
"search": {
"hybridAlpha": 0.7,
"maxResults": 10,
"minConfidence": 0.5
},
"lifecycle": {
"autoArchiveDays": 30,
"pruneInactive": true
},
"hooks": {
"onStart": true,
"onCommand": true,
"onFileEdit": true,
"onSearch": true,
"onError": true,
"onDecision": true
}
}加载配置文件:
bash
agentmemory --config ./agentmemory.config.jsonCommon Patterns
常见使用模式
Pattern 1: Architecture Decision Capture
模式1:架构决策捕获
typescript
// When agent makes architectural decision, store it
await memory.store({
sessionId: currentSession,
content: 'Decided to use PostgreSQL with Prisma ORM for type safety',
type: 'decision',
tags: ['architecture', 'database', 'prisma', 'postgresql'],
confidence: 0.95,
metadata: {
rationale: 'Team familiar with Prisma, need strong typing',
alternatives: ['MySQL + Drizzle', 'MongoDB'],
impact: 'high',
reversible: false
}
});
// Next session, agent recalls this automatically
const context = await memory.recallForSession(newSession);
// Agent knows: "Previously decided on PostgreSQL + Prisma for type safety"typescript
// 当Agent做出架构决策时,存储该记录
await memory.store({
sessionId: currentSession,
content: '决定使用PostgreSQL搭配Prisma ORM以保证类型安全',
type: 'decision',
tags: ['architecture', 'database', 'prisma', 'postgresql'],
confidence: 0.95,
metadata: {
rationale: '团队熟悉Prisma,需要强类型支持',
alternatives: ['MySQL + Drizzle', 'MongoDB'],
impact: 'high',
reversible: false
}
});
// 下一次会话中,Agent会自动召回该记录
const context = await memory.recallForSession(newSession);
// Agent会知道:"之前已决定使用PostgreSQL + Prisma保证类型安全"Pattern 2: Code Pattern Memory
模式2:代码模式记忆
typescript
// Store reusable code pattern
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/lib/api-client.ts',
language: 'typescript',
summary: 'API client with retry logic and exponential backoff',
pattern: `
export async function fetchWithRetry(url: string, options?: RequestInit) {
let attempt = 0;
while (attempt < 3) {
try {
return await fetch(url, options);
} catch (err) {
if (attempt === 2) throw err;
await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
attempt++;
}
}
}
`,
tags: ['api', 'retry', 'fetch', 'resilience'],
keyDecisions: [
'3 retries with exponential backoff',
'Throws on final failure',
'No retry on 4xx errors (only network failures)'
]
});
// Later, when user asks about API calls
const codeMemories = await memory.search({
query: 'api error handling',
type: 'code',
limit: 3
});
// Agent suggests: "We use fetchWithRetry from api-client.ts for resilience"typescript
// 存储可复用的代码模式
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/lib/api-client.ts',
language: 'typescript',
summary: '带重试逻辑和指数退避的API客户端',
pattern: `
export async function fetchWithRetry(url: string, options?: RequestInit) {
let attempt = 0;
while (attempt < 3) {
try {
return await fetch(url, options);
} catch (err) {
if (attempt === 2) throw err;
await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
attempt++;
}
}
}
`,
tags: ['api', 'retry', 'fetch', 'resilience'],
keyDecisions: [
'3次重试搭配指数退避策略',
'最后一次失败时抛出错误',
'仅针对网络失败重试,不处理4xx错误'
]
});
// 之后当用户询问API调用相关问题时
const codeMemories = await memory.search({
query: 'API错误处理',
type: 'code',
limit: 3
});
// Agent会建议:"我们使用api-client.ts中的fetchWithRetry实现容错能力"Pattern 3: Bug Fix Memory
模式3:Bug修复记忆
typescript
// When bug is found and fixed
await memory.store({
sessionId: currentSession,
content: 'Fixed race condition in WebSocket reconnection logic',
type: 'bug_fix',
tags: ['websocket', 'race-condition', 'concurrency'],
confidence: 1.0,
metadata: {
symptom: 'Duplicate connections causing message echoes',
rootCause: 'reconnect() called before disconnect() completed',
fix: 'Added connectionLock mutex to serialize connect/disconnect',
filePath: 'src/websocket/connection.ts',
linesChanged: '45-67',
testAdded: 'tests/websocket/reconnect.test.ts'
}
});
// Prevents re-introducing similar bugs
const pastBugs = await memory.search({
query: 'websocket connection issues',
type: 'bug_fix'
});
// Agent warns: "Watch out - we had a race condition here before (see connectionLock)"typescript
// 当发现并修复Bug时
await memory.store({
sessionId: currentSession,
content: '修复了WebSocket重连逻辑中的竞态条件',
type: 'bug_fix',
tags: ['websocket', 'race-condition', 'concurrency'],
confidence: 1.0,
metadata: {
symptom: '重复连接导致消息重复',
rootCause: 'disconnect()完成前调用了reconnect()',
fix: '添加connectionLock互斥锁序列化连接/断开操作',
filePath: 'src/websocket/connection.ts',
linesChanged: '45-67',
testAdded: 'tests/websocket/reconnect.test.ts'
}
});
// 防止再次引入类似Bug
const pastBugs = await memory.search({
query: 'WebSocket连接问题',
type: 'bug_fix'
});
// Agent会提醒:"注意——这里之前出现过竞态条件(参考connectionLock)"Pattern 4: Preference Learning
模式4:偏好学习
typescript
// Capture user preferences over time
await memory.store({
sessionId: currentSession,
content: 'User prefers named exports over default exports',
type: 'preference',
tags: ['code-style', 'exports', 'modules'],
confidence: 0.85
});
await memory.store({
sessionId: currentSession,
content: 'User wants all async errors wrapped in Result<T, E> type',
type: 'preference',
tags: ['error-handling', 'types', 'functional'],
confidence: 0.9
});
// Agent adapts to preferences automatically
const prefs = await memory.search({
query: 'code style preferences',
type: 'preference'
});
// Agent generates code matching user's style without being toldtypescript
// 逐步捕获用户偏好
await memory.store({
sessionId: currentSession,
content: '用户偏好命名导出而非默认导出',
type: 'preference',
tags: ['code-style', 'exports', 'modules'],
confidence: 0.85
});
await memory.store({
sessionId: currentSession,
content: '用户希望所有异步错误都用Result<T, E>类型包裹',
type: 'preference',
tags: ['error-handling', 'types', 'functional'],
confidence: 0.9
});
// Agent会自动适配用户偏好
const prefs = await memory.search({
query: '代码风格偏好',
type: 'preference'
});
// Agent无需额外告知就能生成符合用户风格的代码Pattern 5: Cross-File Context
模式5:跨文件上下文关联
typescript
// Link related code across files
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/middleware/auth.ts',
language: 'typescript',
summary: 'JWT authentication middleware',
tags: ['auth', 'jwt', 'middleware']
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'src/routes/api.ts',
relationship: 'used_by',
context: 'All /api/* routes use JWT auth middleware'
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'tests/middleware/auth.test.ts',
relationship: 'tested_by',
context: 'Test coverage: token validation, expiry, refresh'
});
// Agent understands impact of changes
const linkedFiles = await memory.getCodeLinks('src/middleware/auth.ts');
// Agent warns: "Changing auth.ts affects 12 API routes and has test coverage"typescript
// 关联不同文件中的相关代码
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/middleware/auth.ts',
language: 'typescript',
summary: 'JWT认证中间件',
tags: ['auth', 'jwt', 'middleware']
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'src/routes/api.ts',
relationship: 'used_by',
context: '所有/api/*路由都使用JWT认证中间件'
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'tests/middleware/auth.test.ts',
relationship: 'tested_by',
context: '测试覆盖:令牌验证、过期、刷新'
});
// Agent能理解代码变更的影响范围
const linkedFiles = await memory.getCodeLinks('src/middleware/auth.ts');
// Agent会提醒:"修改auth.ts会影响12个API路由,且已有测试覆盖"Real-Time Viewer
实时可视化界面
Open http://localhost:3112 to see:
- Memory timeline: Visual history of all stored memories
- Session explorer: Browse by session, see context evolution
- Search interface: Test queries, see retrieval scores
- Knowledge graph: Visual map of connected memories
- Stats dashboard: Recall accuracy, token savings, storage usage
- 记忆时间线:所有存储记忆的可视化历史
- 会话浏览器:按会话浏览,查看上下文演变
- 搜索界面:测试查询词,查看检索得分
- 知识图谱:记忆关联的可视化图谱
- 统计面板:召回准确率、token节省量、存储使用情况
Viewer API
可视化界面API
typescript
// Programmatic access to viewer data
const viewerData = await fetch('http://localhost:3112/api/viewer/data').then(r => r.json());
console.log(viewerData);
// {
// sessions: [...],
// memories: [...],
// stats: { totalMemories: 1247, avgRecall: 0.952, tokensSaved: 168420 }
// }typescript
// 程序化访问可视化界面数据
const viewerData = await fetch('http://localhost:3112/api/viewer/data').then(r => r.json());
console.log(viewerData);
// {
// sessions: [...],
// memories: [...],
// stats: { totalMemories: 1247, avgRecall: 0.952, tokensSaved: 168420 }
// }CLI Commands
CLI命令
bash
undefinedbash
undefinedStart server
启动服务器
agentmemory
agentmemory
Start with custom port
使用自定义端口启动
agentmemory --port 4000 --viewer-port 4001
agentmemory --port 4000 --viewer-port 4001
Start in background
后台启动
agentmemory --daemon
agentmemory --daemon
Stop daemon
停止后台进程
agentmemory stop
agentmemory stop
Connect agent
连接Agent
agentmemory connect <agent-name>
agentmemory connect <agent-name>
Run demo
运行演示
agentmemory demo
agentmemory demo
Export memories
导出记忆
agentmemory export --format json --output memories.json
agentmemory export --format json --output memories.json
Import memories
导入记忆
agentmemory import --input memories.json
agentmemory import --input memories.json
Clear all memories (with confirmation)
清空所有记忆(需要确认)
agentmemory clear
agentmemory clear
Show stats
查看统计数据
agentmemory stats
agentmemory stats
Health check
健康检查
agentmemory health
agentmemory health
Update to latest
更新到最新版本
agentmemory update
undefinedagentmemory update
undefinedTroubleshooting
故障排查
Server Won't Start
服务器无法启动
bash
undefinedbash
undefinedCheck if port is in use
检查端口是否被占用
lsof -i :3111
lsof -i :3111
Kill existing process
杀死占用端口的进程
kill -9 $(lsof -t -i:3111)
kill -9 $(lsof -t -i:3111)
Start on different port
使用其他端口启动
agentmemory --port 4000
undefinedagentmemory --port 4000
undefinedAgent Not Connecting
Agent无法连接
bash
undefinedbash
undefinedVerify server is running
验证服务器是否运行
Check MCP configuration
检查MCP配置
cat ~/Library/Application\ Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json
cat ~/Library/Application\ Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json
Test MCP connection manually
手动测试MCP连接
npx @agentmemory/agentmemory mcp
undefinednpx @agentmemory/agentmemory mcp
undefinedPoor Recall Accuracy
召回准确率低
typescript
// Increase hybrid search weight toward embeddings
AGENTMEMORY_HYBRID_ALPHA=0.85 // 85% embeddings, 15% BM25
// Or switch to OpenAI embeddings for better quality
OPENAI_API_KEY=your_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-largetypescript
undefinedMemory Storage Growing Large
增加混合搜索中向量嵌入的权重
bash
undefinedAGENTMEMORY_HYBRID_ALPHA=0.85 // 85%向量嵌入,15% BM25
Archive old sessions
或切换到OpenAI嵌入模型以提升质量
agentmemory archive --older-than 30d
OPENAI_API_KEY=your_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-large
undefinedPrune low-confidence memories
记忆存储占用过大
agentmemory prune --min-confidence 0.5
bash
undefinedCompact database
归档旧会话
agentmemory compact
undefinedagentmemory archive --older-than 30d
Viewer Not Loading
清理低置信度记忆
bash
undefinedagentmemory prune --min-confidence 0.5
Check viewer port
压缩数据库
agentmemory compact
undefinedRestart with viewer explicitly enabled
可视化界面无法加载
agentmemory --enable-viewer --viewer-port 3112
undefinedbash
undefinednpx Cache Issues
检查可视化界面端口
bash
undefinedClear npx cache (macOS/Linux)
显式启用可视化界面并重启
rm -rf ~/.npm/_npx
agentmemory --enable-viewer --viewer-port 3112
undefinedWindows
npx缓存问题
Delete %LOCALAPPDATA%\npm-cache_npx
—
Force latest version
—
npx -y @agentmemory/agentmemory@latest
undefinedbash
undefinedAdvanced: iii Engine Integration
清除npx缓存(macOS/Linux)
agentmemory is built on the iii engine, a knowledge processing system. You can use iii directly for custom memory backends:
typescript
import { IIIEngine } from '@iii-hq/iii';
const engine = new IIIEngine({
storage: 'local',
embeddings: 'all-MiniLM-L6-v2'
});
// Store knowledge node
await engine.store({
content: 'User prefers Tailwind CSS for styling',
type: 'preference',
tags: ['ui', 'css', 'tailwind'],
confidence: 0.9
});
// Query with iii's advanced graph traversal
const results = await engine.query({
semantic: 'css framework choice',
graphDepth: 2,
includeRelated: true
});rm -rf ~/.npm/_npx
Environment Setup Example
Windows系统
—
删除%LOCALAPPDATA%\npm-cache_npx
—
强制使用最新版本
bash
undefinednpx -y @agentmemory/agentmemory@latest
undefined.env file for production
进阶:iii引擎集成
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=/var/lib/agentmemory
AGENTMEMORY_EMBEDDING_PROVIDER=local
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
AGENTMEMORY_HYBRID_ALPHA=0.75
AGENTMEMORY_AUTO_ARCHIVE_DAYS=90
AGENTMEMORY_MIN_CONFIDENCE=0.6
AGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_LOG_LEVEL=info
undefinedagentmemory基于iii引擎构建,这是一个知识处理系统。你可以直接使用iii引擎自定义记忆后端:
typescript
import { IIIEngine } from '@iii-hq/iii';
const engine = new IIIEngine({
storage: 'local',
embeddings: 'all-MiniLM-L6-v2'
});
// 存储知识节点
await engine.store({
content: '用户偏好使用Tailwind CSS进行样式开发',
type: 'preference',
tags: ['ui', 'css', 'tailwind'],
confidence: 0.9
});
// 使用iii的高级图谱遍历功能查询
const results = await engine.query({
semantic: 'CSS框架选择',
graphDepth: 2,
includeRelated: true
});Performance Notes
生产环境配置示例
- Embedding: Local model (all-MiniLM-L6-v2) processes ~500 tokens/sec on M1 Mac
- Search: Hybrid search returns results in <50ms for 10K memories
- Storage: ~1KB per memory average, ~10MB for 10K memories
- Startup: Cold start ~2 seconds, warm start <500ms
- Token savings: 92% reduction vs. full context pasting (see benchmarks)
bash
undefinedResources
.env生产环境配置文件
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=/var/lib/agentmemory
AGENTMEMORY_EMBEDDING_PROVIDER=local
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
AGENTMEMORY_HYBRID_ALPHA=0.75
AGENTMEMORY_AUTO_ARCHIVE_DAYS=90
AGENTMEMORY_MIN_CONFIDENCE=0.6
AGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_LOG_LEVEL=info
undefined—
性能说明
—
- 嵌入处理:本地模型(all-MiniLM-L6-v2)在M1 Mac上处理速度约为500 tokens/秒
- 搜索速度:混合搜索在10K条记忆数据下返回结果耗时<50ms
- 存储占用:单条记忆平均约1KB,10K条记忆约占用10MB
- 启动速度:冷启动约2秒,热启动<500ms
- Token节省:相比粘贴完整上下文,可减少92%的Token消耗(参考基准测试)
—