agent-memory-system

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agent Memory System

Agent 内存系统

Overview

概述

agent-memory-system provides persistent memory architecture enabling AI agents to remember across sessions, learn from experience, and build long-term knowledge.
Purpose: Enable true continuous improvement through persistent memory
Pattern: Capabilities-based (4 memory types with independent operations)
Key Innovation: Multi-layered memory architecture (episodic, procedural, semantic, short-term) enabling agents to learn and adapt over time
Core Principles:
  1. Episodic Memory - Remember specific past events and decisions
  2. Procedural Memory - Learn and improve skills over time
  3. Semantic Memory - Build knowledge graphs of facts and relationships
  4. Short-Term Memory - Active working context

agent-memory-system 提供持久化内存架构,让AI Agent能够跨会话留存记忆、从经验中学习并构建长期知识体系。
核心目标:通过持久化内存实现真正的持续改进
设计模式:基于能力分层(4种独立运作的记忆类型)
关键创新:多层级内存架构(情景、过程、语义、短期),支持Agent随时间推移不断学习与适应
核心原则:
  1. 情景记忆 - 记住特定的过往事件与决策
  2. 过程记忆 - 随时间积累并优化技能
  3. 语义记忆 - 构建事实与关系的知识图谱
  4. 短期记忆 - 活跃的工作上下文

When to Use

适用场景

