SLOPSHOPPER

shake

Shrink a long session by replacing old tool results in the session file with saved-file placeholders, then reloading it

commandpromptprocesstimer
v0.4.0no licenseupdated 2026-10-20serhiichuk/claude-shake
A shopper browsing a rack in a slop shop
README

shake

A Claude Code 2.1.304 mod (function-hook plugin). It shrinks a long session while you keep working in it: at an idle point it replaces old, large tool results in the session file with a <persisted-output> placeholder that points to a saved copy. Every other line stays as it is. Then it queues /resume <same session id>, so the session loads the shaken file at once.

The mod uses no compaction. On a Team or Enterprise login, the built-in cc-plugin-sec-default guard skips the session.compact hook of a user plugin, so the compaction route of 0.3.x did not work there.

The plugin name is shake, because Claude Code reserves names that start with claude-.

Decisions

The design decisions live in the agents repo, not here. These links assume both repos are checked out side by side under ~/Repos.

docs/research/ holds frozen copies of the reports and reviews the ADR cites. Update the ADR, not the copies.

How it works

  • Threshold shake. After each main-loop turn that ends with an answer, the mod reads the used context. If it is at or above thresholdTokens, and the shake frees at least floorShare of it, the mod shakes. After a try, the next one waits until the context grows by floorShare.
  • Idle shake. After each main-loop turn, and when a session starts or resumes, the mod starts a timer that ends when the prompt cache expires: the time of the last main-loop request plus 1.5 times the cache lifetime (90 minutes for the 1 h cache, as in omp; the margin keeps a shake off a cache that is still warm). A new prompt stops it. When it fires, the next request writes the whole cache in any case, so the mod shakes with no floor, if any tool result is old enough. On a resume after a longer pause, the timer fires at once.
  • The cache lifetime comes from the session file: the newest cache write shows ephemeral_1h_input_tokens (60 minutes) or ephemeral_5m_input_tokens (5 minutes). This follows CLAUDE_CODE_PROMPT_CACHE_TTL, promptCacheTtl and the plan default without reading them. With no cache write found, the mod uses 60.
  • Manual shake. Type /shake. It has no floor.
  • Selection.
  • The newest tool output (16k tokens) stays as it is.
  • An older tool result larger than 2,000 characters is saved to <project dir>/<session id>/shake/<tool_use_id>.txt (file mode 600, directory mode 700, never overwritten). Its text becomes the native placeholder: Output too large (…). Full output saved to: <path> and a 500-character preview that ends on a code point.
  • A result that starts with [shaken:, <persisted-output> or <truncated-output> is never shaken again. Claude Code itself saves large new results as <persisted-output> (measured on 2.1.304: a 25,000-character Bash output), so these are not shaken.
  • File rewrite (bin/shake_io.py shake):
  • waits until the file size is stable for 250 ms and the file ends with a whole line (timeout 3 s);
  • replaces the content of each selected tool_result block, in every row that holds it, and changes no other line. tool_use blocks, ids, is_error flags, thinking, attachment rows and toolUseResult records stay;
  • writes a temp file in the same directory, copies whole lines appended meanwhile, checks the inode, calls fsync and renames. A hard-link backup (<session>.jsonl.shake-bak.<ns>) exists until the rename succeeded. If rows reached the old file during the rename, the rewrite copies them to the new file and keeps that backup. After each rewrite, only the newest backup of the session stays.

A prompt that you send during the rewrite waits for it.

  • Reload. The live process does not read the file back, so the mod queues /resume <same session id> with $.command.run. It runs when the main loop is idle and redraws the transcript from the file. Background shells and background subagents keep running across it, and their results still reach the session (measured). Classic SessionEnd and SessionStart hooks run with the source resume.
  • Status line. After the reload, the mod writes one dim transcript line that the model does not read: Shook N tool results (~X tokens freed)., as omp shows it. /shake with nothing to shake shows Nothing to shake.
  • Cost. Each shake makes the next request write the prompt cache of all messages after the first changed one again, and the server drops the thinking after that message. The break-even is about 20 x kept / freed requests with the 1 h cache.

Requirements

  • Claude Code 2.1.304 (the mod API is early access and changes between releases).
  • python3 on PATH. The file work runs in bin/shake_io.py, because the mod environment has no rename, fsync or file modes.
  • An interactive session (the TUI). A headless (-p) session has no /resume command: the mod shakes the file, and the session loads it at its next --resume.

Install

Install from GitHub:

claude plugin marketplace add serhiichuk/claude-shake
claude plugin install shake@claude-shake

To get a new version, run claude plugin marketplace update claude-shake.

Load the plugin from a local clone for one session:

claude --plugin-dir /path/to/claude-shake

--plugin-dir overrides an installed copy of the same plugin for that session.

Config

Four values are plugin settings. Change them in /config, or in settings.json under pluginConfigs.shake.options.

SettingDefaultMeaning
thresholdTokens150000Used context that starts a threshold shake
floorShare0.33Least share of the used context a threshold shake must free
idleShaketrueShake with no floor when the prompt cache expires
cacheTtlMinutes0Cache lifetime override; 0 reads it from the session

The other values are in CONFIG in hooks/shake.ts:

KeyDefaultMeaning
keepTokens16000Newest tool output that is never shaken
tokensPerChar0.34Token estimate for one character
minResultChars2000Smallest result that is shaken

With --plugin-dir, a saved edit reloads the module in the running session.

Tools for a manual test

  • bin/shake-fork <session id or path>: copies a session to a new id in the same project directory. Only the sessionId values change; cost-state rows are left out. The source file is read only, and its sha256 is checked before and after. It prints the claude --resume command with a cd to the cwd of the first row: Claude Code finds a session through the project directory of the directory the session started in, not the last cwd. If that cwd does not map to the project directory name, it prints a warning.
  • bin/shake-check <session.jsonl>: prints rows, boundaries with or without anchors, and what the loader would load: duplicate message blocks, tool_use ids and tool_result ids, dangling parents, thinking blocks, shaken results and saved files present. It mirrors the 2.1.293 loader on a best-effort basis.

Manual test

Each step that sends a prompt to the model costs API tokens.

  1. Pick a long session with large old tool outputs (more than 100k tokens of context). Note its session id.
  2. Run bin/shake-fork <session id>. Expected: source sha256 (unchanged), a fork: path and a cd … && claude --resume <new id> --plugin-dir … command.
  3. Run bin/shake-check <fork path>. Keep the output as the baseline.
  4. Run the printed command. Expected: the session opens with no plugin error line. claude --debug shows the plugin's lines in the debug log.
  5. Run /context and note the used tokens.
  6. Type /shake. Expected: the transcript redraws, then the dim line Shook N tool results (~X tokens freed)., or Nothing to shake.
  7. In a second terminal, run bin/shake-check <fork path>. Expected:
  8. all duplicate_* counts are 0;
  9. dangling_parents is 0;
  10. saved_files_missing is 0.
  11. Send one prompt, for example Reply with ok. Expected: a normal answer.
  12. Run /context. Expected: fewer used tokens than in step 5.
  13. Exit, then run the resume command again. Expected: /context shows about the same usage as in step 9.
  14. Optional: ask the model to read one saved file from a placeholder. Expected: it reads the full original output.
  15. Optional, for the automatic triggers: set thresholdTokens to a value under the current usage (or cacheTtlMinutes to 1 for the idle shake, which then fires 90 s after the last request), and send one prompt. Expected: the same redraw and line as in step 6.
  16. Remove the fork when done: the fork .jsonl file and the <project dir>/<new id>/ directory.

Measured

Live tests on 2.1.304 with the Team login and the guard active (Haiku forks, 2026-10-20; report in ~/.agents/artifacts/claude-shake/main/20261020-file-route-spike/):

  • A mod-queued /resume <same id> loaded an edited file: a fork with 2 results replaced sent 7,019 fewer tokens than the unedited control.
  • The threshold shake from turn.complete shook 11 results. The next request sent 140,250 tokens against 171,658 before.
  • The idle shake fired 90 s after the last request (cacheTtlMinutes: 1) and shook 8 results.
  • After both shakes, bin/shake-check reported 0 duplicates, 0 dangling parents and 0 missing saved files.
  • A background shell and a background subagent kept running across the reload, and both results reached the session.

Known limits

  • Each reload redraws the transcript, and the classic SessionStart hooks add their context again.
  • The server drops the thinking after the first changed message, and the prompt cache is written again once per shake.
  • Headless sessions do not reload (see Requirements).
  • Not tested: a prompt typed while the reload runs, /rewind and fork after a shake, Monitor tasks and cron jobs across the reload.
  • Storage v5 is not supported. Without a plain session file, the rewrite refuses.

Checks

claude plugin validate .
claude plugin test .          # selection, placeholder and preview unit checks
python3 test/test_io.py       # save, shake, cache, check and fork on a copied fixture

test/test_io.py takes a session file with large tool results as its argument. The default is the e3 file of the live-shake research run. The fixture is only copied.

Type-check: after one load with --plugin-dir, the engine writes .claude-plugin/types/, and tsc -p . works. Before that, use the tsconfig.json from the header of the types file that the plugin-authoring skill writes.

Source 2 files
hooks/register.ts 131 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3import { CONFIG, type Config, freedTokens, placeholder, selectOld } from './shake'
4
5type Trigger = 'manual' | 'threshold' | 'idle'
6
7const DEFAULT_CACHE_TTL_MINUTES = 60
8// Waits past the TTL with a margin, as omp does (90 min for the 1 h TTL): a shake on a still-warm cache pays a full cache write.
9const CACHE_EXPIRY_MARGIN = 1.5
10
11const runHelper = async ($: EngineInterface, args: string[], stdin?: string) =>
12  $.process.run(['python3', `${$.plugin.root}/bin/shake_io.py`, ...args], { stdin, timeoutMs: 60_000 })
13
14const runJson = async <T>($: EngineInterface, args: string[], stdin: unknown): Promise<T> => {
15  const run = await runHelper($, args, JSON.stringify(stdin))
16  if (run.exitCode !== 0) throw new Error(`shake_io ${args[0]} exit ${run.exitCode}: ${run.stdout.trim()}`)
17  return JSON.parse(run.stdout) as T
18}
19
20let writing: Promise<void> | undefined
21let retryAboveTokens = 0
22let idleShake: Timer | undefined
23let idleArmings = 0
24
25const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`
26
27// Rewrites the tool results in the session file; the live process sends them only after the queued /resume reloads it.
28const shake = async ($: EngineInterface, config: Config, trigger: Trigger): Promise<void> => {
29  const old = selectOld(await $.session.messages())
30  if (old.length === 0) {
31    if (trigger === 'manual') $.ui.log('Nothing to shake.')
32    return
33  }
34  if (trigger === 'threshold') {
35    const tokens = (await $.session.usage()).context.tokens ?? 0
36    if (tokens < config.thresholdTokens || tokens < retryAboveTokens) return
37    // Also stops a retry each turn when the reload fails (headless): the next try waits until the context grows.
38    retryAboveTokens = tokens * (1 + config.floorShare)
39    if (freedTokens(old) < config.floorShare * tokens) return
40  }
41  const id = await $.session.id()
42  const write = (async () => {
43    const items = old.map(result => ({ id: result.tool_use_id, text: result.text }))
44    const saved = await runJson<Record<string, string>>($, ['save', id], { items })
45    const replacements = Object.fromEntries(
46      old.filter(result => saved[result.tool_use_id]).map(r => [r.tool_use_id, placeholder(saved[r.tool_use_id]!, r.text)]),
47    )
48    return runJson<{ replaced: string[] }>($, ['shake', id], replacements)
49  })()
50  writing = write.then(() => undefined, () => undefined)
51  const { replaced } = await write.finally(() => {
52    writing = undefined
53  })
54  if (replaced.length === 0) {
55    if (trigger === 'manual') $.ui.log('Nothing to shake.')
56    return
57  }
58  await $.command.run({ command: 'resume', args: id })
59  retryAboveTokens = 0
60  // An id repeats in the list for each row it was replaced in (copies from before a compaction boundary).
61  const shaken = old.filter(result => replaced.includes(result.tool_use_id))
62  $.ui.log(`Shook ${plural(shaken.length, 'tool result')} (~${Math.round(freedTokens(shaken))} tokens freed).`)
63}
64
65let shaking: Promise<void> | undefined
66
67const startShake = ($: EngineInterface, config: Config, trigger: Trigger): void => {
68  shaking ??= shake($, config, trigger)
69    .catch(error => $.ui.log(`${trigger} shake failed: ${String(error)}`, { to: 'debug' }))
70    .finally(() => {
71      shaking = undefined
72    })
73}
74
75type CacheState = { lastRequestMs: number | null; ttlMinutes: number | null }
76
77const readCache = async ($: EngineInterface): Promise<CacheState> => {
78  const run = await runHelper($, ['cache', await $.session.id()])
79  if (run.exitCode !== 0) throw new Error('shake could not read the session cache state', { cause: run })
80  return JSON.parse(run.stdout) as CacheState
81}
82
83// Fires when the prompt cache expires: then the next request writes it whole anyway, so a shake is free.
84const armIdleShake = async ($: EngineInterface, config: Config, lastRequestMs?: number): Promise<void> => {
85  const arming = ++idleArmings
86  idleShake?.cancel()
87  if (!config.idleShake) return
88  const cache = await readCache($)
89  const since = lastRequestMs ?? cache.lastRequestMs
90  if (since === null) return
91  const ttlMinutes = config.cacheTtlMinutes || cache.ttlMinutes || DEFAULT_CACHE_TTL_MINUTES
92  const delay = Math.max(0, since + ttlMinutes * CACHE_EXPIRY_MARGIN * 60_000 - (await $.clock.now()))
93  if (arming !== idleArmings) return
94  idleShake = $.clock.after(delay, () => startShake($, config, 'idle'))
95}
96
97const logIdleError = ($: EngineInterface) => (error: unknown) =>
98  $.ui.log(`idle shake timer failed: ${String(error)}`, { to: 'debug' })
99
100export const register: Register = (on, options) => {
101  const config = { ...CONFIG, ...options } as Config
102
103  on('session.start', async ($, e, next) => {
104    await $.command.register({ name: 'shake', description: 'shake: replace old tool results now' })
105    void armIdleShake($, config).catch(logIdleError($))
106    return next(e)
107  })
108
109  on('command.run', { command: 'shake' }, async $ => {
110    // The engine refuses a command run from inside the running command's own hook.
111    $.clock.after(0, () => startShake($, config, 'manual'))
112    return {}
113  })
114
115  on('prompt.submit', async (_, e, next) => {
116    idleArmings += 1
117    idleShake?.cancel()
118    // Waits for the file rewrite only: the queued /resume runs after this turn.
119    if (!e.turnId && writing) await writing
120    return next(e)
121  })
122
123  on('turn.complete', async ($, e, next) => {
124    const completed = await next(e)
125    if (e.agentId) return completed
126    void (async () => armIdleShake($, config, await $.clock.now()))().catch(logIdleError($))
127    if (e.reason === 'answer') startShake($, config, 'threshold')
128    return completed
129  })
130}
131
hooks/shake.ts 66 lines
1import type { SessionMessage, ToolResultSummary } from 'claude-code'
2
3export const CONFIG = {
4  thresholdTokens: 150_000,
5  floorShare: 0.33,
6  idleShake: true,
7  cacheTtlMinutes: 0,
8  keepTokens: 16_000,
9  tokensPerChar: 0.34,
10  minResultChars: 2_000,
11}
12
13export type Config = typeof CONFIG
14
15const PREVIEW_CHARS = 500
16const PLACEHOLDER_OVERHEAD_CHARS = PREVIEW_CHARS + 300
17const SHAKEN_PREFIXES = ['[shaken:', '<persisted-output>', '<truncated-output>']
18
19export const isShaken = (text: string): boolean => {
20  const head = text.trimStart()
21  return SHAKEN_PREFIXES.some(prefix => head.startsWith(prefix))
22}
23
24const resultsOf = (messages: readonly SessionMessage[]): ToolResultSummary[] =>
25  messages.flatMap(message => message.toolResults ?? [])
26
27export const selectOld = (messages: readonly SessionMessage[], config: Config = CONFIG): ToolResultSummary[] => {
28  const keepChars = config.keepTokens / config.tokensPerChar
29  const old: ToolResultSummary[] = []
30  let newerChars = 0
31  for (const result of resultsOf(messages).reverse()) {
32    if (isShaken(result.text)) continue
33    const isInKeepWindow = newerChars < keepChars
34    newerChars += result.text.length
35    if (!isInKeepWindow && result.text.length > config.minResultChars) old.push(result)
36  }
37  return old.reverse()
38}
39
40export const freedTokens = (old: readonly ToolResultSummary[], config: Config = CONFIG): number =>
41  old.reduce((sum, result) => sum + Math.max(0, result.text.length - PLACEHOLDER_OVERHEAD_CHARS), 0) * config.tokensPerChar
42
43const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
44
45export const preview = (text: string, maxChars: number = PREVIEW_CHARS): { text: string; hasMore: boolean } => {
46  if (text.length <= maxChars) return { text, hasMore: false }
47  const newline = text.lastIndexOf('\n', maxChars - 1)
48  let cut = newline > maxChars / 2 ? newline : maxChars
49  if (isHighSurrogate(text.charCodeAt(cut - 1))) cut -= 1
50  return { text: text.slice(0, cut), hasMore: true }
51}
52
53const formatSize = (chars: number): string => {
54  if (chars < 1024) return `${chars} bytes`
55  if (chars < 1024 * 1024) return `${Number((chars / 1024).toFixed(1))}KB`
56  return `${Number((chars / (1024 * 1024)).toFixed(1))}MB`
57}
58
59export const placeholder = (path: string, text: string): string => {
60  const cut = preview(text)
61  return (
62    `<persisted-output>\nOutput too large (${formatSize(text.length)}). Full output saved to: ${path}\n\n` +
63    `Preview (first ${formatSize(PREVIEW_CHARS)}):\n${cut.text}${cut.hasMore ? '\n...\n' : '\n'}</persisted-output>`
64  )
65}
66