context-management
Proactive context window management via token monitoring, intelligent extraction, and selective rehydration. Features predictive budget monitoring, context health indicators, and priority-based retention. Use when approaching token limits or needing to preserve essential context. Complements /transcripts and PreCompact hook with proactive optimization.
What this skill does
# Context Management Skill
## Purpose
This skill enables proactive management of Claude Code's context window through intelligent token monitoring, context extraction, and selective rehydration. Instead of reactive recovery after compaction, this skill helps users preserve essential context before hitting limits and restore it efficiently when needed.
**Version 3.0 Enhancements:**
- **Predictive Budget Monitoring**: Estimate when capacity thresholds will be reached
- **Context Health Indicators**: Visual indicators for statusline integration
- **Priority-Based Retention**: Keep requirements and decisions, archive verbose logs
- **Burn Rate Tracking**: Monitor token consumption velocity for early warnings
## When to Use This Skill
- **Token monitoring**: Check current usage and get recommendations
- **Approaching limits**: Create snapshots at 70-85% usage
- **After compaction**: Restore essential context without full conversation
- **Long sessions**: Preserve key decisions and state proactively
- **Complex tasks**: Keep requirements and progress accessible
- **Context switching**: Save state when pausing work
- **Team handoffs**: Package context for others to continue
- **Predictive planning**: Get early warnings before capacity is reached
- **Session health**: Monitor context health for sustained productivity
## Quick Start
### Check Token Status
```
User: Check my current token usage
```
I'll use the `context_manager` tool to check status:
```python
from context_manager import check_context_status
status = check_context_status(current_tokens=<current_count>)
# Returns: ContextStatus with usage percentage and recommendations
```
### Create a Snapshot
```
User: Create a context snapshot named "auth-implementation"
```
I'll use the `context_manager` tool to create a snapshot:
```python
from context_manager import create_context_snapshot
snapshot = create_context_snapshot(
conversation_data=<conversation_history>,
name="auth-implementation"
)
# Returns: ContextSnapshot with snapshot_id, file_path, and token_count
```
### Restore Context
```
User: Restore context from snapshot <snapshot_id> at essential level
```
I'll use the `context_manager` tool to rehydrate:
```python
from context_manager import rehydrate_from_snapshot
context = rehydrate_from_snapshot(
snapshot_id="20251116_143522",
level="essential" # or "standard" or "comprehensive"
)
# Returns: Formatted context text ready to process
```
### List Snapshots
```
User: List my context snapshots
```
I'll use the `context_manager` tool to list snapshots:
```python
from context_manager import list_context_snapshots
snapshots = list_context_snapshots()
# Returns: List of snapshot metadata dicts
```
## Detail Levels
When rehydrating context, choose the appropriate detail level:
- **Essential** (smallest): Requirements + current state only (~250 tokens)
- **Standard** (balanced): + key decisions + open items (~800 tokens)
- **Comprehensive** (complete): + full decisions + tools used + metadata (~1,250 tokens)
Start with essential and upgrade if more context is needed.
## Actions
### Action: `status`
Check current token usage and get recommendations.
**Usage:**
```python
from context_manager import check_context_status
status = check_context_status(current_tokens=750000)
print(f"Usage: {status.percentage}%")
print(f"Status: {status.threshold_status}")
print(f"Recommendation: {status.recommendation}")
```
**Returns:**
- `ContextStatus` object with usage details
- `threshold_status`: 'ok', 'consider', 'recommended', or 'urgent'
- `recommendation`: Human-readable action suggestion
### Action: `snapshot`
Create intelligent context snapshot.
**Usage:**
```python
from context_manager import create_context_snapshot
snapshot = create_context_snapshot(
conversation_data=messages,
name="feature-name" # Optional
)
print(f"Snapshot ID: {snapshot.snapshot_id}")
print(f"Token count: {snapshot.token_count}")
print(f"Saved to: {snapshot.file_path}")
```
**Returns:**
- `ContextSnapshot` object with metadata
- Snapshot saved to `~/.amplihack/.claude/runtime/context-snapshots/`
### Action: `rehydrate`
Restore context from snapshot at specified detail level.
**Usage:**
```python
from context_manager import rehydrate_from_snapshot
context = rehydrate_from_snapshot(
snapshot_id="20251116_143522",
level="standard" # essential, standard, or comprehensive
)
print(context) # Display restored context
```
**Returns:**
- Formatted markdown text with restored context
- Ready to process and continue work
### Action: `list`
List all available context snapshots.
**Usage:**
```python
from context_manager import list_context_snapshots
snapshots = list_context_snapshots()
for snapshot in snapshots:
print(f"{snapshot['id']}: {snapshot['name']} ({snapshot['size']})")
```
**Returns:**
- List of snapshot metadata dicts
- Includes: id, name, timestamp, size, token_count
## Proactive Features (v3.0)
### Predictive Budget Monitoring
Instead of just checking current usage, predict when thresholds will be reached:
```python
# The system tracks token burn rate over time
# When checking status, you get predictive insights
status = check_context_status(current_tokens=500000)
# Status includes predictions (when automation is running):
# - Estimated tool uses until 70% threshold
# - Time estimate based on current burn rate
# - Early warning before you hit capacity
# Example output interpretation:
# "At current rate, you'll hit 70% in ~15 tool uses"
# "Consider creating a checkpoint before your next major operation"
```
**How Prediction Works:**
The automation tracks:
1. Token count at each check interval
2. Number of tool uses between checks
3. Average tokens consumed per tool use
4. Time elapsed between checks
From this data, it estimates:
- Tools remaining until threshold
- Approximate time until threshold
- Whether current task will complete before limit
### Context Health Indicators
Visual indicators for session health, suitable for statusline integration:
| Indicator | Meaning | Usage % | Recommended Action |
| ---------------- | -------- | ------- | -------------------- |
| `[CTX:OK]` | Healthy | 0-30% | Continue normally |
| `[CTX:WATCH]` | Monitor | 30-50% | Plan checkpoint |
| `[CTX:WARN]` | Warning | 50-70% | Create snapshot soon |
| `[CTX:CRITICAL]` | Critical | 70%+ | Snapshot immediately |
**Statusline Integration Example:**
```bash
# In your statusline script, check context health:
# The automation state file contains health status
# Example statusline addition:
if [ -f ".claude/runtime/context-automation-state.json" ]; then
LAST_PCT=$(jq -r '.last_percentage // 0' .claude/runtime/context-automation-state.json)
if [ "$LAST_PCT" -lt 30 ]; then
echo "[CTX:OK]"
elif [ "$LAST_PCT" -lt 50 ]; then
echo "[CTX:WATCH]"
elif [ "$LAST_PCT" -lt 70 ]; then
echo "[CTX:WARN]"
else
echo "[CTX:CRITICAL]"
fi
fi
```
### Priority-Based Context Retention
When creating snapshots, the system prioritizes content by importance:
**High Priority (Always Retained):**
- Original user requirements (first user message)
- Key architectural decisions
- Current implementation state
- Open items and blockers
**Medium Priority (Retained in Standard+):**
- Tool usage history
- Decision rationales
- Questions and clarifications
**Low Priority (Only in Comprehensive):**
- Verbose output logs
- Intermediate steps
- Debugging information
**Usage Pattern:**
```python
# Create snapshot with priority awareness
snapshot = create_context_snapshot(
conversation_data=messages,
name='feature-checkpoint'
)
# Essential level (~200 tokens): Only high priority content
# Standard level (~800 tokens): High + medium priority
# Comprehensive level (~1250 tokens): Everything
# Start minimal, upgrade as needed:
context = rehydrate_from_snapshot(snapshot_id, level='eRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.