1
---
2
name: context-compression
3
description: "This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions."
4
---
5
6
# Context Compression Strategies
7
8
When agent sessions generate millions of tokens of conversation history, compression becomes mandatory. The naive approach is aggressive compression to minimize tokens per request. The correct optimization target is tokens per task: total tokens consumed to complete a task, including re-fetching costs when compression loses critical information.
9
10
## When to Activate
11
12
Activate this skill when:
13
- Agent sessions exceed context window limits
14
- Codebases exceed context windows (5M+ token systems)
15
- Designing conversation summarization strategies
16
- Debugging cases where agents "forget" what files they modified
17
- Building evaluation frameworks for compression quality
18
- Creating durable handoff summaries that preserve decisions, files, risks, and next actions
19
20
Do not activate this skill for adjacent work owned by other skills:
21
- General token-efficiency tactics such as masking, prefix caching, or partitioning: `context-optimization`.
22
- Diagnosing why a long context is failing before choosing a mitigation: `context-degradation`.
23
- Writing raw outputs, logs, or plans to files without summarizing them: `filesystem-context`.
24
- Designing long-term semantic memory across sessions: `memory-systems`.
25
- The model deciding when and where to rewrite its own context: `self-managed-context`. This skill still owns what the replacement text must preserve.
26
- Deciding whether a given model or the harness should trigger compaction, and measuring that behavior across context budgets: `compaction-control-profiling`.
27
28
## Core Concepts
29
30
Context compression trades token savings against information loss. Select from three production-ready approaches based on session characteristics:
31
32
1. **Anchored Iterative Summarization**: Implement this for long-running sessions where file tracking matters. Maintain structured, persistent summaries with explicit sections for session intent, file modifications, decisions, and next steps. When compression triggers, summarize only the newly-truncated span and merge with the existing summary rather than regenerating from scratch. This prevents drift that accumulates when summaries are regenerated wholesale — each regeneration risks losing details the model considers low-priority but the task requires. Structure forces preservation because dedicated sections act as checklists the summarizer must populate, catching silent information loss.
33
34
2. **Opaque Compression**: Reserve this for short sessions where re-fetching costs are low and maximum token savings are required. It produces compressed representations optimized for reconstruction fidelity, achieving 99%+ compression ratios but sacrificing interpretability entirely. The tradeoff matters: there is no way to verify what was preserved without running probe-based evaluation, so never use this when debugging or artifact tracking is critical.
35
36
3. **Regenerative Full Summary**: Use this when summary readability is critical and sessions have clear phase boundaries. It generates detailed structured summaries on each compression trigger. The weakness is cumulative detail loss across repeated cycles — each full regeneration is a fresh pass that may deprioritize details preserved in earlier summaries.
37
38
## Detailed Topics
39
40
### Optimize for Tokens-Per-Task, Not Tokens-Per-Request
41
42
Measure total tokens consumed from task start to completion, not tokens per individual request. When compression drops file paths, error messages, or decision rationale, the agent must re-explore, re-read files, and re-derive conclusions — wasting far more tokens than the compression saved. A strategy saving 0.5% more tokens per request but causing 20% more re-fetching costs more overall. Track re-fetching frequency as the primary quality signal: if the agent repeatedly asks to re-read files it already processed, compression is too aggressive.
43
44
### Solve the Artifact Trail Problem First
45
46
Artifact trail integrity is often the weakest dimension in compression evaluations (claim-context-compression-factory-benchmark). Address this proactively because general summarization cannot reliably maintain it.
47
48
Preserve these categories explicitly in every compression cycle:
49
- Which files were created (full paths)
50
- Which files were modified and what changed (include function names, not just file names)
51
- Which files were read but not changed
52
- Specific identifiers: function names, variable names, error messages, error codes
53
54
Implement a separate artifact index or explicit file-state tracking in agent scaffolding rather than relying on the summarizer to capture these details. Even structured summarization with dedicated file sections struggles with completeness over long sessions.
55
56
### Structure Summaries with Mandatory Sections
57
58
Build structured summaries with explicit sections that prevent silent information loss. Each section acts as a checklist the summarizer must populate, making omissions visible rather than silent.
59
60
```markdown
61
## Session Intent
62
[What the user is trying to accomplish]
63
64
## Files Modified
65
- auth.controller.ts: Fixed JWT token generation
66
- config/redis.ts: Updated connection pooling
67
- tests/auth.test.ts: Added mock setup for new config
68
69
## Decisions Made
70
- Using Redis connection pool instead of per-request connections
71
- Retry logic with exponential backoff for transient failures
72
73
## Current State
74
- 14 tests passing, 2 failing
75
- Remaining: mock setup for session service tests
76
77
## Next Steps
78
1. Fix remaining test failures
79
2. Run full test suite
80
3. Update documentation
81
```
82
83
Adapt sections to the agent's domain. A debugging agent needs "Root Cause" and "Error Messages"; a migration agent needs "Source Schema" and "Target Schema." The structure matters more than the specific sections — any explicit schema outperforms freeform summarization.
84
85
### Choose Compression Triggers Strategically
86
87
When to trigger compression matters as much as how to compress. Select a trigger strategy based on session predictability:
88
89
| Strategy | Trigger Point | Trade-off |
90
|----------|---------------|-----------|
91
| Fixed threshold | 70-80% context utilization | Simple but may compress too early |
92
| Sliding window | Keep last N turns + summary | Predictable context size |
93
| Importance-based | Compress low-relevance sections first | Complex but preserves signal |
94
| Task-boundary | Compress at logical task completions | Clean summaries but unpredictable timing |
95
96
Default to sliding window with structured summaries for coding agents — it provides the best balance of predictability and quality. Use task-boundary triggers when sessions have clear phase transitions (e.g., research then implementation then testing).
97
98
### Evaluate Compression with Probes, Not Metrics
99
100
Traditional metrics like ROUGE or embedding similarity fail to capture functional compression quality. A summary can score high on lexical overlap while missing the one file path the agent needs to continue.
101
102
Use probe-based evaluation: after compression, pose questions that test whether critical information survived. If the agent answers correctly, compression preserved the right information. If not, it guesses or hallucinates.
103
104
| Probe Type | What It Tests | Example Question |
105
|------------|---------------|------------------|
106
| Recall | Factual retention | "What was the original error message?" |
107
| Artifact | File tracking | "Which files have we modified?" |
108
| Continuation | Task planning | "What should we do next?" |
109
| Decision | Reasoning chain | "What did we decide about the Redis issue?" |
110
111
### Score Compression Across Six Dimensions
112
113
Evaluate compression quality for coding agents across these dimensions. Accuracy and artifact-trail preservation tend to separate methods more clearly than lexical similarity (claim-context-compression-factory-benchmark), so compression needs specialized handling beyond general summarization.
114
115
1. **Accuracy**: Are technical details correct — file paths, function names, error codes?
116
2. **Context Awareness**: Does the response reflect current conversation state?
117
3. **Artifact Trail**: Does the agent know which files were read or modified?
118
4. **Completeness**: Does the response address all parts of the question?
119
5. **Continuity**: Can work continue without re-fetching information?
120
6. **Instruction Following**: Does the response respect stated constraints?
121
122
## Practical Guidance
123
124
### Apply the Three-Phase Compression Workflow for Large Codebases
125
126
For codebases or agent systems exceeding context windows, compress through three sequential phases. Each phase narrows context so the next phase operates within budget.
127
128
1. **Research Phase**: Explore architecture diagrams, documentation, and key interfaces. Compress exploration into a structured analysis of components, dependencies, and boundaries. Output: a single research document that replaces raw exploration.
129
130
2. **Planning Phase**: Convert the research document into an implementation specification with function signatures, type definitions, and data flow. A 5M-token codebase compresses to approximately 2,000 words of specification at this stage.
131
132
3. **Implementation Phase**: Execute against the specification. Context stays focused on the spec plus active working files, not raw codebase exploration. This phase rarely needs further compression because the spec is already compact.
133
134
### Use Example Artifacts as Compression Seeds
135
136
When provided with a manual migration example or reference PR, use it as a template to understand the target pattern rather than exploring the codebase from scratch. The example reveals constraints static analysis cannot surface: which invariants must hold, which services break on changes, and what a clean implementation looks like.
137
138
This matters most when the agent cannot distinguish essential complexity (business requirements) from accidental complexity (legacy workarounds). The example artifact encodes that distinction implicitly, saving tokens that would otherwise go to trial-and-error exploration.
139
140
### Implement Anchored Iterative Summarization Step by Step
141
142
1. Define explicit summary sections matching the agent's domain (debugging, migration, feature development)
143
2. On first compression trigger, summarize the truncated history into those sections
144
3. On subsequent compressions, summarize only newly truncated content — do not re-summarize the existing summary
145
4. Merge new information into existing sections rather than regenerating them, deduplicating by file path and decision identity
146
5. Tag which information came from which compression cycle — this enables debugging when summaries drift
147
148
### Select the Right Approach for the Session Profile
149
150
**Use anchored iterative summarization when:**
151
- Sessions are long-running (100+ messages)
152
- File tracking matters (coding, debugging)
153
- Verification of preserved information is needed
154
155
**Use opaque compression when:**
156
- Maximum token savings are required
157
- Sessions are relatively short
158
- Re-fetching costs are low (e.g., no file system access needed)
159
160
**Use regenerative summaries when:**
161
- Summary interpretability is critical for human review
162
- Sessions have clear phase boundaries
163
- Full context review is acceptable on each compression trigger
164
165
### Calibrate Compression Ratios by Method
166
167
| Method | Compression Ratio | Quality Score | Trade-off |
168
|--------|-------------------|---------------|-----------|
169
| Anchored Iterative | 98.6% | 3.70 | Best quality, slightly less compression |
170
| Regenerative | 98.7% | 3.44 | Good quality, moderate compression |
171
| Opaque | 99.3% | 3.35 | Best compression, quality loss |
172
173
Use these as source-specific benchmark figures, not universal constants (claim-context-compression-factory-benchmark). For any task where re-fetching costs exist, this tradeoff generally favors structured approaches.
174
175
## Examples
176
177
**Example 1: Debugging Session Compression**
178
179
Original context (89,000 tokens, 178 messages):
180
- 401 error on /api/auth/login endpoint
181
- Traced through auth controller, middleware, session store
182
- Found stale Redis connection
183
- Fixed connection pooling, added retry logic
184
- 14 tests passing, 2 failing
185
186
Structured summary after compression:
187
188
```markdown
189
## Session Intent
190
Debug 401 Unauthorized error on /api/auth/login despite valid credentials.
191
192
## Root Cause
193
Stale Redis connection in session store. JWT generated correctly but session could not be persisted.
194
195
## Files Modified
196
- auth.controller.ts: No changes (read only)
197
- middleware/cors.ts: No changes (examined)
198
- config/redis.ts: Fixed connection pooling configuration
199
- services/session.service.ts: Added retry logic for transient failures
200
- tests/auth.test.ts: Updated mock setup
201
202
## Test Status
203
14 passing, 2 failing (mock setup issues)
204
205
## Next Steps
206
1. Fix remaining test failures (mock session service)
207
2. Run full test suite
208
3. Deploy to staging
209
```
210
211
**Example 2: Probe Response Quality**
212
213
After compression, asking "What was the original error?":
214
215
Good response (structured summarization):
216
> "The original error was a 401 Unauthorized response from the /api/auth/login endpoint. Users received this error with valid credentials. Root cause was stale Redis connection in session store."
217
218
Poor response (aggressive compression):
219
> "We were debugging an authentication issue. The login was failing. We fixed some configuration problems."
220
221
The structured response preserves endpoint, error code, and root cause. The aggressive response loses all technical detail.
222
223
## Guidelines
224
225
1. Optimize for tokens-per-task, not tokens-per-request
226
2. Use structured summaries with explicit sections for file tracking
227
3. Trigger compression at 70-80% context utilization
228
4. Implement incremental merging rather than full regeneration
229
5. Test compression quality with probe-based evaluation
230
6. Track artifact trail separately if file tracking is critical
231
7. Accept slightly lower compression ratios for better quality retention
232
8. Monitor re-fetching frequency as a compression quality signal
233
234
## Gotchas
235
236
1. **Never compress tool definitions or schemas**: Compressing function call schemas, API specs, or tool definitions destroys agent functionality entirely. The agent cannot invoke tools whose parameter names or types have been summarized away. Treat tool definitions as immutable anchors that bypass compression.
237
238
2. **Compressed summaries hallucinate facts**: When an LLM summarizes conversation history, it may introduce plausible-sounding details that never appeared in the original. Always validate compressed output against source material before discarding originals — especially for file paths, error codes, and numeric values that the summarizer may "round" or fabricate.
239
240
3. **Compression breaks artifact references**: File paths, commit SHAs, variable names, and code snippets get paraphrased or dropped during compression. A summary saying "updated the config file" when the agent needs `config/redis.ts` causes re-exploration. Preserve identifiers verbatim in dedicated sections rather than embedding them in prose.
241
242
4. **Early turns contain irreplaceable constraints**: The first few turns of a session often contain task setup, user constraints, and architectural decisions that cannot be re-derived. Protect early turns from compression or extract their constraints into a persistent preamble that survives all compression cycles.
243
244
5. **Aggressive ratios compound across cycles**: A 95% compression ratio seems safe once, but applying it repeatedly compounds losses. After three cycles at 95%, only 0.0125% of original tokens remain. Calibrate ratios assuming multiple compression cycles, not a single pass.
245
246
6. **Code and prose need different compression**: Prose compresses well because natural language is redundant. Code does not — removing a single token from a function signature or import path can make it useless. Apply domain-specific compression strategies: summarize prose sections aggressively while preserving code blocks and structured data verbatim.
247
248
7. **Probe-based evaluation gives false confidence**: Probes can pass despite critical information being lost, because the probes test only what they ask about. A probe set that checks file names but not function signatures will miss signature loss. Design probes to cover all six evaluation dimensions, and rotate probe sets across evaluation runs to avoid blind spots.
249
250
## Integration
251
252
This skill connects to several others in the collection:
253
254
- context-degradation - Compression is a mitigation strategy for degradation
255
- context-optimization - Compression is one optimization technique among many
256
- evaluation - Probe-based evaluation applies to compression testing
257
- memory-systems - Compression relates to scratchpad and summary memory patterns
258
- self-managed-context - When the model triggers and places its own compaction edits, this skill supplies what the replacement note preserves
259
- compaction-control-profiling - Decides per model who triggers compaction; this skill supplies what the collapse summary preserves
260
261
## References
262
263
Internal reference:
264
- [Evaluation Framework Reference](./references/evaluation-framework.md) - Read when: building or calibrating a probe-based evaluation pipeline, or when needing scoring rubrics and LLM judge configuration for compression quality assessment
265
266
Related skills in this collection:
267
- context-degradation - Read when: diagnosing why agent performance drops over long sessions, before applying compression as a mitigation
268
- context-optimization - Read when: compression alone is insufficient and broader optimization strategies (pruning, caching, routing) are needed
269
- evaluation - Read when: designing evaluation frameworks beyond compression-specific probes, including general LLM-as-judge methodology
270
271
External resources:
272
- Factory Research: Evaluating Context Compression for AI Agents (December 2025) - Read when: needing benchmark data on compression method comparisons or the 36,000-message evaluation dataset
273
- Research on LLM-as-judge evaluation methodology (Zheng et al., 2023) - Read when: implementing or validating LLM judge scoring to understand bias patterns and calibration
274
- Netflix Engineering: "The Infinite Software Crisis" - Three-phase workflow and context compression at scale (AI Summit 2025) - Read when: implementing the three-phase compression workflow for large codebases or understanding production-scale context management
275
276
---
277
278
## Skill Metadata
279
280
**Created**: 2025-12-22
281
**Last Updated**: 2026-05-15
282
**Author**: Agent Skills for Context Engineering Contributors
283
**Version**: 1.3.0
284