Code Guardian integrates seamlessly with Claude Code hooks to automatically validate code changes as Claude edits your files.
npm install -g @diullei/codeguardian@betaAdd this to your Claude Code settings:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "codeguardian check --claude-code-hook"
}
]
}
]
}
}With the --claude-code-hook flag:
- Success (no violations): Runs silently with exit code 0
- Violations found: Shows errors to stderr and exits with code 2, causing Claude to automatically fix them
Validate all file changes:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "codeguardian check --claude-code-hook"
}
]
}
]
}
}Use different rules for different contexts:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "codeguardian check -c .codeguardian/strict-rules.yaml --claude-code-hook"
}
]
}
]
}
}Check the entire working directory, not just changed files:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "codeguardian check --mode=all --claude-code-hook"
}
]
}
]
}
}Check staged files after git add commands:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if echo \"$HOOK_INPUT\" | jq -r .tool_input.command | grep -q '^git add'; then codeguardian check --mode=staged --claude-code-hook; fi"
}
]
}
]
}
}Note: $HOOK_INPUT contains JSON data about the tool call. For Bash commands, .tool_input.command contains the actual shell command being executed. See the official hooks documentation for details on the input structure.
- Claude edits a file
- Code Guardian runs automatically via the hook
- If violations are found:
- Exit code 2 triggers Claude to see the errors
- Claude fixes the violations before continuing
- If no violations:
- Silent execution (no output)
- Claude continues normally
The --claude-code-hook flag can be combined with any Code Guardian options:
# Check specific config files
codeguardian check -c rules.yaml --claude-code-hook
# Exclude patterns
codeguardian check --exclude "test/**" --claude-code-hook
# Check all files (not just changes)
codeguardian check --mode=all --claude-code-hookRun manually to verify it works:
# Should run silently if no violations
codeguardian check --claude-code-hook
# Remove flag to see normal output
codeguardian check- Hook not running: Ensure Code Guardian is in your PATH
- Always passes: Check that your rules match the files being edited
- Performance: Use
--excludeto skip unnecessary directories