context-management
Context window auto-management — signals, strategies, and recovery protocol. Detects approaching context limits and guides compact vs checkpoint decisions to prevent lost work.
Best use case
context-management is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Context window auto-management — signals, strategies, and recovery protocol. Detects approaching context limits and guides compact vs checkpoint decisions to prevent lost work.
Teams using context-management should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/context-management/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How context-management Compares
| Feature / Agent | context-management | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Context window auto-management — signals, strategies, and recovery protocol. Detects approaching context limits and guides compact vs checkpoint decisions to prevent lost work.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Context Window Auto-Management
Strategies for detecting, responding to, and recovering from context window pressure. The session-end hook warns when sessions exceed 90 minutes without a `.clarc/context.md`, prompting a checkpoint.
## When to Activate
- Claude suggests `/compact` or context is nearing capacity
- Session has been running for 90+ minutes
- User is mid-task and worried about context loss
- After recovering from a context reset
- Planning a large multi-file implementation
- Starting a multi-phase refactor that will span more than 20 files so checkpoints are created between phases to prevent losing progress
- Recovering a session after an unexpected compaction wiped the conversation state mid-task and the next steps are unclear
- Setting up a new project to use the `.clarc/` memory bank so session-end hooks automatically persist context across restarts
## Context Pressure Signals
### Warning Signs (Act Proactively)
| Signal | Threshold | Action |
|--------|-----------|--------|
| Session length | > 90 min | Create `.clarc/context.md` checkpoint |
| File count in task | > 20 files | Split into phases with checkpoints |
| Token estimate | > 80% of window | `/compact` or summarize |
| Repeated context loads | Same files > 3x | Extract summary to working file |
| Tool call depth | > 50 in session | `/checkpoint create` before continuing |
### Critical Signs (Act Immediately)
- Claude stops referencing earlier conversation correctly
- Responses become repetitive or miss established constraints
- System suggests `/compact` automatically
- Context compaction triggers mid-task
## Strategies
### 1. Checkpoint Before Compaction
Before running `/compact`, always checkpoint:
```
/checkpoint create pre-compact
```
The checkpoint records:
- Current git SHA
- Files modified so far
- Completed vs remaining tasks
After compaction, restore with:
```
/checkpoint verify pre-compact
cat .clarc/context.md
```
### 2. Memory Bank as Persistent State
`.clarc/context.md` is the canonical session handoff document (written by session-end hook automatically). Keep it current during long sessions:
```markdown
# Session Context — 2026-03-09
## Current focus
- Implementing REST API authentication middleware
- Files: src/middleware/auth.ts, tests/unit/auth.test.ts
## Progress
- [x] JWT validation logic
- [x] Unit tests passing
- [ ] Integration test
- [ ] Rate limiting
## Key decisions
- Using RS256 (not HS256) for multi-service JWT
- Middleware runs before route handlers
## Next steps
1. Write integration test (src/tests/integration/auth.test.ts)
2. Add rate limiting (src/middleware/rate-limit.ts)
```
Update manually at logical milestones or run:
```bash
/checkpoint create milestone-name
```
### 3. Progressive Summarization
For large tasks spanning many files, summarize as you go:
**Working summary pattern:**
1. Read N files
2. Summarize findings in one working note
3. Read next N files (use summary, not all N files)
4. Repeat until done
This reduces re-reading costs and fits more analysis in the context window.
### 4. Phase-Based Implementation
Break large implementations into phases, each fitting in one context window:
```
Phase 1: Plan + design (separate session or first context)
Output: docs/specs/feature-plan.md
Phase 2: Core implementation
Input: feature-plan.md (small, loaded fresh)
Output: core files
Phase 3: Tests + edge cases
Input: feature-plan.md + list of core files
Output: test files
Phase 4: Review + cleanup
Input: git diff (compact representation)
Output: final commits
```
Each phase starts fresh with minimal context load.
## Recovery Protocol
When context has been lost or compacted mid-task:
```
1. Read .clarc/context.md # Memory Bank (if exists)
2. Run: git log --oneline -10 # Recent commits
3. Run: git diff HEAD # Current changes
4. Run: git stash list # Any stashed work
5. Read checkpoint log:
cat .claude/checkpoints.log
6. Reconstruct state and continue
```
If `.clarc/context.md` is up to date, recovery takes < 2 minutes.
## Hook Integration
The session-end hook (`scripts/hooks/session-end.js`) automatically:
- Writes `.clarc/context.md` at session end (if `.clarc/` exists)
- Appends to `.clarc/progress.md`
- Warns after 90-minute sessions without a context checkpoint
To opt in: `mkdir .clarc` in your project root.
## Context Window Budget
Approximate token budget guidance. Context window size varies by model — check current limits at [Anthropic docs](https://docs.anthropic.com/api). The proportions below apply regardless of the exact window size:
| Component | Typical tokens | Notes |
|-----------|---------------|-------|
| System prompt + rules | ~8k | Fixed |
| Conversation history | ~40k | Grows over session |
| Working files | ~30k | Keep focused |
| Tool outputs | ~20k | Flush when done |
| **Available for new work** | **~30k** | After 90 min session (assumes ~128k window) |
When available budget drops below ~20k: checkpoint + compact.
## Token-Efficient vs Token-Heavy Tool Usage
### Before: Token-Heavy Pattern
Reading entire files on every step wastes context budget rapidly.
```
Turn 1: Read src/auth/jwt.ts (800 tokens)
Turn 2: Read src/auth/jwt.ts again (800 tokens — forgot it was already loaded)
Turn 3: Read src/middleware/index.ts (1,200 tokens)
Turn 4: Read src/middleware/index.ts (1,200 tokens — re-loaded for reference)
Turn 5: Read src/auth/jwt.ts (800 tokens — needed one function again)
Total wasted re-reads: ~3,800 tokens
```
Compounded across a 50-file refactor, re-reads alone consume 20–30k tokens.
### After: Token-Efficient Pattern
```
Turn 1: Read src/auth/jwt.ts
→ Write working note: "jwt.ts exports: verifyToken(token), signToken(payload, opts)"
Turn 2: Read src/middleware/index.ts
→ Append to working note: "middleware/index.ts mounts: auth (jwt), rateLimit, cors"
Turn 3: (work continues using the working note — never re-read jwt.ts)
# Working note stays under 200 tokens; replaces thousands of re-read tokens
```
**Rule of thumb:** After reading a file, extract the 3–5 facts you need from it into a working note. Use the note for the rest of the session; re-read the file only if you need the exact text (e.g., before an edit).
### Recognising Re-Read Waste in Practice
These patterns signal you are re-reading unnecessarily:
- Same file appears twice in recent tool calls with no edit between them
- You read a file "just to check" something you noted earlier
- Each sub-task starts by re-reading the same config or schema file
When you notice this: stop, write a one-paragraph working summary, and continue from the summary.Related Skills
subagent-context-retrieval
Pattern for progressively refining context retrieval in multi-agent workflows — avoids context-overflow failures when subagents cannot predict what context they need upfront.
state-management
Frontend state management patterns: TanStack Query for server state, Zustand for client state, URL state, form state with React Hook Form, and when to use what. Prevents over-engineering and the most common state bugs.
release-management
Release management: semantic versioning, conventional commits → CHANGELOG, git tagging, GitHub Releases, pre-release testing, and rollback procedures. Use /release to automate the process.
cost-management
Claude API cost awareness — token estimation, cost drivers, and efficiency strategies for Claude Code sessions
zero-trust-patterns
Zero-Trust security patterns — mTLS between microservices (Istio/SPIFFE), SPIRE workload identity, OPA/Envoy authorization, NetworkPolicy default-deny-all, short-lived credentials, service mesh security, and Kubernetes RBAC hardening.
wireframing
Wireframing and prototyping workflow: fidelity levels (lo-fi sketch → mid-fi wireframe → hi-fi prototype), tool selection (Figma, Excalidraw, Balsamiq), user flow diagrams, wireframe annotation standards, information architecture (IA) mapping, and the handoff from wireframe to visual design. For developers who need to communicate UI structure before writing code.
webrtc-patterns
WebRTC patterns — peer connection setup, ICE/STUN/TURN configuration, signaling server design, SFU vs mesh topology, screen sharing, media track management, and reconnect/ICE restart handling.
webhook-patterns
Webhook patterns for receiving, verifying (HMAC), and idempotently processing third-party events. Covers Stripe, GitHub, and generic webhook patterns, delivery guarantees, retry handling, and testing.
web-performance
Web performance optimization: Core Web Vitals (LCP, CLS, INP), Lighthouse CI with budget configuration, bundle analysis (webpack-bundle-analyzer, vite-bundle-visualizer), hydration performance, network waterfall reading, image optimization (WebP/AVIF, srcset), and font performance.
wasm-performance
WebAssembly performance: wasm-opt binary optimization, size reduction (panic=abort, LTO, strip), profiling WASM in Chrome DevTools, memory management (linear memory, avoiding GC pressure), SIMD, and multi-threading with SharedArrayBuffer.
wasm-patterns
WebAssembly patterns: wasm-pack, wasm-bindgen (JS↔Wasm interop), WASI, Component Model, wasm-opt, Rust-to-WASM compilation, JS integration (web workers, streaming instantiation), and production deployment (CDN, Content-Type headers).
visual-testing
Visual Regression Testing: tool comparison (Chromatic/Percy/Playwright screenshots/BackstopJS), pixel-diff vs AI-based comparison, baseline management, flakiness strategies (masks, tolerances, waitForLoadState), CI integration with GitHub Actions, and Storybook integration.