Feature Request: Add `clearContext` field to Stop hook output
Feature Request: Add clearContext field to Stop hook output
Summary
Add a clearContext boolean field to the Stop hook output schema that clears conversation context before feeding the next prompt back to Claude. This enables automated development loops that maintain fresh context across iterations.
Motivation
The Problem
The ralph-loop technique (iterative AI development loops) works by using a Stop hook to intercept session exit and feed the same prompt back to Claude. This is powerful for automated task completion, but has a critical limitation: context accumulates across iterations.
After 10-20 iterations, context becomes bloated with:
- Previous file reads
- Tool call history
- Intermediate reasoning
- Stale information from earlier iterations
This causes:
- Slower responses (more tokens to process)
- Reduced reasoning quality (attention diluted)
- Eventually hitting context limits
- Wasted tokens/cost
Current Workarounds
- Manual intervention: User runs
/clearbetween iterations (breaks automation) - External orchestrator: Use external tools like
ralph-orchestratorthat spawn freshclaude-codeprocesses (loses in-session benefits, more complex setup) - Accept degradation: Just let context accumulate (poor quality after many iterations)
The Solution
A clearContext field in Stop hook output would enable automated loops with fresh context per iteration - the best of both worlds.
Proposed API
Stop Hook Output Schema Addition
interface StopHookOutput {
decision: "approve" | "block";
reason?: string; // Prompt to feed back when blocking
systemMessage?: string; // Message shown to user
continue?: boolean; // If false, stops Claude entirely
stopReason?: string; // Custom stop message
// NEW FIELD
clearContext?: boolean; // If true, clear conversation before feeding reason
}
Behavior
When clearContext: true is set along with decision: "block":
- Current conversation context is cleared (equivalent to
/clear) - CLAUDE.md and system context are preserved (same as
/clearbehavior) - The
reasonfield is fed as the first message in the fresh context systemMessageis shown to user (if provided)
Example Usage
#!/bin/bash
# stop-hook.sh for devloop + ralph integration
# Check if all tasks complete
COMPLETE=$(./check-plan-complete.sh)
if [ "$COMPLETE" = "true" ]; then
# Allow exit - work is done
echo '{"decision": "approve"}'
else
# Continue with fresh context
cat <<EOF
{
"decision": "block",
"reason": "Continue working on tasks from .devloop/plan.md. Find the next unchecked task and complete it.",
"clearContext": true,
"systemMessage": "🔄 Iteration $N - Context cleared, continuing with fresh state"
}
EOF
fi
Prompt-Based Hook Example
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Check if all tasks in .devloop/plan.md are complete. If yes, return {\"decision\": \"approve\"}. If no, return {\"decision\": \"block\", \"reason\": \"Continue with next task\", \"clearContext\": true}."
}
]
}
]
}
}
Use Cases
1. Automated Development Loops (Primary)
┌─────────────────────────────────────────┐
│ User: /devloop:ralph │
│ └─→ Sets up Stop hook with clearContext│
└──────────────────┬──────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Claude works on Task 1 │
│ └─→ Completes task, tries to exit │
└──────────────────┬──────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Stop hook intercepts │
│ └─→ Checks: more tasks? │
│ └─→ Returns clearContext: true │
└──────────────────┬──────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Context cleared, prompt fed back │
│ └─→ Fresh context for Task 2 │
└──────────────────┬──────────────────────┘
↓
[Repeat until done]
2. Long-Running Agents
Agents that run for extended periods (monitoring, continuous integration) could periodically clear context to maintain performance.
3. Multi-Phase Workflows
Complex workflows with distinct phases (discovery → planning → implementation → testing) could clear context between phases to focus attention.
Alternatives Considered
A. External Process Orchestration
Approach: Use external tools to spawn fresh claude-code processes.
Drawbacks:
- Loses in-session state (MCP connections, environment)
- More complex setup
- Higher latency between iterations
- Can't leverage existing plugin infrastructure
B. Automatic Context Compaction
Approach: Enhanced auto-compact that's more aggressive.
Drawbacks:
- Still accumulates some context
- Not as clean as fresh start
- May lose important context unintentionally
C. New Hook Event (ContextReset)
Approach: Add a new hook event type that triggers on context operations.
Drawbacks:
- More complex than a simple field
- Doesn't solve the "trigger clear from hook" problem
Implementation Considerations
State Preservation
When clearContext: true:
- CLAUDE.md content: Preserved (reloaded as normal)
- System prompts: Preserved
- MCP server connections: Preserved (no reconnection needed)
- Tool permissions: Preserved (per-session permissions maintained)
- Conversation history: Cleared
- File read cache: Cleared (files re-read as needed)
Hook Execution Order
If multiple Stop hooks exist:
- All hooks execute in order
- If ANY hook returns
clearContext: true, context is cleared - The
reasonfrom the LAST blocking hook is used as the prompt
Error Handling
- If
clearContext: truebutdecision: "approve", ignoreclearContext(context only cleared when continuing) - If
clearContext: truebut noreasonprovided, use empty prompt (just clear)
Logging
Add log entry when context is cleared by hook:
[hook] Stop hook cleared context (hook: /path/to/hook.sh)
Security Considerations
clearContextshould respect existing permission model- Hooks already have significant power (can block exit, feed arbitrary prompts)
- Context clearing is less dangerous than arbitrary prompt injection
- Consider adding a setting to disable hook-triggered context clearing if needed
Backwards Compatibility
- New optional field, existing hooks unchanged
- Default
clearContext: false(current behavior) - No breaking changes to existing Stop hook implementations
Related
- Stop hook documentation: https://docs.anthropic.com/claude-code/hooks#stop
- Ralph Wiggum technique: https://ghuntley.com/ralph/
- ralph-orchestrator: https://github.com/mikeyobrien/ralph-orchestrator
Summary
Adding clearContext to Stop hook output would enable powerful automated development loops while maintaining fresh context. This is a minimal, backwards-compatible change that unlocks significant new capabilities for plugin developers.
---
Submitted by: @Zate
Plugin: devloop (cc-plugins marketplace)
Related PR: [Link to devloop ralph integration if applicable]
This issue has 5 comments on GitHub. Read the full discussion on GitHub ↗