mcpField
C
context-management

context-management

github.com/rysweetAgent 工作流76168 次安装21 周前更新
代码仓库

关于 context-management

context-management 是面向 Claude Code 长会话的上下文管理技能,可监测 token 使用情况,并在压缩前保存重点、之后按需恢复。它通过优先级保留需求、决策和进度,并提供预测、健康状态指示及自动化管理。

主要功能

  1. 01监测 token 用量与消耗速度
  2. 02预测容量阈值并提供建议
  3. 03按优先级创建上下文快照
  4. 04按详略级别恢复上下文
  5. 05提供会话健康指示
  6. 06通过 Hook 自动监控与恢复

适用场景

  1. 01长会话中提前保存关键进度
  2. 02压缩后恢复需求和当前状态
  3. 03暂停任务或交接时打包上下文
  4. 04在 statusline 查看会话健康状况

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/rysweet/amplihack --skill context-management

安装后在 Claude Code 中输入/context-management确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

QUICK_START.md
README.md
__init__.py
automation.py
context_extractor.py
context_rehydrator.py
core.py
models.py
orchestrator.py
test_full_automation_flow.py
test_model_aware_thresholds.py
test_performance.py
test_real_hook_integration.py
test_with_real_transcript.py
token_monitor.py
examples/
basic_usage.md
proactive_management.md
proactive_workflow.md
rehydration_levels.md
tests/
__init__.py
test_context_extractor.py
test_context_rehydrator.py
test_integration.py
test_orchestrator.py
test_token_monitor.py
tests/fixtures/
high_token_usage.json
sample_conversation.json
sample_snapshot.json

详细介绍

上下文管理技能

用途

此技能通过智能 Token 监控、上下文提取和选择性恢复,主动管理 Claude Code 的上下文窗口。此技能不必等到压缩后才被动恢复,而是帮助用户在达到限制前保留关键上下文,并在需要时高效恢复。

版本 3.0 增强功能:

  • 预测性预算监控:估算何时会达到容量阈值
  • 上下文健康指标:为状态栏集成提供可视化指标
  • 基于优先级的保留:保留需求和决策,将冗长日志归档
  • 消耗速率跟踪:监控 Token 消耗速度,提前发出警告

何时使用此技能

  • Token 监控:检查当前用量并获取建议
  • 接近限制:在用量达到 70-85% 时创建快照
  • 压缩后:无需恢复完整对话即可还原关键上下文
  • 长会话:主动保留关键决策和状态
  • 复杂任务:确保需求和进度便于查阅
  • 切换上下文:暂停工作时保存状态
  • 团队交接:打包上下文,方便他人继续工作
  • 预测性规划:在达到容量上限前获取预警
  • 会话健康状况:监控上下文健康状况,保持高效工作

快速开始

检查 Token 状态
User: Check my current token usage

我将使用 context_manager 工具检查状态:

from context_manager import check_context_status

status = check_context_status(current_tokens=<current_count>)
# Returns: ContextStatus with usage percentage and recommendations
创建快照
User: Create a context snapshot named "auth-implementation"

我将使用 context_manager 工具创建快照:

from context_manager import create_context_snapshot

snapshot = create_context_snapshot(
    conversation_data=<conversation_history>,
    name="auth-implementation"
)
# Returns: ContextSnapshot with snapshot_id, file_path, and token_count
恢复上下文
User: Restore context from snapshot <snapshot_id> at essential level

我将使用 context_manager 工具恢复上下文:

from context_manager import rehydrate_from_snapshot

context = rehydrate_from_snapshot(
    snapshot_id="20251116_143522",
    level="essential"  # or "standard" or "comprehensive"
)
# Returns: Formatted context text ready to process
列出快照
User: List my context snapshots

我将使用 context_manager 工具列出快照:

from context_manager import list_context_snapshots

snapshots = list_context_snapshots()
# Returns: List of snapshot metadata dicts

详细程度

恢复上下文时,请选择合适的详细程度:

  • 精简(最少):仅包含需求和当前状态(约 250 个 Token)
  • 标准(均衡):+ 关键决策 + 未完成事项(约 800 个 Token)
  • 全面(完整):+ 完整决策 + 使用的工具 + 元数据(约 1,250 个 Token)

