Skip to content

younann/context-free

Repository files navigation

Claude Context Monitor

npm version License: MIT

Automatic context window management for Claude Code sessions.

When your Claude Code session approaches the context limit, this tool automatically saves your progress (goals, tasks, file changes) and seamlessly restarts with a fresh session that continues from where you left off.

The Problem

Claude Code has a 200k token context window. During long coding sessions, you can hit this limit, causing:

  • Loss of conversation context
  • Need to manually re-explain what you were working on
  • Interrupted workflows

The Solution

Context Monitor wraps Claude Code to:

  1. Track context window usage in real-time
  2. Save session state when approaching the threshold (default: 50%)
  3. Restart automatically with a new session
  4. Resume seamlessly with preserved context
┌─────────────────────────────────────────────────┐
│           Context Monitor Wrapper               │
├─────────────────────────────────────────────────┤
│  TokenTracker    StateManager    SessionController
│       │               │                │        │
│       └───────────────┴────────────────┘        │
│                       │                         │
│              Claude Code SDK                    │
├─────────────────────────────────────────────────┤
│         .claude/session-state.json              │
└─────────────────────────────────────────────────┘

Installation

Prerequisites

  • Node.js 18+
  • Claude Code CLI installed (npm install -g @anthropic-ai/claude-code)
  • Valid Anthropic API key configured

Option 1: Install from npm (Recommended)

npm install -g claude-context-monitor

Option 2: Install from source

git clone https://github.com/younann/context-free.git
cd claude-context-monitor
npm install
npm run build
npm link

Quick Start

As a Standalone Command

# Run with context monitoring
context-monitor "Build a REST API with authentication"

# With custom threshold (60%)
context-monitor -t 60 "Refactor the database layer"

# Verbose mode
context-monitor -v "Debug the payment system"

Replace Claude Command (Seamless Integration)

Add to your ~/.zshrc or ~/.bashrc:

# Claude Code Context Monitor
export CLAUDE_REAL_PATH="$(which claude)"
export CLAUDE_CONTEXT_THRESHOLD=50
alias claude="claude-monitored"

Then reload your shell:

source ~/.zshrc  # or ~/.bashrc

Now use claude normally - monitoring is automatic!

Configuration

Environment Variables

Variable Default Description
CLAUDE_CONTEXT_THRESHOLD 50 Restart threshold (% of context window)
CLAUDE_CONTEXT_WARNING 45 Warning threshold (% of context window)
CLAUDE_CONTEXT_SIZE 200000 Context window size in tokens
CLAUDE_CONTEXT_MONITOR true Set to false to disable monitoring
CLAUDE_REAL_PATH auto-detect Path to real claude executable

CLI Options

Usage: context-monitor [options] <prompt>

Options:
  -t, --threshold <n>    Context usage threshold percentage (default: 50)
  -c, --context-size <n> Context window size in tokens (default: 200000)
  -d, --cwd <path>       Working directory for the session
  --no-resume            Don't resume from previous saved state
  -v, --verbose          Enable verbose output
  -h, --help             Show help message
  --version              Show version

How It Works

State Preservation

When the context threshold is reached, the monitor saves:

{
  "version": "1.0",
  "savedAt": "2024-01-15T10:30:00Z",
  "previousSessionId": "session-abc123",
  "contextAtSave": {
    "usedPercentage": 50.2,
    "inputTokens": 100400
  },
  "currentGoal": "Implement user authentication",
  "completedTasks": [
    { "id": "task-001", "subject": "Create user model", "status": "completed" }
  ],
  "pendingTasks": [
    { "id": "task-002", "subject": "Implement login endpoint", "status": "pending" }
  ],
  "fileChanges": [
    { "path": "src/models/User.ts", "action": "created" }
  ],
  "resumeInstructions": "Continue implementing login endpoint..."
}

Resume Flow

When a new session starts, it receives a structured resume prompt:

## Resuming Previous Session

**Previous Session:** session-abc123
**Saved At:** 2024-01-15T10:30:00Z

### Current Goal
Implement user authentication

### Completed Tasks
- [x] Create user model

### Pending Tasks
- ⏳ Implement login endpoint

### File Changes Made
- ✨ src/models/User.ts (created)

### Resume Instructions
Continue implementing login endpoint...

---
Please continue from where we left off.

Alternative: Hooks-Based Monitoring

If you prefer using Claude Code hooks (warnings only, no auto-restart):

  1. Copy the hook script:
cp hooks/context-monitor-hook.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/context-monitor-hook.sh
  1. Add to ~/.claude/settings.json:
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "*",
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/context-monitor-hook.sh"
      }]
    }]
  }
}

Note: Hooks cannot restart sessions programmatically - they can only warn and save state.

Programmatic Usage

import { SessionController, TokenTracker, StateManager } from 'claude-context-monitor';

const controller = new SessionController({
  config: {
    thresholdPercentage: 50,
    contextWindowSize: 200000,
  },
  onThresholdReached: (percentage) => {
    console.log(`Context at ${percentage}%, restarting...`);
  },
  onSessionRestart: (sessionNumber) => {
    console.log(`Starting session #${sessionNumber}`);
  },
});

await controller.runWithMonitoring("Build a todo app with React");

Comparison: Wrapper vs Hooks

Feature Wrapper Hooks
Auto-restart at threshold ✅ Yes ❌ No
State preservation ✅ Yes ✅ Yes
Seamless resume ✅ Automatic ⚠️ Manual
Interactive mode support ⚠️ Pass-through ✅ Full
Zero config after install ✅ Yes ❌ No

Troubleshooting

"claude command not found"

Ensure Claude Code CLI is installed:

npm install -g @anthropic-ai/claude-code

Session keeps restarting immediately

Your threshold may be too low. Increase it:

export CLAUDE_CONTEXT_THRESHOLD=60

State file not being created

Check write permissions for .claude/ directory in your project.

Monitoring not working

Verify the monitor is active:

CLAUDE_CONTEXT_MONITOR=true context-monitor -v "test"

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Author

Younan Nwesre - @younann

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built with the Claude Agent SDK
  • Inspired by the need for seamless long-running coding sessions

Created by Younan Nwesre

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors