Skill: athola/nm-conserve-clear-context (version 1.0.2)

--- name: clear-context description: | Automatic context management with graceful handoff to a continuation subagent at 80% usage version: 1.9.5 metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/conserve", "emoji": "\ud83e\udd9e"}} source: claude-night-market source_plugin: conserve --- > **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin. ## Table of Contents - [Quick Start](#quick-start) - [When to Use](#when-to-use) - [The Auto-Clear Pattern](#the-auto-clear-pattern) - [Thresholds](#thresholds) - [Auto-Clear Workflow](#auto-clear-workflow) - [Integration with Existing Hooks](#integration-with-existing-hooks) - [Self-Monitoring Pattern](#self-monitoring-pattern) # Clear Context Skill ## Quick Start When context pressure reaches critical levels (80%+), invoke this skill to: 1. Save current session state 2. Delegate continuation to a fresh subagent 3. Continue work without manual intervention ``` Skill(conserve:clear-context) ``` ## When To Use - **Proactively**: Before starting large multi-chained tasks - **Reactively**: When context warning indicates 80%+ usage - **Automatically**: Integrated into long-running workflows ## When NOT To Use - Context usage is under 50% - continue working normally - Mid-critical-operation where handoff would lose state - **Consider "Summarize from here" first** (Claude Code 2.1.32+): Before full auto-clear, try partial summarization via the message selector. This compresses older context while preserving recent work — often sufficient to relieve pressure without a full handoff. ## The Auto-Clear Pattern 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 ``` ## Thresholds | 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` default ## Auto-Clear Workflow ### Step 1: Assess Current State Before triggering auto-clear, gather: - Current task/goal description - Progress made so far - Key decisions and rationale - Files being actively worked on - Open TodoWrite items ### Step 1.5: Finalize Task List Before Handoff **Important**: Before saving state or spawning a continuation agent, reconcile the task list: 1. **Review all tasks** via `TaskList` 2. **Mark completed tasks** as `completed` via `TaskUpdate` — do NOT leave done work as `in_progress` 3. **Record existing task IDs** — collect all task IDs (pending and in_progress) to pass in the session state so the continuation agent references them instead of creating duplicates 4. **Include task IDs in session state** under the `existing_task_ids` field (see Step 2) This prevents the continuation agent from creating duplicate tasks. ### Step 2: Save Session State **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`): ```markdown # 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: ```python # 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"] ``` ### Step 3: Spawn Continuation Agent 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:** - Spawns subagent with fresh 1M context window - Up to 10 parallel agents supported - ~20k token overhead per subagent ### Step 3 Fallback: Graceful Wrap-Up If Task tool is unavailable (permissions, context restrictions): 1. **Complete current in-progress work** (finish edits, commits) 2. **Summarize remaining tasks** in your response 3. **Let auto-compact handle continuation** - Claude Code compresses context automatically 4. **Manual continuation options**: - `claude --continue` to resume session - New session + `/catchup` to understand changes - Read `.claude/session-state.md` for saved context > **Fixed in 2.1.63**: `/clear` now properly resets cached skills. Previously, stale skill content could persist into the new conversation. The `/clear` + `/catchup` pattern is now fully reliable. > **Fixed in 2.1.72**: `/clear` now only clears foreground tasks. Background agent and bash tasks continue running. Previously, `/clear` would kill all tasks including background ones, which was problematic for long-running background agents that should survive context resets. ## Integration with Existing Hooks This skill works with `context_warning.py` hook: 1. Hook fires on PreToolUse 2. At 80%+ threshold, hook injects emergency guidance 3. Guidance recommends invoking this skill 4. Skill executes auto-clear workflow ## Module Loading For detailed session state format and examples: - See `modules/session-state.md` for checkpoint format and handoff patterns - See `modules/session-state-schema.md` for versioned schema and migration logic ## Self-Monitoring Pattern For workflows that might exceed context, add periodic checks: ```python # 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 ``` ## Context Measurement Methods ### Precise (Headless/Batch) For accurate token breakdown in automation: ```bash claude -p "/context" --verbose --output-format json ``` See `/conserve:optimize-context` for full headless documentation. ### Fast Estimation (Real-time Hooks) For hooks where speed matters, use heuristics: 1. **JSONL file size**: ~800KB ≈ 100% context (used by context_warning hook) 2. **Turn count**: ~5-10K tokens per complex turn 3. **Tool invocations**: Heavy tool use = faster growth ## Example: Brainstorm with Auto-Clear ```markdown ## 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 ``` ## Best Practices 1. **Checkpoint Frequently**: During long tasks, save state at natural breakpoints 2. **Clear Instructions**: Continuation agent needs specific, actionable guidance 3. **Verify Handoff**: Ensure state file is written before spawning subagent 4. **Monitor Recursion**: Continuation agents can also hit limits - design for chaining ## Troubleshooting ### Continuation agent doesn't have full context - Ensure session-state.md is comprehensive - Include all relevant file paths - Document implicit assumptions ### Subagent fails to continue properly - Check that state file path is correct - Verify file permissions - Add more specific continuation instructions ### Context threshold not detected - CLAUDE_CONTEXT_USAGE may not be set - The `context_warning` hook uses fallback estimation from session file size - Manual invocation always works ## Hook Integration This skill is triggered automatically by the **context_warning hook** (`hooks/context_warning.py`): - **40% usage**: WARNING - plan optimization soon - **50% usage**: CRITICAL - immediate optimization required - **80% usage**: EMERGENCY - this skill should be invoked immediately The hook monitors context via: 1. `CLAUDE_CONTEXT_USAGE` environment variable (when available) 2. Fallback: estimates from session JSONL file size (~800KB = 100%) Configure thresholds via environment: - `CONSERVE_EMERGENCY_THRESHOLD`: Override 80% default (e.g., "0.75") - `CONSERVE_CONTEXT_ESTIMATION`: Set to "0" to disable fallback - `CONSERVE_CONTEXT_WINDOW_BYTES`: Override 800000 byte estimate

