mcpField
C
compact

compact

github.com/catlog22エージェントワークフロー2.1k119 回インストール19 週間前に更新
リポジトリ

compact について

compact は、セッションの作業記憶を復元しやすい構造化テキストにまとめ、目標、計画、ファイル、決定事項、保留作業を記録するコマンドです。MCP の core_memory ツールまたは ccw CLI に保存でき、作業完了時やセッション切り替え前に使えます。

主な機能

  1. 01セッションの目標と計画を抽出
  2. 02作業ファイルと参照ファイルを記録
  3. 03決定、制約、既知の問題を整理
  4. 04core_memory に記憶を保存
  5. 05説明、タグ、強制保存オプション

活用シーン

  1. 01作業後の進捗を保存して復元
  2. 02セッション切り替え時に文脈を保持
  3. 03デバッグ記録と次の手順を保存

MCP 対応

MCP の core_memory ツールで構造化テキストをインポートし、エクスポートによる記憶の復元にも対応します。ccw core-memory CLI も利用できます。

インストール

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

$npx skills add https://github.com/catlog22/claude-code-workflow --skill compact

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

詳細

Memory Compact コマンド(/memory:compact)

1. 概要

memory:compact コマンドは、現在のセッションの作業メモリを圧縮して、セッションの復元に最適化された構造化テキストにまとめ、重要な情報を抽出し、MCP の core_memory ツールを介して永続ストレージに保存します。

基本理念:

  • セッションの復元を最優先:作業をスムーズに再開するために必要な情報をすべて記録します
  • 再調査を最小限に抑える:重複した分析を避けるため、ファイルパス、決定事項、状態を含めます
  • 思考の過程を保持:複雑なデバッグに役立つメモや仮説を残します
  • 実行可能な状態を記録:直近の操作結果と既知の問題を記録します

2. パラメーター

  • --description:カスタムセッションの説明(任意)
    • 例:「core-memory モジュールを完成」
    • 例:「JWT の更新をデバッグ中 — メモリリークの疑い」
  • --tags:分類用のカンマ区切りタグ(任意)
  • --force:確認を省略して直接保存

3. 構造化出力形式

## Session ID
[WFS-ID if workflow session active, otherwise (none)]

## Project Root
[Absolute path to project root, e.g., D:\Claude_dms3]

## Objective
[High-level goal - the "North Star" of this session]

## Execution Plan
[CRITICAL: Embed the LATEST plan in its COMPLETE and DETAILED form]

### Source: [workflow | todo | user-stated | inferred]

<details>
<summary>Full Execution Plan (Click to expand)</summary>

[PRESERVE COMPLETE PLAN VERBATIM - DO NOT SUMMARIZE]
- ALL phases, tasks, subtasks
- ALL file paths (absolute)
- ALL dependencies and prerequisites
- ALL acceptance criteria
- ALL status markers ([x] done, [ ] pending)
- ALL notes and context

Example:
## Phase 1: Setup
- [x] Initialize project structure
  - Created D:\Claude_dms3\src\core\index.ts
  - Added dependencies: lodash, zod
- [ ] Configure TypeScript
  - Update tsconfig.json for strict mode

## Phase 2: Implementation
- [ ] Implement core API
  - Target: D:\Claude_dms3\src\api\handler.ts
  - Dependencies: Phase 1 complete
  - Acceptance: All tests pass

</details>

## Working Files (Modified)
[Absolute paths to actively modified files]
- D:\Claude_dms3\src\file1.ts (role: main implementation)
- D:\Claude_dms3\tests\file1.test.ts (role: unit tests)

## Reference Files (Read-Only)
[Absolute paths to context files - NOT modified but essential for understanding]
- D:\Claude_dms3\.claude\CLAUDE.md (role: project instructions)
- D:\Claude_dms3\src\types\index.ts (role: type definitions)
- D:\Claude_dms3\package.json (role: dependencies)

## Last Action
[Last significant action and its result/status]

## Decisions
- [Decision]: [Reasoning]
- [Decision]: [Reasoning]

## Constraints
- [User-specified limitation or preference]

## Dependencies
- [Added/changed packages or environment requirements]

## Known Issues
- [Deferred bug or edge case]

## Changes Made
- [Completed modification]

## Pending
- [Next step] or (none)

## Notes
[Unstructured thoughts, hypotheses, debugging trails]

4. フィールド定義

