SLOPSHOPPER

merge-gate

Denies a Bash merge (gh pr merge, git merge on main, push onto main) unless the latest human message says the word merge; ship, push and deploy do not count.

newguardcommandpromptprocess
★ 1v0.3.0MITupdated 2026-09-21yash-gadodia/claude-mods/merge-gate
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · merge-gate
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(rm -rf build && git push --force origin main) ⎿ Denied by merge-gate: merge-gate: Yash has not said merge in his latest message. Ask him, or he says 'merg ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /merge-gate ⎿ merge-gate: merge-gate is on; latest message does not say merge ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Mods that keep an agent honest — plus a few that make the terminal fun.

claude-code · mod · function-hooks · typescript · macos

License: MIT Claude Code — mod test

usage  max  volty  opus-5  5h 34%  7d 12%  ctx 41% 82k  $1.23
scope: 3/4 files
 ▸

<sub>Thirteen mods, each drawing or guarding its own slice of the session. Above: usage-band and scope-guard.</sub>

usage-band, wod-band and wod-timer above the prompt <sub>usage-band, wod-band and wod-timer in a live session.</sub>

Why

Claude Code will tell you a deploy worked because git push exited 0. It will turn a one-line fix into a nine-file refactor and never mention it. Written rules in CLAUDE.md help until the model forgets them, and you find out on the deploy that breaks.

These are the same rules, moved out of prose and into the engine — where they hold whether or not the model remembers.

What a mod is

A mod is a Claude Code plugin whose behaviour lives in a TypeScript hooks module — register(on, options) wiring handlers onto engine events (tool.call, ui.render, turn.complete) rather than markdown the model reads. A mod can deny a tool call, rewrite it in flight, draw above the prompt, or put evidence in front of the model that it cannot argue with.

Every mod here is source you can read in one sitting. None of them phone home: there is no $.http.fetch anywhere in this repo.

Install

Function hooks are behind a flag. Set it first, in your shell profile or settings.json env:

export CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1

Then, in Claude Code:

/plugin marketplace add yash-gadodia/claude-mods
/plugin install scope-guard@claude-mods

Install only what you want — each mod is independent. Update with claude plugin update <name>@claude-mods.

The mods

Discipline

ModWhat it does
scope-guardCounts the distinct files one turn edits. At the threshold it stops and makes the goal get restated, so a small ask cannot quietly become a refactor. /scope sets it.
deploy-verifyAfter a deploy command succeeds, waits for the GitHub Actions run it started, then curls the live URL with cache-busting and puts the verdict in the model's context. A deploy cannot be claimed without evidence.
receiptThe turn footer becomes a receipt: edits, runs and curls, with a warning when edits ran nothing. Destructive commands are never folded into a tool group, a claim of "fixed" with no run puts "unverified claim pending" in the spinner, and Tab suggests running the tests.
diff-reviewA docked pane with each edited file's hunk and keep or revert buttons. Reverting runs git directly; no model turn.
merge-gateDenies gh pr merge, a git merge on trunk, or a push to main unless the latest human message contains the word merge. Ship, push and deploy do not count. /merge-gate toggles it.
mini-offloadRewrites heavy Bash commands (test suites, builds, Docker) to run on a second machine over ssh — syncing the commit there first, because the remote checkout is the real hazard. /mini sets always, ask, or off.

Instruments

ModWhat it does
usage-bandThe 5-hour and 7-day limit windows, this session's context fill and cost, above the prompt. Nudges you to /clear when the window gets expensive.
money-bandLiquid assets, CPF, debt and month-to-date spend, read from a pair of SQLite databases over ssh. Every figure is the database's own; nothing is estimated.
copy-bandClick-to-copy buttons above the prompt for every code block and quoted draft in the last answer, plus a durable stash of older ones. Copying runs pbcopy directly — no model turn.
done-blinkWhen a turn lands, the iTerm2 tab blinks orange every half second until you send the next prompt or three minutes pass, so a finished session is obvious from any other tab. Works inside tmux with no passthrough config: the escape goes to the tmux client's tty. /done-blink 60 sets the ceiling.
chrome-switchSwitches the Claude in Chrome extension between named browser profiles using select_browser, which needs no approval click. /chromep maps them.

Fun

ModWhat it does
wod-bandA pixel-art athlete above the prompt who does a rep every turn. The session is an AMRAP of thrusters, burpees and pull-ups.
wod-timer3, 2, 1, GO in the spinner when you submit, a running gym clock while Claude works, and a whiteboard split in the footer when the turn lands: turn, time, AMRAP total, PR. /wod-timer voice on reads long splits aloud.

