Saves each compaction's summary, with the files edited before it, to ~/.claude/handoffs so the context before /compact can be recovered

Saves a handoff file each time the conversation is compacted, so the context before /compact can be recovered.
One Markdown file per compaction in ~/.claude/handoffs/, named <date>-<time>-<project>-<session>.md:
claude --resume command/compactA short toast names the file once it is saved. Subagent compactions are skipped, and a failed write never blocks the compaction.
/compact is saved about a second after it finishes, an automatic compaction at the end of the reply it ran in. That file has no token counts, and its trigger reads auto or plugin for anything but /compact. In the desktop app, /clear stops Claude Code before the mod can read the conversation, so an automatic compaction cleared before its reply ends gets no file.claude plugin marketplace add arasovic/claude-code-mods
claude plugin install compact-keeper@claude-code-mods
Restart Claude Code. Nothing to open: the next compaction writes the first file.
claude plugin validate .
claude plugin test .
../typecheck.sh compact-keeperhooks/register.ts 150 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMessage } from 'claude-code'
3
4// Paths edited since the last compaction, listed in the next handoff.
5const edited = atom({ plugin: 'compact-keeper', key: 'edited' } as const, [] as string[])
6
7const pad = (n: number) => String(n).padStart(2, '0')
8const stamp = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
9
10export const fileName = (at: number, cwd: string, sessionId: string) => {
11 const d = new Date(at)
12 const project = (cwd.split('/').filter(Boolean).pop() ?? 'root').replace(/[^\w.-]+/g, '-')
13 return `${stamp(d)}-${pad(d.getHours())}${pad(d.getMinutes())}-${project}-${sessionId.slice(0, 8)}.md`
14}
15
16// The summary is the message core wrote: the one carrying no handle from the transcript it replaced.
17export const summaryOf = (before: readonly SessionMessage[], after: readonly SessionMessage[]) => {
18 const kept = new Set(before.map(m => m.handle).filter(Boolean))
19 return (after.find(m => m.text && !(m.handle && kept.has(m.handle))) ?? after[0])?.text ?? ''
20}
21
22export const handoff = (h: { at: number; cwd: string; sessionId: string; trigger: string; instructions?: string; tokensBefore?: number; tokensAfter?: number; files: readonly string[]; summary: string }) => {
23 const d = new Date(h.at)
24 const size = h.tokensBefore === undefined ? '' : `, ${Math.round(h.tokensBefore / 1000)}k → ${h.tokensAfter === undefined ? '?' : Math.round(h.tokensAfter / 1000)}k tokens`
25 return [
26 `# Handoff: ${h.cwd.split('/').filter(Boolean).pop() ?? h.cwd}`,
27 '',
28 // toTimeString starts with the local HH:MM:SS.
29 `- Compacted: ${stamp(d)} ${d.toTimeString().slice(0, 5)} (${h.trigger})${size}`,
30 `- Directory: ${h.cwd}`,
31 `- Session: ${h.sessionId} (\`claude --resume ${h.sessionId}\`)`,
32 ...(h.instructions ? [`- Instructions: ${h.instructions}`] : []),
33 '',
34 '## Files edited before this compaction',
35 '',
36 ...(h.files.length ? h.files.map(f => `- ${f}`) : ['- none']),
37 '',
38 '## Summary',
39 '',
40 h.summary.trim(),
41 '',
42 ].join('\n')
43}
44
45type Saved = { trigger: string; instructions?: string; tokensBefore?: number; tokensAfter?: number; summary: string }
46
47async function save($: EngineInterface, h: Saved) {
48 try {
49 const at = await $.clock.now()
50 const cwd = await $.session.cwd()
51 const sessionId = await $.session.id()
52 const home = await $.env.get('HOME')
53 const files = await read($, edited)
54 const path = `${home ?? '.'}/.claude/handoffs/${fileName(at, cwd, sessionId)}`
55 await $.fs.write(path, handoff({ ...h, at, cwd, sessionId, files }))
56 await update($, edited, () => [])
57 $.ui.toast(`Handoff saved: ${path.replace(home ?? '\0', '~')}`)
58 } catch {
59 // Saving is a convenience: a failed write must never undo the compaction.
60 }
61}
62
63// A seated cc-plugin-sec-default sends session.compact past user-tier mods. The fallback notices a compaction
64// afterwards: it is the only thing that replaces the conversation's first text (/clear resets in session.end).
65let seenFirst: string | undefined
66// ponytail: module state, so a reload between a compaction and its check writes that handoff twice.
67let handled = false
68// What /compact was run with: core swaps the conversation only after the command returns, so the next check saves it.
69let typed: { trigger: string; instructions?: string } | undefined
70// Ticks left to look for the conversation /compact leaves.
71let polls = 0
72const POLL_MS = 500
73
74async function firstText($: EngineInterface) {
75 // The rows form keeps what a compaction replaced while the process lives, so only the request's form shows it.
76 // Core's own notes can come ahead of the summary, and a compaction sends new ones.
77 const block = (await $.session.messages({ as: 'api' })).flatMap(m => m.content).find(b => b.type === 'text' && typeof b.text === 'string' && !b.text.startsWith('<system-reminder>'))
78 return typeof block?.text === 'string' ? block.text : undefined
79}
80
81async function check($: EngineInterface) {
82 const first = await firstText($)
83 const compacted = seenFirst !== undefined && first !== undefined && first !== seenFirst
84 const saved = handled
85 const run = typed
86 seenFirst = first
87 handled = false
88 typed = undefined
89 if (compacted && !saved) await save($, { trigger: run?.trigger ?? 'auto or plugin', instructions: run?.instructions, summary: first })
90}
91
92// The desktop's /clear stops the process, and by session.end the conversation is out of reach,
93// so /compact is saved as soon as its conversation shows, not at the next turn.
94async function poll($: EngineInterface) {
95 if (typed === undefined || polls <= 0) return
96 polls--
97 const first = await firstText($)
98 // A conversation read mid-swap may have no first text; checking it would drop the pending label.
99 if (first !== undefined && first !== seenFirst) await check($)
100}
101
102export const register: Register = on => {
103 // A timer started in any other hook stops when that hook's dispatch ends.
104 on('session.start', async ($, e, next) => ($.clock.every(POLL_MS, () => void poll($).catch(() => {})), next(e)))
105
106 on('tool.call', async ($, e, next) => {
107 const result = await next(e)
108 if ((e.tool === 'Edit' || e.tool === 'Write') && result.deny === undefined && !result.isError) {
109 const path = (e as unknown as { file_path: string }).file_path
110 await update($, edited, list => [path, ...list.filter(p => p !== path)].slice(0, 100))
111 }
112 return result
113 })
114
115 on('session.compact', async ($, e, next) => {
116 const result = await next(e)
117 // A precompute may never be installed, and a subagent's compaction is not the conversation's.
118 if (result.skip !== undefined || e.trigger === 'precompute' || e.agentId !== undefined) return result
119 handled = true
120 await save($, { trigger: e.trigger, instructions: e.instructions, tokensBefore: result.tokensBefore, tokensAfter: result.tokensAfter, summary: summaryOf(e.messages, result.messages) })
121 return result
122 })
123
124 // /compact, typed or run by a plugin, leaves its label for the poll; any other compaction waits for the next main turn or session end.
125 on('command.run', { command: 'compact' }, async ($, e, next) => {
126 // A resumed session can compact before any turn has read its first message.
127 seenFirst ??= await firstText($).catch(() => undefined)
128 const result = await next(e)
129 typed = { trigger: e.origin.kind === 'plugin' ? 'plugin' : 'manual', instructions: e.args.trim() || undefined }
130 polls = 240
131 return result
132 })
133
134 on('turn.complete', async ($, e, next) => {
135 if (e.agentId === undefined) await check($).catch(() => {})
136 return next(e)
137 })
138
139 on('session.end', async ($, e, next) => {
140 // The terminal's /clear ends the session before it empties the conversation; a resume may already show the next one.
141 // The desktop's /clear stops the process instead, and reading the conversation here throws.
142 // ponytail: inside session.end's short wall-clock bound, so a slow disk can cut this write.
143 if (e.reason !== 'resume') await check($).catch(() => {})
144 seenFirst = undefined
145 handled = false
146 typed = undefined
147 return next(e)
148 })
149}
150types/index.d.ts 8 lines1declare module 'claude-code' {
2 interface PluginState {
3 'compact-keeper': {
4 edited: string[]
5 }
6 }
7}
8