从精简级别开始,如果需要更多上下文,再升级级别。

操作

操作:status

检查当前 Token 用量并获取建议。

用法:

from context_manager import check_context_status

status = check_context_status(current_tokens=750000)
print(f"Usage: {status.percentage}%")
print(f"Status: {status.threshold_status}")
print(f"Recommendation: {status.recommendation}")

返回:

  • 包含用量详情的 ContextStatus 对象
  • threshold_status:'ok'、'consider'、'recommended' 或 'urgent'
  • recommendation:易于理解的操作建议
操作:snapshot

创建智能上下文快照。

用法:

from context_manager import create_context_snapshot

snapshot = create_context_snapshot(
    conversation_data=messages,
    name="feature-name"  # Optional
)
print(f"Snapshot ID: {snapshot.snapshot_id}")
print(f"Token count: {snapshot.token_count}")
print(f"Saved to: {snapshot.file_path}")

返回:

  • 包含元数据的 ContextSnapshot 对象
  • 快照保存至 ~/.amplihack/.claude/runtime/context-snapshots/
操作:rehydrate

按指定的详细程度从快照恢复上下文。

用法:

from context_manager import rehydrate_from_snapshot

context = rehydrate_from_snapshot(
    snapshot_id="20251116_143522",
    level="standard"  # essential, standard, or comprehensive
)
print(context)  # Display restored context

返回:

  • 包含恢复后上下文的格式化 Markdown 文本
  • 可立即处理并继续工作
操作:list

列出所有可用的上下文快照。

用法:

from context_manager import list_context_snapshots

snapshots = list_context_snapshots()
for snapshot in snapshots:
    print(f"{snapshot['id']}: {snapshot['name']} ({snapshot['size']})")

返回:

  • 快照元数据字典列表
  • 包含:id、name、timestamp、size、token_count

主动功能(v3.0)

预测性预算监控

不只检查当前用量,还可以预测何时会达到阈值:

# The system tracks token burn rate over time
# When checking status, you get predictive insights

status = check_context_status(current_tokens=500000)

# Status includes predictions (when automation is running):
# - Estimated tool uses until 70% threshold
# - Time estimate based on current burn rate
# - Early warning before you hit capacity

# Example output interpretation:
# "At current rate, you'll hit 70% in ~15 tool uses"
# "Consider creating a checkpoint before your next major operation"

预测方式:

自动化流程会跟踪:

  1. 每次检查时的 Token 数量
  2. 两次检查之间的工具使用次数
  3. 每次工具调用平均消耗的 Token 数
  4. 两次检查之间经过的时间

根据这些数据,它会估算:

  • 达到阈值前剩余的工具调用次数
  • 距离达到阈值的大致时间
  • 当前任务能否在达到限制前完成
上下文健康指标

适用于状态行集成的会话健康状况可视化指标:

指标含义使用率建议操作
[CTX:OK]健康0-30%正常继续
[CTX:WATCH]监控30-50%规划检查点
[CTX:WARN]警告50-70%尽快创建快照
[CTX:CRITICAL]严重70%+立即创建快照

状态行集成示例:

# In your statusline script, check context health:
# The automation state file contains health status

# Example statusline addition:
if [ -f ".claude/runtime/context-automation-state.json" ]; then
    LAST_PCT=$(jq -r '.last_percentage // 0' .claude/runtime/context-automation-state.json)
    if [ "$LAST_PCT" -lt 30 ]; then
        echo "[CTX:OK]"
    elif [ "$LAST_PCT" -lt 50 ]; then
        echo "[CTX:WATCH]"
    elif [ "$LAST_PCT" -lt 70 ]; then
        echo "[CTX:WARN]"
    else
        echo "[CTX:CRITICAL]"
    fi
fi
基于优先级的上下文保留

创建快照时,系统会按重要性对内容进行优先级排序:

高优先级(始终保留):

  • 用户的原始需求(第一条用户消息)
  • 关键架构决策
  • 当前实现状态
  • 待处理事项和阻碍因素

