Feature Request: Add `clearContext` field to Stop hook output

Resolved 💬 5 comments Opened Jan 7, 2026 by Zate Closed Mar 18, 2026

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

  1. Manual intervention: User runs /clear between iterations (breaks automation)
  2. External orchestrator: Use external tools like ralph-orchestrator that spawn fresh claude-code processes (loses in-session benefits, more complex setup)
  3. 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":

  1. Current conversation context is cleared (equivalent to /clear)
  2. CLAUDE.md and system context are preserved (same as /clear behavior)
  3. The reason field is fed as the first message in the fresh context
  4. systemMessage is 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:

  1. All hooks execute in order
  2. If ANY hook returns clearContext: true, context is cleared
  3. The reason from the LAST blocking hook is used as the prompt

Error Handling

  • If clearContext: true but decision: "approve", ignore clearContext (context only cleared when continuing)
  • If clearContext: true but no reason provided, 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

  • clearContext should 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

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]

View original on GitHub ↗

This issue has 5 comments on GitHub. Read the full discussion on GitHub ↗