SLOPSHOPPER

handoff-on-clear

Saves a handoff when you /clear or exit, and offers it back on your next prompt

newbandcommandtoastpromptmodel
v0.1.0MITupdated 2026-10-04ipartington/claude-mods/handoff-on-clear
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · handoff-on-clear
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /handoff ⎿ handoff-on-clear: No handoff saved for this directory. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Five Claude Code mods that remove the routine I kept doing by hand. Each one comes from an audit of my last 30 Claude Code sessions. A mod is a plugin of function hooks: it runs inside Claude Code and can draw a band above the prompt, a pane, a toast or a status line, and can step into prompts, tool calls and the session's start and end.

ModThe habit it removesWhat you seeUsage cost
merge-followthroughTyping "616 merged" (61 times in 30 sessions), then Claude spending a turn on git checkout main && git pull and deleting the branch; ! git pull by hand at session startBand of your open PRs with CI ✓ ✗ …; toast when a merge has been pulled; /prsNone
handoff-on-clear"give me a prompt to restart", "I've lost your feedback, can you redisplay" after /clearToast on save; band ↺ Handoff from last session [Load] [Dismiss]; /handoffOne cached fork per /clear (option summarize, on by default)
bg-task-band"how are we looking", "any updates", "when's the estimated end time?"Band: ⏳ Wait for cp-22 recap 12m/25m · TASK [drain]; toast on finishNone
review-ledger"what's left to do from the review?", updating the H/M/L list by handPane of items by severity (/review); toast when an item's PR mergesNone
tts-liteA Stop hook starting a full claude -p per reply to speak a summary, which left 200 stray transcriptsAudio onlyShort replies none; longer ones one bare Haiku completion

How each one works

merge-followthrough: polls gh pr list --author @me every 60 s. When a PR it saw open is merged, it checks out the default branch, pull --ff-onlys, deletes the local branch and prunes, as long as the working tree is clean. On your next prompt it tells Claude what it already did, so Claude doesn't redo it. Typing 616 merged runs the same steps at once. At session start it fast-forwards the default branch if you're on it with no changes.

handoff-on-clear: on session.end (a /clear or an exit) it saves the last answer, your recent asks, PR numbers and artifact links mentioned, the branch, and (with summarize) a 200-word handoff from one $.model.fork, which the API serves mostly from the prompt cache. It's kept per directory for three days. It goes to Claude when you press Load, run /handoff, or ask something like "redisplay" or "prompt to restart".

bg-task-band: records background Bash, Monitor and Agent calls as they start, reads each one's output file every 10 s for the last line, and marks it done from the task notification that arrives when it ends. A TaskStop marks it stopped. Finished tasks stay on the band for 90 s.

review-ledger: registers the tool mcp__review-ledger__items, which Claude calls to record findings (H1, M3, L2) and their state: open, in-progress with a PR number, done, or won't do. It's stored per repository root, so it survives /clear and new sessions. Every 5 minutes it checks in-progress PRs and marks an item done when its PR merges. A prompt that says "review" or names an item gets the ledger as context.

tts-lite: on turn.complete it reads replies of 20 words or fewer out as they are, and asks Haiku for one sentence about anything longer. It plays them through Piper and paplay, or espeak. It reads the same CLAUDE_TTS, CLAUDE_TTS_SPEED, CLAUDE_TTS_VOICE and CLAUDE_TTS_MODEL variables as the shell hook it replaces, and stays silent while that hook (tts-speak.sh) is still in ~/.claude/settings.json, so you never hear double.

Install

Requirements: Claude Code 2.1.288 or later (function-hook mods are early access and the API moves between releases), plus git and an authenticated gh for merge-followthrough and review-ledger. tts-lite needs paplay and Piper or espeak.

Load them for every session by listing the folders in CLAUDE_CODE_PLUGIN_DIRS (colon-separated) in the env block of ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "~/code/claude-mods/merge-followthrough:~/code/claude-mods/handoff-on-clear:~/code/claude-mods/bg-task-band:~/code/claude-mods/review-ledger:~/code/claude-mods/tts-lite"
  }
}

For one session only:

claude --plugin-dir ./merge-followthrough --plugin-dir ./bg-task-band

