@claude-flow/memory

中文文档
3.3.0发布于 2026/11/10TypeScriptES Module近 30 天下载 36.4万

内存模块 - AgentDB统一,HNSW索引,向量搜索,混合 SQLite+AgentDB后端(ADR-009)

中文使用文档
文档目录45 节
  1. 有什么新鲜的 3.0.0-alpha.18 (发展成果评估-125)
  2. 特征
  3. 安装
  4. 独立使用(没有 Ruflo CLI)
  5. 道具1 — HNSW 指数, 内置定量( 无其它道具)
  6. 道具 2 — 驱动控制器注册到您自己的代理数据库
  7. 快速启动
  8. 从 3.0.0-alpha.17 或更早时间
  9. 持久性
  10. 内存整合
  11. 优雅检索( FTS5倒计时)
  12. API 参考
  13. HNSW 指数
  14. AgentDB 适配器
  15. 快取管理器
  16. 查询构建器
  17. 移徙
  18. 量化选项
  19. 自动记忆桥(ADR-048)
  20. 快速启动
  21. 同步模式
  22. 透视类别
  23. 键优化
  24. 工具函数
  25. 类型
  26. 自学桥(ADR-049)
  27. 快速启动
  28. 独立使用
  29. 置信周期
  30. 知识图(ADR-049)
  31. 快速启动
  32. 独立使用
  33. 边缘类型
  34. 业绩
  35. 代理扫描内存(ADR-049)
  36. 快速启动
  37. 范围路径
  38. 公用事业
  39. 业绩基准
  40. HNSW 搜索基线 baseline-20260519T212453Z.md (中文(简体) )
  41. ADR-049 基准
  42. 类型脚本
  43. 依赖关系
  44. 相关软件包
  45. 许可证

@ claude- flow/ 记忆

npm version Ecosystem downloads Git clones (14d) License: MIT TypeScript HNSW search

Claude Flow V3的高性能记忆——一克能 MemoryService API在真实的混合后端上方(sql.js + AgentDB),持续的HNSW向量搜索在重启后存活下来,内存有集成器,嵌入器不可用时优雅的关键词(FTS5)回落,外加AutoMemoryBridge,自学,和上方所构建的知识图层.

有什么新鲜的 3.0.0-alpha.18 (发展成果评估-125)

这个发行结束 ADR-125 — 记忆巩固。如果你正在升级 从 3.0.0-alpha.17 或更早,这是标题 :

  • 一个犬科入口. MemoryService 替换旧的 UnifiedMemoryService 名称( 两者仍然导出—— 旧名称是 : @deprecated 将被移除时 3.0.0-rc) (中文(简体) ). 见 移徙 见下文.
  • 真正的混合默认 . createHybridService(...) 最后返回一个服务,其后端是实际的 HybridBackend (sql.js + AgentDB). 更早的释放悄悄地将这降级到AgentDB-只——ADR-009的承诺直到现在才兑现.
  • 持续HNSW. 关闭服务将其 HNSW 索引快照到侧车(<dbPath>.hnsw + 键 <dbPath>.meta.json) (中文(简体) ). 在同一道上重开会以毫秒的速度恢复,而不是从零开始重建——搜索准备的冷起.
  • MemoryConsolidator。 。 。 . 从索引中删除过期条目的背景服务 财务报告和审定财务报表 HNSW,由内容散列来分解,当HNSW指数被分解后重建. 自动运行在可配置的计时器上(默认为6小时),所以内存仍然被限制.
  • 优雅的检索. service.search('query') 不再掷出当 @claude-flow/embeddings 无法使用 – 它降解为 FTS5 关键字搜索并发送 health.embedder = 'degraded'. 完整的混合路径还添加了真正的对等的 Rank Fusion + MMR 多样性重新排序.
  • 可复制基准. npm run bench 现在实际运行。 HNSW 搜索基线( 单行径, 1k × 128- dim 宇宙向量在 Apple Silicon, 第22号节点上): 0.53 ms/ search 1,889 ops/s 533 ms来建造1k。见 benchmarks/results/baseline-20260519T212453Z.md。 。 。 .
  • 节点 26 安装支持 (单位:千美元)# 1867 (英语)(b) —— better-sqlite3 完全可选 ; 安装在 Node 24/26 上成功, 当本地建筑不可用时, 软件包会回到 sql.js .

