Communitygithub.com

战略压缩技能

建议在逻辑阶段节点进行手动上下文压缩,以在任务阶段之间保留关键上下文,而非依赖任意的自动压缩。当会话接近上下文限制且任务阶段适合压缩时使用。

战略压缩技能 是什么?

战略压缩技能是一个针对AI编码助手(如Claude Code)的专业工具,旨在帮助开发者优化会话上下文窗口的使用。它通过智能检测会话上下文大小(基于令牌数)和工具调用频率,在逻辑任务边界(如从研究过渡到规划,或完成里程碑后)主动建议手动执行/compact命令。技能支持200K和1M令牌窗口的自动阈值缩放,并提供可配置的环境变量(COMPACT_THRESHOLD、COMPACT_CONTEXT_THRESHOLD等)以适应不同模型。核心价值在于避免自动压缩打断复杂多步骤操作,同时防止上下文碎片化——通过仅在真正需要的时刻(如上下文接近窗口上限)发出建议,并允许用户在压缩前将关键状态保存到文件。此外,技能还提供压缩决策表、令牌优化模式(如触发器表惰性加载、重复指令检测)和持久化洞察(如CLAUDE.md文件、内存文件、Git状态会保留,而中间推理和对话历史会丢失),帮助开发者高效管理会话上下文。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

战略压缩技能 是做什么的?

建议在工作流程中的战略节点手动执行 /compact,而不是依赖任意的自动压缩。

何时激活

  • 运行长时间会话即将达到上下文上限(200K+ 令牌)
  • 处理多阶段任务(研究 → 计划 → 实现 → 测试)
  • 在同一会话中切换不相关的任务
  • 完成重大里程碑并开始新工作时
  • 当响应变慢或变得不连贯时(上下文压力)

为什么需要战略压缩?

自动压缩在任意节点触发:

  • 经常在任务中途触发,丢失重要上下文
  • 不了解逻辑任务边界
  • 可能中断复杂的多步骤操作

在逻辑边界处进行战略压缩:

  • 探索完成后,执行之前 — 压缩研究上下文,保留实现计划
  • 完成里程碑后 — 为下一阶段重新开始
  • 重大上下文切换前 — 在开始不同任务前清除探索上下文

工作原理

suggest-compact.js 脚本在 PreToolUse (Edit/Write) 时运行,结合两种信号:

  1. 上下文大小(主要信号) — 从会话记录(transcript_path 在 hook payload 中)读取最新的 usage 记录,计算 input_tokens + cache_read_input_tokens + cache_creation_input_tokens(本次轮对话的真实上下文大小)。在窗口缩放的阈值下建议 /compact — 200K 窗口下 160K 令牌,1M 窗口下 250K(从 [1m] 模型标记检测,或当观察到的令牌已超过 200K 时推断)— 此后每增加 60K 上下文令牌则再次提醒
  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 — 上下文大小建议触发前的上下文令牌数(默认:200K 窗口下 160000,1M 窗口下 250000;0 禁用上下文信号)
  • COMPACT_CONTEXT_INTERVAL — 建议重复前的额外上下文令牌数(默认:60000)
  • COMPACT_STATE_TTL_DAYS — temp 目录中过时的每会话状态文件在被清理前的保留天数(默认:14)
  • ECC_CONTEXT_WINDOW_TOKENS — 显式上下文窗口大小(令牌数),覆盖自动检测。对报告 ID 中缺少 [1m] 标记的大窗口模型(例如 400K Opus 4.x,或新的 1M 窗口模型系列)进行设置,以便阈值缩放到实际窗口,而不是默认使用 200K 并高估上下文使用量。
  • CLAUDE_CODE_AUTO_COMPACT_WINDOW — Claude Code 的原生窗口大小覆盖,令牌数;在 ECC_CONTEXT_WINDOW_TOKENS 未设置时作为后备使用。

否则上下文窗口从 [1m] 模型标记自动检测,或在观察到的令牌已超过 200K 时推断。对于同时缺失这两个信号的大窗口模型,请设置上述一个覆盖项,以使 /compact 建议在正确的时间触发。

压缩决策指南

使用此表来决定何时压缩:

阶段转换压缩?原因
研究 → 规划是研究上下文很庞大;计划是提炼后的输出
规划 → 实现是计划已写入文件(文件,或如果有的话是任务列表);为代码释放上下文
实现 → 测试可能如果测试引用最新代码则保留;如果切换焦点则压缩
调试 → 下一个功能是调试痕迹会污染无关工作的上下文
实现中否丢失变量名、文件路径和部分状态代价很高
失败方法后是在尝试新方法前清除死胡同推理

压缩后保留的内容

了解哪些内容持久存在,有助于你放心地压缩:

保留丢失
CLAUDE.md 指令中间推理和分析
磁盘上的文件你之前读取的文件内容
内存文件(~/.claude/memory/)多步骤对话上下文
Git 状态(提交、分支)工具调用历史和计数
任务列表 — 仅当你有待办工具时(见下文)口头表达的用户细微偏好

不要依赖任务列表的持久性 — 它可能不存在

Claude Code 2.1.233 在 Opus 4.8、Sonnet 5、Fable 5、Mythos 5 及更新模型上默认移除了待办/任务工具(TodoWrite、TaskCreate/Get/Update/List)。CLAUDE_CODE_ENABLE_TODO_TOOLS=1 可以恢复它们,但这是一个按机器的环境设置 — 它不随此技能一起传播,因此你不能假定读者拥有它。

这一点很重要,因为“我的待办列表在压缩后幸存”是人们选择压缩而不是写下状态的原因。如果工具不存在,列表就无法幸存,计划也就直接消失了。请在压缩前将计划写入文件 — 文件在每个版本和每个模型上都持久。将任务列表视为一个可能缺失的便利设施,永远不要将其视为你的持久记录。

最佳实践

  1. 规划后压缩 — 一旦计划最终确定并写入文件,压缩以重新开始
  2. 调试后压缩 — 在继续之前清除错误分析上下文
  3. 不要在实现过程中压缩 — 保留相关更改的上下文
  4. 阅读建议 — hook 告诉你何时,你决定是否
  5. 压缩前写入 — 在压缩前将重要上下文保存到文件或内存中
  6. 使用带摘要的 /compact — 添加自定义消息:/compact 接下来专注于实现认证中间件

令牌优化模式

触发器表惰性加载

不在会话开始时加载完整的技能内容,而是使用将关键字映射到技能路径的触发器表。技能仅在触发时加载,将基线上下文减少 50% 以上:

触发器技能加载时机
"test", "tdd", "coverage"tdd-workflow用户提到测试
"security", "auth", "xss"security-review安全相关工作
"deploy", "ci/cd"deployment-patterns部署上下文

上下文构成意识

监控什么在消耗你的上下文窗口:

  • CLAUDE.md 文件 — 始终加载,保持精简
  • 加载的技能 — 每个技能增加 1-5K 令牌
  • 对话历史 — 随每次交互增长
  • 工具结果 — 文件读取、搜索结果增加体积

重复指令检测

重复上下文的常见来源:

  • 同时在 ~/.claude/rules/ 和项目 .claude/rules/ 中存在相同的规则
  • 重复 CLAUDE.md 指令的技能
  • 覆盖重叠领域的多个技能

上下文优化工具

  • token-optimizer MCP — 通过内容去重实现 95%+ 的自动令牌减少
  • context-mode — 上下文虚拟化(已演示从 315KB 到 5.4KB)

相关内容

  • 长篇指南 — 令牌优化部分
  • 内存持久化 hook — 用于在压缩后幸存的状态
  • 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相关技能