agentleFS
felvieirafelvieira/claude-skills-fv/skills/49-context-budget/SKILL.md

context-budget

Skill23 starsChanged 3 months agoApache-2.0View on GitHub

Audita o peso de contexto carregado na sessão — CLAUDE.md, agents, MCP descriptions, rules ativas, skills invocadas e histórico acumulado. Estima tokens por componente, reporta headroom disponível e emite alertas de overflow. Distinto do cost-tracker (skill 30) que rastreia tokens gastos em completions runtime. Trigger em: "contexto inchado", "context overflow", "quanto contexto estou usando", "peso do contexto", "context budget", "tokens carregados", "sessao lenta", "respostas degradadas", "headroom de contexto", "custo fixo de contexto", "overhead de rules", "overhead dos agents", "impacto do MCP no contexto", "espaco no context window", "quanto cabe no context window"

27 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use agent-sort, lead-intelligence and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • JamkrisSkill

    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.

    Also in 4 projects that use this

  • JamkrisSkill

    lead-intelligence

    AI-native lead intelligence and outreach pipeline. Replaces Apollo, Clay, and ZoomInfo with agent-powered signal scoring, mutual ranking, warm path discovery, source-derived voice modeling, and channel-specific outreach across email, LinkedIn, and X. Use when the user wants to find, qualify, and reach high-value contacts.

    Also in 4 projects that use this

  • JunMysterySkill

    ecc-guide

    Guide users through ECC's current agents, skills, commands, hooks, rules, install profiles, and project onboarding by reading the live repository surface before answering.

    Also in 3 projects that use this

  • JunMysterySkill

    recsys-pipeline-architect

    Design composable recommendation, ranking, and feed pipelines using the six-stage Source→Hydrator→Filter→Scorer→Selector→SideEffect framework popularized by xAI's open-sourced For You algorithm. Use this skill whenever the user is building any system that picks "the top K items for a (user, context)" — social feeds, content CMSs, RAG rerankers, task prioritizers, notification triage, search reranking, ad ranking.

    Also in 3 projects that use this

  • Exploration-labsSkill

    token-budget-advisor

    Proactive token budget assessment and task chunking strategy. Use this skill when queries involve multiple large file uploads, requests for comprehensive multi-document analysis, complex multi-step workflows with heavy research (10+ tool calls), phrases like "complete analysis", "full audit", "thorough review", "deep dive", or tasks combining extensive research with large output artifacts. This skill helps assess token consumption risk early and recommend chunking strategies before beginning work.

    Also in 5 projects that use this

  • thanvish21Skill

    benchmark-optimization-loop

    Optimization loops for Hermes benchmarks

    Also in 3 projects that use this

  • +5 more from Jamkris

The file

Files
SKILL.md

Skill 49 — Context Budget

Objetivo

Auditar o peso de contexto carregado em uma sessão Claude Code: quais skills/agents/MCP/rules/CLAUDE.md estão contribuindo para o overhead de tokens, quanto custa cada componente, e o que pode ser cortado ou adiado sem perder funcionalidade.

Distinção crítica:

  • Skill 30 (cost-tracker) → rastreia tokens/$ gastos em runtime (completions, tool calls)
  • Skill 49 (context-budget) → audita tokens carregados no contexto antes de qualquer completion (system prompt, CLAUDE.md, rules, skills, MCP descriptions)

Quando usar

  • Sessão com latência alta ou model degradation (possível context overflow)
  • Repo novo com .bot/ — auditoria do que foi instalado
  • Antes de habilitar novo MCP server ou subagent
  • Após instalar rules system path-scoped — verificar overhead real
  • Quando /savings mostrar contexto inchado

Protocolo

Fase 0 — Identificar componentes carregados

Listar o que está no contexto da sessão:

1. CLAUDE.md (global + projeto)
2. .claude/rules/**/*.md (path-scoped — quais foram ativados?)
3. skills/ carregadas via Skill() nesta sessão
4. agents/ descrições (sempre presentes no system prompt)
5. MCP server descriptions (presentes para cada server ativo)
6. Arquivos abertos/lidos na sessão
7. Histórico de conversa acumulado

Fase 1 — Estimar peso por componente

Para cada componente, estimar tokens:

regra geral: ~4 chars por token (aproximação BPE)

- ler tamanho do arquivo em bytes
- tokens ≈ bytes / 4
- overhead real pode ser 10-20% maior (BPE não é linear)

Comando de varredura rápida:

