SLOPSHOPPER

branch-base

Start new branches and PRs from your integration branch (origin/dev by default); ask which base when a repo has none

newguardprocess
v0.2.0MITupdated 2026-10-14blackironj/claude-mods/branch-base
A shopper browsing a rack in a slop shop
README

claude-mods

Five Claude Code mods that guard risky actions and cut down on babysitting: confirm production changes, keep secrets out of the model's context, start branches from the right base, hold Claude to "just look" when you ask for it, and tell you when CI finishes.

They started as one person's setup and stay opinionated, but every personal value is a plugin option with a sensible default.

[!WARNING] Mods run inside Claude Code with your permissions and are not sandboxed. These guards parse shell commands heuristically: they catch the common forms Claude writes, not every way a command can be spelled. Treat them as a safety net for mistakes, not a security boundary. Read the source before installing.

Mods

ModWhat it does
prod-guardHolds mutating kubectl/helm commands against production contexts and aws iam writes until you confirm the exact command; a confirmed call skips the auto-mode classifier. Refuses mutating kubectl without an explicit --context. Judges the command inside aws-vault exec <profile> -- … by the same rules, and puts aws-vault login or a bare aws-vault exec <profile> (an interactive shell) in your prompt box as ! … instead of running it.
secret-guardBlocks Bash and Read access to .env files (not .env.example) and to ~/.claude.json. Masks JWTs, AWS/GitHub/Slack/Anthropic/OpenAI/Google keys and private key blocks in Bash and Read output before Claude sees them.
branch-baseRewrites git checkout -b, git switch -c and git worktree add with no start point to start from origin/<base> after a fetch, and adds --base <base> to gh pr create. When a repo has no such branch, asks you which base to use (remembered per repo until reload).
read-only-lockAfter a look-only prompt ("just investigate", "plan first, don't change anything", or Korean equivalents such as "확인만 해"), blocks file edits and mutating commands and shows a one-line band with an Unlock button. "go ahead", "apply it" or the button unlocks.
deploy-watchAfter git push or gh pr create, polls GitHub Actions for that commit every 30 s; after gh pr merge, for the merge commit GitHub made on the base branch, where deploy workflows run (an auto-merge is followed until it lands); after gh workflow run, for the dispatched workflow. Raises a toast and a notification when the runs finish and adds the result to the conversation, so Claude knows without watching CI itself. /ci opens a pane with the runs.

Install

Requires Claude Code v2.1.287 or later (mods are on by default). At the prompt of a terminal session:

/plugin install prod-guard --marketplace blackironj/claude-mods

Answer y to add the marketplace, then pick a scope (user scope loads it in every session). Repeat for each mod you want: secret-guard, branch-base, read-only-lock, deploy-watch.

From a shell:

claude plugin install prod-guard --marketplace blackironj/claude-mods

Disable or uninstall any mod from the Installed tab in /plugin.

Options

Set them on the install screen, or change them later in /config.

ModOptionDefaultMeaning
prod-guardprodContextsprodComma-separated kube contexts whose mutations need confirmation (also matched against helm --kube-context).
prod-guardrequireContexttrueRefuse mutating kubectl commands without --context.
branch-basebaseBranchdevRemote branch new branches start from and PRs target.

Requirements and limits

  • deploy-watch needs the GitHub CLI signed in; branch-base needs git.
  • Panes, bands and toasts draw in the terminal and the Desktop app's Code tab. Under claude -p and the VS Code chat panel the guards still run but nothing is drawn.
  • read-only-lock decides from keywords, so it can lock or stay unlocked when you didn't mean it to; the band shows when it is on.
  • secret-guard also blocks commands that create a .env (for example cp .env.example .env); run those yourself. Masking covers the token shapes listed above, not arbitrary passwords.
  • branch-base does not affect worktrees Claude Code creates on its own (EnterWorktree).
  • prod-guard lets a call you confirmed run even where a permission rule or the auto-mode classifier would stop it, and its aws-vault handoff puts a command Claude wrote into your prompt box: a ! command runs in your shell with no permission check, so read it before pressing Enter.
  • prod-guard lets aws-vault exec <profile> -- … run in Claude's shell, which has no terminal for prompts. When the session needs an MFA code or a key-store passphrase, the command fails; run one aws-vault command yourself with ! to refresh the session.