Use agent-memory-system when:
  • Building agents that learn from experience
  • Preserving context across multiple sessions
  • Implementing personalization (remember user preferences)
  • Creating adaptive systems (improve over time)
  • Long-running projects (remember decisions made weeks ago)
  • Skill improvement tracking (what works, what doesn't)

在以下场景中使用agent-memory-system:
  • 构建能从经验中学习的Agent
  • 跨多个会话保留上下文信息
  • 实现个性化功能(记住用户偏好)
  • 创建自适应系统(随时间不断优化)
  • 长期运行项目(记住数周前做出的决策)
  • 技能改进追踪(记录有效与无效的方法)

Prerequisites

前置条件

Required

必需条件

  • File system access (for file-based memory)
  • JSON support (for structured memory storage)
  • 文件系统访问权限(用于基于文件的内存存储)
  • JSON支持(用于结构化内存存储)

Optional

可选条件

  • Vector database (Pinecone, Weaviate, Chroma) for episodic memory
  • Graph database (Neo4j) for semantic memory
  • Redis for fast short-term memory
  • 向量数据库(Pinecone、Weaviate、Chroma)用于情景记忆
  • 图数据库(Neo4j)用于语义记忆
  • Redis用于高速短期记忆

Understanding

知识储备

  • Memory types and when to use each
  • Trade-offs (file-based vs. database)

  • 各类记忆类型的适用场景
  • 存储方案的权衡(基于文件 vs 数据库)

Memory Types

记忆类型

Memory Type 1: Episodic Memory

记忆类型1:情景记忆

What: Remembers specific past events, decisions, and their outcomes
Use When: Need to recall "What happened last time we tried X?"
Storage: Vector database (similarity search) or timestamped JSON files
Structure:
json
{
  "episode_id": "ep_20250115_1530",
  "timestamp": "2025-01-15T15:30:00Z",
  "event_type": "implementation",
  "description": "Implemented user authentication with OAuth",
  "context": {
    "objective": "Add OAuth to existing password auth",
    "approach": "Expand-migrate-contract pattern",
    "decisions": [
      {
        "question": "JWT vs Sessions?",
        "choice": "JWT",
        "rationale": "Stateless, scales better"
      }
    ],
    "outcomes": {
      "quality_score": 94,
      "test_coverage": 89,
      "time_actual": "6.5 hours",
      "time_estimated": "5 hours"
    },
    "learnings": [
      "OAuth token refresh needs explicit testing",
      "Expand-migrate-contract took longer than estimated"
    ]
  },
  "tags": ["authentication", "oauth", "implementation"],
  "embedding": [0.123, -0.456, ...] // For similarity search
}
Operations:
  1. Store Episode: Save event after completion
  2. Recall Similar: Find similar past episodes (vector similarity)
  3. Query by Tag: Retrieve all episodes with specific tags
  4. Learn from Outcomes: Extract patterns from successful episodes
Queries:
bash
undefined
定义:记录特定的过往事件、决策及其结果
适用场景:需要回忆“上次尝试X时发生了什么?”
存储方式:向量数据库(相似度检索)或带时间戳的JSON文件
数据结构:
json
{
  "episode_id": "ep_20250115_1530",
  "timestamp": "2025-01-15T15:30:00Z",
  "event_type": "implementation",
  "description": "Implemented user authentication with OAuth",
  "context": {
    "objective": "Add OAuth to existing password auth",
    "approach": "Expand-migrate-contract pattern",
    "decisions": [
      {
        "question": "JWT vs Sessions?",
        "choice": "JWT",
        "rationale": "Stateless, scales better"
      }
    ],
    "outcomes": {
      "quality_score": 94,
      "test_coverage": 89,
      "time_actual": "6.5 hours",
      "time_estimated": "5 hours"
    },
    "learnings": [
      "OAuth token refresh needs explicit testing",
      "Expand-migrate-contract took longer than estimated"
    ]
  },
  "tags": ["authentication", "oauth", "implementation"],
  "embedding": [0.123, -0.456, ...] // For similarity search
}
核心操作:
  1. 存储事件:事件完成后保存记录
  2. 召回相似事件:查找过往相似事件(向量相似度匹配)
  3. 按标签查询:检索带特定标签的所有事件
  4. 从结果中学习:从成功事件中提取模式
查询示例:
bash
undefined

Find similar past implementations

查找相似的过往实现案例

recall-episode --similar "implementing OAuth" --top 5
recall-episode --similar "implementing OAuth" --top 5

Find all authentication-related episodes

查找所有与认证相关的事件

recall-episode --tag authentication
recall-episode --tag authentication

Learn from failures

从失败案例中学习

recall-episode --filter "quality_score < 80" --analyze

**Benefits**:
- Avoid repeating mistakes
- Apply successful patterns
- Improve estimation accuracy
- Faster decision-making

**Storage**:
- **Simple**: JSON files in `.memory/episodic/YYYY-MM-DD/`
- **Advanced**: Vector DB for semantic search

---
recall-episode --filter "quality_score < 80" --analyze

**优势**:
- 避免重复犯错
- 复用成功模式
- 提高估算准确性
- 加快决策速度

**存储方案**:
- **基础版**:JSON文件存储在 `.memory/episodic/YYYY-MM-DD/`
- **进阶版**:向量数据库用于语义检索

---

Memory Type 2: Procedural Memory

记忆类型2:过程记忆

What: Learned skills, successful patterns, automation rules
Use When: "How do we usually do X?" or "What's our standard approach for Y?"
Storage: Structured files or code patterns
Structure:
json
{
  "skill_id": "implement_authentication",
  "skill_name": "Implementing Authentication Systems",
  "learned_from": [
    "ep_20250115_1530",
    "ep_20250120_1045",
    "ep_20250125_1400"
  ],
  "pattern": {
    "approach": "Expand-migrate-contract",
    "steps": [
      "1. Add new auth alongside existing",
      "2. Dual-write period (both methods work)",
      "3. Migrate users gradually",
      "4. Deprecate old auth"
    ],
    "pitfalls": [
      "Always test token refresh explicitly",
      "Plan for 20% longer than estimated (migrations complex)"
    ],
    "success_criteria": {
      "quality_score": ">= 90",
      "test_coverage": ">= 85",
      "backward_compatible": true
    }
  },
  "usage_count": 3,
  "success_rate": 1.0,
  "avg_quality_score": 93.3,
  "avg_time_hours": 6.2,
  "last_used": "2025-01-25T14:00:00Z"
}
Operations:
  1. Extract Pattern: Learn pattern from successful episodes
  2. Store Skill: Save learned procedural knowledge
  3. Apply Skill: Use learned pattern for new task
  4. Improve Skill: Update based on new experiences
Queries:
bash
undefined
定义:已习得的技能、成功模式、自动化规则
适用场景:“我们通常如何做X?”或“处理Y的标准方法是什么?”
存储方式:结构化文件或代码模式
数据结构:
json
{
  "skill_id": "implement_authentication",
  "skill_name": "Implementing Authentication Systems",
  "learned_from": [
    "ep_20250115_1530",
    "ep_20250120_1045",
    "ep_20250125_1400"
  ],
  "pattern": {
    "approach": "Expand-migrate-contract",
    "steps": [
      "1. Add new auth alongside existing",
      "2. Dual-write period (both methods work)",
      "3. Migrate users gradually",
      "4. Deprecate old auth"
    ],
    "pitfalls": [
      "Always test token refresh explicitly",
      "Plan for 20% longer than estimated (migrations complex)"
    ],
    "success_criteria": {
      "quality_score": ">= 90",
      "test_coverage": ">= 85",
      "backward_compatible": true
    }
  },
  "usage_count": 3,
  "success_rate": 1.0,
  "avg_quality_score": 93.3,
  "avg_time_hours": 6.2,
  "last_used": "2025-01-25T14:00:00Z"
}
核心操作:
  1. 提取模式:从成功事件中提炼模式
  2. 存储技能:保存已习得的过程性知识
  3. 应用技能:将已学模式用于新任务
  4. 优化技能:基于新经验更新技能
查询示例:
bash
undefined

Get learned pattern for authentication

获取认证实现的已学模式

get-skill "authentication implementation"
get-skill "authentication implementation"

Find most successful patterns

查找成功率最高的模式

list-skills --sort-by success_rate --top 10
list-skills --sort-by success_rate --top 10

Update skill with new learning

用新经验更新技能

update-skill "authentication" --episode ep_20250125_1400

**Benefits**:
- Codify successful patterns
- Improve patterns over time
- Share knowledge across team
- Faster implementation (apply proven patterns)

**Storage**: `.memory/procedural/skills/`

---
update-skill "authentication" --episode ep_20250125_1400

**优势**:
- 固化成功模式
- 随时间优化模式
- 跨团队共享知识
- 加快实现速度(应用已验证的模式)

**存储方案**:`.memory/procedural/skills/`

---

Memory Type 3: Semantic Memory

记忆类型3:语义记忆

What: Facts, relationships, knowledge graph of concepts
Use When: "What's the relationship between X and Y?" or "What do we know about Z?"
Storage: Graph database (Neo4j) or JSON with relationships
Structure:
json
{
  "concepts": [
    {
      "id": "oauth",
      "type": "technology",
      "description": "OAuth 2.0 authorization framework",
      "properties": {
        "security_level": "high",
        "complexity": "medium",
        "browser_required": true
      },
      "relationships": [
        {
          "type": "used_by",
          "target": "user_authentication",
          "weight": 0.95
        },
        {
          "type": "requires",
          "target": "jwt",
          "weight": 0.85
        },
        {
          "type": "alternative_to",
          "target": "password_auth",
          "weight": 0.7
        }
      ]
    }
  ],
  "facts": [
    {
      "subject": "oauth",
      "predicate": "supports",
      "object": "multiple_providers",
      "confidence": 1.0,
      "source": "ep_20250115_1530"
    }
  ]
}
Operations:
  1. Store Fact: Add new knowledge
  2. Query Knowledge: Retrieve facts about concepts
  3. Find Relationships: Navigate knowledge graph
  4. Infer Knowledge: Deduce new facts from relationships
Queries:
bash
undefined
定义:事实、关系、概念的知识图谱
适用场景:“X和Y之间的关系是什么?”或“我们对Z了解多少?”
存储方式:图数据库(Neo4j)或带关系的JSON
数据结构:
json
{
  "concepts": [
    {
      "id": "oauth",
      "type": "technology",
      "description": "OAuth 2.0 authorization framework",
      "properties": {
        "security_level": "high",
        "complexity": "medium",
        "browser_required": true
      },
      "relationships": [
        {
          "type": "used_by",
          "target": "user_authentication",
          "weight": 0.95
        },
        {
          "type": "requires",
          "target": "jwt",
          "weight": 0.85
        },
        {
          "type": "alternative_to",
          "target": "password_auth",
          "weight": 0.7
        }
      ]
    }
  ],
  "facts": [
    {
      "subject": "oauth",
      "predicate": "supports",
      "object": "multiple_providers",
      "confidence": 1.0,
      "source": "ep_20250115_1530"
    }
  ]
}
核心操作:
  1. 存储事实:添加新知识
  2. 查询知识:检索关于概念的事实
  3. 查找关系:遍历知识图谱
  4. 推断知识:从现有关系中推导新事实
查询示例:
bash
undefined

What do we know about OAuth?

我们对OAuth有哪些了解?

query-knowledge "oauth"
query-knowledge "oauth"

What are alternatives to password auth?

密码认证的替代方案有哪些?

query-knowledge "password_auth" --relationship alternative_to
query-knowledge "password_auth" --relationship alternative_to

Find all authentication methods

查找所有认证方法

query-knowledge --type authentication_method

**Benefits**:
- Build institutional knowledge
- Understand concept relationships
- Make informed decisions
- Avoid knowledge loss

**Storage**:
- **Simple**: JSON files in `.memory/semantic/`
- **Advanced**: Neo4j graph database

---
query-knowledge --type authentication_method

**优势**:
- 构建机构知识
- 理解概念间的关系
- 做出明智决策
- 避免知识流失

**存储方案**:
- **基础版**:JSON文件存储在 `.memory/semantic/`
- **进阶版**:Neo4j图数据库

---

Memory Type 4: Short-Term Memory

记忆类型4:短期记忆

What: Active working context, current session state
Use When: Need to remember within current conversation
Storage: RAM or Redis (fast access)
Structure:
json
{
  "session_id": "session_20250126_1200",
  "started_at": "2025-01-26T12:00:00Z",
  "current_task": "Implementing user authentication",
  "context": {
    "files_read": [
      "src/auth/login.ts",
      "src/auth/tokens.ts"
    ],
    "decisions_made": [
      {"what": "Use JWT", "why": "Stateless scaling"}
    ],
    "next_steps": [
      "Implement token refresh",
      "Add rate limiting"
    ]
  },
  "temporary_data": {
    "research_findings": "...",
    "plan_summary": "..."
  }
}
Operations:
  1. Set Context: Store current working data
  2. Get Context: Retrieve active context
  3. Update Context: Modify current state
  4. Clear Context: Reset working memory
Benefits:
  • Fast access to current state
  • No context window pollution
  • Efficient session management
Storage: File in
.memory/short-term/current-session.json

定义:活跃的工作上下文、当前会话状态
适用场景:需要在当前对话中保留信息
存储方式:RAM或Redis(高速访问)
数据结构:
json
{
  "session_id": "session_20250126_1200",
  "started_at": "2025-01-26T12:00:00Z",
  "current_task": "Implementing user authentication",
  "context": {
    "files_read": [
      "src/auth/login.ts",
      "src/auth/tokens.ts"
    ],
    "decisions_made": [
      {"what": "Use JWT", "why": "Stateless scaling"}
    ],
    "next_steps": [
      "Implement token refresh",
      "Add rate limiting"
    ]
  },
  "temporary_data": {
    "research_findings": "...",
    "plan_summary": "..."
  }
}
核心操作:
  1. 设置上下文:存储当前工作数据
  2. 获取上下文:检索活跃上下文
  3. 更新上下文:修改当前状态
  4. 清除上下文:重置工作内存
优势:
  • 快速访问当前状态
  • 避免上下文窗口污染
  • 高效的会话管理
存储方案:文件存储在
.memory/short-term/current-session.json

Core Operations

核心操作

Operation 1: Store Memory

操作1:存储记忆

Purpose: Save information to appropriate memory type
Process:
typescript
// Store episodic memory
await storeMemory({
  type: 'episodic',
  event: {
    description: 'Implemented OAuth authentication',
    decisions: [...],
    outcomes: {...},
    learnings: [...]
  },
  tags: ['authentication', 'oauth', 'implementation']
});

// Store procedural memory (learned pattern)
await storeMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication',
  pattern: {
    approach: 'Expand-migrate-contract',
    steps: [...],
    pitfalls: [...]
  }
});

