Communitygithub.com

戦略的コンパクト

任意の自動コンパクトではなく、タスクフェーズの論理的な区切りで手動コンパクトを提案し、セッションのコンテキストを効率的に維持します。

戦略的コンパクト とは?

このスキルは、Claude CodeなどのAIエージェント開発ツールにおいて、コンテキスト制限に近づいた際に、論理的なタスク境界(例:調査→計画→実装→テスト)で手動の`/compact`を提案することで、自動コンパクトの欠点を補います。自動コンパクトはタスク途中で重要なコンテキストを失う可能性がありますが、戦略的コンパクトはフェーズ間でのみ実行されるため、関連する情報を保持しつつ不要な履歴を削除できます。このフックはPreToolUse(編集/書き込み)で動作し、主にコンテキストサイズ(トークン数)とツール呼び出し回数の2つの信号を監視します。環境変数によって閾値や動作を細かく調整でき、ユーザーはコンパクトの判断をガイドするテーブルや、コンパクト前に状態をファイルに保存するベストプラクティスに従うことで、セッションを効率的に管理できます。

対応✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/strategic-compact

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

戦略的コンパクトスキル

任意の自動コンパクトではなく、ワークフローの戦略的なポイントで手動/compactを提案します。

アクティブにするタイミング

  • コンテキスト制限に近づく長時間セッション(200K+トークン)
  • マルチフェーズタスク(調査 → 計画 → 実装 → テスト)に取り組んでいる場合
  • 同じセッション内で無関係なタスクを切り替える場合
  • 主要なマイルストーンを完了し、新しい作業を開始した後
  • 応答が遅くなったり、一貫性が低下したりした場合(コンテキストプレッシャー)

なぜ戦略的コンパクトなのか?

自動コンパクトは任意のタイミングでトリガーされます:

  • タスクの途中で発生することが多く、重要なコンテキストを失う
  • 論理的なタスク境界を認識しない
  • 複雑なマルチステップ操作を中断する可能性がある

論理的な境界での戦略的コンパクト:

  • 探索後、実行前 — 調査コンテキストを圧縮し、実装計画を保持
  • マイルストーン完了後 — 次のフェーズのための新鮮なスタート
  • 大きなコンテキストシフトの前 — 異なるタスクの前に探索コンテキストをクリア

仕組み

suggest-compact.js スクリプトはPreToolUse(編集/書き込み)で実行され、2つの信号を組み合わせます:

  1. コンテキストサイズ(プライマリ) — セッショントランスクリプト(フックペイロードのtranscript_path)から最新のusageレコードを読み取り、input_tokens + cache_read_input_tokens + cache_creation_input_tokens(ターンの真のコンテキストサイズ)を合計します。ウィンドウスケールの閾値(200kウィンドウで160kトークン、1Mウィンドウで250kトークン、[1m]モデルマーカーから検出、または観測されたトークンが既に200kを超えている場合は推測)で/compactを提案し、その後コンテキストが60kトークン増加するごとに再通知します。
  2. ツール呼び出し回数(セカンダリ) — セッション内のツール呼び出しをカウントし、設定可能な閾値(デフォルト: 50回)で提案し、その後25回ごとに提案します。

ツールカウントだけではウィンドウプレッシャーの弱いプロキシです。少数の大きなファイル読み込みやMCP応答でウィンドウがすぐに満杯になることがある一方、多数の小さな呼び出しではウィンドウがほぼ空の状態で50回に達することもあります。コンテキストサイズ信号は、実際に問題がある場合に発火します。

フックのセットアップ

プラグインとしてインストール? セットアップは不要です。プラグインのhooks/hooks.jsonはすでにsuggest-compact.jsを登録しています(フックID pre:edit-write:suggest-compact、standardおよびstrictフックプロファイルでアクティブ)。以下のブロックを~/.claude/settings.jsonにコピーしないでください — プラグインインストールでは~/.claude/scripts/は存在せず、プラグインフックを重複させると二重実行になります。

手動でインストールした場合(./install.sh)、~/.claude/settings.jsonに以下を追加:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [{ "type": "command", "command": "node ~/.claude/scripts/hooks/suggest-compact.js" }]
      },
      {
        "matcher": "Write",
        "hooks": [{ "type": "command", "command": "node ~/.claude/scripts/hooks/suggest-compact.js" }]
      }
    ]
  }
}

設定

環境変数:

  • COMPACT_THRESHOLD — 最初の提案までのツール呼び出し回数(デフォルト: 50)
  • COMPACT_CONTEXT_THRESHOLD — コンテキストサイズ提案が行われるまでのコンテキストトークン数(デフォルト: 200kウィンドウで160000、1Mウィンドウで250000、0でコンテキスト信号を無効化)
  • COMPACT_CONTEXT_INTERVAL — 提案が繰り返されるまでの追加コンテキストトークン数(デフォルト: 60000)
  • COMPACT_STATE_TTL_DAYS — 一時ディレクトリ内の古いセッション状態ファイルが削除されるまでの日数(デフォルト: 14)
  • ECC_CONTEXT_WINDOW_TOKENS — 自動検出を上書きする明示的なコンテキストウィンドウサイズ(トークン単位)。報告されたIDに[1m]マーカーがない大ウィンドウモデル(例: 400kのOpus 4.x、または新しい1Mウィンドウモデルファミリー)に設定し、閾値が実際のウィンドウにスケーリングされるようにします。設定しないとデフォルトの200kにフォールバックし、コンテキスト使用量を過大評価する可能性があります。
  • CLAUDE_CODE_AUTO_COMPACT_WINDOW — Claude Codeのネイティブウィンドウサイズオーバーライド(トークン単位)。ECC_CONTEXT_WINDOW_TOKENSが設定されていない場合のフォールバックとして使用されます。