path: modules/session-state-schema.md
content: ---
name: session-state-schema
description: |
  Versioned schema definition for session state files.
  Enables backward compatibility as the format evolves.
category: conservation
---

# Session State Schema

## Current Version: 1

All session state files MUST include a `state_version` field on the first content line after the heading. This enables continuation agents to detect the format and apply migration logic when needed.

## Version 1 Schema

### Required Header

```markdown
# Session State Checkpoint
state_version: 1
Generated: YYYY-MM-DD HH:MM:SS
Reason: [Context threshold | Manual checkpoint | Task boundary]
```

### Required Sections

| Section | Purpose |
|---------|---------|
| `## Execution Mode` | Mode, auto-continue flag, source command |
| `## Current Task` | What we are trying to accomplish |
| `## Progress Summary` | What has been done so far |
| `## Continuation Instructions` | Next steps for the continuation agent |

### Optional Sections

| Section | Purpose |
|---------|---------|
| `## Key Decisions` | Decisions and rationale |
| `## Active Files` | Files being modified or referenced |
| `## Pending TodoWrite Items` | Outstanding todo items |
| `## Existing Task IDs` | Task IDs for deduplication |
| `## Metadata` | JSON block with handoff count, priority, etc. |

## Version 0 (Unversioned Legacy)

Any session state file that lacks the `state_version` field is v0. These files were written before versioning was introduced.

### Identifying v0 Files

A v0 file typically starts with:

```markdown
# Session State Checkpoint
Generated: YYYY-MM-DD HH:MM:SS
```

No `state_version` line is present.

### V0 Field Mapping

V0 files use the same section names as v1. The only difference is the missing version header. All sections are compatible.

## Migration: V0 to V1

When a continuation agent encounters a v0 file, apply this migration:

1. **Treat it as v1.** The content is structurally identical.
2. **Do not rewrite the file** just to add the version header. Only add `state_version: 1` if you are already updating the file for other reasons (e.g., progress checkpoint).
3. **Log the migration.** Note in your handoff summary: "Migrated session state from v0 (unversioned) to v1."

No field renaming or restructuring is needed. V0 and v1 are content-compatible.

## Version Check Logic

Continuation agents MUST follow this sequence when reading a session state file:

```
1. Read the file
2. Look for "state_version: N" in the first 5 lines
3. If found:
   a. version == 1  -> proceed normally
   b. version > 1   -> warn "Unknown state version N, attempting to read"
                        then proceed (best-effort forward compatibility)
4. If not found:
   -> treat as v0, proceed normally (v0 is compatible with v1)
```

### Forward Compatibility

Future versions should maintain backward-compatible section names where possible. If a breaking change is needed, the version number increments and this document gets a new migration section.

A continuation agent encountering an unknown future version should:
- Log a warning: "Session state version N is newer than expected (v1). Reading with best effort."
- Attempt to read all recognized sections
- Skip unrecognized sections without error
- Continue the work rather than failing

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 0 | Pre-1.5.2 | Original unversioned format |
| 1 | 1.5.2 | Added `state_version` header field |


path: modules/session-state.md
content: ---
name: session-state
description: |
  Session state persistence format and management for context handoffs.
  Defines the checkpoint structure that enables seamless continuation.
category: conservation
---

# Session State Module

## Overview

This module defines the session state format used for context handoffs. A well-structured state file enables continuation agents to seamlessly pick up where the previous agent left off.

## State File Location

**Default**: `.claude/session-state.md`

**Override**: Set `CONSERVE_SESSION_STATE_PATH` environment variable

```bash
export CONSERVE_SESSION_STATE_PATH="/tmp/my-session-state.md"
```

## State File Format

### Full Template

```markdown
# Session State Checkpoint
state_version: 1

**Generated**: YYYY-MM-DD HH:MM:SS
**Reason**: [Context threshold | Manual checkpoint | Task boundary]
**Context Level**: [Estimated percentage if known]

---

## Current Objective

[One clear sentence describing what we're trying to accomplish]

### Success Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3

---

## Progress Summary

### Completed
- [x] Step 1: [Brief description]
- [x] Step 2: [Brief description]

### In Progress
- [ ] Step 3: [What's currently being worked on]

### Remaining
- [ ] Step 4: [Next step]
- [ ] Step 5: [Future step]

---

## Key Decisions Made

| Decision | Rationale | Alternatives Considered |
|----------|-----------|------------------------|
| Decision 1 | Why we chose this | Option A, Option B |
| Decision 2 | Why we chose this | Option C, Option D |

---

## Active Context

### Files Being Modified
| File | Status | Notes |
|------|--------|-------|
| path/to/file1.py | In progress | Adding function X |
| path/to/file2.md | Pending review | Needs formatting |

### Files Read (Reference)
- `path/to/reference1.py` - Used for pattern reference
- `path/to/reference2.md` - Contains requirements

### Open TodoWrite Items
```json
[
  {"id": "todo-1", "status": "pending", "description": "Item 1"},
  {"id": "todo-2", "status": "in_progress", "description": "Item 2"}
]
```

### Existing Task IDs

**IMPORTANT**: List all task IDs from TaskList so the continuation agent
references them via TaskUpdate instead of creating duplicates.

| Task ID | Subject | Status |
|---------|---------|--------|
| #1 | Task subject | in_progress |
| #2 | Task subject | pending |

> The continuation agent MUST use TaskUpdate on these IDs.
> It MUST NOT create new tasks via TaskCreate unless genuinely new work is discovered.

---

## Continuation Instructions

### Immediate Next Step
[Specific action to take first]

### Context to Re-read
1. [File path 1] - [Why it's needed]
2. [File path 2] - [Why it's needed]

### Warnings/Gotchas
- [Any pitfalls the continuation agent should avoid]
- [Known issues encountered]

### If Blocked
[What to do if the immediate next step fails]

---

## Execution Mode

**CRITICAL**: Capture and propagate execution mode for unattended workflows.

```markdown
## Execution Mode

**Mode**: [unattended | interactive | dangerous]
**Auto-Continue**: [true | false]
**Source Command**: [do-issue | execute-plan | batch-process | etc.]
**Remaining Tasks**: [list of pending task IDs or issue numbers]

### Flags Inherited
- `--dangerous`: Continue executing without user prompts
- `--no-confirm`: Skip confirmation dialogs
- `--batch`: Processing multiple items
```

| Mode | Behavior | Use Case |
|------|----------|----------|
| `interactive` | Pause at checkpoints, ask user | Normal development |
| `unattended` | Continue automatically, log decisions | CI/CD, batch processing |
| `dangerous` | Like unattended + skip permissions | Fully automated pipelines |

**Detection**: Check environment variables and session context:
- `CLAUDE_DANGEROUS_MODE=1` → dangerous mode
- `CLAUDE_UNATTENDED=1` → unattended mode
- Presence of `--dangerous` in original command → dangerous mode
- Multiple issues/tasks in queue → likely batch mode

---

## Metadata

```json
{
  "checkpoint_version": "1.1",
  "parent_session_id": null,
  "handoff_count": 0,
  "estimated_remaining_work": "medium",
  "priority": "high",
  "execution_mode": {
    "mode": "interactive",
    "auto_continue": false,
    "source_command": null,
    "remaining_tasks": [],
    "dangerous_mode": false
  },
  "existing_task_ids": []
}
```
```

## Minimal Template

For quick checkpoints:

```markdown
# Quick Checkpoint
state_version: 1

**Task**: [What we're doing]
**Progress**: [Where we are]
**Next**: [Immediate next step]
**Files**: [Key files to read]
```

## Writing Session State

### When to Write

1. **Context threshold exceeded** (80%+)
2. **Natural task boundary** (phase complete)
3. **Before risky operation** (safety checkpoint)
4. **Manual checkpoint request**

### What to Include

**Essential** (always include):
- Current objective
- Progress summary
- Immediate next step
- Key files

**Important** (include when relevant):
- Decisions made with rationale
- Open TodoWrite items
- Warnings/gotchas

**Optional** (include for complex tasks):
- Alternatives considered
- Blocked items
- Detailed metadata

### Writing Checklist

Before writing session state:

- [ ] Objective is clear and specific
- [ ] Progress accurately reflects completed work
- [ ] Next step is actionable (not vague)
- [ ] File paths are correct and accessible
- [ ] Decisions are documented with rationale
- [ ] No sensitive information included

## Reading Session State

### Continuation Agent Protocol

When a continuation agent starts:

1. **Read state file first**
   ```
   Read .claude/session-state.md
   ```

2. **Verify understanding**
   - Summarize the objective
   - Confirm progress status
   - Identify immediate next step

3. **Re-read critical files**
   - Files listed in "Context to Re-read"
   - Files marked "In Progress"

4. **Acknowledge handoff**
   - Confirm readiness to continue
   - Note any questions or ambiguities

5. **Execute continuation**
   - Start from "Immediate Next Step"
   - Follow task workflow

### Handling Ambiguity

If state file is unclear:

1. **Check for related files**
   - Recent git changes
   - Open PRs/issues
   - Project documentation

2. **Make reasonable assumptions**
   - Document assumptions made
   - Proceed with caution

3. **Flag uncertainties**
   - Note areas of confusion
   - Ask for clarification if critical

## State File Lifecycle

```
┌─────────────────┐
│ Task Started    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Work in Progress│◄──────────────┐
└────────┬────────┘               │
         │                        │
         ▼                        │
┌─────────────────┐    No        │
│ Context > 80%?  │──────────────┘
└────────┬────────┘
         │ Yes
         ▼
┌─────────────────┐
│ Write State File│
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Spawn Subagent  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Subagent Reads  │
│ State File      │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Continue Work   │──────────────►(Back to Work in Progress)
└─────────────────┘
```

## Multi-Handoff Chains

For very long tasks, multiple handoffs may occur:

```markdown
## Metadata

```json
{
  "checkpoint_version": "1.0",
  "parent_session_id": "handoff-001",
  "handoff_count": 2,
  "handoff_history": [
    {"id": "handoff-001", "reason": "context_threshold", "timestamp": "..."},
    {"id": "handoff-002", "reason": "context_threshold", "timestamp": "..."}
  ]
}
```
```

Each continuation agent increments `handoff_count` and adds to `handoff_history`.

**Recommended max**: Set a limit of 5-10 handoffs to prevent infinite chains. If `handoff_count` exceeds the limit, stop and report to the user rather than spawning another continuation agent.

## Best Practices

1. **Be Specific**: "Add validation to parse_config()" not "Continue working on config"

2. **Include Context**: Don't assume continuation agent knows anything

3. **Document Decisions**: Future agents need to understand WHY, not just WHAT

4. **Test File Paths**: Ensure all referenced files exist and are readable

5. **Keep It Updated**: Stale state files cause confusion

6. **Clean Up**: Remove old state files after task completion

## Example: Real Handoff

### Original Agent State

```markdown
# Session State Checkpoint
state_version: 1

**Generated**: 2025-01-15 14:30:00
**Reason**: Context threshold exceeded (82%)
**Context Level**: ~82%

---

## Current Objective

Implement the `clear-context` skill for the conserve plugin, including
the main skill file, session-state module, and hook integration.

### Success Criteria
- [x] Create skill directory structure
- [x] Write main SKILL.md
- [ ] Write session-state module
- [ ] Update context_warning.py hook
- [ ] Create continuation agent definition
- [ ] Test the full workflow

---

## Progress Summary

### Completed
- [x] Created /plugins/conserve/skills/clear-context/
- [x] Created /plugins/conserve/skills/clear-context/modules/
- [x] Wrote SKILL.md with full documentation

### In Progress
- [ ] Writing session-state.md module (this file)

### Remaining
- [ ] Update context_warning.py with 80% threshold
- [ ] Create continuation-agent.md
- [ ] Integration testing

---

## Key Decisions Made

| Decision | Rationale | Alternatives |
|----------|-----------|--------------|
| Use subagent delegation | Can't programmatically /clear | Manual clear workflow |
| 80% default threshold | Leaves 20% buffer | 75%, 85% |
| .claude/session-state.md | Project-scoped | /tmp, ~/.claude |

---

## Continuation Instructions

### Immediate Next Step
Complete the session-state.md module, then update context_warning.py

### Context to Re-read
1. `/plugins/conserve/skills/clear-context/SKILL.md` - Main skill reference
2. `/plugins/conserve/hooks/context_warning.py` - Hook to update

### Warnings/Gotchas
- CLAUDE_CONTEXT_USAGE env var may not be set
- Design must work with estimation fallback
```

### Continuation Agent Response

```
I've read the session state checkpoint. Let me verify my understanding:

**Objective**: Implement clear-context skill for conserve plugin
**Progress**: SKILL.md is complete, session-state module in progress
**Next Step**: Complete session-state.md, then update context_warning.py

Reading the referenced files now to continue...
```


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)