SLOPSHOPPER

clippy

One helpful toast per session per trigger, in the classic paperclip voice: when you edit a migrations folder, a Dockerfile or a GitHub workflow, or run rm -rf…

newguardtoast
★ 1v0.5.1MITupdated 2026-10-06baselane-sh/mods/plugins/clippy
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · clippy
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ clippy │ ⏺ Read(src/auth.ts) │ clippy: It looks like you're deleting │ ⎿ Read 6 lines │ files with rm -rf. Want me to point out │ ⏺ Update(src/auth.ts) │ that there is no undo? The guard will ask │ ⎿ 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 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Baselane mods

Small mods for Claude Code. Pick the ones you want and combine them.

Baselane mods are Claude Code plugins made of function hooks. Each mod does one thing: a guard that asks before rm -rf, a band with the session cost, a side pane with your git status, a sound when tests pass, a pirate voice for Claude's prose. There are 100+ mods in families such as guards, panes, meters, sounds and stats. Install one, or stack ten. They do not need each other.

Quick start (30 seconds)

You need Claude Code 2.1.288 or later, with mods.

claude plugin marketplace add baselane-sh/mods-catalog
claude plugin install guard-essentials@baselane-mods
claude plugin install receipt@baselane-mods

Start Claude Code. Now it asks before harsh commands, and /receipt prints a receipt of the session.

Browse every mod at https://baselane-sh.github.io/mods-catalog/. The gallery (baselane-mods) pins each mod to a reviewed commit, so a new mod reaches the gallery a short time after it reaches this repo. For update, uninstall, options and starter sets, read docs/INSTALL.md.

This repo also has a development marketplace, baselane-mods-dev, that tracks main. Use it only to try changes that are not released yet:

claude plugin marketplace add baselane-sh/mods
claude plugin install <name>@baselane-mods-dev

Each mod is released with a git tag <name>--v<version>.

How packs work

Most mods have one rule. A pack is one mod with several rules from the same family. For example, guard-essentials holds several guards and band-pack puts several meters in one band.

  • Install a pack when you want the whole set with one command.
  • Install single mods when you want only some of the rules.
  • Install a pack or its single mods, not both. Each mod has its own copy of its engine, so a rule in two installed mods runs two times. For example, with guard-pack and infra-guard installed, the terraform destroy check runs two times, and you can see two questions.
  • Mods from different families combine with no conflict. guard-essentials, cost-meter and git-pane work well together.

The catalog below marks each pack with "pack".

Beads mods

Beads (bd) is an issue tracker that lives in your repo. 19 mods show your beads in Claude Code: bars above the prompt, panes, slash commands, a guard and reminders. They need bd 1.2 or later and a repo with a .beads folder. Without these, they do nothing.

The core set in one go (the bars, the panes, /ready and the guard):

claude plugin install beads-bars@baselane-mods
claude plugin install beads-pane@baselane-mods
claude plugin install epics-pane@baselane-mods
claude plugin install ready@baselane-mods
claude plugin install beads-guard@baselane-mods

Each beads mod is also in the catalog below, in its family.

Safety

  • Guards ask. They do not block. A guard stops a harsh command and asks you first. You decide. If a guard check fails, it asks you. It does not let the call through without a question.
  • Your data stays on your machine. No mod sends data out unless you set a destination yourself, such as an ntfy topic for ntfy-notify or long-run-notify, or a webhook URL for slack-notify or discord-notify. With a destination set, those mods send a short message only: a generic "needs input" text with the project folder name, or the project name and the seconds. One exception needs no setup: ci-band and ops-band ask GitHub, through your own gh login, for the latest Actions run of your branch every 2 minutes, sending the repository and branch name. Without gh, or with gh not logged in, they do nothing.
  • One mod can make a model call, and it is off by default. sports-narrator makes one small model call at the end of a turn that used tools. It sends tool names, file names and the first two words of each shell command, never file contents. It spends tokens, so you must turn it on.
  • Beads mods only read your beads. They run read commands of your own bd on your machine, such as bd status --json and bd ready --json. No beads mod creates, changes or closes a bead. beads-guard asks before a bd command that deletes or rewrites beads.
  • Display mods do not change what Claude reads. The mods in "Display and render" change only how rows and replies look on your screen. Other families can add text for Claude: prompt styles change how Claude writes, secret-output-guard tells Claude not to repeat a credential, auto-format and auto-lint tell Claude to read a file again, beads-prime adds the workflow text that bd prime prints from your repo's .beads files, and bead-claim-nudge and bead-commit-nudge add a one-line reminder at your next prompt.
  • Stats stay local. Streaks, achievements and /wrapped read records that the mods keep on your machine.
  • Mods that write files say so. /handoff writes .claude/handoff.md and never overwrites it. session-journal appends to ~/.claude/journal.log. auto-format and auto-lint run your project's own formatter or linter fix, which can rewrite files. The descriptions say what each mod writes.

Requirements

  • Claude Code 2.1.288 or later, with mods (the plugin function-hook API, in early access). Read the Claude Code mods docs.
  • Some mods use local tools: git for the git pane, the git band and most commands, lsof for port-watch, gh for ci-band, bd 1.2 or later for the beads mods, ps for process-pane, and on macOS pmset for battery-band and pgrep with osascript for now-playing.
  • To build from source: Node.js.

Build and check from source

plugins/ and .claude-plugin/marketplace.json are generated. Do not edit them by hand.

node scripts/build.mjs          # build one plugin folder per catalog entry
bash scripts/check.sh           # rebuild, then validate, test and type-check every mod
bash scripts/check.sh git-pane  # check only the mods you name
node scripts/gen-docs.mjs       # rewrite the catalog in this README
node --test 'scripts/*.test.mjs'  # test the docs generator

A change is done when check.sh prints check: 0 failure(s). Read AGENTS.md for the layout and the API facts.

Contributing

To add a mod:

  1. Add a rule to an engine: engines/<engine>/hooks/rules/<id>.ts, with a test in engines/<engine>/tests/<id>.test.ts.
  2. Add a catalog entry in catalog/<name>.json: { "name", "description", "rules": ["<id>"] }. Give the description the slash command, if the mod has one (for example "Open it with /git"). The catalog table reads it from there.
  3. Run node scripts/build.mjs, then bash scripts/check.sh <mod>, then node scripts/gen-docs.mjs.

A new engine needs a family in scripts/gen-docs.mjs. Keep files small, do not change inputs in place, and do not use the em-dash character.

Licence

MIT. Copyright (c) 2026 Baselane, LLC. Read LICENSE.

Catalog

<!-- catalog:start -->

199 mods in 10 families.

"needs setup" means the mod has options that you set with claude plugin configure <mod>. Its description tells you if it works before you set them. "pack" means one mod with several rules.

Guards (36)

Ask you before a harsh or risky command runs.

ModWhat it doesCommandNotes
beads-guardAsks before bd commands that delete data or rewrite history: delete, purge, prune, gc, sql, admin, import, rename, forget, restore, migrate and more. Reads only the command text, runs no bd.
secret-filename-guardAsks before a Bash command touches a secret-looking file (.env, private keys, credentials).
secret-guardAsks before a live API key, token or private key is written, edited or run.
env-exfil-guardAsks before a command prints your environment, echoes a secret variable or sends local data to a remote host.
infra-guardAsks before terraform destroy, kubectl delete, force-push, DROP TABLE or rm -rf.
secret-commit-guardAsks before a git commit that would record a credential or a secret-named file. Reads the staged diff with git.
protect-mainAsks before a commit, push or merge while you are on main or master. Reads the branch with git.
gitignore-checkAsks before git add or commit when secret-looking files are not ignored or are already tracked. Checks with git ls-files.
secret-output-guardTells Claude not to repeat a credential that showed up in command or file output, and names the source to rotate.
curl-pipe-guardAsks before a download is piped into a shell or interpreter (curl \sh, wget -O- \bash, bash <(curl ...)).
sudo-guardAsks before sudo, doas or su -c runs a command with elevated rights.
no-verify-guardAsks before git hooks are skipped (--no-verify, commit -n, HUSKY=0, core.hooksPath=/dev/null).
lockfile-guardAsks before a lockfile is written or edited by hand; the package manager should change it.
package-guardAsks before a new dependency is installed (npm, pnpm, yarn, bun, pip, uv, poetry, cargo, go, gem) and names the packages.
prod-db-guardAsks before destructive SQL runs in a command: TRUNCATE, DELETE or UPDATE with no WHERE.
path-jailAsks before Write, Edit or NotebookEdit changes a file outside the working directory, by real path.
docker-guardAsks before Docker commands that delete data: system, volume or image prune, rm -f, volume rm and compose down -v.
k8s-guardAsks before kubectl apply or replace with --force, kubectl drain, helm uninstall, and kubectl delete behind global flags (plain kubectl delete is infra-guard's).
migration-guardAsks before Write or Edit changes a migration that already exists; new migration files pass.
ci-config-guardAsks before Write or Edit changes CI config: .github/workflows, .gitlab-ci.yml or .circleci/config.yml.
chmod-guardAsks before chmod makes files world-writable (777, a+w, o+w) or chmod or chown runs recursively on a broad path (/, a system folder, a home folder).
git-history-guardAsks before git commands that throw away work or rewrite history: reset --hard, clean, rebase, filter-branch, filter-repo, push --delete, branch -D and stash clear.
big-file-guardAsks before a Write creates content over 1 MB, or git add names a file over 5 MB. Measures the files with find.
publish-guardAsks before a package is published: npm, pnpm, yarn or bun publish, cargo publish, twine upload, gem push, poetry or uv publish. Dry runs pass.
tag-guardAsks before release tags go to a remote: git push --tags, --follow-tags or --mirror, a push of a tag ref, and a push that deletes a remote tag. Dry runs pass. Reads tags with git.
deploy-guardAsks before a production deploy: vercel --prod, netlify deploy --prod, firebase deploy, fly deploy, gcloud app deploy, eb deploy, heroku rollback, serverless deploy to prod.
db-reset-guardAsks before a framework wipes a database: prisma migrate reset, rails or rake db:drop and db:reset, alembic downgrade, django flush, supabase db reset, knex rollback --all.
ssh-guardAsks before a private key in .ssh is read, authorized_keys or the SSH config is changed, or ssh-keygen would overwrite a key. Public keys and ssh -i pass. Reads HOME with printenv.
cron-guardAsks before scheduled jobs or services are wiped or stopped: crontab -r, crontab replaced from stdin or a file, launchctl unload or bootout, systemctl stop, disable or mask.
upload-guardAsks before local files go to a remote host: scp or rsync to host:path, piped input to nc, curl -T, sftp put. Local copies, downloads and localhost pass.
registry-push-guardAsks before an image or chart is pushed to a registry: docker push, docker buildx --push, podman push, helm push, gcloud artifacts docker push. Local registries pass.
guard-essentialsAsks only before harsh or disaster commands: destructive infra, git and SQL, piping downloads into a shell, sudo, leaking or committing secrets. Reads git. The quiet choice for daily work.pack
guard-packThe 15 core Baselane guards in one mod (secrets, git, infra, packages, path jail). Some read git, measure files with find, read HOME with printenv, or check where a path really lands.pack
guard-devopsAsks before harsh DevOps commands: destructive Docker, Kubernetes and Helm calls, CI config edits, broad chmod and chown, and git commands that lose work. Add infra-guard for plain kubectl delete.pack
release-packAsks before a release leaves your machine: package publish, tag push, production deploy and registry push guards in one mod. The tag guard reads tags with git.pack
ship-safe-packThe release-pack guards plus db-reset-guard and upload-guard: asks before publish, tag push, production deploy, registry push, database wipes and file uploads. Reads tags with git.pack

Reminders (19)

One quiet toast at turn end when something needs your attention.

ModWhat it doesCommandNotes
bead-claim-nudgeAt turn end, if Claude edited a file and no bead is in progress, shows a toast and reminds Claude at your next prompt, once per session. Reads with bd count; quiet without bd.
bead-commit-nudgeAt turn end, if a git commit named no bead id while a bead is in progress, shows a toast and reminds Claude at your next prompt. Reads with bd count and bd where; quiet without bd.
test-reminderReminds you at turn end when source files changed but no test command ran since.
ctx-nudgeReminds you to /clear or /compact when the context window passes 75 percent.
clippyOne helpful toast per session per trigger, in the classic paperclip voice: when you edit a migrations folder, a Dockerfile or a GitHub workflow, or run rm -rf. At most one toast per turn.
sports-narratorOne line of sports play-by-play at turn end. OFF by default: one haiku call per turn with tools. Turn on the enabled option. Sends tool names, file names and the first two words of each command.needs setup
commit-nudgeSuggests a commit at turn end after 8 or more file edits since the last git commit. One toast per batch of edits; a successful git commit resets the count.
todo-nudgeAt turn end, one toast with the count of TODO, FIXME and HACK lines your edits added this turn. Quiet when none were added.
break-nudgeSuggests a short break once the session has run 90 minutes, and again every 90 minutes after that.
docs-nudgeAt turn end, one toast when edits added exported code (an export statement in .ts or .js, or a public function signature) and no README or docs file was edited this session.
debug-print-nudgeAt turn end, one toast naming the count of console.log, print(, debugger and dbg! lines your edits added this turn. Only code files count.
typecheck-nudgeAt turn end, one toast when .ts or .tsx files were edited and no type check (tsc, vue-tsc, a typecheck script or a build) ran since the last edit.
lockfile-nudgeAt turn end, one toast when dependencies in package.json, pyproject.toml, Cargo.toml or go.mod changed and neither the matching lockfile was edited nor an install command ran.
big-diff-nudgeSuggests splitting the change once your edits added or removed more than 500 lines since the last git commit. A successful commit resets the count.
migration-nudgeAt turn end, one toast when a schema file changed (schema.prisma, models.py, SQL under schema/, a drizzle schema) and no migration file was created this session.
env-example-nudgeAt turn end, one toast when edits add a reference to an environment variable (process.env, os.environ, os.getenv, Deno.env) that .env.example does not list. Reads only .env.example names, never .env.
nudge-packTwo turn-end reminders in one mod: test-reminder and ctx-nudge.pack
focus-packThree quiet nudges in one mod: commit after 8 edits, TODO/FIXME/HACK lines added, and debug prints added.pack
quality-packThree quiet nudges in one mod: type check after TypeScript edits, lockfile after dependency edits, and a split suggestion past 500 changed lines.pack

Commands (31)

Slash commands that print a result and, where it helps, copy it.

ModWhat it doesCommandNotes
readyAdds /ready: the 20 top ready beads, one line each, and the total. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./ready
beadAdds /bead <id>: one bead with status, priority, labels, description, blockers and children. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./bead
beads-standupAdds /beads-standup: beads closed since yesterday, in progress, and the next 5 ready. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./beads-standup
receiptAdds /receipt: a shareable receipt of the session (tools, files, commands, blocks, context, cost), printed and copied./receipt
standupAdds /standup: Yesterday, Today and Blockers from your git log and this session's record, printed and copied./standup
changelogAdds /changelog: commits since the last tag (or the last 30), read with git log and grouped by conventional-commit type, as Markdown. Copies the result to your clipboard./changelog
pr-descriptionAdds /pr-description: title, summary, diff totals and a test plan stub for the current branch against main or master, read with git. Copies the result to your clipboard./pr-description
handoffAdds /handoff: writes a session summary with the git status to .claude/handoff.md (never overwriting) and answers with the path. Copies the result to your clipboard./handoff
todosAdds /todos: TODO, FIXME and HACK lines in tracked files, found with git grep, grouped by file (50 lines at most). Read-only. Copies the result to your clipboard./todos
locAdds /loc: lines of tracked text files by language, read with git, sorted, with a total. Skips lockfiles and binaries. Read-only. Copies the result to your clipboard./loc
hotspotsAdds /hotspots: the 10 files changed most often in the last 90 days, from git log, with change counts. Read-only. Copies the result to your clipboard./hotspots
commit-msgAdds /commit-msg: a Conventional Commits message proposed from the staged diff, read with git. Heuristic, no model call, writes nothing. Copies the result to your clipboard./commit-msg
branchesAdds /branches: local branches merged into the default branch or idle for 30 days, as a cleanup list, read with git. Never deletes. Copies the result to your clipboard./branches
treeAdds /tree: tracked files (git ls-files) as a tree, 2 levels deep, folders with file counts (80 lines at most). Read-only. Copies the result to your clipboard./tree
depsAdds /deps: direct dependencies with versions from package.json, pyproject.toml, requirements.txt, go.mod and Cargo.toml at the repo root. No network. Read-only. Copies the result to your clipboard./deps
authorsAdds /authors: the top 15 contributors by commit count with their last commit date, from git log. Names only, never email addresses. Read-only. Copies the result to your clipboard./authors
scriptsAdds /scripts: runnable tasks from package.json scripts, Makefile targets, justfile recipes and pyproject scripts at the git repo root. Read-only. Copies the result to your clipboard./scripts
env-checkAdds /env-check: variable names in .env.example against .env at the git repo root, listing missing and extra names. Reads names only, never a value. Read-only. Copies the result to your clipboard./env-check
sizeAdds /size: the 15 largest tracked files and the total tracked size at HEAD, read with git. Read-only. Copies the result to your clipboard./size
licensesAdds /licenses: the licence of each direct dependency, from node_modules and Python dist-info at the git repo root. Shows unknown when it cannot tell. Read-only. Copies the result to your clipboard./licenses
conflictsAdds /conflicts: tracked files that still hold merge conflict markers, with line numbers, found with git grep. Read-only. Copies the result to your clipboard./conflicts
secret-scanAdds /secret-scan: tracked files and line numbers that hold secret-shaped text, found with git grep. Never prints a matched value. Read-only. Copies the result to your clipboard./secret-scan
envinfoAdds /envinfo: versions of git, node, npm, python3, go, rustc and docker if installed, by running each (2 s limit), and the OS. Read-only. Copies the result to your clipboard./envinfo
stashesAdds /stashes: git stashes with their age and the branch each was made on. Read-only, never applies or drops. Copies the result to your clipboard./stashes
recentAdds /recent: your last 15 commits across all local branches (author is git user.name), with branch and date. Read-only. Copies the result to your clipboard./recent
file-ownersAdds /owners <path>: the top 5 authors of a file or folder by lines, from git blame. Names only, never addresses. Read-only. Copies the result to your clipboard./owners
readme-checkAdds /readme-check: missing README sections (install, usage, licence, contributing) and broken relative links, at the git repo root. Read-only. Copies the result to your clipboard./readme-check
command-packThe five original slash commands in one mod: /receipt, /standup, /changelog, /pr-description and /handoff. They read git; /handoff also writes .claude/handoff.md. They copy results to the clipboard./receipt, /standup, /changelog, /pr-description, /handoffpack
repo-packFive read-only repo commands in one mod: /todos, /loc, /hotspots, /commit-msg and /branches. They read git. They copy results to the clipboard./todos, /loc, /hotspots, /commit-msg, /branchespack
explore-packFive read-only repo exploration commands in one mod: /tree, /deps, /authors, /scripts and /env-check. They read git and project files. They copy results to the clipboard./tree, /deps, /authors, /scripts, /env-checkpack
audit-packThree read-only audit commands in one mod: /secret-scan, /conflicts and /licenses. They read git, project files and dependency folders. They copy results to the clipboard./secret-scan, /conflicts, /licensespack

Band meters (30)

A one-line band above the prompt.

ModWhat it doesCommandNotes
cost-meterA band above the prompt with the session cost so far and what the last turn cost.
latte-meterA band above the prompt that counts the session cost in lattes. Set the latte price in the plugin options.needs setup
context-meterA band above the prompt with a 10 cell bar of the context window used, yellow from 60 percent, red from 80.
daily-spendA band above the prompt with today's total cost across all your sessions.

| pomodoro | A band above the prompt with a 25/5 focus timer (focus 18:42, break 03:10). Start and stop it with /pomodoro; a to

Source 5 files
hooks/register.ts 14 lines
1import type { Register } from 'claude-code'
2
3import { createNotes } from './engine'
4import { observeCalls } from './hosts/observe'
5import { remindAtStop } from './hosts/stop'
6import { create as clippy } from './rules/clippy'
7
8export const register: Register = on => {
9  const rules = [clippy()]
10  const shared = createNotes()
11  observeCalls(on, rules)
12  remindAtStop(on, rules)
13}
14
hooks/engine.ts 121 lines
1import type { ModelCompleteRequest, ModelCompleteResult, PluginOptions, ProcessRunResult, ToolCallEnvelope, ToolCallResult } from 'claude-code'
2
3// What a nudge may read when the turn stops. The engine forbids passing `$`
4// itself, so it hands over these functions instead.
5export type NudgeTools = {
6  contextPercent: () => Promise<number | undefined>
7  // The host clock and the session start, both in milliseconds since the epoch.
8  now: () => Promise<number>
9  sessionStartedAt: () => Promise<number>
10  // The variable NAMES listed in `.env.example` (never values, never `.env`),
11  // or undefined when the project has no `.env.example`.
12  envExampleNames: () => Promise<readonly string[] | undefined>
13  // One model call. It resolves with `isAnswered: false` instead of throwing
14  // when the model gives no text, so a nudge checks that before it speaks.
15  complete: (request: ModelCompleteRequest) => Promise<ModelCompleteResult>
16  // Runs a program (argv only, no shell) in `cwd`, with a time limit. It
17  // rejects when the program is missing or runs too long.
18  run: (argv: readonly string[], cwd: string) => Promise<ProcessRunResult>
19}
20
21export const RUN_TIMEOUT_MS = 10_000
22
23// One nudge: it may watch each tool call once the tool answered, and when
24// the turn stops it may name a one-line reminder for the person. The engine
25// shows each reminder as a toast. The model reads it only when the mod's host keeps it as a note for the next prompt (the bead nudges do; see PendingNotes). `options` are the
26// plugin's userConfig values, empty for a mod that declares none. `cwd` is
27// the session cwd ('' when the host gave none), for `repoPath`.
28export type Nudge = {
29  id: string
30  observe?: (e: ToolCallEnvelope, ran: ToolCallResult, cwd: string) => void
31  atStop: (tools: NudgeTools, options: PluginOptions) => string | undefined | Promise<string | undefined>
32}
33
34export const ENV_EXAMPLE = '.env.example'
35
36// Keeps only the NAME of each `NAME=value` line; the value is dropped here.
37export const envNames = (text: string): string[] =>
38  text.split('\n').flatMap(line => {
39    const name = /^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=/.exec(line)?.[1]
40    return name === undefined ? [] : [name]
41  })
42
43const failed = (id: string, error: unknown): string =>
44  `${id}: skipped, ${error instanceof Error ? error.message : String(error)}`
45
46// The tools a host does not give. A nudge that calls one is logged and
47// skipped, and its tests fail: name what it uses in engine.json `needs`.
48const absent = (name: string) => (): Promise<never> =>
49  Promise.reject(new Error(`${name} is not given to this mod; name it in engine.json needs`))
50
51export const NO_TOOLS: NudgeTools = {
52  contextPercent: absent('contextPercent'),
53  now: absent('now'),
54  sessionStartedAt: absent('sessionStartedAt'),
55  envExampleNames: absent('envExampleNames'),
56  complete: absent('complete'),
57  run: absent('run'),
58}
59
60// Reminders waiting for the person's next prompt, so Claude reads them too.
61// Made once per mod and shared by the turn-end host and the prompt host. A
62// note is fixed text, a count or an id that matched the id pattern, never a
63// title or commit text.
64export type PendingNotes = { add: (note: string) => void; take: () => readonly string[] }
65
66export const createNotes = (): PendingNotes => {
67  let pending: readonly string[] = []
68  return {
69    add: note => {
70      pending = [...pending, note]
71    },
72    take: () => {
73      const taken = pending
74      pending = []
75      return taken
76    },
77  }
78}
79
80// Hands each finished tool call to the nudges that watch them. `log` closes
81// over the hook's `$`.
82export const observeAll = async (
83  nudges: readonly Nudge[],
84  e: ToolCallEnvelope,
85  ran: ToolCallResult,
86  cwd: string,
87  log: (text: string) => unknown,
88): Promise<void> => {
89  for (const nudge of nudges) {
90    try {
91      nudge.observe?.(e, ran, cwd)
92    } catch (error) {
93      await log(failed(nudge.id, error))
94    }
95  }
96}
97
98// Asks each nudge for its reminder as the turn stops and shows it as a toast.
99// `toast` and `log` close over the hook's `$`.
100export const remindAll = async (
101  nudges: readonly Nudge[],
102  tools: NudgeTools,
103  options: PluginOptions,
104  toast: (text: string) => unknown,
105  log: (text: string) => unknown,
106): Promise<readonly string[]> => {
107  let reminders: readonly string[] = []
108  for (const nudge of nudges) {
109    try {
110      const reminder = await nudge.atStop(tools, options)
111      if (reminder !== undefined) {
112        await toast(`${nudge.id}: ${reminder}`)
113        reminders = [...reminders, reminder]
114      }
115    } catch (error) {
116      await log(failed(nudge.id, error))
117    }
118  }
119  return reminders
120}
121
hooks/hosts/observe.ts 15 lines
1import type { On } from 'claude-code'
2
3import { observeAll } from '../engine'
4import type { Nudge } from '../engine'
5
6// For nudges with `observe`: each tool call, once the tool answered.
7export const observeCalls = (on: On, nudges: readonly Nudge[]): void => {
8  on('tool.call', async ($, e, next) => {
9    const ran = await next(e)
10    const cwd = await $.session.cwd().catch(() => '')
11    await observeAll(nudges, e, ran, cwd, text => $.ui.log(text))
12    return ran
13  })
14}
15
hooks/hosts/stop.ts 14 lines
1import type { On, PluginOptions } from 'claude-code'
2
3import { NO_TOOLS, remindAll } from '../engine'
4import type { Nudge } from '../engine'
5
6// The turn's end for nudges that read nothing but what they watched.
7export const remindAtStop = (on: On, nudges: readonly Nudge[], options: PluginOptions = {}): void => {
8  on('classic.Stop', async ($, e, next) => {
9    const tools = NO_TOOLS
10    await remindAll(nudges, tools, options, text => $.ui.toast(text), text => $.ui.log(text))
11    return next(e)
12  })
13}
14
hooks/rules/clippy.ts 73 lines
1import type { Nudge } from '../engine'
2
3type Trigger = 'migration' | 'dockerfile' | 'workflow' | 'rm-rf'
4
5// The classic paperclip: it looks like you're doing X, want help? Each line
6// is a comment, never a block: the guard decides about rm -rf, clippy only talks.
7export const LINES: Readonly<Record<Trigger, string>> = {
8  migration: "It looks like you're writing a migration. Want me to remind you to back up first?",
9  dockerfile:
10    "It looks like you're editing a Dockerfile. Would you like me to remind you to pin the base image and keep secrets out of the layers?",
11  workflow:
12    "It looks like you're editing a GitHub Actions workflow. Want a tip? Pin third-party actions to a commit SHA and give the job the least permissions it needs.",
13  'rm-rf':
14    "It looks like you're deleting files with rm -rf. Want me to point out that there is no undo? The guard will ask anyway; I'm just a paperclip.",
15}
16
17const FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
18
19const pathTrigger = (path: string): Trigger | undefined => {
20  const parts = path.split('/')
21  const name = parts.at(-1) ?? ''
22  if (/^dockerfile(\..+)?$/i.test(name) || /\.dockerfile$/i.test(name)) return 'dockerfile'
23  if (/(^|\/)\.github\/workflows\/./.test(path)) return 'workflow'
24  if (parts.slice(0, -1).some(part => part.toLowerCase() === 'migrations')) return 'migration'
25  return undefined
26}
27
28// `rm` in command position with both a recursive and a force flag, in any
29// spelling (-rf, -fr, -Rf, -r -f, --recursive --force). `git rm` and the word
30// in an argument do not count.
31export const isRmRf = (command: string): boolean =>
32  command.split(/[;&|\n]+/).some(part => {
33    const words = part.trim().split(/\s+/)
34    const start = words[0] === 'sudo' ? 1 : 0
35    if (words[start] !== 'rm') return false
36    const flags = words.slice(start + 1).filter(word => word.startsWith('-'))
37    const short = flags.filter(flag => !flag.startsWith('--')).join('')
38    const isRecursive = /[rR]/.test(short) || flags.includes('--recursive')
39    const isForce = /f/.test(short) || flags.includes('--force')
40    return isRecursive && isForce
41  })
42
43const triggerOf = (e: Parameters<NonNullable<Nudge['observe']>>[0]): Trigger | undefined => {
44  if (FILE_TOOLS.has(e.tool)) {
45    const path = 'file_path' in e ? e.file_path : 'notebook_path' in e ? e.notebook_path : undefined
46    return typeof path === 'string' ? pathTrigger(path) : undefined
47  }
48  return e.tool === 'Bash' && isRmRf(e.command) ? 'rm-rf' : undefined
49}
50
51// One toast per session per trigger. At most one per turn (a stop): when
52// several triggers fire in one turn the first speaks and the rest wait, in
53// order, for the next turn's stop.
54export const create = (): Nudge => {
55  const spoken = new Set<Trigger>()
56  let waiting: readonly Trigger[] = []
57
58  return {
59    id: 'clippy',
60    observe: e => {
61      const trigger = triggerOf(e)
62      if (trigger !== undefined && !spoken.has(trigger) && !waiting.includes(trigger)) waiting = [...waiting, trigger]
63    },
64    atStop: () => {
65      const [next, ...rest] = waiting
66      if (next === undefined) return undefined
67      waiting = rest
68      spoken.add(next)
69      return LINES[next]
70    },
71  }
72}
73