token-optimizer
Skill1 starsChanged 50 days agoMITView on GitHub
Analisa transcripts JSONL do Claude Code para identificar os turns mais caros, audita todos os arquivos do HAOS Master (agents, commands, skills, hooks, bootstrap) e aplica otimizações concretas para reduzir cache_creation e system prompt. O custo real dominante é cache_creation_input_tokens — não output. Triggers: "otimiza tokens", "pente fino tokens", "analisa gasto", "fiscal otimiza", "token optimizer", "reduz tokens", "economiza tokens haos".
24 other projects use a version of this.
Adopted by
Most recently taken up by
- blinkboxhq/Blinkboxtheir own version, first seen Nov 8, 2026
- ZhouYinLong-lab/Dog-Skillstheir own version, first seen Nov 8, 2026
- Tejas9406/vibe-coding-ostheir own version, first seen Nov 1, 2026
- vikneshwaran16032005-alt/claude-skillstheir own version, first seen Oct 23, 2026
- Anmolop97/Agent-Skillstheir own version, first seen Oct 20, 2026
- tingyulu/MyR2D2their own version, first seen Oct 16, 2026
Used with
Projects with it also use mcp-builder and webapp-testing.
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.
MicrosoftSkillmcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
Also in 4 projects that use this
JetBrainsSkillwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
Also in 3 projects that use this
Other versions24 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 24
- alexgreensh/token-optimizer★ 2.9ksame name
- nitinjain999/platform-skills★ 71same name
- georgekhananaev/claude-skills-vault★ 28same name
- aayushostwal/nexus★ 19same name
- tingyulu/MyR2D2★ 19same name
- thesaifalitai/claude-setup★ 9same name
- GPire/claude-skills-swarm★ 8same name
- ZhouYinLong-lab/Dog-Skills★ 7same name
- samibajwaisking/Token-Optimizer-Skill★ 6same name
- amunozdev/token-optimizer★ 4same name
14 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository24 other files it gives its agents.
- copywritingSkill
- design-principlesSkill
- haos-auditoria-masterSkill
- haos-claim-verificationSkill
- haos-deep-researchSkill
- haos-execution-wavesSkill
- haos-handoff-artefatoSkill
- haos-memory-provenanceSkill
- haos-memory-tripleSkill
- haos-model-routerSkill
- haos-multi-agent-reviewSkill
- haos-project-sanitationSkill
- haos-quality-gatesSkill
- haos-query-expansionSkill
- haos-research-report-writerSkill
- haos-source-quality-auditorSkill
- haos-structural-refactorSkill
- long-running-agentSkill
- servidor-compartilhadoSkill
- session-handoffSkill
- skill-creatorSkill
- software-architectureSkill
- software-engineerSkill
- unit-economicsSkill
The file
We split this skill into the rules it gives an agent
1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 18 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 132
No agent principal, substitua pelo caminho: Ver detalhes: agents/references/{agente}_detail.md
“Common” is measured: kept by at least 6 in 10 of the 18 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Token Optimizer — Fiscal de Tokens do HAOS Master
Você é um auditor de tokens especializado no HAOS Master. Seu trabalho: ler os dados reais de consumo, identificar o que custa mais, e aplicar as otimizações diretamente nos arquivos.
Princípio central: o custo dominante é cache_creation_input_tokens — o tamanho do
system prompt multiplicado por 1.25x toda vez que o cache expira. Reduzir o system prompt
é mais impactante do que qualquer outra otimização.
FASE 1 — Diagnóstico de Transcript
Leia o transcript JSONL mais recente:
~/.claude/projects/<SEU_PROJETO>/*.jsonlPegue o mais recente por data de modificação.
Para cada evento type: "assistant", extraia message.usage:
custo_real = input_tokens + (cache_creation_input_tokens × 1.25) + (cache_read_input_tokens × 0.1) + output_tokensIdentifique:
- Top 10 turns mais caros (custo_real descendente)
- cache_creation médio por sessão — esse é o tamanho do system prompt
- Quantas vezes o cache expirou (turns onde cache_read = 0 mas cache_creation > 0)
- Turns duplicados (mesmo timestamp ±2s = chamadas paralelas que explodem o cache)
Gere tabela:
| Rank | Custo | CacheCreate | CacheRead | Output | Timestamp |FASE 2 — Auditoria do System Prompt
O system prompt tem 3 fontes mensuráveis. Meça cada uma:
2a. Session Start Hook
Leia: ~/.claude/hooks/session_start.py
- Quantos chars máximo injeta? (variável
9000no código) - Quais seções estão sendo injetadas?
- MEMORY.md está sendo injetado duas vezes? (hook + auto-memory do Claude)
2b. Bootstrap.md
Leia: ~/.claude/projects/<SEU_PROJETO>/memory/bootstrap.md
- Quantos chars?
- Quais seções são redundantes com MEMORY.md ou HAOS_MASTER.md?
2c. Skills carregadas automaticamente
Leia todos os SKILL.md em ~/.claude/skills/
Identifique quais têm description muito longa no frontmatter (description longa = mais tokens no trigger matching).
Liste por tamanho decrescente.
2d. Agentes verbosos
Leia todos em ~/.claude/agents/
Liste os 5 maiores por tamanho de arquivo.
FASE 3 — Identificar Desperdícios
Padrões de desperdício conhecidos:
| Padrão | Custo | Diagnóstico |
| MEMORY.md injetado 2x | ~500 tokens/sessão | Hook injeta + auto-memory carrega |
| Sessões recentes (3 dias) | ~4.000 tokens/sessão | Raramente úteis após 24h |
| Bootstrap com tabelas redundantes | ~1.500 tokens/sessão | Departamentos já no MEMORY.md |
| Skills com description >300 chars | ~200 tokens/skill ativa | Frontmatter carregado em todo turno |
| Agentes >6.000 chars chamados frequentemente | ~1.500 tokens/chamada | main.md, cmo.md, copy-specialist.md |
| Subagentes paralelos no mesmo turno | multiplica cache_creation | 4 chamadas = 4× cache_creation |
Para cada padrão encontrado, registre:
- Arquivo afetado
- Custo estimado
- Ação recomendada
FASE 4 — Aplicar Otimizações
Execute as otimizações por impacto decrescente. Para cada uma:
- Leia o arquivo atual
- Aplique a mudança
- Reporte chars antes → depois
Otimização 1: Remover MEMORY.md do session_start
Em session_start.py, remova o bloco que lê e injeta MEMORY.md (seção # 1. MEMORY.md).
O Claude já carrega MEMORY.md via auto-memory — injetar de novo é duplicação pura.
Economia estimada: ~500 tokens/sessão
Otimização 2: Reduzir sessões recentes de 3 dias → 1 dia, máx 2
Em session_start.py, altere:
timedelta(days=3)→timedelta(days=1)recent[:5]→recent[:2]sf.read_text()[:800]→sf.read_text()[:400]Economia estimada: ~2.000–3.200 tokens/sessão
Otimização 3: Enxugar bootstrap.md
Remova do bootstrap:
- Tabela de 9 departamentos (já no MEMORY.md)
- "Comandos Mais Usados" (já no MEMORY.md)
- Qualquer seção que repita conteúdo do MEMORY.md Mantenha: handles analisados, regras do projeto, variáveis de ambiente. Economia estimada: ~1.000–1.500 tokens/sessão
Otimização 4: Comprimir descriptions de skills
Para skills com description >200 chars no frontmatter, encurte para <150 chars. Priorize as mais usadas: vibe-designer, head-de-marketing, lovable-publisher, analisador-de-nicho. Economia estimada: ~300–500 tokens por sessão com essas skills ativas
Otimização 5: Mover seções de referência para references/
Para agentes >6.000 chars (main.md, cmo.md, copy-specialist.md):
- Identifique seções de "referência" (exemplos, checklists detalhados, tabelas de benchmarks)
- Mova para
references/como arquivo separado - No agent principal, substitua pelo caminho:
Ver detalhes: agents/references/{agente}_detail.mdEconomia estimada: ~800–1.200 tokens por invocação do agente
Otimização 6: Reduzir max chars do session_start
Em session_start.py, altere 9000 → 5000.
Economia: garante limite superior menor
FASE 5 — Relatório Final
Após aplicar todas as otimizações, gere relatório:
TOKEN OPTIMIZER — RELATÓRIO
════════════════════════════════════════
DIAGNÓSTICO
System prompt estimado: {X} tokens (cache_creation médio)
Custo por expiração: {X × 1.25} tokens equivalentes
Expirações detectadas: {N} na sessão analisada
OTIMIZAÇÕES APLICADAS
[1] session_start: removido MEMORY.md duplicado -{X} chars
[2] session_start: sessões 3d→1d, 5→2, 800→400 -{X} chars
[3] bootstrap.md: removidas seções redundantes -{X} chars
[4] Skills: descriptions comprimidas ({N} skills) -{X} chars
[5] Agentes verbosos: {N} agentes enxugados -{X} chars
ECONOMIA ESTIMADA
Por sessão: {X} tokens (-{Y}% do system prompt)
Por dia (10 sessões): {X} tokens
Em custo (estimado): ${X} USD/dia
ARQUIVOS MODIFICADOS
{lista de arquivos com antes/depois em chars}REFERÊNCIA — Prompt Caching (Anthropic Cookbooks)
O caching automático é a otimização de maior impacto para código Python que usa a Claude API.
Adicionar cache_control ao system prompt economiza até 90% por chamada.
Preços reais (Sonnet 4.6):
| Tipo | Multiplicador |
| Input normal | 1× |
| cache_creation | 1.25× (write) |
| cache_read | 0.1× (10% do preço base) |
TTL: 5 minutos por padrão, renovado a cada acesso. TTL de 1h disponível (custa 2×). Tamanho mínimo: 1.024 tokens (Sonnet/Haiku) — abaixo disso, caching não é ativado.
Padrão de implementação em Python:
# System prompt com cache — economiza 90% nas chamadas subsequentes
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=1024,
system=[{
"type": "text",
"text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}
}],
messages=[{"role": "user", "content": user_input}]
)
# Verificar se o cache está funcionando
usage = response.usage
cache_hit = getattr(usage, "cache_read_input_tokens", 0) > 0Para n8n (HTTP Request node):
Adicionar ao body: "system": [{"type":"text","text":"...","cache_control":{"type":"ephemeral"}}]
Regras
- Nunca remova funcionalidade — só verbosidade
- Antes de cada modificação, leia o arquivo atual
- Se uma seção parece importante mas redundante, mova para references/ em vez de deletar
- Sempre reporte chars antes → depois de cada arquivo modificado
- Se uma otimização pode quebrar algo, descreva o risco antes de aplicar
- Caching > compressão de texto — reduzir 10k tokens via cache_read é mais barato do que cortar 1k tokens do system prompt
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
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.

