@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,629 @@
1
+ # Token Flow Architecture: How Claude Code Loads Context
2
+
3
+ Understanding how tokens flow through Claude Code is critical for optimization. This document maps the complete loading sequence.
4
+
5
+ ---
6
+
7
+ ## Contents
8
+
9
+ - [The Loading Sequence (Every Message)](#the-loading-sequence-every-message)
10
+ - [Token Budget Breakdown (Typical Setup)](#token-budget-breakdown-typical-setup)
11
+ - [What You Can Control (Optimization Targets)](#what-you-can-control-optimization-targets)
12
+ - [Progressive Loading (How Skills/Commands Work)](#progressive-loading-how-skillscommands-work)
13
+ - [The Hidden Tax: System Reminders](#the-hidden-tax-system-reminders)
14
+ - [Subagent Context Inheritance](#subagent-context-inheritance)
15
+ - [Context Window Lifecycle](#context-window-lifecycle)
16
+ - [The 1,000 Token Rule](#the-1000-token-rule)
17
+ - [Caching Behavior (Prompt Caching)](#caching-behavior-prompt-caching)
18
+ - [Real Cost: Context Budget, Not Dollars](#real-cost-context-budget-not-dollars)
19
+ - [Model Cost Comparison (Why Routing Matters)](#model-cost-comparison-why-routing-matters)
20
+ - [Optimization Priority Matrix](#optimization-priority-matrix)
21
+ - [Real-World Example: Unaudited Power User (Tool Search Active)](#real-world-example-unaudited-power-user-tool-search-active)
22
+ - [Additional Config Features (Token Impact)](#additional-config-features-token-impact)
23
+ - [Cache Economics and Compaction](#cache-economics-and-compaction)
24
+ - [Further Reading](#further-reading)
25
+
26
+ ---
27
+
28
+ ## The Loading Sequence (Every Message)
29
+
30
+ When you send a message to Claude Code, this is what loads:
31
+
32
+ ```
33
+ MESSAGE SEND
34
+ |
35
+ +-----------------------------------------------------+
36
+ | PHASE 1: Core System (FIXED, ~15,000 tokens) |
37
+ |----------------------------------------------------|
38
+ | - System prompt base ~3,000 tokens |
39
+ | - Built-in tools (18+) ~12,000 tokens |
40
+ | Read, Write, Edit, Bash, Grep, Glob, Task, etc. |
41
+ | (Source: the /context output; varies by build) |
42
+ | |
43
+ | NOTE: The "system prompt" is often reported as |
44
+ | ~3,000 tokens. But built-in tool definitions |
45
+ | (~12,000 tokens) load alongside it every message. |
46
+ | The real fixed floor is ~15,000, not ~3,000. |
47
+ | Posts quoting the base prompt alone understate |
48
+ | overhead by 5x. |
49
+ +-----------------------------------------------------+
50
+ |
51
+ +-----------------------------------------------------+
52
+ | PHASE 2: MCP Tools (VARIABLE) |
53
+ |----------------------------------------------------|
54
+ | Tool Search (on by default): |
55
+ | - ToolSearch tool def ~500 tokens |
56
+ | - Deferred tool names ~15 tokens each |
57
+ | - Full definitions load on use only |
58
+ | - Auto-triggers when MCP tools exceed 10% of context |
59
+ | - 85% reduction vs pre-Tool-Search (Anthropic data) |
60
+ | |
61
+ | WITHOUT Tool Search (old versions, <10K threshold): |
62
+ | - Full definitions upfront ~300-850 tokens each |
63
+ | - 50 tools = ~25,000-42,500 tokens |
64
+ | |
65
+ | WITH Tool Search (current default): |
66
+ | - 50 deferred tools = ~1,250 tokens |
67
+ | - 100 deferred tools = ~2,000 tokens |
68
+ | - 178 deferred tools = ~3,170 tokens |
69
+ +-----------------------------------------------------+
70
+ |
71
+ +-----------------------------------------------------+
72
+ | PHASE 3: Skills & Commands (VARIABLE) |
73
+ |----------------------------------------------------|
74
+ | - Skills: frontmatter only ~100 tokens each |
75
+ | (full SKILL.md loads on invoke) |
76
+ | - Commands: frontmatter only ~50 tokens each |
77
+ | |
78
+ | Example: |
79
+ | - 54 skills = ~5,400 tokens |
80
+ | - 29 commands = ~1,450 tokens |
81
+ +-----------------------------------------------------+
82
+ |
83
+ +-----------------------------------------------------+
84
+ | PHASE 4: User Configuration (VARIABLE) |
85
+ |----------------------------------------------------|
86
+ | ALWAYS LOADED (every message): |
87
+ | - ~/.claude/CLAUDE.md ~2,000-5,000 tokens |
88
+ | (Anthropic: under 200 lines; ~300/~4,500 internal)|
89
+ | - ~/.claude/projects/.../ ~1,500-3,000 tokens |
90
+ | MEMORY.md (200-line auto-load cap) |
91
+ | - [repo]/CLAUDE.md ~10-1,500 tokens |
92
+ | |
93
+ | ** OPTIMIZATION TARGET: These load EVERY message |
94
+ +-----------------------------------------------------+
95
+ |
96
+ +-----------------------------------------------------+
97
+ | PHASE 5: System Reminders (AUTO-INJECTED) |
98
+ |----------------------------------------------------|
99
+ | - Modified files warning ~500-3,000 tokens |
100
+ | - Budget warnings ~100 tokens |
101
+ | - Tool-specific reminders Variable |
102
+ | |
103
+ | Can't control, but permissions.deny rules help |
104
+ +-----------------------------------------------------+
105
+ |
106
+ +-----------------------------------------------------+
107
+ | PHASE 6: Conversation History |
108
+ |----------------------------------------------------|
109
+ | - Your message Variable |
110
+ | - Previous messages Variable |
111
+ | (up to context limit) |
112
+ +-----------------------------------------------------+
113
+ |
114
+ CLAUDE PROCESSES
115
+ |
116
+ RESPONSE GENERATED
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Token Budget Breakdown (Typical Setup)
122
+
123
+ **Note**: Percentages assume a 1M-token context window, the default on current Claude models (Haiku 5.5, Sonnet 5+, Opus 4.7+; Sonnet 4.6 and Opus 4.6 reach 1M only through their `[1m]` variants). On a 200K window, these same absolute numbers represent 5x higher percentages (multiply by 5).
124
+
125
+ ### Well-Optimized Setup (~23K baseline, Tool Search active)
126
+ ```
127
+ Core system + tools: 15,000 tokens
128
+ MCP (ToolSearch + 1,000 tokens (500 base + ~30 tools x 15)
129
+ deferred names):
130
+ Skills (20): 2,000 tokens
131
+ Commands (10): 500 tokens
132
+ CLAUDE.md: 2,500 tokens (~170 lines, well under 200-line Anthropic guidance)
133
+ MEMORY.md: 1,500 tokens (~100 lines, well under 200-line cap)
134
+ System reminders: 1,000 tokens
135
+ ---------------------------------
136
+ BASELINE: ~23,500 tokens (2.4% of 1M)
137
+ ```
138
+
139
+ ### Unaudited Setup (~43K consumed, Tool Search active)
140
+ ```
141
+ Core system + tools: 15,000 tokens
142
+ MCP tools: 9,000 tokens (deferred tools + server instructions)
143
+ Skills (60): 6,000 tokens
144
+ Commands (60): 3,000 tokens
145
+ CLAUDE.md: 3,500 tokens (250 lines. A 700-line file = 12K)
146
+ MEMORY.md: 3,500 tokens
147
+ System reminders: 3,000 tokens (no permissions.deny rules)
148
+ ---------------------------------
149
+ CONSUMED: ~43,000 tokens (4.3% of 1M)
150
+ = UNAVAILABLE: ~43,000 tokens (4.3% of 1M), plus auto-compact headroom
151
+ ```
152
+
153
+ **Difference**: ~19,500 tokens consumed per message = 1.8x overhead vs optimized
154
+ **Note**: Before Tool Search, MCP alone could add 40-80K tokens; Tool Search (on by default) reduced this by ~85%. This "unaudited" baseline is a power user who has been adding to their config for 3+ months without auditing. When auto-compact is enabled (the default), Claude Code reserves extra headroom inside the compact window, so the true unavailable figure is higher still; on 1M models compaction fires at about 967K tokens by default.
155
+
156
+ ---
157
+
158
+ ## What You Can Control (Optimization Targets)
159
+
160
+ ### HIGH IMPACT (Always Loaded)
161
+
162
+ | Component | Control Level | Optimization Method |
163
+ |-----------|---------------|---------------------|
164
+ | **CLAUDE.md** | Full | Slim to under 200 lines (Anthropic guidance; code.claude.com/docs/en/memory). Internal heuristic: ~300 lines / ~4,500 tokens. Move content to skills. Apply tiered architecture. |
165
+ | **MEMORY.md** | Full | Stay under 200-line auto-load cap (~3,000 tokens). Remove duplication with CLAUDE.md. |
166
+ | **Project CLAUDE.md** | Full | Keep project-specific only. No duplication with global. |
167
+
168
+ ### MEDIUM IMPACT (Menu Overhead)
169
+
170
+ | Component | Control Level | Optimization Method |
171
+ |-----------|---------------|---------------------|
172
+ | **Skills count** | Full | Archive unused skills. Merge duplicates. |
173
+ | **Commands count** | Full | Archive unused commands. Merge similar ones. |
174
+ | **MCP servers** | Full | Disable broken/unused servers. Tool Search already defers definitions. |
175
+
176
+ ### LOW IMPACT (Can't Control Directly)
177
+
178
+ | Component | Control Level | Optimization Method |
179
+ |-----------|---------------|---------------------|
180
+ | **Core system** | None | Fixed by Claude Code. Accept it. |
181
+ | **System reminders** | Partial | Use `permissions.deny` rules to exclude files from context. |
182
+ | **Tool definitions** | Partial | Tool Search defers most. Can't reduce further without disabling tools. |
183
+
184
+ ---
185
+
186
+ ## Progressive Loading (How Skills/Commands Work)
187
+
188
+ ### Skills
189
+ ```
190
+ AT STARTUP (always loaded):
191
+ ---
192
+ name: morning
193
+ description: "Your daily briefing..."
194
+ ---
195
+ (~100 tokens for frontmatter)
196
+
197
+ WHEN INVOKED (/morning):
198
+ [Full SKILL.md content loads]
199
+ [Reference files load if Read calls made]
200
+ (+5,000-20,000 tokens depending on skill)
201
+ ```
202
+
203
+ **Implication**: Skills are 98% cheaper than CLAUDE.md for same content.
204
+
205
+ ### Commands
206
+ ```
207
+ AT STARTUP (always loaded):
208
+ Namespace listing + description
209
+ (~50 tokens per command)
210
+
211
+ WHEN INVOKED (/my-command):
212
+ [Command executes, may load files]
213
+ (Variable additional tokens)
214
+ ```
215
+
216
+ ---
217
+
218
+ ## The Hidden Tax: System Reminders
219
+
220
+ System reminders are auto-injected by Claude Code when certain conditions occur:
221
+
222
+ ### When They Trigger
223
+ | Condition | Reminder | Token Cost |
224
+ |-----------|----------|------------|
225
+ | You edited a file | "File was modified" warning | ~500-2,000 |
226
+ | Approaching budget | Budget warning | ~100 |
227
+ | Reading malware-like code | Security warning | ~200 |
228
+ | Tool-specific context | Tool guidance | ~100-500 |
229
+
230
+ ### How to Reduce
231
+ - **Use `permissions.deny`** (narrowly): Exclude files Claude never needs (secrets, `node_modules`, build output). Keep rules narrow, a broad deny on a path Claude actively wants causes repeated "permission denied" feedback that accumulates in context and costs tokens.
232
+ - **Don't edit unnecessary files**: Each edit = potential injection
233
+ - **Be aware**: You can't disable these entirely, but you can avoid triggering them
234
+
235
+ ---
236
+
237
+ ## Subagent Context Inheritance
238
+
239
+ When you dispatch a subagent via the Task tool, it inherits the FULL system prompt.
240
+
241
+ ```
242
+ Main Session Context: 30,000 tokens
243
+ |
244
+ Task(description="Research agent")
245
+ |
246
+ Subagent receives:
247
+ - Full core system (~15,000 tokens)
248
+ - Full MCP tools (all deferred tool listings)
249
+ - Full skills/commands frontmatter
250
+ - Full CLAUDE.md
251
+ - Full MEMORY.md
252
+ - Task description
253
+ ---------------------------------
254
+ TOTAL: ~30,000+ tokens BEFORE doing any work
255
+ ```
256
+
257
+ **Anthropic's own data**: Agent teams use approximately 7x more tokens than standard sessions (source: code.claude.com/docs/en/costs). Subagents automatically load "CLAUDE.md, MCP servers, and skills" (direct quote from Anthropic docs), confirming full system prompt inheritance.
258
+
259
+ **Implication**: If you dispatch 5 subagents in a single session:
260
+ - Each inherits ~30K tokens
261
+ - 5 x 30K = 150K tokens just for setup
262
+ - This is BEFORE they read any files or do work
263
+
264
+ **Optimization**: Session folder pattern
265
+ - Subagents write findings to files
266
+ - Orchestrator never reads full outputs
267
+ - Synthesis agent reads files directly
268
+ - Prevents orchestrator context overflow
269
+
270
+ ---
271
+
272
+ ## Context Window Lifecycle
273
+
274
+ ```
275
+ SESSION START
276
+ |
277
+ Message 1: 20,000 tokens baseline + 1,000 message = 21,000 total
278
+ |
279
+ Message 2: 21,000 previous + new message + response = ~35,000 total
280
+ |
281
+ Message 3: 35,000 previous + new message + response = ~50,000 total
282
+ |
283
+ ...context grows...
284
+ |
285
+ AUTO-COMPACT fires at the model's compact window: about 967K tokens by
286
+ default on 1M models, near the context limit on 200K models
287
+ |
288
+ Context compressed (lossy)
289
+ |
290
+ Continue until /clear or session end
291
+ ```
292
+
293
+ ### Context Fill Degradation
294
+ Token Optimizer's quality score follows a published long-context retrieval curve for Claude models, by share of the window filled (an estimate, not a measurement):
295
+
296
+ | Window filled | Estimated retrieval quality |
297
+ |---------------|-----------------------------|
298
+ | 0-10% | 98 to 96 |
299
+ | 10-25% | 96 to 93 |
300
+ | 25-50% | 93 to 88 |
301
+ | 50-70% | 88 to 80 |
302
+ | 70-100% | 80 to 76 |
303
+
304
+ **Recommendation**: Compact manually at phase boundaries instead of waiting. Auto-compact on 1M models fires at about 967K tokens by default, well past where quality has dropped, so set a lower per-model 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 the user's own history whether an earlier window pays off.
305
+
306
+ `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` sets the percent of the compact window used when auto-compaction fires (lower compacts earlier; it cannot raise the threshold). Token Optimizer reports it and never changes it.
307
+
308
+ ---
309
+
310
+ ## The 1,000 Token Rule
311
+
312
+ **Rule of thumb from research**:
313
+ - 1 line of prose ~ 15 tokens
314
+ - 1 line of YAML/lists ~ 8 tokens
315
+ - 1 line of code ~ 10 tokens
316
+
317
+ **Examples**:
318
+ - 50-line CLAUDE.md prose section = ~750 tokens
319
+ - 100-line skill frontmatter (YAML) = ~800 tokens
320
+ - 200-line Python file = ~2,000 tokens
321
+
322
+ **Use for estimation**: "This section is 40 lines of prose, so ~600 tokens. Worth it?"
323
+
324
+ ---
325
+
326
+ ## Caching Behavior (Prompt Caching)
327
+
328
+ **Prompt caching is on by default in Claude Code.** Disable it with `DISABLE_PROMPT_CACHING=1`.
329
+ - Cache order: tools first, then system prompt, then messages (chronological)
330
+ - Main-conversation default TTL: 1 hour on subscription billing, 5 minutes on usage credits or an API key. The `promptCacheTtl` setting, the `CLAUDE_CODE_PROMPT_CACHE_TTL` env var, `ENABLE_PROMPT_CACHING_1H`, and `FORCE_PROMPT_CACHING_5M` control it (see the controls table in token-coach's quick-reference.md). The timer resets with each active message.
331
+ - Subagents default to 5 minutes; `subagentPromptCacheTtl`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, or per-agent `experimental.cacheTtl` can raise that to 1 hour.
332
+
333
+ **Pricing**:
334
+ - Cache reads: 0.1x base input (90% cheaper)
335
+ - Cache writes: 1.25x base input for a 5-minute cache, 2x for a 1-hour cache
336
+ - Minimum cacheable prompt size varies by model; see the prompt caching docs
337
+
338
+ **What gets cached**: System prompt (including CLAUDE.md), tool definitions, conversation history prefix up to last cache breakpoint.
339
+
340
+ **What breaks the cache** (critical, avoid mid-session):
341
+ - Adding/removing an MCP tool ("all 18K+ tokens after that have to be reprocessed")
342
+ - Switching models mid-session ("caches are per model")
343
+ - Editing CLAUDE.md mid-session
344
+ - Timestamps or dynamic content in system prompt
345
+ - Any change to content before a cache breakpoint
346
+
347
+ **What caching does NOT fix** (why optimization still matters):
348
+ - Context window SIZE: cached tokens still occupy your window
349
+ - Rate limits: cache reads count toward subscription usage quotas
350
+ - Quality: lost-in-the-middle degradation grows as the window fills, regardless of caching
351
+ - Multi-agent amplification: each subagent inherits full overhead at full size
352
+
353
+ **Structuring for cache hits**: Stable sections first (identity, rules), volatile sections last. This maximizes the cached prefix length.
354
+
355
+ ---
356
+
357
+ ## Real Cost: Context Budget, Not Dollars
358
+
359
+ **Official Anthropic data** (code.claude.com/docs/en/costs): Average cost is ~$6/dev/day ($100-200/mo with Sonnet). Background token usage (hooks, auto-memory) typically under $0.04/session.
360
+
361
+ Most Claude Code users are on Max subscriptions ($100-200/month), not per-token API pricing. The real cost of overhead is not dollars. It is context budget:
362
+
363
+ ### Why Overhead Hurts (Even on Subscription)
364
+ ```
365
+ 1. FASTER CONTEXT FILL
366
+ 20K overhead = 10% of a 200K window (2% of 1M) gone before you type
367
+ 35K overhead = 18% of 200K (3.5% of 1M). Compaction arrives that much sooner.
368
+
369
+ 2. MORE COMPACTION CYCLES
370
+ Each compaction is lossy. More compactions = more context lost.
371
+ A session with 35K overhead compacts ~2x more often than 20K.
372
+
373
+ 3. QUALITY DEGRADATION
374
+ Retrieval quality slips as the window fills (see the curve above).
375
+ With 35K overhead you reach any given fill level after fewer messages.
376
+
377
+ 4. BEHAVIORAL MULTIPLIER
378
+ Every message re-sends the overhead. 100 messages/day
379
+ at 35K overhead = 3.5M tokens of overhead alone.
380
+ At 20K overhead = 2.0M tokens. That's 1.5M tokens freed
381
+ for actual work content.
382
+ ```
383
+
384
+ ### For API Users (Per-Token Pricing)
385
+
386
+ Price the token math below at your model's current input rate from the platform pricing page; the rates change often enough that this guide quotes tokens, not dollars.
387
+
388
+ **Without caching** (worst case, e.g. cache misses from inactivity):
389
+ ```
390
+ 20K overhead x 100 msgs/day x 30 days = 60M tokens/mo billed at full input
391
+ 35K overhead x 100 msgs/day x 30 days = 105M tokens/mo billed at full input
392
+ Optimization removes ~45M tokens/mo of that full-price billing.
393
+ ```
394
+
395
+ **With caching** (typical for active sessions):
396
+ ```
397
+ Cached reads cost 10% of base input price.
398
+ 20K overhead: ~2M effective tokens/mo | 35K overhead: ~3.5M effective tokens/mo
399
+ Savings from optimization scale with your model's input rate; cache reads keep them at one-tenth of full price.
400
+ ```
401
+
402
+ **The honest framing**: For subscription users (Max, Pro), dollar cost is irrelevant. The real impact is context window space, rate limit quota burn, and quality degradation from fuller context.
403
+
404
+ ---
405
+
406
+ ## Model Cost Comparison (Why Routing Matters)
407
+
408
+ Routing subagents to the right model tier is the highest-ROI behavioral change. The verified floor: Haiku 5.5 input is $0.10/MTok up to 100K prompt tokens and $0.50/MTok above that (5x on long prompts, per the platform pricing page). Sonnet and Opus bill higher per token; check anthropic.com/pricing for current rates rather than relying on any table here.
409
+
410
+ **Worked shape**: 5-agent workflow (file scanning + analysis + synthesis):
411
+ - **All Opus**: 5 agents x (30K input + 5K output) at Opus's input/output rates
412
+ - **Routed** (3 Haiku + 1 Sonnet + 1 Opus): the same tokens, but the three data-gathering agents bill at Haiku's input rate, the cheapest tier
413
+ - The routed mix costs a fraction of all-Opus; quote exact dollars from the current pricing page, not from memory
414
+
415
+ 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.
416
+
417
+ **What routing does NOT save**: Context window space. Subagents inherit the full system prompt regardless of model. A Haiku agent gets the same ~30K token overhead as an Opus agent. Routing saves dollars and rate limits. Config optimizations (CLAUDE.md slimming, skill archival) save context window space.
418
+
419
+ See `optimization-checklist.md` for the full Model Routing Strategy section with task-to-model mapping and a ready-to-paste CLAUDE.md snippet.
420
+
421
+ ---
422
+
423
+ ## Optimization Priority Matrix
424
+
425
+ | Component | Unaudited Typical | Optimized Target | Savings | Impact x Effort |
426
+ |-----------|-------------------|------------------|---------|-----------------|
427
+ | MCP tools | 9,000 tokens | 6,000 tokens | -3,000 | HIGH x MEDIUM |
428
+ | CLAUDE.md | 3,500 tokens | 2,500 tokens (~170 lines) | -1,000 | HIGH x LOW |
429
+ | Skills (60 -> 30) | 6,000 tokens | 3,000 tokens | -3,000 | MEDIUM x MEDIUM |
430
+ | MEMORY.md | 3,500 tokens | 2,000 tokens (~130 lines) | -1,500 | HIGH x LOW |
431
+ | System reminders | 3,000 tokens | 1,000 tokens | -2,000 | MEDIUM x LOW |
432
+ | Commands (60 -> 25) | 3,000 tokens | 1,200 tokens | -1,800 | LOW x LOW |
433
+
434
+ **Start here**: CLAUDE.md + MEMORY.md (30 min effort, ~2,500 token savings)
435
+
436
+ ---
437
+
438
+ ## Real-World Example: Unaudited Power User (Tool Search Active)
439
+
440
+ **Before optimization** (typical after 3+ months of use):
441
+ ```
442
+ Core system + tools: 15,000 tokens (fixed, unavoidable)
443
+ MCP tools: 9,000 tokens (deferred tools + server instructions)
444
+ Skills (~60): 6,000 tokens
445
+ Commands (~60): 3,000 tokens
446
+ CLAUDE.md: 3,500 tokens (grown organically, never trimmed)
447
+ MEMORY.md: 3,500 tokens (duplicates CLAUDE.md content)
448
+ System reminders: 3,000 tokens (no permissions.deny rules)
449
+ ---------------------------------
450
+ CONSUMED: ~43,000 tokens (4.3% of 1M)
451
+ = UNAVAILABLE: ~43,000 tokens (4.3% of 1M) plus auto-compact headroom
452
+ ```
453
+
454
+ **After config optimization**:
455
+ ```
456
+ Core system + tools: 15,000 tokens (fixed)
457
+ MCP tools: 6,000 tokens (pruned unused servers)
458
+ Skills (~30): 3,000 tokens (archived 30)
459
+ Commands (~25): 1,200 tokens (archived 35)
460
+ CLAUDE.md: 2,500 tokens (~170 lines, under 200-line Anthropic guidance)
461
+ MEMORY.md: 2,000 tokens (~130 lines, under 200-line cap)
462
+ System reminders: 1,000 tokens (permissions.deny)
463
+ ---------------------------------
464
+ CONSUMED: ~30,700 tokens (3.1% of 1M)
465
+ = UNAVAILABLE: ~30,700 tokens (3.1% of 1M) plus auto-compact headroom
466
+
467
+ CONFIG SAVINGS: ~12,300 tokens/msg (29% reduction in consumed overhead)
468
+ ```
469
+
470
+ **At 100 messages/day, that's 1.2M tokens of overhead saved daily.**
471
+
472
+ Prompt caching means the dollar savings are modest (cached tokens cost 10% of base). But the context window space savings are real: you hit compaction later, quality stays higher longer, and each subagent inherits ~12,000 fewer tokens of overhead.
473
+
474
+ **Plus behavioral changes** (compound across every message):
475
+ - Agent model selection (haiku for data): the largest per-token cut on automation
476
+ - /compact at phase boundaries: the biggest reductions come from compacting right after a bulky research or exploration phase
477
+ - Extended thinking awareness: variable, potentially largest factor
478
+ - Batching requests: 2-3x on multi-step tasks
479
+
480
+ **Config changes shrink overhead per message. Behavioral changes multiply across every session.**
481
+
482
+ ---
483
+
484
+ ## Additional Config Features (Token Impact)
485
+
486
+ ### `.claude/rules/` Directory (Path-Scoped Rules)
487
+
488
+ Rules files in `.claude/rules/*.md` support `paths:` frontmatter for directory-scoped loading. Each rule file loads similarly to CLAUDE.md content (~15 tokens/line of prose).
489
+
490
+ ```
491
+ .claude/rules/
492
+ backend.md # paths: ["src/backend/**"]
493
+ frontend.md # paths: ["src/frontend/**"]
494
+ testing.md # paths: ["tests/**"]
495
+ general.md # no paths = always loaded
496
+ ```
497
+
498
+ **Token impact**: Rules without `paths:` frontmatter load every message (same as CLAUDE.md). Rules with `paths:` load only when working in matching directories. Measure total rules content with `measure.py report`.
499
+
500
+ **Optimization**: Audit `.claude/rules/` for stale rules, duplicates, and rules that should have path scoping but don't.
501
+
502
+ ### `CLAUDE.local.md` (Project-Local, Gitignored)
503
+
504
+ A gitignored version of project CLAUDE.md. Always loaded alongside CLAUDE.md when present. Used for local overrides, personal preferences, or environment-specific config that shouldn't be committed.
505
+
506
+ **Token impact**: Adds to CLAUDE.md overhead every message. Must be audited alongside CLAUDE.md.
507
+
508
+ ### `.claude/settings.local.json` (Local Settings Overlay)
509
+
510
+ Local settings file that overlays `.claude/settings.json`. Can contain env var overrides, permission changes. Not committed to git.
511
+
512
+ **Token impact**: Indirect. Can override env vars like `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`, `MAX_THINKING_TOKENS`, etc. The optimizer should check for its existence and report any token-relevant overrides.
513
+
514
+ ### `@imports` in CLAUDE.md
515
+
516
+ CLAUDE.md supports `@path/to/file.md` imports that pull external file content into the always-loaded context. This can silently add thousands of tokens.
517
+
518
+ ```markdown
519
+ # My CLAUDE.md
520
+ @docs/coding-standards.md
521
+ @docs/api-reference.md
522
+ ```
523
+
524
+ **Token impact**: Each imported file's full content loads every message. A 200-line coding standards doc = ~3,000 tokens added silently.
525
+
526
+ **Optimization**: Grep CLAUDE.md for `@` patterns. Resolve paths. Estimate total imported content. Move large imports to skills or reference files.
527
+
528
+ ### `disable-model-invocation: true` in Skill Frontmatter
529
+
530
+ Skills inject `name` + `description` into always-on context every turn (progressive disclosure: the body loads only on invoke). Dropping a skill's description from that always-on context recovers its per-turn description cost — quantify it with the per-skill token cost `measure.py report` already computes, not a flat constant. Descriptions are also dropped after `/compact` and never re-injected, so the savings persist across compaction. Claude Code gives **two distinct levers** to do this, and they are NOT the same thing:
531
+
532
+ **1. `skillOverrides` in settings (the true "name-only" middle mode).** `.claude/settings.local.json` `skillOverrides` maps a skill name to one of four visibility states (the `/skills` menu writes it for you — highlight a skill, press `Space` to cycle, `Enter` to save). Per the official docs (code.claude.com/docs/en/skills.md, "Override skill visibility from settings"):
533
+
534
+ | Value | Listed to Claude | In `/` menu |
535
+ | :-- | :-- | :-- |
536
+ | `"on"` (default) | Name **and** description | Yes |
537
+ | `"name-only"` | **Name only** (description hidden) | Yes |
538
+ | `"user-invocable-only"` | Hidden from Claude | Yes |
539
+ | `"off"` | Hidden | Hidden |
540
+
541
+ `"name-only"` is the real name-visible/description-hidden middle mode: the model still sees the skill's **name** (so it can still invoke it by name) but not its description, so it stops auto-triggering on description match while you keep the token savings. This is the right choice for a skill you want to stay discoverable-by-name without paying for its description or letting it fire automatically.
542
+
543
+ **2. `disable-model-invocation: true` in SKILL.md frontmatter (fully hidden from the model).** This **removes the skill from the model's context entirely** — not even the name is visible; only the USER can invoke it via `/name`. Official docs, verbatim: *"Description not in context, full skill loads when you invoke"* and *"They stay completely out of context until you invoke them with /name"* (context-window.md). Use it for skills only the user ever triggers explicitly (e.g. one that launches a browser tab, where auto-triggering on a guess is intrusive). It is a **binary** frontmatter flag (advertised, or fully hidden) — the graded middle states live in `skillOverrides` above, not in the flag. Equivalent settings values are `"user-invocable-only"` / `"off"`.
544
+
545
+ Do NOT relabel `disable-model-invocation` as "name-only" — that term is Claude Code's `skillOverrides` state (name kept), and `disable-model-invocation` hides the name too. Keep skills whose value is proactive auto-triggering on the default `"on"`.
546
+
547
+ **Cross-harness caveat**: both levers are **Claude-Code-specific**. Codex / OpenCode / Copilot skills keep `name` + `description` resident regardless; there is no per-skill "hide description" toggle there (the equivalent is a different primitive — a command / prompt-file — or a full disable via `[[skills.config]] enabled = false` on Codex). Other harnesses ignore the unknown frontmatter key (harmless, not an error).
548
+
549
+ ### Compact Instructions Section in CLAUDE.md
550
+
551
+ CLAUDE.md can include a section that guides what gets preserved during context compaction. This influences what survives /compact and auto-compact.
552
+
553
+ ```markdown
554
+ ## Compact Instructions
555
+ When compacting this conversation, always preserve:
556
+ - Current task context and progress
557
+ - File paths being modified
558
+ - Test results and error messages
559
+ ```
560
+
561
+ **Token impact**: Small (the section itself is ~50-100 tokens). But the behavioral impact is significant: it controls what survives compaction, affecting quality of continued sessions.
562
+
563
+ ### `/rewind` Command
564
+
565
+ Targeted compaction alternative. Instead of full /compact (which summarizes everything), /rewind removes specific recent turns. Better for "that didn't work, let me try again" situations.
566
+
567
+ **Token impact**: More precise context management. Less lossy than full /compact.
568
+
569
+ ### Context Loading Hierarchy (13 Levels)
570
+
571
+ Full priority order for what Claude Code loads:
572
+
573
+ ```
574
+ 1. Core system prompt (fixed)
575
+ 2. Built-in tool definitions (fixed)
576
+ 3. MCP tool definitions (deferred via Tool Search)
577
+ 4. MCP server instructions
578
+ 5. Plugin-bundled skills/commands
579
+ 6. User skills frontmatter (~/.claude/skills/)
580
+ 7. User commands frontmatter (~/.claude/commands/)
581
+ 8. Global CLAUDE.md (~/.claude/CLAUDE.md)
582
+ 9. Project CLAUDE.md ([repo]/CLAUDE.md)
583
+ 10. CLAUDE.local.md ([repo]/CLAUDE.local.md)
584
+ 11. .claude/rules/*.md (path-matched rules)
585
+ 12. MEMORY.md (~/.claude/projects/.../memory/MEMORY.md)
586
+ 13. System reminders (auto-injected)
587
+ ```
588
+
589
+ Items 1-5 are largely fixed or deferred. Items 6-12 are your optimization targets. Item 13 is partially controlled via `permissions.deny` rules.
590
+
591
+ ### Settings.json Environment Variables (Token-Relevant)
592
+
593
+ The `env` block in `~/.claude/settings.json` can set several token-relevant variables:
594
+
595
+ ```json
596
+ {
597
+ "env": {
598
+ "CLAUDE_CODE_MAX_THINKING_TOKENS": "10000",
599
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "16384",
600
+ "MAX_MCP_OUTPUT_TOKENS": "25000",
601
+ "ENABLE_TOOL_SEARCH": "auto"
602
+ }
603
+ }
604
+ ```
605
+
606
+ See `optimization-checklist.md` items 23-30 for what each does and how the optimizer audits them.
607
+
608
+ ---
609
+
610
+ ## Cache Economics and Compaction
611
+
612
+ Prompt caching is the foundation of Claude Code's cost model. Cached reads cost 10% of full input price. When compaction fires, the entire conversation is replaced with a summary, invalidating the cache prefix. Every token after compaction gets billed at full price until the new cache warms up.
613
+
614
+ **The compaction tax**: A single compaction in a 100K-token session re-bills ~90K tokens at full input price instead of the cached rate, and multiple compactions compound this.
615
+
616
+ **Mitigation strategies** (see optimization-checklist.md item 8):
617
+ 1. **Delay compaction**: Keep context lean (the optimizer's core job). Fewer tokens = later compaction = fewer rebuilds.
618
+ 2. **Context Editing API** (API users): `clear_tool_uses_20250919` and `clear_thinking_20251015` surgically evict stale content without triggering full compaction. Cache prefix survives.
619
+ 3. **Smart Compaction**: PreCompact checkpoint + Compact Instructions + SessionStart restore minimizes wasted post-compaction turns (which compound the cost).
620
+ 4. **Strategic cache breakpoints**: Place `cache_control` breakpoints before editable content. The 20-block lookback window means partial invalidation, not total.
621
+
622
+ ---
623
+
624
+ ## Further Reading
625
+
626
+ - **Official Docs**: https://docs.anthropic.com (prompt caching, context windows, context editing)
627
+ - **Official Costs**: https://code.claude.com/docs/en/costs (average spend, agent-team multiplier, background overhead data)
628
+ - **Model config**: https://code.claude.com/docs/en/model-config (context windows and auto-compaction defaults)
629
+ - **Tool Search**: on by default (deferred tool loading, ~85% MCP reduction)