Automatically handles high context usage (80%+) by saving state and handing off to a fresh subagent, enabling uninterrupted continuation of long-running tasks.
From conservenpx claudepluginhub athola/claude-night-market --plugin conserveThis skill uses the workspace's default tool permissions.
modules/session-state-schema.mdmodules/session-state.mdDesigns and optimizes AI agent action spaces, tool definitions, observation formats, error recovery, and context for higher task completion rates.
Enables AI agents to execute x402 payments with per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents pay for APIs, services, or other agents.
Compares coding agents like Claude Code and Aider on custom YAML-defined codebase tasks using git worktrees, measuring pass rate, cost, time, and consistency.
When context pressure reaches critical levels (80%+), invoke this skill to:
Skill(conserve:clear-context)
Since /clear requires user action, we achieve automatic context clearing without interruption through subagent delegation:
Main Agent (high context)
↓
Saves state to .claude/session-state.md
↓
Spawns continuation subagent (fresh context)
↓
Subagent reads state, continues work
| Level | Threshold | Action |
|---|---|---|
| WARNING | 40% | Monitor, plan optimization |
| CRITICAL | 50% | Prepare for handoff |
| EMERGENCY | 80% | Execute auto-clear now |
Configuration (environment variables):
CONSERVE_EMERGENCY_THRESHOLD: Override 80% default (e.g., 0.75 for 75%)CONSERVE_SESSION_STATE_PATH: Override .claude/session-state.md defaultBefore triggering auto-clear, gather:
Important: Before saving state or spawning a continuation agent, reconcile the task list:
TaskListcompleted via TaskUpdate — do NOT leave done work as in_progressexisting_task_ids field (see Step 2)This prevents the continuation agent from creating duplicate tasks.
Important: If .claude/session-state.md already exists, always Read it first before writing (Claude Code requires reading existing files before overwriting). Create the .claude/ directory if it doesn't exist.
Write to .claude/session-state.md (or $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]
Execution Mode Detection:
Before writing state, detect the execution mode:
# 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"]
Use the Task tool to delegate. Important: Include execution mode in the task prompt:
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
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.
For batch/multi-issue workflows (e.g., /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 Tool Details:
If Task tool is unavailable (permissions, context restrictions):
claude --continue to resume session/catchup to understand changes.claude/session-state.md for saved contextFixed in 2.1.63:
/clearnow properly resets cached skills. Previously, stale skill content could persist into the new conversation. The/clear+/catchuppattern is now fully reliable.
Fixed in 2.1.72:
/clearnow only clears foreground tasks. Background agent and bash tasks continue running. Previously,/clearwould kill all tasks including background ones, which was problematic for long-running background agents that should survive context resets.
This skill works with context_warning.py hook:
For detailed session state format and examples:
modules/session-state.md for checkpoint format and handoff patternsmodules/session-state-schema.md for versioned schema and migration logicFor workflows that might exceed context, add periodic checks:
# 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
For accurate token breakdown in automation:
claude -p "/context" --verbose --output-format json
See /conserve:optimize-context for full headless documentation.
For hooks where speed matters, use heuristics:
## 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
context_warning hook uses fallback estimation from session file sizeThis skill is triggered automatically by the context_warning hook (hooks/context_warning.py):
The hook monitors context via:
CLAUDE_CONTEXT_USAGE environment variable (when available)Configure thresholds via environment:
CONSERVE_EMERGENCY_THRESHOLD: Override 80% default (e.g., "0.75")CONSERVE_CONTEXT_ESTIMATION: Set to "0" to disable fallbackCONSERVE_CONTEXT_WINDOW_BYTES: Override 800000 byte estimate