Communitygithub.com

上下文預算

審計 Claude Code 會話中代理程式、技能、MCP 伺服器和規則的上下文視窗消耗量。識別臃腫、冗餘的元件,並產生優先級排序的 token 節省建議。當上下文視窗填充過快,需要找出消耗元件的首選工具。

上下文預算 是什麼?

Context Budget (上下文預算) 是一項專門用於 Claude Code 會話的審計技能,旨在分析與優化 token 消耗。它能全面盤點當前載入的代理程式、技能、MCP 伺服器和規則文件,估算每個元件的 token 用量,並識別導致上下文視窗快速填滿的臃腫或冗餘元件。該技能分為四個階段:盤點、分類、問題檢測和報告生成。它會標記大型檔案、冗長描述、內容重疊的規則以及工具過多的 MCP 伺服器,並根據潛在的 token 節省量對優化建議進行排序。此技能支援 Claude Code 和 Codex 平台,可透過 `/context-budget` 命令直接呼叫。其獨特價值在於不僅提供數據,還能產生可操作的報告,幫助開發者收回上下文空間,提升會話效能與輸出品質。

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

在你喜歡的 AI 中提問

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

說明文件

上下文預算 是做什麼的?

分析 Claude Code 會話中每個已載入元件的 Token 開銷,並提出可行的最佳化建議,以回收上下文空間。

使用時機

  • 會話效能感覺遲緩或輸出品質正在下降
  • 您最近新增了許多技能、代理程式或 MCP 伺服器
  • 您想知道實際上還有多少上下文空間
  • 計劃新增更多元件,需要知道是否還有空間
  • 執行 /context-budget 指令(此技能支援該指令)

運作方式

第一階段:盤點

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

代理程式 (agents/*.md)

  • 計算每個檔案的行數與 Token 數(字數 × 1.3)
  • 擷取 description Frontmatter 長度
  • 標記:檔案 >200 行(過重),描述 >30 字(Frontmatter 臃腫)

技能 (skills/*/SKILL.md)

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

規則 (rules/**/*.md)

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

MCP 伺服器 (.mcp.json 或有效的 MCP 配置)

  • 計算已配置的伺服器數與工具總數
  • 估算 Schema 開銷:每個工具約 500 個 Token
  • 標記:工具數 >20 的伺服器、包裝簡單 CLI 指令 (gh, git, npm, supabase, vercel) 的伺服器

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

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

第二階段:分類

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

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

第三階段:檢測問題

識別以下問題模式:

  • 代理程式描述臃腫 — 描述 >30 字的 Frontmatter 會載入到每個 Task 工具呼叫中
  • 過重的代理程式 — 檔案 >200 行會在每次產生時膨脹 Task 工具上下文
  • 冗餘元件 — 技能重複代理邏輯、規則重複 CLAUDE.md 內容
  • MCP 過度訂閱 — 伺服器數 >10 個,或包裝了可免費使用的 CLI 工具的伺服器
  • CLAUDE.md 臃腫 — 冗長的說明、過時的部分、應作為規則的指示

第四階段:報告

產生上下文預算報告:

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 工具清單(含每個工具的 Schema 大小估算)。

範例

基本審計

User: /context-budget
Skill: 掃描設定 → 16 個代理程式 (12,400 tokens),28 個技能 (6,200),87 個 MCP 工具 (43,500),2 個 CLAUDE.md (1,200)
       標記:3 個過重代理程式,14 個 MCP 伺服器 (3 個可被 CLI 取代)
       最大節省:移除 3 個 MCP 伺服器 → -27,500 tokens (減少 47% 開銷)

詳細模式

User: /context-budget --verbose
Skill: 完整報告 + 逐檔案解析顯示 planner.md (213 行,1,840 tokens),
       MCP 工具清單(含每個工具的大小),以及重複的規則行並排顯示

擴充前檢查

User: 我想新增 5 個 MCP 伺服器,還有空間嗎?
Skill: 當前開銷 33% → 新增 5 個伺服器 (~50 個工具) 將增加約 25,000 tokens → 開銷推升至 45%
       建議:先移除 2 個可被 CLI 取代的伺服器,使開銷維持在 40% 以下

最佳做法

  • Token 估算:散文使用 words × 1.3,程式碼密集檔案使用 chars / 4
  • MCP 是最大的槓桿:每個工具 Schema 約耗費 500 tokens;一個 30 個工具的伺服器比您所有的技能加起來還貴
  • 代理程式描述始終被載入:即使代理程式從未被叫用,其描述欄位也存在於每個 Task 工具上下文中
  • 詳細模式用於除錯:當您需要精確定位導致開銷的檔案時使用,不適用於常規審計
  • 變更後進行審計:在新增任何代理程式、技能或 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/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.

相關技能