SLOPSHOPPER

bead-chime

Plays a short chime when a Bash call that ran bd close (or bd done) ends with exit code 0. It reads only the command text and the result, and runs no program.

newguardaudio
★ 1v0.5.1MITupdated 2026-10-06baselane-sh/mods/plugins/bead-chime
A shopper browsing a rack in a slop shop
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 7 lines
1import type { Register } from 'claude-code'
2
3import { registerSounds } from './engine'
4import { rule as beadChime } from './rules/bead-chime'
5
6export const register: Register = (on, options) => registerSounds(on, [beadChime], options)
7
hooks/engine.ts 83 lines
1import type { On, PluginOptions } from 'claude-code'
2
3import { closesBead } from './bead'
4import { TEST_RUNNER } from './runner'
5
6// The sounds of a rule, as paths inside the plugin folder. A pack names the
7// first four; a rule that plays for one event names only that one, and the
8// events it leaves out stay silent.
9export type Clips = {
10  testPass?: string
11  testFail?: string
12  denied?: string
13  turnDone?: string
14  beadClosed?: string
15}
16
17// One sound rule: it maps each event to a file under assets/<id>/.
18export type SoundRule = { id: string; clips: Clips }
19
20// The plugin's userConfig values, checked. `gain` is $.audio.play's linear
21// gain (0 to 4).
22export type Settings = { gain: number; quiet: boolean }
23
24const DEFAULT_GAIN = 1
25const MAX_GAIN = 4
26
27export const settingsFrom = (options: PluginOptions): Settings => {
28  const volume = options['volume']
29  const valid = typeof volume === 'number' && Number.isFinite(volume) && volume >= 0
30  return { gain: valid ? Math.min(volume, MAX_GAIN) : DEFAULT_GAIN, quiet: options['quiet'] === true }
31}
32
33const failed = (id: string, error: unknown): string =>
34  `${id}: no sound, ${error instanceof Error ? error.message : String(error)}`
35
36type Play = (asset: string) => Promise<void>
37
38// A clip that cannot play is logged and dropped: a sound never changes what
39// a tool call or a turn does. `audio` is a closure over the hook's `$`.
40export const playAll = async (
41  rules: readonly SoundRule[],
42  pick: (clips: Clips) => string | undefined,
43  audio: Play,
44  log: (text: string) => unknown,
45): Promise<void> => {
46  for (const rule of rules) {
47    try {
48      const clip = pick(rule.clips)
49      if (clip !== undefined) await audio(clip)
50    } catch (error) {
51      await log(failed(rule.id, error))
52    }
53  }
54}
55
56// The events a finished tool call stands for, as the clip each one plays.
57const picksFor = (e: { tool: string; command?: string }, ran: { deny?: string; isError?: boolean }): ((clips: Clips) => string | undefined)[] => {
58  if (ran.deny !== undefined) return [clips => clips.denied]
59  if (e.tool !== 'Bash' || e.command === undefined) return []
60  const picks: ((clips: Clips) => string | undefined)[] = []
61  if (TEST_RUNNER.test(e.command)) picks.push(ran.isError === true ? clips => clips.testFail : clips => clips.testPass)
62  // Only a close that ended with exit 0 chimes.
63  if (ran.isError !== true && closesBead(e.command)) picks.push(clips => clips.beadClosed)
64  return picks
65}
66
67// The sound registration shared by every sound mod: what a tool call plays.
68// The turn-end sound is a host (hosts/turn.ts), so a mod without one does not
69// list the hook.
70export const registerSounds = (on: On, rules: readonly SoundRule[], options: PluginOptions): void => {
71  const { gain } = settingsFrom(options)
72  // Gain 0 is silence: skip the call rather than start a muted player.
73  if (gain === 0) return
74
75  on('tool.call', async ($, e, next) => {
76    const ran = await next(e)
77    for (const pick of picksFor(e, ran)) {
78      await playAll(rules, pick, asset => $.audio.play({ asset }, { gain }), text => $.ui.log(text))
79    }
80    return ran
81  })
82}
83
hooks/rules/bead-chime.ts 9 lines
1import type { SoundRule } from '../engine'
2
3// One chime, for one event: a `bd close` (or `bd done`) that ended with exit 0.
4// The bell is the zen pack's pass bell, copied (a rule's assets are its own).
5export const rule: SoundRule = {
6  id: 'bead-chime',
7  clips: { beadClosed: 'assets/bead-chime/chime.wav' },
8}
9
hooks/bead.ts 94 lines
1// Says whether a Bash command line closes a bead: some command in it is
2// `bd close` or `bd done` (the alias), run for real. It only reads the text;
3// it never runs anything. The sound and stats engines each keep their own
4// copy of this file (a mod may import only its own files), and a test in each
5// holds the same table.
6//
7// Quoted text is one word, so `echo "bd close x"` is an echo. A command that
8// is written inside a string for another shell (`bash -c "bd close x"`) is
9// not seen. The caller checks the exit code: a line that ends with exit 0
10// but hid a failed close (`bd close x || true`) still counts, a limit of
11// reading only the text.
12
13// bd's global flags that take a value as the next word (`--flag=value` is one word).
14const VALUE_FLAGS = new Set(['-C', '--directory', '--actor', '--db', '--dolt-auto-commit'])
15// Words that may stand before a command and leave it the same command.
16const PREFIXES = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', 'time', 'command', 'exec', 'nohup', 'sudo', 'env'])
17const CLOSERS = new Set(['close', 'done'])
18const HEREDOC = /<<-?\s*(['"]?)([A-Za-z_][\w-]*)\1/g
19
20const withoutHeredocs = (command: string): string => {
21  const lines = command.split('\n')
22  const kept: string[] = []
23  let ends: string | undefined
24  for (const line of lines) {
25    if (ends !== undefined) {
26      if (line.trim() === ends) ends = undefined
27      continue
28    }
29    kept.push(line)
30    const match = [...line.matchAll(HEREDOC)].at(-1)
31    if (match !== undefined) ends = match[2]
32  }
33  return kept.join('\n')
34}
35
36// The commands of a line as lists of words. Quotes group a word and are
37// dropped; `;`, `&`, `|`, a newline and a parenthesis or brace end a command.
38const commandsOf = (line: string): string[][] => {
39  const commands: string[][] = []
40  let words: string[] = []
41  let word = ''
42  let inWord = false
43  let quote: '"' | "'" | undefined
44  const endWord = () => {
45    if (inWord) words = [...words, word]
46    word = ''
47    inWord = false
48  }
49  const endCommand = () => {
50    endWord()
51    if (words.length > 0) commands.push(words)
52    words = []
53  }
54  for (let i = 0; i < line.length; i += 1) {
55    const ch = line.charAt(i)
56    if (quote !== undefined) {
57      if (ch === quote) quote = undefined
58      else if (ch === '\\' && quote === '"' && i + 1 < line.length) word += line.charAt(++i)
59      else word += ch
60    } else if (ch === '"' || ch === "'") {
61      quote = ch
62      inWord = true
63    } else if (ch === '\\' && i + 1 < line.length) {
64      word += line.charAt(++i)
65      inWord = true
66    } else if (ch === ' ' || ch === '\t') endWord()
67    else if (';&|\n(){}`'.includes(ch)) endCommand()
68    else {
69      word += ch
70      inWord = true
71    }
72  }
73  endCommand()
74  return commands
75}
76
77const isBd = (word: string): boolean => word === 'bd' || word.endsWith('/bd')
78
79const closes = (words: readonly string[]): boolean => {
80  let i = 0
81  // Leading words that do not change the command: keywords, wrappers, NAME=value.
82  while (i < words.length && (PREFIXES.has(words[i] ?? '') || /^[A-Za-z_]\w*=/.test(words[i] ?? ''))) i += 1
83  if (!isBd(words[i] ?? '')) return false
84  i += 1
85  while (i < words.length && (words[i] ?? '').startsWith('-')) {
86    i += VALUE_FLAGS.has(words[i] ?? '') ? 2 : 1
87  }
88  if (!CLOSERS.has(words[i] ?? '')) return false
89  // Help and a read-only run change nothing.
90  return !words.some(word => word === '-h' || word === '--help' || word === '--readonly')
91}
92
93export const closesBead = (command: string): boolean => commandsOf(withoutHeredocs(command)).some(closes)
94
hooks/runner.ts 8 lines
1// Test runners count only in command position, so `cat jest.config.js` or
2// `grep vitest` never count as a test run. Copied from the nudge engine's
3// test-reminder rule: a mod may import only its own files.
4const START = '(^|[;&|] *)((npx|bunx|pnpm exec|yarn|uv run|poetry run|bundle exec) +)?'
5const RUNNERS =
6  '((npm|pnpm|yarn|bun) +(run +)?test|vitest|jest|mocha|pytest|python3? +-m +(pytest|unittest)|go +test|cargo +test|rspec|phpunit|mvn +(test|verify)|gradle +test|dotnet +test|ctest|make +(test|check)|bash +tests?/run\\.sh|tests?/run\\.sh|claude +plugin +test)'
7export const TEST_RUNNER = new RegExp(`${START}${RUNNERS}( |$)`, 'm')
8