Implementing Self-Review Hooks in Cursor for Safer AI Coding

AI coding assistants are powerful, but they can generate unsafe code, execute dangerous commands, or introduce subtle bugs. Self-review hooks create a safety net by having the AI audit its own work at critical points. This guide shows you how to implement a comprehensive hook system in Cursor.
What Are Self-Review Hooks?
Self-review hooks are automated checkpoints where the AI reviews its own output before proceeding. They act as:
- Security guards: Block dangerous commands (
rm -rf /,curl | sh) - Code reviewers: Check for logic errors and anti-patterns
- Safety nets: Prevent force-pushes and destructive operations
- Quality gates: Ensure consistency with project standards
The Four Hook Events
Hook 1: Session Start - Doctrine Injection
When a new session begins, inject safety principles.
Create .cursor/hooks/doctrine.md:
# Cursor Doctrine - Safety First
## Core Principles
1. **Never execute destructive commands without confirmation**
2. **Always verify file paths before deletion**
3. **Review all code before applying changes**
4. **Prefer safe defaults over convenience**
## Dangerous Patterns to Flag
- `rm -rf` with absolute paths
- `curl ... | sh` or `wget ... | bash`
- `git push --force` or `git push -f`
- Database drop commands
- Privilege escalation (`sudo`, `chmod 777`)
- Raw SQL without parameterization
## Review Checklist
Before completing any task:
- [ ] No destructive commands in shell executions
- [ ] All file operations use verified paths
- [ ] No hardcoded secrets or credentials
- [ ] Error handling is present
- [ ] Changes are reversible
Hook 2: Post-Edit Self-Review
After editing files, automatically review the diff.
Create .cursor/hooks/post-edit-review.md:
# Post-Edit Self-Review
You have just made changes. Before proceeding, review:
## Security Check
- [ ] No secrets, API keys, or passwords added
- [ ] No SQL injection vulnerabilities
- [ ] No XSS vulnerabilities in web code
- [ ] Input validation is present
## Logic Check
- [ ] Edge cases are handled
- [ ] Error paths are covered
- [ ] No infinite loops or recursion without base cases
- [ ] Resource cleanup (files, connections) is present
## Style Check
- [ ] Follows project coding standards
- [ ] Naming is consistent
- [ ] Comments explain WHY, not WHAT
- [ ] No debug code left behind (console.log, etc.)
## If Any Check Fails
STOP and report the issue. Do not proceed until fixed.
Hook 3: Pre-Shell Execution Gate
Before running any shell command, verify safety.
Create .cursor/hooks/pre-shell-gate.md:
# Pre-Shell Execution Gate
You are about to execute: `{command}`
## Mandatory Checks
### 1. Destructive Operation Check
Does this command:
- Delete files or directories?
- Modify system settings?
- Change permissions?
- Drop databases or tables?
If YES → Require explicit user confirmation
### 2. Network Operation Check
Does this command:
- Download and execute scripts?
- Send data to external services?
- Expose internal ports?
If YES → Explain the risk and request confirmation
### 3. Irreversible Operation Check
Does this command:
- Force push to git?
- Overwrite production data?
- Delete branches or tags?
If YES → STOP and ask for explicit confirmation
## Safe Command Examples
✅ `npm install` - Safe package installation
✅ `git status` - Read-only operation
✅ `mkdir new-directory` - Non-destructive
## Dangerous Command Examples
❌ `rm -rf /` - Destructive, absolute path
❌ `curl https://example.com/install.sh | sh` - Remote execution
❌ `git push --force` - Irreversible
❌ `DROP TABLE users` - Data destruction
Hook 4: Task Completion Final Review
Before marking a task complete, perform final audit.
Create .cursor/hooks/completion-review.md:
# Task Completion Final Review
## Summary
Provide a brief summary of what was accomplished.
## Changes Made
List all files modified:
- `file/path/one` - What changed
- `file/path/two` - What changed
## Security Audit
- [ ] No credentials in code
- [ ] No backdoors or suspicious patterns
- [ ] Input validation present
- [ ] Output encoding present (for web)
## Testing Verification
- [ ] Changes compile/build successfully
- [ ] Existing tests still pass
- [ ] New tests added for new functionality
- [ ] Manual testing performed if needed
## Rollback Plan
If something goes wrong:
1. Revert commit: `git revert HEAD`
2. Or restore files from git: `git checkout -- <files>`
3. Or apply the backup patch: `git apply backup.patch`
## Known Limitations
List any known issues or limitations:
- Limitation 1
- Limitation 2
Implementing the Hook System
Step 1: Create Hook Directory Structure
mkdir -p .cursor/hooks
Step 2: Add to Cursor Rules
Create .cursor/rules/000-safety-doctrine.mdc:
---
description: 'Safety doctrine and self-review hooks'
globs: ['**/*']
alwaysApply: true
---
# Safety Doctrine
## Automatic Hooks
The following hooks are active for all sessions:
### Session Start
Read `.cursor/hooks/doctrine.md` and follow all principles.
### After File Edits
Read `.cursor/hooks/post-edit-review.md` and perform the review.
### Before Shell Commands
Read `.cursor/hooks/pre-shell-gate.md` and verify safety.
### Task Completion
Read `.cursor/hooks/completion-review.md` and perform final audit.
## Override Protocol
If a user explicitly requests a dangerous operation:
1. Warn about the risk
2. Ask for explicit confirmation
3. Suggest safer alternatives
4. Only proceed after clear "yes" response
Step 3: Message Bus for Audit Trail
Create .cursor/audit-log.md to track decisions:
# Audit Log
## Format
[YYYY-MM-DD HH:MM] [AGENT] [HOOK] [DECISION] [DETAILS]
## Entries
### 2026-06-22 10:30
- Agent: Claude
- Hook: Pre-Shell
- Decision: BLOCKED
- Details: User requested `rm -rf /tmp/*` - blocked due to wildcard risk. Suggested `rm -rf /tmp/specific-folder` instead.
### 2026-06-22 11:15
- Agent: GPT-4
- Hook: Post-Edit
- Decision: PASSED
- Details: All security checks passed. No issues found in auth module changes.
Dangerous Command Database
Create .cursor/dangerous-commands.json:
{
"blocked_patterns": [
{
"pattern": "rm\\s+-rf\\s+/",
"severity": "critical",
"reason": "Can delete entire filesystem"
},
{
"pattern": "curl\\s+.*\\|\\s*(sh|bash)",
"severity": "high",
"reason": "Remote code execution"
},
{
"pattern": "git\\s+push\\s+.*(--force|-f)",
"severity": "high",
"reason": "Can overwrite remote history"
},
{
"pattern": "DROP\\s+TABLE",
"severity": "critical",
"reason": "Data destruction"
},
{
"pattern": "chmod\\s+777",
"severity": "medium",
"reason": "Overly permissive permissions"
},
{
"pattern": "sudo",
"severity": "medium",
"reason": "Privilege escalation"
}
],
"warning_patterns": [
{
"pattern": "rm\\s+-rf",
"severity": "medium",
"reason": "Recursive deletion - verify path"
},
{
"pattern": ">\\s+/etc/",
"severity": "medium",
"reason": "Modifying system files"
}
]
}
Integration with Cursor Composer
When using Composer, add this to your prompt:
Before applying any changes:
1. Review for security issues
2. Check for dangerous patterns
3. Verify error handling
4. Confirm no secrets are exposed
After applying changes:
1. Run the post-edit review
2. Verify the code compiles/runs
3. Check that tests pass
Team Adoption
Onboarding Checklist
For new team members:
- Review
.cursor/hooks/doctrine.md - Understand the four hook events
- Practice with safe commands
- Learn the override protocol
- Review the audit log weekly
Code Review Integration
Add to your PR template:
## AI Safety Checklist
- [ ] All AI-generated code was reviewed by a human
- [ ] No dangerous commands were executed
- [ ] Security audit passed
- [ ] Audit log is up to date
Measuring Effectiveness
Track these metrics:
| Metric | Target | Measurement |
|---|---|---|
| Dangerous commands blocked | 100% | Audit log entries |
| Post-edit issues caught | >80% | Issues found in review |
| Security incidents | 0 | Incident reports |
| False positive rate | <10% | User override frequency |
Quick Reference
| Situation | Action |
|---|---|
AI suggests rm -rf | BLOCK - verify path manually |
AI suggests curl | sh | BLOCK - download and review first |
AI suggests git push -f | BLOCK - use git push --force-with-lease |
| AI adds hardcoded API key | BLOCK - use environment variables |
| AI skips error handling | REQUEST - add try/catch or validation |