Add ContextThreshold hook event for proactive memory management
Summary
PreCompact fires at compaction time — often too late to do anything meaningful. Users need a warning at a configurable threshold (e.g., 80%) so agents can proactively flush memory, wrap up tasks, or create handoff notes while there's still room in the context.
Proposing a new ContextThreshold hook event that fires once when context usage crosses a configurable percentage.
Related Issues
- #25689 — Context usage threshold hook event with plan-and-continue workflow
- #30590 — Context threshold hook / expose context usage to hooks
- #34340 — Expose context window usage to hooks via environment variable
- #34879 — Expose context window usage metrics to Claude for self-analysis
- #38523 — Add token_count and usage_percent to PreCompact hook input (companion proposal)
Also related to: "Inject context usage into system-reminder" (filing separately).
Proposed Configuration
{
"contextThreshold": 80,
"hooks": {
"ContextThreshold": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/context-threshold.sh"
}
]
}
]
}
}
Proposed Hook Input Schema
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/current/working/directory",
"hook_event_name": "ContextThreshold",
"token_count": 800000,
"context_window_size": 1000000,
"usage_percent": 80,
"threshold_percent": 80
}
Design Decisions
- Fire once per threshold crossing — not every turn after 80%. Reset on compaction (new effective session).
- Matcher on threshold_percent — allows different hooks for different thresholds. Could support multiple thresholds (70%, 80%, 90%) with separate handlers.
- Observe-only — cannot block, same as PreCompact. Injected context via stdout goes into the next turn.
- Configurable threshold —
contextThresholdsetting in settings.json, defaults to 80%.
Implementation Outline
From binary analysis of v2.1.81:
1. Add to hook event validator (CG$()):
Add "ContextThreshold" to the set of valid hook event names (alongside PreToolUse, PostToolUse, PreCompact, etc.)
2. Add Zod schema:
Following the pattern of existing hook schemas (hookEventName: h.literal("PreCompact"))
3. New hook executor function (following CGH() pattern):
async function contextThresholdHook(params, signal, timeoutMs = DP) {
let input = {
...g4(void 0),
hook_event_name: "ContextThreshold",
token_count: params.tokenCount,
context_window_size: params.contextWindowSize,
usage_percent: params.usagePercent,
threshold_percent: params.thresholdPercent
};
return await ub({ hookInput: input, matchQuery: String(params.thresholdPercent), signal, timeoutMs });
}
4. Add threshold check in main conversation loop (where auto-compact check already happens):
if (usagePercent >= threshold && !thresholdFiredThisSession) {
thresholdFiredThisSession = true;
await contextThresholdHook({ tokenCount, contextWindowSize, usagePercent, thresholdPercent: threshold }, abortSignal);
}
Complexity
Medium. Requires changes to:
- Hook event type registry (add "ContextThreshold")
- Hook schema definitions (add Zod schema)
- Main conversation loop (add threshold check)
- Session state (track whether threshold has fired)
- Configuration schema (add
contextThresholdsetting)
Use Case
With a ContextThreshold hook, agents can:
- Proactively flush important findings to memory files before compaction
- Create task handoff notes with remaining work
- Warn the user that context is getting full
- Trigger a
/memory-flushskill automatically - Save conversation state that would otherwise be lost
Current Workaround
There is no reliable workaround. PostToolUse hooks can check transcript file size as a rough proxy, but this is imprecise and doesn't correlate directly with token count. The context_window.used_percentage field in the statusline JSON is the closest available signal, but it's only accessible to the statusline script, not to hooks.
Community Demand
8+ existing issues requesting context threshold awareness, spanning multiple use cases (memory management, task planning, autonomous agents). This is the most-requested missing hook event.
---
Labels suggestion: enhancement, area:hooks
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