Refuses force-pushes, pushes to protected branches, --no-verify and kills by process name; optionally fences off listed paths, a subagent's edits to a shared…

A Claude Code plugin marketplace from Darling Data.
/plugin marketplace add erikdarlingdata/claude-plugins
sqlserver-query-plansTeaches Claude to read a SQL Server execution plan and say what is actually slow, and why.
/plugin install sqlserver-query-plans@erikdarling
Point Claude at a .sqlplan file and ask. The skill is model-invoked — you do not need to call it explicitly.
The hard part of plan analysis is not spotting operators. It is knowing which numbers mean what they appear to mean. This plugin is built mostly out of the conclusions that sound authoritative and are wrong:
ActualElapsedms ranks them by depth and always crowns the root node. Batch mode reports standalone times. Exchange operators report times that are close to meaningless.EstimateRows is per-execution; ActualRows is a total. Without dividing by ActualExecutions, the inner side of every nested loop looks catastrophically underestimated when it may have estimated perfectly.Impact figure is a percentage of an estimated cost.It also ships scripts/extract.py, which flattens a .sqlplan into a compact digest. This is not a convenience:
.sqlplan files are UTF-16, so grep silently matches nothing and reports no error. A negative result from grep on a plan file is worthless.encoding="utf-16", because they were opened and re-saved. Strict XML parsers reject them.The extractor handles the encoding, computes correct self-time attribution (subtracting children in row mode, within a thread rather than across threads in parallel plans, and not at all in batch mode), normalizes cardinality per execution, and recognizes the optimizer's default-guess selectivity fingerprints. --node N drills into a single operator; --sql recovers full statement text.
Requires Python 3 (standard library only). Without it, the skill degrades to a documented grep-based fallback and says plainly what it cannot determine.
This plugin also works in GitHub Copilot CLI, which reads the same SKILL.md and plugin.json format.
copilot plugin marketplace add erikdarlingdata/claude-plugins
copilot plugin install sqlserver-query-plans@erikdarling
Or add just the skill, without the marketplace:
/skills add ./plugins/sqlserver-query-plans/skills/query-plan-analysis
As in Claude Code, the skill is model-invoked: point Copilot at a .sqlplan and ask.
Small hook modules for people who run several agents at once. Each one is a plugin of its own. Install only the ones you want, and set their options in /config (or under pluginConfigs in settings.json). They need a Claude Code version that loads plugin hook modules.
subagent-fenceStops the mistakes an unattended agent makes that cannot be taken back.
/plugin install subagent-fence@erikdarling
For the main session and every subagent it refuses four things. A force-push. A push to a protected branch. A git command that skips the repository's hooks. Killing processes by name (pkill, killall, taskkill /IM, Stop-Process -Name), because a name match can kill another session's processes.
Three more guards are off until you set them. One bans folders: nothing reads, writes or enters them. One keeps a subagent from editing a plain git checkout, or running a changing git command there, so it works in its own worktree. One stops a subagent reading a big text file whole instead of by offset and limit.
| Option | Default | What it does | | :- | :- | :- | | guard_force_push | on | Refuse --force, --force-with-lease, -f and +refspec pushes | | guard_protected_branches | on | Refuse a push that targets a protected branch | | protected_branches | main, master, dev | The branch names a push cannot target | | guard_no_verify | on | Refuse the git flag that skips hooks | | guard_kill_by_name | on | Refuse killing processes by name | | banned_paths | none | Folders that nothing reads, writes or enters | | guard_shared_checkout | off | Keep subagents out of plain git checkouts | | shared_checkout_root | empty | Limit that guard to checkouts under this folder. Empty detects a plain checkout anywhere: a folder whose .git is a directory, where a linked worktree has a .git file | | read_limit_bytes | 0 (off) | Refuse a subagent's Read of a text file over this size when it gives no limit |
model-allowlistChecks the model a subagent is spawned with.
/plugin install model-allowlist@erikdarling
A pinned model id goes stale: a dated or versioned name keeps pointing at an old model after the tier moves on. This refuses a spawn that names one and asks for a tier alias (opus, sonnet, haiku) instead. A spawn with no model is always allowed, because the agent file or the parent decides then.
You can add rules of your own. One example: the lane agent runs Sonnet, and Opus only when the brief says design, security or hard debugging. With no rules, every alias is allowed.
| Option | Default | What it does | | :- | :- | :- | | refuse_pinned_ids | on | Refuse any model that is not an allowed alias | | allowed_aliases | opus, sonnet, haiku, fable, inherit | The names that count as aliases. A trailing [1m]-style suffix is ignored | | rules | none | One rule per entry, written agent type pattern => model => brief pattern => message |
A rule applies when the spawn's agent type matches the first pattern and it names that model (* for any model). The brief must then match the brief pattern, or the spawn is refused. Leave the brief pattern empty to refuse the pairing outright. The message is optional and can use {type} and {model}. Patterns are case-insensitive regular expressions. A rule that does not parse is skipped. For example:
^(lane|worker-.*)$ => opus => \b(design|security|hard[- ]debug) => {type} runs sonnet; name the reason in the brief to use opus.
seat-resumeBrings interrupted sessions back after a crash, a reboot or a closed terminal.
/plugin install seat-resume@erikdarling
The plugin writes one small file per interactive session: its id, name, folder, permission mode and last activity. It marks the file when the session ends. /resume-sessions lists the sessions that died or were interrupted in the last 72 hours, with the command that reopens each. The script's -Launch switch reopens all of them in terminal tabs. Sessions you left with /exit, Ctrl+C or /clear stay closed. The plugin name still says "seat", but everything you see says "session".
This one is Windows only. The bundled script (scripts/resume-sessions.ps1) is PowerShell. It compares Windows process start times to tell a live session from a reused process id. It reopens tabs in WezTerm or Windows Terminal. Nobody has tried the plugin on macOS or Linux.
| Option | Default | What it does | | :- | :- | :- | | registry_dir | empty: session-registry in your Claude config folder | Where the per-session files go | | sessions_dir | empty: sessions in your Claude config folder | Where Claude Code records its running sessions | | resume_script | empty: the bundled script | The PowerShell script /resume-sessions runs | | powershell | pwsh | The program that runs it (powershell for Windows PowerShell 5.1) | | terminal | wezterm | wezterm or windows-terminal: where -Launch reopens sessions |
The Claude config folder is CLAUDE_CONFIG_DIR when that is set, otherwise .claude in your home folder.
open-asksKeeps the questions Claude asks you from scrolling away. Every time a reply asks you something or leaves a decision to you, Claude records it. The question stays in a band above your prompt, with Claude's recommended answer, until you answer, decline or drop it. Claude gets ask_add, ask_resolve and ask_list tools. You get /asks (done <ids>, clear, hide, show). Open asks are saved per session, so a resumed session still has them.
/plugin install open-asks@erikdarling
| Option | Default | What it does |
|---|---|---|
maxBandAsks | 6 | Most asks the band draws. The rest stay in /asks. |
maxQuestionChars | 400 | Longest question or recommendation shown before it is cut. |
keepDays | 30 | Saved asks from other sessions are removed after this many days. 0 keeps them. |
subagent-bandA live view of your subagents. The band above the prompt has one row per running subagent: type, model, effort, steps, context size, advisor calls and estimated cost. /fleet opens a pane with every subagent of the session, finished ones included. /subagent-cost totals the estimated cost by agent type and by issue number in the description, with the main session's own cost. /steer <id> <text> sends a running subagent a message. Claude gets a cheap subagent_vitals tool, so it does not have to read output files to check progress. Costs are list-price estimates, not your bill.
/plugin install subagent-band@erikdarling
| Option | Default | What it does |
|---|---|---|
priceTable | opus:4:20, sonnet:2:10, haiku:1:5, fable:10:50 | Input and output USD per million tokens for each model family. A model id is matched by containing the family name. |
cacheWriteMultiplier | 1.25 | Cache write price as a multiple of the input price. |
cacheReadMultiplier | 0.1 | Cache read price as a multiple of the input price. |
usage-budgetWatches the account's 5-hour and 7-day usage windows. A toast tells you each time a window crosses a percent. Past a higher percent, Claude also gets a one-time note so it can stop starting optional work and write its handoff. Past the last one, new subagents are refused until the window resets.
/plugin install usage-budget@erikdarling
| Option | Default | What it does |
|---|---|---|
warnPercents | 70, 85, 95 | Percents that raise a toast, once each per window. |
tellModelAtPercent | 85 | From here the model is told as well. 0 never tells it. |
spawnGatePercent | 95 | A new subagent is refused when either window is at or past this. 0 turns the refusal off. |
subagent-wallA wall-clock limit for subagents. After a warning time, a subagent is told to finish up. After the limit, it can only run git and gh commands and write .md or .txt files. It commits, reports and ends instead of running on. It also nudges a code-changing subagent that has a lot of context but no edited file to stop exploring and make the change. The main session is never limited.
/plugin install subagent-wall@erikdarling
| Option | Default | What it does |
|---|---|---|
warnMinutes | 45 | Minutes before a subagent is told to finish up. 0 turns the warning off. |
limitMinutes | 60 | Minutes before it is held to git, gh and note writes. 0 turns the limit off. |
noEditNudgeK | 100 | Thousands of context tokens before the no-edit nudge. 0 turns it off. |
codeAgentTypes | general-purpose | Comma-separated subagent types that get the no-edit nudge. |
This repository is also a pi package: the root package.json declares every plugins/*/skills and plugins/*/extensions directory, and pi reads the same SKILL.md format the other two harnesses do. Install straight from git — no marketplace step:
pi install git:github.com/erikdarlingdata/claude-plugins
As everywhere else, the skill is model-invoked: point pi at a .sqlplan and ask.
pi-session-resume (pi only)Your machine restarts for updates with a dozen pi sessions open; this brings them all back with one command, as terminal tabs, in their original directories, with full history:
pi-resume-sessions
An extension (auto-loaded by the install above) records every open interactive session; the pi-resume-sessions script reopens the interrupted ones — Ghostty tabs on macOS, tmux anywhere. Sessions you quit deliberately (Ctrl+D, /quit) stay closed; sessions killed by a reboot, a closed window, or a crash come back. Idle-time filters keep abandoned sessions from resurrecting.
The script needs a one-time symlink onto your PATH, and macOS needs a one-time Automation permission — see plugins/pi-session-resume/README.md for both, plus the design notes. This one is pi-only: Claude Code and Copilot CLI don't load pi extensions.
pi-subagent-watchdog (pi only)Background subagents only report back when they finish — nothing wakes the orchestrator while one wedges on a giant grep or balloons from 200k to 2M tokens. This extension (auto-loaded by the install above) polls every running subagent's live vitals — tokens, cost, context %, tool uses, turns, wall clock, compactions — and batches nearby threshold crossings into one compact orchestrator check-in. Full structured records persist outside LLM context; per-agent and fleet-wide rate limits keep the watchdog from becoming its own token amplifier. Two orchestrator postures: guide (assess with judgment) and strict (thresholds are budgets — wrap up by default, one evidence-cited extension max). Optional automatic hard stop handles the truly wedged, with the outcome reported from the RPC reply rather than assumed. An optional exact model invariant hard-stops any top-level child that bypasses the manager's pre-spawn model policy. Optional per-agent cost signal and hard stop, plus session and daily USD budget warnings. The CLI surfaces also identify each child's effective model and thinking level.
Humans get a /watchdog panel (vitals, manual check-ins, steering, hard stop) plus /watchdog help | status | config | reload — config edits apply live, no session restart. See plugins/pi-subagent-watchdog/README.md for signals, modes, and design notes. Requires the pi-subagents extension; pi-only for the same reason as above.
pi-subagent-guardrails (pi only)Token-budget guardrails for multi-agent setups, built after an overnight orchestration burned through its usage limit (95% of the spend came at more than 150k context). It has three pieces:
guardrails.md: the written rules for fan-out caps, model tiers, context discipline, session length and ranking.lane agent type for code-editing lanes: Sonnet, its own worktree, draft PRs, no fan-out tools.The wall is deliberately not auto-loaded, because it would wall off your interactive session too. See plugins/pi-subagent-guardrails/README.md for install and the recommended watchdog and pi-subagents settings.
pi-setup-guide.md — a distilled ~15-minute setup for pi written for Claude Code ex-pats: install, model/thinking defaults, the trust model, a Claude-to-pi habit translation table, a tested-together extension stack, full source for a few small quality-of-life extensions (refusal fallback, tab-title status, ! command wake-ups + autocomplete), how to point pi at years of accumulated Claude Code memory instead of migrating it, and a troubleshooting section of the gotchas that actually happened. The plugins in this repo (§11–§13 of the guide) slot into that stack.
Built by Erik Darling at Darling Data. SQL Server consulting, training, and free tools: <https://erikdarling.com>
MIT
hooks/register.ts 168 lines1import type { EngineInterface, PluginOptions, Register } from 'claude-code'
2
3// Paths compare in one form: forward slashes, no doubled slashes, lower case, /c/... as c:/...
4const slashes = (p: unknown) => String(p ?? '').trim().replace(/\\/g, '/').replace(/\/{2,}/g, '/')
5const norm = (p: unknown) => slashes(p).replace(/^\/([a-z])\//i, '$1:/').replace(/(.)\/$/, '$1').toLowerCase()
6// A whole command line in the same form, so a banned root is found wherever it is written in it.
7const normCommand = (c: string) => slashes(c).replace(/(^|[^a-z0-9])\/([a-z])\//gi, '$1$2:/').toLowerCase()
8const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
9
10// A list option arrives as an array; a hand-edited settings.json may hold one comma-separated string.
11const list = (v: unknown): string[] => (Array.isArray(v) ? v : typeof v === 'string' ? v.split(/[,\n]/) : [])
12 .map(s => String(s).trim()).filter(Boolean)
13const flag = (v: unknown, fallback: boolean) => (typeof v === 'boolean' ? v : fallback)
14
15const MUTATING_GIT = new Set(['add', 'am', 'apply', 'checkout', 'cherry-pick', 'clean', 'commit', 'merge', 'mv', 'pull',
16 'rebase', 'reset', 'restore', 'revert', 'rm', 'stash', 'switch'])
17const NOT_TEXT = /\.(png|jpe?g|gif|webp|bmp|ico|pdf|ipynb)$/i
18
19const KILL_BY_NAME = /\bpkill\b|\bkillall\b|\btaskkill\b[^;&|\n]*\/+im\b|\bstop-process\b[^;&|\n]*-name\b/i
20const NO_VERIFY = /\bgit\b[^;&|\n]*\s--no-verify\b/
21
22type Config = {
23 forcePush: boolean
24 protectedPush: boolean
25 protectedBranch: RegExp | undefined
26 noVerify: boolean
27 killByName: boolean
28 bannedRoots: string[]
29 bannedInCommand: RegExp[]
30 sharedCheckout: boolean
31 sharedRoot: string
32 readLimitBytes: number
33}
34
35function readConfig(options: PluginOptions): Config {
36 const bannedRoots = list(options.banned_paths).map(norm).filter(Boolean)
37 const branches = list(options.protected_branches).map(escapeRegex)
38 const limit = Number(options.read_limit_bytes)
39
40 return {
41 forcePush: flag(options.guard_force_push, true),
42 protectedPush: flag(options.guard_protected_branches, true),
43 protectedBranch: branches.length ? new RegExp(`(^|:)(refs/heads/)?(${branches.join('|')})$`) : undefined,
44 noVerify: flag(options.guard_no_verify, true),
45 killByName: flag(options.guard_kill_by_name, true),
46 bannedRoots,
47 bannedInCommand: bannedRoots.map(root => new RegExp(`(^|[^a-z0-9_.-])${escapeRegex(root)}(?=[/'"\\s;&|)]|$)`)),
48 sharedCheckout: flag(options.guard_shared_checkout, false),
49 sharedRoot: norm(options.shared_checkout_root),
50 readLimitBytes: Number.isFinite(limit) && limit > 0 ? limit : 0,
51 }
52}
53
54// Each `git push` in a command: refused when it forces, or names a protected branch as a target.
55function pushProblem(command: string, cfg: Config): string | undefined {
56 for (const m of command.matchAll(/\bgit\b(?:\s+-C\s+\S+)?\s+push\b([^;&|\n]*)/g)) {
57 const words = m[1].trim().split(/\s+/).filter(Boolean)
58 if (cfg.forcePush && words.some(w => /^(--force|--force-with-lease(=.*)?|--force-if-includes|-[a-zA-Z]*f[a-zA-Z]*)$/.test(w))) {
59 return 'a force-push'
60 }
61 const refspecs = words.filter(w => !w.startsWith('-')).slice(1)
62 if (cfg.forcePush && refspecs.some(r => r.startsWith('+'))) {
63 return 'a force-push (+refspec)'
64 }
65 if (cfg.protectedPush && cfg.protectedBranch && refspecs.some(r => cfg.protectedBranch!.test(r))) {
66 return 'a push to a protected branch'
67 }
68 }
69 return undefined
70}
71
72// A plain git checkout is shared; a linked worktree is not. Walks up from the path to the nearest `.git`:
73// a directory means a plain checkout, a file means a linked worktree. With a root set, only paths under it count.
74async function isSharedCheckout($: EngineInterface, path: unknown, cfg: Config): Promise<boolean> {
75 const n = norm(path)
76 if (!/^([a-z]:)?\//.test(n)) {
77 return false // relative: the working directory is unknown here
78 }
79 if (cfg.sharedRoot && !n.startsWith(`${cfg.sharedRoot}/`)) {
80 return false
81 }
82 let dir = slashes(path).replace(/^\/([a-z])\//i, '$1:/').replace(/(.)\/$/, '$1')
83 for (let i = 0; i < 40 && dir; i++) {
84 const git = await $.fs.stat(`${dir}/.git`).catch(() => undefined)
85 if (git) {
86 return git.kind === 'dir'
87 }
88 const up = dir.replace(/\/[^/]*$/, '')
89 if (up === dir || !up || /^[a-z]:$/i.test(up)) {
90 break
91 }
92 dir = up
93 }
94
95 return false
96}
97
98// `git -C <shared checkout> <mutating command>` or `cd <shared checkout> && git <mutating command>`.
99async function sharedGitMutation($: EngineInterface, command: string, cfg: Config): Promise<string | undefined> {
100 const found = [
101 ...[...command.matchAll(/\bgit\s+-C\s+["']?([^\s"']+)["']?\s+([a-z-]+)/g)].map(m => [m[1], m[2]]),
102 ...[...command.matchAll(/\bcd\s+["']?([^\s"';&|]+)["']?\s*(?:&&|;)\s*git\s+([a-z-]+)/g)].map(m => [m[1], m[2]]),
103 ]
104 for (const [dir, verb] of found) {
105 if (MUTATING_GIT.has(verb) && await isSharedCheckout($, `${dir}/`, cfg)) {
106 return `git ${verb} in ${dir}`
107 }
108 }
109 return undefined
110}
111
112const deny = (why: string) => ({ deny: `subagent-fence: ${why}` })
113
114export const register: Register = (on, options) => {
115 const cfg = readConfig(options)
116
117 on('tool.call', async ($, e, next) => {
118 const input = e as unknown as Record<string, unknown>
119 const isSubagent = Boolean(e.agentId)
120 const command = e.tool === 'Bash' || e.tool === 'PowerShell' ? String(input.command ?? '') : ''
121 const path = input.file_path ?? input.notebook_path ?? input.path
122
123 // Everywhere, the main session included.
124 if (cfg.bannedRoots.length) {
125 const n = norm(path)
126 const hit = cfg.bannedRoots.some(root => n === root || n.startsWith(`${root}/`))
127 || (command && cfg.bannedInCommand.some(re => re.test(normCommand(command))))
128 if (hit) {
129 return deny('that path is on the banned list (the banned_paths option). Never read, write or enter it.')
130 }
131 }
132 if (command) {
133 const push = pushProblem(command, cfg)
134 if (push) {
135 return deny(`${push} is never allowed here. Push a feature branch and open a PR; never force-push.`)
136 }
137 if (cfg.noVerify && NO_VERIFY.test(command)) {
138 return deny('--no-verify bypasses the hooks, which is never allowed. Fix what the hook reports instead.')
139 }
140 if (cfg.killByName && KILL_BY_NAME.test(command)) {
141 return deny('killing processes by name can kill other sessions\' processes. Kill by PID only.')
142 }
143 }
144
145 if (isSubagent) {
146 if (cfg.sharedCheckout) {
147 if ((e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit') && await isSharedCheckout($, path, cfg)) {
148 return deny(`${String(path)} is in a shared checkout. Edit only inside your own worktree; never the main checkout.`)
149 }
150 const mutation = command ? await sharedGitMutation($, command, cfg) : undefined
151 if (mutation) {
152 return deny(`${mutation} changes a shared checkout. Run git only inside your own worktree.`)
153 }
154 }
155 if (cfg.readLimitBytes && e.tool === 'Read' && input.limit === undefined && !NOT_TEXT.test(String(path ?? ''))) {
156 const size = await $.fs.stat(String(path)).then(s => (s.kind === 'file' ? s.size : 0)).catch(() => 0)
157 if (size > cfg.readLimitBytes) {
158 return deny(
159 `${String(path)} is ${Math.round(size / 1000)} KB. Read it by offset and limit (150 lines or fewer): ` +
160 'find the line with grep -n first, then read that window.')
161 }
162 }
163 }
164
165 return next(e)
166 }).catch(($, e, next) => next(e)) // if the fence itself fails, the call goes ahead
167}
168