// Store semantic memory (fact)
await storeMemory({
  type: 'semantic',
  fact: {
    subject: 'oauth',
    predicate: 'requires',
    object: 'jwt',
    confidence: 0.95
  }
});
Outputs:
  • Memory persisted to storage
  • Indexed for retrieval
  • Timestamped

目标:将信息保存到合适的记忆类型中
示例代码:
typescript
// 存储情景记忆
await storeMemory({
  type: 'episodic',
  event: {
    description: 'Implemented OAuth authentication',
    decisions: [...],
    outcomes: {...},
    learnings: [...]
  },
  tags: ['authentication', 'oauth', 'implementation']
});

// 存储过程记忆(已学模式)
await storeMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication',
  pattern: {
    approach: 'Expand-migrate-contract',
    steps: [...],
    pitfalls: [...]
  }
});

// 存储语义记忆(事实)
await storeMemory({
  type: 'semantic',
  fact: {
    subject: 'oauth',
    predicate: 'requires',
    object: 'jwt',
    confidence: 0.95
  }
});
输出:
  • 记忆已持久化到存储系统
  • 已建立索引以便检索
  • 已添加时间戳

Operation 2: Recall Memory

操作2:召回记忆

Purpose: Retrieve relevant memories for current task
Process:
typescript
// Recall similar episodes
const similarEpisodes = await recallMemory({
  type: 'episodic',
  query: 'implementing authentication',
  limit: 5
});

