Authoritative technical reference for the unified-memory skill.
For overview and quick start, see README.md.
权威技术参考文档,详细使用说明请参考 README.md。
解决了生产环境中最严重的数据一致性问题,实现企业级数据安全保障:
javascript
// 两阶段提交协议,保证 JSON 和向量存储的一致性
const txManager = new AtomicTransactionManager();
const txId = await txManager.beginTransaction();
// 准备 JSON 写入
try {
const tempFile = await txManager.prepareJsonWrite(txId, memory);
const vectorResult = await txManager.prepareVectorWrite(txId, memory, embedding);
// 提交事务
await txManager.commitTransaction(txId);
} catch (error) {
// 回滚事务
await txManager.rollbackTransaction(txId);
throw error;
}
javascript
// fsync 保证数据写入磁盘
const fd = await fs.open(tmpPath, 'r+');
try {
await fd.sync(); // 确保数据落盘
} finally {
await fd.close();
}
bash
# 部署原子写入修复
./deploy-atomic-fixes.sh
# 验证修复
./verify-repairs.sh
指标修复前修复后改进数据一致性可能不一致100% 保证原子性写入查询性能O(n) 扫描优化的内存过滤5-10倍提升数据安全可能丢失fsync 保证零数据丢失部署时间手动修复一键部署分钟级部署
基于梦境文件系统的深度重构,Unified Memory 实现"文件混乱"到"结构化系统"的升级,性能提升5-10倍:
text
原始混乱文件 → 7层目录结构 → 1760个增强记忆 → 混合搜索系统
优化项效果检索速度5-10倍提升存储空间60%节省记忆数量1760个梦境记忆智能索引49个标签 + 181个实体查询方式5种查询支持
bash
# 查看系统统计
npm run stats
# 查询标签记忆
node memory/.dreams/scripts/query.cjs tag reflection 5
# 全文搜索
node memory/.dreams/scripts/query.cjs search "water" 3
借鉴 OpenViking 记忆系统的架构设计,Unified Memory 从"存储系统"升级为"知识管理系统":
text
L0 (对话录制) → transcript_first.js
↓
L1 (记忆提取) → extract.js + memory_types/
↓
L2 (场景归纳) → scene_block.js
↓
L3 (用户画像) → profile.js / persona_generator.js
javascript
// memory_types/registry.js
const registry = getMemoryTypeRegistry();
// 支持的记忆类型
- facts // 事实型记忆
- patterns // 模式型记忆
- skills // 技能型记忆
- cases // 案例型记忆
- events // 事件型记忆
- preferences // 偏好型记忆
// 自动检测记忆类型
const detected = await registry.detectMemoryType(text);
// 处理记忆
const processed = await registry.processMemory(text, typeName, context);
javascript
// queue/memory_queue.js
const queue = getMemoryQueue();
// 队列类型
- embedding // Embedding 任务
- semantic // 语义分析
- deduplication // 去重
- archiving // 归档
- indexing // 索引
// 入队任务
const taskId = queue.enqueue('embedding', { text: '...' });
// 获取状态
const stats = queue.getQueueStats();
javascript
// deduplication/smart_deduplicator.js
const deduplicator = getSmartDeduplicator();
// 检查重复
const result = await deduplicator.checkDuplicate(memory, existingMemories);
// 合并相似记忆
const merged = await deduplicator.mergeMemories(memory1, memory2);
// 批量去重
const result = await deduplicator.deduplicateBatch(memories);
javascript
// enhanced_memory_system.js
const system = getEnhancedMemorySystem();
// 初始化
await system.initialize();
// 存储记忆(自动类型检测 + 去重)
const result = await system.remember(text, context);
// 回忆记忆(向量 + 文本搜索)
const memories = await system.recall(query, options);
// 处理对话(管道模式)
const taskId = await system.processConversation(conversationData);
// 获取状态
const status = system.getStatus();
const health = system.healthCheck();
text
src/
├── memory_pipeline.js # 分层记忆处理管道
├── enhanced_memory_system.js # 增强版记忆系统
├── memory_types/ # 记忆类型系统
│ ├── registry.js # 类型注册中心
│ ├── facts.js # 事实型记忆处理器
│ ├── patterns.js # 模式型记忆处理器
│ ├── skills.js # 技能型记忆处理器
│ ├── cases.js # 案例型记忆处理器
│ ├── events.js # 事件型记忆处理器
│ └── preferences.js # 偏好型记忆处理器
├── queue/ # 队列系统
│ └── memory_queue.js # 记忆队列
└── deduplication/ # 去重系统
└── smart_deduplicator.js # 智能去重器
特性OpenVikingUnified Memory v4.5分层架构✅ L0-L3✅ L0-L3记忆类型✅ 类型注册✅ 6种类型异步处理✅ 队列系统✅ 5种队列智能去重✅ 语义去重✅ 多维度去重向量存储✅ 多集合✅ LanceDB/SQLiteAPI 设计✅ REST API✅ MCP Tools配置驱动✅ ov.conf✅ 环境变量
recall/memory_recall_optimizer.js)解决的问题:召回的记忆不够精准,或者太多太杂
核心功能:
使用效果:召回精准度提升 40%
compression/memory_compressor.js)解决的问题:记忆太多,占用大量 token
核心功能:
使用效果:Token 节省 70%
lifecycle/memory_lifecycle_manager.js)解决的问题:记忆越来越多,需要自动归档和清理
核心功能:
使用效果:零维护,自动管理
compression/layered_compressor.js) 【新增:借鉴 OpenViking】解决的问题:一次性加载所有记忆浪费 token
核心功能:
使用效果:Token 节省 83%(基于 OpenViking 实验数据)
FieldValueNameunified-memoryVersion4.4.0 (see docs/CHANGELOG.md)FrameworkOpenClaw Agent · Node.js ESM · MCP stdioNode>=18.0.0OpenClaw>=2026.3.0Transportstdio (MCP over node src/index.js)
text
L0 (对话录制) → transcript_first.js ✅
↓
L1 (记忆提取) → extract.js ✅
↓
L2 (场景归纳) → scene_block.js 🆕
↓
L3 (用户画像) → profile.js ✅ / persona_generator.js ✅
工具功能memory_scene_induct从记忆中归纳场景块 (L2)memory_scene_list列出所有场景块memory_scene_get获取场景块详情memory_scene_delete删除场景块memory_scene_search搜索场景块memory_scene_stats获取场景统计memory_pipeline_status获取四层管线状态memory_pipeline_trigger手动触发管线阶段memory_pipeline_config更新管线配置memory_cleaner_status获取数据清理器状态memory_cleaner_config更新数据清理器配置memory_cleaner_run手动执行一次数据清理memory_local_embedding_status获取本地 Embedding 服务状态memory_local_embedding_warmup启动模型预热memory_local_embedding_embed使用本地模型获取向量
before_prompt_build 自动召回, agent_end 自动捕获text
Vector Store Factory (vector_factory.js)
│
├── 'lancedb' → VectorMemory (LanceDB 后端,默认)
│ └── 现有实现,保持兼容
│
└── 'sqlite' → VectorStore (SQLite 后端,🆕)
├── L0: l0_conversations + l0_vec
├── L1: l1_records + l1_vec
├── FTS5: l1_fts + l0_fts (jieba 分词)
├── BM25: 全文排序
└── sqlite-vec 扩展
环境变量默认值说明VECTOR_STORE_TYPE``lancedb后端类型: lancedb 或 sqlite``SQLITE_DB_PATH``./memory/memory.dbSQLite 数据库路径
bash
# 使用 LanceDB 后端(默认)
export VECTOR_STORE_TYPE=lancedb
# 使用 SQLite 后端(需要 sqlite-vec 扩展)
export VECTOR_STORE_TYPE=sqlite
export SQLITE_DB_PATH=/root/.openclaw/workspace/memory/memory.db
bash
# Option 1: ClawHub (recommended)
clawhub install unified-memory
# Option 2: Manual
git clone https://github.com/mouxangithub/unified-memory.git
cd unified-memory && npm install
# Verify
mcporter call unified-memory memory_health '{}'
When any of these keywords or commands appear in a user message, this skill activates automatically:
TypeKeywords / CommandsKeywords (EN)memory, recall, forget, remember, 知识库Keywords (中文)记忆, 记住, 记一下, 我想知道Commands/memory
json
{
"filesystem": {
"read": ["~/.openclaw/workspace/memory/"],
"write": ["~/.openclaw/workspace/memory/"]
},
"env": ["OLLAMA_HOST", "OLLAMA_EMBED_MODEL", "STORAGE_MODE"]
}
VariableDefaultDescriptionOLLAMA_HOST``http://localhost:11434Ollama API endpointOLLAMA_EMBED_MODEL``nomic-embed-textEmbedding model nameLLM_MODEL``qwen2.5:7bLLM model for generation tasksLLM_PROVIDER``ollamaLLM providerVECTOR_ENGINE``lancedbVector database backendSTORAGE_MODE``jsonStorage backend: json or sqlite``OPENCLAW_WORKSPACE_DIR``~/.openclaw/workspaceWorkspace directory变量默认值说明OLLAMA_HOST``http://localhost:11434Ollama API 地址OLLAMA_EMBED_MODEL``nomic-embed-textEmbedding 模型LLM_MODEL``qwen2.5:7b生成任务用的大模型LLM_PROVIDER``ollama大模型 providerVECTOR_ENGINE``lancedb向量数据库后端STORAGE_MODE``json存储后端: json 或 sqlite``OPENCLAW_WORKSPACE_DIR``~/.openclaw/workspace工作目录-->
v4.0 is the recommended path for all new development. Built on SQLite-first StorageGateway with incremental indexes, multi-tenant team spaces, and distributed rate limiting. v4.0 新存储后端,基于 SQLite + 增量索引,推荐所有新开发使用。
All v4 tools: mcporter call unified-memory <tool-name> '<json-args>'
ToolDescriptionmemory_v4_statsStorageGateway statistics (memory count, evidence, revisions, WAL)memory_v4_searchIncremental BM25 search (no full rebuild on new documents)memory_v4_storeWAL + incremental index in single SQLite transactionmemory_v4_listB-tree scope-filtered memory listing
ToolDescriptionmemory_v4_hybrid_searchBM25 + Ollama vector RRF fusion with normalized scores
ToolDescriptionmemory_v4_create_teamCreate a team spacememory_v4_list_teamsList all teamsmemory_v4_get_teamGet team config + memory countmemory_v4_delete_teamDelete team (memories preserved)memory_v4_team_storeStore memory in team space (auto-creates team)memory_v4_team_searchStrict team isolation — only team memories, never leaks to USER/GLOBAL scopememory_v4_team_searchStrict team isolation search — only team memories, never leaks to USER/GLOBAL scope
ToolDescriptionmemory_v4_rate_limit_statusCheck current rate limit (write/read/search)
ToolDescriptionmemory_v4_evidence_statsEvidence chain stats (TTL 90-day)memory_v4_trim_evidenceManually trigger TTL trimmemory_v4_revision_statsRevision history stats (max 50/memory)
ToolDescriptionmemory_v4_wal_statusWAL status (total/pending/committed)memory_v4_wal_exportExport WAL as JSONLmemory_v4_wal_truncateRemove non-committed WAL entries
工具说明memory_v4_stats存储网关统计(记忆数、evidence、版本、WAL)memory_v4_search增量 BM25 搜索(新文档无需全量重建)memory_v4_storeWAL + 增量索引单 SQLite 事务memory_v4_listB-tree 范围过滤列表
工具说明memory_v4_hybrid_searchBM25 + Ollama 向量 RRF 融合,归一化分数
工具说明memory_v4_create_team创建团队空间memory_v4_list_teams列出所有团队memory_v4_get_team获取团队配置 + 记忆数memory_v4_delete_team删除团队(记忆保留)memory_v4_team_store在团队空间中存储记忆(自动创建团队)memory_v4_team_search严格团队隔离搜索 — 仅搜团队内记忆,绝不泄露到 USER/GLOBAL
工具说明memory_v4_rate_limit_status查看当前限流状态(写/读/搜索)
工具说明memory_v4_evidence_statsEvidence 链统计(TTL 90天)memory_v4_trim_evidence手动触发 TTL 清理memory_v4_revision_stats版本历史统计(最多50条/记忆)
工具说明memory_v4_wal_statusWAL 状态(总数/pending/committed)memory_v4_wal_exportJSONL 导出 WALmemory_v4_wal_truncate删除未提交的 WAL 条目-->
⚠️ Legacy v3 tools — 79 tools from the v3.x series. For new development, use v4.0 tools above. v3 工具 — 遗留工具集。新开发请使用上方 v4.0 工具。
All tools are called via mcporter call unified-memory <tool-name> <args>.
所有工具通过 mcporter call unified-memory <tool-name> <args> 调用。
ToolDescriptionmemory_searchHybrid BM25 + Vector search with scope filtering. Returns ranked results with highlights.memory_listList memories with optional pagination and scope filter.memory_concurrent_searchParallel multi-query search for faster coverage.memory_recommendRecommend relevant memories based on current context.memory_qmdQMD (Query Memory Document) structured search.memory_noiseFilter noise — skip generic or meaningless queries.memory_intentDetect user intent and route to appropriate handler.工具说明memory_search混合搜索:BM25 + 向量检索,支持范围过滤,返回排序结果和摘要高亮。memory_list列出记忆,支持分页和范围过滤。memory_concurrent_search并发多查询搜索,更快覆盖。memory_recommend根据当前上下文推荐相关记忆。memory_qmdQMD 结构化查询。memory_noise过滤无意义查询。memory_intent检测用户意图并路由到合适的处理器。-->
ToolDescriptionmemory_storeStore a new memory with text, category, importance, tags, scope.memory_deleteDelete a memory by ID.memory_pinPin a memory to prevent decay and deletion.memory_unpinUnpin a pinned memory.memory_pinsList all pinned memories.memory_exportExport memories in JSON, CSV, or Markdown format.memory_cloud_backupBackup all memories to cloud storage.memory_cloud_restoreRestore memories from cloud backup.memory_syncSync memories with external sources.工具说明memory_store存储新记忆,支持文本、分类、重要度、标签、范围。memory_delete按 ID 删除记忆。memory_pin置顶记忆,防止衰减和删除。memory_unpin取消置顶。memory_pins列出所有置顶记忆。memory_export导出记忆为 JSON/CSV/Markdown 格式。memory_cloud_backup备份到云存储。memory_cloud_restore从云备份恢复。memory_sync与外部数据源同步。-->
ToolDescriptionmemory_extractExtract entities, relations, and facts from text using LLM.memory_reflectionReflect on past memories to identify patterns and insights.memory_lessonsGenerate and store lessons learned from experiences.memory_preferenceLearn and apply user preferences.memory_inferenceInfer new facts from existing memories (logical reasoning).memory_adaptiveAdapt search and retrieval based on usage patterns.memory_compress_tierCompress low-importance memories to save tokens.memory_identity_extractExtract identity information from memories.memory_identity_getGet stored identity profiles.memory_identity_updateUpdate identity profiles.工具说明memory_extract用 LLM 从文本中提取实体、关系和事实。memory_reflection反思过去的记忆,识别模式和洞察。memory_lessons从经验中生成和存储教训。memory_preference学习和应用用户偏好。memory_inference从现有记忆推断新事实(逻辑推理)。memory_adaptive根据使用模式调整搜索和检索。memory_compress_tier压缩低重要度记忆以节省 token。memory_identity_extract从记忆中提取身份信息。memory_identity_get获取存储的身份档案。memory_identity_update更新身份档案。-->
ToolDescriptionmemory_statsGet memory statistics: count, categories, tags, distribution.memory_healthHealth check: storage, vector DB, WAL integrity, Ollama status.memory_metricsGet detailed usage metrics and performance data.memory_budgetGet token budget status and allocation.memory_tierManage memory tiers (HOT/WARM/COLD) and view tier stats.memory_tier_statsStatistics for each tier.memory_decayGet decay scores for memories.memory_dedupDeduplicate memories by text similarity.memory_organizeOrganize memories by category, tag, or time.memory_full_organizeFull reorganization of all memories.memory_cacheCache management for vector and BM25 indexes.memory_cognitiveCognitive analysis of memory patterns.memory_scopeManage scope assignments and filters.memory_archive_oldArchive old memories automatically.memory_lanesLane-based memory isolation for multi-agent scenarios.memory_dashboardAccess the web dashboard data.memory_walWAL (Write-Ahead Log) status and operations.memory_wal_statusGet WAL integrity status.memory_wal_exportExport WAL operations.memory_wal_importImport WAL operations.memory_wal_replayReplay WAL operations.memory_wal_truncateTruncate WAL.memory_wal_writeWrite a WAL entry directly.memory_engineGet/set storage engine configuration.memory_graphKnowledge graph operations.memory_summaryGenerate a summary of memories.memory_templatesUse templates for structured memory storage.memory_qaQuestion answering over stored memories.memory_versionVersion history management for memories.memory_evidence_statsEvidence chain statistics.memory_evidence_addAdd evidence to a memory's chain.memory_evidence_getGet evidence chain for a memory.memory_evidence_find_by_sourceFind evidence by source ID.memory_evidence_find_by_typeFind evidence by type.memory_proactiveProactive memory management and suggestions.memory_proactive_careProactive care: monitor and maintain important memories.memory_proactive_recallProactive recall: remind user of relevant past memories.memory_reminderSet reminders based on memory content.memory_traceTrace memory access and modification history.memory_transcriptTranscript management for context capture.memory_transcript_addAdd a transcript entry.memory_transcript_compactCompact transcript data.memory_transcript_deleteDelete transcript entries.memory_transcript_find_by_sourceFind transcript entries by source.memory_transcript_getGet transcript entry.memory_transcript_listList transcript entries.memory_transcript_rebuildRebuild transcript index.memory_transcript_statsTranscript statistics.memory_transcript_summaryGenerate transcript summary.memory_transcript_updateUpdate transcript entry.memory_transcript_verifyVerify transcript integrity.memory_sessionSession memory management.memory_git_notesGit commit message memory.memory_gitnotes_backupBackup git notes.memory_gitnotes_restoreRestore git notes.memory_cloud_backup_apiCloud backup API management.工具说明memory_stats记忆统计:数量、分类、标签、分布。memory_health健康检查:存储、向量库、WAL 完整性、Ollama 状态。memory_metrics详细使用指标和性能数据。memory_budgetToken 预算状态和分配。memory_tier管理记忆层级(HOT/WARM/COLD)并查看层级统计。memory_tier_stats各层级统计。memory_decay获取记忆衰减分数。memory_dedup按文本相似度去重。memory_organize按分类/标签/时间整理记忆。memory_full_organize全量整理所有记忆。memory_cache向量和 BM25 索引缓存管理。memory_cognitive记忆模式认知分析。memory_scope范围分配和过滤管理。memory_archive_old自动归档旧记忆。memory_lanes多 Agent 场景的通道隔离。memory_dashboard访问 Web 仪表盘数据。memory_wal_*WAL(预写日志)相关操作(状态/导出/导入/回放/截断/写入)。memory_engine获取/设置存储引擎配置。memory_graph知识图谱操作。memory_summary生成记忆摘要。memory_templates使用模板存储结构化记忆。memory_qa基于记忆的问答。memory_version记忆版本历史管理。memory_evidence_*Evidence Chain 操作(统计/添加/获取/按源查找/按类型查找)。memory_proactive_*主动记忆管理(建议/关怀/提醒)。memory_reminder根据记忆内容设置提醒。memory_trace记忆访问和修改历史追踪。memory_transcript_*Transcript(会话记录)完整操作集。memory_session会话记忆管理。memory_git_notes*Git notes 备份和恢复。memory_cloud_backup_api云备份 API 管理。-->
bash
# Health check
mcporter call unified-memory memory_health '{}'
# Store a memory
mcporter call unified-memory memory_store '{"text": "用户偏好简洁风格", "category": "preference", "importance": 0.8}'
# Search memories
mcporter call unified-memory memory_search '{"query": "用户偏好", "topK": 5}'
# List with pagination
mcporter call unified-memory memory_list '{"page": 1, "pageSize": 20}'
# Get statistics
mcporter call unified-memory memory_stats '{}'
# Delete
mcporter call unified-memory memory_delete '{"id": "mem_xxx"}'
# Export
mcporter call unified-memory memory_export '{"format": "json"}'
# Evidence chain
mcporter call unified-memory memory_evidence_add '{"memoryId": "mem_xxx", "type": "transcript", "sourceId": "msg_123"}'
# Version history
mcporter call unified-memory memory_version '{"memoryId": "mem_xxx"}'
bash
# 健康检查
mcporter call unified-memory memory_health '{}'
# 存储记忆
mcporter call unified-memory memory_store '{"text": "用户偏好简洁风格", "category": "preference", "importance": 0.8}'
# 搜索记忆
mcporter call unified-memory memory_search '{"query": "用户偏好", "topK": 5}'
# 分页列表
mcporter call unified-memory memory_list '{"page": 1, "pageSize": 20}'
# 统计
mcporter call unified-memory memory_stats '{}'
# 删除
mcporter call unified-memory memory_delete '{"id": "mem_xxx"}'
# 导出
mcporter call unified-memory memory_export '{"format": "json"}'
# Evidence 链
mcporter call unified-memory memory_evidence_add '{"memoryId": "mem_xxx", "type": "transcript", "sourceId": "msg_123"}'
# 版本历史
mcporter call unified-memory memory_version '{"memoryId": "mem_xxx"}'
-->
Memories are isolated by scope:
ScopeDescriptionUSERPrivate to the current user (default)TEAMShared within a teamAGENTAgent-specific memoryGLOBALAccessible to all agents and users
Scope filtering is O(1) via in-memory Map index. See docs/ARCHITECTURE.md for details.
范围说明USER当前用户私有(默认)TEAM团队内共享AGENTAgent 专用GLOBAL所有 Agent 和用户可访问
范围过滤通过内存 Map 索引实现 O(1) 查询,详见 docs/ARCHITECTURE.md。 | -->
BackendModeDescriptionjson (default)File-basedmemories.json with write-behind bufferingsqliteDatabaseSQLite via storage_sqlite.js, enabled by STORAGE_MODE=sqlite
SQLite backend provides better concurrency and I/O performance for high-throughput scenarios.
后端模式说明json(默认)文件memories.json,写缓冲优化sqlite数据库STORAGE_MODE=sqlite 启用,提供更好的并发和 I/O 性能-->
text
┌─────────────────────────────────────────────────────┐
│ index.js (MCP Server) │
│ 79 registered tools / 79个注册工具 │
└────────────────┬────────────────────────────────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐
│storage │ │ BM25 │ │ Vector │
│.js │ │.js │ │(LanceDB) │
└────┬───┘ └────┬───┘ └─────┬────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────┐
│ Scope Index (Map O(1)) │
│ USER / TEAM / AGENT / GLOBAL │
└─────────────────────────────────────────┘
Full architecture details: docs/ARCHITECTURE.md
完整架构详见 docs/ARCHITECTURE.md。 -->
⚠️ The new docs/ folder is the authoritative source for Hook + MCP integration guides. The links below supersede older inline documentation.
DocumentDescriptiondocs/en/README.mdOverview, quick start, architecture, FAQdocs/en/HOOK_INTEGRATION.mdHook mechanism, before_prompt_build, agent_end, performancedocs/en/MCP_INTEGRATION.mdMCP tools, manual usage, configuration examplesdocs/en/INTEGRATION_COMPARISON.mdHook+MCP vs MCP-only vs Hook-only comparison
文档说明docs/zh/README.md概述、快速开始、架构、常见问题docs/zh/HOOK_INTEGRATION.mdHook 机制、before_prompt_build、agent_end、性能分析docs/zh/MCP_INTEGRATION.mdMCP 工具、手动调用、配置示例docs/zh/INTEGRATION_COMPARISON.mdHook+MCP vs 仅MCP vs 仅Hook 对比分析
DocumentDescriptionREADME.mdBilingual overview, features, quick startdocs/ARCHITECTURE.mdTechnical architecture (bilingual)docs/competitive-analysis.mdCompetitive analysisdocs/CHANGELOG.mdVersion history and changelogSKILL_CN.mdLegacy Chinese SKILL (superseded by this file)HOOK.mdHook lifecycle and configuration reference
⚡ 新功能: 从 Supermemory 学习并实现的增强功能
从最近 N 条记忆中提取动态画像,结合静态画像(persona.md)。
功能:
static: 从 persona.md 读取长期稳定事实 + 偏好dynamic: 归纳最近活动(工作重点、关注点)API:
javascript
import { getProfile } from './profile/dynamic_profile.js';
const profile = await getProfile(userId, {
recentMemoryLimit: 100,
recencyWindowDays: 7,
});
// 返回: { static: {...}, dynamic: {...}, lastUpdated: timestamp }
字段说明:
static.facts: 长期事实static.preferences: 用户偏好static.skills: 技能列表static.goals: 目标列表dynamic.keywords: 近期关键词dynamic.topics: 近期主题dynamic.entities: 近期实体dynamic.activities: 活动类型dynamic.focusAreas: 关注点检测并解决记忆中的矛盾陈述。
功能:
API:
javascript
import { detectContradictions, resolveContradictions } from './forgetting/contradiction_resolver.js';
// 检测矛盾
const contradictions = await detectContradictions(memories, { useLLM: true });
// 解决矛盾
const result = await resolveContradictions(contradictions, { storage });
支持的模式:
检测和清理临时事实(有过期时间的记忆)。
功能:
API:
javascript
import { extractExpiryTime, cleanExpiredMemories } from './forgetting/temporal_expiry.js';
// 提取过期时间
const expiry = await extractExpiryTime(memory);
// 清理过期记忆
const result = await cleanExpiredMemories(memories, storage);
支持的时间表达式:
统一搜索接口,支持记忆 + 文档混合搜索。
搜索模式:
memories: 只搜索记忆documents: 只搜索文档(RAG)hybrid: 合并两者结果(默认)API:
javascript
import { hybridSearch } from './search/hybrid_search.js';
// 混合搜索
const results = await hybridSearch(query, {
searchMode: 'hybrid',
maxResults: 20,
rerankResults: true,
});
特性:
为外部数据源提供统一的同步接口。
BaseConnector:
javascript
import { BaseConnector } from './connectors/base.js';
class GitHubConnector extends BaseConnector {
constructor(options) {
super({ name: 'github', type: 'github', ...options });
}
async _doSync() {
// 实现具体同步逻辑
return items;
}
}
接口:
sync(): 全量同步watch(callback): 增量监听normalize(rawData): 数据格式转换为不同类型文件提供统一的内容提取接口。
BaseExtractor:
javascript
import { BaseExtractor } from './extractors/base.js';
class PDFExtractor extends BaseExtractor {
constructor(options) {
super({ name: 'pdf', type: 'pdf', supportedFormats: ['pdf'], ...options });
}
async _doExtract(filePath, options) {
// 实现具体提取逻辑
return { content, metadata };
}
}
接口:
extract(filePath): 提取文件内容extractBatch(filePaths): 批量提取supports(filePath): 检查是否支持内置提取器:
TextExtractor: 文本文件 (txt, md, json, yaml, csv)javascript
// Dynamic Profile
import { getProfile, getProfiles, invalidateCache } from './profile/dynamic_profile.js';
// Contradiction Resolution
import { detectContradiction, detectContradictions, resolveContradictions } from './forgetting/contradiction_resolver.js';
// Temporal Expiry
import { extractExpiryTime, cleanExpiredMemories, startExpiryChecker } from './forgetting/temporal_expiry.js';
// Hybrid Search
import { hybridSearch, searchMemoriesOnly, searchDocumentsOnly } from './search/hybrid_search.js';
// Connectors
import { BaseConnector, registerConnector, createConnector } from './connectors/index.js';
// Extractors
import { BaseExtractor, TextExtractor, autoExtract } from './extractors/index.js';
🆕 新增功能:Benchmark 验证 + 可配置实体类型 + 插件系统
运行 recall@K / precision@K / MRR 基准测试,对标 LoCoMo / LongMemEval。
新工具:
工具功能memory_benchmark_recall运行召回率基准测试
使用方法:
javascript
// 直接调用
const report = runRecallBenchmark();
// 返回: { timestamp, dataset_size, metrics: { recall@1/5/10, precision@1/5, mrr }, results: [...] }
输出指标:
recall@K: 前 K 个结果中包含的相关记忆比例precision@K: 前 K 个结果中相关记忆的占比MRR: 首个相关结果的倒数排名平均值Benchmark 报告保存位置:
text
~/.openclaw/skills/unified-memory/src/benchmark/results/
实体类型不再硬编码,改为从配置文件加载,支持运行时扩展。
新工具:
工具功能memory_entity_types_list列出所有实体类型配置memory_entity_type_add添加/更新实体类型
配置文件:
text
~/.openclaw/workspace/memory/config/entity_types.json
默认实体类型:
类型标签颜色优先级person人物#667eea10organization组织#10b9818project项目#f59e0b9topic主题#8b5cf66tool工具#06b6d47location地点#ef44445date日期#ec48994event事件#84cc166
运行时添加新类型:
javascript
addEntityType('framework', {
label: '框架',
color: '#ff6b6b',
keywords: ['React', 'Vue', 'Angular', 'Next.js'],
priority: 7,
});
使用 MCP 工具:
json
{
"name": "memory_entity_type_add",
"arguments": {
"typeName": "framework",
"label": "开发框架",
"color": "#ff6b6b",
"keywords": ["React", "Vue", "Angular"],
"priority": 7
}
}
可插拔架构,支持在搜索/写入关键节点注入自定义逻辑。
内置插件:
插件功能kg-enrich知识图谱增强:在搜索结果中附加 KG 实体/关系上下文dedup去重:写入前检查相似记忆,防止重复revision版本追踪:自动记录每次写入的 revision
新工具:
工具功能memory_plugins_list列出所有已注册插件memory_plugin_enable启用插件memory_plugin_disable禁用插件memory_plugin_register注册外部插件
插件 Hook 接口:
javascript
const myPlugin = {
name: 'my-plugin',
version: '1.0.0',
description: 'My custom plugin',
enabled: true,
hooks: {
beforeSearch: async (query, context) => query,
afterSearch: async (results, context) => results,
beforeWrite: async (memory, context) => memory,
afterWrite: async (memory, context) => memory,
onConflictDetected: async (local, remote) => ({ resolution: 'merged' }),
},
config: { /* 自定义配置 */ },
};
Hook 执行顺序:
text
beforeSearch → [实际搜索] → afterSearch
↓
beforeWrite → [实际写入] → afterWrite
插件注册表位置:
text
~/.openclaw/workspace/memory/plugins/registry.json
javascript
// Benchmark
import { runRecallBenchmark } from './benchmark/eval_recall.js';
// Entity Config
import { loadEntityConfig, addEntityType, getEntityTypesByPriority } from './graph/entity_config.js';
// Plugin System
import { getPlugins, enablePlugin, disablePlugin, registerPlugin } from './plugin/plugin_manager.js';
MIT License. See README.md.