cc-safe-setup

May 15, 2026 · View on GitHub

npm version npm downloads tests

🚀 Launching on Product Hunt, April 21! Follow us and upvote to support open source safety for AI coding agents.

One command to make Claude Code safe for autonomous operation. 734 example hooks · 70+ Anthropic Issues addressed by hook · 9,200+ tests · 30K+ total installs · 日本語

npx cc-safe-setup

Installs 8 safety hooks in ~10 seconds. Blocks rm -rf /, prevents pushes to main, catches secret leaks, validates syntax after every edit. Zero npm dependencies. Hooks use jq at runtime (brew install jq / apt install jq).

What's a hook? A checkpoint that runs before Claude executes a command. Like airport security, it inspects what's about to happen and blocks anything dangerous before it reaches the gate.

▶ Live Demo (see hooks block rm -rf in your browser) · Incident Tracker (90 real incidents) · Token Checkup (what type are you?) · All 8 Tools

  cc-safe-setup
  Make Claude Code safe for autonomous operation

  Prevents real incidents (from GitHub Issues):
  ✗ rm -rf permanently destroyed ~50 GB / 1,500 files (#49129) ← April 2026
  ✗ Auto mode approved ~/.ssh deletion, all SSH keys gone (#49554)
  ✗ ~/.git-credentials PATs deleted without confirmation (#49539)
  ✗ rm -rf deleted 3,467 files (~7 GB) without confirmation (#46058)
  ✗ rm -rf deleted entire user directory via NTFS junction (#36339)
  ✗ Remove-Item -Recurse -Force destroyed unpushed source (#37331)
  ✗ Entire Mac filesystem deleted during cleanup (#36233)
  ✗ Untested code pushed to main at 3am
  ✗ Force-push rewrote shared branch history
  ✗ API keys committed to public repos via git add .
  ✗ Syntax errors cascading through 30+ files
  ✗ Sessions losing all context with no warning
  ✗ CLAUDE.md rules silently ignored after context compaction
  ✗ Claude ran destructive DDL on production database (#46684)
  ✗ AI executed delete/kill operations on production environment (#46650)
  ✗ Subagents ignoring all CLAUDE.md rules since v2.1.84 (#40459)

  Hooks to install:

  ● Destructive Command Blocker
  ● Branch Push Protector
  ● Post-Edit Syntax Validator
  ● Context Window Monitor
  ● Bash Comment Stripper
  ● cd+git Auto-Approver
  ● Secret Leak Prevention

  Install all 8 safety hooks? [Y/n] Y

  ✓ Done. 8 safety hooks installed.

Why This Exists

A user lost 3,467 files (~7 GB) when Claude ran rm -rf on their data directory without confirmation. Another lost their entire C:\Users directory when rm -rf followed NTFS junctions. Another lost all source code when Claude ran Remove-Item -Recurse -Force * on a repo. One user's Claude ran destructive DDL on a production database when asked only to investigate. Another had Claude execute delete and kill operations on production systems. Others had untested code pushed to main at 3am. API keys got committed via git add .. Syntax errors cascaded through 30+ files before anyone noticed. And CLAUDE.md rules get silently dropped after context compaction, your instructions vanish mid-session.

One user analyzed 6,852 sessions and found the Read:Edit ratio dropped from 6.6 to 2.0, Claude editing files it never read jumped from 6% to 34%. That issue has over 2,100 reactions. The read-before-edit example hook catches this pattern before damage happens.

In April 2026, $1,446 was transferred without authorization when Claude moved funds between exchange accounts. A user lost $367 and got their account suspended from a Claude-generated script. Physical coordinates were uploaded to a public website despite 17 sessions of "no PII" in CLAUDE.md. And deny rules can be bypassed with 50+ subcommands.

Claude Code ships with no safety hooks by default. This tool fixes that. (Standalone guard script for quick setup | Database protection hooks | Credential protection hooks | Fabrication detection hook | Security vulnerability hooks)

Works with Auto Mode. Claude Code's Auto Mode sandboxing provides container-level isolation. cc-safe-setup adds process-level hooks as defense-in-depth, catching destructive commands even outside sandboxed environments.

Works with subagents. Since v2.1.84, subagents and teammates don't receive CLAUDE.md, your project rules are silently skipped. Hooks operate at the process level, but subagent tool calls may bypass PreToolUse hooks in some configurations. As defense-in-depth, cc-safe-setup installs hooks at the user level (~/.claude/settings.json). The subagent-claudemd-inject example hook re-injects critical rules into subagent prompts.

🚨 Opus 4.7 Crisis (April 2026)

Opus 4.7 broke auto mode's safety classifier, it was hardcoded to Opus 4.6. If you use auto mode with Opus 4.7, dangerous commands run without the built-in safety check. In 3 days: 50 GB permanently deleted, ~/.ssh wiped, git credentials destroyed, shell configs truncated to 0 bytes. Users report 4x token consumption from silent model switches.

One command to fix it:

npx cc-safe-setup --opus47

Installs 4 hooks targeting known Opus 4.7 regressions. Full details → · Emergency Defense Kit (Gist) · Safety Scanner

What Gets Installed

HookPreventsRelated Issues
Destructive Guardrm -rf /, git reset --hard, git clean -fd, git checkout --force, sudo + destructive, PowerShell Remove-Item -Recurse -Force, rd /s /q, NFS mount detection#46058 #36339 #36640 #37331
Branch GuardPushes to main/master + force-push (--force) on all branches
Secret Guardgit add .env, credential files, git add . with .env present#6527
Syntax CheckPython, Shell, JSON, YAML, JS errors after edits
Context MonitorSession state loss from context window overflow (40%→25%→20%→15% warnings)
Comment StripperBash comments breaking permission allowlists#29582
cd+git Auto-ApproverPermission prompt spam for cd /path && git log#32985 #16561
API Error AlertSilent session death from rate limits or API errors, desktop notification + log

Each hook exists because a real incident happened without it.

Free diagnostic tools

ToolWhat it does
Token Checkup5 questions → find where your tokens are going (30 seconds)
Security Checkup6 questions based on real incidents ($1,800+ in losses)
Version CheckIs your CC version affected by cache inflation?

Free guides

GuideWhat it covers
6-hook fortification for the 2026-04 regression clusterThe April 2026 postmortem recap + which 6 cc-safe-setup hooks would have caught each issue. No signup.
Find which CC versions ran your cache regression sessionsOne-line grep + jq diagnostic over ~/.claude/ logs. Shows per-day per-version count of sessions affected by #46829/#46917.
/usage --json: 5 fields, one ratio that decides whether you migratecache_creation_ratio cheat sheet for the v2.1.118 /usage --json output. Five fields and one ratio with HEALTHY / WATCH / TRIGGER bands so you can decide migration timing from your own logs, no third-party dashboard.
PocketOS 9-second wipe, 3-prevention audit scriptRead-only audit script (Railway / AWS / GCP / GitHub examples) for the three preventions surfaced by the 2026-04-25 PocketOS production-database wipe (HN 817pt). No destructive commands; prints questions and read-only checks you run yourself.
Postmortems incident #1 free preview, cache TTL regression Signal + DiagnosisVerbatim chapter excerpt from the Postmortems book (live on Gumroad since 2026-05-05). Three read-only checks (one minute total) to tell whether the March 2026 cache TTL regression hit your sessions, no purchase required.
Copilot 2026-06-01 transition pre-flight checklistFive read-only audit steps to run today before GitHub's "Preview my bill" tool launches in early May. Identifies your tier, inventories your past 30-day usage by surface, and stages the stay/switch/hybridize decision tree against your own numbers. No purchase required.
Five primary-source-verified Claude Code signals (2026-04-26 to 2026-04-28)48-hour roundup with audit one-liners. #52921 (Max 20× weekly limits resetting on a ~24-hour cycle, Anthropic in-app support acknowledged), #53489 (Web MCP connectors lost + v2.1.120 force-rolled-back within 24h), #53262 (HERMES.md substring routing), plugin hook path drift cluster, and the 2026-04-25 Anthropic Rate Limits API release. Two issues independently primary-source-verified.
claim-verify-audit.sh — 8 diagnostic checks for the May 2026 failure-mode clusterOne-shot read-only audit (single bash file, MIT). Eight checks against documented patterns: 8.3 short-name allow-rule bypass (#58614), skill bloat token tax (Reddit 1tbbove), session backup absence (#58608), .env subagent inheritance (#57068), auto-compact drift (#57490 + #58373), bypassPermissions remote override (#57810), settings.json JSON validity (#57491), cache-trail forensic (#58608). Each finding cites the source issue + the prevention chapter. Run with bash scripts/claim-verify-audit.sh from any working directory. Also published as a standalone Gist.

Companion log-analysis tools (third-party)

These are unaffiliated projects that pair well with the cc-safe-setup hooks, they read your ~/.claude/projects/ JSONL logs from a post-hoc analysis angle, where the hooks here intervene at pre-execution time. Use them together if you want both prevention (hooks) and observation (viewers).

ToolWhat it doesLicense
delexw/claude-code-trace (251★)Real-time viewer for Claude Code session logs, desktop app (Tauri), web UI, and TUI. Browse projects, conversations, tool calls, token usage. Rust + TypeScript + React.MIT
Claude Code のログから学びを得る (slides, JP)DS perspective on parsing CC logs to learn from agent behavior. JSONL format walkthrough, subagent delegation patterns, EDA examples. By @rmizuta3, GO/DeNA AI Community 2026-03-26.Public slides

Go deeper

ResourceWhat you getPrice
Token BookCut token consumption in half. CLAUDE.md templates, hook configs, context management, 32 failure patterns with fixes. 44,000+ words from 800+ hours of real operation data.¥2,500 (~$17). Ch.1 free
Migration PlaybookStay, switch, or hybridize? Six-week timeline of the April 2026 quota wars + 5 measurable migration triggers + Path A/B/C frameworks + cost forecasting worksheet + decision tree + 48-hour rollback checklist. Edition 1, 105 pages, English. Live since 2026-04-25; free verified-update sweep on 2026-05-08. Edition 2 ships 2026-05-22 with 4 new triggers, 3 new migration paths (A'/B'/D), and a 9-layer expansion of the claim-vs-reality cluster. Free update for Edition 1 buyers via the Gumroad library.$19. Free preview Gist
Claim-Verify HandbookForensic record of 95 cases (15 main + 80 Appendix D continuing evidence, 192 hours from 2026-05-09 to 2026-05-15 morning, 23-fold acceleration over the 30-day baseline) where Claude Code or its sub-agents claimed success while the underlying runtime did not match. 3-stage framework + 14 operator defenses + 5 detection tools (all 5 implemented and tested, 165+ test cases passing). Anchored by Anthropic's own v2.1.140 release (5 fix items mapping directly to the failure-mode taxonomy) and the immediate v2.1.141 regression of the same shape. Ships 2026-05-22, sister product to Migration Playbook Edition 2.$19. Free preview Gist
Incident PostmortemsForensic archaeology of 10 production-level Claude Code incidents (cache TTL, Opus 4.7 silent downgrade, tokenizer inflation, MCP regression, weekly quota reset, /doctor settings corruption, and more), each with reproduction steps, official response analysis, and a detection hook. 100 pages, English. Live since 2026-05-05.See product page for the current price. Free preview
Safety GuideEnd-to-end Claude Code safety setup. From first install to overnight autonomous runs.¥800 (~$5). Ch.3 free
CLAUDE.md Audit (service)Written audit of your CLAUDE.md + top-3 fixes, delivered within 48h via this repo's Issue tracker.$29 (~¥3,980)
Token Burn Audit (service)Diagnosis of your actual /cost output, top 3 waste patterns tied to Token Book Ch.8 symptoms, with per-pattern fixes. 48h delivery.$29 (~¥3,980)
CC Safety Lab FounderMonthly digest: 4–8 newly-found incidents (with fixes), 1 deep-dive failure case, 1–2 copy-paste safety hooks, an updated safety checklist, and product update notes. The recurring companion to the one-time books.¥500/month, Founder pricing locked. Free May 2026 preview Gist

Why pay? A Max plan costs $200/month. One token waste incident burns 50–80% of your weekly quota in hours (#46727). One rm -rf incident costs days of recovery. The Token Book costs less than 2 hours of Max subscription time, and the CLAUDE.md templates alone can reduce consumption by 40%. For the recurring track, one Safety Lab month covers what would otherwise mean reading 50–100 GitHub Issues yourself; one avoided Max-plan incident pays for a year of membership.

Pick one path. Cost out of control? → Token Book. Considering a switch (Cursor / Codex / Cline)? → Migration Playbook. Need to know what's already broken in production? → Incident Postmortems. Need to keep up with what's breaking now? → Safety Lab.

v2.1.85: if Field Support

Hooks now support an if field for conditional execution. The hook process only spawns when the command matches the pattern, ls won't trigger a git-only hook.

{
  "type": "command",
  "if": "Bash(git push *)",
  "command": "~/.claude/hooks/test-before-push.sh"
}

All example hooks include if field documentation in their headers.

PermissionRequest Hooks (NEW)

Override Claude Code's built-in confirmation prompts. These run after the built-in safety checks, so they can auto-approve prompts that permissions.allow cannot suppress.

HookWhat It SolvesIssue
quoted-flag-approver"Quoted characters in flag names" prompt on git commit -m "msg"#27957
bash-heuristic-approverSafety heuristic prompts for $(), backticks, ANSI-C quoting#30435
edit-always-allowEdit prompts in .claude/skills/ despite bypassPermissions#36192
allow-git-hooks-dirEdit prompts in .git/hooks/ for pre-commit/pre-push setup
allow-protected-dirsAll protected directory prompts (CI/Docker environments)#36168
git-show-flag-sanitizerStrips invalid --no-stat from git show (wastes context on error)#13071
compact-blockerBlocks auto-compaction via PreCompact (preserves full context)#6689
webfetch-domain-allowAuto-approves WebFetch by domain (fixes broken domain:* wildcard)#9329

Install any of these: npx cc-safe-setup --install-example <name>

Session Protection Hooks

Guards against issues that corrupt sessions or waste tokens silently.

HookWhat It SolvesIssue
cch-cache-guardBlocks reads of Claude session/billing files that poison prompt cache via cch= substitution#40652
image-file-validatorBlocks Read of fake image files (text in .png) that permanently corrupt sessions#24387
terminal-state-restoreRestores Kitty keyboard protocol, cursor, bracketed paste on exit#39096 #39272
large-read-guardWarns before reading large files via cat/less that waste context tokens#41617
prompt-usage-loggerLogs every prompt with timestamps to track token consumption patterns#41249
compact-alert-notificationAlerts when auto-compaction fires (tracks compact-rebuild cycles that burn tokens)#41788
token-budget-guardBlocks tool calls when estimated session cost exceeds a configurable threshold#38335
session-index-repairRebuilds sessions-index.json on exit so claude --resume finds all sessions#25032
session-backup-on-startBacks up session JSONL files on start (protects against silent deletion)#41874
working-directory-fenceBlocks Read/Edit/Write outside CWD (prevents operating on wrong project copy)#41850
mcp-warmup-waitWaits for MCP servers to initialize on session start (fixes first-turn tool errors)#41778
pre-compact-transcript-backupFull JSONL backup before compaction (protects against rate-limit data loss)#40352
conversation-history-guardBlocks access to session JSONL files (prevents 20x cache poisoning)#40524
read-before-editWarns when Edit targets a file not recently Read (Read:Edit ratio dropped 70%, #42796)#42796
replace-all-guardWarns/blocks Edit replace_all:true (prevents bulk data corruption)#41681
ripgrep-permission-fixAuto-fixes vendored ripgrep +x permission on start (fixes broken commands/skills)#41933

All 49 Commands

CommandWhat It Does
npx cc-safe-setupInstall 8 safety hooks
--create "desc"Generate hook from plain English
--audit [--fix|--json|--badge]Safety score 0-100
--lintStatic analysis of config
--diff <file>Compare settings
--compare <a> <b>Side-by-side hook comparison
--migrateDetect hooks from other projects
--generate-ciCreate GitHub Actions workflow
--shareGenerate shareable URL
--benchmarkMeasure hook speed
--dashboardReal-time terminal UI
--issuesGitHub Issues each hook addresses
--doctorDiagnose hook problems
--watchLive blocked command feed
--statsBlock history analytics
--learn [--apply]Pattern learning
--scan [--apply]Tech stack detection
--export / --importTeam config sharing
--verifyTest each hook
--install-example <name>Install from 727 examples
--examples [filter]Browse examples by keyword
--fullAll-in-one setup
--statusCheck installed hooks
--dry-runPreview changes
--uninstallRemove all hooks
--shieldMaximum safety in one command
--guard "rule"Instantly enforce a rule from English
--suggestPredict risks from project analysis
--from-claudemdConvert CLAUDE.md rules to hooks
--teamProject-level hooks for git sharing
--profile [level]Switch safety profiles
--save-profile <name>Save current hooks as profile
--analyzeSession analysis dashboard
--healthHook health table
--quickfixAuto-fix common problems
--replayVisual blocked commands timeline
--why <hook>Show real incident behind hook
--migrate-from <tool>Migrate from other hook tools
--diff-hooks [path]Compare hook configurations
--init-projectFull project setup (hooks + CLAUDE.md + CI)
--scoreCI-friendly safety score (exit 1 if below threshold)
--test-hook <name>Test a specific hook with sample input
--simulate "cmd"Preview how all hooks react to a command
--protect <path>Block edits to a file or directory
--rules [file]Compile YAML rules into hooks
--validateValidate all hook scripts (syntax + structure)
--safe-modeMaximum protection: all safety hooks + strict config
--changelogShow what changed in each version
--reportGenerate safety report
--helpShow help

Quick Start by Scenario

I want to...Command
Make Claude Code safe right nownpx cc-safe-setup --shield
Stop permission prompt spamnpx cc-safe-setup --install-example auto-approve-readonly
Enforce a rule instantlynpx cc-safe-setup --guard "never delete production data"
See what risks my project hasnpx cc-safe-setup --suggest
Convert CLAUDE.md rules to hooksnpx cc-safe-setup --from-claudemd
Share hooks with my teamnpx cc-safe-setup --team && git add .claude/
Choose a safety levelnpx cc-safe-setup --profile strict
See what Claude blocked todaynpx cc-safe-setup --replay
Know why a hook existsnpx cc-safe-setup --why destructive-guard
Block silent memory file editsnpx cc-safe-setup --install-example memory-write-guard
Stop built-in skills editing opaquelynpx cc-safe-setup --install-example skill-gate
Diagnose why hooks aren't workingnpx cc-safe-setup --doctor
Preview how hooks react to a commandnpx cc-safe-setup --simulate "git push origin main"
Protect a specific file from editsnpx cc-safe-setup --protect .env
Stop .git/ write promptsnpx cc-safe-setup --install-example allow-git-hooks-dir
Auto-approve compound git commandsnpx cc-safe-setup --install-example auto-approve-compound-git
Detect prompt injection patternsnpx cc-safe-setup --install-example prompt-injection-detector
Define rules in YAML, compile to hooksnpx cc-safe-setup --rules rules.yaml
Validate all hook scripts are correctnpx cc-safe-setup --validate
Maximum protection modenpx cc-safe-setup --safe-mode
Migrate from Cursor/WindsurfMigration Guide

Plugin Marketplace

Install safety hooks as Claude Code plugins, no npm required:

/plugin marketplace add yurukusa/cc-safe-setup
/plugin install safety-essentials@cc-safe-setup
PluginWhat it blocks
safety-essentialsrm -rf, force-push, hard-reset, .env overwrite, npm publish
git-protectionForce-push, main/master push, git clean, branch -D
credential-guard.env write/edit, API keys in commands, service account files

Also listed on claudemarketplaces.com.

Common Pain Points (from GitHub Issues)

ProblemIssueFix
Claude uses cat/grep/sed instead of built-in Read/Edit/Grep#19649 (48👍)npx cc-safe-setup --install-example prefer-builtin-tools
cd /path && cmd bypasses permission allowlist#28240 (88👍)npx cc-safe-setup --install-example compound-command-approver
Multiline commands skip pattern matching#11932 (47👍)Use hooks instead of allowlist patterns for complex commands
No notification when Claude asks a question#13024 (52👍)npx cc-safe-setup --install-example notify-waiting
allow overrides ask in permissions#6527 (17👍)Use hooks to block dangerous commands instead of ask rules
Plans stored in ~/.claude/ with random names#12619 (163👍)npx cc-safe-setup --install-example plan-repo-sync

How It Works

  1. Writes hook scripts to ~/.claude/hooks/
  2. Updates ~/.claude/settings.json to register the hooks
  3. Restart Claude Code, hooks are active

Safe to run multiple times. Existing settings are preserved. A backup is created if settings.json can't be parsed.

Maximum safety: npx cc-safe-setup --shield, one command: fix environment, install hooks, detect stack, configure settings, generate CLAUDE.md.

Instant rule: npx cc-safe-setup --guard "never touch the database", generates, installs, activates a hook instantly from plain English.

Team setup: npx cc-safe-setup --team, copy hooks to .claude/hooks/ with relative paths, commit to repo for team sharing.

Preview first: npx cc-safe-setup --dry-run

Check status: npx cc-safe-setup --status, see which hooks are installed (exit code 1 if missing).

Verify hooks work: npx cc-safe-setup --verify, sends test inputs to each hook and confirms they block/allow correctly.

Troubleshoot: npx cc-safe-setup --doctor, diagnoses why hooks aren't working (jq, permissions, paths, shebang).

Live monitor: npx cc-safe-setup --watch, real-time dashboard of blocked commands during autonomous sessions.

Uninstall: npx cc-safe-setup --uninstall, removes all hooks and cleans settings.json.

Requires: jq for JSON parsing (brew install jq / apt install jq).

Note: Hooks are skipped when Claude Code runs with --bare or --dangerously-skip-permissions. These modes bypass all safety hooks by design.

Known limitations:

  • In headless mode (-p / --print), hook exit code 2 may not block tool execution (#36071). For CI pipelines, use interactive mode with hooks rather than -p mode.
  • FileChanged notifications inject file contents into model context before hooks can intervene. If a sensitive file (.env, credentials.json) is modified externally during a session, its contents may appear in the conversation transcript regardless of hooks (#44909). Mitigation: use dotenv-watch to get alerted, and avoid editing sensitive files while Claude Code is running.

Before / After

Run npx cc-health-check to see the difference:

BeforeAfter
Safety Guards25%75%
Overall Score50/10095/100
Destructive commandsUnprotectedBlocked
Force pushAllowedBlocked
.env in gitPossibleBlocked
Context warningsNone4-stage alerts

Configuration

VariableHookDefault
CC_ALLOW_DESTRUCTIVE=1destructive-guard0 (protection on)
CC_SAFE_DELETE_DIRSdestructive-guardnode_modules:dist:build:.cache:__pycache__:coverage
CC_PROTECT_BRANCHESbranch-guardmain:master
CC_ALLOW_FORCE_PUSH=1branch-guard0 (protection on)
CC_SECRET_PATTERNSsecret-guard.env:.env.local:credentials:*.pem:*.key
CC_CONTEXT_MISSION_FILEcontext-monitor$HOME/mission.md

After Installing

Verify your setup:

npx cc-health-check

Full Kit

cc-safe-setup gives you 8 essential hooks. Want to know what else your setup needs?

Run npx cc-health-check (free, 20 checks) to see your current score. If it's below 80, the Claude Code Ops Kit fills the gaps, 6 hooks + 5 templates + 9 scripts + install.sh. Pay What You Want ($0+).

Starter Kit: Want hooks + settings + templates in one download? The Claude Code Safety Kit bundles 5 safety hooks, a pre-configured settings.json, CLAUDE.md templates, and 800-hour operation tips. Name your price ($0+).

Or browse the free hooks: claude-code-hooks

Examples

Safety Audit

Try it in your browser: paste your settings.json, get a score instantly. Nothing leaves your browser.

Or from the CLI:

npx cc-safe-setup --audit

Analyzes 9 safety dimensions and gives you a score (0-100) with one-command fixes for each risk.

CI Integration (GitHub Action)

# .github/workflows/safety.yml
- uses: yurukusa/cc-safe-setup@main
  with:
    threshold: 70  # CI fails if score drops below this

Project Scanner

npx cc-safe-setup --scan         # detect tech stack, recommend hooks
npx cc-safe-setup --scan --apply # auto-create CLAUDE.md with project rules

Create Hooks from Plain English

npx cc-safe-setup --create "block npm publish without tests"
npx cc-safe-setup --create "auto approve test commands"
npx cc-safe-setup --create "block curl pipe to bash"
npx cc-safe-setup --create "block DROP TABLE and TRUNCATE"

9 built-in templates + generic fallback. Creates the script, registers it, and runs a smoke test.

Self-Learning Safety

npx cc-safe-setup --learn        # analyze your block history for patterns
npx cc-safe-setup --learn --apply # auto-generate custom hooks from patterns

Examples

Need custom hooks beyond the 8 built-in ones? Install any example with one command:

npx cc-safe-setup --install-example block-database-wipe

Or browse all available examples in examples/:

  • claude-update-smart.sh: Skip the 226 MB tarball download when already up-to-date (workaround for #51243). Turns 30 s checks into 0.3 s. Falls through to the real claude update when a new release exists or the registry is unreachable.
  • auto-approve-git-read.sh: Auto-approve git status, git log, even with -C flags
  • auto-approve-ssh.sh: Auto-approve safe SSH commands (uptime, whoami, etc.)
  • enforce-tests.sh: Warn when source files change without corresponding test files
  • notify-waiting.sh: Desktop notification when Claude Code waits for input (macOS/Linux/WSL2)
  • edit-guard.sh: Block Edit/Write to protected files (defense-in-depth for #37210)
  • auto-approve-build.sh: Auto-approve npm/yarn/cargo/go/python build, test, and lint commands
  • auto-approve-docker.sh: Auto-approve docker build, compose, ps, logs, and other safe commands
  • block-database-wipe.sh: Block destructive database commands: Laravel migrate:fresh, Django flush, Rails db:drop, raw DROP DATABASE (#46684 #46650 #37405 #37439)
  • sql-bulk-delete-warn.sh: Warn when DELETE/UPDATE/TRUNCATE runs via psql/mysql/sqlite3/sqlcmd without a row-count safeguard. Catches the Issue #56738 pattern (DELETE WHERE col IS NULL after a regex/UPDATE that silently NULLed nearly every row, wiping 24,472 of 24,475 rows in 5 minutes before autovacuum cleaned the dead tuples). Also flags DELETE/UPDATE without WHERE, TRUNCATE TABLE, and psql -c invocations missing an explicit transaction. Strict mode via CC_SQL_BULK_DELETE_BLOCK=1 (#56738)
  • auto-approve-python.sh: Auto-approve pytest, mypy, ruff, black, isort, flake8, pylint commands
  • auto-snapshot.sh: Auto-save file snapshots before edits for rollback protection (#37386 #37457)
  • allowlist.sh: Block everything not explicitly approved, inverse permission model (#37471)
  • protect-dotfiles.sh: Block modifications to ~/.bashrc, ~/.aws/, ~/.ssh/ and chezmoi without diff (#37478)
  • scope-guard.sh: Block file operations outside project directory, absolute paths, home, parent escapes (#36233)
  • auto-checkpoint.sh: Auto-commit after every edit for rollback protection (#34674)
  • git-config-guard.sh: Block git config --global modifications without consent (#37201)
  • deploy-guard.sh: Block deploy commands when uncommitted changes exist (#37314)
  • network-guard.sh: Warn on suspicious network commands sending file contents (#37420)
  • test-before-push.sh: Block git push when tests haven't been run (#36970)
  • large-file-guard.sh: Warn when Write tool creates files over 500KB
  • commit-message-check.sh: Warn on non-conventional commit messages (feat:, fix:, docs:, etc.)
  • env-var-check.sh: Block hardcoded API keys (sk-, ghp_, glpat-) in export commands
  • timeout-guard.sh: Warn before long-running commands (npm start, rails s, docker-compose up)
  • branch-name-check.sh: Warn on non-conventional branch names (feature/, fix/, etc.)
  • todo-check.sh: Warn when committing files with TODO/FIXME/HACK markers
  • path-traversal-guard.sh: Block Edit/Write with ../../ path traversal and system directories
  • case-sensitive-guard.sh: Detect case-insensitive filesystems (exFAT, NTFS, HFS+) and block rm/mkdir that would collide due to case folding (#37875)
  • compound-command-approver.sh: Auto-approve safe compound commands (cd && git log, cd && npm test) that the permission system can't match (#30519 #16561)
  • tmp-cleanup.sh: Clean up accumulated /tmp/claude-*-cwd files on session end (#8856)
  • session-checkpoint.sh: Save session state to mission file before context compaction (#37866)
  • verify-before-commit.sh: Block git commit when lint/test commands haven't been run (#37818)
  • hook-debug-wrapper.sh: Wrap any hook to log input/output/exit code/timing to ~/.claude/hook-debug.log
  • loop-detector.sh: Detect and break command repetition loops (warn at 3, block at 5 repeats)
  • commit-quality-gate.sh: Warn on vague commit messages ("update code"), long subjects, mega-commits
  • session-handoff.sh: Auto-save git state and session info to ~/.claude/session-handoff.md on session end
  • diff-size-guard.sh: Warn/block when committing too many files at once (default: warn at 10, block at 50)
  • dependency-audit.sh: Warn when installing packages not in manifest (npm/pip/cargo supply chain awareness)
  • env-source-guard.sh: Block sourcing .env files into shell environment (#401)
  • symlink-guard.sh: Detect symlink/junction traversal in rm targets (#36339 #764)
  • no-sudo-guard.sh: Block all sudo commands
  • no-install-global.sh: Block npm -g and system-wide pip
  • no-curl-upload.sh: Warn on curl POST/upload (data exfiltration)
  • no-port-bind.sh: Warn on network port binding
  • git-tag-guard.sh: Block pushing all tags at once
  • npm-publish-guard.sh: Version check before npm publish
  • max-file-count-guard.sh: Warn when 20+ new files created per session
  • protect-claudemd.sh: Block edits to CLAUDE.md and settings files
  • reinject-claudemd.sh: Re-inject CLAUDE.md rules after compaction (#6354)
  • binary-file-guard.sh: Warn when Write targets binary file types (images, archives)
  • stale-branch-guard.sh: Warn when working branch is far behind default
  • cost-tracker.sh: Estimate session token cost and warn at thresholds ($1, $5)
  • read-before-edit.sh: Warn when editing files not recently read (prevents old_string mismatches)
  • windows-python-stub-detector.sh: SessionStart probe that surfaces the Microsoft Store python3 stub on Windows Git Bash — which python3 succeeds but subprocess exits 49 with no output, silently no-op-ing every Python-based hook. Matches four failure modes (exit 49 / Store-redirect stderr / exit 127 / silent stub) and warns via hookSpecificOutput (#57946)

Safety Checklist

SAFETY_CHECKLIST.md: Copy-paste checklist for before/during/after autonomous sessions.

Windows Support

Works on Windows via WSL or Git Bash. Native PowerShell is not supported (hooks are bash scripts).

Common issue: If you see Permission denied or No such file errors after install, run:

npx cc-safe-setup --doctor

This detects Windows backslash paths (C:\Users\...C:/Users/...) and missing execute permissions.

See Issue #1 for details.

Troubleshooting

TROUBLESHOOTING.md: "Hook doesn't work" → step-by-step diagnosis. Covers every common failure pattern.

settings.json Reference

SETTINGS_REFERENCE.md: Complete reference for permissions, hooks, modes, and common configurations. Includes known limitations and workarounds.

Migration Guide

MIGRATION.md: Step-by-step guide for moving from permissions-only to permissions + hooks. Keep your existing config, add safety layers on top.

Learn More

Free Gists

Professional Services

Need help configuring Claude Code safely? Safety Setup Service, audit, token optimization, and custom hooks by the cc-safe-setup team.

FAQ

Q: I installed hooks but Claude says "Unknown skill: claude-code-hooks:setup"

cc-safe-setup installs hooks, not skills or plugins. Hooks run automatically in the background, you don't invoke them manually. After install + restart, try running a dangerous command; the hook will block it silently.

Q: cc-health-check says to run cc-safe-setup but I already did

cc-safe-setup covers Safety Guards (75-100%) and Monitoring (context-monitor). The other health check dimensions (Code Quality, Recovery, Coordination) require additional CLAUDE.md configuration or manual hook installation from claude-code-hooks.

Q: Will hooks slow down Claude Code?

No. Each hook runs in ~10ms. They only fire on specific events (before tool use, after edits, on stop). No polling, no background processes.

Q: My permission patterns don't match compound commands like cd /path && git status

This is a known limitation of Claude Code's permission system (#16561, #28240). Permission matching evaluates only the first token (cd), not the actual command (git status). Use a PreToolUse hook instead, hooks see the full command string and can parse compound commands. See compound-command-allow.sh in examples.

Q: --dangerously-skip-permissions still prompts for .claude/ and .git/ writes

Since v2.1.78, protected directories always prompt regardless of permission mode (#35668). Use a PermissionRequest hook to auto-approve specific protected directory operations. See allow-protected-dirs.sh in examples.

Q: allow: ["Bash(*)"] overrides my ask rules

allow takes precedence over ask. If you allow all Bash, ask rules are ignored (#6527). Use PreToolUse hooks to block dangerous commands instead of relying on the ask/allow priority system.

Q: Hooks silently fail on macOS (Homebrew jq not found)

Claude Code runs hooks with a restricted PATH that excludes /opt/homebrew/bin (#46954). If jq is installed via Homebrew, hooks silently exit 0. Fix: add export PATH="/opt/homebrew/bin:$PATH" at the top of your hook script, or use absolute paths like /opt/homebrew/bin/jq. Inline hooks in settings.json may also be affected, add a PATH export prefix: export PATH="/opt/homebrew/bin:$PATH"; INPUT=$(cat); ...

Q: How is this different from claude-token-efficient?

Different goals. claude-token-efficient optimizes CLAUDE.md to make Claude's responses shorter and cheaper. cc-safe-setup prevents dangerous operations (file deletion, credential leaks, force-push). They work well together: use claude-token-efficient for cost reduction, cc-safe-setup for safety. For comprehensive token optimization beyond CLAUDE.md (hooks, context management, workflow design), see the Token Book.

Still stuck? See the full Permission Troubleshooting Flowchart for step-by-step diagnosis.

Contributing

Report a problem: Found a false positive or a bypass? Open an issue. Include the command that was incorrectly blocked/allowed and your OS.

Request a hook: Describe the problem you're trying to prevent (not the solution). We'll figure out the hook together.

Write a hook: Fork, add your .sh file to examples/, add tests to test.sh, and open a PR. Every hook needs:

  • A comment header explaining what it blocks and why
  • At least 7 test cases (block, allow, empty input, edge cases)
  • bash -n syntax validation passing

Share your experience: Used cc-safe-setup and have feedback? Open a discussion or comment on any issue. We read everything.

If cc-safe-setup saved you from a disaster (or just saved you time), a ⭐ helps others find it too.

Affiliate Program

If you write or teach about Claude Code, you can earn 30% commission promoting our paid books and kits. Apply with any Gumroad account, no application form, 30-day cookie window, automatic Gumroad payouts:

Eligible products include the Migration Playbook, Incident Postmortems (live since 2026-05-05), Token Book EN (pay what you want), Complete Survival Kit, CLAUDE.md Templates, and other Claude Code titles. See each product page for the current price.

Also by yurukusa

License

MIT