Edit and Write rows show a compact +12 -3 bar beside the file name: green for lines added, red for lines removed, up to 20 cells.

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.
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>.
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.
guard-pack and infra-guard installed, the terraform destroy check runs two times, and you can see two questions.guard-essentials, cost-meter and git-pane work well together.The catalog below marks each pack with "pack".
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.
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.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.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.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./wrapped read records that the mods keep on your machine./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.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.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.
To add a mod:
engines/<engine>/hooks/rules/<id>.ts, with a test in engines/<engine>/tests/<id>.test.ts.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.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.
MIT. Copyright (c) 2026 Baselane, LLC. Read LICENSE.
<!-- 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.
Ask you before a harsh or risky command runs.
| Mod | What it does | Command | Notes | ||
|---|---|---|---|---|---|
beads-guard | Asks 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-guard | Asks before a Bash command touches a secret-looking file (.env, private keys, credentials). | ||||
secret-guard | Asks before a live API key, token or private key is written, edited or run. | ||||
env-exfil-guard | Asks before a command prints your environment, echoes a secret variable or sends local data to a remote host. | ||||
infra-guard | Asks before terraform destroy, kubectl delete, force-push, DROP TABLE or rm -rf. | ||||
secret-commit-guard | Asks before a git commit that would record a credential or a secret-named file. Reads the staged diff with git. | ||||
protect-main | Asks before a commit, push or merge while you are on main or master. Reads the branch with git. | ||||
gitignore-check | Asks before git add or commit when secret-looking files are not ignored or are already tracked. Checks with git ls-files. | ||||
secret-output-guard | Tells Claude not to repeat a credential that showed up in command or file output, and names the source to rotate. | ||||
curl-pipe-guard | Asks before a download is piped into a shell or interpreter (curl \ | sh, wget -O- \ | bash, bash <(curl ...)). | ||
sudo-guard | Asks before sudo, doas or su -c runs a command with elevated rights. | ||||
no-verify-guard | Asks before git hooks are skipped (--no-verify, commit -n, HUSKY=0, core.hooksPath=/dev/null). | ||||
lockfile-guard | Asks before a lockfile is written or edited by hand; the package manager should change it. | ||||
package-guard | Asks before a new dependency is installed (npm, pnpm, yarn, bun, pip, uv, poetry, cargo, go, gem) and names the packages. | ||||
prod-db-guard | Asks before destructive SQL runs in a command: TRUNCATE, DELETE or UPDATE with no WHERE. | ||||
path-jail | Asks before Write, Edit or NotebookEdit changes a file outside the working directory, by real path. | ||||
docker-guard | Asks before Docker commands that delete data: system, volume or image prune, rm -f, volume rm and compose down -v. | ||||
k8s-guard | Asks 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-guard | Asks before Write or Edit changes a migration that already exists; new migration files pass. | ||||
ci-config-guard | Asks before Write or Edit changes CI config: .github/workflows, .gitlab-ci.yml or .circleci/config.yml. | ||||
chmod-guard | Asks 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-guard | Asks 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-guard | Asks before a Write creates content over 1 MB, or git add names a file over 5 MB. Measures the files with find. | ||||
publish-guard | Asks 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-guard | Asks 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-guard | Asks 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-guard | Asks 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-guard | Asks 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-guard | Asks 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-guard | Asks 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-guard | Asks 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-essentials | Asks 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-pack | The 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-devops | Asks 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-pack | Asks 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-pack | The 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 |
One quiet toast at turn end when something needs your attention.
| Mod | What it does | Command | Notes |
|---|---|---|---|
bead-claim-nudge | At 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-nudge | At 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-reminder | Reminds you at turn end when source files changed but no test command ran since. | ||
ctx-nudge | Reminds you to /clear or /compact when the context window passes 75 percent. | ||
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. At most one toast per turn. | ||
sports-narrator | One 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-nudge | Suggests 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-nudge | At turn end, one toast with the count of TODO, FIXME and HACK lines your edits added this turn. Quiet when none were added. | ||
break-nudge | Suggests a short break once the session has run 90 minutes, and again every 90 minutes after that. | ||
docs-nudge | At 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-nudge | At 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-nudge | At 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-nudge | At 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-nudge | Suggests 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-nudge | At 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-nudge | At 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-pack | Two turn-end reminders in one mod: test-reminder and ctx-nudge. | pack | |
focus-pack | Three quiet nudges in one mod: commit after 8 edits, TODO/FIXME/HACK lines added, and debug prints added. | pack | |
quality-pack | Three quiet nudges in one mod: type check after TypeScript edits, lockfile after dependency edits, and a split suggestion past 500 changed lines. | pack |
Slash commands that print a result and, where it helps, copy it.
| Mod | What it does | Command | Notes |
|---|---|---|---|
ready | Adds /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 | |
bead | Adds /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-standup | Adds /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 | |
receipt | Adds /receipt: a shareable receipt of the session (tools, files, commands, blocks, context, cost), printed and copied. | /receipt | |
standup | Adds /standup: Yesterday, Today and Blockers from your git log and this session's record, printed and copied. | /standup | |
changelog | Adds /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-description | Adds /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 | |
handoff | Adds /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 | |
todos | Adds /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 | |
loc | Adds /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 | |
hotspots | Adds /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-msg | Adds /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 | |
branches | Adds /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 | |
tree | Adds /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 | |
deps | Adds /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 | |
authors | Adds /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 | |
scripts | Adds /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-check | Adds /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 | |
size | Adds /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 | |
licenses | Adds /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 | |
conflicts | Adds /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-scan | Adds /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 | |
envinfo | Adds /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 | |
stashes | Adds /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 | |
recent | Adds /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-owners | Adds /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-check | Adds /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-pack | The 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, /handoff | pack |
repo-pack | Five 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, /branches | pack |
explore-pack | Five 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-check | pack |
audit-pack | Three 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, /licenses | pack |
A one-line band above the prompt.
| Mod | What it does | Command | Notes |
|---|---|---|---|
cost-meter | A band above the prompt with the session cost so far and what the last turn cost. | ||
latte-meter | A band above the prompt that counts the session cost in lattes. Set the latte price in the plugin options. | needs setup | |
context-meter | A band above the prompt with a 10 cell bar of the context window used, yellow from 60 percent, red from 80. | ||
daily-spend | A 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
hooks/register.ts 10 lines1import type { Register } from 'claude-code'
2
3import { drawToolRows } from './hosts/row'
4import { create as diffStats } from './rules/diff-stats'
5
6export const register: Register = on => {
7 const rules = [diffStats()]
8 drawToolRows(on, rules)
9}
10hooks/hosts/row.ts 19 lines1import type { On } from 'claude-code'
2
3import { drawToolRow, NO_ROW_READS } from '../engine'
4import type { RenderRule } from '../engine'
5
6// Tool rows for rules that draw from the row alone.
7export const drawToolRows = (on: On, rules: readonly RenderRule[]): void => {
8 for (const { id, toolRow } of rules) {
9 if (toolRow === undefined) continue
10 on('ui.render', { component: 'ToolUse' }, async ($, e, next) =>
11 drawToolRow(id, toolRow, e, next, {
12 ...NO_ROW_READS,
13 elements: () => $.ui.resolve(e),
14 log: text => $.ui.log(text),
15 }),
16 )
17 }
18}
19hooks/rules/diff-stats.ts 55 lines1import type { RenderElement } from 'claude-code'
2
3import { barCells, lineDiff } from '../diff'
4import type { DiffStats } from '../diff'
5import type { RenderRule } from '../engine'
6
7const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
8
9// From the call's input as the model sent it. Write's props carry no earlier
10// content, so a Write counts as all lines added and none removed.
11const statsOf = (tool: string, input: unknown): DiffStats | undefined => {
12 if (!isRecord(input)) return undefined
13 if (tool === 'Edit') {
14 const { old_string: before, new_string: after } = input
15 return typeof before === 'string' && typeof after === 'string' ? lineDiff(before, after) : undefined
16 }
17 if (tool === 'Write') {
18 const { content } = input
19 return typeof content === 'string' ? lineDiff('', content) : undefined
20 }
21 return undefined
22}
23
24export const create = (): RenderRule => ({
25 id: 'diff-stats',
26 toolRow: {
27 tools: ['Edit', 'Write'],
28 draw: ({ e, row, elements: { Box, Text } }) => {
29 // A refused, failed or cut call changed nothing worth counting.
30 if (e.props.isErrored || e.props.isInterrupted) return undefined
31 const stats = statsOf(e.props.tool, e.props.input)
32 if (stats === undefined || stats.added + stats.removed === 0) return undefined
33 const { green, red } = barCells(stats)
34 // The engine's row stays whole; a Text may not hold it, so the bar's
35 // Texts are its siblings in a row Box.
36 return h(
37 Box,
38 { flexDirection: 'row' },
39 row,
40 ' ',
41 h(
42 Box,
43 { key: 'diff-stats', flexDirection: 'row', flexShrink: 0 },
44 h(Text, { color: 'green' }, `+${stats.added}`),
45 ' ',
46 h(Text, { color: 'red' }, `-${stats.removed}`),
47 ' ',
48 green > 0 ? h(Text, { color: 'green' }, '█'.repeat(green)) : null,
49 red > 0 ? h(Text, { color: 'red' }, '█'.repeat(red)) : null,
50 ),
51 ) as RenderElement
52 },
53 },
54})
55hooks/engine.ts 200 lines1import type { ElementTable, FsStat, RenderElement, RenderInput, RenderPropsOf, SessionRepo } from 'claude-code'
2
3// Which tools a rule draws on: a list of names, or every tool.
4export type ToolSet = readonly string[] | 'all'
5
6// Reads a draw may make, as closures over `$` (a rule never holds `$`).
7// `repo` is the session's git repository, or null outside one.
8export type Reads = {
9 cwd: () => Promise<string>
10 repo: () => Promise<SessionRepo | null>
11}
12
13// A draw may answer at once or after its reads.
14type Drawn = RenderElement | undefined | Promise<RenderElement | undefined>
15
16// What a tool row rule draws from: the row's input, the engine's own drawing
17// of it (`next(e)`), and the surface's elements. `durationMs` is how long the
18// call ran, given to a `timed` rule once the call has ended in this session.
19export type ToolRowDraw = Reads & {
20 e: RenderInput<'ToolUse'>
21 row: RenderElement
22 elements: ElementTable
23 durationMs?: number
24}
25
26// What a tool row rewrite reads: the row's props, the person's home folder
27// and the session's project root.
28export type ToolRowRewrite = {
29 props: RenderPropsOf['ToolUse']
30 home: () => Promise<string | undefined>
31 root: () => Promise<string>
32}
33
34// What a tool result rule draws from: the result block's input, the engine's
35// drawing of it, and the surface's elements.
36export type ToolResultDraw = Reads & {
37 e: RenderInput<'ToolResult'>
38 row: RenderElement
39 elements: ElementTable
40}
41
42// What an assistant text rule draws from. `$` never leaves the engine's hook,
43// so the calls a rule needs come as closures over it.
44export type AssistantDraw = Reads & {
45 e: RenderInput<'AssistantMessage'>
46 elements: ElementTable
47 stat: (path: string) => Promise<FsStat>
48 insert: (text: string) => void
49}
50
51// What an assistant text rewrite reads: the block, and the session's reads.
52export type AssistantRewrite = Reads & { e: RenderInput<'AssistantMessage'> }
53
54// One rendering rule. `toolRow` rewrites the props of the ToolUse rows of the
55// named tools (`rewrite`, which changes the row alone) or draws beside them
56// (`draw`); `toolResult` rewrites the props of a result block (`rewrite`) or
57// draws beside it (`draw`); `assistantText` rewrites an assistant reply's
58// text (`rewrite`, handed on to the hooks beneath, so rules of several mods
59// stack) or draws the block itself (`draw`). A draw or rewrite that answers
60// undefined, or throws, leaves the engine's.
61export type RenderRule = {
62 id: string
63 toolRow?: {
64 tools: ToolSet
65 timed?: true
66 rewrite?: (input: ToolRowRewrite) => Promise<RenderPropsOf['ToolUse'] | undefined>
67 draw?: (input: ToolRowDraw) => Drawn
68 }
69 toolResult?: {
70 tools: ToolSet
71 rewrite?: (props: RenderPropsOf['ToolResult']) => RenderPropsOf['ToolResult'] | undefined
72 draw?: (input: ToolResultDraw) => Drawn
73 }
74 assistantText?: {
75 rewrite?: (input: AssistantRewrite) => Promise<string | undefined>
76 draw?: (input: AssistantDraw) => Promise<RenderElement | undefined>
77 }
78}
79
80export const reason = (error: unknown): string => (error instanceof Error ? error.message : String(error))
81
82const covers = (tools: ToolSet, tool: string): boolean => tools === 'all' || tools.includes(tool)
83
84// The calls a host does not give. A rule that makes one has its draw logged
85// and skipped, and its tests fail: name what it uses in engine.json `needs`.
86export const absent = (name: string) => (): Promise<never> =>
87 Promise.reject(new Error(`${name} is not given to this mod; name it in engine.json needs`))
88
89export const NO_READS: Reads = { cwd: absent('cwd'), repo: absent('repo') }
90
91type Log = (text: string) => unknown
92
93// What a tool row hook hands its rule, as closures over the hook's `$`.
94export type RowHost = Reads & {
95 home: () => Promise<string | undefined>
96 root: () => Promise<string>
97 duration: () => Promise<number | undefined>
98 elements: () => ElementTable
99 log: Log
100}
101
102export const NO_ROW_READS = { ...NO_READS, home: absent('home'), root: absent('root'), duration: absent('duration') }
103
104// ToolUse carries no ctrl+o flag, so the engine's row is always kept and the
105// rule draws beside it.
106export const drawToolRow = async (
107 id: string,
108 toolRow: NonNullable<RenderRule['toolRow']>,
109 e: RenderInput<'ToolUse'>,
110 next: (e: RenderInput<'ToolUse'>) => Promise<RenderElement>,
111 host: RowHost,
112): Promise<RenderElement> => {
113 const { rewrite, draw } = toolRow
114 if (!covers(toolRow.tools, e.props.tool)) return next(e)
115 let props: RenderPropsOf['ToolUse'] | undefined
116 try {
117 props = await rewrite?.({ props: e.props, home: host.home, root: host.root })
118 } catch (error) {
119 await host.log(`${id}: drew the engine's props, ${reason(error)}`)
120 }
121 const row = await next(props === undefined ? e : { ...e, props })
122 if (draw === undefined) return row
123 try {
124 // Read only by a timed rule, so the other rows do not redraw on a write.
125 const durationMs = toolRow.timed ? await host.duration() : undefined
126 const drawn = await draw({ e, row, elements: host.elements(), durationMs, cwd: host.cwd, repo: host.repo })
127 return drawn ?? row
128 } catch (error) {
129 await host.log(`${id}: drew the engine's row, ${reason(error)}`)
130 return row
131 }
132}
133
134// What a tool result hook hands its rule, as closures over the hook's `$`.
135export type ResultHost = Reads & { elements: () => ElementTable; log: Log }
136
137export const drawToolResult = async (
138 id: string,
139 toolResult: NonNullable<RenderRule['toolResult']>,
140 e: RenderInput<'ToolResult'>,
141 next: (e: RenderInput<'ToolResult'>) => Promise<RenderElement>,
142 host: ResultHost,
143): Promise<RenderElement> => {
144 const { tools, rewrite, draw } = toolResult
145 if (!covers(tools, e.props.tool)) return next(e)
146 let props: RenderPropsOf['ToolResult'] | undefined
147 try {
148 props = rewrite?.(e.props)
149 } catch (error) {
150 await host.log(`${id}: drew the engine's props, ${reason(error)}`)
151 }
152 const row = await next(props === undefined ? e : { ...e, props })
153 if (draw === undefined) return row
154 try {
155 return (await draw({ e, row, elements: host.elements(), cwd: host.cwd, repo: host.repo })) ?? row
156 } catch (error) {
157 await host.log(`${id}: drew the engine's result, ${reason(error)}`)
158 return row
159 }
160}
161
162// What an assistant text hook hands its rule, as closures over the hook's `$`.
163export type TextHost = Reads & {
164 elements: () => ElementTable
165 stat: (path: string) => Promise<FsStat>
166 insert: (text: string) => void
167 log: Log
168}
169
170export const NO_TEXT_READS = { ...NO_READS, stat: absent('stat'), insert: () => {
171 throw new Error('insert is not given to this mod; name it in engine.json needs')
172} }
173
174export const drawAssistantText = async (
175 id: string,
176 assistantText: NonNullable<RenderRule['assistantText']>,
177 e: RenderInput<'AssistantMessage'>,
178 next: (e: RenderInput<'AssistantMessage'>) => Promise<RenderElement>,
179 host: TextHost,
180): Promise<RenderElement> => {
181 const { rewrite, draw } = assistantText
182 let text: string | undefined
183 try {
184 text = await rewrite?.({ e, cwd: host.cwd, repo: host.repo })
185 } catch (error) {
186 await host.log(`${id}: drew the engine's text, ${reason(error)}`)
187 }
188 // The rewrite goes on through `next`, so a link rule of another mod beneath
189 // this one adds its links to ours. The other props are carried as received.
190 const passed = text === undefined || text === e.props.text ? e : { ...e, props: { ...e.props, text } }
191 if (draw === undefined) return next(passed)
192 try {
193 const drawn = await draw({ e: passed, elements: host.elements(), cwd: host.cwd, repo: host.repo, stat: host.stat, insert: host.insert })
194 return drawn ?? next(passed)
195 } catch (error) {
196 await host.log(`${id}: drew the engine's text, ${reason(error)}`)
197 return next(passed)
198 }
199}
200hooks/diff.ts 52 lines1export type DiffStats = { added: number; removed: number }
2
3// The widest the bar gets, in cells.
4export const MAX_BAR = 20
5
6// Above this many cells (old lines times new lines, after the shared head and
7// tail are cut) the line diff is skipped and every differing line counts:
8// about a million steps, a few milliseconds.
9const MAX_DIFF_CELLS = 1_000_000
10
11// One trailing newline ends the last line; it does not start another.
12const linesOf = (text: string): string[] => (text === '' ? [] : text.replace(/\n$/, '').split('\n'))
13
14// Length of the longest common subsequence, one row at a time.
15const commonLines = (before: readonly string[], after: readonly string[]): number => {
16 let previous: number[] = new Array<number>(after.length + 1).fill(0)
17 for (const line of before) {
18 const row: number[] = [0]
19 after.forEach((other, j) => {
20 row.push(line === other ? (previous[j] ?? 0) + 1 : Math.max(previous[j + 1] ?? 0, row[j] ?? 0))
21 })
22 previous = row
23 }
24 return previous[after.length] ?? 0
25}
26
27// Lines added and removed going from `before` to `after`, as a line diff
28// counts them.
29export const lineDiff = (before: string, after: string): DiffStats => {
30 const a = linesOf(before)
31 const b = linesOf(after)
32 let head = 0
33 while (head < a.length && head < b.length && a[head] === b[head]) head += 1
34 let tail = 0
35 while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1
36 const removedPart = a.slice(head, a.length - tail)
37 const addedPart = b.slice(head, b.length - tail)
38 const common = removedPart.length * addedPart.length > MAX_DIFF_CELLS ? 0 : commonLines(removedPart, addedPart)
39 return { added: addedPart.length - common, removed: removedPart.length - common }
40}
41
42// Cells of green and red: one per line up to MAX_BAR, then proportional. A
43// side with any lines keeps at least one cell.
44export const barCells = ({ added, removed }: DiffStats): { green: number; red: number } => {
45 const total = added + removed
46 if (total === 0) return { green: 0, red: 0 }
47 const cells = Math.min(MAX_BAR, total)
48 const share = Math.round((cells * added) / total)
49 const green = added > 0 && share === 0 ? 1 : removed > 0 && share === cells ? cells - 1 : share
50 return { green, red: cells - green }
51}
52types/index.d.ts 17 lines1// The state the render rules draw from. The build copies this file into the
2// mod as its contract (plugin.json "types"), with the token below replaced by
3// the mod's name: only the plugin that owns a `$.state` value may write it.
4
5// How long one tool call ran, in milliseconds.
6export type DurationMs = number
7
8declare module 'claude-code' {
9 interface PluginState {
10 'diff-stats': {
11 // How long each tool call ran, in milliseconds, by tool_use_id: the
12 // PostToolUse duration, permission prompts and hooks not counted.
13 durations: StateFamily<DurationMs>
14 }
15 }
16}
17