重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
context-compression by guanyang/antigravity-skills
npx skills add https://github.com/guanyang/antigravity-skills --skill context-compression当智能体会话生成数百万令牌的对话历史时,压缩变得势在必行。简单粗暴的方法是进行激进压缩,以最小化每次请求的令牌数。正确的优化目标是每任务令牌数:完成一个任务所消耗的总令牌数,包括压缩丢失关键信息时重新获取的成本。
在以下情况下启用此技能:
上下文压缩在节省令牌和信息损失之间进行权衡。根据会话特征,从三种可用于生产环境的方法中选择:
锚定迭代摘要:对于需要跟踪文件的长运行会话,请实施此方法。维护结构化的、持久的摘要,包含明确的会话意图、文件修改、决策和后续步骤等部分。当触发压缩时,仅总结新截断的部分,并与现有摘要合并,而不是从头开始重新生成。这可以防止在整体重新生成摘要时累积的漂移——每次重新生成都可能丢失模型认为优先级低但任务需要的细节。结构化强制保留信息,因为专用部分充当摘要器必须填充的检查清单,从而捕捉无声的信息丢失。
不透明压缩:将此方法保留用于重新获取成本低且需要最大令牌节省的短会话。它生成针对重建保真度优化的压缩表示,实现 99%+ 的压缩比,但完全牺牲了可解释性。这种权衡很重要:如果不运行基于探针的评估,就无法验证保留了哪些内容,因此在调试或工件跟踪至关重要时切勿使用此方法。
再生式完整摘要:当摘要可读性至关重要且会话具有清晰的阶段边界时,请使用此方法。它在每次压缩触发时生成详细的结构化摘要。其弱点在于跨重复周期的累积细节丢失——每次完整的重新生成都是一次新的处理,可能会降低先前摘要中保留的细节的优先级。
衡量从任务开始到完成所消耗的总令牌数,而不是每次单独请求的令牌数。当压缩丢弃文件路径、错误消息或决策依据时,智能体必须重新探索、重新读取文件和重新推导结论——浪费的令牌数远多于压缩节省的令牌数。一种策略每次请求多节省 0.5% 的令牌,但导致重新获取成本增加 20%,总体成本更高。将重新获取频率作为主要质量信号进行跟踪:如果智能体反复要求重新读取它已经处理过的文件,则压缩过于激进。
工件追踪完整性是所有压缩方法中最薄弱的维度,在评估中得分仅为 2.2-2.5(满分 5.0)。需要主动解决此问题,因为通用摘要无法可靠地维护它。
在每个压缩周期中明确保留以下类别:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
在智能体脚手架中实现单独的工件索引或显式的文件状态跟踪,而不是依赖摘要器来捕获这些细节。即使是带有专用文件部分的结构化摘要,在长会话中也难以保证完整性。
构建具有明确部分的结构化摘要,以防止无声的信息丢失。每个部分都充当摘要器必须填充的检查清单,使遗漏可见而非无声。
## 会话意图
[用户试图完成什么]
## 已修改的文件
- auth.controller.ts: 修复了 JWT 令牌生成
- config/redis.ts: 更新了连接池配置
- tests/auth.test.ts: 为新配置添加了模拟设置
## 已做出的决策
- 使用 Redis 连接池而非每次请求的连接
- 针对瞬时故障采用指数退避的重试逻辑
## 当前状态
- 14 个测试通过,2 个失败
- 剩余任务:会话服务测试的模拟设置
## 后续步骤
1. 修复剩余的测试失败
2. 运行完整的测试套件
3. 更新文档
根据智能体的领域调整部分。调试智能体需要“根本原因”和“错误消息”;迁移智能体需要“源模式”和“目标模式”。结构比具体部分更重要——任何明确的模式都优于自由格式的摘要。
何时触发压缩与如何压缩同样重要。根据会话的可预测性选择触发策略:
| 策略 | 触发点 | 权衡 |
|---|---|---|
| 固定阈值 | 上下文使用率达到 70-80% | 简单,但可能压缩过早 |
| 滑动窗口 | 保留最后 N 轮对话 + 摘要 | 可预测的上下文大小 |
| 基于重要性 | 首先压缩低相关性部分 | 复杂,但保留信号 |
| 任务边界 | 在逻辑任务完成时压缩 | 摘要清晰,但时机不可预测 |
对于编码智能体,默认使用带有结构化摘要的滑动窗口——它在可预测性和质量之间提供了最佳平衡。当会话具有清晰的阶段转换时(例如,研究、然后实施、然后测试),使用任务边界触发。
传统的指标如 ROUGE 或嵌入相似性无法捕捉功能性压缩质量。摘要可能在词汇重叠上得分很高,但却遗漏了智能体继续工作所需的那一个文件路径。
使用基于探针的评估:压缩后,提出测试关键信息是否保留的问题。如果智能体回答正确,则压缩保留了正确的信息。否则,它会猜测或产生幻觉。
| 探针类型 | 测试内容 | 示例问题 |
|---|---|---|
| 回忆 | 事实保留 | “原始错误消息是什么?” |
| 工件 | 文件跟踪 | “我们修改了哪些文件?” |
| 延续 | 任务规划 | “我们下一步应该做什么?” |
| 决策 | 推理链 | “关于 Redis 问题我们做出了什么决定?” |
从以下维度评估编码智能体的压缩质量。准确性在不同方法之间显示出最大的差异(0.6 分的差距),使其成为最强的区分因素。工件追踪普遍较弱(2.2-2.5),证实了它需要超越通用摘要的专门处理。
对于超出上下文窗口的代码库或智能体系统,通过三个顺序阶段进行压缩。每个阶段缩小上下文,以便下一阶段在预算内运行。
当提供手动迁移示例或参考 PR 时,将其用作模板来理解目标模式,而不是从头开始探索代码库。该示例揭示了静态分析无法呈现的约束:哪些不变量必须成立、哪些服务在更改时会中断,以及干净的实现是什么样子。
当智能体无法区分本质复杂性(业务需求)和偶然复杂性(遗留解决方案)时,这一点最为重要。示例工件隐式地编码了这种区别,节省了原本用于试错探索的令牌。
在以下情况下使用锚定迭代摘要:
在以下情况下使用不透明压缩:
在以下情况下使用再生式摘要:
| 方法 | 压缩比 | 质量得分 | 权衡 |
|---|---|---|---|
| 锚定迭代 | 98.6% | 3.70 | 质量最佳,压缩率稍低 |
| 再生式 | 98.7% | 3.44 | 质量良好,压缩率中等 |
| 不透明 | 99.3% | 3.35 | 压缩率最佳,质量损失 |
结构化摘要保留的额外 0.7% 令牌换来了 0.35 的质量分——当在多个压缩周期中累积时,这是一个显著的差距。对于任何存在重新获取成本的任务,这种权衡倾向于结构化方法。
示例 1:调试会话压缩
原始上下文(89,000 令牌,178 条消息):
/api/auth/login 端点出现 401 错误压缩后的结构化摘要:
## 会话意图
调试 `/api/auth/login` 在凭据有效的情况下出现 401 未授权错误。
## 根本原因
会话存储中的 Redis 连接陈旧。JWT 生成正确,但会话无法持久化。
## 已修改的文件
- auth.controller.ts: 无更改(仅读取)
- middleware/cors.ts: 无更改(已检查)
- config/redis.ts: 修复了连接池配置
- services/session.service.ts: 为瞬时故障添加了重试逻辑
- tests/auth.test.ts: 更新了模拟设置
## 测试状态
14 个通过,2 个失败(模拟设置问题)
## 后续步骤
1. 修复剩余的测试失败(模拟会话服务)
2. 运行完整的测试套件
3. 部署到预发布环境
示例 2:探针响应质量
压缩后,询问“原始错误是什么?”:
良好响应(结构化摘要):
“原始错误是来自
/api/auth/login端点的 401 未授权响应。用户在凭据有效的情况下收到此错误。根本原因是会话存储中的 Redis 连接陈旧。”
较差响应(激进压缩):
“我们正在调试一个身份验证问题。登录失败。我们修复了一些配置问题。”
结构化响应保留了端点、错误代码和根本原因。激进响应丢失了所有技术细节。
config/redis.ts 时,摘要说“更新了配置文件”会导致重新探索。在专用部分中逐字保留标识符,而不是将它们嵌入到散文中。此技能与集合中的其他几个技能相关联:
内部参考:
本集合中的相关技能:
外部资源:
创建日期 : 2025-12-22 最后更新 : 2026-03-17 作者 : Agent Skills for Context Engineering Contributors 版本 : 1.2.0
每周安装数
56
代码仓库
GitHub 星标数
520
首次出现
2026年1月26日
安全审计
安装于
opencode50
codex49
gemini-cli48
github-copilot48
kimi-cli47
cursor47
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.
Activate this skill when:
Context compression trades token savings against information loss. Select from three production-ready approaches based on session characteristics:
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.
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.
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.
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.
Artifact trail integrity is the weakest dimension across all compression methods, scoring only 2.2-2.5 out of 5.0 in evaluations. Address this proactively because general summarization cannot reliably maintain it.
Preserve these categories explicitly in every compression cycle:
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.
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.
## 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
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.
When to trigger compression matters as much as how to compress. Select a trigger strategy based on session predictability:
| Strategy | Trigger Point | Trade-off |
|---|---|---|
| Fixed threshold | 70-80% context utilization | Simple but may compress 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 |
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).
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.
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.
| 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?" |
Evaluate compression quality for coding agents across these dimensions. Accuracy shows the largest variation between methods (0.6 point gap), making it the strongest discriminator. Artifact trail is universally weak (2.2-2.5), confirming it needs specialized handling beyond general summarization.
For codebases or agent systems exceeding context windows, compress through three sequential phases. Each phase narrows context so the next phase operates within budget.
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.
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.
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.
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.
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.
Use anchored iterative summarization when:
Use opaque compression when:
Use regenerative summaries when:
| Method | Compression Ratio | Quality Score | Trade-off |
|---|---|---|---|
| Anchored Iterative | 98.6% | 3.70 | Best quality, slightly less compression |
| Regenerative | 98.7% | 3.44 | Good quality, moderate compression |
| Opaque | 99.3% | 3.35 | Best compression, quality loss |
The 0.7% additional tokens retained by structured summarization buys 0.35 quality points — a significant gap when compounded over multiple compression cycles. For any task where re-fetching costs exist, this tradeoff favors structured approaches.
Example 1: Debugging Session Compression
Original context (89,000 tokens, 178 messages):
Structured summary after compression:
## Session Intent
Debug 401 Unauthorized error on /api/auth/login despite valid credentials.
## Root Cause
Stale Redis connection in session store. JWT generated correctly but session could not be persisted.
## Files Modified
- auth.controller.ts: No changes (read only)
- middleware/cors.ts: No changes (examined)
- config/redis.ts: Fixed connection pooling configuration
- services/session.service.ts: Added retry logic for transient failures
- tests/auth.test.ts: Updated mock setup
## Test Status
14 passing, 2 failing (mock setup issues)
## Next Steps
1. Fix remaining test failures (mock session service)
2. Run full test suite
3. Deploy to staging
Example 2: Probe Response Quality
After compression, asking "What was the original error?":
Good response (structured summarization):
"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."
Poor response (aggressive compression):
"We were debugging an authentication issue. The login was failing. We fixed some configuration problems."
The structured response preserves endpoint, error code, and root cause. The aggressive response loses all technical detail.
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.
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.
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.
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.
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.
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.
This skill connects to several others in the collection:
Internal reference:
Related skills in this collection:
External resources:
Created : 2025-12-22 Last Updated : 2026-03-17 Author : Agent Skills for Context Engineering Contributors Version : 1.2.0
Weekly Installs
56
Repository
GitHub Stars
520
First Seen
Jan 26, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode50
codex49
gemini-cli48
github-copilot48
kimi-cli47
cursor47
AI界面设计评审工具 - 全面评估UI/UX设计质量、检测AI生成痕迹与优化用户体验
58,500 周安装
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.