Skip to content
/

Claude Code Guardrails

claude-code-guardrails · wangbooth/Claude-Code-Guardrails · ★ 54 · last commit 2025-09-15

Primitive shape 4 total
Hooks 4
00

Summary

Claude Code Guardrails — Summary

Claude Code Guardrails is a bash-script bundle that installs three Claude Code hooks to prevent accidental code loss during AI-assisted development: a pre-write branch guard (PreToolUse), a post-write auto-commit snapshot (PostToolUse), and a session-end checkpoint squasher (Stop/PreCompact).

Problem it solves: Claude Code modifies files directly without warning when working on protected branches, can overwrite uncommitted manual changes, and produces messy git histories with hundreds of micro-checkpoint commits. The three hooks enforce branch safety, preserve intermediate states as git snapshots, and squash those snapshots into clean task commits at session end.

Distinctive trait: The four-hook configuration covers the full write lifecycle — PreToolUse blocks dangerous writes, PostToolUse captures each change as a snapshot commit, Stop squashes checkpoints into a task commit, and PreCompact squashes before context compaction. This is a complete git-safety harness delivered as a bash install script that intelligently merges with existing .claude/settings.json.

Target audience: Developers using Claude Code who have experienced "AI overwrote my uncommitted work" or "git history has 200 micro-commits from one coding session."

Production-readiness: Active but small project (54 stars, MIT, Shell, last commit September 2025). Bilingual documentation (English, Chinese, Japanese). Clean install script with backup/dedup/idempotent behavior.

Differs from seeds: Most similar to spec-kit's PostToolUse hooks (which auto-run tests) in using the hook lifecycle for automation, but Claude Code Guardrails exclusively targets git safety rather than quality gates. Unlike superpowers's using-git-worktrees skill (which isolates features), Guardrails operates in-place and focuses on protecting the working state via continuous snapshotting rather than isolation.

01

Overview

Claude Code Guardrails — Overview

Origin

Created by wangbooth. The README is trilingual (English, Chinese, Japanese), suggesting a Chinese-origin project with international audience in mind. GitHub: wangbooth/Claude-Code-Guardrails.

Philosophy

"Triple Security Mechanism: Pre-write Interception Alert + Precise Snapshot Commits + Smart Merge Archiving"

The framework addresses what the README calls "Dangerous Moments" in vibe coding:

  • Direct modification on main branch
  • Interrupted modifications (intermediate artifacts lost)
  • Chaotic multiple modifications
  • Accidentally deleted important files
  • Manual changes overwritten by AI

Core Principles

  1. Protected branch interception — Block writes to main branch, suggest creating feature branch
  2. Uncommitted changes protection — Block when manual changes are uncommitted, force commit first
  3. File-level precise snapshots — Each modification commits only changed files (not git add .)
  4. Smart backup mechanism — Backup gitignore files to .claude/backups/ before modification
  5. Safe history merging — Multiple checkpoints intelligently merged into clean task commits

Design Constraints

  • Does not overwrite existing Claude Code Hooks — uses jq to intelligently merge .claude/settings.json
  • Backup + deduplication + idempotent — safe to run multiple times
  • Coexists with user hooks — does not affect existing hook configurations
  • Project-level vs global installation — both supported
02

Architecture

Claude Code Guardrails — Architecture

Distribution

  • Type: bash-script-bundle + Claude Code settings injection
  • License: MIT
  • Language: Shell

Install Methods

# Project-level (recommended)
curl -fsSL https://raw.githubusercontent.com/wangbooth/claude-code-guardrails/main/install.sh | bash

# Global installation
curl -fsSL https://raw.githubusercontent.com/wangbooth/claude-code-guardrails/main/install.sh | bash -s -- --global

# From clone (local installation)
./install.sh --target /path/to/project

Required Runtime

  • bash
  • git (configured with user.name / user.email)
  • jq (for JSON merging)
  • Claude Code (hooks system)

Directory Structure