// Recall learned patterns
const authPattern = await recallMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication'
});

// Query knowledge
const oauthFacts = await recallMemory({
  type: 'semantic',
  concept: 'oauth'
});
Outputs:
  • Relevant memories retrieved
  • Ranked by relevance/recency
  • Ready to inform current decisions

目标:为当前任务检索相关记忆
示例代码:
typescript
// 召回相似事件
const similarEpisodes = await recallMemory({
  type: 'episodic',
  query: 'implementing authentication',
  limit: 5
});

// 召回已学模式
const authPattern = await recallMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication'
});

// 查询知识
const oauthFacts = await recallMemory({
  type: 'semantic',
  concept: 'oauth'
});
输出:
  • 已检索到相关记忆
  • 按相关性/时效性排序
  • 可直接用于指导当前决策

Operation 3: Learn from Experience

操作3:从经验中学习

Purpose: Extract patterns and update procedural memory
Process:
  1. Analyze Episodes:
    typescript
    // Get all authentication implementations
    const authEpisodes = await recallMemory({
      type: 'episodic',
      tags: ['authentication', 'implementation']
    });
    
    // Extract patterns
    const patterns = analyzePatterns(authEpisodes);
    // - Approach used: expand-migrate-contract (3/3 times)
    // - Avg quality score: 93.3
    // - Common pitfall: Token refresh testing (3/3 missed initially)
  2. Update Procedural Memory:
    typescript
    await storeMemory({
      type: 'procedural',
      skillName: 'Implementing Authentication',
      pattern: {
        approach: 'expand-migrate-contract', // Learned from all 3 episodes
        common_pitfall: 'Always test token refresh explicitly', // Learned
        quality_target: '>= 93', // Based on historical avg
        time_estimate: '6-7 hours' // Based on historical data
      },
      learnedFrom: authEpisodes.map(ep => ep.id),
      confidence: 0.95 // High (based on 3 episodes)
    });
Outputs:
  • Learned patterns codified
  • Procedural memory updated
  • Future decisions informed by experience

目标:提取模式并更新过程记忆
示例流程:
  1. 分析事件:
    typescript
    // 获取所有认证实现事件
    const authEpisodes = await recallMemory({
      type: 'episodic',
      tags: ['authentication', 'implementation']
    });
    
    // 提取模式
    const patterns = analyzePatterns(authEpisodes);
    // - 使用的方法:expand-migrate-contract(3/3次)
    // - 平均质量得分:93.3
    // - 常见陷阱:Token刷新测试(3/3次最初都遗漏了)
  2. 更新过程记忆:
    typescript
    await storeMemory({
      type: 'procedural',
      skillName: 'Implementing Authentication',
      pattern: {
        approach: 'expand-migrate-contract', // 从所有3个事件中习得
        common_pitfall: 'Always test token refresh explicitly', // 已习得
        quality_target: '>= 93', // 基于历史平均值
        time_estimate: '6-7 hours' // 基于历史数据
      },
      learnedFrom: authEpisodes.map(ep => ep.id),
      confidence: 0.95 // 高置信度(基于3个事件)
    });
输出:
  • 已固化已学模式
  • 已更新过程记忆
  • 未来决策将基于经验

Operation 4: Personalize

操作4:个性化

Purpose: Adapt to user preferences and patterns
Process:
typescript
// Track user preferences
const preferences = await recall Memory({
  type: 'semantic',
  concept: 'user_preferences'
});

// Learn from usage patterns
const userPatterns = {
  preferred_approach: 'TDD', // User always uses TDD
  testing_thoroughness: 'high', // User requests >=95% coverage
  verification_level: 'all_layers', // User runs all 5 layers
  commit_style: 'conventional' // User uses conventional commits
};

// Apply personalization
if (userPatterns.preferred_approach === 'TDD') {
  // Auto-suggest TDD workflow
  // Skip asking "test-first or code-first?"
}
Outputs:
  • Personalized recommendations
  • Reduced repetitive questions
  • Faster workflows

