@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,714 @@
1
+ # Token Optimization Checklist
2
+
3
+ Comprehensive checklist of ALL optimization techniques.
4
+
5
+ ---
6
+
7
+ ## Contents
8
+
9
+ - [QUICK WINS (< 30 minutes each)](#quick-wins--30-minutes-each)
10
+ - [MODEL ROUTING STRATEGY (Highest-ROI Behavioral Change)](#model-routing-strategy-highest-roi-behavioral-change)
11
+ - [MEDIUM EFFORT (1-3 hours, save 2,000-5,000 tokens)](#medium-effort-1-3-hours-save-2000-5000-tokens)
12
+ - [DEEP OPTIMIZATION (power users)](#deep-optimization-power-users)
13
+ - [BEHAVIORAL CHANGES (Free, highest cumulative impact)](#behavioral-changes-free-highest-cumulative-impact)
14
+ - [ADVANCED (Power Users)](#advanced-power-users)
15
+ - [MONITORING & MEASUREMENT](#monitoring--measurement)
16
+ - [TOKEN FLOW REFERENCE](#token-flow-reference)
17
+ - [WORKED EXAMPLE: Power User Optimization](#worked-example-power-user-optimization)
18
+ - [ENVIRONMENT VARIABLES & SETTINGS (Tune your setup)](#environment-variables--settings-tune-your-setup)
19
+ - [ANTI-PATTERNS](#anti-patterns)
20
+
21
+ ---
22
+
23
+ ## QUICK WINS (< 30 minutes each)
24
+
25
+ ### 1. Check /cost and /context (0 minutes)
26
+ **Target**: Know your baseline before changing anything
27
+
28
+ **Actions**:
29
+ - [ ] Run `/cost` to see current session spending
30
+ - [ ] Run `/context` to see context fill level
31
+ - [ ] Note your per-message overhead (this IS your baseline)
32
+
33
+ **Why first**: You can't optimize what you don't measure. And these are built-in, zero effort.
34
+
35
+ ---
36
+
37
+ ### 2. Check Model Routing (5 minutes)
38
+ **Target**: Confirm you have model routing instructions in CLAUDE.md
39
+
40
+ **Quick check**: Does your CLAUDE.md tell Claude which model to use for subagents? If not, add the snippet from the Model Routing section below. One line, the largest per-token cut you can get on every multi-agent workflow.
41
+
42
+ **Expected savings**: The biggest single cut on automation costs (see full breakdown below)
43
+
44
+ ---
45
+
46
+ ### 3. CLAUDE.md Consolidation
47
+ **Target**: Under 200 lines per CLAUDE.md file — Anthropic's documented guidance (code.claude.com/docs/en/memory). The ~300 lines / ~4,500 tokens figure is an internal aggressive heuristic (derived at ~15 tokens/line for prose), not an Anthropic recommendation.
48
+
49
+ **Actions**:
50
+ - [ ] Remove content that belongs in skills/commands (workflows, detailed configs)
51
+ - [ ] Remove content that duplicates MEMORY.md (paths, gotchas, personality)
52
+ - [ ] Move reference content to on-demand files (coding standards, tool configs)
53
+ - [ ] Condense personality spec to 1-2 lines (full spec can live in MEMORY.md)
54
+ - [ ] Apply tiered architecture (see below)
55
+
56
+ **Tiered Architecture Pattern**:
57
+ - **Tier 1 (always loaded, ~300 lines / ~4,500 tokens — internal heuristic, not Anthropic's under-200-lines guidance)**: Identity, critical rules, key paths, personality ONE-LINER
58
+ - **Tier 2 (skill/command, loaded on-demand)**: Workflows, domain docs, tool configs
59
+ - **Tier 3 (file reference, explicit only)**: Full guides, templates, detailed standards
60
+
61
+ **Expected savings**: 1,000-3,000+ tokens/msg (depends on starting size)
62
+
63
+ ---
64
+
65
+ ### 4. MEMORY.md Deduplication
66
+ **Target**: Remove 100% overlap with CLAUDE.md
67
+
68
+ **Actions**:
69
+ - [ ] Remove Key Paths if already in CLAUDE.md (choose ONE source of truth)
70
+ - [ ] Remove personality spec if already in CLAUDE.md
71
+ - [ ] Condense verbose operational history to current rule only
72
+ - [ ] Keep only: Learnings, corrections, habit tracking
73
+
74
+ **Expected savings**: 400-800 tokens/msg
75
+
76
+ ---
77
+
78
+ ### 5. File Exclusion Rules
79
+ **Target**: Block unnecessary files from context via `permissions.deny`
80
+
81
+ See `examples/permissions-deny-template.json` for a ready-to-use template.
82
+
83
+ Add `permissions.deny` rules to `.claude/settings.json` (project-level) or `~/.claude/settings.json` (global):
84
+
85
+ ```json
86
+ {
87
+ "permissions": {
88
+ "deny": [
89
+ "Read(./.env)",
90
+ "Read(./.env.*)",
91
+ "Read(./node_modules/**)",
92
+ "Read(./dist/**)",
93
+ "Read(./**/*.log)"
94
+ ]
95
+ }
96
+ }
97
+ ```
98
+
99
+ **Why**: Files matching deny patterns are excluded from file discovery, search, and read operations. This is the official approach (replaces deprecated `ignorePatterns`). The rules are enforced locally and are NOT injected into the prompt, so they cost zero tokens per turn.
100
+
101
+ **CAUTION**: Deny rules affect ALL tools in ALL sessions for the scope they're applied to.
102
+ - Apply at **project level** (`.claude/settings.json`) first, not global. Easier to debug when something breaks.
103
+ - **Never deny `*.sqlite` or `*.db` globally** unless you're certain no tools need database access. Many plugins (session memory, search indexes, WhatsApp) read SQLite files.
104
+ - **Credential denies** (`.env`, `*.key`) are usually safe and desired, but will break any skill that reads API keys from those files at runtime.
105
+
106
+ **TOKEN-COST CAUTION (counterintuitive)**: Deny rules save tokens only when Claude *never tries* the path. If you deny a path Claude actively wants, each blocked attempt returns feedback that accumulates in the conversation and is re-sent every turn, which **costs** tokens. Prefer narrow paths over broad globs (`Read(./logs/**)` over `Read(./**/*.log)`), only deny what Claude wouldn't read anyway, and if Claude keeps hitting "permission denied" on the same path, narrow or remove that rule.
107
+
108
+ **Expected savings**: Varies. Net positive when rules target files Claude never needs (secrets, `node_modules`, build output). Broad globs on actively-read paths can net negative.
109
+
110
+ ---
111
+
112
+ ### 6. Archive Unused Skills
113
+ **Target**: Reduce skill menu overhead
114
+
115
+ **Actions**:
116
+ - [ ] Identify duplicate skills (similar names/descriptions)
117
+ - [ ] Identify unused domain skills
118
+ - [ ] Create backup: `mkdir -p ~/.claude/_backups/skills-archived-$(date +%Y%m%d)`
119
+ - [ ] Move unused skills: `mv ~/.claude/skills/[skill-name] ~/.claude/_backups/skills-archived-*/`
120
+
121
+ A subfolder such as `_archived/` inside skills/ still loads as a namespace, so move archived skills outside skills/ entirely.
122
+
123
+ **Expected savings**: ~100 tokens per skill archived
124
+
125
+ ---
126
+
127
+ ### 7. Trim Commands
128
+ **Target**: Reduce command menu overhead
129
+
130
+ **Actions**:
131
+ - [ ] Identify rarely-used commands
132
+ - [ ] Merge similar commands if possible
133
+ - [ ] Archive to `~/.claude/_backups/commands-archived-$(date +%Y%m%d)/`
134
+
135
+ **Expected savings**: ~50 tokens per command archived
136
+
137
+ ---
138
+
139
+ ### 8. Cache Preservation (Reduce Compaction-Triggered Cache Rebuilds)
140
+ **Target**: Fewer full cache rebuilds per session
141
+
142
+ Every compaction event invalidates the prompt cache. Post-compaction, ALL context gets re-billed at full input price (not the 10% cached rate). In a heavy Opus session, a single cache rebuild can cost $2-5.
143
+
144
+ **Strategies**:
145
+ - [ ] Keep context lean (the optimizer's core job) to delay or prevent compaction
146
+ - [ ] Enable Smart Compaction (`setup-smart-compact`) to preserve state across compaction events
147
+ - [ ] For API users: Use Anthropic's Context Editing API (`clear_tool_uses_20250919` beta) to surgically evict old tool results WITHOUT triggering full compaction. This preserves the cache prefix.
148
+ - [ ] For API users: Use thinking block clearing (`clear_thinking_20251015`) to free context space without compaction
149
+ - [ ] Place strategic cache breakpoints before editable content (API users)
150
+
151
+ **Why it matters**: The LinkedIn poster's dashboard showed cache hit rates swinging from 88% to 17% after compaction. At $5/M tokens on Opus, that's the difference between $0.50/M and $5/M for the same context.
152
+
153
+ **Expected savings**: 1-3 cache rebuilds avoided per long session = $2-15 in API costs
154
+
155
+ **Compaction Timing Guide**:
156
+
157
+ Compaction timing matters as much as frequency. Compact at *phase boundaries*, not mid-task:
158
+
159
+ | When to compact | Why |
160
+ |-----------------|-----|
161
+ | After research/exploration, before execution | Bulky context served its purpose; the plan is the output |
162
+ | After debugging, before next feature | Debug traces and hypothesis state pollute unrelated work |
163
+ | After a failed approach, before retrying | Dead-end reasoning wastes context on the retry |
164
+ | After completing a milestone (commit/merge) | Natural checkpoint; fresh context for fresh work |
165
+
166
+ | When NOT to compact | Why |
167
+ |---------------------|-----|
168
+ | Mid-implementation | Losing file paths and partial state is costly to rebuild |
169
+ | Mid-debugging | Losing hypothesis state forces re-investigation |
170
+ | During multi-step operations | Breaks continuity across related steps |
171
+
172
+ Rule of thumb: if you just *produced* something (a plan, a commit, a diagnosis), compact. If you're *in the middle* of producing something, hold.
173
+
174
+ ---
175
+
176
+ ## MODEL ROUTING STRATEGY (Highest-ROI Behavioral Change)
177
+
178
+ Model routing is the single highest-ROI optimization for multi-agent workflows. It saves dollars (API users), rate limit quota (subscription users), and wall-clock time. One instruction in CLAUDE.md, 50-75% cost reduction on automation.
179
+
180
+ ### Cost Math
181
+
182
+ Check anthropic.com/pricing for current rates; this file keeps no price table because it would go stale. The shape that holds: Sonnet and Opus bill more per token than Haiku, and Haiku 5.5 charges 5x more on the part of a prompt beyond 100K tokens ($0.10/MTok up to 100K, $0.50/MTok above, per the platform pricing page). For work that needs no judgment or deep reasoning, a larger model is overspend.
183
+
184
+ ### Task-to-Model Mapping
185
+
186
+ | Task Type | Model | Examples | Why |
187
+ |-----------|-------|----------|-----|
188
+ | Data gathering | haiku | File reading, counting, scanning, listing, presence checks | No judgment needed, pattern matching only |
189
+ | Light analysis | haiku | Formatting, simple transforms, status checks, inventory | Structured output from structured input |
190
+ | Moderate reasoning | sonnet | Code review, writing, synthesis, moderate debugging, content analysis | Requires judgment + coherence |
191
+ | Complex reasoning | opus | Architecture decisions, novel problems, cross-cutting analysis, multi-file synthesis | Needs full capability, nuanced tradeoffs |
192
+
193
+ ### CLAUDE.md Snippet (Ready to Copy-Paste)
194
+
195
+ ```markdown
196
+ ## Agent Model Selection
197
+ Default subagents to haiku. Upgrade only when task requires judgment:
198
+ - haiku: file reading, data gathering, counting, scanning, formatting
199
+ - sonnet: analysis, code review, writing, moderate reasoning
200
+ - opus: architecture decisions, novel debugging, cross-cutting synthesis
201
+ ```
202
+
203
+ ### Worked Example: 5-Agent Workflow
204
+
205
+ A typical audit workflow dispatches 5 agents to scan files, count items, analyze content, and synthesize findings, each using roughly 30K input and 5K output tokens.
206
+
207
+ - **Without routing (all on the largest model)**: all five agents bill at that model's input and output rates.
208
+ - **With routing (3 data-gathering agents on Haiku, 1 on Sonnet, 1 on Opus)**: the same tokens, but the three data-gathering agents bill at the cheapest rate.
209
+
210
+ The routed mix costs a fraction of the all-largest-model run. Work out exact dollars from the current pricing page and the measured token counts (`measure.py trends` shows them), not from memory.
211
+
212
+ For subscription users (Max plan): model routing affects rate limits, not dollars. Lighter models consume fewer quota units, so routing keeps your session under rate limits longer and agents return results faster.
213
+
214
+ ### What Routing Does NOT Save
215
+
216
+ - **Context window space**: Subagents inherit the full system prompt regardless of model. A Haiku agent gets the same system prompt overhead as an Opus agent.
217
+ - **System prompt overhead**: CLAUDE.md, skills, MCP tools all load for every subagent at full size.
218
+
219
+ Routing saves **dollars** (API users), **rate limit quota** (subscription users), and **wall-clock time** (everyone). It does not reduce context window consumption. That's what the config optimizations (CLAUDE.md slimming, skill archival, etc.) address.
220
+
221
+ ### Detection: Is Your Setup Routing Efficiently?
222
+
223
+ Signs of inefficient routing:
224
+ - No model routing instructions in CLAUDE.md or MEMORY.md
225
+ - `measure.py trends` shows >70% of tokens going to Opus/Sonnet
226
+ - Subagent types include data-gathering patterns (Explore, general-purpose for file reads) running on Opus, since Explore inherits the main model
227
+ - The Settings & Advanced auditor checks this automatically (see agent-prompts.md)
228
+
229
+ ---
230
+
231
+ ## MEDIUM EFFORT (1-3 hours, save 2,000-5,000 tokens)
232
+
233
+ ### 8. MCP Server Audit
234
+ **Target**: Remove broken/unused MCP servers and their deferred tool listings
235
+
236
+ **First, check Tool Search status**:
237
+ - If ToolSearch is available in your session, Tool Search is active. Unset, Claude Code defers all MCP tools by default; it loads them upfront on some cloud-provider models and when `ANTHROPIC_BASE_URL` points to a non-first-party host
238
+ - Tool Search means definitions are deferred (~15 tokens per tool name in the menu, not 300-850 for full definitions)
239
+ - If Tool Search is NOT active, enabling it is the single biggest MCP optimization you can make
240
+
241
+ **How to audit**:
242
+ 1. Check Claude Code config: `~/.claude/settings.json` (primary, mcpServers key)
243
+ 2. Check Desktop config: `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS)
244
+ 3. Check plugin configs: `~/.claude/plugins/` (plugins can bundle MCP servers)
245
+ 4. Count deferred tools in current session (system prompt shows count)
246
+
247
+ **Identify**:
248
+ - [ ] Broken servers (auth failed, deprecated APIs)
249
+ - [ ] Duplicate tools across servers AND plugins (same tool from multiple sources)
250
+ - [ ] Rarely-used servers (domain-specific, >10 tools, used <1x/month)
251
+ - [ ] Plugin-bundled MCP that duplicates standalone servers
252
+
253
+ **Expected savings**: ~15 tokens per deferred tool removed (with Tool Search active). Larger savings from removing full server instructions (~50-100 tokens per server).
254
+
255
+ ---
256
+
257
+ ### 9. Install qmd for Local Search
258
+ **Target**: 60-95% reduction on code exploration tasks
259
+
260
+ **Install**:
261
+ ```bash
262
+ # Option 1: npm
263
+ npm install -g qmd
264
+
265
+ # Option 2: bun
266
+ bun install -g github:tobi/qmd
267
+ ```
268
+
269
+ **Index your codebase**:
270
+ ```bash
271
+ qmd index /path/to/codebase
272
+ ```
273
+
274
+ **Add to CLAUDE.md** (1 line):
275
+ ```
276
+ Before reading files, always try `qmd search [query]` or `qmd query [question]` first.
277
+ ```
278
+
279
+ **Why**: Pre-indexes your files with hybrid search (keyword + vector). Claude queries the index instead of reading every file.
280
+
281
+ **Expected savings**: 60-95% on exploration sessions
282
+
283
+ ---
284
+
285
+ ### 10. Migrate CLAUDE.md Content to Skills
286
+ **Target**: Move domain-specific content to on-demand loading
287
+
288
+ **Pattern**: Skills load ~100 tokens at startup (frontmatter only). Full content loads on-demand. Only the short frontmatter sits in every message; the body loads when the skill is used, whereas CLAUDE.md content loads every time.
289
+
290
+ **How**:
291
+ 1. Create skill: `mkdir ~/.claude/skills/[name]`
292
+ 2. Write SKILL.md with content
293
+ 3. Remove from CLAUDE.md
294
+ 4. Add 1-line reference in CLAUDE.md: "Full config: see /[name] skill"
295
+
296
+ **Expected savings**: ~500-1,000 tokens (depends on volume moved)
297
+
298
+ ---
299
+
300
+ ## DEEP OPTIMIZATION (power users)
301
+
302
+ ### 11. Session Folder Pattern (Architecture Change)
303
+ **Target**: Prevent orchestrator context overflow
304
+
305
+ **Problem**: Multi-agent workflows load all agent outputs into main context. At 5-10K tokens per agent x 5 agents = 25-50K tokens in orchestrator.
306
+
307
+ **Solution**:
308
+ 1. Orchestrator creates a project-local session folder: `./.agent-sessions/[task-name]-$(date +%Y%m%d-%H%M%S)/` (add `.agent-sessions/` to `.gitignore`)
309
+ 2. Agents write findings to files in session folder
310
+ 3. Orchestrator receives ONLY: "Agent X completed, output at {path}"
311
+ 4. Synthesis agent reads files directly
312
+ 5. Orchestrator does not read full agent outputs, which is what keeps its context small
313
+
314
+ **When to use**: Any task with 3+ subagents or agents producing >5K tokens output each.
315
+
316
+ ---
317
+
318
+ ### 12. Progressive Disclosure Pattern
319
+ **Target**: Load context incrementally, not all at once
320
+
321
+ **Pattern**:
322
+ - Phase 1: Load minimal context (identity, current state)
323
+ - Phase 2: Ask clarifying questions
324
+ - Phase 3: Load relevant context based on answers
325
+ - Phase 4: Execute
326
+
327
+ **Expected savings**: 30-50% on large context tasks
328
+
329
+ ---
330
+
331
+ ## BEHAVIORAL CHANGES (Free, highest cumulative impact)
332
+
333
+ These save more than config changes over a full day of usage.
334
+
335
+ ### 13. Extended Thinking Awareness (Informational)
336
+ **Target**: Understand thinking token costs (no action needed for most users)
337
+
338
+ **What it is**: When extended thinking is enabled, Claude generates "thinking" tokens (output-priced, more expensive than input). Claude's built-in **adaptive thinking** automatically adjusts thinking depth based on task complexity, using more for hard problems and less for simple ones.
339
+
340
+ **Why this is informational, not prescriptive**: If you chose Opus, you chose it for deep reasoning. The optimizer respects that choice. "Deep reasoning" is subjective and task-dependent, so we don't recommend disabling or manually toggling thinking. Claude's adaptive system handles this better than manual rules.
341
+
342
+ **Actions**:
343
+ - [ ] Use `/cost` to see thinking token breakdown (awareness only)
344
+ - [ ] If `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` is set, understand it forces fixed thinking budget regardless of task complexity
345
+
346
+ **What the optimizer does**: Reports thinking token usage for cost awareness. Does NOT recommend disabling or reducing thinking. Your model choice is your intent.
347
+
348
+ ---
349
+
350
+ ### 14. /compact and /clear Hygiene
351
+ **Target**: Keep context lean, extend productive session length
352
+
353
+ **Rules**:
354
+ - [ ] Compact earlier than the default when sessions run long: on 1M models auto-compact fires at about 967K tokens, and on 200K models near the context limit. Set a lower window with `/autocompact <n>` (100K-1M, saved per model; `/autocompact auto` restores the tuned window) or the `autoCompactWindow` setting. `measure.py compact-advice` estimates from your own history whether an earlier window pays off
355
+ - [ ] Run `/compact` at natural breakpoints (after commit, after feature)
356
+ - [ ] Run `/clear` between unrelated topics (cheaper than compact, no summary overhead)
357
+ - [ ] Check `/context` periodically to know your fill level
358
+ - [ ] If `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is set, confirm it is intentional: it is the percent of the compact window used when compaction fires, so a low value compacts early (doctor reports it and never removes it)
359
+
360
+ **Measured**: Community measurements show /compact can reduce conversation history from 77K to 4K tokens (18x reduction), freeing context from ~50% to 90%.
361
+
362
+ **Note**: /clear is often better than /compact when switching tasks. Compacting preserves conversation context as a summary. Clearing is cheaper and gives you a completely fresh window.
363
+
364
+ ---
365
+
366
+ ### 15. Batch Requests
367
+ **Target**: Reduce context re-sends
368
+
369
+ **DON'T**:
370
+ ```
371
+ "Change button color" -> response -> "Make it bigger" -> response -> "Add shadow"
372
+ (3 messages = 3 full context sends)
373
+ ```
374
+
375
+ **DO**:
376
+ ```
377
+ "Change button color to navy, make it bigger (48px), add subtle shadow"
378
+ (1 message = 1 context send)
379
+ ```
380
+
381
+ **Expected savings**: 2x-3x on multi-step tasks
382
+
383
+ ---
384
+
385
+ ### 16. Skip Confirmations
386
+ **Target**: Reduce message count
387
+
388
+ **DON'T**:
389
+ ```
390
+ User: "Thanks!"
391
+ Claude: "You're welcome!"
392
+ (Claude just re-sent full context for a courtesy)
393
+ ```
394
+
395
+ **Community stat**: One analysis showed 40% of tokens were confirmations and "looks good" messages.
396
+
397
+ ---
398
+
399
+ ### 17. Test Locally, Not Through Claude
400
+ **Target**: Avoid expensive test output in chat
401
+
402
+ **DON'T**: Let Claude run tests and dump 5,000 tokens of output.
403
+
404
+ **DO**: Run `pytest tests/` locally and paste any failures.
405
+
406
+ **Expected savings**: 5,000-50,000 tokens per test run
407
+
408
+ ---
409
+
410
+ ## ADVANCED (Power Users)
411
+
412
+ ### 18. Prompt Caching Awareness
413
+ **Target**: Understand what caching does and doesn't fix
414
+
415
+ **Confirmed behavior**: Prompt caching is active by default in Claude Code. The status line input carries a `prompt_cache` object (TTL, hit ratio, expiry) so you can watch it.
416
+
417
+ **Pricing**:
418
+ - Cache reads: 0.1x base input, 90% cheaper than normal input
419
+ - Cache writes: 1.25x base input for the 5-minute cache, 2x for the 1-hour cache
420
+ - TTL: the main conversation gets 1 hour on subscription plans and 5 minutes on usage credits, an API key or a cloud provider; subagents get 5 minutes even on a subscription. The timer resets with each cache hit. `promptCacheTtl`, `subagentPromptCacheTtl` and per-agent `experimental.cacheTtl` (frontmatter, v2.1.248+) change this; see the cache controls table in `token-coach/references/quick-reference.md`
421
+
422
+ **What gets cached**: System prompt (including CLAUDE.md), tool definitions, conversation history prefix up to last cache breakpoint.
423
+
424
+ **What breaks the cache** (avoid these mid-session):
425
+ - Adding/removing an MCP tool
426
+ - Switching models
427
+ - Editing CLAUDE.md mid-session
428
+ - Putting timestamps in system prompt
429
+ - Any change to content before a cache breakpoint
430
+
431
+ **What caching does NOT fix**:
432
+ - Context window SIZE (cached tokens still occupy your window)
433
+ - Rate limit quotas (cache reads count toward subscription limits)
434
+ - Quality degradation as the window fills (lost-in-the-middle)
435
+ - Multi-agent amplification (each subagent inherits full overhead)
436
+
437
+ **Optimization**: Structure CLAUDE.md so stable sections come FIRST, volatile sections LAST. This maximizes cache prefix length.
438
+
439
+ See `examples/claude-md-optimized.md` for the pattern.
440
+
441
+ ---
442
+
443
+ ### 19. Multi-Project CLAUDE.md Strategy
444
+ **Target**: Different configs for different projects
445
+
446
+ **Pattern**:
447
+ - Global `~/.claude/CLAUDE.md`: Identity, personality, core rules (~2,000-3,000 tokens, under 200 lines)
448
+ - Project `[repo]/CLAUDE.md`: Project-specific context, tech stack, conventions (~1,000-1,500 tokens, under 100 lines)
449
+
450
+ **Why**: Global CLAUDE.md loads for ALL projects. Project CLAUDE.md loads only in that directory. Keep global minimal.
451
+
452
+ ---
453
+
454
+ ### 20. Hook-Based Optimizations
455
+ **Target**: Pre/post-session token management
456
+
457
+ See `examples/hooks-starter.json` for a ready-to-use template.
458
+
459
+ **Key hooks**:
460
+ - **PreCompact**: Guide compaction to preserve critical context
461
+ - **PostToolUse**: Trigger auto-formatters, save output tokens
462
+
463
+ ---
464
+
465
+ ### 21. Smart Compaction
466
+ **Target**: Preserve decisions, context, and state across compaction events
467
+
468
+ **What it does**: Captures structured session state before compaction fires, then restores the critical pieces after compaction completes. Decisions, error-fix sequences, agent state, and modified files survive the lossy compaction process.
469
+
470
+ **Actions**:
471
+ - [ ] Install Smart Compaction hooks: `python3 $MEASURE_PY setup-smart-compact --dry-run` (preview first)
472
+ - [ ] Run `python3 $MEASURE_PY setup-smart-compact` to install
473
+ - [ ] Generate project-specific Compact Instructions: `python3 $MEASURE_PY compact-instructions`
474
+ - [ ] Add the generated instructions to `.claude/settings.json` under `compactInstructions`
475
+
476
+ **What the hooks do**:
477
+ - **PreCompact**: Captures session state (decisions, files, errors, agent state) to a markdown checkpoint
478
+ - **SessionStart** (after compact): Injects the checkpoint back as context, filling gaps left by compaction
479
+ - **Stop/SessionEnd**: Saves a checkpoint when the session ends, enabling continuity in the next session
480
+
481
+ **Checkpoints stored in**: the `token-optimizer/checkpoints/` folder under the runtime's data directory, auto-cleaned (default: 5 newest per session, 7 days, 400 overall; tune with `TOKEN_OPTIMIZER_CHECKPOINT_PER_SESSION`, `TOKEN_OPTIMIZER_CHECKPOINT_RETENTION_DAYS`, `TOKEN_OPTIMIZER_CHECKPOINT_RETENTION_MAX`)
482
+
483
+ **Expected impact**: Preserves 3-10 key decisions per compaction. Prevents "what were we doing?" restart loops after compaction. Enables session continuity across /clear and session death.
484
+
485
+ ---
486
+
487
+ ### 22. Context Quality Monitoring
488
+ **Target**: Measure content quality, not just quantity
489
+
490
+ **What it does**: Analyzes your session JSONL and scores how useful your context content is. A session at 60% with clean, relevant content performs differently from 60% stuffed with stale reads and duplicate injections.
491
+
492
+ **Actions**:
493
+ - [ ] Run `python3 $MEASURE_PY quality` on your current or recent session
494
+ - [ ] Check your score: 85+ is excellent, 70-84 good, 50-69 degraded, <50 critical
495
+ - [ ] Act on specific issues: stale reads, bloated results, duplicate reminders
496
+
497
+ **Quality signals**:
498
+ - Stale read ratio (files read then later edited, making the read content outdated)
499
+ - Tool result bloat (large results never referenced again)
500
+ - Duplicate content (repeated system reminders)
501
+ - Compaction depth (each compaction = information loss)
502
+ - Decision density (ratio of substantive to overhead exchanges)
503
+ - Agent efficiency (dispatch cost vs useful result size)
504
+
505
+ **Expected impact**: Quantifies when to /compact (score dropping) and validates that smart compaction is working (score improves post-compact).
506
+
507
+ ---
508
+
509
+ ## MONITORING & MEASUREMENT
510
+
511
+ ### 23. Baseline Your Usage
512
+
513
+ ```bash
514
+ # Measure current state
515
+ python3 $MEASURE_PY report
516
+
517
+ # Save snapshot before optimizing
518
+ python3 $MEASURE_PY snapshot before
519
+
520
+ # After optimization
521
+ python3 $MEASURE_PY snapshot after
522
+
523
+ # Compare
524
+ python3 $MEASURE_PY compare
525
+ ```
526
+
527
+ Also track with `/cost` at end of each session and `measure.py trends` for historical data. The SessionEnd hook auto-collects usage into a local SQLite database.
528
+
529
+ ---
530
+
531
+ ### 24. Regular Audits
532
+ **Quarterly** (every 3 months):
533
+ - [ ] Re-run `/token-optimizer` (skills accumulate, CLAUDE.md grows back)
534
+ - [ ] Re-check MCP servers (you add new ones)
535
+
536
+ **Why**: Optimization entropy. Without discipline, configs grow back to original size.
537
+
538
+ ---
539
+
540
+ ## TOKEN FLOW REFERENCE
541
+
542
+ **Every message loads this stack** (with Tool Search active, the default):
543
+ ```
544
+ ├─ Core system prompt: ~3,000 tokens (fixed)
545
+ ├─ Built-in tools (18+): ~12,000 tokens (fixed)
546
+ ├─ MCP (Tool Search + names): ~500 + ~15 tokens per deferred tool
547
+ ├─ MCP server instructions: ~50-100 tokens per server
548
+ ├─ Skills frontmatter: ~100 tokens x skill count
549
+ ├─ Commands frontmatter: ~50 tokens x command count
550
+ ├─ CLAUDE.md (global): Variable (Anthropic guidance: under 200 lines; internal heuristic ~4,500 tokens / ~300 lines)
551
+ ├─ Project CLAUDE.md: Variable (target: <300 tokens)
552
+ ├─ MEMORY.md: Variable (200-line auto-load cap, ~3,000 tokens)
553
+ ├─ System reminders: ~2,000 tokens (auto-injected, variable)
554
+ └─ Message + history: Variable
555
+ ```
556
+
557
+ **Irreducible floor**: ~15K tokens even with zero config (no CLAUDE.md, no skills, no MCP). This is core system + built-in tools alone.
558
+ **Baseline (well-optimized)**: ~21K tokens first message
559
+ **Power user (unoptimized)**: ~43K tokens first message
560
+
561
+ ---
562
+
563
+ ## WORKED EXAMPLE: Power User Optimization
564
+
565
+ **Before** (unaudited power user, 3+ months of use, Tool Search active; the percentages show both common window sizes because the same tokens matter far more on a 200K window):
566
+ - Core system + built-in tools: ~15,000 tokens (fixed)
567
+ - MCP tools: ~9,000 tokens (deferred tools + server instructions)
568
+ - Skills (~60): ~6,000 tokens
569
+ - Commands (~60): ~3,000 tokens
570
+ - CLAUDE.md: ~3,500 tokens (grown organically, never trimmed)
571
+ - MEMORY.md: ~3,500 tokens (duplicates CLAUDE.md content)
572
+ - System reminders: ~3,000 tokens (no permissions.deny rules)
573
+ - **Total consumed: ~43,000 tokens/msg (4% of a 1M window, 22% of a 200K window)**
574
+
575
+ **Config changes** (what the optimizer implements):
576
+ 1. CLAUDE.md: 3,500 -> 2,500 tokens (progressive disclosure, under 300-line target)
577
+ 2. MEMORY.md: 3,500 -> 2,000 tokens (dedup with CLAUDE.md, under 200-line cap)
578
+ 3. Skills: 60 -> 30 (30 archived, ~3,000 tokens saved)
579
+ 4. Commands: 60 -> 25 (35 archived, ~1,800 tokens saved)
580
+ 5. MCP: pruned unused servers (~3,000 tokens saved)
581
+ 6. permissions.deny rules added (~2,000 tokens saved from file exclusion)
582
+ - **Config savings: ~12,300 tokens/msg (29% reduction in consumed overhead)**
583
+ - **After consumed: ~30,700 tokens/msg (3% of a 1M window, 15% of a 200K window)**
584
+
585
+ **Behavioral changes** (what the optimizer teaches):
586
+ - Agent model selection (lighter tier for data gathering): a large share of automation cost
587
+ - /compact at natural breakpoints: replaces a long history with a short summary
588
+ - Extended thinking awareness: variable, potentially largest single factor
589
+ - Batching requests: 2-3x on multi-step tasks
590
+ - /clear between topics: prevents stale context accumulation
591
+ - **Behavioral savings: extend productive session length, reduce compaction cycles, improve output quality**
592
+
593
+ The config changes shrink your per-message overhead. The behavioral changes compound across every message, every session, every day. Together they are the full picture.
594
+
595
+ ---
596
+
597
+ ## ENVIRONMENT VARIABLES & SETTINGS (Tune your setup)
598
+
599
+ These are settings that affect token usage and context behavior. The optimizer audits current values and explains tradeoffs.
600
+
601
+ ### 25. MAX_THINKING_TOKENS (default: unset)
602
+ **Target**: Understand thinking token budget
603
+
604
+ **What it is**: A fixed token budget for extended thinking, capped one token below the request's max output tokens and never below 1,024. When unset, models with adaptive reasoning (Sonnet 5 and later, Haiku 5.5, Opus 4.7 and later, Fable) choose their own thinking depth; other models use the cap. Thinking uses output-priced tokens.
605
+
606
+ **Actions**:
607
+ - [ ] Check current value: `CLAUDE_CODE_MAX_THINKING_TOKENS` in settings.json env block
608
+ - [ ] Observe thinking patterns in `/cost` output (thinking tokens are listed separately)
609
+ - [ ] Consider if thinking budget is being spent on simple tasks (file renames and quick edits do not need a large thinking budget)
610
+
611
+ **What the optimizer does**: Reports current value. Surfaces patterns where thinking budget was clearly wasted (e.g., thousands of thinking tokens on a file rename). Does NOT suggest reducing it for complex reasoning tasks.
612
+
613
+ ---
614
+
615
+ ### 26. CLAUDE_CODE_MAX_OUTPUT_TOKENS (default varies by model)
616
+ **Target**: Understand output token budget
617
+
618
+ **What it is**: Maximum tokens Claude generates per response. Defaults and caps vary by model, and Claude Code lowers a value above the model's cap to the cap. Raising it reduces the effective context window available before auto-compaction triggers.
619
+
620
+ **Actions**:
621
+ - [ ] Check current value in settings.json env block
622
+ - [ ] Note if you've seen truncation issues
623
+ - [ ] Default is fine for most users
624
+
625
+ **What the optimizer does**: Reports current value. Notes if user has hit truncation issues.
626
+
627
+ ---
628
+
629
+ ### 27. MAX_MCP_OUTPUT_TOKENS (default: 25,000)
630
+ **Target**: Understand MCP tool output limits
631
+
632
+ **What it is**: Maximum tokens a single MCP tool call can return. Tools returning max-length output may be sending more data than needed.
633
+
634
+ **Actions**:
635
+ - [ ] Check if any MCP tools consistently return very large outputs
636
+ - [ ] Consider if those tools have filtering options to reduce output size
637
+
638
+ **What the optimizer does**: Reports current value. Flags MCP tools that consistently return near-max output (potential tuning opportunity).
639
+
640
+ ---
641
+
642
+ ### 28. BASH_MAX_OUTPUT_LENGTH (default: 30,000 characters, max 150,000)
643
+ **Target**: Control bash output token consumption
644
+
645
+ **What it is**: Limits how much stdout/stderr from Bash tool calls gets captured into context. Verbose test runners or build logs can dump thousands of tokens.
646
+
647
+ **Actions**:
648
+ - [ ] Check if bash output is frequently truncated (might need raising)
649
+ - [ ] Check if verbose commands are filling context unnecessarily (might need lowering)
650
+
651
+ **What the optimizer does**: Reports current value. Flags if bash output appears frequently truncated.
652
+
653
+ ---
654
+
655
+ ### 29. ENABLE_TOOL_SEARCH (default: unset, MCP tools deferred)
656
+ **Target**: Verify Tool Search is active (the largest MCP saving)
657
+
658
+ **What it is**: Tool Search defers MCP tool definitions until actually needed. Instead of loading 300-850 tokens per tool upfront, only ~15 tokens per tool name is loaded. This is the single biggest MCP optimization.
659
+
660
+ **Actions**:
661
+ - [ ] Verify Tool Search is active in your session (look for ToolSearch in available tools)
662
+ - [ ] If not active, check the Claude Code version, the provider, and whether `ANTHROPIC_BASE_URL` points to a non-first-party host
663
+ - [ ] `true` always defers, `false` loads everything upfront, `auto` loads upfront only when tool definitions fit within 10% of context, and `auto:N` sets a custom percentage such as `auto:5`
664
+
665
+ **What the optimizer does**: Reports if Tool Search is active. If not, explains what enabling it saves. This is flagged as high priority if missing.
666
+
667
+ ---
668
+
669
+ ### 30. CLAUDE_CODE_DISABLE_AUTO_MEMORY (default: not set)
670
+ **Target**: Audit auto-memory content quality, not the feature itself
671
+
672
+ **What it is**: Auto-memory writes learnings to MEMORY.md automatically. This is a valuable feature. The optimization target is the CONTENT it produces, not the feature.
673
+
674
+ **Actions**:
675
+ - [ ] Check MEMORY.md for duplicate entries (auto-memory sometimes writes the same insight twice)
676
+ - [ ] Check for entries that duplicate CLAUDE.md content
677
+ - [ ] Check for stale entries (rules that no longer apply)
678
+ - [ ] Condense verbose entries to current rule only
679
+
680
+ **What the optimizer does**: Audits MEMORY.md for duplicates, stale entries, and redundancy with CLAUDE.md. Cleans up the CONTENT. Does NOT suggest disabling the feature.
681
+
682
+ ---
683
+
684
+ ### 31. CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING (default: not set)
685
+ **Target**: Understand what adaptive thinking does
686
+
687
+ **What it is**: Set to `1`, it turns off adaptive reasoning on Opus 4.6 and Sonnet 4.6 and falls back to the fixed budget in `MAX_THINKING_TOKENS`. It has no effect on Sonnet 5 and later, Haiku 5.5, Opus 4.7 and later, or Fable, which always use adaptive reasoning.
688
+
689
+ **Actions**:
690
+ - [ ] Check if set in settings.json env block
691
+ - [ ] Understand that disabling this means fixed thinking budget regardless of task
692
+
693
+ **What the optimizer does**: Reports if set. Explains what it does. No recommendation to disable.
694
+
695
+ ---
696
+
697
+ ### 32. CLAUDE_AUTOCOMPACT_PCT_OVERRIDE
698
+ **Documented, and never removed by Token Optimizer.** It is the percent of the compact window already used when auto-compaction fires: a lower value compacts earlier, and it cannot raise the threshold. Doctor explains the current value and flags one low enough to compact very early; the user decides.
699
+
700
+ ---
701
+
702
+ ## ANTI-PATTERNS
703
+
704
+ - Don't add content to CLAUDE.md without asking "Can this be a skill or reference file?"
705
+ - Don't duplicate rules between CLAUDE.md and MEMORY.md
706
+ - Don't archive skills to subfolder inside skills/ (still loads)
707
+ - Don't use the largest model for plain file reading (see the Model Routing section)
708
+ - Don't wait for auto-compact when a session is clearly past a natural breakpoint (compact manually, or set an earlier window with `/autocompact`)
709
+ - Don't paste full error logs (paste relevant lines only)
710
+ - Don't run tests through Claude (run locally, paste failures only)
711
+ - Don't dump everything in global CLAUDE.md (project-specific goes in project CLAUDE.md)
712
+ - Be aware that extended thinking uses output-priced tokens (Claude's adaptive thinking manages depth automatically)
713
+ - Don't assume MCP overhead is huge (Tool Search defers definitions by default)
714
+ - Don't quote dollar savings to subscription users (talk context budget, not money)