context-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Context Management Skill

上下文管理Skill

Purpose

用途

This skill enables proactive management of Claude Code's context window through intelligent token monitoring, context extraction, and selective rehydration. Instead of reactive recovery after compaction, this skill helps users preserve essential context before hitting limits and restore it efficiently when needed.
Version 3.0 Enhancements:
  • Predictive Budget Monitoring: Estimate when capacity thresholds will be reached
  • Context Health Indicators: Visual indicators for statusline integration
  • Priority-Based Retention: Keep requirements and decisions, archive verbose logs
  • Burn Rate Tracking: Monitor token consumption velocity for early warnings
该Skill可通过智能Token监控、上下文提取和选择性复现,实现Claude Code上下文窗口的主动式管理。不同于压缩后的被动恢复,该Skill能帮助用户在达到限制前保留关键上下文,并在需要时高效恢复。
V3.0版本增强功能:
  • 预测性预算监控:预估何时会达到容量阈值
  • 上下文健康指标:适用于状态栏集成的可视化指标
  • 基于优先级的保留:保留需求和决策内容,归档冗长日志
  • 消耗速率跟踪:监控Token消耗速度以提前发出预警

When to Use This Skill

使用场景

  • Token monitoring: Check current usage and get recommendations
  • Approaching limits: Create snapshots at 70-85% usage
  • After compaction: Restore essential context without full conversation
  • Long sessions: Preserve key decisions and state proactively
  • Complex tasks: Keep requirements and progress accessible
  • Context switching: Save state when pausing work
  • Team handoffs: Package context for others to continue
  • Predictive planning: Get early warnings before capacity is reached
  • Session health: Monitor context health for sustained productivity
  • Token监控:查看当前使用情况并获取建议
  • 接近限制时:在使用率70-85%时创建快照
  • 压缩后:无需完整对话即可恢复关键上下文
  • 长会话:主动保留关键决策和状态
  • 复杂任务:让需求和进度随时可查
  • 上下文切换:暂停工作时保存状态
  • 团队交接:打包上下文以便他人继续工作
  • 预测性规划:在容量耗尽前获取早期预警
  • 会话健康:监控上下文健康状况以维持生产力

Quick Start

快速入门

Check Token Status

检查Token状态

User: Check my current token usage
I'll use the
context_manager
tool to check status:
python
from context_manager import check_context_status

status = check_context_status(current_tokens=<current_count>)
User: Check my current token usage
我会使用
context_manager
工具检查状态:
python
from context_manager import check_context_status

status = check_context_status(current_tokens=<current_count>)

Returns: ContextStatus with usage percentage and recommendations

返回:包含使用率百分比和建议的ContextStatus对象

undefined
undefined

Create a Snapshot

创建快照

User: Create a context snapshot named "auth-implementation"
I'll use the
context_manager
tool to create a snapshot:
python
from context_manager import create_context_snapshot

snapshot = create_context_snapshot(
    conversation_data=<conversation_history>,
    name="auth-implementation"
)
User: Create a context snapshot named "auth-implementation"
我会使用
context_manager
工具创建快照:
python
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

返回:包含snapshot_id、file_path和token_count的ContextSnapshot对象

undefined
undefined

Restore Context

恢复上下文

User: Restore context from snapshot <snapshot_id> at essential level
I'll use the
context_manager
tool to rehydrate:
python
from context_manager import rehydrate_from_snapshot

context = rehydrate_from_snapshot(
    snapshot_id="20251116_143522",
    level="essential"  # or "standard" or "comprehensive"
)
User: Restore context from snapshot <snapshot_id> at essential level
我会使用
context_manager
工具进行复现:
python
from context_manager import rehydrate_from_snapshot

context = rehydrate_from_snapshot(
    snapshot_id="20251116_143522",
    level="essential"  # 或 "standard" 或 "comprehensive"
)

Returns: Formatted context text ready to process

返回:可直接用于处理的格式化上下文文本

undefined
undefined

List Snapshots

列出快照

User: List my context snapshots
I'll use the
context_manager
tool to list snapshots:
python
from context_manager import list_context_snapshots

snapshots = list_context_snapshots()
User: List my context snapshots
我会使用
context_manager
工具列出快照:
python
from context_manager import list_context_snapshots

snapshots = list_context_snapshots()

Returns: List of snapshot metadata dicts

返回:快照元数据字典列表

undefined
undefined

Detail Levels

细节级别

When rehydrating context, choose the appropriate detail level:
  • Essential (smallest): Requirements + current state only (~250 tokens)
  • Standard (balanced): + key decisions + open items (~800 tokens)
  • Comprehensive (complete): + full decisions + tools used + metadata (~1,250 tokens)
Start with essential and upgrade if more context is needed.
恢复上下文时,可选择合适的细节级别:
  • Essential(最小):仅包含需求+当前状态(约250个Token)
  • Standard(平衡):+关键决策+未完成事项(约800个Token)
  • Comprehensive(完整):+完整决策+使用的工具+元数据(约1250个Token)
建议从Essential级别开始,若需要更多上下文再升级。

Actions

操作说明

Action:
status

操作:
status

Check current token usage and get recommendations.
Usage:
python
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}")
Returns:
  • ContextStatus
    object with usage details
  • threshold_status
    : 'ok', 'consider', 'recommended', or 'urgent'
  • recommendation
    : Human-readable action suggestion
检查当前Token使用情况并获取建议。
用法:
python
from context_manager import check_context_status

status = check_context_status(current_tokens=750000)
print(f"使用率: {status.percentage}%")
print(f"状态: {status.threshold_status}")
print(f"建议: {status.recommendation}")
返回值:
  • 包含使用详情的
    ContextStatus
    对象
  • threshold_status
    :'ok'、'consider'、'recommended'或'urgent'
  • recommendation
    :易读的操作建议文本

Action:
snapshot

操作:
snapshot

Create intelligent context snapshot.
Usage:
python
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}")
Returns:
  • ContextSnapshot
    object with metadata
  • Snapshot saved to
    ~/.amplihack/.claude/runtime/context-snapshots/
创建智能上下文快照。
用法:
python
from context_manager import create_context_snapshot

snapshot = create_context_snapshot(
    conversation_data=messages,
    name="feature-name"  # 可选
)
print(f"快照ID: {snapshot.snapshot_id}")
print(f"Token数量: {snapshot.token_count}")
print(f"保存路径: {snapshot.file_path}")
返回值:
  • 包含元数据的
    ContextSnapshot
    对象
  • 快照保存至
    ~/.amplihack/.claude/runtime/context-snapshots/

Action:
rehydrate

操作:
rehydrate

Restore context from snapshot at specified detail level.
Usage:
python
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
Returns:
  • Formatted markdown text with restored context
  • Ready to process and continue work
从快照中按指定细节级别恢复上下文。
用法:
python
from context_manager import rehydrate_from_snapshot

context = rehydrate_from_snapshot(
    snapshot_id="20251116_143522",
    level="standard"  # essential、standard或comprehensive
)
print(context)  # 显示恢复后的上下文
返回值:
  • 恢复后的格式化Markdown文本
  • 可直接用于处理和继续工作

Action:
list

操作:
list

List all available context snapshots.
Usage:
python
from context_manager import list_context_snapshots

snapshots = list_context_snapshots()
for snapshot in snapshots:
    print(f"{snapshot['id']}: {snapshot['name']} ({snapshot['size']})")
Returns:
  • List of snapshot metadata dicts
  • Includes: id, name, timestamp, size, token_count
列出所有可用的上下文快照。
用法:
python
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

Proactive Features (v3.0)

V3.0主动式功能

Predictive Budget Monitoring

预测性预算监控

Instead of just checking current usage, predict when thresholds will be reached:
python
undefined
不仅检查当前使用率,还能预测何时会达到阈值:
python
undefined

The system tracks token burn rate over time

系统会随时间跟踪Token消耗速率

When checking status, you get predictive insights

检查状态时,你将获得预测性洞察

status = check_context_status(current_tokens=500000)
status = check_context_status(current_tokens=500000)

Status includes predictions (when automation is running):

状态包含预测信息(当自动化运行时):

- Estimated tool uses until 70% threshold

- 达到70%阈值前还能使用多少次工具

- 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"

"以当前速率,你将在约15次工具使用后达到70%阈值"

"Consider creating a checkpoint before your next major operation"

"建议在下次主要操作前创建检查点"


**How Prediction Works:**

The automation tracks:

1. Token count at each check interval
2. Number of tool uses between checks
3. Average tokens consumed per tool use
4. Time elapsed between checks

From this data, it estimates:

