[Feature] Context-aware session relay: hook events, CLI flags, and env vars for context utilization

Resolved 💬 2 comments Opened Apr 20, 2026 by joshduffy Closed Jun 11, 2026

Problem

Long Claude Code sessions degrade in quality as context fills up. Users who run complex, multi-session builds (Go rewrites, large refactors, multi-file features) need a way to:

  1. Detect when context utilization crosses a threshold (e.g., 75%)
  2. React by writing a structured handoff before quality degrades
  3. Chain sessions automatically, resuming from the handoff

Today, none of these are possible:

  • No context metric exposed. Hooks, scripts, and Claude itself have no access to current context utilization as a percentage or token count. The agent flies blind.
  • PreCompact fires too late. It triggers at ~95% utilization, after quality has already degraded. It also doesn't cause a session exit; compaction runs and the session continues.
  • No --max-turns flag. The only session-length control in -p mode is --max-budget-usd, which correlates with tokens generated, not context consumed. These are orthogonal.
  • No hook can force-exit a session. PreToolUse can block a tool call. Stop can provide feedback. Neither can terminate the session.

This makes automated session relay (critical for CI pipelines, long builds, and autonomous agent loops) structurally impossible to build in userland.

Proposed solution

Three complementary features, in priority order:

1. ContextPressure hook event (highest value)

A new hook event that fires when context utilization crosses a configurable threshold.

// settings.json
{
  "hooks": {
    "ContextPressure": [
      {
        "threshold": 0.75,  // fires at 75% context used
        "hooks": [{
          "type": "command",
          "command": "echo 'Write a handoff document now. Run /handoff and end your turn.'"
        }]
      }
    ]
  }
}

The hook output would be injected into Claude's context as feedback (same as Stop hook output today), giving Claude a chance to write a handoff before quality degrades.

2. $CLAUDE_CONTEXT_PERCENT environment variable

Expose current context utilization to all hook environments:

# Available in PreToolUse, PostToolUse, Stop, PreCompact hooks
echo $CLAUDE_CONTEXT_PERCENT  # "73" (integer 0-100)
echo $CLAUDE_CONTEXT_TOKENS   # "730000" (tokens used)
echo $CLAUDE_CONTEXT_LIMIT    # "1000000" (max tokens)

This lets users build their own context-aware logic in existing hook types without a new event.

3. --max-context-percent flag for -p mode

claude -p "build the feature" --max-context-percent 75

When context utilization hits the threshold, Claude Code:

  1. Injects a system message: "Context limit reached. Write a final handoff and end."
  2. Allows Claude one more turn to write the handoff
  3. Exits with a distinct exit code (e.g., exit 2 = "context limit")

This enables reliable session relay scripts:

while true; do
  claude -p "$PROMPT" --max-context-percent 75
  EXIT=$?
  if [ $EXIT -eq 0 ]; then break; fi        # done
  if [ $EXIT -eq 2 ]; then                    # context limit
    PROMPT=$(read_handoff_file)
    continue
  fi
  exit $EXIT                                  # real error
done

Why this matters

For CI/CD and autonomous agents

Teams running Claude Code in -p mode for automated tasks (test generation, migration scripts, code review) currently have no way to handle context exhaustion gracefully. The session either compacts (losing important earlier context) or fails silently.

For power users with session handoff workflows

Users who already maintain handoff files (see #11455) do so manually. With context utilization exposed, the handoff can be triggered automatically at the right moment, not too early (wasting productive context) and not too late (after quality degrades).

For the 20x token bug

Multiple users report a caching bug that causes ~20x token consumption in long sessions. Context-aware session relay is the primary mitigation: exit before the bug triggers, resume fresh.

Related issues

  • #38400 - Expose context window utilization to the agent
  • #11455 - Session Handoff / Continuity Support
  • #48956 - Warn user when context window is nearly full
  • #46897 - Display context window usage percentage indicator

This feature request differs from the above by proposing programmatic hooks and CLI flags (not just UI indicators), enabling automated relay rather than manual awareness.

Implementation notes

From examining the Claude Code source (autoCompact.ts, query.ts), context utilization is already tracked internally to trigger compaction. The proposed features would:

  1. Expose the existing utilization metric through the hook environment
  2. Add a threshold check in the query loop (before each API call)
  3. Add a new hook event dispatch at the threshold crossing
  4. Add exit-code semantics for the -p mode flag

The internal plumbing already exists; this is primarily a matter of exposing it.

View original on GitHub ↗

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