关于 clear-context
clear-context 是在上下文用量较高时延续 Claude Code 任务的技能。它记录任务状态和执行模式,再将后续工作交给新的子 Agent,并传递现有任务 ID 和明确的待办事项。
主要功能
- 01将会话状态保存到检查点文件
- 02核对任务状态并保留任务 ID
- 03在继续前检查交接信息是否清晰
- 04委派工作给新的子 Agent
- 05通过环境变量配置上下文阈值
适用场景
- 01上下文用量较高时继续任务
- 02交接多问题批处理并避免重复建任务
- 03在长流程中保留工作进度
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ athola/ claude-night-market --skill clear-context安装后在 Claude Code 中输入/clear-context确认已加载。
附带文件modules/session-state-schema.mdmodules/session-state.md
详细介绍
清除上下文技能
快速开始
当上下文压力达到临界水平(80%+)时,调用此技能以:
- 保存当前会话状态
- 将后续工作委派给一个全新的子 Agent
- 无需手动干预即可继续工作
Skill(conserve:clear-context)
何时使用
- 主动使用:开始大型多链式任务之前
- 响应使用:上下文警告显示使用率达到 80%+ 时
- 自动使用:集成到长时间运行的工作流中
何时不使用
- 上下文使用率低于 50%——照常继续工作
- 正在进行关键操作,交接会导致状态丢失时
- 先考虑使用“从此处开始总结”(Claude Code 2.1.32+):在完全自动清除之前, 先通过消息选择器尝试部分总结。这会压缩较早的上下文,同时 保留近期工作,通常足以缓解压力,无需完全交接。
自动清除模式
由于 /clear 需要用户操作,我们通过委派给子 Agent来实现在不中断工作的情况下自动清除上下文:
Main Agent (high context)
↓
Saves state to .claude/session-state.md
↓
Spawns continuation subagent (fresh context)
↓
Subagent reads state, continues work
阈值
| 级别 | 阈值 | 操作 |
|---|---|---|
| WARNING | 40% | 监控并规划优化 |
| CRITICAL | 50% | 准备交接 |
| EMERGENCY | 80% | 立即执行自动清除 |
配置(环境变量):
CONSERVE_EMERGENCY_THRESHOLD:覆盖默认值 80%(例如,0.75表示 75%)CONSERVE_SESSION_STATE_PATH:覆盖默认路径.claude/session-state.md
自动清除工作流
步骤 1:评估当前状态
触发自动清除之前,收集以下信息:
- 当前任务/目标描述
- 已取得的进展
- 关键决策及其理由
- 正在处理的文件
- 未完成的 TodoWrite 项目
步骤 1.5:交接前整理任务列表
重要:保存状态或启动后续 Agent 之前,先核对任务列表:
- 通过
TaskList查看所有任务 - 通过
TaskUpdate将已完成的任务标记为completed:不要将已完成的工作留在in_progress状态 - 记录现有任务 ID:收集所有任务 ID(
pending和in_progress),并将其写入会话状态,以便后续 Agent 引用这些 ID,而不是创建重复任务 - 在会话状态的
existing_task_ids字段中包含任务 ID(参见步骤 2)
这样可以防止后续 Agent 创建重复任务。
步骤 2:保存会话状态
重要:如果 .claude/session-state.md 已存在,写入前务必先读取(Claude Code 要求覆盖现有文件前先读取)。如果 .claude/ 目录不存在,则创建该目录。
写入 .claude/session-state.md(或 $CONSERVE_SESSION_STATE_PATH):
# Session State Checkpoint
state_version: 1
Generated: [timestamp]
Reason: Context threshold exceeded (80%+)
## Execution Mode
**Mode**: [unattended | interactive | dangerous]
**Auto-Continue**: [true | false]
**Source Command**: [do-issue | execute-plan | etc.]
**Remaining Tasks**: [list of pending items]
> **Important**: If `auto_continue: true` or mode is `dangerous`/`unattended`,
> the continuation agent should not pause for user confirmation.
> Continue executing all remaining tasks until completion.
## Current Task
[What we're trying to accomplish]
## Progress Summary
[What's been done so far]
## Key Decisions
- Decision 1: [rationale]
- Decision 2: [rationale]
## Active Files
- path/to/file1.py - [status]
- path/to/file2.md - [status]
## Pending TodoWrite Items
- [ ] Item 1
- [ ] Item 2
## Existing Task IDs
[List task IDs from TaskList so the continuation agent can reference them
instead of creating duplicates. Example:]
- Task #1: "Implement feature X" (in_progress)
- Task #2: "Write tests for feature X" (pending)
## Continuation Instructions
[Specific next steps for the continuation agent]
执行模式检测:
写入状态之前,检测执行模式:
# Detect execution mode from environment/context
execution_mode = {
"mode": "interactive", # default
"auto_continue": False,
"source_command": None,
"remaining_tasks": [],
"dangerous_mode": False,
}
# Check for dangerous/unattended mode indicators
if os.environ.get("CLAUDE_DANGEROUS_MODE") == "1":
execution_mode["mode"] = "dangerous"
execution_mode["auto_continue"] = True
execution_mode["dangerous_mode"] = True
elif os.environ.get("CLAUDE_UNATTENDED") == "1":
execution_mode["mode"] = "unattended"
execution_mode["auto_continue"] = True
# Inherit from parent session state if exists
if parent_state and parent_state.get("execution_mode"):
execution_mode = parent_state["execution_mode"]
步骤 2.5:在交接前确认会话状态清晰
接续 Agent 只能继承 session-state.md 中写明的内容。如果
草稿含糊不清,新 Agent 就会从已损坏的任务
状态开始。生成 Agent 之前,请通过信念清晰度检查来决定是否交接
(Skill(conserve:context-optimization) 的 belief-clarity 模块),
该检查会针对草稿状态提出两个锚点问题:
- 进度探查:当前任务进展如何:已完成哪些内容,任务现在处于 什么状态?
- 缺口探查:完成任务还需要哪些信息:列出有明确范围的具体待办事项, 而不是笼统类别。
门控逻辑:
- 两个答案都具体且范围明确:保存并继续执行步骤 3。
- 缺口探查过于开放,或进度探查含糊其辞:将未通过探查的答案作为明确的
Current state:和Still needed:条目追加到session-state.md,然后重新评分。最多 重新评分两次。第三次仍未通过的草稿应交给用户,而不是交接给 Agent:状态文件的撰写者 在此处也同时是评分者,而自我评分循环只会增强信心, 不会提升清晰度。 - 进度探查含糊或没有答案:不要交接。写入状态并重试之前,
先与用户确认当前状态(或在无人值守模式下使用
imbue:proof-of-work)。
如果已安装 memory-palace:memory-clarity-probe,请将双重探查评估委托给它,
并以其“Proceed”综合结果作为门控依据。这项检查属于定性检查:它能发现偏差和遗漏,
但无法识别看似可信、实际错误的状态,因此对于高风险交接,应配合任务状态验证。
步骤 3:生成接续 Agent
使用 Task 工具进行委派。重要:在任务提示词中注明执行模式:
Task: Continue the work from session checkpoint
Instructions:
1. Read .claude/session-state.md for full context
2. Check the "Execution Mode" section FIRST
3. If `auto_continue: true` or mode is `dangerous`/`unattended`:
- DO NOT pause for user confirmation
- Continue executing ALL remaining tasks until completion
- Only stop on actual errors or when all work is done
4. **TASK LIST**: Do NOT create new tasks via TaskCreate. The parent agent
already created the task list. Use TaskList to see existing tasks, and
TaskUpdate to mark them in_progress/completed. Check the "Existing Task IDs"
section in the session state for the authoritative list.
5. Verify understanding of current task and progress
6. Continue from where the previous agent left off
7. If you also approach 80% context, repeat this handoff process
- PRESERVE the execution mode when creating your own checkpoint
- Increment `handoff_depth` in `session-state.md`. At depth 3,
stop and report to the user instead of spawning again: three
continuations without finishing is a task that needs splitting,
and each handoff loses state the probes cannot see
The session state file contains all necessary context to continue without interruption.
**Execution mode inheritance**: Always inherit and propagate the execution
mode from the session state. If the parent was in dangerous/unattended mode,
you are also in that mode. Do not ask the user for confirmation.
**Task deduplication**: Do not create duplicate tasks. The parent has already
populated the task list. Use TaskUpdate on existing task IDs only.
对于批量/多问题工作流(例如 /do-issue 42 43 44):
Task: Continue batch processing from session checkpoint
Instructions:
1. Read .claude/session-state.md for full context
2. EXECUTION MODE: This is a batch operation with auto_continue=true
3. Process ALL remaining tasks in the queue:
- Remaining: [issue #43, issue #44]
4. DO NOT stop between tasks - continue until all are complete
5. If you hit 80% context, hand off with the same execution mode
6. Only pause for:
- Actual errors requiring human judgment
- Completion of ALL tasks
This is an unattended batch operation. Continue without user prompts.
Task 工具详情:
- 生成具有全新 1M 上下文窗口的子 Agent
- 最多支持 10 个并行 Agent
- 每个子 Agent 的额外开销约为 20k 个 token
步骤 3 备用方案:妥善收尾
如果 Task 工具不可用(权限、上下文限制):
- 完成当前正在进行的工作(完成编辑、提交)
- 在回复中总结剩余任务
- 让自动压缩处理接续——Claude Code 会自动压缩上下文
- 手动接续选项:
- 使用
claude --continue恢复会话 - 开启新会话并使用
/catchup了解变更 - 阅读
.claude/session-state.md获取已保存的上下文
- 使用
已在 2.1.63 中修复:
/clear现在会正确重置缓存的技能。此前,过时的技能内容可能会残留到新对话中。现在,/clear和/catchup模式已完全可靠。
已在 2.1.72 中修复:
/clear现在只会清除前台任务。后台 Agent 和 bash 任务会继续运行。此前,/clear会终止所有任务,包括后台任务,这对于不应因上下文重置而中断的长时间运行后台 Agent 来说很不方便。
与现有钩子的集成
此技能与 context_warning.py 钩子配合使用:
- 钩子在 PreToolUse 时触发
- 达到 80% 及以上阈值时,钩子会注入紧急指导
- 指导建议调用此技能
- 技能执行自动清除工作流
模块加载
有关详细的会话状态格式和示例:
- 请参阅
modules/session-state.md,了解检查点格式和交接模式 - 请参阅
modules/session-state-schema.md,了解版本化架构和迁移逻辑
自我监控模式
对于可能超出上下文限制的工作流,请添加定期检查:
# Pseudocode for context-aware workflow
def long_running_task():
for step in task_steps:
execute_step(step)
# Check context after each major step
if estimate_context_usage() > 0.80:
invoke_skill("conserve:clear-context")
return # Continuation agent takes over
上下文测量方法
精确测量(无头/批处理)
如需在自动化中准确拆分 token:
claude -p "/context" --verbose --output-format json
完整的无头文档请参阅 /conserve:optimize-context。
快速估算(实时钩子)
对于注重速度的钩子,请使用启发式方法:
- JSONL 文件大小:约 800KB ≈ 100% 上下文(由 context_warning 钩子使用)
- 轮次数:每个复杂轮次约 5-10K 个 token
- 工具调用次数:大量使用工具 = 增长更快
示例:通过自动清理进行头脑风暴
## Brainstorm Session with Context Management
1. Before starting, note current context level
2. Set checkpoint after each brainstorm phase:
- Problem definition checkpoint
- Constraints checkpoint
- Approaches checkpoint
- Selection checkpoint
3. If context exceeds 80% at any checkpoint:
- Save brainstorm state
- Delegate to continuation agent
- Agent continues from checkpoint
最佳实践
- 频繁保存检查点:执行长任务时,在自然的阶段节点保存状态
- 明确指示:为继续任务的 Agent 提供具体、明确的指导
- 验证交接:启动子 Agent 前,确保状态文件已写入
- 限制递归:继续任务的 Agent 也可能遇到限制。状态文件中的
handoff_depth会将链条限制为 3 层;超过后,向用户报告
故障排除
继续任务的 Agent 未获得完整上下文
- 确保 session-state.md 内容完整
- 包含所有相关文件路径
- 记录隐含的假设
子 Agent 未能正确继续任务
- 检查状态文件路径是否正确
- 确认文件权限
- 添加更具体的继续任务指示
未检测到上下文阈值
- 可能未设置 CLAUDE_CONTEXT_USAGE
context_warninghook 会根据会话文件大小进行估算,作为后备方案- 手动调用始终有效
Hook 集成
此技能由 context_warning hook(hooks/context_warning.py)自动触发:
- 使用率达 40%:警告——尽快优化计划
- 使用率达 50%:严重——必须立即优化
- 使用率达 80%:紧急——应立即调用此技能
Hook 通过以下方式监控上下文:
CLAUDE_CONTEXT_USAGE环境变量(可用时)- 后备方案:根据会话 JSONL 文件大小估算(约 800KB = 100%)
通过环境变量配置阈值:
CONSERVE_EMERGENCY_THRESHOLD:覆盖默认值 80%(例如,“0.75”)CONSERVE_CONTEXT_ESTIMATION:设为“0”以禁用后备估算CONSERVE_CONTEXT_WINDOW_BYTES:覆盖 800000 字节的估算值
退出标准
- 写入任何状态之前,先核对任务列表(标记已完成的任务,并记录未完成任务 的 ID)
-
.claude/session-state.md已存在,并记录当前任务、 进度、执行模式和继续任务的指示 - 在交接前,已通过会话状态清晰度关卡(步骤 2.5),或已附加未通过 探测的问题答案并重新评分
- 已启动继续任务的 Agent,并传入执行模式和现有任务 ID(不重复创建任务)
- 当进度探测结果含糊或为空时,拒绝交接