目标:适应用户偏好与模式
示例代码:
typescript
// 追踪用户偏好
const preferences = await recall Memory({
  type: 'semantic',
  concept: 'user_preferences'
});

// 从使用模式中学习
const userPatterns = {
  preferred_approach: 'TDD', // 用户始终使用TDD
  testing_thoroughness: 'high', // 用户要求>=95%覆盖率
  verification_level: 'all_layers', // 用户运行所有5层测试
  commit_style: 'conventional' // 用户使用规范提交格式
};

// 应用个性化设置
if (userPatterns.preferred_approach === 'TDD') {
  // 自动推荐TDD工作流
  // 跳过询问“先测试还是先编码?”
}
输出:
  • 个性化推荐
  • 减少重复问题
  • 加快工作流

Cross-Session Integration

跨会话集成

Session Start Integration

会话启动集成

Hook: SessionStart hook loads memory
bash
#!/bin/bash
钩子:SessionStart钩子加载内存
bash
#!/bin/bash

.claude/hooks/load-memory.sh (SessionStart)

.claude/hooks/load-memory.sh (SessionStart)

echo "📚 Loading agent memory..."
echo "📚 加载Agent内存..."

Load short-term memory from last session

加载上一会话的短期内存

if [ -f ".memory/short-term/last-session.json" ]; then echo " └─ Previous session context available"

Claude can read this file to continue work

fi
if [ -f ".memory/short-term/last-session.json" ]; then echo " └─ 存在上一会话上下文"

Claude可读取此文件继续工作

fi

Load recent episodic memories (last 7 days)

加载近期情景记忆(过去7天)

RECENT_EPISODES=$(find .memory/episodic/ -name "*.json" -mtime -7 | wc -l) echo " └─ Recent episodes: $RECENT_EPISODES"
RECENT_EPISODES=$(find .memory/episodic/ -name "*.json" -mtime -7 | wc -l) echo " └─ 近期事件数:$RECENT_EPISODES"

Load active skills

加载已习得技能

LEARNED_SKILLS=$(ls .memory/procedural/skills/ | wc -l) echo " └─ Learned skills: $LEARNED_SKILLS"
echo "✅ Memory loaded"

---
LEARNED_SKILLS=$(ls .memory/procedural/skills/ | wc -l) echo " └─ 已习得技能数:$LEARNED_SKILLS"
echo "✅ 内存加载完成"

---

Session End Integration

会话结束集成

Hook: SessionEnd hook saves memory
bash
#!/bin/bash
钩子:SessionEnd钩子保存内存
bash
#!/bin/bash

.claude/hooks/save-memory.sh (SessionEnd)

.claude/hooks/save-memory.sh (SessionEnd)

echo "💾 Saving agent memory..."
echo "💾 保存Agent内存..."

Save current session to episodic memory

将当前会话保存到情景记忆

if [ -f ".memory/short-term/current-session.json" ]; then TIMESTAMP=$(date +%Y%m%d_%H%M%S) cp .memory/short-term/current-session.json
.memory/episodic/$(date +%Y-%m-%d)/session_$TIMESTAMP.json
echo " └─ Episode saved" fi
if [ -f ".memory/short-term/current-session.json" ]; then TIMESTAMP=$(date +%Y%m%d_%H%M%S) cp .memory/short-term/current-session.json
.memory/episodic/$(date +%Y-%m-%d)/session_$TIMESTAMP.json
echo " └─ 事件已保存" fi

Extract learnings if quality was high

如果质量得分高,则提取经验

(Automated learning extraction)

echo "✅ Memory saved"

---
#(自动学习提取)
echo "✅ 内存保存完成"

---

Memory Architecture

内存架构

File-Based Memory (Simple)

基于文件的内存(基础版)

Structure:
.memory/
├── episodic/              # Past events
│   ├── 2025-01-15/
│   │   ├── session_153000.json
│   │   └── decision_153045.json
│   └── 2025-01-16/
│       └── session_090000.json
├── procedural/            # Learned skills
│   └── skills/
│       ├── authentication_impl.json
│       ├── testing_pattern.json
│       └── verification_approach.json
├── semantic/              # Knowledge graph
│   ├── concepts.json
│   └── relationships.json
└── short-term/            # Active session
    ├── current-session.json
    └── last-session.json (backup)
Benefits:
  • Simple (no database required)
  • Version-controllable
  • Human-readable
  • Easy backup
Limitations:
  • No semantic search
  • Manual indexing needed
  • Slower for large datasets

目录结构:
.memory/
├── episodic/              # 过往事件
│   ├── 2025-01-15/
│   │   ├── session_153000.json
│   │   └── decision_153045.json
│   └── 2025-01-16/
│       └── session_090000.json
├── procedural/            # 已习得技能
│   └── skills/
│       ├── authentication_impl.json
│       ├── testing_pattern.json
│       └── verification_approach.json
├── semantic/              # 知识图谱
│   ├── concepts.json
│   └── relationships.json
└── short-term/            # 活跃会话
    ├── current-session.json
    └── last-session.json (backup)
优势:
  • 简单(无需数据库)
  • 可版本控制
  • 人类可读
  • 易于备份
局限性:
  • 无语义检索功能
  • 需要手动索引
  • 大数据集下速度较慢

Database-Backed Memory (Advanced)

基于数据库的内存(进阶版)