フィールド目的復元時の価値
Session IDワークフローセッション識別子(WFS-*)メモリを特定の状態を持つタスク実行に関連付けます
Project Rootプロジェクトディレクトリの絶対パス新しいセッションで正しいパス解決を可能にします
Objectiveセッションの最終目標より広範な機能の目標を見失わないようにします
Execution Plan任意のソースからの完全な計画(原文のまま)計画の全体像を維持し、再計画を防ぎます
Working Files現在変更中のファイル(絶対パス)作業していた場所をすぐに特定できます
Reference Files読み取り専用のコンテキストファイル(絶対パス)重要なコンテキストの再調査を不要にします
Last Action最後のツール出力/ステータス状態(成功/失敗)をすぐに把握できます
Decisionsアーキテクチャ上の選択とその理由確定済みの決定を再検討するのを防ぎます
Constraintsユーザーが指定した制限個人に合わせたコーディングスタイルを維持します
Dependenciesパッケージ/環境の変更依存関係の不足によるエラーを防ぎます
Known Issues対応を保留したバグ/エッジケース問題を忘れないようにします
Changes Made完了した変更実施内容を明確に記録します
Pending次のステップすぐに着手できる作業項目です
Notes仮説、デバッグの経緯「思考の過程」を保持します

5. 実行フロー

ステップ 1:現在のセッションを分析する

会話履歴から以下の情報を抽出します:

const sessionAnalysis = {
  sessionId: "",       // WFS-* if workflow session active, null otherwise
  projectRoot: "",     // Absolute path: D:\Claude_dms3
  objective: "",       // High-level goal (1-2 sentences)
  executionPlan: {
    source: "workflow" | "todo" | "user-stated" | "inferred",
    content: ""        // Full plan content - ALWAYS preserve COMPLETE and DETAILED form
  },
  workingFiles: [],    // {absolutePath, role} - modified files
  referenceFiles: [],  // {absolutePath, role} - read-only context files
  lastAction: "",      // Last significant action + result
  decisions: [],       // {decision, reasoning}
  constraints: [],     // User-specified limitations
  dependencies: [],    // Added/changed packages
  knownIssues: [],     // Deferred bugs
  changesMade: [],     // Completed modifications
  pending: [],         // Next steps
  notes: ""            // Unstructured thoughts
}
ステップ 2:構造化テキストを生成する
// Helper: Generate execution plan section
const generateExecutionPlan = (plan) => {
  const sourceLabels = {
    'workflow': 'workflow (IMPL_PLAN.md)',
    'todo': 'todo (TodoWrite)',
    'user-stated': 'user-stated',
    'inferred': 'inferred'
  };

  // CRITICAL: Preserve complete plan content verbatim - DO NOT summarize
  return `### Source: ${sourceLabels[plan.source] || plan.source}

<details>
<summary>Full Execution Plan (Click to expand)</summary>

${plan.content}

</details>`;
};

const structuredText = `## Session ID
${sessionAnalysis.sessionId || '(none)'}

## Project Root
${sessionAnalysis.projectRoot}

## Objective
${sessionAnalysis.objective}

## Execution Plan
${generateExecutionPlan(sessionAnalysis.executionPlan)}

## Working Files (Modified)
${sessionAnalysis.workingFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'}

## Reference Files (Read-Only)
${sessionAnalysis.referenceFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'}

## Last Action
${sessionAnalysis.lastAction}

## Decisions
${sessionAnalysis.decisions.map(d => `- ${d.decision}: ${d.reasoning}`).join('\n') || '(none)'}

## Constraints
${sessionAnalysis.constraints.map(c => `- ${c}`).join('\n') || '(none)'}

## Dependencies
${sessionAnalysis.dependencies.map(d => `- ${d}`).join('\n') || '(none)'}

## Known Issues
${sessionAnalysis.knownIssues.map(i => `- ${i}`).join('\n') || '(none)'}

## Changes Made
${sessionAnalysis.changesMade.map(c => `- ${c}`).join('\n') || '(none)'}

## Pending
${sessionAnalysis.pending.length > 0
  ? sessionAnalysis.pending.map(p => `- ${p}`).join('\n')
  : '(none)'}

## Notes
${sessionAnalysis.notes || '(none)'}`
ステップ 3:MCP を介して Core Memory にインポートする

MCP の core_memory ツールを使用して、構造化テキストを保存します:

mcp__ccw-tools__core_memory({
  operation: "import",
  text: structuredText
})

または、CLI を使用します(構造化テキストをパイプでインポート):

# Write structured text to temp file, then import
echo "$structuredText" | ccw core-memory import

# Or from a file
ccw core-memory import --file /path/to/session-memory.md

応答形式:

{
  "operation": "import",
  "id": "CMEM-YYYYMMDD-HHMMSS",
  "message": "Created memory: CMEM-YYYYMMDD-HHMMSS"
}
ステップ 4:復元 ID を報告する

インポートが成功したら、ユーザーに復元 ID を明確に表示します:

╔════════════════════════════════════════════════════════════════════════════╗
║  ✓ Session Memory Saved                                                    ║
║                                                                            ║
║  Recovery ID: CMEM-YYYYMMDD-HHMMSS                                         ║
║                                                                            ║
║  To restore: "Please import memory <ID>"                                   ║
║  (MCP: core_memory export | CLI: ccw core-memory export --id <ID>)         ║
╚════════════════════════════════════════════════════════════════════════════╝

6. 品質チェックリスト

生成する前に確認します:

  • ワークフローセッションがアクティブな場合は、Session ID(WFS-*)を記録している
  • Project Root が絶対パスである(例:D:\Claude_dms3)
  • Objective で「北極星」となる目標を明確に示している
  • Execution Plan:計画全体を要約せずに原文のまま保持している
  • Plan Source:ソースを明確に特定している(workflow | todo | user-stated | inferred)
  • Plan Details:すべてのフェーズ、タスク、ファイルパス、依存関係、ステータスマーカーを含めている
  • すべてのファイルパスが絶対パスである(相対パスではない)
  • Working Files:役割を添えて、変更したファイルを3~8個記載している
  • Reference Files:主要なコンテキストファイル(CLAUDE.md、型定義、設定ファイル)を記載している
  • Last Action に最終状態(成功/失敗)を記録している
  • Decisions に選択内容だけでなく、その理由も含めている
  • Known Issues で対応を保留したバグと、忘れられたバグを区別している
  • Notes にデバッグ時の仮説があれば保持している

7. パス解決ルール

プロジェクトルートの検出
  1. 環境から現在の作業ディレクトリを確認します
  2. プロジェクトを示すファイルやディレクトリを探します:.git/、package.json、.claude/
  3. これらの目印を含む最上位のディレクトリを使用します
絶対パスへの変換
// Convert relative to absolute
const toAbsolutePath = (relativePath, projectRoot) => {
  if (path.isAbsolute(relativePath)) return relativePath;
  return path.join(projectRoot, relativePath);
};

// Example: "src/api/auth.ts" → "D:\Claude_dms3\src\api\auth.ts"
参照ファイルのカテゴリ
カテゴリ例優先度
プロジェクト設定.claude/CLAUDE.md、package.json、tsconfig.json高
型定義src/types/*.ts、*.d.ts高
関連モジュールインターフェースを共有する親モジュール/兄弟モジュール中
テストファイル変更したコードに対応するテストファイル中
ドキュメントREADME.md、ARCHITECTURE.md低

8. 計画の検出(優先順位順)

優先度 1:ワークフローセッション(IMPL_PLAN.md)
// Check for active workflow session
const manifest = await mcp__ccw-tools__session_manager({
  operation: "list",
  location: "active"
});

if (manifest.sessions?.length > 0) {
  const session = manifest.sessions[0];
  const plan = await mcp__ccw-tools__session_manager({
    operation: "read",
    session_id: session.id,
    content_type: "plan"
  });
  sessionAnalysis.sessionId = session.id;
  sessionAnalysis.executionPlan.source = "workflow";
  sessionAnalysis.executionPlan.content = plan.content;
}
優先度 2:TodoWrite(現在のセッションのタスク)
// Extract from conversation - look for TodoWrite tool calls
// Preserve COMPLETE todo list with all details
const todos = extractTodosFromConversation();
if (todos.length > 0) {
  sessionAnalysis.executionPlan.source = "todo";
  // Format todos with full context - preserve status markers
  sessionAnalysis.executionPlan.content = todos.map(t =>
    `- [${t.status === 'completed' ? 'x' : t.status === 'in_progress' ? '>' : ' '}] ${t.content}`
  ).join('\n');
}
優先度 3:ユーザーが示した計画
// Look for explicit plan statements in user messages:
// - "Here's my plan: 1. ... 2. ... 3. ..."
// - "I want to: first..., then..., finally..."
// - Numbered or bulleted lists describing steps
const userPlan = extractUserStatedPlan();
if (userPlan) {
  sessionAnalysis.executionPlan.source = "user-stated";
  sessionAnalysis.executionPlan.content = userPlan;
}
優先度 4:推定した計画
// If no explicit plan, infer from:
// - Task description and breakdown discussion
// - Sequence of actions taken
// - Outstanding work mentioned
const inferredPlan = inferPlanFromDiscussion();
if (inferredPlan) {
  sessionAnalysis.executionPlan.source = "inferred";
  sessionAnalysis.executionPlan.content = inferredPlan;
}

9. 注意事項

  • タイミング:タスクの完了時、またはコンテキストの切り替え前に実行します
  • 頻度:独立したタスクまたはマイルストーンごとに1回
  • 復旧:新しいセッションですぐに全コンテキストを引き継いで作業を続けられます
  • ナレッジグラフ:エンティティ間の関係を自動抽出して可視化します
  • 絶対パス:異なるマシンでセッションをまたいで復旧する際に重要です

コメント