Context management

From rysweet/amplihack · View interactive version

Context management is an AI agent skill from the GitHub repository rysweet/amplihack. Proactive context window management via token monitoring, intelligent extraction, and selective rehydration. Use when approaching token limits or needing to preserve essential context. Complements /transcripts and PreCompact hook with proactive optimization.

How to use this skill

Skill file

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.

When to Use This Skill

Quick Start

Check Token Status

User: Check my current token usage

I'll use the context_manager tool to check status:

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:

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:

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:

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:

Start with essential and upgrade if more context is needed.

Actions

Action: `status`

Check current token usage and get recommendations.

Usage:

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:

Action: `snapshot`

Create intelligent context snapshot.

Usage:

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:

Action: `rehydrate`

Restore context from snapshot at specified detail level.

Usage:

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:

Action: `list`

List all available context snapshots.

Usage:

from context_manager import list_context_snapshots

snapshots = list_context_snapshots()
for snapshot in snapshots:
    print(f"{snapshot['id']}: {snapshot['name']} ({snapshot['size']})")

Returns:

Proactive Usage Workflow

Step 1: Monitor Token Usage

Periodically check status during long sessions:

status = check_context_status(current_tokens=current)

if status.threshold_status == 'consider':
    # Usage at 70%+ - consider creating snapshot
    print("Consider creating a snapshot soon")
elif status.threshold_status == 'recommended':
    # Usage at 85%+ - snapshot recommended
    create_context_snapshot(messages, name='current-work')
elif status.threshold_status == 'urgent':
    # Usage at 95%+ - create snapshot immediately
    create_context_snapshot(messages, name='urgent-backup')

Step 2: Create Snapshot at Threshold

When 70-85% threshold reached, create a named snapshot:

snapshot = create_context_snapshot(
    conversation_data=messages,
    name='descriptive-name'
)
# Save snapshot ID for later rehydration

Step 3: Continue Working

After snapshot creation:

Step 4: Rehydrate After Compaction

After compaction, restore essential context:

# Start minimal
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='essential'
)

# If more context needed, upgrade to standard
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='standard'
)

# For complete context, use comprehensive
context = rehydrate_from_snapshot(
    snapshot_id='20251116_143522',
    level='comprehensive'
)

Integration with Existing Systems

vs. PreCompact Hook

PreCompact Hook (automatic safety net):

Context Skill (proactive optimization):

Relationship: Complementary, not competing. Hook = safety net, Skill = optimization.

vs. /transcripts Command

/transcripts (reactive restoration):

Context Skill (proactive preservation):

Relationship: Transcripts for full recovery, skill for efficient management.

Storage Locations

Automatic Management

Context management runs automatically via the post_tool_use hook:

This happens transparently without user intervention.

Implementation

All context management functionality is provided by:

See tool documentation for complete API reference and implementation details.

Common Patterns

Pattern 1: Preventive Snapshotting

Check before long operation and create snapshot if needed:

status = check_context_status(current_tokens=current)
if status.threshold_status in ['recommended', 'urgent']:
    create_context_snapshot(messages, name='before-refactoring')

Pattern 2: Context Switching

Save state when pausing work on one feature to start another:

# Pausing work on Feature A
create_context_snapshot(messages, name='feature-a-paused')

# [... work on Feature B ...]

# Resume Feature A later
context = rehydrate_from_snapshot('feature-a-snapshot-id', level='standard')

Pattern 3: Team Handoff

Create comprehensive snapshot for teammate:

snapshot = create_context_snapshot(
    messages,
    name='handoff-to-alice-api-work'
)
# Share snapshot ID with teammate
# Alice can rehydrate and continue work

Philosophy Alignment

Ruthless Simplicity

Single Responsibility

Zero-BS Implementation

Trust in Emergence

Tips for Effective Context Management

  1. Monitor regularly: Check status at natural breakpoints
  2. Snapshot strategically: At 70-85% or before long operations
  3. Start minimal: Use essential level first, upgrade if needed
  4. Name descriptively: Use clear snapshot names for later reference
  5. List periodically: Review and clean old snapshots
  6. Combine tools: Use with /transcripts for full recovery option
  7. Trust emergence: Don't over-snapshot, let context flow naturally

Resources

Remember

This skill provides proactive context management through a clean, reusable tool. The tool can be called from skills, commands, and hooks. It complements existing tools (PreCompact hook, /transcripts) rather than replacing them. Use it to maintain clean, efficient context throughout long sessions.

Key Takeaway: Business logic lives in context_manager.py, this skill just tells you how to use it.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.