Turning them off

Every mod checks one environment variable before doing anything:

CLAUDE_MODS_DISABLE=all            # every mod in this repo becomes a pass-through
CLAUDE_MODS_DISABLE=scope-guard    # just that one
CLAUDE_MODS_DISABLE=wod-band,wod-timer

A disabled mod registers no command and every hook falls straight through to next(e).

Configuration

Mods that touch your machine declare their settings in plugin.json userConfig, so they are editable through /config rather than by hand:

  • scope-guard — /scope <n> sets the file threshold. /scope judge on|off (default on) lets a one-shot Haiku call decide at the threshold whether the next edit is still inside the goal you stated first; a yes raises the ceiling by one for that turn, a no or a failed call falls back to asking. /scope off disables the guard.
  • merge-gate — /merge-gate on|off. "merge x3" or "merge after each" in your message grants that many merges.
  • mini-offload — host (ssh alias, default mini), remotePath (the PATH export prefixed to every offloaded command). Per-repo overrides live at <repo>/.claude/mini-offload.json.
  • money-band — host, networthDb, financeDb. Expects SQLite databases with accounts/balances and transactions tables. efAccount (default UOB One) and efTarget (default 30000) feed the EF 41% footer label.
  • usage-band — sgdRate (default 1.30) for the S$ footer label; /usage-band sgd off hides it.
  • receipt — /receipt on|off|status.
  • done-blink — /done-blink on|off|status|<seconds> (default 180, max 900).
  • diff-review — /diff-review open|close|on|off.
  • deploy-verify — per-repo, at <repo>/.claude/deploy-verify.json: ``json { "url": "https://example.com", "matchFile": "VERSION" } ``
  • chrome-switch — ~/.claude/chrome-browsers.json, mapping labels to deviceIds.

Evidence, not decoration

scope-guard and deploy-verify also write a block into the model's own context (prompt.context), replacing their previous copy rather than accumulating:

# deployVerify
Last live deploy check, 2 minutes ago:
  VERIFIED live: https://example.com served "v3.10.10"
This is the only evidence about the live site in this session. Do not describe the deploy as
verified unless a line above starts with VERIFIED, and do not re-state an older claim over it.

A band above the prompt is for you. A context block is for the model — and it cannot be talked around. Repeated advisories are hashed and suppressed for a cooldown so this costs context once, not once per tool call; verdicts themselves are never throttled, because a verdict is evidence.

Tests

npm install
npm test

npm test typechecks every mod, runs its suite under claude plugin test (the official kit, claude-code/testing, with a mocked clock, store and process table), and checks each mod's footprint: the hooks, $ calls and env reads that claude plugin validate reports, pinned in <mod>/FOOTPRINT. A mod that starts calling $.http.fetch fails the build instead of a README sentence going stale. scripts/footprint.sh --write re-pins after a deliberate change.

The interesting half of deploy-verify's suite is the clean baseline: commands that mention a deploy without being one — echo "git push", grep -r "wrangler deploy", git push --dry-run, a commit message quoting make deploy, a heredoc containing one. A false positive curls a live URL nothing was pushed to and then reports a verdict about it, which is worse than not checking at all.

Design rules

The ones that survived contact with real sessions:

  1. A deny always carries the fix. Blocking without saying what to do instead strands the model in a retry loop. Every refusal here names the next action.
  2. Never block when there is no way through. If the only outcomes are "denied" and "denied again", let it run and say something instead.
  3. A render hook that throws takes the whole mod down with it. Every band wraps its frame in try/catch and falls back to what was there.
  4. Hooks have ten seconds of their own time. next(e) and $ calls are free; $.clock.sleep is not. Past the budget, or on a throw, the engine skips the hook silently unless it declares .catch — so every guard here catches and denies, and slow work belongs on a timer.
  5. Bands yield. e.props.hasSurvey means the engine wants that slot; give it back.

Requirements

Claude Code 2.1.271+ with CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1. macOS — copy-band shells out to pbcopy, and mini-offload/money-band assume ssh and a Homebrew path on the remote.

License

MIT