- Tools remaining until threshold
- Approximate time until threshold
- Whether current task will complete before limit

**预测原理:**

自动化会跟踪以下数据:

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

基于这些数据,系统会预估:

- 达到阈值前剩余的工具使用次数
- 达到阈值的大致时间
- 当前任务是否能在限制前完成

Context Health Indicators

上下文健康指标

Visual indicators for session health, suitable for statusline integration:
IndicatorMeaningUsage %Recommended Action
[CTX:OK]
Healthy0-30%Continue normally
[CTX:WATCH]
Monitor30-50%Plan checkpoint
[CTX:WARN]
Warning50-70%Create snapshot soon
[CTX:CRITICAL]
Critical70%+Snapshot immediately
Statusline Integration Example:
bash
undefined
用于会话健康的可视化指标,适合集成到状态栏:
指标含义使用率 %建议操作
[CTX:OK]
健康0-30%正常继续工作
[CTX:WATCH]
需监控30-50%规划检查点
[CTX:WARN]
警告50-70%尽快创建快照
[CTX:CRITICAL]
紧急70%+立即创建快照
状态栏集成示例:
bash
undefined

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
undefined
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
undefined

Priority-Based Context Retention

基于优先级的上下文保留

When creating snapshots, the system prioritizes content by importance:
High Priority (Always Retained):
  • Original user requirements (first user message)
  • Key architectural decisions
  • Current implementation state
  • Open items and blockers
Medium Priority (Retained in Standard+):
  • Tool usage history
  • Decision rationales
  • Questions and clarifications
Low Priority (Only in Comprehensive):
  • Verbose output logs
  • Intermediate steps
  • Debugging information
Usage Pattern:
python
undefined
创建快照时,系统会按重要性对内容进行优先级排序:
高优先级(始终保留):
  • 原始用户需求(第一条用户消息)
  • 关键架构决策
  • 当前实现状态
  • 未完成事项和障碍
中优先级(Standard及以上级别保留):
  • 工具使用历史
  • 决策理由
  • 问题与澄清内容
低优先级(仅Comprehensive级别保留):
  • 冗长的输出日志
  • 中间步骤
  • 调试信息
使用模式:
python
undefined

Create snapshot with priority awareness

创建具备优先级感知的快照

snapshot = create_context_snapshot( conversation_data=messages, name='feature-checkpoint' )
snapshot = create_context_snapshot( conversation_data=messages, name='feature-checkpoint' )

Essential level (~200 tokens): Only high priority content

Essential级别(约200个Token):仅保留高优先级内容

Standard level (~800 tokens): High + medium priority

Standard级别(约800个Token):高+中优先级内容

Comprehensive level (~1250 tokens): Everything

Comprehensive级别(约1250个Token):所有内容

Start minimal, upgrade as needed:

从最小级别开始,按需升级:

context = rehydrate_from_snapshot(snapshot_id, level='essential')
undefined
context = rehydrate_from_snapshot(snapshot_id, level='essential')
undefined

Burn Rate Tracking

消耗速率跟踪

Monitor how fast you're consuming context:
python
undefined
监控上下文的消耗速度:
python
undefined

The automation tracks consumption velocity

自动化会跟踪消耗速度

Adaptive checking frequency based on burn rate:

基于消耗速率自适应检查频率:

Low burn rate (< 1K tokens/tool): Check every 50 tools

低消耗速率(<1K Token/工具):每50次工具使用检查一次

Medium burn rate (1-5K tokens/tool): Check every 10 tools

中等消耗速率(1-5K Token/工具):每10次工具使用检查一次

High burn rate (> 5K tokens/tool): Check every 3 tools

高消耗速率(>5K Token/工具):每3次工具使用检查一次

Critical zone (70%+): Check every tool

紧急区域(70%+):每次工具使用都检查

This means:

这意味着:

- Normal development: Minimal overhead (checks rarely)

- 常规开发:开销最小(很少检查)

- Large file operations: Increased monitoring

- 大文件操作:增加监控频率

- Approaching limits: Continuous monitoring

- 接近限制:持续监控


**Burn Rate Thresholds:**

| Burn Rate   | Risk Level | Monitoring Frequency |
| ----------- | ---------- | -------------------- |
| < 1K/tool   | Low        | Every 50 tools       |
| 1-5K/tool   | Medium     | Every 10 tools       |
| > 5K/tool   | High       | Every 3 tools        |
| Any at 70%+ | Critical   | Every tool           |

