Skip to main content
vzwjustin

context-window-manager

by vzwjustinv1.0.0

Monitor, analyze, and optimize Claude Code context window usage with real-time alerts and historical tracking

Installation guide →

Keywords

contexttokensmonitoringoptimizationanalytics

Commands

alert

Set up context usage alerts and thresholds

analyze

Analyze current context window usage and provide optimization recommendations

context-map

Generate comprehensive map of current context knowledge with token costs

history

View historical context usage data and trends

optimize

Get actionable steps to optimize context window usage right now

prune

Automatically prune unused context to save tokens

report

Generate a comprehensive context usage report for the current session

savings

Calculate and track token savings from optimizations

status

Quick context window status check with visual indicator

Documentation

# Claude Code Context Window Manager

A comprehensive plugin for monitoring, analyzing, and optimizing your Claude Code context window usage. Stay in control of your context and maximize productivity with real-time tracking, intelligent alerts, and actionable insights.

## 🎯 Features

### 📊 Real-Time Monitoring
- **Live Context Tracking**: Automatic monitoring of token usage throughout your session
- **Usage Alerts**: Configurable thresholds warn you before hitting limits
- **Session Metrics**: Track tool calls, files accessed, and token consumption patterns

### 🔍 Deep Analysis
- **Slash Commands**: Quick status checks and detailed usage reports
- **AI-Powered Skills**: Sophisticated analysis using specialized AI capabilities
- **Historical Tracking**: Compare current session against your usage history

### ⚡ Smart Optimization
- **Actionable Recommendations**: Get specific steps to reduce context bloat
- **Impact Estimation**: See exactly how many tokens each optimization will save
- **Automated Logging**: Hooks track usage automatically without manual intervention

### 📈 Comprehensive Reporting
- **Multiple Formats**: Export data as JSON, CSV, or Markdown
- **Visual Indicators**: Progress bars, health status, and trend charts
- **Session Archives**: Complete history of all your Claude Code sessions

## ⚡ NEW: Advanced Features

### 🤖 Agent-Powered Analysis (10x Faster!)
- **Context Analyzer Agent**: Complete analysis in <2 minutes (vs 10-15 min manual)
- **Context Pruner Agent**: Intelligent pruning in <90 seconds
- **Parallel Processing**: Multiple analyses run simultaneously for maximum speed

### 🔪 Auto-Pruning System
- **Smart Detection**: Automatically identifies unused files, old logs, and temporary content
- **Safe Removal**: Only removes low-risk items with zero chance of data loss
- **Configurable Rules**: Set patterns for always-prune, always-keep files
- **Token Savings**: Average 40,000-70,000 tokens saved per comprehensive prune

### 🗺️ Context Knowledge Mapping
- **Real-Time Tracking**: Maintains live database of everything in context
- **Access Heatmaps**: Visual representation of file usage patterns
- **Dependency Graphs**: See relationships between files and tools
- **Predictive Analysis**: Estimates future usage and time to limits

### 💰 Token Savings Tracker
- **Lifetime Statistics**: Track cumulative token savings across all sessions
- **ROI Calculator**: See return on optimization investment
- **Gamification**: Milestones, leaderboards, and achievement tracking
- **Scenario Simulator**: Preview savings from different optimization strategies

**📖 See [FEATURES.md](FEATURES.md) for complete details on advanced features**

## 🚀 Quick Start

### Installation

1. **Clone or download this plugin:**
   ```bash
   git clone <repository-url> context-window-manager
   cd context-window-manager
   ```

2. **Test locally with Claude Code:**
   ```bash
   claude --plugin-dir ./
   ```

3. **Install permanently** (optional):
   ```bash
   # Copy to Claude Code plugins directory
   mkdir -p ~/.claude/plugins
   cp -r . ~/.claude/plugins/context-window-manager
   ```

### First Use

Once loaded, try these commands in your Claude Code session:

```bash
# Quick status check
/context-window-manager:status

# Detailed analysis (agent-powered, fast!)
/context-window-manager:analyze

# Auto-prune unused context (NEW!)
/context-window-manager:prune

# View context knowledge map (NEW!)
/context-window-manager:context-map

# Track token savings (NEW!)
/context-window-manager:savings

# Get optimization recommendations
/context-window-manager:optimize

# Generate full report
/context-window-manager:report
```

**📘 New to the plugin? Read [QUICKSTART.md](QUICKSTART.md) for a 5-minute guided tour!**

## 📖 Documentation

### Slash Commands

The plugin provides six powerful slash commands:

#### `/context-window-manager:status`
Quick at-a-glance status check with visual indicator.

**Use when:** You want a fast check without detailed analysis.

**Output:**
```
┌─────────────────────────────────────────────────┐
│ CONTEXT WINDOW STATUS                           │
├─────────────────────────────────────────────────┤
│ Capacity:   200K tokens                         │
│ Used:       72,000 tokens (36%)                 │
│ Available:  128,000 tokens (64%)                │
│ Status:     🟢 Healthy                          │
│                                                 │
│ Progress: [███████░░░░░░░░░] 36%               │
└─────────────────────────────────────────────────┘
```

#### `/context-window-manager:analyze`
Deep analysis of current context usage with optimization recommendations.

**Use when:** You want to understand what's consuming your context.

**Output includes:**
- Current usage breakdown by component
- Top context consumers
- Token burn rate and time projections
- Health status and recommendations

#### `/context-window-manager:optimize`
Get actionable steps to reduce context usage immediately.

**Use when:** Context usage is approaching limits (>60%).

**Output includes:**
- Prioritized optimization checklist
- Expected token savings per action
- Risk assessment for each optimization
- Prevention tips for future sessions

#### `/context-window-manager:report`
Comprehensive usage report with historical comparison.

**Use when:** You need detailed documentation or trend analysis.

**Output includes:**
- Executive summary
- Complete token allocation breakdown
- Session timeline and metrics
- Historical comparison
- Detailed recommendations

#### `/context-window-manager:history`
View historical context usage data and trends.

**Use when:** You want to see patterns across multiple sessions.

**Output includes:**
- Last 10 sessions summary
- Usage trends over time
- Average vs current comparison
- Peak usage identification

#### `/context-window-manager:alert`
Configure context usage alerts and thresholds.

**Use when:** Setting up or adjusting monitoring preferences.

**Features:**
- Set warning/critical thresholds
- Configure notification methods
- Test alert triggers
- Enable/disable monitoring

### Automatic Hooks

The plugin includes four event hooks that run automatically:

#### SessionStart Hook
**Triggers:** When a new Claude Code session begins
**Actions:**
- Initializes log files
- Creates session tracking file
- Sets up default configuration if missing

#### PostToolUse Hook
**Triggers:** After each Read, Write, Edit, Glob, or Grep tool use
**Actions:**
- Logs tool usage
- Estimates token consumption
- Updates session metrics
- Checks alert thresholds

#### PreCompact Hook
**Triggers:** Before automatic context compaction
**Actions:**
- Warns user about impending compaction
- Logs compaction event
- Suggests whether to continue or break
- Updates warning counters

#### Stop/SessionEnd Hook
**Triggers:** When session ends
**Actions:**
- Finalizes session metrics
- Archives session data
- Generates session summary
- Cleans up temporary files

### AI Skills

Three specialized skills provide sophisticated analysis:

#### CONTEXT_ANALYZER
Expert analysis of context usage patterns.

**Capabilities:**
- Parse /context output for precise metrics
- Calculate burn rates and projections
- Identify optimization opportunities
- Provide risk-assessed recommendations

**Best for:** When you need AI-powered insights beyond basic metrics.

#### USAGE_REPORTER
Professional report generation.

**Capabilities:**
- Create formatted reports in multiple styles
- Generate visual representations (charts, tables)
- Compare historical data
- Export-ready documentation

**Best for:** Documentation, sharing insights with team, tracking progress.

#### CONTEXT_OPTIMIZER
Optimization strategy expert.

**Capabilities:**
- Identify high-impact optimizations
- Prioritize actions by ROI
- Assess risks and reversibility
- Provide step-by-step implementation guides

**Best for:** Critical situations requiring immediate context reduction.

### Utility Scripts

Three command-line utilities for offline analysis:

#### `utils/analyze-logs.sh`
Analyze logged session data without starting Claude Code.

```bash
./utils/analyze-logs.sh
```

**Shows:**
- Current session status
- Session history statistics
- Tool usage breakdown
- Recent warnings and alerts

#### `utils/view-session.sh`
View detailed information about a specific session.

```bash
# View current session
./utils/view-session.sh

# View specific archived session
./utils/view-session.sh session-20240115-143022.json
```

**Shows:**
- Complete session timeline
- All metrics and statistics
- Files accessed
- Efficiency calculations

#### `utils/export-report.sh`
Export usage data to various formats.

```bash
# Export as JSON (default)
./utils/export-report.sh json

# Export as CSV
./utils/export-report.sh csv

# Export as Markdown
./utils/export-report.sh markdown
```

**Outputs:**
- `context-reports/` directory with timestamped files
- Aggregated session data
- Ready for import to analytics tools

## 📁 File Structure

```
context-window-manager/
├── .claude-plugin/
│   └── plugin.json              # Plugin manifest (required)
├── commands/                    # Slash commands
│   ├── analyze.md               # Deep usage analysis
│   ├── report.md                # Comprehensive report
│   ├── optimize.md              # Optimization recommendations
│   ├── status.md                # Quick status check
│   ├── history.md               # Historical data viewer
│   └── alert.md                 # Alert configuration
├── skills/                      # AI capabilities
│   ├── CONTEXT_ANALYZER.md      # Analysis expert
│   ├── USAGE_REPORTER.md        # Report generator
│   └── CONTEXT_OPTIMIZER.md     # Optimization expert
├── hooks/                       # Event hooks
│   ├── hooks.json               # Hook configuration
│   └── scripts/
│       ├── session-start.sh     # Session initialization
│       ├── post-tool-track.sh   # Tool usage tracking
│       ├── pre-compact-warn.sh  # Compaction warning
│       └── session-end.sh       # Session finalization
├── utils/                       # Utility scripts
│   ├── analyze-logs.sh          # Offline log analysis
│   ├── view-session.sh          # Session viewer
│   └── export-report.sh         # Data export tool
├── plugin.json                  # Plugin manifest (root)
└── README.md                    # This file
```

