Adds `/compact micro`: elides Read results and strips thinking, keeping the conversation structure

A Claude Mod that adds micro-compaction as /compact micro. Instead of asking a model to summarize your whole conversation, it trims the two bulkiest and cheapest-to-recover parts of the transcript and leaves everything else exactly as it was.
When you run /compact micro, the plugin rewrites the conversation transcript locally:
Read tool result is replaced with a short placeholder such as [file contents elided by compaction: <path>, N lines. Read it again if needed.] (or lines A-B for partial reads). Images and PDFs get one too ([image elided by compaction: <path>, WxH. …], [PDF elided …], [PDF pages elided …, pages N]), since their image and document blocks are usually the largest results in a conversation. Claude can read the file again on its own whenever it needs the contents.Some results are deliberately left alone: errored reads, text results already shorter than their placeholder ("unchanged since last read" stubs, tiny files), and earlier placeholders. Running /compact micro repeatedly is safe, because elision is idempotent.
/compact tiny does everything /compact micro does and also elides what Write and Edit calls carry: a Write call's content and an Edit call's old_string and new_string become placeholders such as [content elided by compaction: N lines. Read the file if needed.]. The file path and the other arguments stay. A payload already shorter than its placeholder is kept. For an elided call, the "file state is current in your context" note on its result is removed, since that no longer holds; Claude reads the file again before working on it. Use it when a session has written or rewritten a lot of code that is now on disk.
/compact micro or /compact tiny./compact, with or without instructions (/compact keep the plan), is passed through unchanged to Claude Code's normal model-written summary.Requires Claude Code v2.1.287 or later.
Install it from the official Anthropic plugin directory. In case you haven't added this marketplace yet, add it first, and refresh it to get the latest listing:
claude plugin marketplace add anthropic-plugin-directory
claude plugin marketplace update anthropic-plugin-directory
claude plugin install micro-compaction@anthropic-plugin-directory
If you prefer using the TUI, inside a session, use /plugin marketplace add, /plugin marketplace update and /plugin install with the same arguments.
To update to a newer release later:
claude plugin marketplace update anthropic-plugin-directory
claude plugin update micro-compaction@anthropic-plugin-directory
To try a local checkout while developing, load it directly instead:
claude --plugin-dir /path/to/micro-compaction
Then run /compact micro. Plain /compact keeps working as usual.
bashOutputMaxChars in your Claude Code config. Micro-compaction leaves Bash output alone, but long output is spilled to a file that Claude then reads with Read, and that read can be elided. The default threshold is 30000 characters; a lower one (for example 10000) spills more output to files, so more of it can be stripped./compact (the default) is a better fit, as is /clear. Micro-compaction keeps everything except file reads and thinking, so it can't discard irrelevant discussion.Read tool for file contents. Only Read results are elided. Output from cat in Bash, or from other tools such as MCP tools, web fetches and searches, is kept as is./compact for a summary, or rely on automatic compaction, which always uses the normal summary.The plugin registers exactly one hook, on the session.compact event, with the filter trigger: 'manual'. session.compact is also the name of the call that Claude Code makes to compact a conversation, so this hook sees the conversation's message list for every manual /compact. It changes the call only when the instructions are exactly micro or tiny (ignoring surrounding whitespace and case): then it returns a rewritten list (file reads elided, thinking dropped, and for tiny Write and Edit payloads elided) in place of core's model-written summary. For any other /compact, with or without instructions, it calls next with the call unchanged, so Claude Code compacts as usual. Other triggers (automatic, plugin, precompute) never reach the hook because of its trigger: 'manual' filter. The plugin never makes the session.compact call itself, and it hooks no other event.
session.compact hook, written in TypeScript (hooks/register.ts and hooks/elide.ts), inside Claude Code.tiny, Write and Edit payloads) and dropped thinking blocks.The core logic is the pure function microCompact(messages, { tiny }) in hooks/elide.ts, covered by unit tests in tests/elide.test.ts.
claude plugin validate .
claude plugin testhooks/register.ts 17 lines1import { microCompact } from './elide.ts'
2
3const MODES = ['micro', 'tiny'] as const
4
5export function register(on: any) {
6 // Only the person's `/compact micro` or `/compact tiny`; any other /compact (with or without
7 // instructions) and auto, plugin, precompute go to core's summary untouched
8 on('session.compact', { trigger: 'manual' }, async ($: any, e: any, next: any) => {
9 const mode = MODES.find(m => m === e.instructions?.trim().toLowerCase())
10 if (!mode) return next(e)
11 const { messages, stats } = microCompact(e.messages, { tiny: mode === 'tiny' })
12 const writes = mode === 'tiny' ? ` and ${stats.writesElided} write/edit payloads` : ''
13 $.ui.log(`Elided ${stats.elided} file reads${writes} with ${stats.chars} chars`)
14 return { messages }
15 })
16}
17hooks/elide.ts 176 lines1import type { SessionMessage as Msg } from 'claude-code'
2
3export type MicroCompactStats = {
4 elided: number
5 /** Characters of Read results and (tiny) Write/Edit payloads replaced by placeholders */
6 chars: number
7 thinkingDropped: number
8 /** Write and Edit payloads elided (tiny only), one per call however many fields */
9 writesElided: number
10}
11
12export type CompactOptions = {
13 /** Also elide what Write and Edit calls carry: `content`, `old_string`, `new_string` */
14 tiny?: boolean
15}
16
17const MARKER = ' elided by compaction: '
18const AGAIN = '. Read it again if needed.]'
19// Any of our placeholders, so a second pass leaves them be
20const PLACEHOLDER = /^\[[^\]\n]* elided by compaction: /
21
22// Read numbers its output as ` 12\tline`; the first and last numbers give the range read
23const LINE_NO = /^\s*(\d+)\t/
24
25const pathOf = (input: Record<string, unknown>) => (typeof input.file_path === 'string' ? input.file_path : 'unknown file')
26
27function describeText(input: Record<string, unknown>, text: string): string {
28 let first: number | null = null
29 let last: number | null = null
30 for (const line of text.split('\n')) {
31 const m = LINE_NO.exec(line)
32 if (!m) continue
33 const n = Number(m[1])
34 first ??= n
35 last = n
36 }
37 const range = first === null ? '' : first === 1 ? `, ${last} lines` : `, lines ${first}-${last}`
38 return `[file contents${MARKER}${pathOf(input)}${range}${AGAIN}`
39}
40
41/**
42 * The placeholder for a Read whose bulk is an image or document block rather than text
43 * (`result.type` image, pdf, or parts: PDF pages rendered as images), or null for any other.
44 * Their `text` is empty or a one-line note, so length says nothing about their size.
45 */
46function describeMedia(input: Record<string, unknown>, result: unknown): string | null {
47 if (!result || typeof result !== 'object') return null
48 const r = result as { type?: unknown; file?: any; firstPage?: unknown }
49 const path = pathOf(input)
50 switch (r.type) {
51 case 'image': {
52 const d = r.file?.dimensions
53 const size = d?.originalWidth && d?.originalHeight ? `, ${d.originalWidth}x${d.originalHeight}` : ''
54 return `[image${MARKER}${path}${size}${AGAIN}`
55 }
56 case 'pdf':
57 return `[PDF${MARKER}${path}${AGAIN}`
58 case 'parts': {
59 const first = typeof r.firstPage === 'number' ? r.firstPage : null
60 const count = typeof r.file?.count === 'number' ? r.file.count : null
61 const pages =
62 typeof input.pages === 'string' ? input.pages : first !== null && count !== null ? `${first}-${first + count - 1}` : null
63 return `[PDF pages${MARKER}${path}${pages ? `, pages ${pages}` : ''}${AGAIN}`
64 }
65 default:
66 return null
67 }
68}
69
70// The bulky fields of each call that tiny elides
71const PAYLOADS: Record<string, readonly string[]> = {
72 Write: ['content'],
73 Edit: ['old_string', 'new_string'],
74}
75
76// What a Write or Edit result appends, as seen in a spike (2.1.294); false once the payload is elided
77const STATE_NOTE = /\s*\(file state is current in your context[^)]*\)/
78
79const lineCount = (s: string) => s.split('\n').length - (s.endsWith('\n') ? 1 : 0)
80
81/**
82 * The input with each payload field replaced by a placeholder, or null when none is
83 * longer than its placeholder (short strings, earlier placeholders)
84 */
85function elidePayload(
86 fields: readonly string[],
87 input: Record<string, unknown>,
88): { input: Record<string, unknown>; chars: number } | null {
89 let out: Record<string, unknown> | null = null
90 let chars = 0
91 for (const f of fields) {
92 const v = input[f]
93 if (typeof v !== 'string' || PLACEHOLDER.test(v)) continue
94 const n = lineCount(v)
95 const text = `[${f}${MARKER}${n} line${n === 1 ? '' : 's'}. Read the file if needed.]`
96 if (v.length <= text.length) continue
97 out ??= { ...input }
98 out[f] = text
99 chars += v.length
100 }
101 return out && { input: out, chars }
102}
103
104// Thinking blocks come as assistant messages of their own (one transcript entry per block),
105// which read as no text and no tool uses
106function isThinkingOnly(m: Msg): boolean {
107 return m.role === 'assistant' && !m.text && m.toolUses.length === 0
108}
109
110/**
111 * Elides the results of Read calls and drops thinking; with `tiny`, also the payloads of
112 * Write and Edit calls. Every other message keeps its handle, so the engine keeps it whole;
113 * a message holding an elided result or payload is rebuilt.
114 */
115export function microCompact(
116 messages: readonly Msg[],
117 { tiny = false }: CompactOptions = {},
118): { messages: Msg[]; stats: MicroCompactStats } {
119 const reads = new Map<string, Record<string, unknown>>()
120 // Write and Edit calls whose payload is elided, by id, with their new input and the chars saved
121 const writes = new Map<string, { input: Record<string, unknown>; chars: number }>()
122 for (const m of messages)
123 for (const u of m.toolUses) {
124 if (u.tool === 'Read') reads.set(u.tool_use_id, u.input)
125 const fields = tiny ? PAYLOADS[u.tool] : undefined
126 const elided = fields && elidePayload(fields, u.input)
127 if (elided) writes.set(u.tool_use_id, elided)
128 }
129
130 const stats: MicroCompactStats = { elided: 0, chars: 0, thinkingDropped: 0, writesElided: 0 }
131 const out: Msg[] = []
132 for (const m of messages) {
133 if (isThinkingOnly(m)) {
134 stats.thinkingDropped++
135 continue
136 }
137 let changed = false
138 const toolUses = m.toolUses.map(u => {
139 const elided = writes.get(u.tool_use_id)
140 if (!elided) return u
141 changed = true
142 stats.writesElided++
143 stats.chars += elided.chars
144 return { ...u, input: elided.input }
145 })
146 const toolResults = m.toolResults?.map(r => {
147 if (writes.has(r.tool_use_id)) {
148 // The content is gone from the context, so the result must not say otherwise
149 const text = r.text.replace(STATE_NOTE, '')
150 if (text === r.text) return r
151 changed = true
152 return { tool_use_id: r.tool_use_id, isError: r.isError, text }
153 }
154 const input = reads.get(r.tool_use_id)
155 if (!input || r.isError || PLACEHOLDER.test(r.text)) return r
156 let text = describeMedia(input, r.result)
157 if (text === null) {
158 text = describeText(input, r.text)
159 // Already short (an "unchanged since last read" stub, a tiny file)
160 if (r.text.length <= text.length) return r
161 }
162 changed = true
163 stats.elided++
164 stats.chars += r.text.length
165 return { tool_use_id: r.tool_use_id, isError: r.isError, text }
166 })
167 if (!changed) {
168 out.push(m)
169 continue
170 }
171 const { handle: _, ...rest } = m
172 out.push({ ...rest, toolUses, ...(toolResults && { toolResults }) })
173 }
174 return { messages: out, stats }
175}
176