**消耗速率阈值:**

| 消耗速率     | 风险等级 | 监控频率             |
| ----------- | -------- | -------------------- |
| <1K/工具    | 低       | 每50次工具使用检查一次 |
| 1-5K/工具   | 中       | 每10次工具使用检查一次 |
| >5K/工具    | 高       | 每3次工具使用检查一次  |
| 70%+任意速率 | 紧急     | 每次工具使用都检查     |

Auto-Summarization Triggers

自动汇总触发

The system automatically creates snapshots before limits are hit:
python
undefined
系统会在达到限制前自动创建快照:
python
undefined

Automatic snapshot triggers (already implemented):

自动快照触发条件(已实现):

- 30% usage: First checkpoint created

- 30%使用率:创建第一个检查点

- 40% usage: Second checkpoint created

- 40%使用率:创建第二个检查点

- 50% usage: Third checkpoint created (for 1M models)

- 50%使用率:创建第三个检查点(针对1M模型)

For smaller context windows (< 800K):

对于较小的上下文窗口(<800K):

- 55% usage: First checkpoint

- 55%使用率:创建第一个检查点

- 70% usage: Second checkpoint

- 70%使用率:创建第二个检查点

- 85% usage: Urgent checkpoint

- 85%使用率:创建紧急检查点

After compaction detected (30% token drop):

检测到压缩后(Token下降>30%):

- Automatically rehydrates from most recent snapshot

- 自动从最新快照复现上下文

- Uses smart level selection based on previous usage

- 根据之前的使用情况智能选择级别

undefined
undefined

Proactive Usage Workflow

主动式使用流程

Step 1: Monitor Token Usage

步骤1:监控Token使用情况

Periodically check status during long sessions:
python
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')
在长会话中定期检查状态:
python
status = check_context_status(current_tokens=current)

if status.threshold_status == 'consider':
    # 使用率70%+ - 考虑创建快照
    print("建议尽快创建快照")
elif status.threshold_status == 'recommended':
    # 使用率85%+ - 建议创建快照
    create_context_snapshot(messages, name='current-work')
elif status.threshold_status == 'urgent':
    # 使用率95%+ - 立即创建快照
    create_context_snapshot(messages, name='urgent-backup')

Step 2: Create Snapshot at Threshold

步骤2:达到阈值时创建快照

When 70-85% threshold reached, create a named snapshot:
python
snapshot = create_context_snapshot(
    conversation_data=messages,
    name='descriptive-name'
)
当使用率达到70-85%时,创建命名快照:
python
snapshot = create_context_snapshot(
    conversation_data=messages,
    name='descriptive-name'
)

Save snapshot ID for later rehydration

保存快照ID以便后续恢复

undefined
undefined

Step 3: Continue Working

步骤3:继续工作

After snapshot creation:
  • Continue conversation naturally
  • Let Claude Code compact if needed
  • Use
    /transcripts
    for full history if desired
  • PreCompact hook saves everything automatically
创建快照后:
  • 正常继续对话
  • 如需压缩,让Claude Code自动处理
  • 如需完整历史,使用/transcripts命令
  • PreCompact钩子会自动保存所有内容

Step 4: Rehydrate After Compaction

步骤4:压缩后恢复上下文

After compaction, restore essential context:
python
undefined
压缩完成后,恢复关键上下文:
python
undefined

Start minimal

从最小级别开始

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

If more context needed, upgrade to standard

若需要更多上下文,升级到standard级别

context = rehydrate_from_snapshot( snapshot_id='20251116_143522', level='standard' )
context = rehydrate_from_snapshot( snapshot_id='20251116_143522', level='standard' )

For complete context, use comprehensive

如需完整上下文,使用comprehensive级别

context = rehydrate_from_snapshot( snapshot_id='20251116_143522', level='comprehensive' )
undefined
context = rehydrate_from_snapshot( snapshot_id='20251116_143522', level='comprehensive' )
undefined

Integration with Existing Systems

与现有系统的集成

vs. PreCompact Hook

与PreCompact钩子的对比

PreCompact Hook (automatic safety net):
  • Triggered by Claude Code before compaction
  • Saves complete conversation transcript
  • Automatic, no user action needed
  • Full conversation export to markdown
