Warn on Unusually Frequent Context Compaction
Compaction is a cost signal, not just a context-management one — a session compacting repeatedly in a short window usually means something is causing runaway context growth (a tool returning far more than needed, a loop re-reading the same large file). This flags the pattern rather than just letting each compaction pass silently.
1. Save this as the hook script
#!/usr/bin/env python3
"""PreCompact hook — warns if compaction is firing more than N times in
the last hour."""
import json, sys, time
from pathlib import Path
data = json.load(sys.stdin)
HOURLY_LIMIT = 4
state_path = Path(data.get("cwd", ".")) / ".claude" / "compaction_times.txt"
now = time.time()
times = []
if state_path.exists():
times = [float(t) for t in state_path.read_text().splitlines() if t.strip()]
times = [t for t in times if now - t < 3600]
times.append(now)
state_path.parent.mkdir(parents=True, exist_ok=True)
state_path.write_text("\n".join(str(t) for t in times))
if len(times) > HOURLY_LIMIT:
print(f"WARNING: {len(times)} compactions in the last hour, above the "
f"{HOURLY_LIMIT}/hr threshold — likely runaway context growth.", file=sys.stderr)
sys.exit(1)
sys.exit(0)
Save to a path inside your project, e.g. .claude/hooks/warn-frequent-compaction.sh, then chmod +x it.
2. Wire it into .claude/settings.json
{
"hooks": {
"PreCompact": [
{
"hooks": [
{"type": "command", "command": "python3 .claude/hooks/warn-frequent-compaction.py"}
]
}
]
}
}
Before you use this
A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.
Related hooks