Source 1 files
hooks/register.ts 164 lines
1import type { Register, EngineInterface } from 'claude-code'
2
3// "Do NOT merge PRs unless I explicitly say merge." A merge is a deploy with no approval gate
4// behind it, so this mod denies the Bash merge verbs unless the latest human message contains
5// the word merge. "ship", "push", "deploy" and "land" authorise landing work on the branch, not
6// merging it; the user expects to press merge themselves.
7
8const MOD = 'merge-gate'
9const ENABLED_KEY = 'merge-gate:enabled'
10const HUMAN_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
11const TRUNK = ['main', 'master']
12
13const GIT = String.raw`(^|[\s&;|('"])git(\s+-\S+(\s+\S+)?)*\s+`
14const PR_MERGE = new RegExp(String.raw`(pulls/[0-9]+/merge|merge_requests/[0-9]+/merge|(^|[\s&;|('"])["']?gh["']?\s+pr\s+merge(\s|$|["'])|(^|[\s&;|('"])gh\s+api\s[^|;&]*/merge(\s|$|["']))`, 'm')
15const GIT_MERGE = new RegExp(GIT + String.raw`merge(\s|$|["'])`, 'm')
16const GIT_MERGE_LOCAL = new RegExp(GIT + String.raw`merge\s+--(abort|continue|quit)(\s|$)`, 'm')
17const GIT_PUSH = new RegExp(GIT + String.raw`push(\s|$|["'])`, 'm')
18const INERT = /^(echo|printf|grep|rg|ag|cat|less|head|tail)\b|^git(\s+-\S+(\s+\S+)?)*\s+(commit|log|show|grep)\b/
19const GIT_VALUED = ['-C', '-c', '--git-dir', '--work-tree', '--namespace']
20const SAYS_MERGE = /\bmerge\b/i
21const NEGATED = /\b(don'?t|do not|never|no|not)\s+(\w+\s+)?merge\b/i
22const GRANT_COUNT = /\bmerge\s*[x*]\s*([0-9]+)\b|\b([0-9]+)\s+merges\b/i
23const GRANT_EACH = /\bmerge\s+(after|between|per|each|every)\b|\b(after|between)\s+each\b[^.]{0,40}\bmerge\b/i
24const GRANT_EACH_USES = 5
25
26let latest: string | undefined
27let grantUses = 0
28let enabled = true
29
30// Only a segment that prints or records text is dropped; a quoted merge anywhere else (bash -c, eval) runs.
31const executable = (command: string) =>
32  command
33    .split(/&&|\|\||;|\||\n/)
34    .filter(seg => !INERT.test(seg.replace(/^[\s(]*(\w+=\S*\s+)*/, '')))
35    .join(' ; ')
36
37const saysMerge = (text: string) => {
38  const t = text.replace(/\bmerge-gate\b/gi, '')
39  return SAYS_MERGE.test(t) && !NEGATED.test(t)
40}
41
42const grantOf = (text: string): number => {
43  const m = text.replace(/\n/g, ' ').match(GRANT_COUNT)
44  const n = Number(m?.[1] ?? m?.[2])
45  if (n > 0) return n
46  return GRANT_EACH.test(text) ? GRANT_EACH_USES : 0
47}
48
49// Every branch a `git push` in the command writes to; undefined when one is left to git's default.
50const pushTargets = (command: string): string[] | undefined => {
51  const tokens = command.replace(/\n/g, ' ; ').split(/\s+/).filter(Boolean)
52  const targets: string[] = []
53  for (let i = 0; i < tokens.length; i++) {
54    if (tokens[i] !== 'git') continue
55    i++
56    while (tokens[i]?.startsWith('-')) i += GIT_VALUED.includes(tokens[i] ?? '') ? 2 : 1
57    if (tokens[i] !== 'push') continue
58    i++
59    let remote = false
60    let named = false
61    for (; i < tokens.length && !['&&', '||', ';', '|'].includes(tokens[i] ?? ''); i++) {
62      const token = tokens[i] ?? ''
63      if (['--repo', '--push-option', '--receive-pack', '--exec', '-o'].includes(token)) i++
64      else if (token.startsWith('-')) continue
65      else if (!remote) remote = true
66      else {
67        named = true
68        targets.push(token.replace(/^\+/, '').split(':').pop()?.replace(/^refs\/heads\//, '') ?? '')
69      }
70    }
71    if (!named) return undefined
72  }
73  return targets
74}
75
76const git = async ($: EngineInterface, args: string[]) => {
77  const run = await $.process.run(['git', ...args])
78  return run.exitCode === 0 ? run.stdout.trim() : undefined
79}
80
81const hasPrFlow = async ($: EngineInterface) => /github|gitlab|bitbucket/i.test((await git($, ['remote', 'get-url', 'origin'])) ?? '')
82
83const isMerge = async ($: EngineInterface, command: string): Promise<boolean> => {
84  const bare = executable(command)
85  if (PR_MERGE.test(bare)) return true
86  if (GIT_MERGE.test(bare) && !GIT_MERGE_LOCAL.test(bare)) return TRUNK.includes((await git($, ['rev-parse', '--abbrev-ref', 'HEAD'])) ?? '')
87  if (!GIT_PUSH.test(bare)) return false
88  const targets = pushTargets(bare)
89  if (!targets?.some(t => TRUNK.includes(t))) return false
90  const branch = await git($, ['rev-parse', '--abbrev-ref', 'HEAD'])
91  return branch !== undefined && !TRUNK.includes(branch) && (await hasPrFlow($))
92}
93
94// Tracked prompts are exact; after a resume the transcript stands in, every user message counted as human.
95const latestHuman = async ($: EngineInterface): Promise<string | undefined> => {
96  if (latest !== undefined) return latest
97  const messages = await $.session.messages()
98  return messages.filter(m => m.role === 'user' && !m.toolResults?.length && m.text.trim() !== '').at(-1)?.text
99}
100
101const DENIED = [
102  'merge-gate: Yash has not said merge in his latest message. Ask him, or he says \'merge\' and this passes.',
103  '"ship", "push", "deploy" and "land" do not count: stop at the push, report the PR state, and let him merge.',
104].join('\n')
105
106// The first thing anyone does when a mod misbehaves is try to turn it off. `CLAUDE_MODS_DISABLE=all`,
107// or a comma list naming this mod, makes every hook here a pass-through and registers no command.
108let disabled = false
109const readDisabled = async ($: EngineInterface): Promise<boolean> => {
110  const raw = (await $.env.get('CLAUDE_MODS_DISABLE').catch(() => undefined)) ?? ''
111  disabled = raw
112    .split(',')
113    .map(v => v.trim())
114    .some(v => v === 'all' || v === MOD)
115  return disabled
116}
117
118export const register: Register = on => {
119  on('session.start', async ($, e, next) => {
120    const r = await next(e)
121    if (await readDisabled($)) return r
122    enabled = (await $.store.get(ENABLED_KEY).catch(() => undefined)) !== false
123    await $.command
124      .register({
125        name: 'merge-gate',
126        description: 'Deny Bash merges unless the latest message says merge (merge-gate)',
127        argumentHint: '[on | off | status]',
128        immediate: true,
129      })
130      .catch(err => $.ui.log(`merge-gate: /merge-gate not registered: ${err}`))
131    return r
132  })
133
134  on('command.run', { command: 'merge-gate' }, async ($, e) => {
135    const arg = e.args.trim().toLowerCase()
136    if (arg === 'on' || arg === 'off') {
137      enabled = arg === 'on'
138      await $.store.set(ENABLED_KEY, enabled).catch(err => $.ui.log(`merge-gate: store write failed: ${err}`))
139      return { text: `merge-gate ${arg}` }
140    }
141    if (arg === '' || arg === 'status') {
142      return { text: `merge-gate is ${enabled ? 'on' : 'off'}; latest message ${latest === undefined ? 'unknown' : saysMerge(latest) ? 'says merge' : 'does not say merge'}${grantUses ? `; ${grantUses} granted merge(s) left` : ''}` }
143    }
144    return { text: `merge-gate: "${arg}" is not on, off, or status` }
145  })
146
147  on('prompt.submit', ($, e, next) => {
148    if (disabled || !HUMAN_ORIGINS.includes(e.origin.kind)) return next(e)
149    latest = e.text
150    grantUses = grantOf(e.text) || grantUses
151    return next(e)
152  })
153
154  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
155    if (disabled || !enabled || !(await isMerge($, e.command))) return next(e)
156    const text = await latestHuman($)
157    const said = text !== undefined && saysMerge(text)
158    if (!said && grantUses === 0) return { deny: DENIED }
159    if (grantUses > 0) grantUses--
160    if (!said) $.ui.log(`merge-gate: allowed by a standing grant, ${grantUses} left`)
161    return next(e)
162  }).catch(($, e, next) => (next.called ? undefined : { deny: 'merge-gate check failed; blocking until it works. To get past it: /merge-gate off, or CLAUDE_MODS_DISABLE=merge-gate.' }))
163}
164