SLOPSHOPPER

read-only-lock

After a look-only prompt (English or Korean), block edits and mutating commands until you unlock

newbandguardprompt
v0.2.0MITupdated 2026-10-14blackironj/claude-mods/read-only-lock
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 4 files
hooks/register.tsx 50 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { LockReason } from '../types'
5import { intentOf, violation } from './rules'
6
7const isLocked = atom({ plugin: 'read-only-lock', key: 'isLocked' } as const, false)
8const reason = atom({ plugin: 'read-only-lock', key: 'reason' } as const, null as LockReason | null)
9
10const CONTEXT =
11  'read-only-lock is on: the user asked to investigate or plan only. Do not edit files, run mutating commands, ' +
12  'or change remote state (git, gh, kubectl, package installs). Report findings or a plan and stop; the user will unlock.'
13
14export const register: Register = on => {
15  on('prompt.submit', async ($, e, next) => {
16    if (e.command !== undefined || e.isMeta) return next(e)
17
18    const intent = intentOf(e.text)
19    if (intent === 'lock') {
20      await update($, isLocked, () => true)
21      await update($, reason, () => e.text.replace(/\s+/g, ' ').trim().slice(0, 40))
22    } else if (intent === 'unlock') {
23      await update($, isLocked, () => false)
24    }
25    return (await read($, isLocked)) ? next({ ...e, context: [...(e.context ?? []), CONTEXT] }) : next(e)
26  })
27
28  on('tool.call', async ($, e, next) => {
29    if (!(await read($, isLocked))) return next(e)
30    const why = violation(String(e.tool), e as { command?: string; file_path?: string; notebook_path?: string })
31    return why === undefined
32      ? next(e)
33      : { deny: `read-only-lock: ${why} is blocked because the user asked to look only. Report what you found or propose the change, and wait for the user to unlock.` }
34  }).catch(($, e, next) => (next.called ? next(e) : { deny: 'read-only-lock: the guard failed; the call did not run.' }))
35
36  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
37    if (e.props.hasSurvey || !(await read($, isLocked))) return next(e)
38
39    const { Box, Button, Text } = $.ui.resolve(e)
40    const why = await read($, reason)
41    return (
42      <Box>
43        <Text color="yellow">read-only</Text>
44        <Text dimColor> · edits blocked{why === null ? '' : ` · "${why}"`} </Text>
45        <Button key="unlock" label="Unlock" onPress={() => update($, isLocked, () => false)} />
46      </Box>
47    )
48  })
49}
50
hooks/rules.ts 96 lines
1import { option, positionals, program, segments } from './shell'
2
3// Prompts that ask for investigation or a plan only. English is the base
4// set; Korean phrases ride along so either language triggers the lock.
5const LOCK_EN = [
6  /\bread[- ]?only\b/,
7  /\b(just|only)\s+(look|investigate|check|read|explore|review)\b/,
8  /\b(look|investigate|check|explore|review)\s+(only|first)\b/,
9  /\b(plan|propose)\s+(it\s+)?first\b/,
10  /\b(don'?t|do not|without)\s+(chang|modify|modifying|edit|touch|fix|commit|proceed)\w*/,
11  /\bno\s+(changes|edits)\b/,
12]
13const LOCK_KO = [
14  /확인\s*(부터|만)|파악\s*(부터|만)|살펴\s*보기?만|보기만|계획\s*(부터|만)/,
15  /(수정|변경|고치|건드리)\s*(하지|지)\s*마|(수정|변경)\s*없이|읽기\s*전용/,
16]
17// Prompts that explicitly ask for changes.
18const UNLOCK_EN = [
19  /\bgo ahead\b/,
20  /\b(apply|implement|fix|commit|ship)\s+(it|this|that|them)\b/,
21  /\bmake\s+the\s+changes?\b/,
22  /\byou\s+can\s+(now\s+)?(edit|change|modify|proceed)\b/,
23  /^\s*(proceed|do it|lgtm)\b/,
24]
25const UNLOCK_KO = [/(수정|고쳐|적용|반영|구현|커밋|머지|작업|진행|저장)\s*(해|하자|합시다|ㄱ)|해도\s*(돼|된다|됨)/]
26
27const LOCK = [...LOCK_EN, ...LOCK_KO]
28const UNLOCK = [...UNLOCK_EN, ...UNLOCK_KO]
29
30export type PromptIntent = 'lock' | 'unlock' | 'none'
31
32/** Lock wins when a prompt says both ("look first, don't commit yet"). */
33export function intentOf(text: string): PromptIntent {
34  const lower = text.toLowerCase()
35  if (LOCK.some(re => re.test(lower))) return 'lock'
36  if (UNLOCK.some(re => re.test(lower))) return 'unlock'
37  return 'none'
38}
39
40const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
41const SCRATCH = /^\/tmp\//
42
43const GIT_MUTATING = new Set([
44  'add', 'commit', 'push', 'merge', 'rebase', 'reset', 'checkout', 'switch', 'cherry-pick',
45  'revert', 'rm', 'mv', 'restore', 'clean', 'am', 'apply', 'pull',
46])
47const GH_MUTATING = /^(create|merge|close|edit|reopen|comment|review|delete|ready|lock|unlock|transfer|run|rerun|cancel|set|upload)$/
48const KUBECTL_MUTATING = new Set(['apply', 'create', 'delete', 'edit', 'patch', 'replace', 'scale', 'drain', 'cordon', 'uncordon', 'taint', 'label', 'annotate', 'rollout', 'set', 'exec', 'cp'])
49const PLAIN_MUTATING = new Set(['rm', 'mv', 'cp', 'mkdir', 'rmdir', 'touch', 'chmod', 'chown', 'ln', 'truncate', 'dd', 'tee', 'patch', 'install', 'helm', 'terraform'])
50const PKG = new Set(['npm', 'pnpm', 'yarn', 'pip', 'uv', 'cargo', 'go', 'bun'])
51const PKG_MUTATING = new Set(['install', 'i', 'add', 'remove', 'rm', 'uninstall', 'update', 'upgrade', 'sync', 'get', 'publish', 'init'])
52
53function isMutatingCommand(ws: string[]): boolean {
54  const [cmd, a, b] = ws
55  if (cmd === undefined) return false
56  if (PLAIN_MUTATING.has(cmd)) return true
57  if (cmd === 'sed' && ws.some(w => /^-i/.test(w) || w === '--in-place')) return true
58  if (cmd === 'git') {
59    // branch/tag/stash/worktree list when bare or given `list`
60    const [sub = '', arg] = positionals(ws, 1, ['-C', '-c'])
61    if (['branch', 'tag'].includes(sub)) return arg !== undefined || ws.some(w => /^-[dDmMcCf]$|^--(delete|move|copy|force)$/.test(w))
62    if (['stash', 'worktree'].includes(sub)) return arg !== undefined && !['list', 'show'].includes(arg)
63    return GIT_MUTATING.has(sub)
64  }
65  if (cmd === 'gh' && a === 'api') {
66    const method = option(ws, '-X', '--method')
67    const hasFields = ['-f', '-F', '--field', '--raw-field', '--input'].some(f => ws.includes(f))
68    return method !== undefined ? method.toUpperCase() !== 'GET' : hasFields
69  }
70  if (cmd === 'gh') return b !== undefined && GH_MUTATING.test(b)
71  if (cmd === 'kubectl') return ws.slice(1).some(w => KUBECTL_MUTATING.has(w))
72  if (PKG.has(cmd)) return a !== undefined && PKG_MUTATING.has(a)
73  return false
74}
75
76/** Output redirection into a file (not /dev/null or /tmp, not fd duplication). */
77function writesFile(text: string): boolean {
78  return /(^|[^0-9&<>])>>?(?!>)\s*(?![\s&]|\/dev\/null|\/tmp\/)[^\s|;&>]+/.test(text.replace(/(["'])(?:\\.|(?!\1).)*\1/g, '""'))
79}
80
81/** Why a tool call breaks the read-only lock, or undefined when it doesn't. */
82export function violation(tool: string, input: { command?: string; file_path?: string; notebook_path?: string }): string | undefined {
83  if (FILE_TOOLS.has(tool)) {
84    const path = input.file_path ?? input.notebook_path ?? ''
85    return SCRATCH.test(path) ? undefined : `${tool} on ${path}`
86  }
87  if (tool === 'Bash' && input.command !== undefined) {
88    for (const seg of segments(input.command)) {
89      const ws = program(seg.words)
90      if (isMutatingCommand(ws)) return `\`${seg.text.slice(0, 80)}\``
91      if (writesFile(seg.text)) return `a file redirect in \`${seg.text.slice(0, 80)}\``
92    }
93  }
94  return undefined
95}
96
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
types/index.d.ts 8 lines
1export type LockReason = string
2
3declare module 'claude-code' {
4  interface PluginState {
5    'read-only-lock': { isLocked: boolean; reason: LockReason | null }
6  }
7}
8