Episodic (Vector DB):
  • Pinecone: Managed, fast, expensive
  • Weaviate: Self-hosted, flexible
  • Chroma: Lightweight, good for prototypes
Semantic (Graph DB):
  • Neo4j: Industry standard
  • AgensGraph: PostgreSQL-based
  • NetworkX: Python library (simple graphs)
Short-Term (Cache):
  • Redis: Fast, ephemeral
  • Memcached: Simple caching
Benefits:
  • Semantic search (similarity, relationships)
  • Fast queries at scale
  • Advanced capabilities
Limitations:
  • Infrastructure complexity
  • Cost (hosted solutions)
  • Deployment overhead

情景记忆(向量数据库):
  • Pinecone:托管式、高速、付费
  • Weaviate:自托管、灵活
  • Chroma:轻量、适合原型开发
语义记忆(图数据库):
  • Neo4j:行业标准
  • AgensGraph:基于PostgreSQL
  • NetworkX:Python库(简单图)
短期记忆(缓存):
  • Redis:高速、临时存储
  • Memcached:简单缓存
优势:
  • 语义检索(相似度、关系)
  • 大规模下的快速查询
  • 高级功能
局限性:
  • 基础设施复杂度高
  • 成本(托管方案)
  • 部署开销大

Integration with Multi-AI Skills

与多AI技能的集成

With multi-ai-implementation

与multi-ai-implementation集成

Before Implementation (recall relevant patterns):
typescript
// Step 1: Explore - Check memory for similar implementations
const similarWork = await recallMemory({
  type: 'episodic',
  query: currentObjective,
  limit: 3
});

// Apply learnings
if (similarWork.length > 0) {
  console.log("📚 Found similar past work:");
  similarWork.forEach(episode => {
    console.log(`  - ${episode.description}`);
    console.log(`    Quality: ${episode.outcomes.quality_score}`);
    console.log(`    Learnings: ${episode.learnings.join(', ')}`);
  });
}

// Step 2: Plan - Use learned patterns
const authPattern = await recallMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication'
});

if (authPattern) {
  console.log("📖 Applying learned pattern:");
  console.log(`  Approach: ${authPattern.pattern.approach}`);
  console.log(`  Estimated time: ${authPattern.avg_time_hours} hours`);
}
After Implementation (save episode):
typescript
// Step 6: Commit - Save to episodic memory
await storeMemory({
  type: 'episodic',
  event: {
    description: 'Implemented user authentication',
    decisions: capturedDuringImplementation,
    outcomes: {
      quality_score: 94,
      test_coverage: 89,
      time_actual: 6.5,
      time_estimated: 5
    },
    learnings: [
      'Token refresh needs explicit testing',
      'Estimation was 30% low'
    ]
  }
});

// Extract and update patterns
await learnFromExperience(['authentication', 'implementation']);

实现前(召回相关模式):
typescript
// 步骤1:探索 - 检查内存中是否有相似实现
const similarWork = await recallMemory({
  type: 'episodic',
  query: currentObjective,
  limit: 3
});

// 应用所学经验
if (similarWork.length > 0) {
  console.log("📚 找到相似的过往工作:");
  similarWork.forEach(episode => {
    console.log(`  - ${episode.description}`);
    console.log(`    质量得分:${episode.outcomes.quality_score}`);
    console.log(`    经验总结:${episode.learnings.join(', ')}`);
  });
}

// 步骤2:规划 - 使用已学模式
const authPattern = await recallMemory({
  type: 'procedural',
  skillName: 'Implementing Authentication'
});

if (authPattern) {
  console.log("📖 应用已学模式:");
  console.log(`  方法:${authPattern.pattern.approach}`);
  console.log(`  预计时间:${authPattern.avg_time_hours} 小时`);
}
实现后(保存事件):
typescript
// 步骤6:提交 - 保存到情景记忆
await storeMemory({
  type: 'episodic',
  event: {
    description: 'Implemented user authentication',
    decisions: capturedDuringImplementation,
    outcomes: {
      quality_score: 94,
      test_coverage: 89,
      time_actual: 6.5,
      time_estimated: 5
    },
    learnings: [
      'Token刷新需要显式测试',
      '估算偏差30%'
    ]
  }
});

// 提取并更新模式
await learnFromExperience(['authentication', 'implementation']);

With multi-ai-planning

与multi-ai-planning集成

Before Planning:
typescript
// Recall similar plans
const similarPlans = await recallMemory({
  type: 'episodic',
  query: 'plan for ' + objective,
  filter: 'event_type == "planning"'
});

// Check quality of past plans
if (similarPlans.length > 0) {
  const avgQuality = average(similarPlans.map(p => p.outcomes.quality_score));
  console.log(`📊 Past similar plans averaged ${avgQuality}/100`);
}
After Planning:
typescript
// Save plan to memory
await storeMemory({
  type: 'episodic',
  event: {
    event_type: 'planning',
    description: 'Planned OAuth implementation',
    context: {
      tasks: planGenerated.tasks.length,
      quality_score: planGenerated.quality_score,
      estimated_hours: planGenerated.metadata.estimated_total_hours
    }
  }
});

规划前:
typescript
// 召回相似的规划
const similarPlans = await recallMemory({
  type: 'episodic',
  query: 'plan for ' + objective,
  filter: 'event_type == "planning"'
});

