claude-guardrails
One Claude Code hook with all your rules in a JSON file. MIT licence.
It is one Claude Code hook. It blocks commands, asks before risky ones, keeps files out of folders and adds reminders after edits. It needs only bash and jq, and takes around 10 to 20 milliseconds per tool call.
Source: github.com/davidewins/claude-guardrails.
{
"tools": ["Bash"],
"command": ["eas(-cli)?[[:space:]]+build", "(--profile|-e)[= ]+production"],
"decision": "ask",
"reason": "Production EAS build: needs the user's explicit go-ahead."
}Install
git clone https://github.com/davidewins/claude-guardrails ~/.claude/claude-guardrails
cp ~/.claude/claude-guardrails/examples/guardrails.json ~/.claude/guardrails.jsonAdd the hook to ~/.claude/settings.json (or a project's .claude/settings.json):
{
"hooks": {
"PreToolUse": [
{ "matcher": "Bash|Write|Edit", "hooks": [{ "type": "command", "command": "~/.claude/claude-guardrails/guardrails.sh", "timeout": 5 }] }
],
"PostToolUse": [
{ "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "~/.claude/claude-guardrails/guardrails.sh", "timeout": 5 }] }
]
}
}The config is read from $GUARDRAILS_CONFIG, or ~/.claude/guardrails.json if that is not set. If the file is missing, the hook does nothing.
Rules
rules is a list. On each tool call the first rule that matches wins. If no rule matches, the hook prints nothing and Claude Code carries on as normal.
event:PreToolUse(default) orPostToolUsetools: Tool names the rule applies to, such as["Bash"]or["Write", "Edit"]. Leave it out to match every tool.command: Regexes tested against a Bash command. All of them must match.path: Globs tested againstfile_path. One of them must match.*matches across/. Case is ignored.except: Globs that cancel apathmatch.decision:deny,askorallow(PreToolUse)reason: Shown to Claude (deny) or to you (ask)context: Text added to Claude's context instead of a decision. Use it for reminders on PostToolUse.
Regexes use jq's Oniguruma syntax, so POSIX classes like [[:space:]] work. Matching is on the raw command text, so ssh host 'bun install' is caught too.
Before matching, file_path is cleaned up: ., .. and doubled slashes are resolved, so docs/blog/../PLAN.md cannot slip past an except glob. Symlinks are followed too: a path rule is checked against the path as written and against the real path, and it applies if either one matches and is not excepted. Globs ignore case, because on a Mac or Windows disk docs/plan.md and Docs/PLAN.md are the same file.
If an except glob names a folder through a symlink (on a Mac /tmp is a link to /private/tmp), write it so it also matches the real path, for example */tmp/*.
Path rules only see the file_path of tools like Write and Edit. A file written by a Bash command (echo > file, cp, sed -i) is not checked against them. Use a command rule to catch those.
If the config has bad JSON or a bad regex, the hook exits 2 and blocks the call instead of letting it through.
Example rules
examples/guardrails.json has rules for the following:
- no bun
- no unrequested PRs
- ask before production EAS builds and OTA updates
- no new plan
.mdfiles in a projects folder - a screenshot reminder after UI edits
Test
./test/run.shEach line of test/cases.jsonl is a hook input plus the expected result (deny, ask, allow, context or none), checked against the example config.
Full source
The hook script and the example config, ready to copy.
guardrails.shShowHide
#!/usr/bin/env bash
# claude-guardrails: one Claude Code hook, every rule in a JSON config.
#
# Wire it to PreToolUse and PostToolUse in settings.json. On each call it reads
# the hook input from stdin, finds the first rule that matches, and prints the
# hook output for it (deny / ask / allow, or extra context). No match: no output.
#
# Config: $GUARDRAILS_CONFIG, else ~/.claude/guardrails.json.
set -u
config="${GUARDRAILS_CONFIG:-$HOME/.claude/guardrails.json}"
[ -f "$config" ] || exit 0
input="$(cat)"
# The real path of $1 after following symlinks, so a link into a protected folder is
# matched as that folder. The file may not exist yet: this resolves the deepest part
# that does and puts the rest back on the end.
realpath_of() {
local p="$1" rest="" target dir hops=0
while :; do
if [ -L "$p" ] && [ "$hops" -lt 40 ]; then
hops=$((hops + 1))
target="$(readlink "$p")" || break
case "$target" in /*) p="$target" ;; *) p="$(dirname "$p")/$target" ;; esac
continue
fi
if [ -d "$p" ] && dir="$(cd -P -- "$p" 2>/dev/null && pwd -P)"; then
printf '%s%s' "${dir%/}" "$rest"
return
fi
case "$p" in / | . | "") break ;; esac
rest="/$(basename "$p")$rest"
p="$(dirname "$p")"
done
printf '%s' "$1"
}
real=""
case "$input" in *'"file_path"'*)
raw="$(printf '%s' "$input" | jq -r '(.tool_input.file_path // "") as $f
| if $f == "" or ($f | startswith("/")) or (.cwd // "") == "" then $f else .cwd + "/" + $f end' 2>/dev/null)"
[ -n "$raw" ] && real="$(realpath_of "$raw")"
;;
esac
# Fail closed: a broken config or bad regex blocks the call (exit 2) instead of letting it through.
printf '%s' "$input" | jq -c --slurpfile cfg "$config" --arg real "$real" '
# Glob to anchored regex. * and ? match across /, like a bash case pattern.
# Case is ignored: on a Mac or Windows disk docs/plan.md and Docs/PLAN.md are the same file.
def glob2re: "^" + (gsub("(?<c>[.+^${}()|\\[\\]\\\\])"; "\\\(.c)") | gsub("\\*"; ".*") | gsub("\\?"; ".")) + "$";
def anyglob($s): any(.[]; . as $g | $s | test($g | glob2re; "i"));
# Resolve ., .. and repeated slashes so a/_archive/../plan.md cannot slip past an except glob.
# Relative paths are resolved against the hook cwd; a leading .. that is left over is kept.
def normpath:
(if startswith("/") then "/" else "" end) as $root
| $root + (reduce (split("/")[] | select(. != "" and . != ".")) as $p ([];
if $p != ".." then . + [$p]
elif length > 0 and .[-1] != ".." then .[:-1]
elif $root == "" then . + [".."]
else . end) | join("/"));
. as $in
| ($in.tool_input.command // "") as $cmd
| ($in.tool_input.file_path // "") as $raw
| (if $raw == "" or ($raw | startswith("/")) or ($in.cwd // "") == "" then $raw else $in.cwd + "/" + $raw end | normpath) as $file
# The path as written and the path the symlinks lead to. A path rule applies if either one
# matches and is not excepted.
| ([$file, (if $real == "" then $file else ($real | normpath) end)] | unique) as $files
| [ $cfg[0].rules[]
| select((.event // "PreToolUse") == $in.hook_event_name)
| select(.tools == null or any(.tools[]; . == $in.tool_name))
| select(.command == null or all(.command[]; . as $re | $cmd | test($re)))
| select(.path == null or (. as $rule | any($files[]; . as $f
| ($rule.path | anyglob($f)) and (($rule.except // []) | anyglob($f) | not))))
]
| first // empty
| if .context then
{hookSpecificOutput: {hookEventName: $in.hook_event_name, additionalContext: .context}}
else
{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: .decision, permissionDecisionReason: .reason}}
end
' || { echo "claude-guardrails: could not evaluate $config (bad JSON or regex), blocking." >&2; exit 2; }examples/guardrails.jsonShowHide
{
"rules": [
{
"tools": ["Write"],
"path": ["*/projects/*.md"],
"except": ["*/README.md", "*/CHANGELOG.md", "*/CLAUDE.md", "*/AGENTS.md", "*/SKILL.md", "*/node_modules/*", "*/docs/blog/*"],
"decision": "deny",
"reason": "Plans, specs and audits go in the issue tracker, not new .md files in the repo. Write content docs under docs/blog/ or ask the user first."
},
{
"tools": ["Bash"],
"command": ["(^|[;&|(`\"'[:space:]])bunx?([[:space:]]|$)"],
"decision": "deny",
"reason": "This project uses npm. Use npm / npx instead of bun / bunx."
},
{
"tools": ["Bash"],
"command": ["gh[[:space:]]+pr[[:space:]]+create"],
"decision": "deny",
"reason": "Do not open pull requests unless the user asks for one."
},
{
"tools": ["Bash"],
"command": ["eas(-cli)?[[:space:]]+build", "(--profile|-e)[= ]+production"],
"decision": "ask",
"reason": "Production EAS build: needs the user's explicit go-ahead."
},
{
"tools": ["Bash"],
"command": ["eas(-cli)?[[:space:]]+update"],
"decision": "ask",
"reason": "OTA update: confirm lint passed and the channel, runtime version and env are right before shipping."
},
{
"event": "PostToolUse",
"tools": ["Write", "Edit"],
"path": ["*/src/*.tsx"],
"except": ["*__tests__*", "*.test.tsx", "*.spec.tsx"],
"context": "UI file changed. Before calling this done:\n- Screenshot it in light and dark mode and look at the result.\n- Check the empty, loading and error states.\nIf you did not check something, say so."
}
]
}Licence
MIT.
Licence text
MIT License Copyright (c) 2026 David Ewins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.