Context Skill (proactive optimization):
  • Triggered by user when monitoring indicates
  • Saves intelligent context extraction
  • User-initiated, deliberate choice
  • Essential context only, not full dump
Relationship: Complementary, not competing. Hook = safety net, Skill = optimization.
PreCompact钩子(自动安全网):
  • 由Claude Code在压缩前触发
  • 保存完整对话记录
  • 自动执行,无需用户操作
  • 将完整对话导出为Markdown
上下文Skill(主动式优化):
  • 当监控数据显示需要时,由用户触发
  • 保存智能提取的上下文
  • 用户主动发起,可自主选择
  • 仅保留关键上下文,而非完整转储
关系:互补而非竞争。钩子是安全网,Skill是优化工具。

vs. /transcripts Command

与/transcripts命令的对比

/transcripts (reactive restoration):
  • Restores full conversation after compaction
  • Complete history, all messages
  • Used when you need everything back
  • Reactive recovery tool
Context Skill (proactive preservation):
  • Preserves essential context before compaction
  • Selective rehydration, not full history
  • Used when you want efficient context
  • Proactive optimization tool
Relationship: Transcripts for full recovery, skill for efficient management.
/transcripts(被动恢复):
  • 压缩后恢复完整对话
  • 包含所有消息的完整历史
  • 适用于需要恢复全部内容的场景
  • 被动恢复工具
上下文Skill(主动式保留):
  • 压缩前保留关键上下文
  • 选择性恢复,而非完整历史
  • 适用于需要高效上下文的场景
  • 主动式优化工具
关系:Transcripts用于完整恢复,Skill用于高效管理。

Storage Locations

存储位置

  • Snapshots:
    ~/.amplihack/.claude/runtime/context-snapshots/
    (JSON)
  • Transcripts:
    ~/.amplihack/.claude/runtime/logs/<session_id>/CONVERSATION_TRANSCRIPT.md
  • No conflicts: Different directories, different purposes
  • 快照
    ~/.amplihack/.claude/runtime/context-snapshots/
    (JSON格式)
  • 对话记录
    ~/.amplihack/.claude/runtime/logs/<session_id>/CONVERSATION_TRANSCRIPT.md
  • 无冲突:不同目录,不同用途

Automatic Management

自动管理

Context management runs automatically via the post_tool_use hook:
  • Monitors token usage every Nth tool use (adaptive frequency)
  • Creates snapshots at thresholds (30%, 40%, 50% for 1M models)
  • Detects compaction (token drop > 30%)
  • Auto-rehydrates after compaction at appropriate level
This happens transparently without user intervention.
上下文管理通过post_tool_use钩子自动运行:
  • 每N次工具使用后监控Token使用情况(自适应频率)
  • 在阈值点创建快照(1M模型为30%、40%、50%)
  • 检测压缩操作(Token下降>30%)
  • 压缩后自动以合适级别复现上下文
此过程在后台透明执行,无需用户干预。

Implementation

实现细节

All context management functionality is provided by:
  • Tool:
    ~/.amplihack/.claude/tools/amplihack/context_manager.py
  • Hook Integration:
    ~/.amplihack/.claude/tools/amplihack/context_automation_hook.py
  • Hook System:
    ~/.amplihack/.claude/tools/amplihack/hooks/tool_registry.py
See tool documentation for complete API reference and implementation details.
所有上下文管理功能由以下组件提供:
  • 工具
    ~/.amplihack/.claude/tools/amplihack/context_manager.py
  • 钩子集成
    ~/.amplihack/.claude/tools/amplihack/context_automation_hook.py
  • 钩子系统
    ~/.amplihack/.claude/tools/amplihack/hooks/tool_registry.py
查看工具文档获取完整API参考和实现细节。

Common Patterns

常见使用模式

Pattern 1: Preventive Snapshotting

模式1:预防性快照

Check before long operation and create snapshot if needed:
python
status = check_context_status(current_tokens=current)
if status.threshold_status in ['recommended', 'urgent']:
    create_context_snapshot(messages, name='before-refactoring')
在长时间操作前检查,如需则创建快照:
python
status = check_context_status(current_tokens=current)
if status.threshold_status in ['recommended', 'urgent']:
    create_context_snapshot(messages, name='before-refactoring')

Pattern 2: Context Switching

模式2:上下文切换

Save state when pausing work on one feature to start another:
python
undefined
暂停一个功能的工作时保存状态,以便后续继续:
python
undefined