Claude-Code-Guardrails/
├── .claude/
│   ├── settings.json           # Hook definitions
│   └── hooks/
│       └── guardrails/
│           ├── guard-branch.sh      # PreToolUse: branch protection + uncommitted changes
│           ├── auto-commit.sh       # PostToolUse: file-level snapshot commit
│           └── squash-checkpoints.sh # Stop/PreCompact: squash into task commit
├── install.sh                  # Installer: merges settings.json, copies scripts
├── uninstall.sh                # Removes hooks + scripts
├── README.md                   # English
├── README_CN.md                # Chinese
└── README_JA.md                # Japanese

Hook Configuration (.claude/settings.json)

{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Write|Edit|MultiEdit",
        "hooks": [{ "command": "...guard-branch.sh", "timeout": 10 }] }
    ],
    "PostToolUse": [
      { "matcher": "Write|Edit|MultiEdit",
        "hooks": [{ "command": "...auto-commit.sh", "timeout": 30 }] }
    ],
    "Stop": [
      { "hooks": [{ "command": "...squash-checkpoints.sh", "timeout": 30 }] }
    ],
    "PreCompact": [
      { "hooks": [{ "command": "...squash-checkpoints.sh compact", "timeout": 60 }] }
    ]
  }
}

Install Path Variants

  • Project install: Scripts at $CLAUDE_PROJECT_DIR/.claude/hooks/guardrails/; settings in .claude/settings.json
  • Global install: Scripts at ~/.claude/hooks/guardrails/; settings in ~/.claude/settings.json

Target AI Tools