コンテキストウィンドウはそれ以外の場合、[1m]モデルマーカーから自動検出されるか、観測されたトークンが既に200kを超えている場合は推測されます。どちらのシグナルも持たない大ウィンドウモデルでは、上記のオーバーライドのいずれかを設定して、/compactの提案が適切なタイミングで発火するようにします。

コンパクト判断ガイド

この表を使って、いつコンパクトすべきかを判断してください:

フェーズ遷移コンパクト?理由
調査 → 計画はい調査コンテキストはかさばる。計画はその蒸留された出力。
計画 → 実装はい計画はファイルに書き留められている(またはタスクリストがあればそれ)。コードのためにコンテキストを解放。
実装 → テスト場合によるテストが最近のコードを参照する場合は保持。焦点を切り替える場合はコンパクト。
デバッグ → 次の機能はいデバッグトレースは無関係な作業のコンテキストを汚染する。
実装途中いいえ変数名、ファイルパス、部分的な状態を失うのはコストがかかる。
失敗したアプローチの後はい新しいアプローチを試す前に、行き止まりの推論をクリア。

コンパクト後も残るもの

何が残るかを理解すると、安心してコンパクトできます:

残る失われる
CLAUDE.mdの指示中間の推論と分析
ディスク上のファイル以前に読んだファイルの内容
メモリファイル(~/.claude/memory/)マルチステップの会話コンテキスト
Gitの状態(コミット、ブランチ)ツール呼び出し履歴とカウント
タスクリスト — ただし、todoツールがある場合のみ(以下参照)口頭で述べられた微妙なユーザー設定

タスクリストの永続性に依存しないでください — 存在しない可能性があります

Claude Code 2.1.233では、Opus 4.8、Sonnet 5、Fable 5、Mythos 5以降のモデルでtodo/タスクツールがデフォルトで削除されました(TodoWrite、TaskCreate/Get/Update/List)。CLAUDE_CODE_ENABLE_TODO_TOOLS=1で復元できますが、これはマシンごとの環境設定です — このスキルには付属しないため、読者がその設定を持っていると想定できません。

「TODOリストがコンパクト後も残る」というのは、状態を書き留める代わりにコンパクトする理由として人々が挙げる点であるため重要です。ツールが存在しない場合、残るリストはなく、計画は単に失われます。コンパクトする前に計画をファイルに書き込んでください — ファイルはすべてのバージョンとすべてのモデルで永続します。タスクリストは存在しない可能性がある便利なものとして扱い、決して耐久性のある記録として扱わないでください。

ベストプラクティス

  1. 計画後にコンパクト — 計画が確定しファイルに書き込まれたら、新鮮な状態で開始するためにコンパクト
  2. デバッグ後にコンパクト — エラー解決コンテキストをクリアしてから続行
  3. 実装途中ではコンパクトしない — 関連する変更のためにコンテキストを保持
  4. 提案を読む — フックはいつを伝え、あなたはするかどうかを決定
  5. コンパクト前に書き込む — 重要なコンテキストをファイルやメモリに保存してからコンパクト
  6. /compactをサマリーとともに使用 — カスタムメッセージを追加: /compact 次は認証ミドルウェアの実装に集中する

トークン最適化パターン

トリガーテーブルの遅延読み込み

セッション開始時にスキル全体の内容を読み込む代わりに、キーワードをスキルパスにマッピングするトリガーテーブルを使用します。スキルはトリガーされたときだけ読み込まれ、ベースラインコンテキストを50%以上削減します:

トリガースキル読み込み時
"test", "tdd", "coverage"tdd-workflowユーザーがテストに言及
"security", "auth", "xss"security-reviewセキュリティ関連の作業
"deploy", "ci/cd"deployment-patternsデプロイコンテキスト

コンテキスト構成の認識

何がコンテキストウィンドウを消費しているか監視:

  • CLAUDE.mdファイル — 常に読み込まれる。スリムに保つ。
  • 読み込まれたスキル — 各スキルが1〜5Kトークンを追加
  • 会話履歴 — 各やり取りで増加
  • ツール結果 — ファイル読み込み、検索結果がかさばる

重複指示の検出

コンテキスト重複の一般的な原因:

  • ~/.claude/rules/とプロジェクト.claude/rules/の両方に同じルール
  • CLAUDE.mdの指示を繰り返すスキル
  • 重複するドメインをカバーする複数のスキル

コンテキスト最適化ツール

  • token-optimizer MCP — コンテンツ重複排除による95%以上のトークン削減を自動化
  • context-mode — コンテキスト仮想化(315KBから5.4KBへの削減を実証済み)

関連

  • The Longform Guide — トークン最適化セクション
  • メモリ永続化フック — コンパクト後も残る状態のため
  • continuous-learning スキル — セッション終了前にパターンを抽出

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

関連スキル