David Ewins

claude-guardrails

One Claude Code hook with all your rules in a JSON file. MIT licence.

guardrails.shShow
guardrails.sh
#!/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.jsonShow
examples/guardrails.json
{
  "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 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.