Claude Code only (uses Claude Code's hook system exclusively).

03

Components

Claude Code Guardrails — Components

Hooks (4 events → 3 scripts)

Event Matcher Script Purpose
PreToolUse Write|Edit|MultiEdit guard-branch.sh Block writes to protected branches; block if uncommitted manual changes exist; suggest creating vibe branch
PostToolUse Write|Edit|MultiEdit auto-commit.sh Commit only the files changed in this tool-use as a snapshot commit (not git add .)
Stop (none) squash-checkpoints.sh Squash all checkpoint commits from this session into a single clean task commit
PreCompact (none) squash-checkpoints.sh compact Squash checkpoints before context compaction to prevent history pollution

Scripts (3 bash scripts)

Script Timeout Purpose
guard-branch.sh 10s Branch guard: detect protected branch (main/master), detect uncommitted manual changes, exit 2 (block) with explanation
auto-commit.sh 30s Auto-snapshot: stage only the files touched by the tool-use event, commit with timestamp and operation metadata
squash-checkpoints.sh 30s/60s Squash: identify session checkpoint commits, squash them into one well-named task commit

Install Scripts (2)

Script Purpose
install.sh Download scripts, create directories, jq-merge .claude/settings.json, set executable bits. Supports --global, --target, --verbose. Idempotent — backs up changed files.
uninstall.sh Remove hooks and scripts; restore settings.json

Backup Mechanism

Before modifying .gitignore or other tracked config files, auto-commit.sh backs up the original to .claude/backups/<filename>.bak.<timestamp>.

No Commands, Skills, MCP Servers

Pure hook automation. No slash commands, no skills, no MCP.

05

Prompts

Claude Code Guardrails — Prompts

Claude Code Guardrails is a pure bash/git automation system with no LLM calls and no prompt files. The "intelligence" is in git operations and exit codes, not AI.

Hook Behavior Specifications (from install.sh and README)

guard-branch.sh intent (not a prompt — bash logic):

IF current branch is main or master:
  EXIT 2 with message: "Protected branch detected. Create a 'vibe' branch first."

IF git status shows unstaged changes to tracked files:
  EXIT 2 with message: "Uncommitted manual changes detected. Commit or stash before continuing."

OTHERWISE:
  EXIT 0 (allow write to proceed)

auto-commit.sh intent:

CAPTURE the list of files modified in the tool-use event (from hook stdin JSON)
git add <only those files>  (not 'git add .')
git commit -m "checkpoint: [operation] [files] [timestamp]"
EXIT 0

squash-checkpoints.sh intent:

FIND all commits since session start with message prefix "checkpoint:"
IF count > 1:
  git rebase -i to squash them into one commit
  Use task-level commit message
EXIT 0

CLAUDE.md Content

The installed CLAUDE.md documents the hooks for the agent:

  • Explains that writes to main are blocked
  • Explains that auto-commit happens after each write
  • Explains that squash happens at session end This is context-injection, not a prompt — it tells the agent what behaviors to expect.

Note: No AI prompt files exist in this framework. All enforcement is bash + git.

09

Uniqueness

Claude Code Guardrails — Uniqueness

Differs from Seeds

Claude Code Guardrails is closest to spec-kit in using all four major hook events (PreToolUse, PostToolUse, Stop, PreCompact) for automation — but it automates git safety rather than quality checks. Unlike superpowers's using-git-worktrees skill (which isolates features in separate worktrees), Guardrails stays in-place and protects the current branch state through continuous snapshotting. Unlike claude-flow's worktree_per_feature: yes isolation, Guardrails does not create branches — it blocks writes to existing protected branches. The PreCompact hook (squash before compaction) is a capability no seed framework explicitly implements. The commits_automatically: yes behavior is shared with some seed frameworks but Guardrails does it with file-level precision (only changed files, not git add .) and includes a session-end squash that other frameworks lack.

Key Differentiators

  1. Four-event complete lifecycle: The only framework in the corpus that hooks PreToolUse + PostToolUse + Stop + PreCompact for a complete write-lifecycle coverage.
  2. File-level snapshots: Auto-commit only stages the files changed in the specific tool-use event, avoiding noise from git add ..
  3. Session-end squash: Checkpoint commits created during the session are squashed into one clean task commit at Stop.
  4. PreCompact squash: Squashes before context compaction — preventing history pollution at a boundary no other framework handles.
  5. Intelligent settings merge: jq-based merge of existing settings.json — installs alongside other hooks without collision.

Positioning

Claude Code Guardrails occupies the "git safety automation" niche — protecting against the three most common vibe-coding git disasters: pushing to main, overwriting uncommitted work, and creating messy micro-commit histories. It does not improve code quality or enforce methodology — it only protects the state of the repository.

Observable Failure Modes

  • Squash conflicts: If the session produced commits with diverging changes, git rebase interactive may conflict and block the squash.
  • jq dependency: Missing jq blocks installation entirely (the script exits with a clear error, but it's a hard dependency).
  • Squash identification: The squash script identifies checkpoints by commit message prefix "checkpoint:" — commits without this prefix (e.g., from other tools) may confuse the squash.
  • Pre-commit hook interaction: If the repository has pre-commit hooks, the auto-commit after each write may be slow or fail.
  • Global install context confusion: Global hooks apply to all Claude Code projects — blocking writes to main across all repos, even if some repos intentionally work on main.

Explicit Antipatterns

  • Direct commits to main/master branch by the AI agent
  • git add . instead of file-level staging (noise in commit history)
  • Hundreds of micro-commits from a single session
  • Losing intermediate work states when session is interrupted
04

Workflow

Claude Code Guardrails — Workflow

Normal Write Session

1. Claude Code attempts Write/Edit/MultiEdit
   → PreToolUse: guard-branch.sh
     - On main/master branch? → BLOCK (exit 2), suggest: create 'vibe' branch
     - Uncommitted manual changes exist? → BLOCK (exit 2), force user to commit first
     - OK → ALLOW (exit 0)

2. Write/Edit/MultiEdit executes

3. PostToolUse: auto-commit.sh
   → Stage only the files touched in this operation
   → Commit: "checkpoint: <operation-type> <file-list> [timestamp]"

4. Session continues with more writes → more snapshot commits

5. Session ends (Stop event): squash-checkpoints.sh
   → Identify all checkpoint commits from this session
   → Squash into one clean task commit
   → Git history: one commit per task instead of hundreds of micro-commits

Context Compaction Handling

PreCompact fires → squash-checkpoints.sh compact
   → Squash all pending checkpoints before context is compacted
   → Prevents loss of work tracking across compaction boundary

Phase-to-Artifact Map

Phase Artifact
Each write Snapshot commit in git history
Session end Squashed task commit in git history
PreCompact Squashed commits before context reset
gitignore edit Backup in .claude/backups/

Approval Gates

Gate Trigger Type
Branch protection PreToolUse on main/master Automated block (exit 2)
Uncommitted changes check PreToolUse when dirty working tree Automated block (exit 2)

No user-facing approval gates — all decisions are automated.

Intelligent Settings Merge

The installer merges hook definitions using jq rather than overwriting. Existing hooks are preserved; Guardrails entries are added without collision.

06

Memory Context

Claude Code Guardrails — Memory & Context

State Storage

Storage Path Purpose
Git history .git/ All snapshot commits and squashed task commits
File backups .claude/backups/ Pre-modification backups of config files
Hook configs .claude/settings.json Merged hook definitions

Persistence Model

  • Permanent: Git commits persist indefinitely in the repository
  • Session-scoped: Checkpoint commits are squashed at session end (Stop event)
  • Backup-scoped: .claude/backups/ accumulates timestamped backups

Context Injection

The CLAUDE.md installed by Guardrails informs the agent about the hook behaviors — specifically that writes to main are blocked, that auto-commits happen after each write, and that checkpoints are squashed at session end. This is informational context, not behavior modification.

Cross-Session Handoff

Implicit via git history. The squashed task commit from the previous session is visible in git log, providing a clear record of what was accomplished.

Compaction Handling

Explicit: PreCompact hook fires squash-checkpoints.sh compact before context is compacted. This ensures that even if context is lost, the git history reflects a clean state.

No AI Memory System

Guardrails has no semantic memory, vector store, or cross-session knowledge persistence. State lives entirely in git.

07

Orchestration

Claude Code Guardrails — Orchestration

Multi-Agent

No — Guardrails is a single-session git safety layer. No multi-agent coordination.

Orchestration Pattern

None. Event-driven bash hooks, not an orchestration system.

Execution Mode

Event-driven — hooks fire in response to Claude Code lifecycle events.

Multi-Model

No.

Isolation Mechanism

None — Claude Code Guardrails operates in-place (no worktrees, no containers). Branch protection is enforced via blocking, not isolation. The safety model is "don't let the agent write to the wrong branch" rather than "run the agent in a separate workspace."

Git Automation

Yes — this is the primary purpose:

  • commits_automatically: yes (PostToolUse auto-commit after every write)
  • creates_pr_automatically: no
  • merges_automatically: no

The squash-checkpoints mechanism creates clean task commits automatically at session end.

Consensus Mechanism

None.

Prompt Chaining

No.

Streaming Output

No.

08

Ui Cli Surface

Claude Code Guardrails — UI / CLI Surface

CLI

No dedicated CLI binary. The installer is a bash script:

# Project-level
curl -fsSL ...install.sh | bash

# With flags
./install.sh --global
./install.sh --target /path/to/project
./install.sh --verbose
./uninstall.sh

Flags: --global, --target <dir>, --verbose/-v, --help/-h.

No Web Dashboard, No TUI

All output is through Claude Code's hook feedback (block messages shown in-context) and git history.

User-Facing Messages (from hooks)

When a write is blocked by guard-branch.sh:

  • English: "Protected branch detected. Create a 'vibe' branch first."
  • Chinese: "检测到受保护分支。请先创建 'vibe' 分支。" (bilingual friendly reminders noted in README)

IDE Integration

Claude Code only. The hooks fire within any Claude Code session (terminal, VSCode extension, etc.).

Observability

Git history serves as the audit log:

  • Every write creates a checkpoint: commit
  • Session end produces a squashed task commit
  • git log shows the full session history

No separate audit log format.

Related frameworks

same archetype · same primary tool · same memory type

OpenHarness ★ 13k

Open-source Python agent runtime providing complete harness infrastructure: tools, memory, governance, swarm coordination, and…

Trae Agent ★ 12k

Research-friendly open-source CLI coding agent by ByteDance, designed for academic ablation studies and modular LLM provider…

Sweep AI ★ 7.7k

Autonomous GitHub bot that converts issues to pull requests using a sequential multi-agent pipeline.

Agent Governance Toolkit (microsoft) ★ 2.3k

Enterprise-grade AI agent governance: YAML policy enforcement, 12-vector prompt injection defense, zero-trust identity,…

TDD Guard ★ 2.1k

Mechanically enforces the Red-Green-Refactor TDD cycle by blocking file writes that violate TDD principles via a PreToolUse hook…

Agentic Coding Flywheel Setup (ACFS) ★ 1.5k

Take a complete beginner from laptop to three AI coding agents running on a VPS in 30 minutes via an idempotent manifest-driven…