Development

Each mod is a plugin folder (.claude-plugin/plugin.json, hooks/hooks.json, a TypeScript hooks module, tests). There is no build step: Claude Code loads the .ts/.tsx sources directly. See CLAUDE.md for the layout, checks and conventions.

claude plugin validate prod-guard   # what the module hooks and calls, and anything the engine would refuse
claude plugin test prod-guard       # runs prod-guard/tests/*.test.ts against the engine
claude --plugin-dir ./prod-guard    # a session with your working copy loaded and hot-reloaded

License

MIT

Source 3 files
hooks/register.ts 63 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { findSites, rewrite, type Site } from './plan'
4
5const KEEP = 'Keep as typed'
6const CANCEL = 'Cancel'
7
8type Base = { branch: string } | { keep: true } | { cancel: true }
9
10// Answers for repos without the preferred base, per repo, until the module reloads.
11const chosen = new Map<string, Base>()
12
13async function git($: EngineInterface, dir: string | undefined, ...args: string[]) {
14  const cwd = dir?.startsWith('~') ? `${(await $.env.get('HOME')) ?? ''}${dir.slice(1)}` : dir
15  return $.process.run(['git', ...args], cwd === undefined ? {} : { cwd })
16}
17
18async function hasRemoteBranch($: EngineInterface, dir: string | undefined, branch: string) {
19  return (await git($, dir, 'rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`)).exitCode === 0
20}
21
22async function baseFor($: EngineInterface, dir: string | undefined, preferred: string): Promise<Base> {
23  const common = await git($, dir, 'rev-parse', '--path-format=absolute', '--git-common-dir')
24  if (common.exitCode !== 0) return { keep: true }
25  const repo = common.stdout.trim()
26
27  if (await hasRemoteBranch($, dir, preferred)) return { branch: preferred }
28  const known = chosen.get(repo)
29  if (known) return known
30
31  const candidates: string[] = []
32  for (const b of ['main', 'master']) if (b !== preferred && (await hasRemoteBranch($, dir, b))) candidates.push(b)
33  const answer = await $.ui.ask(
34    `${repo.replace(/\/\.git$/, '')} has no origin/${preferred}. Which branch should new branches and PRs start from?`,
35    { header: 'branch base', options: [...candidates, KEEP, CANCEL] },
36  )
37  const base: Base = answer === CANCEL ? { cancel: true } : answer === KEEP ? { keep: true } : { branch: answer.trim() }
38  if (!('cancel' in base)) chosen.set(repo, base)
39  return base
40}
41
42export const register: Register = (on, options) => {
43  const preferred = String(options.baseBranch ?? 'dev').trim() || 'dev'
44  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
45    const sites = findSites(e.command)
46    if (sites.length === 0) return next(e)
47
48    const bases = new Map<Site, string>()
49    for (const site of sites) {
50      const base = await baseFor($, site.dir, preferred)
51      if ('cancel' in base) return { deny: 'branch-base: the user cancelled; ask which base branch to use.' }
52      if ('branch' in base) bases.set(site, base.branch)
53    }
54    if (bases.size === 0) return next(e)
55
56    const command = rewrite(e.command, sites, site => bases.get(site))
57    const ran = await next({ ...e, command })
58    if (ran.deny !== undefined) return ran
59    const note = `branch-base rewrote the command to start from ${[...new Set(bases.values())].map(b => `origin/${b}`).join(', ')}: ${command}`
60    return { ...ran, context: [...(ran.context ?? []), note] }
61  }).catch(($, e, next) => (next.called ? next(e) : { deny: 'branch-base: could not decide the base branch; the command did not run.' }))
62}
63
hooks/plan.ts 84 lines
1import { option, positionals, program, segments } from './shell'
2
3/** A branch or PR creation in a Bash command that names no base. */
4export type Site = {
5  kind: 'branch' | 'pr'
6  /** Offset and source text of the simple command in the full command. */
7  start: number
8  text: string
9  /** The `git` words before the subcommand (`git -C dir`), for a fetch. */
10  gitPrefix: string[]
11  /** Directory the command runs in: `git -C`, an earlier `cd`, or undefined. */
12  dir: string | undefined
13}
14
15const GIT_GLOBAL_VALUED = ['-C', '-c', '--git-dir', '--work-tree']
16
17export function shQuote(w: string): string {
18  return /^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replace(/'/g, `'\\''`)}'`
19}
20
21function gitSite(ws: string[]): Pick<Site, 'kind' | 'gitPrefix'> | undefined {
22  let i = 1
23  while (ws[i]?.startsWith('-')) i += GIT_GLOBAL_VALUED.includes(ws[i] ?? '') ? 2 : 1
24  const sub = ws[i]
25  const gitPrefix = ws.slice(0, i)
26  const rest = ws.slice(i)
27
28  if (sub === 'checkout') {
29    const isNew = rest.includes('-b') || rest.includes('-B')
30    if (!isNew || rest.includes('--orphan')) return undefined
31    return positionals(rest, 1, []).length === 1 ? { kind: 'branch', gitPrefix } : undefined
32  }
33  if (sub === 'switch') {
34    const isNew = ['-c', '-C', '--create', '--force-create'].some(f => rest.includes(f))
35    if (!isNew || rest.includes('--orphan')) return undefined
36    return positionals(rest, 1, []).length === 1 ? { kind: 'branch', gitPrefix } : undefined
37  }
38  if (sub === 'worktree' && rest[1] === 'add') {
39    if (rest.includes('--detach') || rest.includes('--orphan')) return undefined
40    // -b/-B take the new branch's name, which then counts as a positional
41    const hasName = rest.includes('-b') || rest.includes('-B')
42    return positionals(rest, 2, ['--reason']).length === (hasName ? 2 : 1) ? { kind: 'branch', gitPrefix } : undefined
43  }
44  return undefined
45}
46
47/** Every branch/PR creation in `command` that leaves its base implicit. */
48export function findSites(command: string): Site[] {
49  const sites: Site[] = []
50  let cdDir: string | undefined
51
52  for (const seg of segments(command)) {
53    const ws = program(seg.words)
54    if (ws[0] === 'cd' && ws[1] !== undefined) {
55      cdDir = ws[1]
56      continue
57    }
58    if (ws[0] === 'git') {
59      const site = gitSite(ws)
60      if (site) sites.push({ ...site, start: seg.start, text: seg.text, dir: option(site.gitPrefix, '-C') ?? cdDir })
61    } else if (ws[0] === 'gh' && ws[1] === 'pr' && ws[2] === 'create') {
62      // A PR for another repo (--repo) can't be checked against local refs
63      const isImplicit = option(ws, '--base', '-B') === undefined && option(ws, '-R', '--repo') === undefined
64      if (isImplicit) sites.push({ kind: 'pr', start: seg.start, text: seg.text, gitPrefix: ['git'], dir: cdDir })
65    }
66  }
67  return sites
68}
69
70/** The command with each site rewritten onto `base` (a branch on origin). */
71export function rewrite(command: string, sites: readonly Site[], baseOf: (site: Site) => string | undefined): string {
72  let out = command
73  for (const site of [...sites].sort((a, b) => b.start - a.start)) {
74    const base = baseOf(site)
75    if (base === undefined) continue
76    const replaced =
77      site.kind === 'pr'
78        ? `${site.text} --base ${shQuote(base)}`
79        : `${site.gitPrefix.map(shQuote).join(' ')} fetch origin ${shQuote(base)} --quiet && ${site.text} ${shQuote(`origin/${base}`)}`
80    out = out.slice(0, site.start) + replaced + out.slice(site.start + site.text.length)
81  }
82  return out
83}
84
hooks/shell.ts 144 lines
1// Minimal shell splitting for guards: good enough to find simple commands
2// in a Bash tool call, not a full shell parser. Quotes are respected;
3// substitutions ($(...), backticks) are not expanded.
4
5export type Segment = {
6  /** The segment's source text, trimmed. */
7  text: string
8  /** Offset of `text` in the full command. */
9  start: number
10  /** Words with quotes removed. */
11  words: string[]
12}
13
14/** Splits a command line at unquoted `&&`, `||`, `;`, `|`, `&` and newlines. */
15export function segments(command: string): Segment[] {
16  const out: Segment[] = []
17  let segStart = 0
18  let quote: '"' | "'" | null = null
19
20  const push = (end: number) => {
21    const raw = command.slice(segStart, end)
22    const lead = raw.length - raw.trimStart().length
23    const text = raw.trim()
24    if (text !== '') out.push({ text, start: segStart + lead, words: words(text) })
25  }
26
27  for (let i = 0; i < command.length; i++) {
28    const c = command.charAt(i)
29    if (quote !== null) {
30      if (c === '\\' && quote === '"') i++
31      else if (c === quote) quote = null
32      continue
33    }
34    if (c === '\\') {
35      i++
36      continue
37    }
38    if (c === '"' || c === "'") {
39      quote = c
40      continue
41    }
42    const two = command.slice(i, i + 2)
43    if (two === '&&' || two === '||') {
44      push(i)
45      segStart = i + 2
46      i++
47    } else if (c === '&' && /[<>]/.test(command.charAt(i - 1) + command.charAt(i + 1))) {
48      // fd duplication or `&>`, not a separator
49      continue
50    } else if (c === ';' || c === '|' || c === '&' || c === '\n') {
51      push(i)
52      segStart = i + 1
53    }
54  }
55  push(command.length)
56  return out
57}
58
59/** Splits one simple command into words, removing quotes. */
60export function words(text: string): string[] {
61  const out: string[] = []
62  let cur = ''
63  let has = false
64  let quote: '"' | "'" | null = null
65
66  for (let i = 0; i < text.length; i++) {
67    const c = text.charAt(i)
68    if (quote !== null) {
69      if (c === quote) quote = null
70      else if (c === '\\' && quote === '"' && i + 1 < text.length) cur += text.charAt(++i)
71      else cur += c
72      continue
73    }
74    if (c === '"' || c === "'") {
75      quote = c
76      has = true
77    } else if (c === '\\' && i + 1 < text.length) {
78      cur += text.charAt(++i)
79      has = true
80    } else if (/\s/.test(c)) {
81      if (has) out.push(cur)
82      cur = ''
83      has = false
84    } else {
85      cur += c
86      has = true
87    }
88  }
89  if (has) out.push(cur)
90  return out
91}
92
93const WRAPPERS = new Set(['sudo', 'env', 'time', 'command', 'exec'])
94
95/** Drops leading `VAR=value` assignments and `sudo`/`env`/`time` wrappers. */
96export function program(ws: string[]): string[] {
97  const i = ws.findIndex(w => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && !WRAPPERS.has(w))
98  return i === -1 ? [] : ws.slice(i)
99}
100
101/**
102 * The value of a long or short option in `ws`, written `--name=value` or
103 * `--name value`; undefined when absent.
104 */
105export function option(ws: string[], ...names: string[]): string | undefined {
106  for (const [i, w] of ws.entries()) {
107    for (const name of names) {
108      if (w === name) return ws[i + 1]
109      if (name.startsWith('--') && w.startsWith(name + '=')) return w.slice(name.length + 1)
110    }
111  }
112  return undefined
113}
114
115/**
116 * Positional words after `from`, skipping flags and redirections; flags in
117 * `valued` consume the next word unless written `--flag=value`.
118 */
119export function positionals(ws: string[], from: number, valued: readonly string[]): string[] {
120  const out: string[] = []
121  let skip = false
122  for (const [i, w] of ws.entries()) {
123    if (i < from) continue
124    if (skip) {
125      skip = false
126      continue
127    }
128    if (w === '--') {
129      out.push(...ws.slice(i + 1))
130      break
131    }
132    if (/^\d*(>>?|<|&>)/.test(w)) {
133      skip = /^\d*(>>?|<|&>)$/.test(w)
134      continue
135    }
136    if (w.startsWith('-') && w !== '-') {
137      skip = !w.includes('=') && valued.includes(w)
138      continue
139    }
140    out.push(w)
141  }
142  return out
143}
144