mcpField
A
agent-memory-system

agent-memory-system

github.com/adaptationioエージェントワークフロー46 回インストール
リポジトリ

agent-memory-system について

agent-memory-systemは、AIエージェント向けの永続メモリアーキテクチャです。セッションをまたぐ情報保持や経験からの学習を支援し、エピソード、手続き、意味、短期の4種類に記憶を分けます。

主な機能

  1. 014種類の独立したメモリ
  2. 02過去の出来事や判断の想起
  3. 03学習したスキルの抽出と更新
  4. 04事実と関係の整理
  5. 05現在のセッション情報の保持

活用シーン

  1. 01複数セッション間でのコンテキスト維持
  2. 02過去のタスクで得たパターンの再利用
  3. 03ユーザー設定の追跡
  4. 04長期プロジェクトの判断の記録

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/adaptationio/skrillz --skill agent-memory-system

インストール後、Claude Code で/agent-memory-systemを入力して読み込まれたか確認します。

詳細

エージェントメモリシステム

概要

agent-memory-system は、AI エージェントがセッションをまたいで記憶し、経験から学び、長期的な知識を構築できるようにする永続メモリアーキテクチャを提供します。

目的:永続メモリを通じて、真の継続的な改善を可能にします

パターン:機能ベース(独立した操作を備えた4種類のメモリ)

主な革新点:多層メモリアーキテクチャ(エピソード記憶、手続き記憶、意味記憶、短期記憶)により、エージェントが時間をかけて学習し、適応できるようにします

基本原則:

  1. エピソード記憶 - 過去の具体的な出来事や判断を記憶します
  2. 手続き記憶 - 時間をかけてスキルを学び、向上させます
  3. 意味記憶 - 事実や関係性のナレッジグラフを構築します
  4. 短期記憶 - アクティブな作業コンテキストです

使用する場面

次のような場合に agent-memory-system を使用します。

  • 経験から学習するエージェントを構築する
  • 複数のセッションにわたってコンテキストを保持する
  • パーソナライズ(ユーザーの好みを記憶する)を実装する
  • 適応型システム(時間をかけて改善する)を作成する
  • 長期間にわたるプロジェクト(数週間前の判断を記憶する)
  • スキルの改善状況を追跡する(うまくいくこと、いかないこと)

前提条件

必須
  • ファイルシステムへのアクセス(ファイルベースのメモリ用)
  • JSON のサポート(構造化されたメモリの保存用)
任意
  • エピソード記憶用のベクトルデータベース(Pinecone、Weaviate、Chroma)
  • 意味記憶用のグラフデータベース(Neo4j)
  • 高速な短期記憶用の Redis
理解しておくこと
  • メモリの種類と、それぞれを使用する場面
  • トレードオフ(ファイルベースとデータベース)

メモリの種類

メモリタイプ1:エピソード記憶

内容:過去の具体的な出来事、判断、その結果を記憶します

使用場面:「前回 X を試したとき、何が起きたか」を思い出す必要がある場合

保存先:ベクトルデータベース(類似性検索)またはタイムスタンプ付き 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. 結果からの学習:成功したエピソードからパターンを抽出します

クエリ:

# Find similar past implementations
recall-episode --similar "implementing OAuth" --top 5

# Find all authentication-related episodes
recall-episode --tag authentication

# Learn from failures
recall-episode --filter "quality_score < 80" --analyze

利点:

  • 同じ失敗を繰り返さない
  • 成功したパターンを適用する
  • 見積もりの精度を高める
  • 意思決定を迅速化する

保存先:

  • シンプル:.memory/episodic/YYYY-MM-DD/ 内の JSON ファイル
  • 高度:意味検索用のベクトル DB

メモリタイプ2:手続き記憶

内容:学習したスキル、成功したパターン、自動化ルール

使用場面:「通常、X はどのように行うか」や「Y にはどのような標準的な方法を使うか」と確認する場合

保存先:構造化ファイルまたはコードパターン

構造:

{
  "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. スキルの改善:新たな経験に基づいて更新します

クエリ:

# Get learned pattern for authentication
get-skill "authentication implementation"

# Find most successful patterns
list-skills --sort-by success_rate --top 10

# Update skill with new learning
update-skill "authentication" --episode ep_20250125_1400

利点:

  • 成功したパターンを体系化する
  • 時間をかけてパターンを改善する
  • チーム内で知識を共有する
  • 実証済みのパターンを適用し、実装を迅速化する

保存先:.memory/procedural/skills/


メモリタイプ3:意味記憶

内容:事実、関係性、概念のナレッジグラフ

使用場面:「X と Y の関係は何か」や「Z について何がわかっているか」と確認する場合

保存先:グラフデータベース(Neo4j)または関係性を含む 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. 知識の推論:関係性から新しい事実を導き出します

クエリ:

# What do we know about OAuth?
query-knowledge "oauth"

# What are alternatives to password auth?
query-knowledge "password_auth" --relationship alternative_to

# Find all authentication methods
query-knowledge --type authentication_method

利点:

  • 組織の知識を構築する
  • 概念間の関係性を理解する
  • 情報に基づいて判断する
  • 知識の喪失を防ぐ

保存先:

  • シンプル:.memory/semantic/ 内の JSON ファイル
  • 高度:Neo4j グラフデータベース

メモリータイプ 4:短期メモリー

内容:アクティブな作業コンテキスト、現在のセッション状態

使用する場面:現在の会話中に記憶しておく必要がある場合

ストレージ:RAM または Redis(高速アクセス)

構造:

{
  "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 内のファイル


主な操作

操作 1:メモリーの保存

目的:適切なメモリータイプに情報を保存します

手順:

// 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
  }
});

出力:

  • メモリーがストレージに保存されます
  • 検索できるようにインデックス化されます
  • タイムスタンプが付与されます

操作 2:メモリーの想起

目的:現在のタスクに関連するメモリーを取得します

手順:

// 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'
});

出力:

  • 関連するメモリーが取得されます
  • 関連性/新しさに基づいて順位付けされます
  • 現在の判断に活用できる状態になります

操作 3:経験から学習

目的:パターンを抽出し、手続き的メモリーを更新します

手順:

  1. エピソードを分析する:

    // 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. 手続き的メモリーを更新する:

    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)
    });
    

出力:

  • 学習したパターンがコード化されます
  • 手続き的メモリーが更新されます
  • 今後の判断に経験が反映されます

操作 4:パーソナライズ

目的:ユーザーの好みやパターンに合わせて調整します

手順:

// 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?"
}

出力:

  • パーソナライズされた提案
  • 繰り返しの質問を削減
  • ワークフローの高速化

セッション間の統合

セッション開始時の統合

フック:SessionStart フックがメモリーを読み込みます

#!/bin/bash
# .claude/hooks/load-memory.sh (SessionStart)

echo "📚 Loading agent memory..."

# 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

# Load recent episodic memories (last 7 days)
RECENT_EPISODES=$(find .memory/episodic/ -name "*.json" -mtime -7 | wc -l)
echo "  └─ Recent episodes: $RECENT_EPISODES"

# Load active skills
LEARNED_SKILLS=$(ls .memory/procedural/skills/ | wc -l)
echo "  └─ Learned skills: $LEARNED_SKILLS"

echo "✅ Memory loaded"

セッション終了時の統合

フック:SessionEnd フックがメモリーを保存します

#!/bin/bash
# .claude/hooks/save-memory.sh (SessionEnd)

echo "💾 Saving agent memory..."

# 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

# Extract learnings if quality was high
# (Automated learning extraction)

echo "✅ Memory saved"

メモリーアーキテクチャ

ファイルベースのメモリー(シンプル)

構造:

.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)

メリット:

  • シンプル(データベースが不要)
  • バージョン管理が可能
  • 人が読みやすい
  • バックアップが簡単

制限事項:

  • セマンティック検索ができません
  • 手動でインデックスを作成する必要があります
  • 大規模なデータセットでは処理が遅くなります

データベースを利用したメモリー(高度)

エピソード(ベクトルデータベース):

  • Pinecone:マネージド、高速、高価
  • Weaviate:セルフホスト可能、柔軟
  • Chroma:軽量、プロトタイプに最適

セマンティック(グラフデータベース):

  • Neo4j:業界標準
  • AgensGraph:PostgreSQL ベース
  • NetworkX:Python ライブラリ(シンプルなグラフ)

短期(キャッシュ):

  • Redis:高速、一時的
  • Memcached:シンプルなキャッシュ

メリット:

  • セマンティック検索(類似性、関係性)
  • 大規模環境でも高速なクエリ
  • 高度な機能

制限事項:

  • インフラストラクチャが複雑
  • コスト(ホスト型ソリューション)
  • デプロイのオーバーヘッド

Multi-AI スキルとの統合

multi-ai-implementation との連携

実装前(関連するパターンを想起):

// 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`);
}

実装後(エピソードを保存):

// 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']);