特征

  • 光学 MemoryService API 密码 ——存储/检索/搜索/混合查询的一个出入口
  • 真正的混合后端 —— 说 HybridBackend (sql.js + AgentDB)用于结构化+向量查询(ADR-009 / ADR-125 第2阶段)
  • 持久性 HNSW ——指数存续 close() 并重新启动; 自动拍摄每 Nth 写入( ADR-125 阶段 3)
  • MemoryConsolidator —— 说 sweepExpired() + 键 dedup() + 键 compactHnsw() + 自动运行计时器(ADR-125 第4阶段)
  • 优雅的检索 ——嵌入器无法接通时自动FTS5关键字回落;RRF+MMR用于混合(ADR-125相5)
  • HNSW 向量搜索 测量 0.53毫秒/在1k×128暗处搜索 苹果硅; 见上文基线
  • 自动内存桥 —— Claude Code 自动存储器和 AdentDB (ADR-048) 之间的双向同步
  • 自学 ——学习桥将洞察力与SONA/ReasoningBank神经管连接(ADR-049)
  • 知识图 - PageRank + 标签传播社区在内存条目上的检测(ADR-049)
  • 代理扫描内存 3个范围(项目/本地/用户)具有跨代理知识转让(ADR-049)的代理内存
  • 矢量量化 4-32x内存减少的二进制、分级和产品量化
  • 多距离计量 - 克辛、欧几利得、点产品和曼哈顿
  • 查询构建器 ——流利的API用于构建复杂的内存查询
  • 快取管理器 具有可配置尺寸和TTL的LRU缓冲
  • 迁移工具 —— 说 MemoryMigrator 用于从 V2 内存系统移动
  • 跨平台 ——关于Linux,macOS,和Windows的作品;节点18+(包括节点24/26)

安装

npm install @claude-flow/memory

独立使用(没有 Ruflo CLI)

这个套装是靠自己工作的,你不需要 @claude-flow/cli 或 完全安装 Ruflo 。 HNSW 向量搜索 AgentDB façade, 或您自己的应用程序中的 v3 控制器注册 .

两种操作最密集表面的食谱:

道具1 — HNSW 指数, 内置定量( 无其它道具)

// recipe.mjs
import { HNSWIndex } from '@claude-flow/memory';

const index = new HNSWIndex({
  dimensions: 8,
  M: 16,
  efConstruction: 200,
  metric: 'cosine',
});

// Add a few vectors
await index.addPoint('doc-a', new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]));
await index.addPoint('doc-b', new Float32Array([0.9, 0.1, 0, 0, 0, 0, 0, 0]));
await index.addPoint('doc-c', new Float32Array([0, 1, 0, 0, 0, 0, 0, 0]));

// Search — top 2 nearest to "doc-a"-shaped query
const hits = await index.search(new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]), 2);
console.log(hits); // [{ id: 'doc-a', distance: 0 }, { id: 'doc-b', distance: ~0.005 }]

道具 2 — 驱动控制器注册到您自己的代理数据库

登记册坐标为15+内存控制器(学习桥、内存) 图形、分级缓存、向量后端等) 你拥有。 当您已经拥有了 AgentDB 生命周期, 并且只是 想要 v3 治理层( 问题 # 2019 添加 agentdb 注射 字段,使这个干净.

import { ControllerRegistry } from '@claude-flow/memory';
import { AgentDB } from 'agentdb';

const agentdb = new AgentDB({ dbPath: ':memory:' });
await agentdb.initialize();

const registry = new ControllerRegistry();
await registry.initialize({ agentdb });

// Now everything backed by AgentDB is reachable through the registry
const reflexion = registry.get('reflexion');     // ReflexionMemory
const vectorBackend = registry.get('vectorBackend'); // live vector backend
const enabled = registry.isEnabled('skills');    // true

const health = await registry.healthCheck();
console.log(`${health.activeControllers}/${health.controllers.length} controllers active`);

await registry.shutdown();

快速启动

获得全功能内存服务——混合后端,HNSW向量索引,FTS5关键字回落,持续快照,合并计时器——最快的方法是 createHybridService数字 :

import { createHybridService } from '@claude-flow/memory';

async function embedder(text: string): Promise<Float32Array> {
  // Use any embedding provider — OpenAI, @claude-flow/embeddings, your own model.
  // If the embedder ever fails, MemoryService falls back to FTS5 keyword search
  // automatically (emitting `health.embedder = 'degraded'`).
  return new Float32Array(/* ... */);
}

const memory = await createHybridService('./data/memory.db', embedder, 1536);
await memory.initialize();

// Store an entry — content is embedded and added to both SQLite and HNSW
await memory.store({
  key: 'auth-patterns',
  content: 'OAuth 2.0 implementation patterns for secure authentication',
  tags: ['auth', 'security', 'patterns'],
});

// Semantic search via HNSW
const similar = await memory.semanticSearch('user authentication best practices', 5);

// Keyword search via FTS5 (also used as the automatic fallback)
const exact = await memory.searchKeyword('OAuth 2.0', { limit: 10 });

// Hybrid search — RRF-fused dense + sparse, MMR-diversified
const blended = await memory.search('authentication patterns', { limit: 10 });

// Clean shutdown — flushes the consolidator timer and snapshots HNSW to disk
await memory.close();

// Reopen the same path — entries AND HNSW index are restored from sidecar
const reopened = await createHybridService('./data/memory.db', embedder, 1536);
await reopened.initialize();
// memory.search() is immediately fast — no rebuild

也可以直接使用下层原始. HNSWIndex 正在导出,并且工作时不需要任何服务层,只要您想要一个矢量索引:

import { HNSWIndex } from '@claude-flow/memory';

const index = new HNSWIndex({
  dimensions: 1536,  // OpenAI embedding size
  M: 16,             // Max connections per node
  efConstruction: 200,
  metric: 'cosine',
});

await index.addPoint('memory-1', new Float32Array(embedding));
await index.addPoint('memory-2', new Float32Array(embedding2));

const results = await index.search(queryVector, 10);
// [{ id: 'memory-1', distance: 0.05 }, { id: 'memory-2', distance: 0.12 }]

// New in 3.0.0-alpha.18: persist the index to a buffer for restore later
const snapshot: Buffer = index.serialize();
const restored = HNSWIndex.deserialize(snapshot);

从 3.0.0-alpha.17 或更早时间

如果您已经使用此软件包 :

// Before
import { UnifiedMemoryService } from '@claude-flow/memory';
const memory = new UnifiedMemoryService({ /* ... */ });

// After (recommended) — both names resolve to the same class
import { MemoryService } from '@claude-flow/memory';
const memory = new MemoryService({ /* ... */ });

// `UnifiedMemoryService` continues to work through 3.0.0-rc as a `@deprecated` alias.

有两件事改变了 3.0.0-alpha.18数字 :

  1. createHybridService 现在照它的名字去做. 如果你只依靠以前的AgentDB降级 你会得到一个真正的 HybridBackend 现在——语义搜索和有条理的查询都不用额外的接线就可以工作.
  2. semanticSearch 当嵌入器不在时就不再扔了. 依赖于所抛出的错误来检测错误的嵌入器的代码应该听 health.embedder = 'degraded' 事件。 见 优雅的检索 见下文.

这个 HnswLite 财务报告和审定财务报表 RvfBackend 类别已不再是顶级出口(它们是内部执行的细节)。 如果您的代码导入, 请切换到 HNSWIndex (更能,更能持久)——它们被证实没有外部进口商.

持久性

单位 3.0.0-alpha.18 hNSW指数存活下来 close() 并重新启动。 快照自动发生 :

  • 打开 service.close(),索引序列化为 <dbPath>.hnsw 和内存条目/名称空间/密钥/tag地图 <dbPath>.meta.json。 。 。 .
  • 在服务期间,索引还每晚自动拍摄 store() 调用( 默认) N=1000,可通过 MemoryServiceConfig.snapshotInterval) (中文(简体) ).
  • 在初始化时,如果两辆侧车都存在,它们会被恢复. 服务发出3个之一 health.persistence 事件: 'restored' (成功), 'fresh' (未发现侧车-首跑),或 'corrupt' (去序列化失败——自动倒向新状态).
import { MemoryService, HNSWIndex } from '@claude-flow/memory';

const memory = new MemoryService({
  persistenceEnabled: true,
  persistencePath: './data/memory.db',
  snapshotInterval: 500,   // snapshot every 500 stores
  embeddingGenerator,
});

