Skip to content

Claude Code Hook for Context Window Monitoring - Real-time token tracking and automatic session continuation

Notifications You must be signed in to change notification settings

Guard8-ai/ContextGuard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ContextGuard

Claude Code Hook for Context Window Monitoring

ContextGuard is a Rust-based hook for Claude Code that monitors context window usage and prevents critical context exhaustion by alerting users before reaching token limits.

🎯 Features

  • Real-time token monitoring - Tracks usage from Claude Code session JSONL files
  • Automatic session continuation - SessionStart hooks for seamless context handoff
  • Configurable thresholds - TOML config file (project or global)
  • Zero dependencies - Fast, lightweight Rust binary (~433KB)
  • Defensive error handling - Handles missing files, corrupted JSON, and edge cases
  • Non-intrusive - Silent when usage is normal, alerts only when needed

πŸ“Š How It Works

ContextGuard uses two measurement methods with three hooks for comprehensive context management:

Method A: Exact /context Parsing (100% Accuracy)

When you run /context, ContextGuard:

  1. Parses the output from the JSONL transcript
  2. Extracts exact token counts (system, tools, messages, buffer)
  3. Uses this as the baseline for all monitoring
  4. Updates automatically each time you run /context

Method B: Heuristic Estimation (~98% Accuracy)

When no /context output is available, ContextGuard:

  1. Counts billable tokens from API usage events
  2. Applies compression ratio (accounts for deduplication)
  3. Adds system overhead (prompts, tools, buffer)
  4. Formula: total β‰ˆ (billable Γ— 0.071) + 60,000

UserPromptSubmit Hook (Token Monitoring)

  1. Before each prompt, reads the session transcript JSONL file
  2. Tries Method A (parse /context output) for exact accuracy
  3. Falls back to Method B (heuristic) if no /context available
  4. Checks against thresholds:
    • < 60%: Silent, allows continuation
    • 60-75%: Shows warning message, allows continuation
    • β‰₯ 75%: Creates CONTINUE_SESSION.md with handoff instructions

SessionStart Hooks (Automatic Continuation)

  1. sessionstart-context: Asks Claude to prompt user to run /context for accuracy
  2. sessionstart-continuation: Auto-loads CONTINUE_SESSION.md if present
  3. Zero friction: New sessions automatically continue with previous context

πŸ’‘ Pro Tip: Run /context at the start of your session for 100% accurate monitoring!

πŸš€ Quick Start

Installation

# Clone or navigate to ContextGuard directory
cd /data/git/Guard8.ai/ContextGuard

# Build and install
./install.sh

Enable Globally

Add to ~/.claude/settings.json:

{
  "hooks": {
    "SessionStart": [{
      "hooks": [
        {
          "type": "command",
          "command": "~/.claude/hooks/contextguard-sessionstart-context"
        },
        {
          "type": "command",
          "command": "~/.claude/hooks/contextguard-sessionstart-continuation"
        }
      ]
    }],
    "UserPromptSubmit": [{
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/contextguard"
      }]
    }]
  }
}

Enable Per-Project

The hook is already configured in .claude/settings.json for this project.

πŸ§ͺ Testing

# Test with missing file (should return safe default)
echo '{"session_id":"test","transcript_path":"/tmp/nonexistent.jsonl","hook_event_name":"UserPromptSubmit"}' | ~/.claude/hooks/contextguard

# Expected output:
# {"continue":true}
# Warning: Transcript file does not exist: /tmp/nonexistent.jsonl

βš™οΈ Configuration

ContextGuard looks for config files in this order:

  1. .claude/contextguard.toml (project-specific)
  2. ~/.claude/contextguard.toml (global)
  3. Built-in defaults (if no config found)

Project-Specific Config

Create .claude/contextguard.toml:

# Total context window limit (default: 200000)
context_limit = 200000

# Critical threshold - blocks execution (default: 0.75 = 75%)
critical_threshold = 0.75

# Warning threshold - shows warning (default: 0.60 = 60%)
warning_threshold = 0.60

Testing Configuration

For testing, set low thresholds (new sessions start ~30%):

context_limit = 200000
critical_threshold = 0.40  # Block at 40%
warning_threshold = 0.35   # Warn at 35%

No rebuild needed - config is read at runtime!

πŸ“ Project Structure

ContextGuard/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs              # Hook entry point
β”‚   β”œβ”€β”€ config.rs            # TOML config loader
β”‚   β”œβ”€β”€ hook_types.rs        # Claude Code hook I/O structures
β”‚   β”œβ”€β”€ jsonl_parser.rs      # JSONL transcript parsing
β”‚   β”œβ”€β”€ threshold_checker.rs # Token usage thresholds
β”‚   └── session_handoff.rs   # Session continuation generation
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ sessionstart-context       # Prompts /context command
β”‚   └── sessionstart-continuation  # Auto-loads CONTINUE_SESSION.md
β”œβ”€β”€ .claude/
β”‚   β”œβ”€β”€ contextguard.toml    # Project config (test thresholds)
β”‚   └── settings.json        # Hook registration
β”œβ”€β”€ Cargo.toml               # Rust dependencies
β”œβ”€β”€ install.sh               # Installation script
└── README.md                # This file

πŸ” Implementation Details

JSONL Parsing

Adapted from HalluciGuard:

  • Streams JSONL line-by-line (no memory overhead)
  • Extracts token usage from each event
  • Handles all token types: input, output, cache creation, cache read
  • Defensive against missing files and corrupted lines

Hook Integration

  • Input: JSON from Claude Code via stdin
  • Output: JSON response to stdout
  • Fields:
    • continue: true (allow) or false (block)
    • stopReason: Optional blocking reason
    • systemMessage: Optional user-facing message

Error Handling

Handles known Claude Code issues:

  • Issue #3046: Missing transcript files after /clear
  • Issue #2597: Cross-session summary contamination
  • Safe defaults: missing file = 0 tokens

πŸ“ˆ Example Output

Warning (60-75%)

⚠️  ContextGuard: Approaching context limit
Usage: 125.0k / 200.0k tokens (63%)
Consider using /clear soon.

Critical (β‰₯75%)

πŸ›‘ ContextGuard: Critical context usage!
Usage: 155.0k / 200.0k tokens (78%)
Please use /clear or start a new session to continue.

πŸ› οΈ Development

# Run tests
cargo test

# Build optimized release
cargo build --release

# Check binary size
ls -lh target/release/contextguard

# Manual test with sample data
echo '{"session_id":"test","transcript_path":"test_data.jsonl","hook_event_name":"UserPromptSubmit"}' | cargo run --release

πŸ”— Related Projects

πŸ“š References

πŸ“ License

Part of the Guard8.ai toolkit.


Built with TaskGuard - See tasks/ for implementation tracking

About

Claude Code Hook for Context Window Monitoring - Real-time token tracking and automatic session continuation

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •