A Claude Code plugin that lets Claude compact its own context at task milestones: agent-initiated /compact with self-written instructions, then auto-continue.
Quick start · When it compacts · Cost model · Docs · English | 简体中文
self-compact gives Claude a compact_now tool. When Claude finishes a unit of work (a spec is written, a merge request is up, a task is handed to a background agent), it can request a compaction and write the handoff itself: your standing orders in your own words, the decisions and their reasons, what is still pending, and the first step after compaction. The plugin enforces the context thresholds (the break-even floor) and runs the compaction after the turn ends; once past them, Claude decides whether compacting is worth it. After compaction it sends a continuation prompt so work picks up without you typing anything.
Long sessions compact whether or not you plan for it. Auto-compact fires at an arbitrary moment, often mid-task, and the summarizer has to guess which parts of the conversation matter. A manual /compact with your own instructions works better, but only when you are there to pick the moment and write them.
This plugin moves that judgment to Claude, which knows where the task stands. It addresses two open feature requests: anthropics/claude-code#19877 and #96713 (let the model trigger compaction itself, at a good moment, instead of auto-compact firing at a random one).
The node and anti-node lists below were drawn from 214 manual compactions in the author's own history. Median context before compaction was 318k tokens on a 1M window, and about a third happened at 32-72% of the window in the middle of a task.
- Claude judges it is at a node and calls
mcp__self-compact__compact_now(handoff). - The gate checks context size. Too small: the call is denied with the current percentage and the floor. Otherwise the plugin writes
handoff-<n>.md, queues the request and returns "scheduled". Claude ends the turn with one line. - After the main turn completes (not aborted), a 1.5 s debounce, then a re-check of usage and
$.session.compact({ instructions })with Claude's handoff as the instructions. A skip or error retries every 2 s up to 5 times, then once more at the next turn end, then gives up with a toast and a note to Claude. - On success the plugin shows a toast (
A% -> B%), logs the run and submits a continuation prompt: node, before and after, handoff path,next, standing orders and pending items verbatim.
Races are handled: a new prompt from you wins (compaction still runs, next is dropped), auto-compact running first drops the request, Esc drops it, and a handoff that goes stale after more than 3 further tool calls is dropped with a note to Claude. Details in docs/en/DESIGN.md.
- Claude Code 2.1.287 or later (plugin mods are on by default from that version). Developed on 2.1.322.
- A 1M-token window is the target. See Limitations.
Inside Claude Code:
/plugin marketplace add w21180239/claude-code-self-compact
/plugin install self-compact@claude-code-self-compact
Or from a shell:
claude plugin marketplace add w21180239/claude-code-self-compact
claude plugin install self-compact@claude-code-self-compactRestart Claude Code or run /reload-plugins, then check it loaded. Ask Claude "what tools do you have for compaction?" and look for mcp__self-compact__compact_now. To test the gate early in a fresh session, ask Claude to call it: below the floor the call is denied with your current context percentage and the threshold.
After that there is nothing to run. Claude decides when to call the tool.
Two layers. The plugin enforces a floor. Claude decides everything above it, guided by the tool description and by nudges.
The plugin derives every threshold from P, the learned post-compact size (see the cost model). It refuses a call below the floor, max(C(floorCalls), floorPct x window), where C(floorCalls) is the size at which compacting pays back within 20 later calls. With P = 87k the floor is 147k; on a heavy setup it rises with P. Every tier is capped at the urgent size, min(urgentK x 1k, 80% of the auto-compact limit), so a small window still opens the tool. Every tier is then raised to at least P + 25k, so a compaction always frees 25k or more and the context cannot re-trip a tier right after it.
| Context | Behavior |
|---|---|
below the floor (C(20)) |
denied by the plugin |
floor to node (C(10)) |
big phase handoffs only (spec to plan, plan to implementation, MR up to review) |
node (C(10)) and up |
any clean node |
| node, then every 5% | nudge |
| urgent (350k or 80% of the auto-compact limit) and up | nudge wording escalates: compact at the next safe step |
Nudges ride on the next text tool result, or on the next prompt's context. They are silent while a request is queued or compacting, in subagents, in non-interactive sessions and when disabled.
Good nodes:
- A block of work ends (push or merge verified, tests green, PR opened or merged, message sent, todos complete), with no agents running.
- State was just written to disk (handoff file, memory, skill) and pushed.
- You change topic, or pick the work up again after a pause.
- A phase handoff: spec or plan written, next step named, merge request created.
- A subagent returned, or work was delegated and Claude is now waiting, with every running task and its reporting route listed in
pending. - Finished work is saved to disk and handed to you for review or sign-off (a rendered page, a draft file), with what you are asked to look at listed in
pending. - You say "compact", "continue" or "next".
Anti-nodes, where Claude is told not to compact:
- A question is waiting for your answer and that answer decides the next step, or an outgoing draft is waiting for you to say send.
- You just corrected something or gave a new rule or permission that is not yet in the handoff.
- Mid polling, retrying, editing or a debug loop.
- The API just returned an error, or Claude is waiting for you to log in or dismiss a dialog.
- A background agent's result arrived and has not been read.
The plugin checks one of these itself: if the last tool call was AskUserQuestion, the request is denied.
The tool description alone does not make Claude compact: in a live session it finished a phase and moved on. The plugin therefore adds three triggers, so you never have to mention compaction:
- Node flag. After a
git push,git merge, a PR/MR create, review or merge, agit tag, a message sent throughgog,agent-slackoroutlook, a spec/plan/handoff file write, or a todo list with every item completed, one line is attached to that tool result when the gate is open. Weaker signals (git commit, tests passed, a new.mdfile, a background agent launch, a subagent returning) are flagged only 5 points above the floor. At most one flag per turn. - Turn-end self-check. After a turn that ends, the plugin submits one short prompt when a node was flagged, when the turn did real work (two or more main-session tool calls) and the context is near the nudge start, or when the context passed the nudge start without a compaction. Passing the thresholds is only a necessary condition: Claude compacts only when the current block is closed, the next work does not depend on large raw text in the context, and enough work remains to repay a compaction; otherwise it answers
skip: <one-line reason>, which the log keeps asreasonon theself-check:declinedrow. A turn ending in a question still asks, because completion summaries often end that way; onlyAskUserQuestionsuppresses it. A check is limited to one per trigger per 5 points of growth and never repeats without new tool activity. - Block-start hint. On every human prompt once the gate is open, a model-only line suggests compacting first when the message opens a new block of work (a different topic, or picking work up after a pause) and the previous block is closed.
autoNodes turns all three off; turnEndCheck turns off only the self-check. Compaction always resumes work: the continuation prompt is sent after every successful compaction, except the one before an exit.
Compact on /exit. /exit (or /quit) says you mean to come back to this session, so when the context is past the break-even line the plugin holds the exit, asks Claude to call compact_now with a handoff for the resume (unfinished work in pending, next says how to pick up), and runs /exit once the compaction ends. If Claude skips (it may weigh an earlier "do not compact" above a plugin's request) or the call is denied, the plugin compacts anyway with generic resume instructions, since the /exit itself is yours. claude --resume then starts from the small summary. Closing the window or Ctrl+C/Ctrl+D exits at once, untouched. A second /exit while it waits leaves now; Esc or typing a message cancels the exit. A failed compaction still exits. Log rows: exit-check, then exit:compacting or exit:declined + exit:direct, exit:aborted, exit:cancelled, exit:forced, exit:failed, and exit. exitCompact turns it off.
compact_now takes a structured handoff: node, objective, standing_orders (your rules and permissions, in your words), decisions (with reasons), artifacts, pending (each running task and how it reports), done, next, language (see below), and optional drop and lessons (what failed and why), keep_skills and drop_skills (skill names, see below). A call missing a required field is denied and the field is named.
The plugin renders it to handoff-<n>.md, adds your original request (saved once per session, so it survives repeated compactions) and your last 5 real messages (commands, system reminders and task notifications are filtered out), and sends the result as the compact instructions. A preamble tells the summarizer to keep standing orders verbatim, list every pending item and end on next, to copy paths with line numbers, error strings, values and signatures exactly, and to drop stale logs, repeated reads and dead ends (keeping their lesson). Instructions are capped at 8,000 characters; done is trimmed first, then your oldest messages. standing_orders, pending, next, the language rules and the hot-skill line are never trimmed.
language carries your per-channel language rules: chat (the conversation language as you set it) and outputs (one rule per channel in your words, e.g. "code/commit/PR: English"). The field is required in the schema but a missing one never blocks a compaction. Per field, what the call gives wins, then the rules inherited from the previous compaction of this session, then (for chat only) the language detected from your last 5 real messages (Chinese when CJK characters are at least 30% of the non-space text, else English; the plugin's own prompts are ignored). The merged rules go first in handoff-<n>.md under "Language rules", the compact instructions tell the summarizer to write in the chat language and copy each rule verbatim as the summary's first section, and the first line of the continuation prompt is the rule line (Chat: Chinese | code/commit/PR: English | ...). For the first 3 real prompts after a compaction the plugin also appends that line to the prompt's context; plugin-submitted prompts and slash commands do not count. The rules are kept across compactions and dropped with the conversation.
Skill working set. After every compaction the engine re-injects the full body of each skill you invoked; mods cannot see or change that step (a managed login skips user mods' prompt.attachment and skill.prompt hooks), so the plugin leaves it alone. What a compaction loses is the skill's working set: the reference files read under the skill's dir (for example references/voice.md) and the step the work had reached. The plugin tracks, per skill loaded through the Skill tool in the main session, the last request that used it and the files it read under /skills/<name>/ (Read, Grep, Glob, Edit, Write, or a path in a Bash command; at most 8, newest first; SKILL.md is use, not a ref). Paths are normalized first (.., ., ~, relative paths; one that climbs out is ignored) and count only under a dir that holds a SKILL.md; when two loaded skills share a short name, the plugin segment in the path picks the owner, else the latest loaded. At compaction a skill is hot when it is in keep_skills, was used within the last hotWindow main requests, or its learned miss rate is at least 0.3 over 3 or more compactions; it is done when it is in drop_skills and not in keep_skills. The compact instructions then ask the summarizer to record, per hot skill, the step reached and what remains (a never-trimmed line). The resume message gets a "Skill working set" section after the language line and the next step: each hot skill as "still in use" with its refs, a ref of at most refInlineK thousand tokens inlined while the total stays within skillBudgetK, the rest listed by path to re-read when needed (an unreadable ref is listed too). A ref is sized with $.fs.stat before any read, so a larger file is never read; reading stops once the budget is spent, and a ref whose real path leaves the skill dir is listed, not read. The instruction line names at most 8 hot skills and counts the rest; each done skill gets one line saying it is finished and its re-injected instructions no longer apply. With no hot or done skill the section is omitted. Learning: a main-session Read of a listed ref within 30 requests after a compaction counts as a miss (skill-ref-miss) and raises the skill's refMisses in profile.json; a Read of an inlined ref only logs skill-ref-reread. Subagent calls are ignored throughout.
After compaction the same standing orders and pending items arrive again, verbatim, in the continuation prompt, so they do not depend on how the summarizer paraphrased them. Claude can also re-read the full handoff file, and the continuation tells it to grep the session transcript when it needs an exact detail from before compaction.
A compaction costs tokens and time: it generates a summary and re-caches what remains. It pays off when enough calls follow at the smaller size.
Assumptions: relative to the input price, cache read is 0.1x, 1-hour cache write 2x and output 5x. One compaction costs about F + 0.1 x C input-token equivalents, where F is compactCostK (default 105k, a conservative fixed estimate for generating the summary and re-caching) and 0.1 x C is the cache read of the context being compacted. Not compacting costs 0.1 x (C - P) more on every later call, where C is the current context and P is the post-compact size. Compacting at C pays back within N calls when N x 0.1 x (C - P) >= F + 0.1 x C, which gives C(N) = (10 x F + N x P) / (N - 1).
| P (post-compact size) | C(8) | C(10) | C(20) |
|---|---|---|---|
| 65k | 224k | 189k | 124k |
| 87k | 249k | 213k | 147k |
| 120k | 287k | 250k | 182k |
Where P comes from: the first main step after each compaction is a real measurement of the post-compact size, stored in ~/.claude/self-compact/profile.json as an exponentially weighted average (alpha 0.3) per project and globally. A sample more than 50% away from the average is an outlier and moves it less (alpha 0.1); three outliers in a row in the same direction reset the average to their mean. An estimate is trusted from 3 samples. Until then P falls back in order to this session's sample, the project's estimate, the global estimate, then the session baseline plus 25k (the baseline is 65k when unknown, so P = 90k). afterPct in log.jsonl is the size the compaction reported, which is the summary; pSample is the measured size of the first real request after it.
A heavy harness (large MCP or skill definitions) has a large P and compaction pays little. When C(workCalls) reaches urgentK, the plugin tells Claude once per session that the harness is heavy and suggests trimming MCP servers or skills. A compaction takes 30-55 seconds. These numbers are estimates; log.jsonl records the sizes so you can check them on your own sessions.
Set the options through the plugin settings (userConfig in plugin.json), for example with claude plugin configure self-compact.
| Option | Default | Meaning |
|---|---|---|
language |
en | en or zh: language of the tool description, denials, toasts, nudges and continuation prompt; any other value falls back to en |
floorPct |
0 | extra floor as a percent of the window; the floor is the larger of this and the floorCalls size |
floorCalls |
20 | floor = the context where compacting pays back within this many later calls (see cost model); at least 2 |
nodeCalls |
10 | node tier: any clean node is allowed from the size that pays back within this many calls |
workCalls |
8 | work tier: the turn-end self-check treats a work block as a node from this payback size |
urgentK |
350 | urgent tier in thousand tokens, capped at 80% of the auto-compact limit (autoCompactWindow, else the model window); every other tier is clamped to it (minimum 50), then raised to at least P + 25k |
compactCostK |
105 | fixed cost of one compaction in thousand tokens (summary plus re-caching); minimum 1 |
nudgeStepPct |
5 | gap between nudges |
hotWindow |
20 | a skill used within this many main requests is hot at compaction (minimum 1) |
refInlineK |
2 | a skill reference of at most this many thousand tokens (4 characters per token) is inlined into the resume message; 0 lists every ref by path |
skillBudgetK |
6 | total thousand tokens of inlined skill references per compaction; 0 inlines nothing |
releaseStopHooks |
false | true: a queued compaction ends a turn that another Stop hook (such as /goal) holds open. Only works on personal (non-managed) setups; the built-in guard skips user mods' Stop hooks elsewhere (see FAQ) |
autoNodes |
true | Autonomous triggers: a one-line flag after node-like tool calls (push, merge, PR, tests green, message sent, spec/plan written, todos done), a turn-end self-check, and a hint on every human prompt once the gate is open. false turns all three off |
turnEndCheck |
true | The turn-end self-check only (needs autoNodes): after a node, a turn that did real work, or a long uncompacted stretch, one extra turn asks Claude whether to compact |
exitCompact |
true | Compact on /exit: past the break-even line, Claude writes a handoff and compacts, then the session exits, so a later resume starts small. Closing the window or Ctrl+C exits as usual |
enabled |
true | false: the tool stays registered, every call is denied, no nudges |
The older minSavingK, nudgeStartPct and urgentPct are still accepted but ignored; the plugin writes one log line at session start when it sees them. Remove them from your settings.
DISABLE_COMPACT=1 in the environment also denies every call. Handoff content (your standing orders, decisions) stays in whatever language you used; language only changes the plugin's own text.
Everything lives under ~/.claude/self-compact/, never inside a repository:
<session-id>/handoff-<n>.md: the rendered handoff plus your original request and last 5 real messages.<session-id>/intent.md: your first message in the session, capped at 1,500 characters.profile.json: the learned post-compact size P and, per skill,skills: { <name>: { compactions, refMisses } }; P is kept per project (keyed by the absolute cwd path) and globally, each with a sample count.log.jsonl(rotated tolog.1.jsonlat about 2 MB; an unreadable log is left untouched, never overwritten): one JSON line per request withts,session,node,pct(usage at request),result(queued,denied:<why>,done,preempted,aborted,stale,failed,error,p-sample,deprecated,tool-describe,lang-drift,skill-ref-miss,skill-ref-reread), an optionalreason,langSource(where the chat language came from:tool,inherited,detectedornone; onqueuedanddone),expectedandgot(onlang-drift: the chat language class and the first assistant reply's),beforePct,afterPct,durationMs,pSample(measured post-compact size) andp(the P in use).doneandpreemptedrows may carryskills({ hot, done, inlinedK, listed }: the hot and done skill names, thousand tokens inlined, number of refs listed by path);skill-ref-missandskill-ref-rereadcarryskillandpath.
Nothing leaves your machine. The plugin makes no network calls and has no dependencies. The compaction itself is Claude Code's own $.session.compact, so the summary is produced by the same model and account as the rest of your session. Handoff files contain your own words from the conversation; delete the folder whenever you like.
- Built for 1M-token windows. The post-compact ratio rule puts the floor at about 77% of a 200k window, so on small windows the tool is effectively closed and auto-compact does the work.
- With a large post-compact size on a small window, tiers can exceed 80% of the window (every tier stays at least P + 25k so a compaction always frees something); the engine's auto-compaction may then fire first.
- Main session only. Subagents are denied; keep them short and split them when they grow.
- Interactive sessions only.
claude -p, SDK and cron sessions are denied and get no nudges. - No typing detection. Mods cannot see your draft or keystrokes, so the plugin runs only when no turn is active, waits 1.5 s after the turn ends, and the continuation prompt waits for idle. A compaction can still land while you are about to type.
/goal-style Stop hooks can hold a queued compaction until the next natural turn end unlessreleaseStopHooksis on (personal setups only).- Compaction uses the native summarizer and takes 30-55 seconds.
| self-compact | Native auto-compact | /compact by hand |
fast-jev-compaction | planning-with-files | Handoff skills | |
|---|---|---|---|---|---|---|
| Who picks the moment | Claude, at a node, above a floor | Claude Code, near the window limit | You | Whatever triggers compaction | n/a (re-injects after compaction) | You or Claude, by convention |
| Who writes the instructions | Claude, structured handoff | None (default prompt) | You | None; replaces the summary | n/a | Claude, free-form file |
| Continues by itself | Yes, continuation prompt | Native behavior | No | Native behavior | Re-reads plan files | Usually a manual new session |
| Needs an API key or network | No | No | No | Yes, an external scoring model | No | No |
| Enforced size gate | Yes | n/a | No | n/a | n/a | No |
How the others work, briefly. Native auto-compact summarizes when the window nears its limit. /compact runs the summarizer once with the instructions you give it. fast-jev-compaction replaces the compaction summary with the original messages minus tool calls and results that an external model scores as no longer needed. planning-with-files keeps plans and progress in files and re-injects them so context loss after compaction or /clear hurts less. Handoff skills write a summary file you can start a fresh session from. These approaches mostly address different parts of the problem and can be combined: for example, self-compact chooses when, and a plan file keeps long-lived state.
Claude says it has no compaction tool. Restart Claude Code or run /reload-plugins, then run /plugin and check that self-compact is enabled. Check claude --version is 2.1.287 or later. Ask "what tools do you have for compaction?" and look for mcp__self-compact__compact_now.
Every call is denied. Read the denial text, which names the reason. Common ones: context below the threshold (the message shows your percentage and the threshold; on a 200k window the threshold is about 77%), a subagent or non-interactive session, the plugin disabled (enabled is false or DISABLE_COMPACT=1), or the last tool call was AskUserQuestion.
Claude called it and nothing compacted. Look at the last lines of ~/.claude/self-compact/log.jsonl (see below) and read the result field. preempted means auto-compact ran first, aborted means you pressed Esc, stale means Claude made more than 3 further tool calls after queueing, failed means the compaction was skipped or errored through all retries.
It compacted at a bad moment. Raise floorPct, or open an issue with the log.jsonl line and what Claude was doing; the node and anti-node lists are tuned from reports like that.
How do I read log.jsonl? One JSON object per line. For example:
tail -n 5 ~/.claude/self-compact/log.jsonl
jq -c 'select(.result == "done")' ~/.claude/self-compact/log.jsonlCompare beforePct and afterPct with the cost model to see whether your floor is right.
Every turn ends with "self-compact: its classic.Stop hook was skipped". Where Claude Code's built-in guard sec-default@builtin (shown as cc-plugin-sec-default) loads, hooks a user's mod registers on classic.<Event> never run, and Claude Code warns at each turn end. The guard loads on any Team/Enterprise /login session and on machines with managed settings, and users cannot turn it off (admin docs). releaseStopHooks is off by default for this reason; the option only helps on personal (non-managed) setups, and leaving it off removes the warning.
I want it off. Set enabled to false, or export DISABLE_COMPACT=1. Auto-compact and /compact are unaffected.
claude plugin uninstall self-compact@claude-code-self-compact
claude plugin marketplace remove claude-code-self-compactThe plugin changes no settings files. To delete its data, remove ~/.claude/self-compact/.
The plugin lives in plugins/self-compact/ (hooks/register.ts, tests/self-compact.test.ts). With the claude CLI installed:
claude plugin validate .
claude plugin validate plugins/self-compact
claude plugin test plugins/self-compactCI runs the same commands on Ubuntu and macOS. See CONTRIBUTING.md and AGENTS.md. Design notes: docs/en/DESIGN.md. Changes: docs/en/CHANGELOG.md.
Dual-licensed under MIT or Apache-2.0, at your option.