memory.on('health.persistence', (status) => {
  // 'restored' | 'fresh' | 'corrupt'
  console.log('Persistence state:', status);
});

await memory.initialize();
// ...store, query...
await memory.close();   // flushes a final snapshot

手动快照/在生件上重存 HNSWIndex数字 :

const buf: Buffer = index.serialize();
// write buf to disk, transfer between processes, etc.

const restored = HNSWIndex.deserialize(buf);
// search works immediately — no rebuild

序列格式的版本为有魔法头(HNSW\x01)——一幅被腐烂或僵化的快照被大声地检测和拒绝,而不是默默地产生出错误的邻居.

内存整合

MemoryConsolidator 保持索引的界限。 三项行动:

import { MemoryConsolidator } from '@claude-flow/memory';

const consolidator = new MemoryConsolidator(memory, {
  dedupStrategy: 'merge-tags',   // 'keep-newest' | 'keep-oldest' | 'merge-tags'
  intervalMs: 6 * 60 * 60 * 1000, // auto-run every 6h
});

// Evict expired entries from all indexes (including HNSW)
const swept = await consolidator.sweepExpired();
// { removed: 142, remaining: 8503 }

// Deduplicate by SHA-256 content hash
const dedup = await consolidator.dedup('keep-newest');
// { merged: 23 }

// Rebuild HNSW to reclaim space after large churn
const compaction = await consolidator.compactHnsw();
// { before: 8503, after: 8503, durationMs: 198 }

// Or run all three in sequence
const result = await consolidator.runAll();

你不必手动构造它.. MemoryService 如果您选择加入, 将会把它连接起来 :

const memory = new MemoryService({
  consolidator: {
    autoRun: true,                     // start a setInterval that runs runAll()
    intervalMs: 6 * 60 * 60 * 1000,    // every 6h (default)
  },
});

memory.on('consolidation.complete', (result) => {
  console.log(`Swept ${result.swept.removed}, deduped ${result.dedup.merged}`);
});

这个 nightlyLearner agentDB控制器登记册中的控制器,现在向 MemoryConsolidator.runAll() 而不是旧的AgentDB通过,因此从每一个期望"夜回想卫生"钩子的地层都引用了综合器.

优雅检索( FTS5倒计时)

MemoryService.search() 财务报告和审定财务报表 semanticSearch() 不再难倒 @claude-flow/embeddings (或你注射的嵌入器)是没有的。 他们:

  1. 试入地道.
  2. 如果投出或丢失,就发射 health.embedder = 'degraded'。 。 。 .
  3. 通过FTS5关键字搜索(porter + unicode61 sorderizer)运行同样的查询并返回这些结果.
const memory = new MemoryService({
  // No embeddingGenerator — semantic queries will fall back to FTS5
});
await memory.initialize();

memory.on('health.embedder', (state) => {
  // 'available' | 'degraded'
  console.warn(`Embedder is ${state}`);
});

await memory.store({ key: 'note-1', content: 'OAuth pattern review' });
const results = await memory.search('OAuth', { limit: 5 });
// Returns FTS-ranked matches; no throw

何时 两者 有密集和稀疏的路径, service.search(query) 将排名与对等排名组合起来k=60),并随着MMR(英语:MMR)重新排序λ=0.7多样性。 这就是代理数据库 hybridSearch 控制器也暴露了——它曾经是返回的根茎 null; 内 3.0.0-alpha.18 这是真正的执行.

API 参考

HNSW 指数

import { HNSWIndex } from '@claude-flow/memory';

const index = new HNSWIndex({
  dimensions: 1536,
  M: 16,                    // Max connections per layer
  efConstruction: 200,      // Construction-time search depth
  maxElements: 1000000,     // Max vectors
  metric: 'cosine',         // 'cosine' | 'euclidean' | 'dot' | 'manhattan'
  quantization: {           // Optional quantization
    type: 'scalar',         // 'binary' | 'scalar' | 'product'
    bits: 8
  }
});

// Add vectors
await index.addPoint(id: string, vector: Float32Array);

// Search
const results = await index.search(
  query: Float32Array,
  k: number,
  ef?: number  // Search-time depth (higher = more accurate)
);

