Claude Code port of the idea behind alshahia/dsh-autocompact. A Claude Code plugin can't replace the compaction engine, so this wraps it with hooks:
| Piece | What it does |
|---|---|
PreCompact hook |
Writes the full verbatim conversation (tool input/output untruncated) to <project>/.claude/handoffs/<session>/<ts>-conversation.md + index.md, then prints instructions that steer Claude Code's own summary (keep paths/commands/errors verbatim, decisions + reasons, verified vs not, side effects, next step; carry brief.md in; any /compact <text> comes first). Archive is hidden via .git/info/exclude, files are owner-only. |
PostCompact hook |
Saves the summary Claude Code produced to <ts>-summary.md / latest-summary.md, so it can be checked against the archive. |
SessionStart (compact) |
Tells the model where the archive is and to use recall (lean); also injects the brief (full). |
SessionStart (startup/clear/compact) |
Injects confirmed learned repo facts (see below). |
SessionStart (resume/fork) |
If the prompt cache expired and the context is over resumeNudgeTokens, says the next message re-caches the whole context (compacting would pay that too, plus the summary) and that /clear is cheapest for unrelated work. |
UserPromptSubmit hook |
Full mode: asks for brief.md at checkpointRatio, warns at warnRatio of the auto-compact window (read from Claude Code's autoCompactWindow unless contextWindow is set). Reads only the transcript's tail. |
PostToolUse / PostToolUseFailure |
Full mode: loop guard: when the same tool error repeats guard.repeats (3) times in a turn, or guard.consecutive (5) calls fail in a row, adds one redirect to the model (re-check assumptions, change approach or ask). At twice that, tells the user and asks the model to stop. Never blocks. Also collects learned facts. |
SessionEnd |
In every mode: appends the session's mode, compaction cost vs saving, plugin overhead and estimated billed cost (cache writes/reads priced separately, subagents rolled in, each API message counted once) to .claude/handoffs/ledger.jsonl. |
/auto-compact:autocompact |
Shows/tunes --mode, --rotate, --tokens (100k–1M or auto), --retain, --warn, --checkpoint, --steer; writes Claude Code's autoCompactWindow setting and migrates away from the old CLAUDE_CODE_AUTO_COMPACT_WINDOW env entry (which overrides /autocompact). |
/auto-compact:doctor |
Checks Node, window conflicts (env var, per-model /autocompact windows, plugin vs Claude Code), archive writability and recent hook errors. |
/auto-compact:status |
Cost by mode (per session, prompt, commit), cost of the current and past sessions, what each compaction cost and saved, plugin overhead, cache hit rate, per-compaction cost (re-caching after it, files re-read), loop-guard nudges, output shrinking, learned facts. |
/auto-compact:optimize |
Cheapest auto-compact window from this project's measured numbers (fixed base, growth per call, compaction cost). |
recall skill |
Ranked full-text search (BM25 over turn-sized chunks) across every archive, saved summary and brief of the project; --regex for exact patterns, --session to narrow. |
Config: ~/.claude/autocompact.json, overridden by <project>/.claude/autocompact.json.
All hooks skip subagents and fail open: errors go to ~/.claude/autocompact-errors.log, never to the session.
Install: claude --plugin-dir ./auto-compact, or add to a marketplace. Requires Node 18+.
Not ported: session_memory tool, Web UI panel, custom summarizer model, unused-tool pruning (Claude Code already defers most tools).
Every compaction costs money: the summary is written at the output price (the most expensive tokens), the summarizer reads the whole context, and the new prompt is written to the cache again. Not compacting costs money too: every API call reads the whole cached context. Extra features can add model output of their own (the checkpoint brief). So the plugin has modes, and measures each one.
| Mode | What runs | Extra model output |
|---|---|---|
lean (default) |
Only at the compaction wall: archive to disk, ask for a short summary (summaryTokens, 2500) because the archive keeps the rest, save the summary, inject a short pointer (about 160 tokens) to the archive and the recall skill. Resume hint. Cost ledger. |
none |
full |
Everything: checkpoint brief.md at 70%, warning at 85%, brief injected after compaction, detailed summary, loop guard, learned facts. |
the brief (~2k output tokens per cycle) |
off |
Claude Code alone. Only the cost ledger runs, as the baseline. | none |
Set one with /auto-compact:autocompact --mode lean|full|off. Keys you set explicitly (for example checkpointRatio or guard) override the mode. For a fair comparison, --rotate lean,full (or lean,full,off) gives each new session one of the listed modes, picked from its session id, so the same session always keeps its mode.
Each SessionEnd record in .claude/handoffs/ledger.jsonl holds the mode, the billed cost (cache writes and reads priced separately, subagents included), prompts and commits, the fixed base, every compaction's cost and saving, and the plugin's own overhead. /auto-compact:status shows:
- By mode: sessions, cost per session, per prompt and per commit, total compaction net and plugin overhead. Sessions differ, so compare after a few per mode.
- Per compaction: context before → after, cost (estimated summary output + summarizer input + measured re-caching), saving (each later call reads fewer cached tokens), the net, the number of calls it takes to pay off, files re-read, and calls per prompt before and after (more calls after can mean lost detail).
- Plugin overhead: tokens the hooks injected, by hook, and the output spent writing checkpoint briefs.
The size after compaction is measured, not assumed. Claude Code's own system prompt, tools, skills and CLAUDE.md are often 50–70k tokens and stay in every call, so a compaction from 200k usually lands near 100k, not 30k.
/auto-compact:optimize reads this project's recent transcripts and measures the fixed base, the size after compaction, the summary size, growth per API call, and what re-caching cost (5-minute or 1-hour TTL). It then prints the window-dependent cost per call for windows from just above the post-compaction size up to --max (1M), the cheapest window, and the range within 5% of it. The curve is usually flat near the minimum. Windows just above the post-compaction size compact very often, and very large windows pay to read a huge context on every call. Pass --max to stay under the model's context limit. Models with a long-prompt price tier (Haiku 5.5 above 100k) are priced per tier.
After a compaction only a ~2k-token brief is injected inline; everything else is read on demand.
File (in .claude/handoffs/<session>/) |
Purpose |
|---|---|
brief.md |
Written by the model at 70% of the window (checkpointRatio): verbatim user requests, decisions + reasons, verified vs unverified, files, side effects, next step. Used once, then renamed brief.prev.md. |
brief.auto.md |
Mechanical fallback built from the transcript: user messages, files edited/read, state-changing commands, last assistant message. |
latest-tail.md |
~5k-token digest (tailTokens): user + assistant text, tool output dropped. |
latest-tail-raw.md |
Full verbatim ~20k-token tail (retainTokens), on demand only. |
turns.md |
One line per turn, so recall is a grep, not a read. |
Config keys: contextWindow (null = Claude Code's window), tailTokens (5000), briefTokens (2000), checkpointRatio (0.70), warnRatio (0.85), steerSummary (true), resumeNudgeTokens (60000).
When a shell command fails and one of the next two shell commands succeeds with only a small change (at most 4 words differ, e.g. pytest -q → python -m pytest -q) and no file was edited in between, the pair is recorded in .claude/handoffs/facts.json. After it shows up in facts.sessions (2) separate sessions it is injected at session start. If the failing form later works, that counts against the fact; it is dropped once the counter-evidence matches the confirmations. Commands with side effects (push, install, rm, curl, deploy…) are never learned. No model calls are involved.
/auto-compact:status measures what matters: billed cost per session including the prompt cache, not raw tokens. Prices are list prices per model (scripts/cost.mjs); override or add models with "pricing": {"<model-id>": {"input": 4, "output": 20, "cacheRead": 0.2}} ($/MTok). Plugin events (nudges, facts, compactions) go to .claude/handoffs/events.jsonl. Everything under .claude/handoffs/ is excluded from git via .git/info/exclude.
Config keys: mode (lean), rotate ([]), summaryTokens (2500), inject, injectBrief, summaryStyle, resumeNudge, archive.enabled, guard ({enabled, repeats: 3, consecutive: 5, nudgesPerTurn: 1}), facts ({enabled, sessions: 2, max: 12}), ledger ({enabled}), pricing.
"shrink": {"enabled": true} shortens Bash output over minChars (12000) to about maxChars (6000) before the model sees it: repeated and near-identical lines (progress bars, PASSED lists) collapse, and the head, the tail and every error, failure, warning and stack-frame line (with context) are kept. The full output is saved to .claude/handoffs/<session>/outputs/ and the shortened version names the file. Output of commands that read content (cat, grep, git diff, ls…) or match shrink.skip (a regex) is never changed, nor is small stderr.
It is off by default because fewer tokens is not the same as lower cost: if the model has to read the full output back, or a cached prompt changes, the bill can go up. /auto-compact:status shows tokens saved next to how often the full output was read back. Compare cost per finished task with it on and off before keeping it.