Or copy them into a session's hot-reload folder:

scripts/sync.sh ~/.claude/dev-mods/<session-id>

Layout

<mod>/
  .claude-plugin/plugin.json   manifest (name, version, options, state contract)
  hooks/hooks.json             { "modules": ["./register.tsx"] }
  hooks/register.tsx           the hooks module
  types/index.d.ts             $.state contract (mods that keep state)
  tests/*.test.ts              claude plugin test
scripts/
  check-mods.sh                validate / test the mods given files touch
  typecheck.sh                 tsc against Claude Code's generated API types
  sync.sh                      copy mods into a load folder

Development

pip install pre-commit && pre-commit install
claude plugin validate <mod>
claude plugin test <mod>
scripts/typecheck.sh            # all mods

The pre-commit hooks run standard hygiene, gitleaks, shellcheck, and for the mods a commit touches: claude plugin validate, a TypeScript check and claude plugin test. The type-check needs the API declarations Claude Code writes into .claude-plugin/types/ when it loads a mod. Those are generated per build, git-ignored, and found automatically in any ~/.claude/dev-mods copy. Without them the type-check is skipped with a note.

See AGENTS.md for the conventions an agent (or a person) should follow when changing a mod.

License

MIT

Source 2 files
hooks/register.tsx 153 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Handoff } from '../types'
5
6// Before /clear (or exit) wipes the context, save what the next session needs:
7// the last answer, recent asks, open PRs, artifact links, and optionally a
8// short summary from one cached fork. Offer it back on the next prompt.
9
10const pending = atom({ plugin: 'handoff-on-clear', key: 'pending' } as const, null)
11const willAttach = atom({ plugin: 'handoff-on-clear', key: 'willAttach' } as const, false)
12
13const MAX_AGE_MS = 3 * 24 * 3600_000
14const ASKS_FOR_IT = /prompt to (restart|continue|complete|resume)|lost (you|your)|redisplay|pull up|where were we|carry on/i
15const SUMMARY_PROMPT =
16  'The user is about to clear this conversation. Write a handoff for a fresh session, under 200 words, plain markdown: ' +
17  'the goal, what is done (PR numbers, merged or open), the exact next step, and any gotchas or decisions made. No preamble.'
18
19function storeKey(cwd: string) {
20  return `handoff:${cwd}`
21}
22
23async function consume($: EngineInterface) {
24  await update($, pending, () => null)
25  await update($, willAttach, () => false)
26  await $.store.delete(storeKey(await $.session.cwd()))
27}
28
29async function snapshot($: EngineInterface, reason: string): Promise<Handoff | undefined> {
30  const messages = await $.session.messages()
31  if (!Array.isArray(messages) || messages.length < 2) return undefined
32
33  const recent = messages.slice(-60)
34  const all = recent.map(m => m.text ?? '').join('\n')
35  const lastAnswer = [...recent].reverse().find(m => m.role === 'assistant' && (m.text ?? '').trim() !== '')?.text ?? ''
36  const prompts = recent
37    .filter(m => m.role === 'user' && (m.text ?? '').trim() !== '' && !(m.text ?? '').startsWith('<'))
38    .map(m => (m.text ?? '').trim().slice(0, 200))
39    .slice(-6)
40  const links = [...new Set(all.match(/https:\/\/claude\.ai\/(code\/)?artifact\/[\w-]+/g) ?? [])].slice(-5)
41  const prs = [...new Set(all.match(/(?:PR\s*)?#\d{2,5}\b|\/pull\/\d+/g) ?? [])]
42    .map(p => `#${p.replace(/\D/g, '')}`)
43  const branch = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
44    .then(r => (r.exitCode === 0 ? r.stdout.trim() : ''))
45    .catch(() => '')
46
47  return {
48    cwd: await $.session.cwd(),
49    savedAt: await $.clock.now(),
50    reason,
51    branch,
52    summary: '',
53    lastAnswer: lastAnswer.slice(0, 4000),
54    prompts,
55    links,
56    prs: [...new Set(prs)].slice(-10),
57  }
58}
59
60function render(ho: Handoff): string {
61  const parts = ['[handoff-on-clear] Context saved from the previous session in this directory.']
62  if (ho.summary) parts.push(`## Summary\n${ho.summary}`)
63  if (ho.branch) parts.push(`Branch at the time: ${ho.branch}`)
64  if (ho.prs.length) parts.push(`PRs mentioned: ${ho.prs.join(', ')}`)
65  if (ho.links.length) parts.push(`Artifacts: ${ho.links.join(' ')}`)
66  if (ho.prompts.length) parts.push(`## Last asks\n${ho.prompts.map(p => `- ${p}`).join('\n')}`)
67  if (ho.lastAnswer) parts.push(`## Last answer\n${ho.lastAnswer}`)
68  return parts.join('\n\n')
69}
70
71function headline(ho: Handoff): string {
72  const first = (ho.summary || ho.prompts.at(-1) || ho.lastAnswer).split('\n').find(l => l.trim() !== '') ?? ''
73  return first.replace(/^[#*\-\s]+/, '').slice(0, 90)
74}
75
76export const register: Register = (on, options) => {
77  const summarize = options.summarize !== false
78
79  on('session.start', async ($, e, next) => {
80    await $.command.register({
81      name: 'handoff',
82      description: 'Show the saved handoff for this directory and give it to Claude',
83    })
84    const saved = (await $.store.get(storeKey(e.cwd))) as Handoff | undefined
85    if (saved && (await $.clock.now()) - saved.savedAt < MAX_AGE_MS) {
86      await update($, pending, () => saved)
87    }
88    return next(e)
89  })
90
91  on('session.end', async ($, e, next) => {
92    if (e.reason !== 'clear' && e.reason !== 'prompt_input_exit') return next(e)
93    const ho = await snapshot($, e.reason)
94    if (!ho) return next(e)
95
96    if (summarize) {
97      const reply = await $.model.fork({ prompt: SUMMARY_PROMPT })
98      if (reply.isAnswered) ho.summary = reply.text.trim()
99    }
100    await $.store.set(storeKey(ho.cwd), ho)
101    // After /clear the process goes on: offer it straight away.
102    await update($, pending, () => ho)
103    await update($, willAttach, () => false)
104    $.ui.toast('Handoff saved: it will be offered on your next prompt')
105
106    return next(e)
107  })
108
109  on('command.run', { command: 'handoff' }, async $ => {
110    const ho = await read($, pending)
111    if (!ho) return { text: 'No handoff saved for this directory.' }
112    await consume($)
113    return { text: render(ho) }
114  })
115
116  on('prompt.submit', async ($, e, next) => {
117    const ho = await read($, pending)
118    if (!ho || e.origin.kind !== 'composer') return next(e)
119    const isWanted = (await read($, willAttach)) || ASKS_FOR_IT.test(e.text)
120    if (!isWanted) return next(e)
121
122    await consume($)
123    return next({ ...e, context: [...(e.context ?? []), render(ho)] })
124  })
125
126  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
127    const ho = await read($, pending)
128    if (!ho || e.props.hasSurvey) return next(e)
129    const isQueued = await read($, willAttach)
130    const { Box, Button, Text } = $.ui.resolve(e)
131
132    return (
133      <Box>
134        <Text color="cyan">↺ </Text>
135        <Text dimColor wrap="truncate">
136          {isQueued ? 'Handoff goes with your next prompt: ' : 'Handoff from last session: '}
137          {headline(ho)}{' '}
138        </Text>
139        {!isQueued && (
140          <Button key="load" label="Load" hotkey="l" variant="primary" onPress={() => update($, willAttach, () => true)} />
141        )}
142        <Button
143          key="dismiss"
144          label="Dismiss"
145          hotkey="d"
146          role="dismiss"
147          onPress={() => consume($)}
148        />
149      </Box>
150    )
151  })
152}
153
types/index.d.ts 21 lines
1export type Handoff = {
2  cwd: string
3  savedAt: number
4  reason: string
5  branch: string
6  summary: string
7  lastAnswer: string
8  prompts: string[]
9  links: string[]
10  prs: string[]
11}
12
13declare module 'claude-code' {
14  interface PluginState {
15    'handoff-on-clear': {
16      pending: Handoff | null
17      willAttach: boolean
18    }
19  }
20}
21