// Search with filters
const filtered = await index.searchWithFilters(
  query,
  k,
  (id) => id.startsWith('session-')
);

// Remove vectors
await index.removePoint(id);

// Get statistics
const stats = index.getStats();
// { vectorCount, memoryUsage, avgSearchTime, compressionRatio }

AgentDB 适配器

import { AgentDBAdapter } from '@claude-flow/memory';

const adapter = new AgentDBAdapter({
  dimension: 1536,
  indexType: 'hnsw',
  metric: 'cosine',
  hnswM: 16,
  hnswEfConstruction: 200,
  enableCache: true,
  cacheSizeMb: 256
});

await adapter.initialize();

// Store memory
await adapter.store({
  id: 'mem-123',
  content: 'User prefers dark mode',
  embedding: vector,
  metadata: { type: 'preference', agentId: 'agent-1' }
});

// Semantic search
const memories = await adapter.search(queryVector, {
  limit: 10,
  threshold: 0.7,
  filter: { type: 'preference' }
});

// Cross-agent memory sharing
await adapter.enableCrossAgentSharing({
  shareTypes: ['patterns', 'preferences'],
  excludeTypes: ['secrets']
});

快取管理器

import { CacheManager } from '@claude-flow/memory';

const cache = new CacheManager({
  maxSize: 1000,
  ttlMs: 3600000,  // 1 hour
  strategy: 'lru'
});

// Cache operations
cache.set('key', value);
const value = cache.get('key');
const exists = cache.has('key');
cache.delete('key');
cache.clear();

// Statistics
const stats = cache.getStats();
// { size, hits, misses, hitRate }

查询构建器

import { QueryBuilder } from '@claude-flow/memory';

const results = await new QueryBuilder()
  .semantic(queryVector)
  .where('agentId', '=', 'agent-1')
  .where('type', 'in', ['pattern', 'strategy'])
  .where('createdAt', '>', Date.now() - 86400000)
  .orderBy('relevance', 'desc')
  .limit(20)
  .execute();

移徙

import { MemoryMigrator, createMigrator } from '@claude-flow/memory';

const migrator = createMigrator({
  source: './data/v2-memory.db',
  destination: './data/v3-memory.db',
});

// Inspect what will be migrated
const preview = await migrator.preview();
console.log(`Will migrate ${preview.recordCount} records`);

// Execute migration
await migrator.execute({
  batchSize: 1000,
  onProgress: (progress) => console.log(`${progress.percent}%`),
});

量化选项

// Binary quantization (32x compression)
const binaryIndex = new HNSWIndex({
  dimensions: 1536,
  quantization: { type: 'binary' }
});

// Scalar quantization (4x compression)
const scalarIndex = new HNSWIndex({
  dimensions: 1536,
  quantization: { type: 'scalar', bits: 8 }
});

// Product quantization (8x compression)
const productIndex = new HNSWIndex({
  dimensions: 1536,
  quantization: { type: 'product', subquantizers: 8 }
});

自动记忆桥(ADR-048)