// 检查过往规划的质量
if (similarPlans.length > 0) {
  const avgQuality = average(similarPlans.map(p => p.outcomes.quality_score));
  console.log(`📊 过往相似规划的平均得分:${avgQuality}/100`);
}
规划后:
typescript
// 将规划保存到内存
await storeMemory({
  type: 'episodic',
  event: {
    event_type: 'planning',
    description: 'Planned OAuth implementation',
    context: {
      tasks: planGenerated.tasks.length,
      quality_score: planGenerated.quality_score,
      estimated_hours: planGenerated.metadata.estimated_total_hours
    }
  }
});

With multi-ai-verification

与multi-ai-verification集成

Before Verification:
typescript
// Recall common issues for this type of code
const commonIssues = await recallMemory({
  type: 'semantic',
  concept: 'authentication',
  relationship: 'common_issues'
});

// Focus verification on known problem areas
verificationFocus = commonIssues.map(issue => issue.description);
After Verification:
typescript
// Save verification results
await storeMemory({
  type: 'episodic',
  event: {
    event_type: 'verification',
    description: 'Verified OAuth implementation',
    outcomes: {
      quality_score: 92,
      layers_passed: 5,
      issues_found: 3,
      time_minutes: 85
    }
  }
});

// Update semantic memory with new facts
if (issues_found.includes('bcrypt_rounds_low')) {
  await storeMemory({
    type: 'semantic',
    fact: {
      subject: 'bcrypt',
      predicate: 'recommended_rounds',
      object: '12-14',
      confidence: 0.95,
      source: 'verification_20250126'
    }
  });
}

验证前:
typescript
// 召回此类代码的常见问题
const commonIssues = await recallMemory({
  type: 'semantic',
  concept: 'authentication',
  relationship: 'common_issues'
});

// 将验证重点放在已知问题区域
verificationFocus = commonIssues.map(issue => issue.description);
验证后:
typescript
// 保存验证结果
await storeMemory({
  type: 'episodic',
  event: {
    event_type: 'verification',
    description: 'Verified OAuth implementation',
    outcomes: {
      quality_score: 92,
      layers_passed: 5,
      issues_found: 3,
      time_minutes: 85
    }
  }
});

// 用新事实更新语义记忆
if (issues_found.includes('bcrypt_rounds_low')) {
  await storeMemory({
    type: 'semantic',
    fact: {
      subject: 'bcrypt',
      predicate: 'recommended_rounds',
      object: '12-14',
      confidence: 0.95,
      source: 'verification_20250126'
    }
  });
}

Memory Management

内存管理

Memory Lifecycle

内存生命周期

Creation (automatic):
  • After every skill completion
  • After significant decisions
  • On verification completion
  • On failure (for learning)
Retention (configurable):
  • Episodic: 90 days (can extend for important episodes)
  • Procedural: Indefinite (patterns persist)
  • Semantic: Indefinite (facts persist)
  • Short-term: Until session end + 1 backup
Cleanup (automatic):
  • Old episodic memories: archive or delete
  • Unused procedural patterns: mark inactive
  • Low-confidence facts: deprecate
  • Short-term: clear after session end
创建(自动):
  • 每次技能完成后
  • 做出重要决策后
  • 验证完成后
  • 失败后(用于学习)
保留时长(可配置):
  • 情景记忆:90天(重要事件可延长)
  • 过程记忆:永久(模式持续留存)
  • 语义记忆:永久(事实持续留存)
  • 短期记忆:会话结束后+1次备份
清理(自动):
  • 旧情景记忆:归档或删除
  • 未使用的过程模式:标记为非活跃
  • 低置信度事实:弃用
  • 短期记忆:会话结束后清除

Memory Consolidation

内存整合

Nightly Process:
bash
#!/bin/bash
夜间处理流程:
bash
#!/bin/bash

Run nightly (cron job)

夜间运行(定时任务)

1. Consolidate recent episodes into patterns

1. 将近期事件整合为模式

node .memory/scripts/consolidate-episodes.js --days 7
node .memory/scripts/consolidate-episodes.js --days 7

2. Update procedural memory

2. 更新过程记忆

node .memory/scripts/update-skills.js
node .memory/scripts/update-skills.js

3. Clean up old short-term memory

3. 清理旧短期记忆

find .memory/short-term/ -name "*.json" -mtime +7 -delete
find .memory/short-term/ -name "*.json" -mtime +7 -delete

4. Archive old episodes

4. 归档旧事件

find .memory/episodic/ -name "*.json" -mtime +90 -exec mv {} .memory/archive/ ;
find .memory/episodic/ -name "*.json" -mtime +90 -exec mv {} .memory/archive/ ;

5. Update knowledge graph

5. 更新知识图谱

node .memory/scripts/update-knowledge-graph.js

---
node .memory/scripts/update-knowledge-graph.js

---

Best Practices

最佳实践

1. Store After Every Significant Event

1. 每次重要事件后立即存储

Don't wait until end of project - save continuously
不要等到项目结束 - 持续保存

2. Tag Generously

2. 大量使用标签

More tags = better recall ("authentication", "security", "oauth", "implementation")
标签越多,召回效果越好(例如“authentication”、“security”、“oauth”、“implementation”)

3. Include Context in Episodes

3. 在事件中包含上下文

Store enough context to understand decision later
存储足够的上下文,以便日后理解决策

4. Extract Learnings Explicitly

4. 明确提取经验总结

Don't just store what happened - store what you learned
不要只存储发生了什么 - 还要存储学到了什么

5. Review Memory Periodically

5. 定期回顾内存

