SLOPSHOPPER

handover

The handover sentence for a cold session, one per session: a band above the prompt, /handover-copy to copy it, after /clear it waits in the prompt, and…

bandguardcommandpromptprocesstimer
★ 3v0.3.0MITupdated 2026-10-18schreibse/claude-code-mods/handover
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · handover
› 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 › /handover-copy ⎿ handover: No handover sentence yet. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-code-mods

Personal Claude Code mods: plugins of function hooks that restyle the transcript, add rows around the prompt and react to tool calls. Built and used on Claude Code 2.1.287+, Linux.

Mods

ModWhat it doesCommandsNeeds
quiet-bashOne-line tool rows (✓ <description>, red ✗ exit N on failure, +N −M on edits, duration for calls ≥10 s). Hides every tool's result block (Bash output, Edit diffs, WebFetch, MCP and Agent results; interactive tools, SendUserFile and image Reads keep theirs), finished read-only rows (Read/Grep/Glob, and calls the engine ran read-only like ls or git status, and every Claude in Chrome step but navigate), collapsed tool groups unless one failed, and timed-out GitLab pipeline-wait notices. Inline PNG thumbnails under rows that read, sent or wrote a PNG (at most 3 written ones per call), relative paths included; a group holding a thumbnail stays open, even under /quiet/quiet brings it all back; /thumb [big] <path> shows a PNG (relative to the session's directory) as thumb #N: <path>ImageMagick (magick) for thumbnails; a terminal with kitty graphics (see herdr)
quiet-spinnerPlain spinner words (thinking, writing, running, waiting, preparing) and Took 1m 4s instead of the whimsical ones––
usage-percentRow under the prompt: `ctx ▰▱▱▱ 34% \5h ▰▰▱▱ 41% \wk ▰▰▰▱ 86% \fable ▰▰▱▱ 28% (four-cell bars; the fourth is the plan's model-scoped week, from the usage endpoint with the session's login) and resets 1d5h a gap after them for the weekly reset, yellow from 80 %, red from 95 %. Memory (claude.slice usage as a ten-cell bar of its limit + app.slice pressure, yellow from 20 %, red from 50 %) is sampled every 10 s and drawn by TamaGoxtix's band. In Nx repos also, on the right, the session's own nx serve projects (▶ admin api; a bare nx serve or run-many -t serve shows ▶ serve) and the branch's pipeline (ci ⏳ test, ⏸` when it waits on a manual job or an approval; none for Azure remotes)–gh / glab logged in for the pipeline; systemd claude.slice for memory
reminder-logTallies the reminders Claude Code injects for the model, per session; drops the token counter and repeated commit attribution blocks (sent again after a compaction)/reminders prints the tally of the last 30 days–
mr-bannerColored card with a link under each MR/PR created, merged, approved or reviewed–GitLab MCP server named gitlab, or glab / gh
coderabbit-bandBand above the prompt with the open CodeRabbit threads (by severity) and nitpicks of the current branch's GitLab MR, with a link. Shows only when something is open/coderabbit hides it until the counts changeglab logged in; GitLab remote
redactSecrets in prompts and tool output reach the model as ‹secret:…› tokens; only Write/Edit turn them back into the real value. See redact–betterleaks on PATH
mem-guardBash commands that run Node tools go into a memory-capped claude-cmd.slice scope. Refused, with the fix in the message: nx affected/run-many without --parallel=1, a pnpm script that has a :lite twin, jest without a worker cap (--maxWorkers=N, -w N or --runInBand; a percentage doesn't count), pkill -f/pgrep -f with an unbracketed pattern, ci:local, heavy runs and dev-server starts while the slice is above 75 % or under pressure, a third heavy command or a third dev server at once, and writes by a check-runner subagent. See mem-guard–Linux with systemd: a user claude-cmd.slice, ps; see mem-guard
handoverSkill plus mod: the handover skill writes a one-sentence handover for a cold session to ~/.claude/handover.md; the mod files it per session under ~/.claude/handovers/<session id>.md, so parallel sessions in one repo never overwrite each other. A band above the prompt shows it; after /clear that session's sentence waits in the prompt (Tab takes it) and the next prompt spends it. A new terminal suggests nothing but lists the open sentences of the repo it started in (newest first, 14 days); a sentence belongs to the repo of the file its session wrote last, else to the folder the session started in/handover-copy copies it and hides the band; /handover lists, /handover N puts one in the prompt, /handover drop N removes it; a sentence pasted by hand leaves the list too–
herdr-notifyGNOME popup when Claude waits for a permission, an answer or a new prompt (a Notification hook, not a plugin). Skipped while that pane is the focused one in herdr. Clicking it raises Ghostty and focuses that session's herdr pane. Hook: `"Notification": [{"matcher": "permission_prompt\idle_prompt\elicitation_dialog", "hooks": [{"type": "command", "command": "bash \"$HOME/.claude/skills/herdr-notify/notify.sh\""}]}]`–herdr, Ghostty, notify-send, jq
stack-downOn /clear and exit (also logout, a finished -p run, SIGINT/SIGTERM/SIGHUP), stops what the session left running in its repo: the nx processes it started (with their workers), and the repo's Docker Compose projects (compose down, volumes kept) unless another Claude session works in the same repo. Only for a session at a repo's top level (git rev-parse --show-toplevel); one started above the repos, such as ~/Dev, stops nothing–docker compose, git
review-walkSkill plus mod: /review-walk takes the findings of the reviews already run in the conversation (/code-review, a repo's own review skill, CodeRabbit threads, MR comments), merges and ranks them, and asks fix / issue / skip one finding at a time; fixes wait until every finding is decided. The mod puts Finding N/M, a progress bar and the decisions so far over each question, and a band above the prompt between them. Decisions you authorised up front ("apply every Fix") are recorded through its ReviewWalkDecide tool instead of a question. The walk starts only after the skill runs, so a review on its own draws no band/review-walkA review run first: it walks findings, it never reviews. Any review skill or source works
tamagoxtixThird line beside the monster, idle and while Claude works: usage-percent's memory bar. A fork of fabandrade88/tamagoxtix (MIT): a pixel monster in place of the spinner that acts out what Claude does, a band above the prompt between turns, cheer scenes while you type, twelve palettes, an optional powerline status line. The fork drops the band's usage column and repo column (repo-line shows repo and branch), the spinner's token line (usage-percent has the limits), pads the effects column so the text beside the monster stays put, adds /tamagoxtix animate off for still scenes, and puts the other mods' bands under the monster's caption instead of replacing them. With quiet-spinner the monster's line shows the plain word when quiet-spinner sits outer in the chain, else the whimsical one. The herdr half is herdr-tamagoxtix (sidebar faces, a usage popup, a tab-bar status area)/tamagoxtix help, `… pet on\off hides the band, … palette <name>, … statusline on\off (writes statusLine into settings.json, backup kept), … theme on\off, … reroll`Node.js 18+, a Nerd Font (or /tamagoxtix icons plain); git for the status line
task-meterBand above the prompt with one row per running task: background shells, foreground shells after 5 s, subagents (their shells as └ child rows, tool count ⚒ N), workflows, monitors. Per row a ten-cell bar (filled where the output shows [N/M], a percentage or an nx task count, else one cell walking), the process tree's memory (yellow from 2 GB, red from 4 GB) and the running time, in aligned columns. Rows end with the task–Linux: ps, /proc/<pid>/fd, tail
repo-lineA line right above the prompt: the repository's name as a badge on the repository's own colour (a golden-angle hue per new repository, kept in the store), the branch (@abc1234 when detached) and (wt: name) in a linked worktree, so a prompt does not go to the wrong session. `/repo-line color <hue#rrggbb> overrides, color reset` drops it/repo-linegit
needs-youAsks that wait on you stand out. Adds a system-prompt section: yes/no approvals and choices go through AskUserQuestion; anything else Claude waits on you for goes on its own line ⏸ Needs you: …. Those lines are drawn bold in the theme's warning colour (as plain text: links and code spans inside them are not formatted), pinned in a band above the prompt until your next message (or Clear), and in herdr shown as a ⏸ in the session's sidebar row; a ? there while an AskUserQuestion picker is open. See herdr for the sidebar row–herdr ≥ 0.9.5 for the sidebar icons, with { token = "$ask" } and { token = "$pick" } in ui.sidebar.agents.rows
ask-guardWhen a reply asks a yes/no question in prose (shall I…?, want me to…?, ok to push…?, should I…? and similar), a Stop hook sends Claude back to ask it with AskUserQuestion, once per reply. Skips code blocks, > quotes, quoted text and ⏸ Needs you lines; a hook that fails lets the reply through––
pii-guardAsks before a tool call would send your personal data off the machine: WebFetch, WebSearch, every MCP tool (Claude in Chrome form fills included) and network Bash commands (curl, wget, urllib, requests, gh, git push …) whose input holds one of your identifiers, plain or URL-encoded, case-insensitive. Calls only to localhost pass. Born from a session that put the user's email into a third-party API's User-Agent because the API's policy asked for contact details. Does not see inside script files a command runs–pluginConfigs.pii-guard.options.identifiers in ~/.claude/settings.json: comma-separated emails and names (empty = off)

The model sees exactly what it would without them: the mods change what is drawn, except reminder-log, which drops two kinds of injected reminders, redact, which hides secrets, mem-guard, which runs Node commands inside a systemd scope and refuses some with a mem-guard: … error, and stack-down, which stops the session's own servers and, when no other session is in the repo, its Compose stacks when the session ends.

Four mods call out on their own:

  • mr-banner, when a GitLab MCP note or approval answers without the MR's link, calls get_merge_request on the gitlab MCP server for the link and title. gh/glab commands cost nothing extra.
  • coderabbit-band polls glab for GitLab origin remotes: a 60 s timer checks the branch, and a fetch (glab mr view plus all pages of the MR's discussions) runs every minute for 15 min after a git push, every 5 min while the band shows something, every 15 min otherwise, and once 5 s after a thread is resolved.
  • tamagoxtix runs node on its usage script at session start and after each turn, and contacts no host. The mod's own README lists every call.
  • usage-percent, in Nx repos, polls every 10 s: ps and pwdx for nx serve processes, and docker inspect once per container a server runs in, to read its compose project directory. The pipeline (gh run list / glab ci get) is fetched when HEAD moves, 15 s after a git push, every minute while it runs and every 5 min otherwise.

Install

From the marketplace (gets updates; herdr-notify and herdr-link-toast are not in it):

claude plugin marketplace add schreibse/claude-code-mods
claude plugin install quiet-bash@schreibse-mods   # per mod

Then turn on updates: /plugin → Marketplaces → schreibse-mods → Enable auto-update. See Updates.

From a clone, to adapt a mod or work on it. Claude Code loads every plugin folder under ~/.claude/skills/ at session start. Don't install the same mod from the marketplace too: the installed copy silently replaces the folder.

New sessions pick them up; a running one needs /exit and claude --continue.

Leave a mod out: claude plugin uninstall <mod>@schreibse-mods, or delete or unlink its folder. Try one for a single session: claude --plugin-dir ~/src/claude-code-mods/<mod>.

Where they run. Built and used only in the terminal CLI on Fedora (Linux, systemd, cgroup v2). The engine also loads user-scope mods in the local session the desktop app starts for its Code tab, and draws them there (desktop surface); untested here. See Setting up for what each mod needs.

This repo is the skills folder itself, so .gitignore ignores everything and re-includes each mod: a new mod needs a !/<name>/ line or git won't see it. .claude-plugin/types/ is generated by the engine and stays untracked.

Updates

Each mod has its own version (plugin.json) and a CHANGELOG.md in its folder; each release is a git tag <mod>--v<version>.

  • Get them: with auto-update on, Claude Code updates the mods after a session's first message and says Plugin updated: <mod> · Run /reload-plugins to apply. Without it nothing tells you; check by hand: ``sh claude plugin marketplace update schreibse-mods claude plugin update quiet-bash@schreibse-mods # per mod; "already at the latest version" if none ``
  • What changed: the mod's CHANGELOG.md. Read every version you skipped: a major version means you have to act (a new hook in settings.json, a new dependency, a removed command).
  • Notified outside Claude Code: on GitHub, Watch → Custom → Releases. Each release carries the mod's changelog entry.
  • From a clone: git -C ~/.claude/skills pull --ff-only, then read the changelogs of the mods whose version moved (git -C ~/.claude/skills diff ORIG_HEAD -- '*/.claude-plugin/plugin.json').

redact: secrets as tokens

betterleaks scans every prompt and tool result before it reaches the model. Each value it flags becomes ‹secret:xxxxxxxx› and stays hidden wherever it appears later, even where the scanner would not recognise it again.

The model's callWhat happens
Write, Edit, NotebookEdit with a tokenthe real value is written to the file
Write that would drop a secret the file holdsrefused: use Edit
Agent, SendMessage, TodoWrite with a tokenpassed on as the token
Any other tool with a token (Bash, WebFetch, MCP …)refused, so the value never leaves
A token the mod no longer knows (after a restart)refused, never restored wrongly

Cut-short output. Before Bash or any tool with a file_path/path (Read, Grep, Edit …) runs, every file the call names (Bash: the first 10 words that could be paths, files up to 1 MB) is scanned whole, so cut -c1-60 .env, cut -d= -f2 or a Read of a few lines from a PEM key still come back as tokens. Multi-line secrets are hidden line by line. Bash words resolve against the directory each segment runs in (cd sub && cut -c1-40 .env), and ~/, $HOME/ and ${HOME}/ expand to the home directory.

Rules. betterleaks' defaults plus redact/betterleaks.toml: Sentry DSN keys, and client secrets too short for the generic rules. A client secret containing dev, local, test, example, changeme or placeholder stays visible, so local dev clients keep working in commands.

Not covered:

  • images; output with no file behind it, cut short (git show HEAD:.env | cut …, printenv | cut …); the transcript file's structured tool records, which keep real values (the model does not read them).
  • the cut-short pre-scan misses globs (cut -c1-40 *.env), quoted paths with spaces and a cd inside a subshell ((cd sub && cut -c1-40 .env)).
  • betterleaks' client-secret rule needs some entropy (≥ 3.0), so short, repetitive client secrets stay visible.
  • values shorter than 8 characters are never hidden.
  • a value restored into a file by Write/Edit can be read back transformed (base64, rev, xxd) or sent (curl -T file). redact keeps secrets out of the model's context by accident; it is not a sandbox against a model trying to get them.
  • a subagent's report that quotes a ‹secret:…› token is refused like any other tool call carrying one.

The vault lives in session memory: /exit forgets it.

The status line shows redacted N once a value is hidden: N counts vault entries, so a PEM key counts once per line. A toast per call names the rules that hid new values. Without betterleaks the status line says off (no betterleaks) and nothing is hidden. A betterleaks run that fails leaves that call unredacted (values already in the vault stay hidden): one toast per failure streak, the status says off (betterleaks), and the next call scans again.

mem-guard: memory rules for Bash

Every Bash command that names a Node tool (node, npx, pnpm, npm, npm exec, yarn, nx, jest, vitest, playwright, tsc, ngc) runs as systemd-run --user --scope --slice=claude-cmd.slice -p MemoryMax=30% -p MemorySwapMax=4% -- bash -c '…', so an overrun dies with exit 137 instead of taking the desktop down. Leading cd … && stay outside the wrapper, so the shell's directory still moves.

The rules read what each part of a command runs (after &&, |, ;, &, $( ), inside bash -c '…', following cd), never words it only mentions, so a commit message saying pkill -f passes. Not looked into: xargs, make, eval, scripts.

At once, counted per scope or service anywhere in claude.slice from one ps scan (skipped when ps fails):

  • at most 2 heavy commands (jest, vitest, Playwright, a node script that imports Playwright, tsc, ngc, an nx task), a running dev server included; the nx daemon doesn't count;
  • at most 2 dev servers (nx serve, nx run x:serve, a serve* script): the API and one app.

A command counts as heavy for these checks when it runs one of those tools, docker compose up, or a test, build, lint, typecheck, e2e or serve* script.

check-runner subagents (an agent type of the owner's) only run checks: git commands that change the tree or history, sed -i, --write/--fix, starting or stopping servers or processes, and writes outside /tmp are refused with "Report the failure instead of fixing it".

Assumes this setup; the messages name it:

  • a claude-cmd.slice user unit. Without it systemd makes the slice with no limit of its own: each command is still capped at 30 % of RAM, but the headroom check has nothing to measure and stays off: ``ini # ~/.config/systemd/user/claude-cmd.slice [Slice] MemoryMax=30% MemorySwapMax=4% ` A full slice can livelock without ever reaching the OOM killer, so let systemd-oomd kill a scope in it under sustained pressure: systemctl --user set-property claude-cmd.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=50%. systemd turns a percentage into bytes of the machine's RAM (on 27 GiB: 8.2G and 1.1G), so the same unit fits any machine. Check what a machine gets: systemd-run --user --scope -q -p MemoryMax=30% -- sh -c 'cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max'`
  • a dev API served on port 4700: the refusal messages say fuser -k 4700/tcp.
  • repos whose heavy scripts have a :lite twin (lint:affected:lite, typecheck:lite, test:affected:lite) and a slow ci:local script.

usage-percent: not covered

  • On GitHub only the newest workflow run of the branch is shown.
  • A remote using an SSH host alias (git@work:org/repo) reads as ci no login (work) though you are logged in.
  • A server counts as the session's when it runs inside the session's root, or in a container whose compose project lives there. Two sessions on one checkout both see its servers.

herdr: images and links

Under herdr (here inside Ghostty), quiet-bash's thumbnails draw only their alt text, and links in mr-banner, coderabbit-band and Claude's own output aren't clickable.

Cause: Claude Code turns on kitty graphics only for terminals whose XTVERSION answer is kitty (≥ 0.28) or starts with ghostty, and hyperlinks only for terminals it recognises. herdr forwards both, but answers with its own name, so Claude Code turns both off.

Fix: force both on, inside herdr only, before Claude Code starts (it reads them at startup):

# ~/.bashrc.d/herdr-terminal.sh
if [ -n "$HERDR_ENV" ]; then
    export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
    export FORCE_HYPERLINK=1
fi

The herdr client forks its server into the client's own cgroup, so a server started inside a Ghostty window dies with that window and takes every pane with it. A wrapper in ~/.bashrc.d starts the first server in its own scope under app.slice instead; every other call, herdr plugin … included, goes straight through:

# ~/.bashrc.d/herdr-scope.sh
herdr() {
    if [ $# -eq 0 ] && [ -z "$HERDR_ENV" ] && ! command herdr status server 2>/dev/null | grep -q '^status: running'; then
        systemd-run --user --scope -q --slice=app.slice --unit="herdr-$(date +%s)" "$HOME/.local/bin/herdr"
    else
        command herdr "$@"
    fi
}

Also turn on herdr's kitty graphics passthrough (off by default) in ~/.config/herdr/config.toml:

[experimental]
kitty_graphics = true

Then herdr server reload-config, open a new herdr pane (old panes keep the old environment) and start Claude Code there. Check it: /thumb /path/to/some.png should draw the picture.

herdr-link-toast (a herdr plugin, not a Claude Code mod)

herdr opens a ctrl+clicked link in the background with no feedback, and ignores file:// links altogether. herdr-link-toast opens http(s) links with xdg-open and shows a toast. It also opens the path in quiet-bash's thumbnail captions, which link to http://localhost/open-file/<path> because file:// isn't clickable in herdr. Such a link opens only when the path ends in .png; any other gets a "Could not open link" toast. Needs python3 ≥ 3.9. Install:

herdr plugin link ~/.claude/skills/herdr-link-toast

needs-you in the herdr sidebar

needs-you reports two tokens on its own pane (herdr pane report-metadata): $ask (⏸) while a ⏸ Needs you line is open, $pick (?) while an AskUserQuestion picker is open. herdr draws them only where the agent row names them, in ~/.config/herdr/config.toml:

[ui.sidebar.agents]
rows = [["state_icon", { token = "$ask", fg = "#f5a623", bold = true }, { token = "$pick", fg = "#f5a623", bold = true }, "machine", "workspace", "tab"], ["agent"]]

fg takes hex only. The row layout is the client's: after editing, choose reload config in herdr's menu (herdr server reload-config does not reload it).

herdr-tamagoxtix (a herdr plugin, not a Claude Code mod)

The herdr half of tamagoxtix, unchanged from upstream: the monster's face in the sidebar, a usage popup (herdr plugin action invoke tamagoxtix.stats) and, on request, a status area right of the tabs and herdr colors f

Source 3 files
hooks/register.tsx 240 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { choicesFor, dirOf, dropIndex, expandHome, handoverPath, isFresh, isPastedIn, sentenceOf, sessionIdOf, sessionPath, storeKey } from './rules'
5import type { Entry } from './rules'
6import type { Handover } from '../types'
7
8const COPY_COMMAND = 'handover-copy'
9const PICK_COMMAND = 'handover'
10const OFFER_EVERY_MS = 500
11const OFFER_TRIES = 20
12const PREVIEW_CHARS = 160
13
14const pending = atom({ plugin: 'handover', key: 'pending' } as const, null)
15const choices = atom({ plugin: 'handover', key: 'choices' } as const, null)
16// The file the session last wrote: the skill updates the plan file, in the repo, just before the sentence.
17const lastEdit = atom({ plugin: 'handover', key: 'lastEdit' } as const, null)
18
19// The key of the sentence last offered in the box; the next prompt sent spends it.
20let offered: string | null = null
21// The list the band and the last bare /handover numbered, so /handover N picks what was shown.
22let listed: Entry[] = []
23
24async function home($: EngineInterface): Promise<string> {
25  return (await $.env.get('HOME')) ?? ''
26}
27
28async function entries($: EngineInterface): Promise<Entry[]> {
29  const found: Entry[] = []
30  for (const key of await $.store.keys()) {
31    if (sessionIdOf(key) !== null) {
32      found.push({ key, handover: (await $.store.get(key)) as Handover })
33    }
34  }
35  return found
36}
37
38async function remove($: EngineInterface, key: string): Promise<void> {
39  await $.store.delete(key).catch(() => undefined)
40  const sessionId = sessionIdOf(key)
41  const dir = await home($)
42  if (sessionId !== null && dir !== '') {
43    await $.process.run(['rm', '-f', sessionPath(dir, sessionId)]).catch(() => undefined)
44  }
45}
46
47async function repoOf($: EngineInterface, dir: string): Promise<string | null> {
48  const found = await $.process.run(['git', '-C', dir, 'rev-parse', '--show-toplevel']).catch(() => null)
49  return found?.exitCode === 0 && found.stdout.trim() !== '' ? found.stdout.trim() : null
50}
51
52// A sentence belongs to the repo its work was in, which a session started in a parent folder only shows
53// through the files it wrote; outside any repo it stays with the folder the session started in.
54async function place($: EngineInterface, edited: string | null): Promise<string> {
55  const root = await $.session.root()
56  return (edited === null ? null : await repoOf($, dirOf(edited))) ?? (await repoOf($, root)) ?? root
57}
58
59async function choicesHere($: EngineInterface): Promise<Entry[]> {
60  listed = choicesFor(await entries($), await place($, null), await $.clock.now())
61  return listed
62}
63
64// Numbers shift once an entry leaves, so the list and a band showing it are renumbered together.
65async function relist($: EngineInterface): Promise<void> {
66  const here = await choicesHere($)
67  await update($, choices, shown => (shown === null || here.length === 0 ? null : here.map(c => c.handover.text)))
68}
69
70function suggest($: EngineInterface, key: string, text: string): void {
71  offered = key
72  // The box refuses while the /clear's own turn still runs, and a reset of the box right after
73  // can drop a suggestion it had taken, so the same text is proposed again for a while.
74  let tries = 0
75  const timer = $.clock.every(OFFER_EVERY_MS, async () => {
76    if (++tries > OFFER_TRIES || offered !== key) {
77      timer.cancel()
78      return
79    }
80    await $.prompt.suggest({ text })
81  })
82}
83
84function preview(text: string): string {
85  return text.length > PREVIEW_CHARS ? `${text.slice(0, PREVIEW_CHARS - 1)}…` : text
86}
87
88export const register: Register = on => {
89  // Every session's sentence goes to a file and a key of its own, so parallel sessions never overwrite one another.
90  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
91    const dir = await home($)
92    const sessionId = await $.session.id()
93    const target = sessionPath(dir, sessionId)
94    const path = expandHome(e.file_path, dir)
95    if (dir === '' || (path !== handoverPath(dir) && path !== target)) {
96      const result = await next(e)
97      if (!result.isError) {
98        await update($, lastEdit, () => path)
99      }
100      return result
101    }
102    const result = await next({ ...e, file_path: target })
103    if (result.isError) {
104      return result
105    }
106    const text = sentenceOf(e.content)
107    const handover: Handover = { text, at: await $.clock.now(), root: await place($, await read($, lastEdit)) }
108    await $.store.set(storeKey(sessionId), handover)
109    await update($, pending, () => text)
110    return result
111  })
112
113  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
114    const result = await next(e)
115    if (!result.isError) {
116      await update($, lastEdit, () => e.file_path)
117    }
118    return result
119  })
120
121  // A /clear fires no session.start; the id read before it runs is the session that wrote the sentence.
122  on('command.run', { command: 'clear' }, async ($, e, next) => {
123    const key = storeKey(await $.session.id())
124    const result = await next(e)
125    const stored = (await $.store.get(key)) as Handover | undefined
126    if (isFresh(stored, await $.clock.now())) {
127      await update($, pending, () => null)
128      suggest($, key, stored.text)
129    }
130    return result
131  })
132
133  // A new process cannot tell which of a repo's sessions it continues, so it lists them and the person picks.
134  on('classic.SessionStart', { source: 'startup' }, async ($, e, next) => {
135    const result = await next(e)
136    const now = await $.clock.now()
137    for (const { key, handover } of await entries($)) {
138      if (!isFresh(handover, now)) {
139        await remove($, key)
140      }
141    }
142    const here = await choicesHere($)
143    await update($, choices, () => (here.length > 0 ? here.map(c => c.handover.text) : null))
144    return result
145  })
146
147  on('prompt.submit', async ($, e, next) => {
148    if (offered !== null) {
149      const key = offered
150      offered = null
151      await remove($, key)
152    }
153    const pasted = (await entries($)).filter(({ handover }) => isPastedIn(e.text, handover.text))
154    for (const { key } of pasted) {
155      await remove($, key)
156    }
157    if (pasted.length > 0) {
158      await relist($)
159    }
160    return next(e)
161  })
162
163  on('session.start', async ($, e, next) => {
164    await $.command.register({ name: COPY_COMMAND, description: 'Copy the handover sentence and hide its band' })
165    await $.command.register({ name: PICK_COMMAND, description: 'List the handovers for this repo (or folder, outside a repo); /handover N puts one in the prompt, /handover drop N removes it' })
166    return next(e)
167  })
168
169  // A band's buttons take a press only once it holds focus, so copying is a command typed at the prompt.
170  on('command.run', { command: COPY_COMMAND }, async $ => {
171    const text = await read($, pending) ?? ((await $.store.get(storeKey(await $.session.id()))) as Handover | undefined)?.text
172    if (!text) {
173      return { text: 'No handover sentence yet.' }
174    }
175    const copied = await $.ui.copy({ text })
176    if (!copied.isCopied) {
177      return { text: `Not copied: ${copied.reason}` }
178    }
179    await update($, pending, () => null)
180    return { text: 'Handover copied.' }
181  })
182
183  on('command.run', { command: PICK_COMMAND }, async ($, e) => {
184    const dropped = dropIndex(e.args)
185    const n = dropped ?? Number(e.args.trim())
186    const here = e.args.trim() === '' || listed.length === 0 ? await choicesHere($) : listed
187    const chosen = Number.isInteger(n) ? here[n - 1] : undefined
188    if (here.length === 0) {
189      return { text: 'No handover for this repo or folder.' }
190    }
191    if (dropped !== null && chosen !== undefined) {
192      await remove($, chosen.key)
193      await relist($)
194      return { text: `Handover ${dropped} dropped.` }
195    }
196    if (chosen === undefined) {
197      await update($, choices, shown => (shown === null ? null : here.map(c => c.handover.text)))
198      return { text: here.map((c, i) => `${i + 1}. ${c.handover.text}`).join('\n\n') }
199    }
200    await update($, choices, () => null)
201    suggest($, chosen.key, chosen.handover.text)
202    return { text: `Handover ${n} waits in the prompt; Tab takes it.` }
203  })
204
205  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
206    const text = await read($, pending)
207    const listed = await read($, choices)
208    const band = await next(e)
209    if ((text === null && listed === null) || e.props.hasSurvey) {
210      return band
211    }
212    const { Box, Text } = $.ui.resolve(e)
213    return (
214      <Box flexDirection="column">
215        {band}
216        {text !== null && (
217          <Box flexDirection="column" paddingX={1} borderStyle="round" borderColor="cyan">
218            <Box>
219              <Text color="cyan" bold>handover </Text>
220              <Text dimColor>/{COPY_COMMAND} to copy · /clear, then Tab</Text>
221            </Box>
222            <Text>{text}</Text>
223          </Box>
224        )}
225        {listed !== null && (
226          <Box flexDirection="column" paddingX={1} borderStyle="round" borderColor="cyan">
227            <Box>
228              <Text color="cyan" bold>handovers here </Text>
229              <Text dimColor>/{PICK_COMMAND} N puts one in the prompt · /{PICK_COMMAND} drop N removes it</Text>
230            </Box>
231            {listed.map((t, i) => (
232              <Text key={String(i)}>{`${i + 1}. ${preview(t)}`}</Text>
233            ))}
234          </Box>
235        )}
236      </Box>
237    )
238  })
239}
240
hooks/rules.ts 65 lines
1import type { Handover } from '../types'
2
3export const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000
4
5const KEY_PREFIX = 'handover:'
6
7// The path the skill writes; each session's sentence then lands in a file of its own.
8export function handoverPath(home: string): string {
9  return `${home}/.claude/handover.md`
10}
11
12export function expandHome(path: string, home: string): string {
13  return path === '~' || path.startsWith('~/') ? `${home}${path.slice(1)}` : path
14}
15
16export function sessionPath(home: string, sessionId: string): string {
17  return `${home}/.claude/handovers/${sessionId}.md`
18}
19
20export function storeKey(sessionId: string): string {
21  return `${KEY_PREFIX}${sessionId}`
22}
23
24export function sessionIdOf(key: string): string | null {
25  return key.startsWith(KEY_PREFIX) ? key.slice(KEY_PREFIX.length) : null
26}
27
28// A sentence from another day may describe work since redone; two weeks is the cut.
29export function isFresh(handover: Handover | undefined, now: number): handover is Handover {
30  return handover !== undefined && handover.text !== '' && now - handover.at < MAX_AGE_MS
31}
32
33export type Entry = { key: string; handover: Handover }
34
35export function choicesFor(entries: readonly Entry[], root: string, now: number): Entry[] {
36  return entries
37    .filter(({ handover }) => isFresh(handover, now) && handover.root === root)
38    .sort((a, b) => b.handover.at - a.handover.at)
39}
40
41export function dirOf(path: string): string {
42  const cut = path.lastIndexOf('/')
43  return cut > 0 ? path.slice(0, cut) : '/'
44}
45
46const oneLine = (text: string): string => text.trim().replace(/\s+/g, ' ')
47
48// A sentence pasted by hand is spent like one taken with Tab, however the terminal rewrapped it.
49export function isPastedIn(prompt: string, sentence: string): boolean {
50  return sentence !== '' && oneLine(prompt).includes(oneLine(sentence))
51}
52
53// `/handover drop N` names an entry of the list; anything else is a pick or a listing.
54export function dropIndex(args: string): number | null {
55  const match = /^drop\s+([1-9]\d*)$/.exec(args.trim())
56  return match === null ? null : Number(match[1])
57}
58
59// The skill writes the sentence alone; a quote marker or surrounding blank lines are not part of it.
60// A leading `!` (a GitLab MR ref) would send the pasted prompt to bash, so it gets a word in front.
61export function sentenceOf(content: string): string {
62  const sentence = content.trim().replace(/^>\s?/gm, '').replace(/\s*\n\s*/g, ' ')
63  return sentence.startsWith('!') ? `MR ${sentence}` : sentence
64}
65
types/index.d.ts 8 lines
1export type Handover = { text: string; at: number; root: string }
2
3declare module 'claude-code' {
4  interface PluginState {
5    handover: { pending: string | null; choices: string[] | null; lastEdit: string | null }
6  }
7}
8