Communitygithub.com

上下文預算

稽核 Claude Code 上下文窗口在 agents、skills、MCP 伺服器與 rules 間的消耗情況,找出臃腫與重複元件,並提供優先順序化的 token 節省建議。適用於上下文窗口過快填滿,且需要識別耗用元件的時機。

上下文預算 是什麼?

「上下文預算」技能旨在監控與最佳化 Claude Code 會話中的上下文窗口使用量,透過分析所有已載入元件(包括 agents、skills、MCP 伺服器與 rules)的 token 消耗,協助開發者識別並消除臃腫或重複的元件,以回收寶貴的上下文空間。此技能適用於 Claude Code,當會話效能變慢、輸出品質下降,或新增大量 skills、agents、MCP 伺服器時特別有用。運作方式分為四個階段:首先盤點所有元件目錄並估算 token 消耗(例如標記超過 200 行的 agent 檔案、超過 400 行的 skill 檔案、超過 100 行的 rule 檔案,以及工具數量超過 20 個的 MCP 伺服器);接著將元件分為「總是需要」、「有時需要」與「很少需要」三類;然後偵測問題模式,包括臃腫的描述、冗餘元件、MCP 過度訂閱以及 CLAUDE.md 臃腫;最後產生一份包含總開銷、元件分解、問題警告與排序列出的最佳化建議報告。此技能還支援詳細模式,可輸出每個檔案的 token 計數與最重量級檔案的逐行分析,幫助開發者精準定位造成開銷的源頭。最佳實踐建議在每次新增元件後執行審計,並特別注意 MCP 伺服器(每個工具約耗 500 tokens)與 agent 描述(即使未使用也會載入)對上下文空間的顯著影響。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/context-budget

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

上下文預算 是做什麼的?

分析 Claude Code 會話中每個已載入元件的 token 開銷,並提供可操作的優化建議以回收上下文空間。

使用時機

  • 會話效能感覺緩慢或輸出品質正在下降
  • 你最近新增了許多 skills、agents 或 MCP 伺服器
  • 你想知道實際上還有多少上下文空間可用
  • 計劃新增更多元件,需要確認是否還有空間
  • 執行 /context-budget 指令(此技能為其後端支援)

運作方式

階段一:盤點

掃描所有元件目錄並估算 token 消耗:

Agents(agents/*.md)

  • 計算每個檔案的行數與 token 數(字數 × 1.3)
  • 擷取 description frontmatter 長度
  • 標記:檔案 >200 行(過重)、description >30 字(frontmatter 臃腫)

Skills(skills/*/SKILL.md)

  • 計算每個 SKILL.md 的 token 數
  • 標記:檔案 >400 行
  • 檢查 .agents/skills/ 中是否有重複副本——跳過相同副本以避免重複計算

Rules(rules/**/*.md)

  • 計算每個檔案的 token 數
  • 標記:檔案 >100 行
  • 偵測同語言模組中 rule 檔案之間的內容重疊

MCP 伺服器(.mcp.json 或作用中的 MCP 設定)

  • 計算已設定的伺服器數量與工具總數
  • 估算結構開銷約為每個工具 500 個 token
  • 標記:工具 >20 個的伺服器、包裝簡單 CLI 指令(gh、git、npm、supabase、vercel)的伺服器

CLAUDE.md(專案層級 + 使用者層級)

  • 計算 CLAUDE.md 鏈中每個檔案的 token 數
  • 標記:合計行數 >300 行

階段二:分類

將每個元件歸入一個類別:

類別條件動作
總是需要在 CLAUDE.md 中被引用、支援作用中的指令,或與當前專案類型相符保留
有時需要特定領域(例如語言模式)、未在 CLAUDE.md 中被引用考慮按需啟用
很少需要無指令引用、內容重疊,或沒有明顯的專案相符項移除或延遲載入

階段三:偵測問題

識別以下問題模式:

  • 臃腫的 agent 描述 — frontmatter 中 description >30 字,每次 Task tool 呼叫時都會載入
  • 過重的 agents — 檔案 >200 行,每次 spawn 時會膨脹 Task tool 的上下文
  • 冗餘元件 — 重複 agent 邏輯的 skills、重複 CLAUDE.md 的 rules
  • MCP 過度訂閱 — 伺服器數量 >10 個,或包裝了可免費使用的 CLI 工具
  • CLAUDE.md 臃腫 — 冗長的說明、過時的部分、應改為 rules 的指示

階段四:報告

產生上下文預算報告:

Context Budget Report
═══════════════════════════════════════

Total estimated overhead: ~XX,XXX tokens
Context model: Claude Sonnet (200K window)
Effective available context: ~XXX,XXX tokens (XX%)

Component Breakdown:
┌─────────────────┬────────┬───────────┐
│ Component       │ Count  │ Tokens    │
├─────────────────┼────────┼───────────┤
│ Agents          │ N      │ ~X,XXX    │
│ Skills          │ N      │ ~X,XXX    │
│ Rules           │ N      │ ~X,XXX    │
│ MCP tools       │ N      │ ~XX,XXX   │
│ CLAUDE.md       │ N      │ ~X,XXX    │
└─────────────────┴────────┴───────────┘

WARNING: Issues Found (N):
[ranked by token savings]

Top 3 Optimizations:
1. [action] → save ~X,XXX tokens
2. [action] → save ~X,XXX tokens
3. [action] → save ~X,XXX tokens

Potential savings: ~XX,XXX tokens (XX% of current overhead)

在詳細模式中,還會額外輸出每個檔案的 token 計數、最重量級檔案的逐行分解、重疊元件之間的特定重複行,以及 MCP 工具清單(含每個工具的結構大小估計)。

範例

基本稽核

User: /context-budget
Skill: Scans setup → 16 agents (12,400 tokens), 28 skills (6,200), 87 MCP tools (43,500), 2 CLAUDE.md (1,200)
       Flags: 3 heavy agents, 14 MCP servers (3 CLI-replaceable)
       Top saving: remove 3 MCP servers → -27,500 tokens (47% overhead reduction)

詳細模式

User: /context-budget --verbose
Skill: Full report + per-file breakdown showing planner.md (213 lines, 1,840 tokens),
       MCP tool list with per-tool sizes, duplicated rule lines side by side

新增前檢查

User: I want to add 5 more MCP servers, do I have room?
Skill: Current overhead 33% → adding 5 servers (~50 tools) would add ~25,000 tokens → pushes to 45% overhead
       Recommendation: remove 2 CLI-replaceable servers first to stay under 40%

最佳實踐

  • Token 估算:純文字使用「字數 × 1.3」,程式碼較多的檔案使用「字元數 / 4」
  • MCP 是最大的槓桿:每個工具結構耗費約 500 token;一個 30 個工具的伺服器花費比所有 skills 加起來還多
  • Agent 描述總是載入:即使 agent 從未被呼叫,其 description 欄位仍會出現在每次 Task tool 的上下文中
  • 詳細模式用於除錯:當你需要精確找出造成開銷的檔案時使用,不適用於常規稽核
  • 變更後進行稽核:在新增任何 agent、skill 或 MCP 伺服器後執行,及早發現膨脹

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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能