中优先级(标准及以上级别保留):

  • 工具使用历史
  • 决策理由
  • 问题和澄清内容

低优先级(仅在全面级别保留):

  • 详细的输出日志
  • 中间步骤
  • 调试信息

使用模式:

# Create snapshot with priority awareness
snapshot = create_context_snapshot(
    conversation_data=messages,
    name='feature-checkpoint'
)

# Essential level (~200 tokens): Only high priority content
# Standard level (~800 tokens): High + medium priority
# Comprehensive level (~1250 tokens): Everything

# Start minimal, upgrade as needed:
context = rehydrate_from_snapshot(snapshot_id, level='essential')
消耗速率跟踪

监控上下文的消耗速度:

# The automation tracks consumption velocity
# Adaptive checking frequency based on burn rate:

# Low burn rate (< 1K tokens/tool): Check every 50 tools
# Medium burn rate (1-5K tokens/tool): Check every 10 tools
# High burn rate (> 5K tokens/tool): Check every 3 tools
# Critical zone (70%+): Check every tool

# This means:
# - Normal development: Minimal overhead (checks rarely)
# - Large file operations: Increased monitoring
# - Approaching limits: Continuous monitoring

消耗速率阈值:

消耗速率风险级别监控频率
< 1K/tool低每 50 个工具检查一次
1-5K/tool中每 10 个工具检查一次
> 5K/tool高每 3 个工具检查一次
任意速率且达到 70%+严重每个工具都检查
自动摘要触发条件

系统会在达到限制之前自动创建快照:

# Automatic snapshot triggers (already implemented):
# - 30% usage: First checkpoint created
# - 40% usage: Second checkpoint created
# - 50% usage: Third checkpoint created (for 1M models)

# For smaller context windows (< 800K):
# - 55% usage: First checkpoint
# - 70% usage: Second checkpoint
# - 85% usage: Urgent checkpoint

# After compaction detected (30% token drop):
# - Automatically rehydrates from most recent snapshot
# - Uses smart level selection based on previous usage

主动使用工作流

步骤 1:监控 Token 使用量

在较长的会话中定期检查状态:

status = check_context_status(current_tokens=current)

if status.threshold_status == 'consider':
    # Usage at 70%+ - consider creating snapshot
    print("Consider creating a snapshot soon")
elif status.threshold_status == 'recommended':
    # Usage at 85%+ - snapshot recommended
    create_context_snapshot(messages, name='current-work')
elif status.threshold_status == 'urgent':
    # Usage at 95%+ - create snapshot immediately
    create_context_snapshot(messages, name='urgent-backup')
步骤 2:达到阈值时创建快照

达到 70-85% 阈值时,创建一个命名快照:

snapshot = create_context_snapshot(
    conversation_data=messages,
    name='descriptive-name'
)
# Save snapshot ID for later rehydration
步骤 3:继续工作

创建快照后:

  • 自然地继续对话
  • 如有需要,让 Claude Code 进行压缩
  • 如需查看完整历史记录,可使用 /transcripts
  • PreCompact hook 会自动保存所有内容
步骤 4:压缩后重新载入上下文

压缩后,恢复必要的上下文:

# Start minimal
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='essential'
)

# If more context needed, upgrade to standard
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='standard'
)

# For complete context, use comprehensive
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='comprehensive'
)

与现有系统集成

与 PreCompact Hook 的对比

PreCompact Hook(自动安全网):

  • 由 Claude Code 在压缩前触发
  • 保存完整的对话记录
  • 自动运行,无需用户操作
  • 将完整对话导出为 Markdown

Context Skill(主动优化):

  • 根据监控结果由用户触发
  • 保存经过智能提取的上下文
  • 由用户主动发起,有意选择
  • 仅保留必要上下文,而非完整内容

关系:二者相辅相成,并不冲突。Hook = 安全网,Skill = 优化。

与 /transcripts 命令的对比

/transcripts(被动恢复):

  • 在压缩后恢复完整对话
  • 包含完整历史记录和所有消息
  • 需要恢复所有内容时使用
  • 被动恢复工具