Claude代码之间的双向同步 自动内存 文件和AgentDB。 自动内存是一个持久的目录( Name~/.claude/projects/<project>/memory/克劳德把学习写成减分. MEMORY.md (前200行)被加载入系统快取;专题文件按要求读取.

快速启动

import { AutoMemoryBridge } from '@claude-flow/memory';

const bridge = new AutoMemoryBridge(memoryBackend, {
  workingDir: '/workspaces/my-project',
  syncMode: 'on-session-end', // 'on-write' | 'on-session-end' | 'periodic'
  pruneStrategy: 'confidence-weighted', // 'confidence-weighted' | 'fifo' | 'lru'
});

// Record an insight (stores in AgentDB + optionally writes to files)
await bridge.recordInsight({
  category: 'debugging',
  summary: 'HNSW index requires initialization before search',
  source: 'agent:tester',
  confidence: 0.95,
});

// Sync buffered insights to auto memory files
const syncResult = await bridge.syncToAutoMemory();

// Import existing auto memory files into AgentDB (on session start)
const importResult = await bridge.importFromAutoMemory();

// Curate MEMORY.md index (stays under 200-line limit)
await bridge.curateIndex();

// Check status
const status = bridge.getStatus();

同步模式

模式行为
on-write立即写入文件 recordInsight()
on-session-end突破洞察力,冲出 syncToAutoMemory()
periodic在可配置间隔上自动同步

透视类别

类别主题文件说明
project-patternspatterns.md守则模式和公约
debuggingdebugging.md错误修正和调试真知灼见
architecturearchitecture.md设计决定和模块关系
performanceperformance.md基准和优化成果
securitysecurity.md安全调查结果和CVE说明
preferencespreferences.md用户和项目偏好
swarm-resultsswarm-results.md多剂组结果

键优化

  • 批量导入 - 说吧 bulkInsert() 而不是个人 store() 电话
  • 预选散列 - 导入时对内容进行单个查询
  • 自动同步 I/ 欧 - 说吧 node:fs/promises 用于非屏蔽写入
  • 准确解密 - 说吧 hasSummaryLine() 使用项目符号前缀匹配,而不是子字符串
  • O(1) 同步跟踪 - 说吧 syncedInsightKeys 设定防止双写比赛
  • 建造前的管道 - 避免O(n^2)指数重建循环

工具函数

import {
  resolveAutoMemoryDir,  // Derive auto memory path from working dir
  findGitRoot,           // Walk up to find .git root
  parseMarkdownEntries,  // Parse ## headings into structured entries
  extractSummaries,      // Extract bullet summaries, strip metadata
  formatInsightLine,     // Format insight as markdown bullet
  hashContent,           // SHA-256 truncated to 16 hex chars
  pruneTopicFile,        // Keep topic files under line limit
  hasSummaryLine,        // Exact bullet-prefix dedup check
} from '@claude-flow/memory';

类型

import type {
  AutoMemoryBridgeConfig,
  MemoryInsight,
  InsightCategory,
  SyncDirection,
  SyncMode,
  PruneStrategy,
  SyncResult,
  ImportResult,
} from '@claude-flow/memory';

自学桥(ADR-049)

将见解与 @claude-flow/neural 学习管道。 神经元无法使用时,所有手术都会退化为无操作.

快速启动

import { AutoMemoryBridge, LearningBridge } from '@claude-flow/memory';

const bridge = new AutoMemoryBridge(backend, {
  workingDir: '/workspaces/my-project',
  learning: {
    sonaMode: 'balanced',
    confidenceDecayRate: 0.005,   // Per-hour decay
    accessBoostAmount: 0.03,      // Boost per access
    consolidationThreshold: 10,   // Min insights before consolidation
  },
});

// Insights now trigger learning trajectories automatically
await bridge.recordInsight({
  category: 'debugging',
  summary: 'Connection pool exhaustion on high load',
  source: 'agent:tester',
  confidence: 0.9,
});

// Consolidation runs JUDGE/DISTILL/CONSOLIDATE pipeline
await bridge.syncToAutoMemory(); // Calls consolidate() first

独立使用

import { LearningBridge } from '@claude-flow/memory';

const lb = new LearningBridge(backend, {
  // Optional: inject neural loader for custom setups
  neuralLoader: async () => {
    const { NeuralLearningSystem } = await import('@claude-flow/neural');
    return new NeuralLearningSystem();
  },
});

// Boost confidence when insight is accessed
await lb.onInsightAccessed('entry-123'); // +0.03 confidence

// Apply time-based decay
const decayed = await lb.decayConfidences('default'); // -0.005/hour

// Find similar patterns via ReasoningBank
const patterns = await lb.findSimilarPatterns('connection pooling');

// Get learning statistics
const stats = lb.getStats();
// { totalTrajectories, activeTrajectories, completedTrajectories,
//   totalConsolidations, accessBoosts, ... }

置信周期

活动效果范围
透视记录来源的初步信心0.1 - 1.0 (中文(简体) )
透视访问+0.03 每个访问封面为 1.0
时间衰变自上次进入以来每小时0.005美元0.1下限
合并神经管可以调整0.1 - 1.0 (中文(简体) )

知识图(ADR-049)

纯TypeScript知识图有PageRank和社区检测. 不需要外部图库 .

快速启动

import { AutoMemoryBridge, MemoryGraph } from '@claude-flow/memory';

const bridge = new AutoMemoryBridge(backend, {
  workingDir: '/workspaces/my-project',
  graph: {
    similarityThreshold: 0.8,
    pageRankDamping: 0.85,
    maxNodes: 5000,
  },
});

// Graph builds automatically on import
await bridge.importFromAutoMemory();

// Curation uses PageRank to prioritize influential insights
await bridge.curateIndex();

独立使用

import { MemoryGraph } from '@claude-flow/memory';

const graph = new MemoryGraph({
  pageRankDamping: 0.85,
  pageRankIterations: 50,
  pageRankConvergence: 1e-6,
  maxNodes: 5000,
});

// Build from backend entries
await graph.buildFromBackend(backend, 'my-namespace');

// Or build manually
graph.addNode(entry);
graph.addEdge('entry-1', 'entry-2', 'reference', 1.0);
graph.addEdge('entry-1', 'entry-3', 'similar', 0.9);

// Compute PageRank (power iteration)
const ranks = graph.computePageRank();

// Detect communities (label propagation)
const communities = graph.detectCommunities();

// Graph-aware ranking: blend vector score + PageRank
const ranked = graph.rankWithGraph(searchResults, 0.7);
// alpha=0.7 means 70% vector score + 30% PageRank

// Get most influential insights for MEMORY.md
const topNodes = graph.getTopNodes(20);

// BFS traversal for related insights
const neighbors = graph.getNeighbors('entry-1', 2); // depth=2

边缘类型

类型来源说明
referenceMemoryEntry.references条目之间的明确对照
similarHNSW 搜索类似值 > 阈值时自动创建
temporal时间戳在同一时间窗口创建条目
co-accessed访问模式经常一起访问的条目
causal学习管道因果关系

业绩

运行结果目标
图形构建(1k节点)2.78个毫秒< 200毫秒( x)
页面朗克(1k个节点)12.21 分钟< 100分钟
社区检测(1k)19.62分钟—— 说
rankWithGraph(10)0.006 分钟—— 说
getTopNodes(20)0.308 分钟—— 说
getNeighbors(d=2)0.005分钟—— 说

代理扫描内存(ADR-049)

Maps Claude Code 三镜特效内存目录 用于每个特效的知识隔离和跨特效转移.

快速启动

import { createAgentBridge, transferKnowledge } from '@claude-flow/memory';

// Create a bridge for a specific agent scope
const agentBridge = createAgentBridge(backend, {
  agentName: 'my-coder',
  scope: 'project', // 'project' | 'local' | 'user'
  workingDir: '/workspaces/my-project',
});

// Record insights scoped to this agent
await agentBridge.recordInsight({
  category: 'debugging',
  summary: 'Use connection pooling for DB calls',
  source: 'agent:my-coder',
  confidence: 0.95,
});

// Transfer high-confidence insights between agents
const result = await transferKnowledge(sourceBackend, targetBridge, {
  sourceNamespace: 'learnings',
  minConfidence: 0.8,   // Only transfer confident insights
  maxEntries: 20,
  categories: ['debugging', 'architecture'],
});
// { transferred: 15, skipped: 5 }

范围路径

范围目录使用大小写
project<gitRoot>/.claude/agent-memory/<agent>/项目特定学习
local<gitRoot>/.claude/agent-memory-local/<agent>/机器本地数据
user~/.claude/agent-memory/<agent>/跨项目的用户知识

公用事业

import {
  resolveAgentMemoryDir,  // Get scope directory path
  createAgentBridge,       // Create scoped AutoMemoryBridge
  transferKnowledge,       // Cross-agent knowledge sharing
  listAgentScopes,         // Discover existing agent scopes
} from '@claude-flow/memory';

// Resolve path for an agent scope
const dir = resolveAgentMemoryDir('my-agent', 'project');
// → /workspaces/my-project/.claude/agent-memory/my-agent/

// List all agent scopes in a directory
const scopes = await listAgentScopes('/workspaces/my-project');
// [{ agentName: 'coder', scope: 'project', path: '...' }, ...]

业绩基准

可复制基准船 benchmarks/*.bench.ts自己运行它们:

cd v3/@claude-flow/memory
npm run build
npm run bench         # runs benchmarks/*.bench.ts under vitest

HNSW 搜索基线baseline-20260519T212453Z.md(中文(简体) )

在苹果硅(M系列)上测量,节点22.22.1,vitest 4.0.16. 情景:1,000个随机128-二分位余弦常态向量被装入单个 HNSWIndex,然后在热身后进行200次查询重复.

度量衡数值页:1
build_time_ms533.42 分钟顺序 addPoint() × 1 000个
search_k10_avg_ms0.5294亿秒暖后,平均200次重复
search_k50_avg_ms0.5235 毫秒(分钟)k=50 → k=10 – 基于堆积的选取占优势
add_avg_ms0.8656 分钟在初始 1k 后增加
search_k10_ops_per_sec1 888.9项行动衍生
search_k50_ops_per_sec1 910.1 行动/s衍生

这些数字是设备专用的;一旦 GitHub 动作板凳的工作降落, CI 基线将替换此文件 。 ADR-125 第3阶段(持久性HNSW)是指 冷启动 恢复应当是 build_time_ms 一旦添加了快照基准.

ADR-049 基准

运行实际目标会议室
图形构建(1k节点)2.78个毫秒< 200毫秒( x)71.9辆
页面朗克(1k个节点)12.21 分钟< 100分钟8.2x 单曲
透视录音0.12毫秒/每秒<5毫秒/每秒41.0x (中文(简体) )
合并0.26 分钟< 500毫秒( 秒)1 955辆
信心衰减(1k)0.23 分钟< 50分钟215个
知识转让1.25分钟< 100分钟80.0x (中文(简体) )

类型脚本

import type {
  // Core
  HNSWConfig, HNSWStats, SearchResult, MemoryEntry,
  QuantizationConfig, DistanceMetric,

  // Auto Memory Bridge (ADR-048)
  AutoMemoryBridgeConfig, MemoryInsight, InsightCategory,
  SyncDirection, SyncMode, PruneStrategy,
  SyncResult, ImportResult,

  // Learning Bridge (ADR-049)
  LearningBridgeConfig, LearningStats,
  ConsolidateResult, PatternMatch,

  // Knowledge Graph (ADR-049)
  MemoryGraphConfig, GraphNode, GraphEdge,
  GraphStats, RankedResult, EdgeType,

  // Agent Scope (ADR-049)
  AgentMemoryScope, AgentScopedConfig,
  TransferOptions, TransferResult,
} from '@claude-flow/memory';

依赖关系

  • agentdb ^3.0.0-alpha.14 —矢量数据库引擎
  • sql.js – SQLite 驱动程序通过 WASM( 总是可用; 不需要本地建筑)
  • better-sqlite3 —— 说 可选 本地 SQLite 驱动程序用于更高的吞吐量 。 套件没有它(sql.js fallback)会工作,所以安装在节点24/26上成功,即使本土建筑无法编译(# 1867 (英语)(中文(简体) )
  • @claude-flow/embeddings —— 说 可选 用于语义搜索. 缺席或失败时, search() 自动倒回 FTS5 关键字( 见 优雅的检索(中文(简体) )
  • @claude-flow/neural —— 说 可选 同伴对自学的依赖性(在无法学习时出现回落)

许可证

麻省理工学院

版本与发布记录

@claude-flow/memory 共发布 42 个版本,首次发布于 2026/01/07;过去 12 个月发布了 42 个版本。

版本发布日期距今
3.3.0latest2026/11/10今天
3.2.62026/11/09今天
3.2.52026/11/09今天
3.2.42026/11/09今天
3.2.32026/11/064 天前
3.2.22026/11/028 天前

其他发布通道:v3alpha → 3.0.6,alpha → 3.0.6。

关于 @claude-flow/memory 的常见问题

@claude-flow/memory 是什么?

内存模块 - AgentDB统一,HNSW索引,向量搜索,混合 SQLite+AgentDB后端(ADR-009)

如何安装 @claude-flow/memory?

在项目目录运行 npm install @claude-flow/memory,或使用 pnpm add / yarn add / bun add。

@claude-flow/memory 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@claude-flow/memory 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@claude-flow/memory 可以商用吗?

@claude-flow/memory 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@claude-flow/memory 的下载量有多少?

根据 npm 官方下载统计,@claude-flow/memory 在 2026/10/10 – 2026/11/08 这 30 天内被下载 364,298 次,日均约 12,143 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@claude-flow/memory 还在维护吗?

最新版本 3.3.0 发布于 2026/11/10(今天);至今共发布 42 个版本,其中过去 12 个月发布了 42 个;首次发布于 2026/01/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。