multi-ai-planning との連携

計画前:

// 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`);
}

計画後:

// 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
    }
  }
});

multi-ai-verification との連携

検証前:

// 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);

検証後:

// 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'
    }
  });
}

メモリー管理

メモリーのライフサイクル

作成(自動):

  • 各スキルの完了後
  • 重要な判断の後
  • 検証の完了時
  • 失敗時(学習のため)

保持(設定可能):

  • エピソード:90 日間(重要なエピソードは延長できます)
  • 手続き的メモリー:無期限(パターンは保持されます)
  • セマンティックメモリー:無期限(事実は保持されます)
  • 短期メモリー:セッション終了まで+バックアップ 1 件

クリーンアップ(自動):

  • 古いエピソードメモリー:アーカイブまたは削除
  • 使用されていない手続き的パターン:非アクティブとしてマーク
  • 信頼度の低い事実:非推奨に設定
  • 短期メモリー:セッション終了後にクリア
メモリーの統合

夜間プロセス:

#!/bin/bash
# Run nightly (cron job)

# 1. Consolidate recent episodes into patterns
node .memory/scripts/consolidate-episodes.js --days 7

# 2. Update procedural memory
node .memory/scripts/update-skills.js

# 3. Clean up old short-term memory
find .memory/short-term/ -name "*.json" -mtime +7 -delete

# 4. Archive old episodes
find .memory/episodic/ -name "*.json" -mtime +90 -exec mv {} .memory/archive/ \;

# 5. Update knowledge graph
node .memory/scripts/update-knowledge-graph.js

ベストプラクティス

1. 重要なイベントの後は毎回保存する

プロジェクトの終了まで待たず、継続的に保存します

2. タグを十分に付ける

タグが多いほど想起の精度が向上します(「authentication」、「security」、「oauth」、「implementation」)

3. エピソードにコンテキストを含める

後から判断の背景を理解できるよう、十分なコンテキストを保存します

4. 学びを明示的に抽出する

起きたことを保存するだけでなく、何を学んだかも記録します

5. メモリを定期的に見直す

月次レビュー:どのようなパターンが現れたか、何が改善したか、何を変更すべきか

6. チームでメモリを共有する

セマンティックメモリと手続き的メモリはチームの資産です


付録 A:フックとのメモリ統合

SessionStart:メモリを読み込む
{
  "event": "SessionStart",
  "description": "Load agent memory on session start",
  "handler": {
    "command": ".claude/hooks/load-memory.sh"
  }
}
SessionEnd:メモリを保存する
{
  "event": "SessionEnd",
  "description": "Save agent memory on session end",
  "handler": {
    "command": ".claude/hooks/save-memory.sh"
  }
}
PostToolUse:判断を追跡する
{
  "event": "PostToolUse",
  "tools": ["Write"],
  "description": "Track significant code changes",
  "handler": {
    "command": ".claude/hooks/track-change.sh \"$FILE\" \"$TOOL\""
  }
}

付録 B:ベクトル DB との統合

シンプルなベクトル検索(ファイルベース)
# Calculate similarity using embeddings
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

# Get embedding for current query
query_embedding = get_embedding(current_objective)

# Load all episode embeddings
episodes = load_all_episodes()

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

# Get top 5 most similar
top_indices = np.argsort(similarities)[-5:][::-1]
similar_episodes = [episodes[i] for i in top_indices]
高度なベクトル DB(Pinecone)
import pinecone

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

# Store episode
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']]

クイックリファレンス

4 種類のメモリ
種類保存先検索方法保持期間用途
エピソードベクトル DB またはタイムスタンプ付き JSON類似度検索90 日「X を実行したとき、何が起きたか?」
手続き的JSON ファイル名前/タグ検索無期限「Y は通常どのように実行するか?」
セマンティックグラフ DB または JSON概念クエリ無期限「Z について何を知っているか?」
短期RAM/Redis または JSON直接アクセスセッションのみ「現在のコンテキストは何か?」
メモリ操作
操作目的複雑さ時間
保存メモリを保存する低即時
想起メモリを取得する低~中ファイルは <1s、DB は <100ms
学習パターンを抽出する中数分
パーソナライズユーザーに適応する中継続的

agent-memory-system はセッションをまたいだ永続的なメモリを実現し、エージェントが経験から学び、時間とともに改善し、組織の知識を蓄積できるようにします。これは真に適応的な AI システムの基盤です。

統合例については examples/ を参照してください。データベースのセットアップについては付録 B を参照してください。

コメント