
Token Coach
- 253 installs
- 1.8k repo stars
- Updated August 3, 2026
- alexgreensh/token-optimizer
Coach developers on shrinking prompts, choosing models, and structuring context to cut token spend while preserving answer quality in daily agent work.
About
Acts as a token-efficiency coach for agent developers, reviewing prompts, tool outputs, and retrieval patterns to recommend smaller contexts, cheaper model tiers, and reusable prompt templates that maintain quality while lowering recurring LLM costs.
- Prompt compression and structuring tips
- Model-tier selection guidance
- Context window budgeting practices
- Before-and-after savings estimates
- Habit coaching for agent authors
Token Coach by the numbers
- 253 all-time installs (skills.sh)
- Ranked #2,545 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/alexgreensh/token-optimizer --skill token-coachAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 253 |
|---|---|
| repo stars | ★ 1.8k |
| Last updated | August 3, 2026 |
| Repository | alexgreensh/token-optimizer ↗ |
What it does
Coach developers on shrinking prompts, choosing models, and structuring context to cut token spend while preserving answer quality in daily agent work.
Files
Token Coach: Plan Token-Efficient Before You Build
Interactive coaching for Claude Code or Codex architecture decisions. Analyzes your setup, identifies patterns (good and bad), and gives personalized advice with real numbers.
Use when: Building something new, existing setup feels slow, designing multi-agent systems, or want a quick health check.
---
Phase 0: Initialize
1. Resolve runtime and measure.py path (same as token-optimizer):
RUNTIME="${TOKEN_OPTIMIZER_RUNTIME:-}"
if [ -z "$RUNTIME" ]; then
if [ -n "$CLAUDE_PLUGIN_ROOT" ] || [ -n "$CLAUDE_PLUGIN_DATA" ]; then
RUNTIME="claude"
elif [ -n "$CODEX_HOME" ] || [ -d "$HOME/.codex" ]; then
RUNTIME="codex"
else
RUNTIME="claude"
fi
fi
MEASURE_PY=""
for f in "$HOME/.codex/skills/token-optimizer/scripts/measure.py" \
"$HOME/.codex/plugins/cache"/*/token-optimizer/*/skills/token-optimizer/scripts/measure.py \
"$HOME/.claude/skills/token-optimizer/scripts/measure.py" \
"$HOME/.claude/plugins/cache"/*/token-optimizer/*/skills/token-optimizer/scripts/measure.py \
"$PWD/skills/token-optimizer/scripts/measure.py"; do
[ -f "$f" ] && MEASURE_PY="$f" && break
done
[ -z "$MEASURE_PY" ] || [ ! -f "$MEASURE_PY" ] && { echo "[Error] measure.py not found. Is Token Optimizer installed?"; exit 1; }
export TOKEN_OPTIMIZER_RUNTIME="$RUNTIME"2. Collect coaching data:
python3 "$MEASURE_PY" coach --jsonParse the JSON output. This gives you: snapshot (current measurements), detected patterns, coaching questions, focus suggestions, and history (trend data from past sessions).
The history key contains (when trends.db has enough data):
quality_recent_avg/quality_prior_avg- 7-day vs older quality scoresduration_recent_avg/duration_prior_avg- session length trends (minutes)cache_hit_recent_avg/cache_hit_prior_avg- prompt cache hit rate trendsgrade_d_pct_recent/grade_distribution- recent grade breakdowntotal_cost_usd/cost_per_session_usd/sessions_in_period- spend summaryquality_short_sessions/quality_long_sessions/optimal_session_hint- duration-quality correlationcompression_measured_saved/compression_opportunity_tokens- compression gapmulti_model_session_pct- percentage of recent sessions that switched models mid-session
Historical patterns also appear in the patterns_bad array (e.g. "Quality Declining", "Session Duration Creep", "Cache Hit Rate Dropping", "Cache Hit Rate Dropping (Model Switches)", "Frequent Model Switching", "High Cost Per Session", "Compression Opportunity Gap").
3. Check context quality (v2.0):
python3 "$MEASURE_PY" quality current --json 2>/dev/nullIf available, parse the quality score and issues. This enriches coaching with session-level insights (not just setup overhead). If the command fails (pre-v2.0 install), skip gracefully.
4. For Codex, check setup readiness:
if [ "$RUNTIME" = "codex" ]; then
python3 "$MEASURE_PY" codex-doctor --project "$PWD" --json 2>/dev/null
fiUse this to tell the user whether balanced hooks, compact prompt guidance, dashboard refresh, and status-line support are installed.
5. Keep-Warm consent (first run only, Claude Code):
python3 "$MEASURE_PY" keepwarm-consent-status # JSON: {billing_mode, consent, should_ask}If should_ask is false, skip silently. If true (API-billed, not yet asked), offer Keep-Warm once after the coaching conversation. First compute the projection from the user's own history:
python3 "$MEASURE_PY" keepwarm-backfill --json --no-fence # read modes."probe-only".net_usdThen pitch: when a session pauses past its 1h cache window and resumes, the prefix is re-written at up to 2x; Keep-Warm pings before expiry (~0.1x, max 2 pings/pause) so resumes stay warm, with a tripwire that auto-disables if it stops paying off. If modes."probe-only".net_usd is positive, say "a history-replay projection from your own last 30 days nets ~$<net_usd>/30d at probe-only"; if backfill yields nothing or net_usd <= 0, drop the dollar sentence (do not invent one) and say savings depend on their own pattern and the dashboard shows it once pings fire.
Record the answer — yes/no FIRST so an interrupted run never strands an "asked" marker with no answer: keepwarm-enable (yes) or keepwarm-disable (no), both terminal. Only if the user defers/ignores (records neither) run keepwarm-consent-asked as the shown-marker. keepwarm-enable records consent and installs the scheduler (macOS); other OSes are scheduler-pending, watchdog-only. Confirm it is armed with keepwarm-scheduler status and keepwarm-tick --dry-run. It is off by default and refuses on subscription auth.
Phase 1: Intake
Ask ONE question:
What's your goal today?
a) Building something new, want it token-efficient from the start
b) Existing project feels sluggish / context fills too fast
c) Designing a multi-agent system, want architecture advice
d) Quick health check with actionable tips
Wait for the answer. Don't dump info before they choose.
Phase 2: Load Context (based on intake)
Resolve the token-coach skill directory:
COACH_DIR=""
if [ -d "$HOME/.codex/skills/token-coach" ]; then
COACH_DIR="$HOME/.codex/skills/token-coach"
elif [ -d "$HOME/.codex/skills/token-optimizer/../token-coach" ]; then
COACH_DIR="$HOME/.codex/skills/token-optimizer/../token-coach"
elif [ -d "$HOME/.claude/skills/token-coach" ]; then
COACH_DIR="$HOME/.claude/skills/token-coach"
elif [ -d "$HOME/.claude/skills/token-optimizer/../token-coach" ]; then
COACH_DIR="$HOME/.claude/skills/token-optimizer/../token-coach"
else
COACH_DIR="$(find "$HOME/.codex/plugins/cache" "$HOME/.claude/plugins/cache" -path "*/token-coach" -type d 2>/dev/null | head -1)"
fiLoad references based on intake choice:
- Option a or b: Read
$COACH_DIR/references/coach-patterns.md+$COACH_DIR/references/quick-reference.md - Option c: Read
$COACH_DIR/references/agentic-systems.md+$COACH_DIR/references/quick-reference.md - Option d: Read
$COACH_DIR/references/quick-reference.mdonly (fast path)
Read the matching example from $COACH_DIR/examples/ as a few-shot template:
- Option a:
coaching-session-new-project.md - Option b:
coaching-session-heavy-setup.md - Option c:
coaching-session-agentic.md - Option d: Skip example (keep it fast)
Read $COACH_DIR/references/coaching-scripts.md for conversation structure.
Phase 3: Coach (conversation, not report)
This is a CONVERSATION. Not a wall of text.
1. Lead with the 1-2 most impactful findings from the coaching data 2. If quality data is available and score < 70, lead with that instead: "Your current session quality is [X]/100. [Top issue] is eating [Y tokens]." 3. If history data is available, weave in trend insights naturally:
- Quality trending down? Lead with that, it's more urgent than a static snapshot
- Cost data? Ground advice in dollars ("At $X.XX/session across Y sessions, routing alone could save $Z/month")
- Duration-quality correlation? "Your short sessions score X vs Y for long ones" is a concrete, actionable insight
- Grade distribution? "N% of your sessions scored D" hits harder than an abstract score
- Model switching? If multi_model_session_pct is high, explain: switching models mid-session invalidates the prompt cache. Set model at session start, not mid-conversation. Subagent routing to cheaper models is fine (separate context)
- Don't dump all history data at once. Pick the 1-2 most relevant trends for their intake choice
4. Reference their actual numbers ("You have 47 skills costing ~4,700 tokens at startup") 5. Ask a follow-up question. Don't dump everything at once. 6. For agentic systems (option c): walk through their architecture step by step 7. Use the coaching scripts for structure, but keep it natural
For Codex specifically, translate all advice to native Codex concepts:
AGENTS.mdinstead ofCLAUDE.md- Codex memories instead of
MEMORY.md - balanced Codex hooks instead of Claude hooks
- Intelligence levels (Low/Medium/High/Extra High) and model selection (GPT-5.5, GPT-5.4, GPT-5.4-Mini, GPT-5.3-Codex, GPT-5.2) instead of Opus/Sonnet/Haiku routing
- Reasoning effort settings instead of model-per-agent routing
- compact prompt guidance instead of PreCompact/PostCompact lifecycle hooks
- Never reference Claude-specific concepts (Opus, Sonnet, Haiku, CLAUDE.md) when coaching a Codex user
Tone: Knowledgeable friend, not corporate consultant. Be direct about what matters and why. Use real numbers from their data.
Anti-patterns to call out: Reference the anti-patterns from coach-patterns.md. Name them ("You've got the 50-Skill Trap going on").
Continue the conversation for 2-4 exchanges. Let the user ask questions. Adjust advice based on what they tell you about their workflow.
Phase 4: Action Plan
After the conversation, generate a prioritized action plan:
1. Summarize 3-5 concrete actions, ordered by impact 2. Include estimated token savings for each action (use the numbers from quick-reference.md) 3. If quality score < 70 in Claude Code: include "Set up Smart Compaction" as a recommended action (python3 $MEASURE_PY setup-smart-compact) 4. If quality score < 70 in Codex: include "Install balanced Codex hooks and compact prompt guidance" (TOKEN_OPTIMIZER_RUNTIME=codex python3 $MEASURE_PY codex-install --project .) 5. If quality score < 50: recommend immediate /compact or /clear before continuing 6. Flag which actions are quick wins vs deeper changes 7. Offer to run /token-optimizer for the full audit + implementation if they want to go beyond coaching
Format: Keep it scannable. Numbered list with bold action names, one-line description, estimated savings.
Phase 5: Dashboard (optional)
If measure.py generated a coach dashboard tab, mention it: "Your Token Health Score and pattern analysis are in the dashboard. Run python3 $MEASURE_PY dashboard to see it."
For Codex, also give the generated file location: ~/.codex/_backups/token-optimizer/dashboard.html.
<!-- Coach Dashboard Tab Fragment
Integrated into token-optimizer dashboard.html as the "Coach" tab.
Data comes from generate_coach_data() in measure.py, injected as data.coach.
This file is a reference copy. The actual rendering lives in dashboard.html's
renderCoach() function. Update both if modifying the coach tab layout.
-->
<!-- Nav item (add to .nav-menu): -->
<!-- <a class="nav-item" data-view="coach">Coach</a> -->
<!-- View container (add to main-col): -->
<!-- <div class="view" id="view-coach"></div> -->
<!-- Rendering: renderCoach() in dashboard.html JavaScript section -->
<!-- Called from init() after renderHealth() -->
<!-- Data structure expected (from measure.py generate_coach_data()): -->
<!--
{
"health_score": 0-100,
"snapshot": {
"total_overhead": number,
"controllable": number,
"fixed": number,
"context_window": number,
"overhead_pct": number,
"usable_tokens": number,
"skill_count": number,
"skill_tokens": number,
"claude_md_tokens": number,
"memory_md_lines": number,
"mcp_server_count": number,
"mcp_tokens": number,
"rules_count": number,
"rules_always_loaded": number,
"imports_count": number,
"imports_tokens": number
},
"patterns_good": [{"name": string, "detail": string}],
"patterns_bad": [{"name": string, "severity": "high"|"medium"|"low", "detail": string, "fix": string, "savings": string}],
"questions": [string],
"focus_area": string|null
}
-->
Example: Coaching Session for Multi-Agent Architecture
User chose option (c): Designing a multi-agent system, want architecture advice.
---
Coach Output
Coach: Multi-agent is where token optimization really matters. Every agent multiplies your config overhead. Your current setup costs ~18,500 tokens at startup. With multiple agents, that compounds fast.
Walk me through what you're building. How many agents? What does each one do?
User: I'm building a research automation. 4 agents: one scrapes web sources, one reads local documents, one analyzes findings, one writes the final report.
Coach: Four agents. Let's do the math on your current config:
- 4 agents x ~18,500 config overhead = 74,000 tokens just for agent setup
- Plus the orchestrator's own session = ~18,500 more
- Total infrastructure cost: ~92,500 tokens before any actual work
That's 46% of a single 200K context window (though agents each get their own window, this matters for cost/rate limits).
Let's optimize each agent:
Web scraper: Data-gathering only. This should be an Explore agent with Haiku. It reads web content, returns summaries. It does NOT need your 54 skills or Opus-level reasoning. With Haiku, you save ~60x on per-token cost for this agent.
Document reader: Also data-gathering. Another Explore agent with Haiku. It reads local files and extracts relevant content. Read-only is fine here.
Analyzer: This one needs judgment. Sonnet is the right model. It takes structured input from the first two agents and produces analysis. Still no need for full skill access unless it uses a specific analysis skill.
Report writer: Needs write access (to create the report file). General-purpose agent, Sonnet or Opus depending on report complexity. Only assign the specific writing-related skill if you have one.
User: The analyzer sometimes needs to look up additional files based on what it finds. Does that change things?
Coach: Good catch. If the analyzer needs to read files reactively, it can't be read-only Explore. Make it a general-purpose agent with Sonnet, but don't assign skills it doesn't need. The key distinction: Explore agents are for pre-planned reads. General-purpose agents handle reactive, multi-step tasks.
For the coordination pattern: create a temp folder. Each agent writes findings to it. The orchestrator tracks completion. The report writer reads from the findings folder directly, never from the orchestrator's context. This prevents your orchestrator from bloating with raw agent output.
/tmp/research-session/
COORDINATION.md
findings/
web-sources.md # Web scraper writes here
local-docs.md # Document reader writes here
analysis.md # Analyzer writes here
output/
final-report.md # Report writer creates hereUser: Should I slim my CLAUDE.md before building this?
Coach: 100%. Your CLAUDE.md at 2,180 tokens loads in EVERY agent. 5 agents (including orchestrator) = 10,900 tokens just for CLAUDE.md copies. If you trim to 800 tokens, that's 5 x 800 = 4,000 tokens. You'd save 6,900 tokens across the system.
Same logic for skills: 54 skills x 5 agents = frontmatter loading 5 times. Archive unused skills, save ~3,500 x 5 = 17,500 tokens across all agents.
Action Plan
1. Assign correct agent types: Web scraper and doc reader as Explore/Haiku (read-only). Analyzer as general-purpose/Sonnet. Report writer as general-purpose/Sonnet. (~60x cost reduction on data-gathering agents) 2. Implement coordination folder: Agents write to files, orchestrator reads summaries only. Prevents context overflow. 3. Slim CLAUDE.md to 800 tokens: Saves ~6,900 tokens across 5 agents (5 x 1,380 tokens saved). 4. Archive unused skills: Saves ~17,500 tokens across 5 agents (5 x 3,500 tokens saved). 5. No skill assignments to data-gathering agents: Web scraper and doc reader need zero skills. Analyzer gets only the analysis skill. Report writer gets only the writing skill.
Example: Coaching Session for a Heavy Setup
User chose option (b): Existing project feels sluggish / context fills too fast.
---
Coach Output
Coach: Found the weight. Your setup uses ~32,400 tokens at startup. That's 16.2% of your 200K window before you type anything. Combined with the ~45K autocompact buffer, you're starting each session with only ~122,600 usable tokens.
The top 3 overhead sources: 1. 54 skills: ~5,400 tokens in the startup menu. You've got the 50-Skill Trap going on. 2. CLAUDE.md: 2,180 tokens. That's over the 800-token target. The CLAUDE.md Novel pattern. 3. 8 MCP servers: ~1,200 tokens between tool names and server instructions.
When does it feel slow? Early in sessions, after a few messages, or during multi-agent work?
User: After about 10-15 messages. Compaction keeps hitting and I lose context.
Coach: That tracks. You're starting at 16.2% used. Each message adds conversation history plus file reads. By message 10-15, you're likely at 70%+ where quality degrades and compaction triggers.
Two things would help most:
First, your skills: 54 installed, but in the last 30 days you've only invoked 19 of them. Those 35 unused skills cost ~3,500 tokens per session for zero benefit. Move them to ~/.claude/_backups/skills-archived/. You can always move them back.
Second, your CLAUDE.md has a 400-line section about coding standards that should be a skill. As a skill, it'd cost ~100 tokens in the menu instead of ~2,000 tokens every message. That's a 95% reduction on that content alone.
Together: ~5,500 tokens recovered per session. That buys you roughly 3-4 more messages before compaction.
User: Which skills should I archive?
Coach: Looking at your trends data, these 35 skills haven't been invoked in 30 days: [list]. Before archiving, scan for any that are seasonal (deploy skills you use monthly, tax-season skills, etc.). Keep those. Archive the rest.
The quick process:
mkdir -p ~/.claude/_backups/skills-archived
mv ~/.claude/skills/[skill-name] ~/.claude/_backups/skills-archived/Action Plan
1. Archive 35 unused skills (Quick Win): Move to ~/.claude/_backups/skills-archived/. Recovers ~3,500 tokens/session. 2. Extract coding standards from CLAUDE.md to a skill (Medium): Create a coding-standards skill. Recovers ~1,900 tokens/message. 3. Review 8 MCP servers (Medium): Disable servers you don't use in CLI. Ask yourself which you actually use in conversation before disabling. 4. Use /compact at 50-70% (Habit): Don't wait for auto-compact. Run /compact proactively around message 8-10 given your current setup. 5. Run /token-optimizer for full audit: Get the before/after measurement and automated fixes.
Example: Coaching Session for Building a New Project
User chose option (a): Building something new, want it token-efficient from the start.
---
Coach Output
Coach: Your current setup starts every session with ~18,200 tokens of overhead. That's 9.1% of your 200K window, pretty reasonable. The big items: CLAUDE.md at 1,450 tokens, 23 skills at ~2,300 tokens, and 4 MCP servers at ~480 tokens.
What are you building?
User: A multi-step skill for doing code reviews. It should read files, run tests, and generate a review summary.
Coach: Good scope. For a code review skill, the architecture is:
1. SKILL.md (~80 lines, ~1,200 tokens on invoke): Orchestrator only. Phase 0 resolves paths, Phase 1 collects code context, Phase 2 analyzes, Phase 3 generates summary. Keep the body focused on control flow.
2. references/review-criteria.md: Your review standards, patterns to check for, severity levels. Zero tokens until the skill reads it. This is where the heavy domain knowledge goes.
3. references/output-templates.md: Example review outputs. Also zero cost until read.
Your frontmatter budget: description under 80 chars. Something like "Code review with test verification and structured summary." That's 56 chars, perfect.
The skill adds ~100 tokens to your startup overhead (frontmatter in the menu). Full cost of ~1,200 tokens only when someone invokes /code-review. The reference files cost zero unless the skill explicitly reads them during execution.
User: Should I use subagents for the test running?
Coach: Yes, for one reason: context isolation. When the skill reads code files for review, those stay in context. Running tests can produce verbose output. A subagent for test execution keeps that output in its own 200K window and reports back just pass/fail + relevant failures.
Use an Explore agent (Haiku, read-only) if you just need to read test results. Use a general-purpose agent if you need to actually run the tests via Bash. Either way, don't assign skills to the test agent unless it specifically needs them.
Action Plan
1. Create skill skeleton: SKILL.md + references/ directory. Budget: ~100 tokens startup, ~1,200 on invoke. (~0 additional startup cost vs no skill) 2. Keep description under 80 chars: "Code review with test verification and structured summary" (56 chars) 3. Use subagent for test execution: Isolates verbose test output from review context. Use general-purpose agent with Bash access, no skill assignments. 4. Put review criteria in references/: Zero cost until the skill reads them. Don't inline domain knowledge in SKILL.md body.
Agentic Systems: Multi-Agent Design Patterns for Token Efficiency
Reference file for Token Coach. Loaded ONLY for option c (multi-agent architecture).
---
The Cost Model
Every subagent gets its own fresh 200K context window. This is both the power and the cost of multi-agent architectures.
What Each Agent Inherits
- System prompt + built-in tools: ~15K tokens (FIXED, same as your main session)
- MCP tool definitions: same as your main session (deferred or eager)
- Skills frontmatter: same menu as your main session (~100 tokens/skill)
- Global CLAUDE.md: full content, every agent
- MEMORY.md: full content, every agent
What Each Agent Does NOT Inherit
- Your conversation history (good, this is why subagents are useful)
- Files you've already read (they start fresh)
- Results from other subagents
The Math
- 5 agents x 15K config overhead = 75K tokens just for setup
- Slimming CLAUDE.md by 1,000 tokens saves 5,000 tokens across 5 agents
- Measured native agent overhead (v1.0.60+): ~13K tokens per agent
---
Design Patterns
Pattern 1: Subagent as Context Isolation
Anthropic's official recommendation: use subagents to preserve main session context.
- Every file Claude reads stays in your context until compaction
- Subagents run in their own 200K window and return only summaries
- Prompt: "use a subagent to investigate X" keeps your main window clean
- Think of subagents as disposable research assistants, not just parallel workers
Pattern 2: The Coordination Folder
Prevents orchestrator context overflow from agent outputs.
/tmp/my-project/
COORDINATION.md # Status tracker
findings/ # Agents write here
agent-1-findings.md
agent-2-findings.md
status/ # Agent completion signals- Agents write FULL findings to files
- Orchestrator gets "Agent X completed, output at {path}" not the full output
- Synthesis agent reads files directly
- NEVER pull raw agent output into the orchestrator's context
Pattern 3: Parallel Dispatch for Independent Tasks
- Independent tasks in one message with multiple Agent tool calls
- Don't dispatch sequentially when tasks have no dependencies
- Each parallel agent gets its own fresh context
- Total token usage is the same, but wall-clock time is much less
Pattern 4: Model Routing for Agents
Default routing table:
| Task Type | Model | Why |
|---|---|---|
| File reading, counting, directory scans | Haiku | 60x cheaper, equally accurate for data gathering |
| Code analysis, judgment calls, writing | Sonnet | Good balance of quality and cost |
| Complex multi-step reasoning, architecture | Opus | Only when you need deep reasoning |
Add to CLAUDE.md: "Default subagents to model='haiku' for data gathering, model='sonnet' for analysis. Reserve model='opus' for complex reasoning."
Pattern 5: Surgical Skill Assignments
- Skills in a subagent's
skills:field load FULLY at agent startup (not progressively) - 5 skills x 3K tokens each = 15K tokens before the agent does anything
- Only assign skills the agent actually needs
- Built-in agents (Explore, Plan) don't get skills at all
- Reference files within assigned skills still load progressively
Pattern 6: Built-in Agent Type Selection
| Type | Model | Access | Use For |
|---|---|---|---|
| Explore | Haiku | Read-only (Glob, Grep, Read) | Codebase navigation, file search |
| Plan | Configurable | Read-only | Planning, architecture analysis |
| General-purpose | Default model | Full tools | Tasks requiring write access |
| Custom | You choose | You configure | Specialized workflows |
Use Explore when you just need to find things. Use Plan when you need reasoning without edits. Use General-purpose only when the agent needs to write files.
Pattern 7: Agent Team Cost-Benefit Analysis
From Anthropic docs: "Agent teams use approximately 7x the tokens of a single session in plan mode."
- Single agent: ~85K tokens for a complex task
- Agent team (3 agents): ~210K tokens for the same task, but 3x faster
- Break-even: only use teams when the time savings justify 2-7x token cost
- For budget-conscious users: single agent with selective /dispatch for parallelizable subtasks
---
Anti-Patterns in Multi-Agent Design
The Context Flood
Problem: Orchestrator reads back all agent output files into its own context. Symptoms: Orchestrator hits compaction after 2-3 agents report back. Fix: Orchestrator receives only "Agent X completed at {path}". Synthesis agent reads files.
The Clone Army
Problem: Every agent is general-purpose with full tools and default model. Symptoms: High cost. Agents doing simple reads with Opus. Fix: Use Explore agents for reads, Plan agents for analysis. Route model by task complexity.
The Skill Dump
Problem: Custom agents assigned all available skills "just in case." Symptoms: Each agent loads 10+ skills fully at startup. 30K+ tokens before work begins. Fix: Assign only the 1-2 skills each agent actually needs.
The Sequential Chain
Problem: Independent tasks dispatched one at a time instead of in parallel. Symptoms: 5 minute task takes 25 minutes. Same total tokens, much longer wall-clock. Fix: Launch independent agents in a single message with multiple Agent tool calls.
The Missing Handoff
Problem: No coordination folder. Agents can't see each other's work. Symptoms: Duplicate work. Agents solving the same problem independently. No synthesis. Fix: Create a coordination folder. Agents write findings to it. Orchestrator tracks status.
---
Quick Decision Framework
Should I use subagents for this task? 1. Does the task require reading many files? -> YES, use subagents for context isolation 2. Are there 3+ independent subtasks? -> YES, parallel dispatch 3. Is it a simple, focused task? -> NO, single session is simpler and cheaper 4. Am I hitting compaction frequently? -> YES, subagents help by isolating file reads
How many agents?
- 1 agent: Simple tasks, focused edits, single-module changes
- 2-3 agents: Multi-module tasks with clear boundaries
- 4-6 agents: Large refactors, cross-cutting changes, parallel research
- 7+ agents: Rarely justified. Coordination overhead exceeds benefits.
Coach Patterns: Architecture Patterns and Anti-Patterns
Reference file for Token Coach. Loaded for options a/b/d (config optimization).
---
Architecture Patterns (The "What To Do" Layer)
Pattern 1: Skill Design for Minimal Overhead
- SKILL.md body under 500 lines (Anthropic's recommendation)
- Description field under 200 characters, but trigger-rich (helps Claude suggest the skill)
- Heavy content in references/ (zero cost until explicitly read)
- Frontmatter is ~60-100 tokens per skill, loaded every session
- Full SKILL.md body loads on invocation (2K-5K tokens)
- References load only when the skill reads them (zero until then)
Pattern 2: CLAUDE.md Layering
- Global CLAUDE.md (~/.claude/CLAUDE.md): Identity, critical rules, key paths, model routing. Target <800 tokens.
- Project CLAUDE.md (<project>/.claude/CLAUDE.md): Project-specific conventions, tech stack, file layout. Keep separate.
- CLAUDE.local.md: Personal overrides, not committed to repo.
- Rule: if content only applies to specific tasks, it belongs in a skill, not CLAUDE.md.
- Every line in CLAUDE.md costs tokens on EVERY message, EVERY session, in EVERY subagent.
Pattern 3: MCP Server Consolidation
- Fewer servers with more tools > many servers with few tools
- Each server adds ~50-100 tokens of instruction text per message (even with deferred tools)
- Disable servers you don't use in CLI (re-enable anytime in settings.json)
- Cloud-synced servers (ENABLE_CLAUDEAI_MCP_SERVERS) may add tools you don't need in CLI
- Check for duplicate tools across servers and plugins
Pattern 4: Rules Scoping
- Always use
paths:frontmatter to scope rules to specific directories - Rules without paths: load EVERY message, same cost as CLAUDE.md
- Audit unscoped rules: are they truly global, or just lazily unscoped?
- Consolidate overlapping rules into fewer files
Pattern 5: Memory Hygiene
- MEMORY.md auto-loads first 200 lines every session
- Lines beyond 200 are truncated but still counted toward your window
- Move detailed notes to topic-specific files in memory/ directory
- Keep MEMORY.md as an index of high-signal, frequently-referenced items
- Dedup against CLAUDE.md (common source of waste)
Pattern 6: Import Auditing
- @imports in CLAUDE.md pull entire files into every message
- Each @path/to/file.md adds that file's FULL token count to every message
- Grep CLAUDE.md for @ patterns, resolve paths, add up tokens
- Move large imports to skills or reference files that load on demand
Pattern 7: Frontmatter Discipline
- Skill descriptions under 200 chars (80 chars is the sweet spot)
- Skill names under 30 chars
- Description should be a trigger phrase, not a paragraph
- Detailed usage instructions belong in SKILL.md body, not frontmatter
Pattern 8: Progressive Loading via Skills
- Content in CLAUDE.md: costs tokens every message
- Same content as a skill: ~100 tokens in menu, full cost only on invocation
- That's 97% savings on messages that don't invoke the skill
- Rule of thumb: if content is only relevant to specific tasks, make it a skill
- Split heavy skill content into references/ (Tier 3, zero until read)
---
Anti-Patterns (Common Mistakes with Fixes)
The 50-Skill Trap
Problem: 50+ skills installed. Menu overhead: 5,000+ tokens every session. Symptoms: Slow startup feel. Context fills faster than expected. Fix: Archive unused skills to ~/.claude/_backups/skills-archived/. A subfolder inside skills/ still loads as a namespace, so move OUTSIDE skills/ entirely. Review with measure.py trends to see which skills you actually invoke. Savings: ~100 tokens per archived skill per session.
The Opus Addiction
Problem: 70%+ of token usage on Opus when Sonnet/Haiku would suffice. Symptoms: High costs, hitting rate limits, budget burns fast. Fix: Add model routing to CLAUDE.md: "Default subagents to haiku for data gathering, sonnet for analysis. Opus only for complex reasoning." Savings: 50-75% cost reduction on multi-agent workflows. Same context tokens, much less spend.
The CLAUDE.md Novel
Problem: 200+ lines in global CLAUDE.md. 2,000+ tokens loading every message. Symptoms: Config overhead dominates. Less room for actual work. Fix: Progressive disclosure. Move workflows to skills. Move standards to reference files. Move gotchas to MEMORY.md. Target <800 tokens. Savings: 400-1,200+ tokens per message.
The Import Avalanche
Problem: Multiple @imports in CLAUDE.md pulling large files every message. Symptoms: Unexpectedly high baseline token count. CLAUDE.md "feels small" but loads heavy. Fix: Audit @import paths. Move large imports to skills. Keep only tiny, critical imports. Savings: Varies wildly. Some users have 5,000+ tokens in forgotten imports.
The MCP Sprawl
Problem: 15+ MCP servers configured, most rarely used. Symptoms: High tool count in /context. Slow tool search. Context pressure. Fix: Audit settings.json. Disable unused servers (can re-enable anytime). Check for cloud-synced servers from claude.ai. Savings: ~50-100 tokens per disabled server (instruction overhead) plus reduced tool search noise.
The Stale Memory
Problem: MEMORY.md duplicates CLAUDE.md content, or contains outdated entries. Symptoms: Wasted tokens on redundant info. Potentially conflicting instructions. Fix: Dedup MEMORY.md against CLAUDE.md. Remove resolved issues, completed migrations, one-time setup notes. Move verbose entries to topic files. Savings: Depends on duplication level. Commonly 200-600 tokens.
The Singleton Session
Problem: One long session for everything. Never uses /clear or /compact. Symptoms: Quality degrades over time. Compaction happens unexpectedly. Hallucinations increase. Fix: Session hygiene. /compact at 50-70%. /clear between unrelated topics. Fresh session for fresh work. Savings: Not token savings per se, but dramatically better output quality.
The Unscoped Rules
Problem: All rules in .claude/rules/ lack paths: frontmatter. Symptoms: Backend rules load when working on frontend. Testing rules load during docs work. Fix: Add paths: frontmatter to scope rules to relevant directories. Savings: Proportional to rule size. Can be hundreds of tokens per message.
Coaching Scripts: Conversation Flows for Each Intake Option
Reference file for Token Coach. Provides conversation structure for each coaching scenario.
---
General Coaching Principles
1. Lead with their data, not your knowledge. "You have 47 skills" lands harder than "Skills cost tokens." 2. One insight at a time. Present 1-2 findings, then ask a question. Don't dump everything. 3. Name the anti-pattern. "You've got the 50-Skill Trap" is memorable. "You have many skills" is forgettable. 4. Quantify everything. "~4,700 tokens" beats "a lot of tokens." 5. Respect their workflow. Some skills matter even if rarely invoked. Ask before recommending removal. 6. End with action, not information. Every coaching exchange should close with "Here's what to do next."
---
Option A: Building Something New
Opening
"Nice, building from scratch is the best time to get this right. Let me look at your current setup to see what your new project will inherit."
Flow
1. Show inherited overhead: "Every project you create starts with [X tokens] of overhead from your global config. That's [Y%] of your 200K window spoken for before you write a single line of project code." 2. Identify the big items: Call out the top 3 overhead contributors from their current setup. 3. Ask about the project: "What are you building? (Skill, MCP server, multi-agent system, app with Claude integration?)" 4. Give architecture advice based on answer:
- Skill: Point to Pattern 1 (Skill Design) and Pattern 7 (Frontmatter Discipline)
- MCP server: Point to Pattern 3 (MCP Consolidation) and deferred loading
- Multi-agent: Switch to agentic-systems.md patterns
- App: Focus on CLAUDE.md layering and session management
5. Recommend a token budget: "For a skill, budget ~100 tokens frontmatter + 3K body + references as needed. For a CLAUDE.md section, budget under 800 tokens total."
Closing
"Want me to run the full audit with /token-optimizer? Or are there specific architecture questions I can help with?"
---
Option B: Existing Project Feels Sluggish
Opening
"Let's figure out where the weight is. I've got your current measurements."
Flow
1. Show the headline number: "Your setup uses [X tokens] at startup. That's [Y%] of your 200K window before you type anything." 2. Identify the top 3 waste sources: Use the coaching data patterns. Name the anti-patterns. 3. Ask what they notice: "When does it feel slow? Early in sessions? After a few messages? During multi-agent work?" 4. Based on their answer:
- Early: Focus on startup overhead (skills, CLAUDE.md, MCP)
- After a few messages: Focus on compaction and context management (/compact, /clear habits)
- During multi-agent: Switch to agentic-systems.md patterns
5. Prioritize fixes: "The biggest win here is [X]. That alone would recover [Y tokens]. Want to tackle that first?"
Closing
"I'd recommend running /token-optimizer for the full audit and automated fixes. It'll back up everything first and measure the before/after difference."
---
Option C: Designing a Multi-Agent System
Opening
"Multi-agent is where token optimization really matters. Every agent multiplies your config overhead. Let's design this right."
Flow
1. Ask about the architecture: "Walk me through what you're building. How many agents? What does each one do?" 2. Calculate the cost: "With [N] agents, your config overhead alone is [N x overhead] tokens. That's before any of them read a single file." 3. Review agent types: "Which of these need write access? Which are just gathering data? The data-gathering ones should be Explore agents (Haiku, read-only)." 4. Check for the common anti-patterns:
- Clone Army: All general-purpose agents
- Skill Dump: Too many skills assigned to agents
- Sequential Chain: Independent tasks not parallelized
- Missing Handoff: No coordination folder
5. Recommend architecture changes: Specific agent types, model routing, coordination pattern.
Closing
"Shall I also look at your overall setup? Slimming CLAUDE.md saves [X x N] tokens across all [N] agents."
---
Option D: Quick Health Check
Opening
"Quick scan coming up."
Flow
1. Token Health Score: Show the composite score (0-100) and what drives it. 2. Top 3 actions: The three highest-impact things they can do right now, with estimated savings. 3. One habit tip: The single behavioral change that would help most.
Closing
Keep it under 2 minutes of reading. "That's the quick view. For the deep dive, run /token-optimizer."
---
Handling Follow-Up Questions
"How do I know which skills to archive?"
"Run python3 measure.py trends to see which skills you've actually invoked in the last 30 days. Anything you haven't used is a candidate. Move to ~/.claude/skills/_archived/ and you can always move it back."
"What should my CLAUDE.md look like?"
"Identity (1-2 lines), critical behavioral rules, key file paths, and model routing instructions. Everything else should be in skills, reference files, or MEMORY.md. Target: under 50 lines, under 800 tokens."
"Is this costing me money or just context?"
"Both, but differently. Context overhead affects output quality (degrades past 50% fill). Token costs affect your bill. Skills cost tokens but only on invocation. CLAUDE.md costs tokens every single message. Multi-agent workflows multiply everything."
"Should I use /compact or /clear?"
"Different tools for different situations. /compact preserves conversation context but may lose nuance. /clear gives you a completely fresh window. Rule of thumb: /compact within a topic, /clear between topics."
"My setup is already minimal. What else can I do?"
"Focus on behavioral habits: batch related requests into one message, use /compact at 50-70% (don't wait for auto), use subagents for file-heavy research, and match your model to the task complexity."
"My session feels degraded but context isn't full."
"That's a quality problem, not a quantity problem. Run python3 measure.py quality current to see what's rotting. Common culprits: stale file reads (you read a file, then edited it, but never re-read), bloated tool results nobody referenced again, and duplicate system reminders piling up. Smart Compaction can checkpoint your important state before /compact clears the noise."
"What's Smart Compaction?"
"Auto-compaction fires when context gets tight, but it's lossy. It summarizes your session with a generic checklist and drops nuance: the 'why' behind decisions, error sequences, agent state. Smart Compaction adds two things: (1) a PreCompact hook that snapshots structured state to disk before compaction, and (2) a SessionStart hook that injects what was lost back into the fresh context. Set it up with python3 measure.py setup-smart-compact."
---
Quality-Driven Coaching (v2.0)
When quality data is available from measure.py quality, use these coaching patterns:
Quality Score 85-100 (Excellent)
"Your session is clean. [Score]/100 quality. Not much to optimize here. Focus on behavioral habits and model routing."
Quality Score 70-84 (Good)
"Session quality is [Score]/100. You've got some bloat building up: [top issue]. A manual /compact now would clear [X tokens] of low-value content. If you haven't set up Smart Compaction yet, now's a good time."
Quality Score 50-69 (Degraded)
"Your session quality dropped to [Score]/100. That's the danger zone. [Top 2 issues] are eating [X tokens] combined. I'd recommend /compact now. If Smart Compaction is installed, your decisions and error context will survive. If not, consider /clear and reloading what you need."
Quality Score <50 (Critical)
"Session quality is [Score]/100. Heavy rot. You've got [N stale reads], [N bloated results], and [N compactions] worth of information loss stacked up. The context window is working against you at this point. Recommended: /clear and start fresh. If you need continuity, install Smart Compaction first (python3 measure.py setup-smart-compact), then /clear. Your state will be checkpointed."
Quick Reference: Hard Numbers for Token Coach
Reference file for Token Coach. The numbers the coach cites. Updated from research data (March 2026).
---
Baseline Overhead (Fresh Session)
| Component | Tokens | % of 200K |
|---|---|---|
| System prompt | ~3,000 | 1.5% |
| Built-in tools (18+) | ~12,000-15,000 | 6-7.5% |
| Autocompact buffer | ~33,000-45,000 | 16.5-22.5% |
| Total fixed floor | ~48,000-63,000 | 24-31.5% |
Usable context before any user config: ~137,000-152,000 tokens.
User Config Overhead (Typical Power User)
| Component | Tokens | Per-Item Cost |
|---|---|---|
| Skills (50 installed) | ~5,000 | ~100/skill |
| Commands (30 installed) | ~1,500 | ~50/command |
| MCP tools (100 deferred) | ~1,500 | ~15/tool |
| MCP server instructions (10 servers) | ~500-1,000 | ~50-100/server |
| CLAUDE.md (global) | ~800-2,000 | Per line |
| MEMORY.md | ~600-1,400 | Per line |
| Rules (5 unscoped) | ~500 | Variable |
| @imports | Variable | Full file cost |
Context Quality Degradation
| Fill Level | Quality | Recommendation |
|---|---|---|
| 0-30% | Peak performance | Work freely |
| 30-50% | Good quality | Monitor context |
| 50-70% | Minor degradation | Run /compact soon |
| 70-85% | Noticeable quality loss | Run /compact NOW |
| 85%+ | Hallucinations, corner-cutting | /clear or new session |
MCP Tool Costs (Real Examples)
| MCP Server | Tools | Tokens (eager) | Tokens (deferred) |
|---|---|---|---|
| GitHub | 35 | ~26,000 | ~525 |
| Slack | 11 | ~21,000 | ~165 |
| Jira | ~20 | ~17,000 | ~300 |
| Docker | 135 | ~125,000 | ~2,025 |
| Chrome automation | ~30 | ~31,700 | ~450 |
Tool Search (default since Jan 2026) reduced total MCP overhead by 85-96%.
Token Costs Per Component
| What | Always-Loaded Cost | On-Demand Cost |
|---|---|---|
| Skill (installed) | ~100 tokens (frontmatter) | 2K-5K (full SKILL.md on invoke) |
| Command | ~50 tokens (frontmatter) | Full file on invoke |
| MCP tool (deferred) | ~15 tokens (name only) | Full schema on use |
| MCP tool (eager) | ~300-850 tokens (full schema) | N/A |
| MCP server instruction | ~50-100 tokens | N/A |
| CLAUDE.md line | ~15 tokens | N/A |
| @import file | Full file tokens | N/A |
| Rule (unscoped) | Full file tokens | N/A |
| Rule (path-scoped) | 0 (until path match) | Full file when matched |
Environment Variables
| Variable | Effect | Default |
|---|---|---|
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1 | Remove git workflow instructions (~2K tokens) | Enabled |
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 | Disable auto memory creation/loading | Enabled |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 | Disable background tasks | Enabled |
ENABLE_CLAUDEAI_MCP_SERVERS=false | Opt out of claude.ai cloud-synced MCP servers | Enabled |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | Max output tokens (higher = larger autocompact buffer) | 16,384 |
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE | Auto-removed if found (inverted semantics cause premature compaction) | not set (~98%) |
includeGitInstructions: false (setting) | Same as DISABLE_GIT env var, in settings.json | true |
effortLevel (setting) | "high" maximizes quality + cost; "medium" saves 15-25% output tokens | auto |
Subagent Costs
| Factor | Cost |
|---|---|
| Native agent overhead (v1.0.60+) | ~13K tokens per agent |
| Config inheritance per agent | Same as main session startup |
| 5 agents x 15K config | 75K tokens just for setup |
| Skill assigned to subagent | FULL SKILL.md at startup (not progressive) |
| Agent Teams vs single agent | ~7x token usage (Anthropic docs) |
Cache-Expiry Waste — per provider (verified June 2026)
Cache economics are model-AGNOSTIC: each provider has its own cache profile, so the detector resolves a session's model to a profile, not to Anthropic semantics. Two waste shapes: explicit-TTL re-WRITE (Anthropic) and automatic-discount COLLAPSE (OpenAI/Codex, Gemini, DeepSeek).
| Provider / model family | Cache kind | Cached read | Effective TTL | User TTL knob |
|---|---|---|---|---|
| Anthropic API/SDK | explicit_ttl | 0.1x input | 5 min default | yes (ttl:"1h", 2x write once) |
| Claude Code | explicit_ttl | 0.1x input | 1 hour (platform default) | no (behavioral only) |
| OpenAI / Codex | automatic_discount | 0.1x input | ~5-10 min (max ~1h) | policy only (prompt_cache_retention="24h") |
| Gemini 2.5+ | explicit_storage | ~0.1x input | implicit auto | yes (cached_content ttl, default 1h, +storage/hr) |
| DeepSeek | automatic_discount | 0.1x input (1/10) | hours-to-days | no |
| unknown / other | none | n/a | n/a | n/a (no cache economics) |
Claude Code REQUESTS a 1-hour prompt cache (the platform default; the historical "silent downgrade to 5 minutes" was a bug fixed in v2.1.129). Empirically the cache survives sub-hour pauses, so the Claude Code detector counts only pauses LONGER than an hour. Raw Anthropic API/SDK/harness sessions (e.g. Hermes → Anthropic) keep the 5-minute default and the 1h-cache_control counterfactual.
Detection: explicit_ttl = gap > effective TTL (Claude Code 1h; API/SDK 5min) AND next-turn cache_creation >= 50% of prior cached prefix. automatic_discount/explicit_storage = prior cached ratio >= 0.40, gap > TTL, next ratio < 0.10 with comparable prompt → lost cached tokens re-billed at full input vs cached rate. none = honest skip (counted, never waste).
Verified remedies (per profile, exactly what the provider offers):
- Claude Code: already holds a 1-hour cache; no setting extends it. Behavioral remedy — resume within the hour or batch related work; pauses longer than an hour re-write the prefix. Token Optimizer can also keep it warm automatically (opt-in, API billing only):
keepwarm-enable(records consent + installs the macOS scheduler; verify withkeepwarm-scheduler status/keepwarm-tick --dry-run). It pings the cache before expiry at ~0.1x of the prefix (vs the 1.25-2x re-write), max 2 pings per pause unless promoted, with a tripwire that auto-disables if pings stop paying for themselves. Off by default; subscription auth stays off (pings would burn quota without saving dollars). To activate on a subscription/off-billing or platform-gap machine: setANTHROPIC_API_KEYand runkeepwarm-enable(on Linux/Windows, wirekeepwarm-tickto your own cron/timer until the scheduler ships). - Anthropic API/SDK/agent harness:
cache_control {"type":"ephemeral","ttl":"1h"}on stable prefixes. - OpenAI/Codex: keep prefix exact-match (>=1024 tok), resume within window;
prompt_cache_retention="24h"for long-lived prefixes. - Gemini: explicit
cached_contentwith userttl(per-hour storage billed). - DeepSeek: automatic; keep prefixes stable while the on-disk cache is warm.
Coverage gaps (not measurable, rendered explicitly): Hermes (per-session aggregates only, cache_read unreliable), OpenClaw/OpenCode (TS engines, no Python per-turn read path), Copilot (credits-billed, no per-turn cache detail).
Surface: measure.py cache-report [--days N] [--json] — per-provider breakdown + coverage gaps. OPPORTUNITY-tier (observed waste, potential recovery); never counts toward realized savings.
Community Pain Points (Feb-March 2026)
1. No per-request token visibility (GitHub #29600, #30814) 2. Compaction triggers too often / unexpectedly (buffer varies 33K-45K by version) 3. Context fills faster than expected (hidden MCP overhead) 4. MCP overhead invisible until session degrades (/context hides deferred overhead) 5. Auto-memory contributing to bloat (v2.1.53-59 regression confirmed by Anthropic) 6. Plugin cache stale versions accumulating (18+ GitHub issues) 7. Per-turn token regression in v2.1.x (GitHub #24243) 8. Agent Teams burn 7x tokens with unclear ROI