Always run git add -A && git commit -m "checkpoint before AI" before any AI session that touches your files. If something goes wrong, git reset --hard HEAD undoes all uncommitted changes instantly. For already-committed AI work you want to reverse, use git revert. For databases, keep a backup before any AI-assisted migration. These three habits eliminate 95% of AI rollback disasters.
The Real Danger: What Can Actually Go Wrong
A question on r/ChatGPTCoding captured what a lot of vibe coders quietly worry about:
"Those of you using Claude Code or Cursor on real projects with actual file system or database access, what happens if it does something you didn't expect? Do you have any way to stop it mid execution or roll back what it did? Or do you just hope for the best?"
Most people replied: hope for the best.
That's not a strategy. Let's talk about what can actually happen when AI agents go wrong — because knowing the failure modes helps you understand exactly why the safety net you'll build in this article matters.
Scenario 1: The Refactor That Went Too Far
You ask Cursor to refactor a messy function. It decides to "clean up" five other files while it's at it. Three of those files had special-case logic you added last week after debugging for two days. It's all gone. The code looks cleaner. It's broken.
Scenario 2: The Deleted Config File
Claude Code is helping you reorganize your project structure. You said "move the config files." It moved them — and also deleted the originals. Your app won't start. You don't know which config values were in those files because AI generated them three weeks ago and you never wrote them down.
Scenario 3: The Database Migration Gone Wrong
You ask an AI agent to "add a column to the users table." It writes and runs a migration. The migration has a typo. Half the rows in your table now have null values where they shouldn't. Your app is serving broken data to real users. You have no backup.
Scenario 4: The Interrupted Operation
You're watching Claude Code work through a complex task — it's partway through modifying eight files. Something looks wrong. You hit Escape. Now five files are changed, three aren't. Your app is in a broken half-state that's neither the original nor the intended new version.
AI agents operate at machine speed across multiple files simultaneously. A human making a mistake touches one file at a time and can stop at any moment. An AI can modify dozens of files, run database commands, and restructure your entire project in under 60 seconds — including the parts you didn't want it to touch.
Every one of these scenarios is recoverable — if you have the right safety net in place before it happens. Let's build that safety net.
Git Reset, Revert, and Stash — Explained for Real Humans
You don't need to understand git deeply to use it as a safety net. You just need to understand three commands and when to reach for each one.
git reset — "Erase This, Go Back to Before"
Think of git reset as a time machine that moves you backward and erases what happened in between. There are two flavors you'll actually use:
# Discard ALL uncommitted changes (tracked files only)
# This is the "oh no" button — use it when AI changed stuff you haven't committed yet
git reset --hard HEAD
# Discard changes to one specific file
git checkout -- path/to/file.js
# Go back to how things were 1 commit ago (erases that commit)
git reset --hard HEAD~1
When to use it: When you want to completely undo changes that haven't been pushed to GitHub yet. Fast, immediate, no trace left.
git reset --hard permanently discards changes. Unsaved work is gone. That's actually the point — it's the emergency eject button. But never run it on commits that are already pushed to a shared branch, because you'll rewrite history that other people (or your CI/CD pipeline) depend on.
git revert — "Undo This Commit Without Erasing History"
If git reset is a time machine, git revert is more like an "anti-commit." It creates a new commit that does the exact opposite of a previous commit. History stays intact.
# See your recent commits and their hashes
git log --oneline
# Revert the most recent commit
git revert HEAD
# Revert a specific commit (use the hash from git log)
git revert a3f2b1c
# Revert without opening the commit message editor
git revert HEAD --no-edit
When to use it: When you've already committed the AI's changes (or pushed them to GitHub) and you want to undo them safely. The bad changes still exist in history, but your current code doesn't include them.
git stash — "Set This Aside, I'll Decide Later"
Stash is like putting changes in a drawer. The working state isn't committed, but it's not thrown away either. You can come back for it.
# Save all current changes to the stash
git stash
# See what's in your stash
git stash list
# Bring back the most recent stash
git stash pop
# Apply the stash but keep it saved (in case you want to apply it again)
git stash apply
# Throw away the most recent stash
git stash drop
When to use it: When you want to quickly get back to a clean state to test something, but you're not ready to throw away the AI's changes permanently. Stash them, test, then decide whether to pop them back or drop them.
Quick Reference: Which Command When?
AI changed files, nothing committed yet → git reset --hard HEAD
AI changed one specific file → git checkout -- filename
AI committed bad changes, not pushed → git reset --hard HEAD~1
AI committed changes, already pushed → git revert HEAD --no-edit
Want to park changes and come back → git stash
Something is very wrong and you need to see recent commits → git log --oneline -10
The Commit-Before-AI-Touches-Anything Rule
This is the single most important habit in this entire article. Everything else is recovery. This is prevention.
Before every AI session — before you type a single prompt in Cursor or Claude Code — run this:
git add -A && git commit -m "checkpoint: before AI session $(date)"
That's it. One command. It takes three seconds. It creates an immovable snapshot of your project at this exact moment. No matter what the AI does next — no matter how many files it touches, what it deletes, what it rewrites — you can always return here with:
git reset --hard HEAD
If you haven't pushed yet, that command will completely undo everything the AI did and restore your project to the exact state it was in before you started.
Why "Just Use Ctrl+Z" Isn't Enough
Your editor's undo history is per-file and per-session. When an AI agent modifies 15 files, you'd need to open each file individually and undo the right number of steps in each one — and you might not even remember which files were changed. The undo history is also gone when you close the editor. Git commits are permanent, multi-file, and tool-agnostic. They're the only reliable rollback mechanism when AI modifies multiple files.
Work on Feature Branches
One level up from commit checkpoints: do all AI-assisted work on a feature branch, never directly on main.
# Create a new branch before starting AI work
git checkout -b ai/feature-name
# Do your AI-assisted work here...
# When you're happy with results, merge back
git checkout main
git merge ai/feature-name
# If AI work was a disaster, just delete the branch
git checkout main
git branch -D ai/feature-name
Working on a branch means your main branch is always in a working state. If the AI session goes sideways, you delete the branch and start fresh. Your stable code was never at risk.
The safest workflow: create a branch, make a checkpoint commit, do AI work, review changes, commit intentionally. Your main branch is untouched. You have a checkpoint to revert to. And you can review the diff between your checkpoint and the AI's work before merging anything.
Database Backup Strategies — Because Git Won't Save Your Data
Here's what git cannot protect: your database. Git tracks code changes. It has no idea what's in your PostgreSQL tables, MongoDB collections, or SQLite database. When an AI agent runs a migration, drops a column, or updates records, that data change is permanent — git can't roll it back.
This is the failure mode that keeps developers up at night. Code you can rewrite. Data your users created is irreplaceable.
Rule 1: Never Use Production Data for AI Work
If you're building with real user data in your database, keep a strict separation:
- Local development database — this is what your AI agent talks to. It has fake/sample data.
- Staging database — a copy of production structure, used for testing migrations.
- Production database — your AI agent should never have credentials for this.
Check your .env file right now. Which database is DATABASE_URL pointing at? If it points at production and you let Claude Code run migrations, you're taking a real risk.
Rule 2: Dump Before You Migrate
Any time an AI is about to touch your database schema — adding tables, dropping columns, changing types — take a snapshot first:
# PostgreSQL — dump the entire database to a file
pg_dump -U your_username your_database_name > backup_$(date +%Y%m%d_%H%M%S).sql
# MySQL / MariaDB
mysqldump -u your_username -p your_database_name > backup_$(date +%Y%m%d_%H%M%S).sql
# SQLite (just copy the file)
cp database.db database_backup_$(date +%Y%m%d_%H%M%S).db
To restore from a PostgreSQL dump if something goes wrong:
# Drop and recreate the database
dropdb your_database_name
createdb your_database_name
# Restore from backup
psql -U your_username your_database_name < backup_20260324_143022.sql
Rule 3: Review Migrations Before Running Them
If you're using a migration framework (Prisma, Drizzle, Django migrations, Alembic), AI tools will generate migration files. These are just code — review them before running migrate.
Look specifically for:
DROP TABLEorDROP COLUMNstatements — these delete dataALTER COLUMNchanging a type — this can corrupt data if conversion failsDELETE FROMorTRUNCATE— these remove rows- Any operation without a corresponding "down" migration to reverse it
AI tools often generate migrations that work correctly in the "up" direction but don't include a safe "down" migration. If the migration fails halfway through, you can end up with a partially-migrated database that's in an inconsistent state. Always backup first, and check that migration frameworks like Prisma are generating both up and down operations.
Tool-Specific Rollback — Cursor, Claude Code, and What They Offer
Beyond git, the tools themselves have some built-in ways to undo changes. Here's what each major tool offers — and what they can't do.
Cursor: Checkpoints and File History
Cursor integrates with VS Code's built-in Timeline feature, which keeps a local history of every file change:
- Open any file in Cursor's explorer
- Click the clock icon in the bottom left (Timeline)
- You'll see a list of every save, including AI-generated changes
- Click any snapshot to preview or restore it
Limitation: This only works one file at a time. If Cursor modified 12 files, you'd need to restore each one individually. It's useful for targeted file recovery, not project-wide rollback.
Cursor's Composer also shows diffs before applying changes — get in the habit of reading those diffs before hitting Accept. One second of review can save an hour of recovery.
Claude Code: Escape and Undo
Claude Code (Anthropic's agentic coding tool) has a few safety mechanisms worth knowing:
- Escape key — interrupts the current operation. The action in progress will stop, but changes already made to files persist.
- Permission prompts — Claude Code asks for permission before running shell commands, writing files, or making changes outside the current working directory. Don't click through these blindly.
- Plan mode — use
/planor ask Claude to "plan before doing" to get a description of what it intends to do before it does anything. Review the plan, then approve or modify.
Claude Code does not have a built-in "undo last action" button. The safety net is git — specifically the checkpoint commit before you start.
Before any significant operation in Claude Code, ask: "Before you make any changes, describe exactly what files you'll modify and what you'll do to each one." This gives you an audit trail and a chance to catch misunderstandings before any code is touched. It also gives you a reference point to check the actual changes against.
Windsurf: Cascade Checkpoint
Windsurf (by Codeium) includes a Cascade view that shows you the sequence of changes made during a session. You can review what changed and selectively revert individual operations from the Cascade history panel. It's more granular than Cursor's Timeline but still file-by-file rather than project-wide atomic rollback.
What None of Them Can Do
No AI coding tool currently has a reliable "undo everything from this session" button that works across multiple files, terminal commands, and database operations simultaneously. That's git's job. The tools are getting better — but right now, the git checkpoint is your ground truth.
Building a Safety Net Workflow — Your AI Coding Protocol
Here's a complete workflow you can start using today. It adds maybe 2-3 minutes of overhead per session and eliminates virtually all AI rollback disasters.
Before Every AI Session
# 1. Make sure you're on a feature branch (not main)
git checkout -b ai/what-im-working-on
# Or if the branch already exists:
git checkout ai/what-im-working-on
# 2. Commit everything (your safety checkpoint)
git add -A && git commit -m "checkpoint: before AI — $(date)"
# 3. If you're doing anything database-related, take a backup
pg_dump -U postgres mydb > backup_$(date +%Y%m%d_%H%M%S).sql
During the AI Session
- Ask for a plan first. Before any major task, ask the AI to describe what it will do before it does it.
- Review diffs before accepting. In Cursor, read the diff. In Claude Code, the changed files are listed — open and review them.
- Watch for scope creep. If the AI says "I also noticed..." and starts changing files you didn't ask about, stop it. Either approve explicitly or tell it to stay focused.
- Don't let AI run database migrations unattended. Review the migration file yourself before running
prisma migrate devor equivalent.
After the AI Session
# Review everything that changed since your checkpoint
git diff HEAD
# Or see a list of changed files
git diff HEAD --name-only
# Test your app — does it still work?
# If yes: commit with an intentional message
git add -A && git commit -m "feat: add feature X (AI-assisted)"
# If no: roll back to checkpoint
git reset --hard HEAD
Emergency Recovery Cheat Sheet
# "AI changed stuff and I haven't committed yet — go back NOW"
git reset --hard HEAD
# "I committed AI's changes and they're broken — undo the commit"
git reset --hard HEAD~1
# "I committed AND pushed and it's on the main branch"
git revert HEAD --no-edit
git push origin main
# "I need to see exactly what changed"
git log --oneline -5
git show HEAD # Shows the last commit's diff
git diff HEAD~1 # Shows diff between current and one commit ago
# "The database is broken"
# Restore from your pre-session backup
psql -U postgres mydb < backup_20260324_143022.sql
The Minimal Viable Safety Net
If you're going to take exactly one thing from this article, make it this alias. Add it to your ~/.bashrc or ~/.zshrc:
# Add this to your shell config file
alias ai-checkpoint='git add -A && git commit -m "checkpoint: before AI — $(date)"'
alias ai-rollback='git reset --hard HEAD'
Now before any AI session, type ai-checkpoint. If something goes wrong, type ai-rollback. That's the entire safety system for code changes.
In a survey of developers using AI coding agents daily, roughly 1 in 5 sessions resulted in at least one unexpected file change that the developer wanted to undo. Among those who had a git checkpoint habit, recovery took under 30 seconds. Among those who didn't, recovery took an average of 47 minutes — or the change wasn't recovered at all.
What to Learn Next
Rolling back changes is one part of building safely with AI. The other part is understanding what the AI is actually generating — so you catch problems before they need a rollback at all.
- How to Review AI-Generated Code for Security Risks — A detailed checklist for catching auth bypass, missing rate limiting, exposed secrets, and other AI-generated vulnerabilities before they reach production.
- AI Sandbox Security Risks — What happens when AI agents have filesystem and network access. Understanding the risk model helps you decide how much access to grant and when.
- Vibe Coding Security Checklist — A full-project checklist for security across authentication, data handling, API design, and deployment. Run this before shipping anything real.
- Secrets Management for AI Coders — How to store API keys, database credentials, and other secrets so AI agents can use them without accidentally exposing them in code.
- Security Basics for AI Coders — The foundational security concepts every vibe coder needs: HTTPS, hashing, encryption, and the security mindset that makes reviewing AI output much easier.
Build your safety habits first (this article) → then review how to review AI-generated code → then run the full security checklist on your current project. You'll catch most of what AI gets wrong and have a recovery path for the rest.
Frequently Asked Questions
Sometimes — but it's risky and incomplete. Most editors keep local file history (VS Code's Timeline, Cursor's file history) that can recover individual files. But if the AI modified many files or deleted something, recovery without a git commit is unreliable. The only guaranteed recovery path is a git commit before the AI touches anything. This is the single habit that eliminates most AI rollback disasters.
git reset --hard moves your branch pointer backward, erasing commits as if they never happened. It's fast and simple but rewrites history — dangerous if you've already pushed to GitHub. git revert creates a NEW commit that undoes a previous commit's changes. History stays intact, making it safe for shared branches and already-pushed code. Rule of thumb: reset for local-only work you haven't pushed; revert for anything that's been shared.
In Claude Code, press Escape to interrupt the current action. For long-running operations, Ctrl+C in the terminal also works. In Cursor, close the Composer panel or click the stop button. The problem is that stopping mid-execution may leave your project in a partially modified state — which is often worse than letting it finish. This is why the commit-before-you-start rule is so important: stopping mid-way is easier to recover from when you have a clean commit to return to.
No. AI agents that have filesystem or database access will execute operations against your actual data. If you ask Claude Code to "clean up old records" or Cursor to "update the schema," it will run those operations on whatever database your app is connected to — development, staging, or production. Always back up your database before running AI agents that touch data. Use a separate development database for AI-assisted work, never production.
Follow the safety net workflow: (1) commit everything before you start any AI session, (2) use a feature branch so main is never touched, (3) review every change before committing again, (4) use a local or development database, never production, (5) keep backups before any migration or schema change. The goal is to ensure that any unexpected AI action can be completely undone in under 60 seconds.