# Peso dos arquivos de contexto fixo
find . -name "CLAUDE.md" -o -name "GLOBAL.md" | xargs wc -c 2>/dev/null

# Peso das rules ativas
find .claude/rules/ -name "*.md" | xargs wc -c 2>/dev/null

# Peso dos agents (sempre no system prompt)
find agents/ -name "*.md" | xargs wc -c 2>/dev/null

# Peso das skills (sob demanda — verificar quais foram invocadas)
find skills/ -name "SKILL.md" | xargs wc -c 2>/dev/null | tail -1

Fase 2 — Categorizar por urgência

CategoriaCritérioAção
Sempre presenteCLAUDE.md, GLOBAL.md, agents/*.md, MCP descriptionsAuditar tamanho, propor corte
Sob demandaskills/ via Skill()Verificar se foi invocada sem necessidade
Path-scoped.claude/rules/*.mdVerificar se paths: glob está restrito
HistóricoConversa acumuladaConsiderar /clear ou nova sessão

Fase 3 — Relatório de budget

Output padrão:

## Context Budget — [repo] — [data]

### Componentes fixos (sempre carregados)
| Componente          | Arquivo              | Tokens est. | % budget |
|---------------------|---------------------|-------------|----------|
| CLAUDE.md (global)  | ~/.claude/CLAUDE.md  | ~2.400      | 12%      |
| CLAUDE.md (projeto) | ./CLAUDE.md          | ~800        | 4%       |
| GLOBAL.md           | ./GLOBAL.md          | ~1.200      | 6%       |
| agents/ (16 agents) | agents/*.md          | ~8.000      | 40%      |
| MCP descriptions    | (runtime)            | ~2.000      | 10%      |
| **Subtotal fixo**   |                      | **~14.400** | **72%**  |

### Componentes dinâmicos (esta sessão)
| Componente           | Tokens est. | Necessário? |
|----------------------|-------------|-------------|
| rules/common/*.md    | ~3.200      | ✓ se editando código |
| rules/typescript/*.md| ~800        | ✓ se arquivo .ts ativo |
| skill 09-orchestrator| ~1.200      | ✓ foi invocada |
| skill 11-reviewer    | ~900        | ? verificar |
| histórico conversa   | ~4.000      | — acumula   |
| **Subtotal dinâmico**| **~10.100** | —           |

### Resumo
- **Total estimado:** ~24.500 tokens (~98 KB)
- **Budget disponível (claude-sonnet-4.5):** 200.000 tokens
- **Headroom:** ~175.500 tokens (88%)
- **Status:** ✅ Saudável

### Recomendações
1. `agents/*.md` representa 40% do budget fixo — considerar frontmatter description mais curto
2. `rules/common/` sempre presente — OK para repo de código
3. Histórico acumula ~500 tokens/turno — considerar `/clear` a cada 50 turnos

Fase 4 — Alertas de overflow

Thresholds por modelo:

ModeloContext windowAlerta (80%)Crítico (95%)
claude-haiku-3.5200k tokens160k190k
claude-sonnet-4.5200k tokens160k190k
claude-opus-4.5200k tokens160k190k

Sinais de overflow iminente:

  • Respostas ficam genéricas ou "esquecem" instruções anteriores
  • Tool calls começam a falhar com erros estranhos
  • /savings mostra context_tokens subindo exponencialmente

Ações corretivas:

1. /clear — descarta histórico (mantém system prompt)
2. Nova sessão — fresh start completo
3. Remover MCP servers não usados (claude mcp remove <name>)
4. Encurtar agents/*.md descriptions
5. Revisar .claude/rules/ — paths: glob muito amplo?

Checkpoint: aplicar a ação mais barata primeiro (1 ou 2, reversível e imediata) → medir de novo (Fase 1) → se o sintoma persistir, aplicar a próxima ação da lista. Não pular direto pra remover MCP server ou editar agents/*.md sem confirmar que o /clear sozinho não resolveu — são mudanças mais permanentes pra um sintoma que às vezes é só histórico acumulado.

Integração com kit

  • Invocar após /savings quando contexto parecer inchado
  • Invocar antes de habilitar novo MCP server
  • Usar em conjunto com skill 30 (cost-tracker) para visão completa: custo fixo (contexto) + custo variável (completions)
  • Output de Fase 3 pode ser salvo em memory/context-budget-YYYY-MM-DD.md

Exemplo de invocação

Skill({ skill: "dev-team-kit-fv:49-context-budget" })
// Carrega playbook; agente executa Fases 0-3 e reporta

Ou via comando:

/context-budget

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.