Pausing work on Feature A

暂停Feature A的工作

create_context_snapshot(messages, name='feature-a-paused')
create_context_snapshot(messages, name='feature-a-paused')

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

[... 处理Feature B ...]

Resume Feature A later

后续恢复Feature A的工作

context = rehydrate_from_snapshot('feature-a-snapshot-id', level='standard')
undefined
context = rehydrate_from_snapshot('feature-a-snapshot-id', level='standard')
undefined

Pattern 3: Team Handoff

模式3:团队交接

Create comprehensive snapshot for teammate:
python
snapshot = create_context_snapshot(
    messages,
    name='handoff-to-alice-api-work'
)
创建完整快照供队友使用:
python
snapshot = create_context_snapshot(
    messages,
    name='handoff-to-alice-api-work'
)

Share snapshot ID with teammate

将快照ID分享给队友

Alice can rehydrate and continue work

Alice可以复现上下文并继续工作

undefined
undefined

Philosophy Alignment

设计理念对齐

Ruthless Simplicity

极致简洁

  • Four single-purpose components in one tool
  • On-demand invocation, no background processes
  • Standard library only, no external dependencies
  • Clear public API with convenience functions
  • 一个工具包含四个单一用途组件
  • 按需调用,无后台进程
  • 仅使用标准库,无外部依赖
  • 清晰的公共API和便捷函数

Single Responsibility

单一职责

  • ContextManager coordinates all operations
  • Token monitoring, extraction, rehydration in one place
  • No duplicate code or scattered logic
  • ContextManager协调所有操作
  • Token监控、提取、复现集中在一处
  • 无重复代码或分散逻辑

Zero-BS Implementation

务实实现

  • No stubs or placeholders
  • All functions work completely
  • Real token estimation, not fake
  • Actual file operations, not simulated
  • 无存根或占位符
  • 所有功能完全可用
  • 真实Token预估,而非模拟
  • 实际文件操作,而非仿真

Trust in Emergence

信任涌现

  • User decides when to snapshot, not automatic (unless via hook)
  • User chooses detail level, not system
  • Proactive choice empowers the user
  • 由用户决定何时创建快照,而非自动执行(除非通过钩子)
  • 由用户选择细节级别,而非系统自动选择
  • 主动选择赋予用户控制权

Tips for Effective Context Management

有效上下文管理技巧

  1. Monitor regularly: Check status at natural breakpoints
  2. Snapshot strategically: At 70-85% or before long operations
  3. Start minimal: Use essential level first, upgrade if needed
  4. Name descriptively: Use clear snapshot names for later reference
  5. List periodically: Review and clean old snapshots
  6. Combine tools: Use with /transcripts for full recovery option
  7. Trust emergence: Don't over-snapshot, let context flow naturally
  1. 定期监控:在自然断点处检查状态
  2. 策略性快照:在70-85%使用率或长时间操作前创建
  3. 从简开始:先使用essential级别,按需升级
  4. 命名清晰:使用明确的快照名称以便后续查找
  5. 定期清理:查看并清理旧快照
  6. 组合工具:与/transcripts配合使用,保留完整恢复选项
  7. 信任涌现:不要过度创建快照,让上下文自然流转

Resources

资源

  • Tool:
    ~/.amplihack/.claude/tools/amplihack/context_manager.py
  • Hook:
    ~/.amplihack/.claude/tools/amplihack/context_automation_hook.py
  • Philosophy:
    ~/.amplihack/.claude/context/PHILOSOPHY.md
  • Patterns:
    ~/.amplihack/.claude/context/PATTERNS.md
  • 工具
    ~/.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

Remember

注意事项

This skill provides proactive context management through a clean, reusable tool. The tool can be called from skills, commands, and hooks. It complements existing tools (PreCompact hook, /transcripts) rather than replacing them. Use it to maintain clean, efficient context throughout long sessions.
Key Takeaway: Business logic lives in
context_manager.py
, this skill just tells you how to use it.
该Skill通过简洁、可复用的工具提供主动式上下文管理。该工具可从Skill、命令和钩子中调用。它是对现有工具(PreCompact钩子、/transcripts)的补充而非替代。使用它可在长会话中保持干净、高效的上下文。
核心要点:业务逻辑位于
context_manager.py
,本Skill仅说明如何使用它。