## 💾 Data Storage

All logs and metrics are stored in `~/.claude/context-logs/`:

```
~/.claude/context-logs/
├── usage.jsonl                  # Event log (JSONL format)
├── sessions.log                 # Human-readable session log
├── current-session.json         # Active session metrics
├── archive/                     # Archived sessions
│   ├── session-20240115-143022.json
│   ├── session-20240115-160845.json
│   └── ...
└── (created by hooks)
```

Configuration is stored in `~/.claude/context-manager/`:

```
~/.claude/context-manager/
└── config.json                  # User preferences
```

## ⚙️ Configuration

Edit `~/.claude/context-manager/config.json` to customize behavior:

```json
{
  "alerts": {
    "enabled": true,
    "thresholds": {
      "warning": 60,      // Warn at 60% usage
      "critical": 85      // Critical at 85% usage
    },
    "notify_increments": 10  // Alert every 10% after warning
  },
  "logging": {
    "enabled": true,
    "verbose": false
  },
  "tracking": {
    "tool_usage": true,
    "file_access": true,
    "token_estimation": true
  }
}
```

## 🎓 Usage Tips

### Best Practices

1. **Monitor Regularly**
   - Run `/context-window-manager:status` every 30-45 minutes
   - Watch for 🟡 Warning status (60%+)

2. **Optimize Proactively**
   - Don't wait until critical (85%+)
   - Run `/context-window-manager:optimize` at 60-70%
   - Remove unused files early

3. **Use History**
   - Compare current session to your averages
   - Identify patterns in context consumption
   - Adjust workflows based on insights

4. **Leverage Hooks**
   - Let automatic tracking work in the background
   - Review session summaries after completion
   - Use PreCompact warnings as session break points

### Common Scenarios

#### Scenario 1: Long Debugging Session
```bash
# Start session - hooks auto-initialize
# Work normally, hooks track automatically

# After 1 hour, check status
/context-window-manager:status

# If at 50%+, get analysis
/context-window-manager:analyze

# If at 70%+, optimize
/context-window-manager:optimize
```

#### Scenario 2: Context Approaching Limits
```bash
# You see 🟡 Warning or 🔴 Critical status
/context-window-manager:optimize

# Follow immediate action checklist
# Remove suggested files
# Clear tool outputs

# Verify reduction
/context-window-manager:status

# If still critical, consider session break
```

#### Scenario 3: Regular Monitoring
```bash
# Set up alerts (one time)
/context-window-manager:alert

# During work, quick checks
/context-window-manager:status

# End of day, review history
/context-window-manager:history

# Export for records
./utils/export-report.sh markdown
```

## 🔧 Troubleshooting

### Hooks Not Running

**Problem:** Automatic tracking isn't working.

**Solution:**
1. Check hooks are configured: `cat ~/.claude/plugins/context-window-manager/hooks/hooks.json`
2. Verify scripts are executable: `ls -l hooks/scripts/*.sh`
3. Make executable if needed: `chmod +x hooks/scripts/*.sh`
4. Check hook paths are absolute or relative to plugin directory

### No Historical Data

**Problem:** `/context-window-manager:history` shows no data.

**Solution:**
1. Hooks need to run for at least one session
2. Check log directory exists: `ls -la ~/.claude/context-logs/`
3. Create manually if needed: `mkdir -p ~/.claude/context-logs/archive`
4. Wait for SessionEnd hook to archive first session

### Utility Scripts Fail

**Problem:** `./utils/*.sh` scripts error out.

**Solution:**
1. Install `jq`: `sudo apt-get install jq` (or `brew install jq` on macOS)
2. Make scripts executable: `chmod +x utils/*.sh`
3. Check log directory exists: `mkdir -p ~/.claude/context-logs`

### Token Estimates Inaccurate

**Problem:** Estimated tokens don't match reality.

**Note:** Token estimation is approximate based on tool type. For accurate data:
1. Use `/context` command output as source of truth
2. Estimates improve with more session data
3. Focus on relative changes, not absolute numbers

## 🤝 Contributing

Contributions welcome! Areas for improvement:

- More accurate token estimation algorithms
- Additional export formats (HTML, PDF)
- Integration with external analytics tools
- Real-time dashboard or TUI
- Machine learning for usage prediction
- Team-wide analytics aggregation

## 📄 License

MIT License - see LICENSE file for details

## 🙏 Acknowledgments

Built for the Claude Code community. Inspired by:
- [Claude-Code-Usage-Monitor](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor)
- [claude-sessions](https://github.com/iannuttall/claude-sessions)
- [ccusage](https://github.com/ccplugins/ccusage)

## 📞 Support

- **Issues:** Open an issue on GitHub
- **Discussions:** Join Claude Code community discussions
- **Documentation:** https://code.claude.com/docs

---

**Happy coding with Claude Code! Stay in control of your context. 🚀**