Community程式設計與開發github.com

context-compression

此技能適用於長時間運行的代理工作階段,需要進行上下文壓縮、結構化摘要、壓縮、每任務 token 最佳化,或保留決策、檔案、風險與下一步行動的持久交接摘要。

context-compression 是什麼?

此技能專為處理長時間運行的 AI 代理工作階段而設計,當對話歷史紀錄產生數百萬個 token 時,上下文壓縮便成為必要。其核心優化目標是「每任務 token 數」,而非「每請求 token 數」,因為過度壓縮可能導致資訊遺失,進而引發代理重新探索檔案或重新推論,反而消耗更多 token。技能提供三種生產就緒的壓縮方法:錨定迭代摘要(最適合長時間工作階段,能保留檔案追蹤與決策)、不透明壓縮(適合短工作階段,最大化 token 節省,但犧牲可解釋性),以及再生式摘要(適合階段邊界明確的工作階段,但多次壓縮後可能遺失細節)。此外,技能強調使用結構化摘要(包含強制性章節,如作業意圖、修改的檔案、做出的決策與後續步驟),並透過探測式評估而非傳統 ROUGE 指標來驗證壓縮品質。此技能廣泛適用於支援程式碼庫操作或有狀態會話管理的代理平台,如 Claude Code、Cursor 或 Codex。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/context-compression

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

上下文壓縮策略

當代理工作階段產生數百萬個 token 的對話歷史時,壓縮就成為必要條件。天真的方法是進行激進壓縮,以最小化每個請求的 token 數量。正確的優化目標是「每任務 token 數」:從任務開始到完成所消耗的總 token 數,包括因壓縮遺失關鍵資訊而導致的重新擷取成本。

何時啟動

在以下情況啟動此技能:

  • 代理工作階段超過上下文視窗限制
  • 程式碼庫超出上下文視窗(500 萬 token 以上的系統)
  • 設計對話摘要策略
  • 除錯代理「忘記」它修改了哪些檔案的情況
  • 為壓縮品質建立評估框架
  • 建立保留決策、檔案、風險與下一步行動的持久交接摘要

請勿在以下由其他技能負責的相鄰工作中啟動此技能:

  • 一般的 token 效率策略,如遮罩、前綴快取或分區:請使用 context-optimization。
  • 在選擇緩解措施前診斷長上下文失敗的原因:請使用 context-degradation。
  • 將原始輸出、日誌或計劃寫入檔案而不進行摘要:請使用 filesystem-context。
  • 設計跨工作階段的長期語意記憶:請使用 memory-systems。
  • 由模型決定何時以及何處重寫自己的上下文:請使用 self-managed-context。此技能仍掌握替換文字必須保留的內容。

核心概念

上下文壓縮是在 token 節省與資訊遺失之間進行權衡。根據工作階段特性,從三種生產就緒的方法中選擇:

  1. 錨定迭代摘要:為需要檔案追蹤的長時間運行工作階段實施此方法。維護結構化、持久的摘要,並包含工作階段意圖、檔案修改、決策和後續步驟的明確章節。當觸發壓縮時,僅對新截斷的範圍進行摘要,並與現有摘要合併,而不是從頭重新產生。這可以防止在整體重新產生摘要時累積的偏移 — 每次重新產生都可能遺失模型認為優先級較低但任務需要的細節。結構強制保留,因為專門的章節充當摘要器必須填寫的檢查清單,從而捕捉無聲的資訊遺失。

  2. 不透明壓縮:保留用於短工作階段,其中重新擷取成本低且需要最大 token 節省。它產生的壓縮表示經過最佳化,可提高重建保真度,實現 99% 以上的壓縮比,但完全犧牲可解釋性。這種權衡很重要:無法驗證保留了哪些資訊,除非進行基於探針的評估,因此在除錯或工件追蹤至關重要時切勿使用此方法。

  3. 再生式完整摘要:當摘要可讀性至關重要且工作階段具有明確的階段邊界時使用此方法。它在每次觸發壓縮時產生詳細的結構化摘要。其缺點是在重複循環中累積細節遺失 — 每次完整再生都是一次新的處理,可能會降低早期摘要中保留的細節的優先級。

詳細主題

為每任務 token 數而非每請求 token 數進行最佳化

測量從任務開始到完成消耗的總 token 數,而不是每個單獨請求的 token 數。當壓縮遺失檔案路徑、錯誤訊息或決策理由時,代理必須重新探索、重新讀取檔案並重新推論結論 — 這會浪費比壓縮節省的多得多的 token。一個每請求節省 0.5% token 但導致重新擷取成本增加 20% 的策略,總體成本更高。將重新擷取頻率作為主要品質訊號進行追蹤:如果代理重複要求重新讀取已處理過的檔案,則表示壓縮過於激進。

首先解決工件追蹤問題

工件追蹤完整性通常是壓縮評估中最薄弱的維度(claim-context-compression-factory-benchmark)。主動解決此問題,因為一般摘要無法可靠地維護它。

在每個壓縮週期中明確保留以下類別:

  • 建立哪些檔案(完整路徑)
  • 修改哪些檔案以及變更內容(包括函數名稱,而不僅僅是檔案名稱)
  • 讀取但未變更的檔案
  • 特定識別碼:函數名稱、變數名稱、錯誤訊息、錯誤代碼

在代理腳手架中實施單獨的工件索引或明確的檔案狀態追蹤,而不是依賴摘要器來捕捉這些細節。即使是具有專用檔案章節的結構化摘要,在長時間工作階段中也難以確保完整性。

使用強制章節建立摘要

建立具有明確章節的結構化摘要,以防止無聲的資訊遺失。每個章節都充當摘要器必須填寫的檢查清單,使遺漏變得可見,而不是無聲無息。

## 工作階段意圖
[使用者試圖完成什麼]

## 修改的檔案
- auth.controller.ts: 修正 JWT token 生成
- config/redis.ts: 更新連線池
- tests/auth.test.ts: 為新配置新增模擬設定

## 做出的決策
- 使用 Redis 連線池而非每個請求的連線
- 針對暫時性失敗使用指數退避的重試邏輯

## 目前狀態
- 14 個測試通過,2 個失敗
- 待辦事項:為 session 服務測試新增模擬設定

## 後續步驟
1. 修正剩餘的測試失敗
2. 執行完整測試套件
3. 更新文件

根據代理的領域調整章節。除錯代理需要「根本原因」和「錯誤訊息」;遷移代理需要「來源架構」和「目標架構」。結構比特定章節更重要 — 任何明確的綱要都優於自由格式的摘要。

策略性地選擇壓縮觸發時機

何時觸發壓縮與如何壓縮同樣重要。根據工作階段的可預測性選擇觸發策略:

策略觸發點權衡
固定閾值70-80% 上下文利用率簡單但可能過早壓縮
滑動視窗保留最後 N 輪 + 摘要可預測的上下文大小
基於重要性先壓縮低相關性章節複雜但保留訊號
任務邊界在邏輯任務完成時壓縮清晰的摘要但時機不可預測

對於編碼代理,預設使用帶有結構化摘要的滑動視窗 — 它在可預測性和品質之間提供了最佳平衡。當工作階段具有明確的階段轉換(例如,研究、實施,然後測試)時,使用任務邊界觸發器。

使用探針而非指標進行評估

傳統指標(如 ROUGE 或嵌入相似度)無法捕捉功能性的壓縮品質。一個摘要可能詞彙重疊度很高,但卻遺漏了代理繼續工作所需的單一檔案路徑。

使用基於探針的評估:壓縮後,提出測試關鍵資訊是否保留的問題。如果代理正確回答,則壓縮保留了正確的資訊。如果沒有,它會猜測或產生幻覺。

探針類型測試內容範例問題
召回事實保留"原始錯誤訊息是什麼?"
工件檔案追蹤"我們修改了哪些檔案?"
延續任務規劃"我們接下來該做什麼?"
決策推理鏈"關於 Redis 問題我們決定了什麼?"

在六個維度上評分壓縮

在以下維度上評估編碼代理的壓縮品質。準確度和工件追蹤保留往往比詞彙相似度更能區分方法(claim-context-compression-factory-benchmark),因此壓縮需要超出一般摘要的專門處理。

  1. 準確度:技術細節是否正確 — 檔案路徑、函數名稱、錯誤代碼?
  2. 上下文感知:回應是否反映當前會話狀態?
  3. 工件追蹤:代理是否知道哪些檔案被讀取或修改?
  4. 完整性:回應是否解決了問題的所有部分?
  5. 連續性:工作能否在無需重新擷取資訊的情況下繼續?
  6. 指令遵循:回應是否尊重陳述的限制條件?

實用指南

對大型程式碼庫應用三階段壓縮工作流程

對於超出上下文視窗的程式碼庫或代理系統,透過三個順序階段進行壓縮。每個階段縮小上下文,使下一階段能夠在預算內運行。

  1. 研究階段:探索架構圖、文件和關鍵介面。將探索壓縮成對元件、依賴項和邊界的結構化分析。輸出:取代原始探索的單一研究文件。

  2. 規劃階段:將研究文件轉換為包含函數簽名、型別定義和資料流程的實作規格。一個 500 萬 token 的程式碼庫在此階段會壓縮到大約 2,000 字的規格。

  3. 實作階段:根據規格執行。上下文保持專注於規格加上活動中的工作檔案,而不是原始程式碼庫探索。此階段很少需要進一步壓縮,因為規格已經很精簡。

使用範例工件作為壓縮種子

當提供手動遷移範例或參考 PR 時,將其用作模板來理解目標模式,而不是從頭探索程式碼庫。該範例揭示了靜態分析無法呈現的限制條件:哪些不變量必須保持、哪些服務會因變更而中斷,以及乾淨的實作是什麼樣子。

當代理無法區分本質複雜性(業務需求)與偶然複雜性(遺留代碼的變通方法)時,這一點最為重要。範例工件隱含地編碼了這種區別,節省了原本會用於試錯探索的 token。

逐步實施錨定迭代摘要

  1. 定義與代理領域(除錯、遷移、功能開發)匹配的明確摘要章節
  2. 在第一次壓縮觸發時,將截斷的歷史摘要到這些章節中
  3. 在後續壓縮中,僅對新截斷的內容進行摘要 — 不要重新摘要現有摘要
  4. 將新資訊合併到現有章節中,而不是重新產生它們,並根據檔案路徑和決策身份進行去重
  5. 標記哪些資訊來自哪個壓縮週期 — 這可以在摘要偏移時進行除錯

為工作階段檔案選擇正確的方法

在以下情況使用錨定迭代摘要:

  • 工作階段運行時間長(超過 100 條訊息)
  • 檔案追蹤很重要(編碼、除錯)
  • 需要驗證保留的資訊

在以下情況使用不透明壓縮:

  • 需要最大 token 節省
  • 工作階段相對較短
  • 重新擷取成本低(例如,不需要檔案系統存取)

在以下情況使用再生式摘要:

  • 摘要的可解釋性對於人工審查至關重要
  • 工作階段具有明確的階段邊界
  • 每次觸發壓縮時都可以接受完整上下文審查

按方法校準壓縮比

方法壓縮比品質分數權衡
錨定迭代98.6%3.70最佳品質,壓縮率略低
再生式98.7%3.44品質好,壓縮率中等
不透明99.3%3.35最佳壓縮,品質損失

將這些用作特定於來源的基準數字,而不是通用常數(claim-context-compression-factory-benchmark)。對於任何存在重新擷取成本的任務,這種權衡通常有利於結構化方法。

範例

範例 1:除錯工作階段壓縮

原始上下文(89,000 token,178 條訊息):

  • /api/auth/login 端點上的 401 錯誤
  • 追蹤了 auth 控制器、中介軟體、session 儲存
  • 發現過期的 Redis 連線
  • 修正了連線池,新增了重試邏輯
  • 14 個測試通過,2 個失敗

壓縮後的結構化摘要:

## 工作階段意圖
除錯 /api/auth/login 在憑證有效的情況下出現 401 Unauthorized 錯誤。

## 根本原因
session 儲存中的 Redis 連線過期。JWT 生成正確,但 session 無法持久化。

## 修改的檔案
- auth.controller.ts: 無變更(僅讀取)
- middleware/cors.ts: 無變更(已檢查)
- config/redis.ts: 修正連線池配置
- services/session.service.ts: 為暫時性失敗新增重試邏輯
- tests/auth.test.ts: 更新模擬設定

## 測試狀態
14 通過,2 失敗(模擬設定問題)

## 後續步驟
1. 修正剩餘的測試失敗(模擬 session 服務)
2. 執行完整測試套件
3. 部署到暫存環境

範例 2:探針回應品質

壓縮後,詢問 "原始錯誤是什麼?"

良好回應(結構化摘要):

"原始錯誤是來自 /api/auth/login 端點的 401 Unauthorized 回應。使用者使用有效憑證時收到此錯誤。根本原因是 session 儲存中的 Redis 連線過期。"

不良回應(激進壓縮):

"我們正在除錯一個驗證問題。登入失敗。我們修正了一些配置問題。"

結構化回應保留了端點、錯誤代碼和根本原因。激進回應遺失了所有技術細節。

指南

  1. 為每任務 token 數而非每請求 token 數進行最佳化
  2. 使用帶有明確章節的結構化摘要進行檔案追蹤
  3. 在上下文利用率達到 70-80% 時觸發壓縮
  4. 實施增量合併而非完整重新產生
  5. 使用基於探針的評估測試壓縮品質
  6. 如果檔案追蹤至關重要,則單獨追蹤工件追蹤
  7. 接受略低的壓縮比以獲得更好的品質保留
  8. 監控重新擷取頻率作為壓縮品質訊號

注意事項

  1. 切勿壓縮工具定義或綱要:壓縮函數呼叫綱要、API 規格或工具定義會完全破壞代理功能。代理無法調用

…

[為翻譯而截斷]

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

tool-design

This skill should be used for the tool-interface layer of an agent system specifically: writing tool descriptions agents can route on, designing tool schemas and response formats, naming conventions, actionable error recovery messages, MCP server design, tool-set consolidation, and deciding when to add or remove an individual tool. Use this when the unit of work is a single tool or a set of tools. Route project-shape, pipeline architecture, and task-model-fit decisions to project-development; route deciding whether to introduce sub-agents to multi-agent-patterns.

相關技能