Context Skill(主动保留):

  • 在压缩前保留必要上下文
  • 选择性地重新载入,而非恢复完整历史记录
  • 需要高效管理上下文时使用
  • 主动优化工具

关系:使用 transcripts 完整恢复,使用 skill 高效管理。

存储位置
  • 快照:~/.amplihack/.claude/runtime/context-snapshots/(JSON)
  • 对话记录:~/.amplihack/.claude/runtime/logs/<session_id>/CONVERSATION_TRANSCRIPT.md
  • 互不冲突:目录不同,用途不同

自动管理

上下文管理通过 post_tool_use hook 自动运行:

  • 每隔 N 次工具调用监控 Token 使用量(自适应频率)
  • 达到阈值时创建快照(1M 模型为 30%、40%、50%)
  • 检测压缩(Token 减少 > 30%)
  • 压缩后在适当级别自动重新载入上下文

此过程会透明运行,无需用户干预。

实现

所有上下文管理功能均由以下组件提供:

  • 工具:~/.amplihack/.claude/tools/amplihack/context_manager.py
  • 钩子集成:~/.amplihack/.claude/tools/amplihack/context_automation_hook.py
  • 钩子系统:~/.amplihack/.claude/tools/amplihack/hooks/tool_registry.py

请参阅工具文档,了解完整的 API 参考和实现详情。

常见模式

模式 1:预防性快照

在长时间操作前进行检查,并在需要时创建快照:

status = check_context_status(current_tokens=current)
if status.threshold_status in ['recommended', 'urgent']:
    create_context_snapshot(messages, name='before-refactoring')
模式 2:上下文切换

暂停某项功能的工作以开始另一项功能时,保存状态:

# Pausing work on Feature A
create_context_snapshot(messages, name='feature-a-paused')

# [... work on Feature B ...]

# Resume Feature A later
context = rehydrate_from_snapshot('feature-a-snapshot-id', level='standard')
模式 3:团队交接

为队友创建全面的快照:

snapshot = create_context_snapshot(
    messages,
    name='handoff-to-alice-api-work'
)
# Share snapshot ID with teammate
# Alice can rehydrate and continue work

理念契合

极致简洁
  • 一个工具中包含四个单一用途的组件
  • 按需调用,无后台进程
  • 仅使用标准库,无外部依赖
  • 提供清晰的公共 API 和便捷函数
单一职责
  • ContextManager 协调所有操作
  • 在同一处进行 Token 监控、提取和恢复
  • 没有重复代码或分散的逻辑
零虚假实现
  • 没有存根或占位符
  • 所有函数均可完整运行
  • 使用真实的 Token 估算,而非伪造数据
  • 执行实际文件操作,而非模拟操作
信任自然演进
  • 由用户决定何时创建快照,而非自动创建(除非通过钩子)
  • 由用户选择详细程度,而非由系统决定
  • 主动选择让用户更有掌控力

有效管理上下文的提示

  1. 定期监控:在自然的工作间隙检查状态
  2. 适时创建快照:在使用量达到 70-85% 时,或长时间操作前创建
  3. 从精简开始:先使用 essential 级别,需要时再提高
  4. 使用描述性名称:为快照取清晰的名称,便于日后查找
  5. 定期列出快照:检查并清理旧快照
  6. 组合使用工具:配合 /transcripts 使用,以便完整恢复
  7. 信任自然演进:不要过度创建快照,让上下文自然流动

资源

  • 工具:~/.amplihack/.claude/tools/amplihack/context_manager.py
  • 钩子:~/.amplihack/.claude/tools/amplihack/context_automation_hook.py
  • 理念:~/.amplihack/.claude/context/PHILOSOPHY.md
  • 模式:~/.amplihack/.claude/context/PATTERNS.md

请记住

此技能通过一个简洁、可复用的工具提供主动式上下文管理。该工具可从技能、命令和钩子中调用。它与现有工具(PreCompact 钩子、/transcripts)相辅相成,而非取而代之。使用它可在长时间会话中保持上下文整洁、高效。

关键要点:业务逻辑位于 context_manager.py 中,此技能只负责说明如何使用它。

评论

支持 Markdown