Communitygithub.com

戰略性壓縮技巧

在邏輯間隔點建議手動上下文壓縮,以保留任務階段間的上下文,而非依賴任意自動壓縮。在會話接近上下文限制且任務階段是自然的壓縮時機時使用。

戰略性壓縮技巧 是什麼?

此技巧旨在幫助開發者與AI代理(如Claude Code)在長時間會話中,於邏輯任務邊界手動執行 `/compact`,而非依賴任意觸發的自動壓縮。它透過監控上下文大小(輸入token + 快取讀取token + 快取創建token)和工具呼叫次數兩個訊號,在適當的時機(例如研究結束準備實作、完成重大里程碑後)提出壓縮建議。支援手動安裝或作為外掛程式使用,可透過環境變數調整閾值。策略性壓縮能保留重要狀態(如檔案、記憶、Git狀態),同時清除中間推理與工具歷史,從而提升會話效率與連貫性。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/strategic-compact

在你喜歡的 AI 中提問

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

說明文件

戰略性壓縮技巧 是做什麼的?

建議在工作流程的戰略性節點手動執行 /compact,而非依賴任意的自動壓縮。

啟用時機

  • 執行長時間會話,接近上下文限制(200K+ tokens)
  • 處理多階段任務(研究 → 規劃 → 實作 → 測試)
  • 在同一會話中切換不相關的任務
  • 完成主要里程碑並開始新工作後
  • 回應變慢或變得不連貫時(上下文壓力)

為什麼要戰略性壓縮?

自動壓縮會在任意節點觸發:

  • 常在任務中途觸發,遺失重要上下文
  • 不認識邏輯任務邊界
  • 可能中斷複雜的多步驟操作

在邏輯邊界進行戰略性壓縮:

  • 探索後,執行前 — 壓縮研究上下文,保留實作計劃
  • 完成里程碑後 — 為下一階段重新開始
  • 重大上下文切換前 — 清除探索上下文,再進行不同任務

運作方式

suggest-compact.js 腳本在 PreToolUse (Edit/Write) 時執行,結合兩種訊號:

  1. 上下文大小(主要) — 從會話記錄(hook payload 中的 transcript_path)讀取最新的 usage 記錄,並加總 input_tokens + cache_read_input_tokens + cache_creation_input_tokens(該輪的真實上下文大小)。在視窗縮放閾值(200k 視窗為 160k tokens,1M 視窗為 250k tokens,後者透過 [1m] 模型標記偵測,或當觀察到的 tokens 已超過 200k 時推斷)時建議 /compact,並且在每次額外增加 60k tokens 的上下文增長後再次提醒。
  2. 工具呼叫次數(次要) — 計算會話中的工具調用次數;在可配置的閾值(預設:50 次)時建議,之後每 25 次呼叫再次建議。

單獨的工具呼叫次數是視窗壓力的弱代理:幾次大型檔案讀取或 MCP 回應即可在極少呼叫下填滿視窗,而大量小型呼叫可能在接近空視窗時就跨越 50 次。上下文大小訊號會在真正重要時觸發。

Hook 設定

以插件形式安裝? 無需設定。插件的 hooks/hooks.json 已註冊 suggest-compact.js(hook id pre:edit-write:suggest-compact,在 standard 和 strict hook 設定檔中啟用)。請勿將下方區塊複製到 ~/.claude/settings.json 中 — 插件安裝時不存在 ~/.claude/scripts/,且重複的插件 hook 會導致雙重執行。

若手動安裝 (./install.sh),請加入你的 ~/.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [{ "type": "command", "command": "node ~/.claude/scripts/hooks/suggest-compact.js" }]
      },
      {
        "matcher": "Write",
        "hooks": [{ "type": "command", "command": "node ~/.claude/scripts/hooks/suggest-compact.js" }]
      }
    ]
  }
}

設定

環境變數:

  • COMPACT_THRESHOLD — 首次建議前的工具呼叫次數(預設:50)
  • COMPACT_CONTEXT_THRESHOLD — 上下文大小建議前的上下文 tokens 數(預設:200k 視窗為 160000,1M 視窗為 250000;設為 0 可停用上下文訊號)
  • COMPACT_CONTEXT_INTERVAL — 建議重複前的額外上下文 tokens 數(預設:60000)
  • COMPACT_STATE_TTL_DAYS — 暫存目錄中過時的每會話狀態檔案清理前的天數(預設:14)
  • ECC_CONTEXT_WINDOW_TOKENS — 明確上下文視窗大小(以 tokens 為單位),覆蓋自動偵測。對於報告的 ID 缺少 [1m] 標記的大視窗模型(例如 400k Opus 4.x 或新的 1M 視窗模型系列),設定此變數可使閾值縮放到真實視窗,而不是預設為 200k 並高估上下文使用量。
  • CLAUDE_CODE_AUTO_COMPACT_WINDOW — Claude Code 的原生視窗大小覆蓋(以 tokens 為單位);在 ECC_CONTEXT_WINDOW_TOKENS 未設定時作為備用。

上下文視窗會從 [1m] 模型標記自動偵測,或當觀察到的 tokens 已超過 200k 時推斷。在同時缺少這兩個訊號的大視窗模型上,請設定其中一個覆蓋變數,以便 /compact 建議在正確的時機觸發。

壓縮決策指南

使用此表格決定何時壓縮:

階段轉換壓縮?原因
研究 → 規劃是研究上下文龐大;規劃是提煉後的輸出
規劃 → 實作是規劃已寫入檔案(或任務列表,如果有);為程式碼騰出上下文
實作 → 測試也許如果測試引用近期程式碼則保留;如果轉移焦點則壓縮
除錯 → 下一個功能是除錯追蹤會污染不相關工作的上下文
實作中途否遺失變數名稱、檔案路徑和部分狀態的代價很高
失敗方法後是嘗試新方法前,清除走入死胡同的推理

壓縮後保留什麼

了解保留的內容有助於你放心壓縮:

保留遺失
CLAUDE.md 指示中間推理與分析
磁碟上的檔案先前讀取的檔案內容
記憶檔案 (~/.claude/memory/)多步驟對話上下文
Git 狀態(提交、分支)工具呼叫歷史與計數
任務列表 — 僅當你擁有 todo 工具時(見下方)以口頭陳述的細微使用者偏好

不要依賴任務列表保留 — 它可能不存在

Claude Code 2.1.233 在 Opus 4.8、Sonnet 5、Fable 5、Mythos 5 及更新型號上移除了預設的 todo/task 工具(TodoWrite、TaskCreate/Get/Update/List)。 CLAUDE_CODE_ENABLE_TODO_TOOLS=1 可以恢復它們,但這是每台機器的環境設定 — 它不會隨此技巧轉移,因此你無法假設讀者擁有它。

這很重要,因為「我的 todo 列表在壓縮後保留」是人們選擇壓縮而不是將狀態寫下來的原因。如果工具不存在,就沒有列表可以保留,計劃就這麼消失了。在壓縮前將計劃寫入檔案 — 檔案在所有版本和所有型號上都會保留。將任務列表視為可能缺失的便利功能,而不是你的持久記錄。

最佳實務

  1. 規劃後壓縮 — 一旦計劃最終確定並寫入檔案,壓縮以重新開始
  2. 除錯後壓縮 — 清除錯誤解析上下文後再繼續
  3. 不要在實作中途壓縮 — 為相關變更保留上下文
  4. 閱讀建議 — Hook 告訴你何時,你決定是否
  5. 先寫再壓縮 — 在壓縮前將重要上下文儲存到檔案或記憶中
  6. 使用 /compact 附帶摘要 — 加入自訂訊息:/compact 接下來專注於實作認證中介層

Token 最佳化模式

觸發表延遲載入

與其在會話開始時載入完整的技巧內容,不如使用觸發表將關鍵字對應到技巧路徑。技巧僅在觸發時載入,可將基準上下文減少 50% 以上:

觸發詞技巧載入時機
"test", "tdd", "coverage"tdd-workflow使用者提及測試
"security", "auth", "xss"security-review安全性相關工作
"deploy", "ci/cd"deployment-patterns部署上下文

上下文組成感知

監控什麼消耗了你的上下文視窗:

  • CLAUDE.md 檔案 — 總是載入,保持精簡
  • 已載入的技巧 — 每個技巧增加 1-5K tokens
  • 對話歷史 — 隨著每次交換增長
  • 工具結果 — 檔案讀取、搜尋結果增加負擔

重複指令偵測

常見的重複上下文來源:

  • 在 ~/.claude/rules/ 和專案 .claude/rules/ 中有相同的規則
  • 重複 CLAUDE.md 指示的技巧
  • 多個技巧涵蓋重疊領域

上下文最佳化工具

  • token-optimizer MCP — 透過內容去重實現自動化 95%+ token 減少
  • context-mode — 上下文虛擬化(已展示從 315KB 到 5.4KB)

相關

  • The Longform Guide — Token 最佳化章節
  • 記憶持久化 hooks — 用於在壓縮後存活的狀態
  • continuous-learning 技巧 — 在會話結束前提取模式

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能