context-compression: Context Compression and Token Optimization for Long-Session Agents

Preface

When a Coding Agent runs for a long time, conversations and tool outputs can quickly pile up the context window. A common approach is to “compress” the history before each request as much as possible. This does reduce the token count per prompt, but in the later stages of a task, the agent repeatedly re-reads files and re-asks about decisions already made, which ends up consuming more total tokens. The following section introduces the context-compression Skill from the repository Agent-Skills-for-Context-Engineering: it shifts the optimization objective from “tokens per request” to “total tokens needed to complete the task,” and provides actionable compression strategies, summary structures, and evaluation methods.

What This Is

context-compression is an Agent Skill (a SKILL.md instruction set), maintained by muratcankoylan/Agent-Skills-for-Context-Engineering under the Context Engineering topic in that collection.

The official description states that this Skill should be activated when long-running sessions require context compression, structured summaries, compaction, per-task token optimization, or a durable handoff summary that preserves decisions, files, risks, and follow-up actions.

It does not cover general token-counting tricks (see context-optimization in the same repository), pre-compression degradation diagnostics (context-degradation), logging-only approaches that write to files without summarizing (filesystem-context), cross-session semantic memory (memory-systems), nor does it replace model-managed context timing (self-managed-context); however, when context needs to be replaced, this Skill defines “what the replacement text must preserve.”

Core Functionality

Three Production-Oriented Compression Paths

The materials treat compression as a trade-off between “token savings” and “information loss,” and offer three options:

  1. Anchored Iterative Summarization
    Suitable for long sessions that need to track file changes. Maintains a persistent summary with fixed sections (session intent, file modifications, decisions, next steps, etc.). When compression triggers, only new truncated segments are summarized and merged with the existing summary, rather than rewriting everything from scratch, reducing drift and silently lost details caused by multiple full rewrites.

  2. Opaque Compression
    Suitable for short sessions where re-fetch costs are low, and extreme compression ratios are needed. It produces a compression representation optimized for reconstruction fidelity—the materials claim it can achieve 99%+ compression—but it is not human-readable; you cannot verify what was preserved without running a probe-based evaluation. It should not be used when auditing or tracking key artifacts is critical.

  3. Regenerative Full Summary
    Suitable when summary readability matters and the session has clear phase boundaries. It generates a new structured, detailed summary at each compression trigger; the weakness is that repeated full regeneration can accumulate lost details.

Optimization Objective: tokens-per-task

Track total tokens from task start to completion, not per request. If compression loses paths, error messages, or reasoning behind decisions, the agent will re-explore, re-read files, and re-derive conclusions—this waste typically exceeds what compression saved. The materials suggest treating “repeated requests to re-read already-processed files” as the primary signal of overly aggressive compression.

Artifact Trail

The materials note that artifact-trail integrity is often the weakest dimension in compression evaluation (citing claim-context-compression-factory-benchmark). Each compression cycle should explicitly preserve:

  • New files (full paths)
  • Modified files and changes (with function names, not just filenames)
  • Read-only files that were not modified
  • Specific identifiers: function names, variable names, error messages and error codes

The recommendation is to maintain a separate artifact index or file-state tracker in the agent scaffold, rather than relying entirely on the summarization model to remember details on its own.

Structured Summary with Required Sections

Use fixed sections as a checklist to reduce silent omissions. The official example skeleton is as follows (sections can be adapted for specific domains—for example, a debugging agent could add Root Cause / Error Messages):

## Session Intent
[What the user is trying to accomplish]

## Files Modified
- auth.controller.ts: Fixed JWT token generation
- config/redis.ts: Updated connection pooling
- tests/auth.test.ts: Added mock setup for new config

## Decisions Made
- Using Redis connection pool instead of per-request connections
- Retry logic with exponential backoff for transient failures

## Current State
- 14 tests passing, 2 failing
- Remaining: mock setup for session service tests

## Next Steps
1. Fix remaining test failures
2. Run full test suite
3. Update documentation

Compression Trigger Strategies

Strategy Trigger Point Trade-off
Fixed threshold 70-80% context utilization Simple but can trigger too early
Sliding window Keep last N turns + summary Predictable context size
Importance-based Compress low-relevance sections first Complex but preserves signal
Task-boundary Compress at logical task completions Clean summaries but unpredictable timing

For coding agents, the materials default to recommending sliding window + structured summaries; use task-boundary when the session has clear phases (research → implementation → testing).

Evaluate with Probes, Not ROUGE Alone

ROUGE or embedding similarity alone cannot reliably indicate whether the agent can continue working. After compression, ask targeted questions about key facts: correct answers mean retention is effective, while wrong answers or speculation indicate overly aggressive compression.

Probe Type What It Tests Example Question
Recall Factual retention “What was the original error message?”
Artifact File tracking “Which files have we modified?”
Continuation Task planning “What should we do next?”
Decision Reasoning chain “What did we decide about the Redis issue?”

For coding agents, the materials also propose scoring across multiple dimensions (including accuracy and artifact-trail retention); accuracy and artifact-trail retention often separate good and bad approaches more effectively than literal overlap.

When to Activate

Activate this Skill in the following situations (excerpted from the official When to Activate):

  • Agent sessions exceed the context window
  • Codebases whose size exceeds the context window (the materials cite a 5M+ token system as an example)
  • Designing a conversation summarization strategy
  • An agent that “forgets” which files it has modified
  • Building a compression-quality evaluation framework
  • Producing handoff summaries that preserve decisions, files, risks, and next actions

Installation and Activation

This Skill consists of text instructions rather than a standalone binary. Common loading methods (consistent with the awesome-agent-skills community index; exact commands vary by platform—consult the respective platform docs):

Claude Code

/skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering

After installing the collection, in the conversation, specify that you want to use the compression strategy from skills/context-compression, or have the agent auto-load the corresponding Skill as described.

npx skills (Vercel labs)

npx skills find context-compression
npx skills add muratcankoylan/Agent-Skills-for-Context-Engineering
npx skills list

Claude.ai

You can paste the raw URL of the SKILL.md file from the skill’s directory into a new conversation (as described in the community Quick Start).

Cursor and Other Compatible Agents

The community index lists Cursor as a compatible platform; typically you place the skill directory in the project or user-level skills configuration path and reference it in the task description by saying “do compression and summarization per context-compression.” Cursor-specific paths should follow the current product documentation; if the materials do not provide dedicated commands, do not invent configuration items.

Skill source file path:

https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/context-compression

Typical Usage Patterns

  1. Select a strategy: For long sessions involving code changes → prioritize Anchored Iterative Summarization + an artifact index in the scaffold; for maximum token savings on short tasks → evaluate whether Opaque Compression’s re-fetch costs are acceptable; for readable handoff documents → use Regenerative Full Summary and manage the frequency of full regeneration.

  2. Set the trigger: Default to sliding window for coding scenarios (keep the most recent N turns + structured summary); use a fixed threshold at 70–80% context utilization as a secondary signal.

  3. Write the summary: Fill in the required sections—Session Intent, Files Modified, Decisions Made, Current State, Next Steps—at each compression step; record paths and function-level changes in full detail.

  4. Verify quality: After compression, run Recall / Artifact / Continuation / Decision probes; if the agent repeatedly re-reads the same files, tighten compression or strengthen artifact tracking.

Use Cases and Caveats

Best for: Autonomous coding agents, long-horizon tasks, multi-user or multi-agent collaboration where handoffs are needed, teams building evaluation and regression tests for their compression approach.

Caveats:

  • Don’t sacrifice artifact-trail integrity for single-request token savings; tokens-per-task is the primary metric.
  • Opaque Compression is unsuitable when you need to audit “what was preserved.”
  • Keep clear boundaries with adjacent skills like context-optimization and self-managed-context, and avoid mixing multiple skills with conflicting instructions on the same problem.

Conclusion

Context-compression turns “how to compress context in long sessions” into an executable strategy and checklist: three compression paths, a structured summary schema, a trigger strategy table, and probe-based evaluation. If you are doing Context Engineering for production-grade agents, you can load this Skill directly from the official directory:

https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/context-compression

羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye