Minimize Anthropic API costs without sacrificing quality. Focus on cache read reduction — the #1 cost driver for long sessions with Opus.
ModelInputCache WriteCache ReadOutputHaiku$0.80$1.00$0.08$4Sonnet$3$3.75$0.30$15Opus$15$18.75$1.50$75
(per MTok — multiply by millions of tokens)
Key insight: Cache read = context_size × num_turns. 200k context × 50 turns on Opus = ~$15 just cache reads.
jsonc
"compaction": {
"mode": "safeguard",
"model": "anthropic/claude-sonnet-4-20250514"
}
Sonnet summarizes at 5x less cost than Opus. Quality comparable for summaries.
jsonc
"contextPruning": { "mode": "cache-ttl", "ttl": "1h" }
TTLBehaviorVerdict1hTrims after 1 hour✅ Best balance30mModerateOK for active sessions5mAggressive⚠️ Loses tool results
jsonc
"params": { "cacheRetention": "long", "context1m": true }
"long" = fewer cache writes ($18.75/MTok on Opus!). Don't switch to "default".
Anthropic cache expires after ~1h idle. Heartbeat at 55min keeps it warm:
jsonc
"heartbeat": { "every": "55m" }
Prevents expensive cache re-writes when agent resumes after idle.
jsonc
"bootstrapMaxChars": 8000,
"bootstrapTotalMaxChars": 30000
Check current injection: /context list. Prevents oversized files from inflating every turn.
FileTargetReview cycleAGENTS.md<500 tokens (~2KB)MonthlySOUL.md<250 tokens (~1KB)RarelyTOOLS.md<500 tokens (~2KB)When tools changeMEMORY.md<400 tokens (~1.5KB)Weekly pruneHEARTBEAT.md<400 tokens (~1.5KB)When donememory/YYYY-MM-DD.md<30 linesCollapse at EODTotal injected****<2,800 tokens
docs/, notes/) — not auto-injectedWrite: decisions + why (1 line), new tools/config, lessons, user preferences. Skip: exploration steps, command outputs, things already in MEMORY.md, delivered content. Format: Bullets, not paragraphs. One fact per line.
/compact after each topic (most effective manual action)#text
/compact Focus on [topic summary]
/new when switching topics entirely#Context resets to 0. Don't carry 200k into unrelated work.
Spawn subagents (cheaper model) for: codebase grep, reading 5+ files, research/web fetch. Tool results stay isolated.
| head -20, | jq '.key'BudgetContent10%Task instructions + constraints40%Recent 5-10 turns of dialogue20%Decision logs ("tried X, failed because Y")20%High-relevance MEMORY.md snippets10%Tool schemas + system prompt
Before compaction hits, critical state must be captured:
SESSION-STATE.md before respondingmemory/working-buffer.mdAfter 85% context or 3+ compactions → start fresh with /new. Good MEMORY.md means minimal context loss.
Problem: Every code review or exploration session re-reads the same files, burning tokens on repeated grep/ read calls. A 500-file project can cost 50k+ tokens just for navigation.
Solution: Generate a persistent codebase map ( atris/MAP.md) once, reuse across sessions.
bash
# Install atris skill
npx clawhub@latest install atris
# Or manually: create atris/ folder in project root, then scan
rg "^(export|function|class|const|def |async def |router\.|app\.)" \
--line-number -g "!node_modules" -g "!.git" -g "!dist" -g "!.env*"
markdown
# MAP.md — [Project] Navigation Guide
> Last updated: YYYY-MM-DD
## Quick Reference
- `src/index.ts:1` — App entry point
- `src/routes/auth.ts:15` — POST /login handler
- `src/models/user.ts:8` — User schema
### Feature: Authentication
- **Entry:** `src/auth/login.ts:45-89` (handleLogin)
- **Validation:** `src/auth/validate.ts:12` (validateToken)
- **Routes:** `src/routes/auth.ts:5-28`
### Feature: Billing
- **Controller:** `src/controllers/billing.ts:20`
- **Service:** `src/services/stripe.ts:1-45`
Before searching codebase:
atris/MAP.md — found? Go directly to file:linerg, then add result to MAP.mdMap gets smarter every session. Never let a discovery go unrecorded.
CodebaseWithout mapWith mapSavingsSmall (50 files)5k tokens/explore1k80%Medium (200 files)20k tokens/explore3k85%Large (500+ files)50k tokens/explore5k90%
text
/context list → token count per injected file
/context detail → full breakdown (tools, skills, system)
/usage tokens → append token count to every reply
/usage cost → cumulative cost summary
/status → model, context %, cost estimate
SituationActionSession >100k context/compact immediatelySwitching topics/new or /compactReading 5+ filesSpawn subagentCompaction cost highSet compaction model to SonnetDaily cost >$10Audit session count, compact moreCache writes spikingHeartbeat ≤55min, keep cacheRetention: longWorkspace injection >20KBMerge/move files, set bootstrapMaxCharsContext >85%/new — start fresh
TechniqueSavingsUX ImpactCompaction model = Sonnet80% compaction costNoneWorkspace file budgets30-50% base costNone/compact after topics40-60% cache readManual stepCache TTL heartbeat (55m)30% cache readBetter (parallel)Tool output discipline20-30% cache writesNoneBootstrap size limits20-30% base costNoneSubagent delegation10-20% per turnRequires habit100% (reset)Lose old contextCodebase map (Atris)~80-90% code explorationOne-time setup/new for new topics
Incorporates ideas from: openclaw-token-optimizer, context-slimmer, context-budgeting, compaction-survival, context-hygiene, atris (codebase map caching).