Feature: configurable auto-compaction threshold

Status Closed — not planned
Maintainer reply None cached
Activity 13 comments · opened Mar 16, 2026 · closed Jun 25, 2026

Feature request

Allow users to configure the context window percentage at which auto-compaction triggers, via a setting in settings.json (user or project level).

{
  "autoCompactionThreshold": 80
}

If not specified, the current default behavior applies.

Motivation

With the statusLine feature, users can now monitor context window usage in real time. However, there's no way to control when auto-compaction fires. In my experience, compaction triggered at ~76% used (24% remaining) — well before the context window was exhausted.

For long-running sessions with heavy context (architecture decisions, multi-file reviews), earlier compaction discards useful context prematurely. For other workflows, later compaction might risk losing important state.

A configurable threshold would let users tune the trade-off between context preservation and safety margin based on their workflow.

Proposed behavior

  • New optional setting: autoCompactionThreshold (integer, 1–99, percentage of context used)
  • When context usage reaches the threshold, auto-compaction fires as it does today
  • If omitted, current default behavior is unchanged
  • Could be set at user level (~/.claude/settings.json) or project level (.claude/settings.json)

View original on GitHub ↗

12 Comments

yurukusa · 5 months ago

+1 on this. I've been running Claude Code autonomously for 140+ hours and context management is critical.

As a workaround until this is natively supported, you can build this with a PostToolUse hook that monitors context usage after every tool call:

#!/bin/bash
# context-monitor.sh — warn when context window is running low
# Add to settings.json as a PostToolUse hook

THRESHOLD_WARN=20   # warn at 20% remaining
THRESHOLD_CRITICAL=5 # critical at 5% remaining

# Parse context info from hook input (stdin JSON)
remaining=$(cat /dev/stdin | python3 -c "
import json,sys
try:
    d=json.load(sys.stdin)
    # Access context percentage if available in hook payload
    print(d.get('context_remaining_percent', ''))
except: pass
" 2>/dev/null)

if [ -n "$remaining" ] && [ "$remaining" -le "$THRESHOLD_CRITICAL" ] 2>/dev/null; then
    echo '{"decision":"block","reason":"⚠️ CRITICAL: Context at '${remaining}'%. Run /compact immediately."}' 
elif [ -n "$remaining" ] && [ "$remaining" -le "$THRESHOLD_WARN" ] 2>/dev/null; then
    echo '{"decision":"warn","reason":"Context at '${remaining}'% remaining. Consider /compact soon."}' 
fi

This gives you configurable thresholds at the userland level. I run a similar hook (context-monitor) that has saved me from losing work multiple times when context was about to hit the wall.

That said, a native autoCompactionThreshold setting would be much cleaner — the hook approach can only warn or block, not actually control when compaction fires.

AbdoKnbGit · 5 months ago

cc-memory addresses this with a different approach that's already working.

Instead of improving compaction, it moves context outside the window entirely:

  • Full conversation turns stored in SQLite + ChromaDB (not summarized,

just moved out)

  • Semantic retrieval injects only relevant prior context back when needed
  • Tiered injection: pinned decisions always included, past context

scored by relevance

  • Cerebras compresses history for free before hitting Anthropic —

no token cost from your subscription

  • Smart compaction with adaptive threshold — the proxy monitors context

density and only triggers compaction when the window crosses a dynamic
threshold. The threshold itself adjusts based on content type:
decision-heavy turns raise it, tool output-heavy turns lower it.
Compaction never fires blindly at a fixed percentage

  • Density check before compaction — if the context is thin or mostly

recoverable content, compaction is skipped entirely

  • Tool result summarization — bulky file reads and command outputs get

summarized before they bloat the window, recoverable content evicted first

  • Second dedup pass after compression — if two turns converge after

cleaning, the duplicate never hits the API

The result: Claude remembers schema decisions, variable names,
architectural rationale across sessions — not just within one session.
Compaction becomes a last resort, not a constant interruption.

Working implementation if you want to try it today:
https://github.com.AbdoKnbGit/claude-code-memory

iuriguilherme · 5 months ago

settings.json should use the same syntax as the API already uses:

````json
{
"context_management": {
"edits": [
{
"type": "compact_20260112",
"trigger": {
"type": "input_tokens",
"value": 150000
},
}
]
}
}

````

iuriguilherme · 5 months ago

Previously closed issue with the same feature request: #10948

joelpoloney · 5 months ago

+1 on this. I got to 250k context usage and queries were so slow, Claude Code became unusable until I compacted manually. Would be great to have the auto-compact feature back at a configurable threshold

junaidtitan · 5 months ago

We wanted this exact feature and ended up building it ourselves — so we open-sourced it: Cozempic.

The guard daemon monitors your session and triggers pruning at a configurable threshold before compaction gets a chance to fire:

cozempic guard --threshold 50    # prune at 50% context (hard)
                                  # soft prune at 30% (no reload)

It's tiered — a gentle prune runs at 30% with no reload, a full prune runs at 50% with optional auto-reload into a clean session. Team state (TaskCreate, SendMessage, subagents) is always protected.

pip install cozempic

Would love feedback on whether the threshold controls map to what you're looking for here.

yurukusa · 5 months ago

A PostToolUse hook can implement configurable auto-compaction:

COUNTER="/tmp/.cc-tool-count-$$"
COUNT=$(($(cat "$COUNTER" 2>/dev/null || echo 0) + 1))
echo "$COUNT" > "$COUNTER"
THRESHOLD=${CC_COMPACT_THRESHOLD:-300}
if [ "$COUNT" -eq "$THRESHOLD" ]; then
    echo '{"hookSpecificOutput":{"additionalContext":"Context threshold reached ('"$COUNT"' tool calls). Consider running /compact to free context space."}}'
fi
if [ "$COUNT" -eq $((THRESHOLD + 50)) ]; then
    echo '{"hookSpecificOutput":{"additionalContext":"⚠ Context critically full ('"$COUNT"' calls). Run /compact NOW or start a new session."}}'
fi
exit 0
{
  "hooks": {
    "PostToolUse": [{"hooks": [{"type": "command", "command": "bash ~/.claude/hooks/auto-compact.sh"}]}],
    "Notification": [{"matcher": "start", "hooks": [{"type": "command", "command": "echo 0 > /tmp/.cc-tool-count-$$"}]}]
  }
}

Set CC_COMPACT_THRESHOLD=200 to compact earlier, or 500 for longer sessions. The hook warns at the threshold and urgently at threshold+50.

junaidtitan · 5 months ago

The tool-count approach is a useful signal but has a blind spot: a single Read of a large file can consume more context than 200 lightweight tool calls, so the threshold fires at the wrong time in file-heavy sessions. Cozempic's guard monitors actual token estimates from the JSONL tail rather than call count, which catches those asymmetric cases.

The other difference is what happens at threshold — the hook warns and asks Claude to /compact, but Cozempic prunes the JSONL directly before compaction fires: stripping progress bars, tool output noise, stale reads, and thinking blocks while protecting team state. The session stays lean enough that compaction either doesn't fire or lands on a much smaller file.

Both approaches are useful — the hook pattern @yurukusa described is a good lightweight complement for sessions where you don't want to install anything. pip install cozempic && cozempic guard if you want the token-aware version with active pruning.

blwfish · 4 months ago

This is crucial. The threshold miscalculations in #42375 and #50888 show why this isn't optional — compaction currently fires at unpredictable (and wrong) points.

More importantly: this area is only getting more complex. As context windows grow, compaction strategies evolve, and automation (agents, long-running tasks) become more prevalent, predicting optimal thresholds is increasingly hard. What works for a 200K window with human users won't work for 1M+ with machine workloads.

Being able to configure when/how compaction happens isn't a nice-to-have — it's foundational for letting users adapt to changing constraints rather than fighting broken defaults.

Evil-Overlord-666 · 3 months ago

Give us a setting .... I'm fed to the back teeth with waiting for compaction every turn after 70% while trying to debug new work ..
The current arrangement effectively ends the session at around 70% for a project that has been running for more than a single session ..
Just give me a threshold setting.

itboat · 3 months ago

Context: I'm on the Max plan and have moved heavily into auto mode plus a custom cc-fresh launcher. My typical workload is 2–3 hour autonomous runs with multiple subagents, heavy testing, and a large, active context. At that scale, latency and "context rot" past ~250–300K tokens noticeably degrade quality — so I want compaction to fire early to keep the working context lean, not near-full.

The internal CLAUDE_AUTOCOMPACT_PCT_OVERRIDE doesn't reliably do this: on a 1M window the proactive compaction path is gated and never fires (consistent with #52390 and #53358), and there's no supported public setting for the threshold.

The broader ask — a complete, configurable context-management lifecycle exposed as hooks/settings, all tied to explicit context-usage percentages, so the whole cycle works natively with no shell workarounds:

  1. Compaction threshold — a real, honored setting for when auto-compaction triggers (percent or tokens), regardless of model/window size.
  2. Pre-compaction checkpoint — a separate, earlier threshold (e.g. 3–5% before the compaction threshold, configurable) that fires a pre-compaction hook, with a guarantee the hook fully completes before compaction proceeds (snapshot a plan, mark what to preserve). Today PreCompact isn't tied to a configurable percentage, and there's no assurance the checkpoint finishes before the context is compacted. Tie both events to explicit percentages so the checkpoint reliably lands first, then compaction runs right after it.
  3. Post-compaction resume — reliable, configurable auto-resume so work continues from the summary. Today this only happens implicitly for auto-compaction and isn't controllable; manual /compact never resumes.
  4. Notification — an event when compaction happens, so external tooling can react.

The primitive already exists at the API layer (context_management / compact_* triggers); the request is to surface it in Claude Code as a configurable, hookable chain. Long-session users are currently forced to build fragile shell/hook crutches around behavior we can't control. +1

github-actions[bot] · 2 months ago

Closing for now — inactive for too long. Please open a new issue if this is still relevant.

Showing cached comments. Read the full discussion on GitHub ↗