Stops irreversible calls: force-push to main, reset --hard, rm -r outside the project, publishing, DROP TABLE, and file edits outside the project

Stops tool calls that cannot be undone from inside the session, before they run:
| Group | Refused |
|---|---|
| git | force-push or delete a protected branch (main, master, prod, production, release, trunk; a bare git push -f reads the current branch from .git/HEAD) · reset --hard · clean -f · checkout . · restore . · stash drop/clear · branch -D |
| rm | -r on /, ~, $HOME, ., ./*, .., the project root, or anything outside the project and temp folders |
| ship | npm/pnpm/yarn publish (not --dry-run), cargo publish, twine upload, gh release create, docker push, gem push |
| infra | terraform destroy, kubectl delete, helm uninstall |
| data | DROP TABLE/DATABASE/SCHEMA, TRUNCATE TABLE through a database client (psql, mysql, sqlite3, …); grep "DROP TABLE" is fine |
| disk | mkfs, dd of=/dev/…, a fork bomb |
| files | Write / Edit / NotebookEdit outside the project, ~/.claude and temp folders, with symbolic links resolved; when the working folder changes (cd, a worktree), the project is read again and the old one counts as outside |
Allowed as usual: rm -rf node_modules dist, git push --force-with-lease origin feature/x, git reset --soft, git restore --staged ., writes to /tmp and plan files under ~/.claude.
Claude receives:
game-barrier blocked this call: it discards uncommitted changes (git reset --hard). This cannot be undone from here.
Find a reversible way (commit or stash first, work on a branch, stay inside the project), or explain why it is needed
and ask the user to run it themselves or to type /barrier pass.
Real run: examples/RUN-2026-10-06.md (the uncommitted change survived).
Part of the GAME MODE pack. Requires Claude Code 2.1.287+; built and tested on 2.1.291.
claude plugin marketplace add Reasonofmoon/bitgame-mods
claude plugin install game-barrier@bitgame-mods
mode (block) | block refuses · warn runs it and tells Claude and you · off |
allow (empty) | more folders where edits and rm -r are fine, comma-separated (~/notes, /srv/shared) |
/barrier | status, with the folders counted as inside (read again when the working folder changes) |
/barrier block · warn · off | change the mode; remembered |
/barrier pass | let the next refused call run once (within 10 minutes) |
warn, off and pass are accepted only when you type them.
./deploy.sh running npm publish) is not opened.rm -r on a path built from a variable (rm -rf "$BUILD_DIR") is let through: the value is not known before the command runs.C:\, c:/, Git Bash /c/). If the project folder cannot be read, edits outside the project are not checked for that session.되돌릴 수 없는 명령(main 강제 push, reset --hard, 프로젝트 밖 rm -rf, 배포·publish, DROP TABLE, 프로젝트 밖 파일 수정)을 실행 전에 막습니다. 꼭 필요하면 직접 /barrier pass를 입력하세요.
hooks/register.ts 410 lines1import type { EngineInterface, Register } from 'claude-code'
2
3// GAME MODE · BARRIER (결계)
4//
5// Stops tool calls that cannot be undone from inside the session:
6// git force-push or delete a protected branch (main, master, prod…),
7// reset --hard, clean -f, checkout/restore the whole tree,
8// stash drop/clear, branch -D
9// rm -r on /, ~, the project root, ./*, or anything outside the
10// project and temp folders
11// ship npm/pnpm/yarn publish, cargo publish, twine upload,
12// gh release create, docker push, gem push
13// infra terraform destroy, kubectl delete, helm uninstall
14// data DROP TABLE/DATABASE/SCHEMA, TRUNCATE TABLE
15// disk mkfs, dd of=/dev/…, a fork bomb
16// files Write/Edit outside the project, ~/.claude and temp folders
17// (symbolic links resolved); the project is read again when the
18// working folder changes (cd, a worktree)
19// On Windows, paths compare without regard to case or slash direction, and
20// Git Bash drives (/c/…) count as C:\….
21//
22// mode block (default) refuses before the call runs; warn lets it run and
23// tells Claude and you. /barrier pass lets the next refused call run once.
24
25type Mode = 'block' | 'warn' | 'off'
26
27type Finding = { why: string }
28
29type Context = {
30 cwd: string
31 home: string
32 win: boolean
33 isAllowed: (path: string) => boolean
34 branch: () => Promise<string | null>
35}
36
37const PROTECTED = /^(?:main|master|prod|production|release|trunk)$/
38const PASS_MS = 10 * 60 * 1000
39
40const WHOLE: { pattern: RegExp; why: string; unless?: RegExp }[] = [
41 { pattern: /(?:^|[\s;&|(])(?:npm|pnpm|yarn)\s+publish\b/, why: 'publishes a package (npm publish), which cannot be taken back', unless: /--dry-run\b/ },
42 { pattern: /\bcargo\s+publish\b/, why: 'publishes a crate (cargo publish), which cannot be taken back', unless: /--dry-run\b/ },
43 { pattern: /\btwine\s+upload\b/, why: 'uploads a release to PyPI (twine upload), which cannot be taken back' },
44 { pattern: /\bgh\s+release\s+create\b/, why: 'creates a public release (gh release create)' },
45 { pattern: /\bdocker\s+push\b/, why: 'pushes an image to a registry (docker push)' },
46 { pattern: /\bgem\s+push\b/, why: 'publishes a gem (gem push), which cannot be taken back' },
47 { pattern: /\bterraform\s+destroy\b|\bterraform\s+apply\b[^\n]*\s-destroy\b/, why: 'destroys infrastructure (terraform destroy)' },
48 { pattern: /\bkubectl\s+delete\b/, why: 'deletes cluster resources (kubectl delete)' },
49 { pattern: /\bhelm\s+(?:uninstall|delete)\b/, why: 'uninstalls a release from a cluster (helm uninstall)' },
50 {
51 // Only through a database client: grep "DROP TABLE" migrations/ is fine.
52 pattern: /\b(?:psql|mysql|mariadb|sqlite3|sqlcmd|duckdb|clickhouse(?:-client)?|mongosh?|cockroach\s+sql|supabase\s+db|prisma\s+db\s+execute)\b[^\n]*\b(?:drop\s+(?:table|database|schema)|truncate\s+table)\b/i,
53 why: 'drops data through a database client (DROP/TRUNCATE)',
54 },
55 { pattern: /\bmkfs(?:\.\w+)?\b|\bdd\b[^\n]*\bof=\/dev\//, why: 'overwrites a disk (mkfs / dd of=/dev/…)' },
56 { pattern: /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/, why: 'starts a fork bomb' },
57]
58
59export const register: Register = (on, options) => {
60 let mode: Mode = modeOf(options.mode)
61 let passUntil = 0
62 let roots: string[] = []
63 let projectRoot = ''
64 let cwd = ''
65 let home = ''
66 let win = false
67
68 const apply = (f: Folders) => {
69 projectRoot = f.projectRoot
70 cwd = f.cwd
71 home = f.home
72 win = f.win
73 roots = f.roots
74 }
75
76 on('session.start', async ($, e, next) => {
77 apply(await readFolders($, String(options.allow ?? ''), await $.session.cwd()))
78
79 const stored = await $.store.get('mode')
80 if (stored === 'block' || stored === 'warn' || stored === 'off') mode = stored
81 await $.command.register({
82 name: 'barrier',
83 description: 'GAME MODE barrier: status, block, warn, off, or pass the next refused call once',
84 argumentHint: '[block|warn|off|pass]',
85 })
86 return next(e)
87 })
88
89 // A new working folder (cd, a worktree) may be another project: read the folders again.
90 on('classic.CwdChanged', async ($, e, next) => {
91 apply(await readFolders($, String(options.allow ?? ''), e.new_cwd || (await $.session.cwd())))
92 return next(e)
93 }).catch(($, e, next) => next(e))
94
95 const isAllowed = (path: string) =>
96 roots.length === 0 || roots.some(root => path === root || path.startsWith(root.endsWith('/') ? root : root + '/'))
97
98 on('tool.call', async ($, e, next) => {
99 if (mode === 'off') return next(e)
100 const ctx: Context = {
101 cwd: cwd || '/',
102 home,
103 win,
104 isAllowed,
105 branch: () => currentBranch($, projectRoot),
106 }
107 const finding = await inspect($, String(e.tool), e as unknown as Record<string, unknown>, ctx, projectRoot)
108 if (finding === undefined) return next(e)
109
110 const label = String(e.tool).toUpperCase()
111 if (mode === 'block') {
112 const now = await $.clock.now()
113 if (now < passUntil) {
114 passUntil = 0
115 $.ui.log(`passed once by /barrier pass — ${label} (${finding.why})`)
116 return next(e)
117 }
118 $.ui.toast(`BARRIER! ${label} 차단 — ${finding.why} · /barrier pass`)
119 $.ui.log(`BARRIER! blocked ${label} (${finding.why})`)
120 return { deny: denyText(finding) }
121 }
122
123 const ran = await next(e)
124 $.ui.toast(`BARRIER? ${label} — ${finding.why} (warn mode: ran)`)
125 if (ran.deny !== undefined || ran.isError === true) return ran
126 return { ...ran, context: [...(ran.context ?? []), `game-barrier (warn mode): this call ${finding.why}. Tell the user what was changed and how to undo it, if it can be.`] }
127 }).catch(($, e, next) =>
128 next.called ? next(e) : { deny: 'game-barrier: the guard failed while checking this call, so it was stopped. Ask the user to check /barrier.' },
129 )
130
131 on('command.run', { command: 'barrier' }, async ($, e) => {
132 const sub = e.args.trim().split(/\s+/)[0]?.toLowerCase() ?? ''
133 const byPerson = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
134
135 if (sub === 'block' || sub === 'warn' || sub === 'off') {
136 if (sub !== 'block' && !byPerson) return { text: 'Only you can loosen the barrier: type the command yourself.' }
137 mode = sub
138 await $.store.set('mode', mode)
139 return { text: `barrier: ${mode}` }
140 }
141 if (sub === 'pass') {
142 if (!byPerson) return { text: 'Only you can pass a refused call: type /barrier pass yourself.' }
143 passUntil = (await $.clock.now()) + PASS_MS
144 return { text: 'The next call the barrier would refuse runs once (within 10 minutes).' }
145 }
146 if (sub !== '') return { text: `Unknown option "${sub}". Use block, warn, off or pass.` }
147 return {
148 text: [
149 `barrier: ${mode}`,
150 `inside: ${roots.join(', ') || '(set at session start)'}`,
151 '/barrier block refuse irreversible calls (default)',
152 '/barrier warn let them run; tell Claude and show a toast',
153 '/barrier off stop checking',
154 '/barrier pass let the next refused call run once',
155 ].join('\n'),
156 }
157 })
158}
159
160type Folders = { projectRoot: string; cwd: string; home: string; win: boolean; roots: string[] }
161
162/** The project root, working folder, home and every folder counted as inside, read now. */
163async function readFolders($: EngineInterface, allow: string, rawCwd: string): Promise<Folders> {
164 const rawRoot = await $.session.root()
165 const win = isWindowsPath(rawRoot) || isWindowsPath(rawCwd) || (await $.env.get('OS')) === 'Windows_NT'
166 const projectRoot = normalize(rawRoot, win)
167 const cwd = normalize(rawCwd, win)
168 let rawHome = (await $.env.get('HOME')) ?? ''
169 if (rawHome === '' && win) rawHome = (await $.env.get('USERPROFILE')) ?? ''
170 const home = rawHome === '' ? '' : normalize(rawHome, win)
171 const temps = [(await $.env.get('TMPDIR')) ?? '']
172 if (win) temps.push((await $.env.get('TEMP')) ?? '', (await $.env.get('TMP')) ?? '')
173 const listed = [
174 projectRoot,
175 cwd,
176 home ? `${home}/.claude` : '',
177 ...temps,
178 '/tmp',
179 '/private/tmp',
180 '/var/folders',
181 '/private/var/folders',
182 ...allow
183 .split(',')
184 .map(p => p.trim())
185 .filter(p => p.length > 0)
186 .map(p => (p.startsWith('~') ? home + p.slice(1) : p)),
187 ]
188 let roots = [...new Set(listed.filter(p => p !== '' && isAbsolute(p, win)).map(p => normalize(p, win)))]
189 for (const root of [...roots]) {
190 const real = await realOf($, root, win)
191 if (real && !roots.includes(real)) roots.push(real)
192 }
193 // Without the project folder among them, every edit would count as outside the project:
194 // check nothing rather than refuse everything.
195 if (!roots.includes(projectRoot) && !roots.includes(cwd)) {
196 roots = []
197 $.ui.log('could not read the project folder, so edits outside the project are not checked this session')
198 }
199 return { projectRoot, cwd, home, win, roots }
200}
201
202function modeOf(value: unknown): Mode {
203 return value === 'warn' || value === 'off' ? value : 'block'
204}
205
206function str(input: Record<string, unknown>, key: string): string | undefined {
207 const value = input[key]
208 return typeof value === 'string' ? value : undefined
209}
210
211async function inspect($: EngineInterface, tool: string, input: Record<string, unknown>, ctx: Context, projectRoot: string): Promise<Finding | undefined> {
212 if (tool === 'Bash') return inspectCommand(str(input, 'command') ?? '', ctx, projectRoot)
213 if (tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') {
214 const raw = str(input, 'file_path') ?? str(input, 'notebook_path')
215 if (raw === undefined) return undefined
216 const path = normalize(isAbsolute(raw, ctx.win) ? raw : `${ctx.cwd}/${raw}`, ctx.win)
217 if (!ctx.isAllowed(path)) return { why: `edits a file outside the project (${path})` }
218 const real = await realOf($, path, ctx.win)
219 if (real !== undefined && !ctx.isAllowed(real)) return { why: `edits a file outside the project through a link (${path} → ${real})` }
220 }
221 return undefined
222}
223
224export async function inspectCommand(command: string, ctx: Context, projectRoot: string): Promise<Finding | undefined> {
225 for (const rule of WHOLE) {
226 if (rule.pattern.test(command) && !(rule.unless?.test(command) ?? false)) return { why: rule.why }
227 }
228
229 for (const segment of command.split(/\|\||&&|[|;&\n]/)) {
230 const words = tokens(segment)
231 while (words[0] !== undefined && (words[0] === 'sudo' || words[0] === 'command' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0]))) words.shift()
232 const [head, ...rest] = words
233 if (head === 'git') {
234 const found = await inspectGit(rest, ctx)
235 if (found) return found
236 }
237 if (head === 'rm' && rest.some(w => /^-[a-zA-Z]*[rR]/.test(w) || w === '--recursive')) {
238 for (const target of rest.filter(w => !w.startsWith('-'))) {
239 const found = inspectRemoval(target, ctx, projectRoot)
240 if (found) return found
241 }
242 }
243 if ((head === 'chmod' || head === 'chown') && rest.some(w => /^-[a-zA-Z]*R/.test(w))) {
244 if (rest.some(w => w === '/' || w === '~' || w === '~/' || w === '$HOME')) return { why: `changes ${head === 'chmod' ? 'permissions' : 'owners'} of everything under / or ~` }
245 }
246 }
247 return undefined
248}
249
250async function inspectGit(args: string[], ctx: Context): Promise<Finding | undefined> {
251 // Skip git's own options (-C dir, -c key=value, --no-pager) to the subcommand.
252 let i = 0
253 while (i < args.length && args[i]!.startsWith('-')) i += args[i] === '-C' || args[i] === '-c' ? 2 : 1
254 const sub = args[i]
255 const rest = args.slice(i + 1)
256 const flags = rest.filter(w => w.startsWith('-'))
257 const plain = rest.filter(w => !w.startsWith('-'))
258
259 switch (sub) {
260 case 'push': {
261 const isForce =
262 flags.some(f => f === '--force' || f.startsWith('--force-with-lease') || f === '--force-if-includes' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(f)) ||
263 plain.some(w => w.startsWith('+'))
264 const isDelete = flags.includes('--delete') || flags.includes('-d') || plain.slice(1).some(w => w.startsWith(':'))
265 if (!isForce && !isDelete) return undefined
266 const verb = isDelete ? 'deletes' : 'force-pushes over'
267 const named = plain.slice(1).map(ref => (ref.replace(/^\+/, '').split(':').pop() ?? '').replace(/^refs\/heads\//, ''))
268 // HEAD and @ stand for the current branch.
269 const needsBranch = named.some(t => t === 'HEAD' || t === '@')
270 const current = needsBranch ? await ctx.branch() : null
271 const targets = named.map(t => (t === 'HEAD' || t === '@' ? (current ?? t) : t))
272 const hit = targets.find(t => PROTECTED.test(t))
273 if (hit) return { why: `${verb} the protected branch ${hit} (git push)` }
274 if (needsBranch && current === null) return { why: 'force-pushes HEAD, and the current branch could not be read' }
275 if (targets.length === 0 && !isDelete) {
276 const branch = await ctx.branch()
277 if (branch === null) return { why: 'force-pushes without naming a branch, and the current branch could not be read' }
278 if (PROTECTED.test(branch)) return { why: `force-pushes over the protected branch ${branch} (git push -f on ${branch})` }
279 }
280 return undefined
281 }
282 case 'reset':
283 return flags.includes('--hard') ? { why: 'discards uncommitted changes (git reset --hard)' } : undefined
284 case 'clean':
285 return flags.some(f => f === '--force' || /^-[a-zA-Z]*f/.test(f)) ? { why: 'deletes untracked files (git clean -f)' } : undefined
286 case 'checkout':
287 return plain.includes('.') ? { why: 'discards changes in the whole working tree (git checkout .)' } : undefined
288 case 'restore':
289 return plain.includes('.') && !(flags.includes('--staged') && !flags.includes('--worktree'))
290 ? { why: 'discards changes in the whole working tree (git restore .)' }
291 : undefined
292 case 'stash':
293 return plain[0] === 'drop' || plain[0] === 'clear' ? { why: `drops stashed work (git stash ${plain[0]})` } : undefined
294 case 'branch':
295 return flags.includes('-D') || (flags.includes('--delete') && flags.includes('--force'))
296 ? { why: 'force-deletes a branch that may not be merged (git branch -D)' }
297 : undefined
298 default:
299 return undefined
300 }
301}
302
303function inspectRemoval(raw: string, ctx: Context, projectRoot: string): Finding | undefined {
304 const target = raw.replace(/^['"]|['"]$/g, '')
305 if (/^(?:\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/\*?|\.|\.\/|\.\/\*|\*|\.\.|\.\.\/|\.\.\/\*)$/.test(target)) {
306 return { why: `deletes everything under ${target} (rm -r)` }
307 }
308 // Windows: a drive (C:\, /c/), the profile folder, or the current folder spelled with a backslash.
309 if (ctx.win && /^(?:[A-Za-z]:[\\/]?\*?|\/(?:cygdrive\/)?[A-Za-z]\/?\*?|~\\\*?|\.\\\*?|\.\.\\\*?|\$\{?USERPROFILE\}?[\\/]?\*?)$/.test(target)) {
310 return { why: `deletes everything under ${target} (rm -r)` }
311 }
312 if (target.includes('$') || target.includes('`')) return undefined
313 const expanded = /^~[\\/]/.test(target) ? ctx.home + target.slice(1) : target
314 const path = normalize(isAbsolute(expanded, ctx.win) ? expanded : `${ctx.cwd}/${expanded}`, ctx.win)
315 if (projectRoot !== '' && path === projectRoot) return { why: `deletes the project root (${path})` }
316 if (!ctx.isAllowed(path)) return { why: `deletes outside the project (${path})` }
317 return undefined
318}
319
320async function currentBranch($: EngineInterface, root: string): Promise<string | null> {
321 try {
322 const head = String(await $.fs.read(`${root}/.git/HEAD`)).trim()
323 const match = /^ref:\s*refs\/heads\/(.+)$/.exec(head)
324 return match?.[1] ?? null
325 } catch {
326 return null
327 }
328}
329
330/** The path with every symbolic link resolved, through its nearest existing ancestor. */
331async function realOf($: EngineInterface, path: string, win: boolean): Promise<string | undefined> {
332 try {
333 let cur = path
334 const rest: string[] = []
335 for (let step = 0; step < 64 && cur !== ''; step++) {
336 if (await $.fs.exists(cur)) {
337 const stat = await $.fs.stat(cur, { resolve: true })
338 if (stat.realPath === undefined) return undefined
339 return normalize([stat.realPath, ...rest].join('/'), win)
340 }
341 if (isRoot(cur)) return undefined
342 const cut = cur.lastIndexOf('/')
343 rest.unshift(cur.slice(cut + 1))
344 const parent = cut <= 0 ? '/' : cur.slice(0, cut)
345 // `c:` alone is the current folder on drive C, not its root.
346 cur = /^[a-z]:$/.test(parent) ? `${parent}/` : parent
347 }
348 } catch {
349 // Unreadable: judged by the spelling alone.
350 }
351 return undefined
352}
353
354function isRoot(path: string): boolean {
355 return path === '/' || /^[a-z]:\/$/.test(path) || /^\/\/[^/]+\/[^/]+$/.test(path)
356}
357
358/** A Windows spelling: a drive (`C:\`, `c:/`) or a network share (`\\server\share`). */
359export function isWindowsPath(path: string): boolean {
360 return /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\')
361}
362
363function isAbsolute(path: string, win: boolean): boolean {
364 return path.startsWith('/') || (win && isWindowsPath(path))
365}
366
367/**
368 * One comparable spelling of a path: `.`, `..` and repeated slashes collapsed. With `win` (a
369 * Windows session), backslashes become slashes, a Git Bash drive (`/c/…`) becomes `c:/…`, and
370 * the path is lower-cased, as Windows file names ignore case.
371 */
372export function normalize(path: string, win = false): string {
373 let p = path
374 let prefix = ''
375 if (win) {
376 p = p.replace(/\\/g, '/').toLowerCase()
377 const bash = /^\/(?:cygdrive\/)?([a-z])(?=\/|$)/.exec(p)
378 if (bash) p = `${bash[1]}:${p.slice(bash[0].length)}`
379 const drive = /^([a-z]):/.exec(p)
380 if (drive) {
381 prefix = `${drive[1]}:/`
382 p = p.slice(2)
383 } else if (p.startsWith('//')) {
384 prefix = '//'
385 p = p.slice(2)
386 }
387 }
388 const absolute = prefix !== '' || p.startsWith('/')
389 const out: string[] = []
390 for (const part of p.split('/')) {
391 if (part === '' || part === '.') continue
392 if (part === '..') out.pop()
393 else out.push(part)
394 }
395 if (prefix !== '') return prefix + out.join('/')
396 return (absolute ? '/' : '') + out.join('/') || (absolute ? '/' : '.')
397}
398
399function tokens(segment: string): string[] {
400 return (segment.match(/'[^']*'|"[^"]*"|\S+/g) ?? []).map(t => t.replace(/^(['"])(.*)\1$/, '$2'))
401}
402
403function denyText(finding: Finding): string {
404 return (
405 `game-barrier blocked this call: it ${finding.why}. ` +
406 'This cannot be undone from here. Find a reversible way (commit or stash first, work on a branch, stay inside the project), ' +
407 'or explain why it is needed and ask the user to run it themselves or to type /barrier pass.'
408 )
409}
410