Monthly review: what patterns emerged, what improved, what to change
每月回顾:出现了哪些模式,哪些方面有改进,需要做出哪些改变

6. Share Memory Across Team

6. 跨团队共享内存

Semantic and procedural memory are team assets

语义和过程记忆是团队资产

Appendix A: Memory Integration with Hooks

附录A:通过钩子集成内存

SessionStart: Load Memory

SessionStart:加载内存

json
{
  "event": "SessionStart",
  "description": "Load agent memory on session start",
  "handler": {
    "command": ".claude/hooks/load-memory.sh"
  }
}
json
{
  "event": "SessionStart",
  "description": "会话启动时加载Agent内存",
  "handler": {
    "command": ".claude/hooks/load-memory.sh"
  }
}

SessionEnd: Save Memory

SessionEnd:保存内存

json
{
  "event": "SessionEnd",
  "description": "Save agent memory on session end",
  "handler": {
    "command": ".claude/hooks/save-memory.sh"
  }
}
json
{
  "event": "SessionEnd",
  "description": "会话结束时保存Agent内存",
  "handler": {
    "command": ".claude/hooks/save-memory.sh"
  }
}

PostToolUse: Track Decisions

PostToolUse:追踪决策

json
{
  "event": "PostToolUse",
  "tools": ["Write"],
  "description": "Track significant code changes",
  "handler": {
    "command": ".claude/hooks/track-change.sh \"$FILE\" \"$TOOL\""
  }
}

json
{
  "event": "PostToolUse",
  "tools": ["Write"],
  "description": "追踪重要代码变更",
  "handler": {
    "command": ".claude/hooks/track-change.sh \"$FILE\" \"$TOOL\""
  }
}

Appendix B: Vector DB Integration

附录B:向量数据库集成

Simple Vector Search (File-Based)

简单向量检索(基于文件)

python
undefined
python
undefined

Calculate similarity using embeddings

使用嵌入向量计算相似度

from sklearn.metrics.pairwise import cosine_similarity import numpy as np
from sklearn.metrics.pairwise import cosine_similarity import numpy as np

Get embedding for current query

获取当前查询的嵌入向量

query_embedding = get_embedding(current_objective)
query_embedding = get_embedding(current_objective)

Load all episode embeddings

加载所有事件的嵌入向量

episodes = load_all_episodes()
episodes = load_all_episodes()

Calculate similarities

计算相似度

similarities = cosine_similarity( [query_embedding], [ep['embedding'] for ep in episodes] )[0]
similarities = cosine_similarity( [query_embedding], [ep['embedding'] for ep in episodes] )[0]

Get top 5 most similar

获取相似度最高的5个事件

top_indices = np.argsort(similarities)[-5:][::-1] similar_episodes = [episodes[i] for i in top_indices]
undefined
top_indices = np.argsort(similarities)[-5:][::-1] similar_episodes = [episodes[i] for i in top_indices]
undefined

Advanced Vector DB (Pinecone)

进阶向量数据库(Pinecone)

python
import pinecone
python
import pinecone

Initialize

初始化

pinecone.init(api_key="...", environment="...") index = pinecone.Index("agent-memory")
pinecone.init(api_key="...", environment="...") index = pinecone.Index("agent-memory")

Store episode

存储事件

index.upsert([ ("ep_20250115_1530", episode_embedding, episode_metadata) ])
index.upsert([ ("ep_20250115_1530", episode_embedding, episode_metadata) ])

Recall similar

召回相似事件

results = index.query( query_embedding, top_k=5, include_metadata=True )
similar_episodes = [r['metadata'] for r in results['matches']]

---
results = index.query( query_embedding, top_k=5, include_metadata=True )
similar_episodes = [r['metadata'] for r in results['matches']]

---

Quick Reference

快速参考

The 4 Memory Types

4种记忆类型

TypeStorageRetrievalRetentionUse For
EpisodicVector DB or timestamped JSONSimilarity search90 days"What happened when we did X?"
ProceduralJSON filesName/tag lookupIndefinite"How do we usually do Y?"
SemanticGraph DB or JSONConcept queriesIndefinite"What do we know about Z?"
Short-TermRAM/Redis or JSONDirect accessSession only"What's the current context?"
类型存储方式检索方式保留时长适用场景
情景记忆向量数据库或带时间戳的JSON相似度检索90天“我们做X时发生了什么?”
过程记忆JSON文件名称/标签查找永久“我们通常如何做Y?”
语义记忆图数据库或JSON概念查询永久“我们对Z了解多少?”
短期记忆RAM/Redis或JSON直接访问仅会话期间“当前上下文是什么?”

Memory Operations

内存操作

OperationPurposeComplexityTime
StoreSave memoryLowInstant
RecallRetrieve memoryLow-Medium<1s file, <100ms DB
LearnExtract patternsMediumMinutes
PersonalizeAdapt to userMediumOngoing

agent-memory-system enables persistent memory across sessions, allowing agents to learn from experience, improve over time, and build institutional knowledge - the foundation for truly adaptive AI systems.
For integration examples, see examples/. For database setup, see Appendix B.
操作目标复杂度耗时
存储保存内存即时
召回检索内存低-中文件存储<1秒,数据库<100毫秒
学习提取模式数分钟
个性化适应用户持续进行

agent-memory-system 实现了跨会话的持久化内存,让Agent能够从经验中学习、随时间优化并构建机构知识——这是真正自适应AI系统的基础。
集成示例请查看 examples/ 目录。数据库设置请查看附录B。