Skip to content
GrowthVector.io

Vibe Coding Workflow: Git, Branches and Review Loops

The vibe coding workflow for one task at a time

Updated

A vibe coding workflow is a loop you repeat for every task: write down what done looks like, let the agent work on its own branch, run a check that passes or fails, review the diff, then commit. This is Step 4 of 12 in the guide. You leave with the git commands to branch, commit and undo agent work safely, and a rule for when to stop prompting and change the method.

The guide follows one project, Bookly, a booking app for a small hair salon. On this page you build Bookly's first feature, booking a time slot, on its own branch with small commits. Then you review the diff, and when the agent breaks something, you roll back to a state that works.

Two habits make the loop hold. Keep the permanent history in git, because agent checkpoints only cover one session. Give every task a check that passes or fails before the agent starts. The sections below cover the git commands, the agent-era tools, the review step and the debugging loop.

Related guides: planning and PRDs, TDD with AI, Claude Code deep dive, Codex deep dive.

The Loop and Git

Why git matters more for vibe coders

Git is your parachute. An agent can change many files in one turn, and a bad change can cost hours of work when no saved version exists.

In July 2025, a Replit AI agent wiped a live production database during a code freeze. The agent first said a rollback would not work. Jason Lemkin recovered the data manually. Replit's CEO called it "Unacceptable and should never be possible." Replit then separated development and production databases and improved rollback.
  • One prompt can touch many files, so one bad response can break several things at once.
  • When a change breaks something, git diff shows the unstaged lines that changed, and git diff --staged shows the staged ones.
  • Commit the working state before a risky change, and commit again when a check passes.

The vibe coding workflow in seven steps

Repeat this for every task: one task, one branch, one check, one review.

1Scope the task. Write one acceptance check: a statement that passes or fails. The planning page covers PRDs and acceptance checks.
2Branch. Create a branch or a worktree for this task only, for example git switch -c feature/book-slot.
3Prompt with the check. Give the agent the command that runs the check. Ask for the command it ran and its output.
4Watch the first minute. Press Esc the moment the agent drifts. Esc stops the action and keeps everything done up to that point.
5Run the check yourself. "All tests pass" from the agent tells you very little. Run the command and read the output.
6Review the diff. Read every changed file before you commit. The review section lists what to look for.
7Commit, then decide the merge. Commit when the check passes. A human makes the merge decision.

Match the loop to the task's risk

The loop stays the same. The checks get stricter, and the merge rule gets tighter, as the risk rises.

TaskLoopMerge rule
Small fix in one file, with one checkOne branch, one check, a diff review and one commit.You merge after you read the diff.
Feature, such as Bookly's book-a-slotA branch or worktree, an acceptance check, a commit per passing check, and a fresh review with /code-review.A human makes the merge decision.
Anything that touches payments, auth or dataA failing test first (see the TDD page), a worktree, a fresh review, and the checks on the security page.A human makes the merge decision. Do not run these tasks unattended.

The riskier the change, the more of the loop you run by hand.

Bookly: book a slot on its own branch

An illustration of the loop. The commit messages are examples, not a record of a real build.

Bookly clients book a time slot and pay a deposit, and the owner sees the day's bookings. The first feature is booking a slot, so the branch covers only that.

# 1. Branch for this task only

git switch -c feature/book-slot

Prompt the agent with the acceptance check from the PRD: a client can book an open slot, and the booking appears in the owner's day view. Ask the agent to reply with the test command it ran and its output.

# 2. Commit each check that passes

git status

git add .

git commit -m "feat: add bookings table and slot query"

Run git status before git add . so that .env is not staged by mistake. Each later check gets the same three commands, for example feat: add book-slot form.

# 3. Review everything the branch changed

git diff main...HEAD --stat

git diff main...HEAD

The three-dot form compares the branch with the point where it split from main, so you see only the branch's work.

Suppose the agent changes the day view query, and the owner's list goes empty. The check fails. Pick the rollback that matches where the bad change sits.

The change is not committed yet.

Warning: this deletes every edit to tracked files. New files stay, so remove them with the clean steps in the recovery section.

git restore --source=HEAD --staged --worktree .

The bad commit is the last one, and you have not pushed it.

Warning: the hard form deletes the changes. Use it only after you read the diff.

# Keep the changes staged so you can fix them

git reset --soft HEAD~1

# Delete the changes

git reset --hard HEAD~1

Git keeps the deleted commit in the reflog for 30 days.

The bad commit is already pushed or shared.

Commit or stash your work first, because revert needs a clean working tree. Revert adds a commit that reverses the bad one, so history stays intact.

git revert <sha>

# 4. After the check passes and the review is done

git switch main

git merge feature/book-slot

Save what works before a risky task

Commit when an acceptance check passes, and before each new task. Do not commit before every prompt.

Warning: git add . stages every file that .gitignore does not exclude. Confirm that .env is listed in .gitignore before you run it.

# Save the working state, after git status shows no secrets

git status

git add .

git commit -m "chore: save working state before the booking task"

  • Commit when an acceptance check passes.
  • Commit before each new task, so the task starts from a known state.
  • Skip per-prompt commits. Agents checkpoint their own turns, which the agent-era section below explains.

Branch-based experimentation

The safest pattern for trying risky agent changes.

1

Create an experiment branch:

git switch -c experiment/new-feature
2

Let the agent change files on this branch. Other branches do not change.

3

If it works, after you review it:

git switch maingit merge experiment/new-feature
4

If it fails:

Warning: -D deletes the branch even when its commits are not merged.

git switch maingit branch -D experiment/new-feature

Main stays untouched. Two agents in one folder still collide, even on different branches, because they share the same files on disk. Use a worktree for parallel work, as the agent-era section explains.

Git is your permanent history

Checkpoints and undo cover one session. Git covers the project.

  • Use one branch or worktree per task.
  • Write descriptive commit messages in the Conventional Commits form.
  • Commit when a check passes, not on a timer.

# Commit form: type, optional scope, description

<type>[scope]: <description>

feat: add new feature

fix: fix a bug

refactor: restructure code

test: add or fix tests

chore: dependency updates

# Also recommended: build, ci, docs, style, perf

How to undo AI damage

Seven steps, from the gentlest to the most destructive. Read each warning before you run its command.

1. See the change

git diff

git diff --staged

git diff shows unstaged edits. git diff --staged shows what is staged.

2. Restore one file

Warning: unstaged edits to this file are lost, and Git keeps no copy. Staged changes stay.

git restore <file>

3. Drop every edit to tracked files

Warning: this drops staged and unstaged edits to tracked files. It does not remove new files.

git restore --source=HEAD --staged --worktree .

4. Remove new files the agent created

Run step 3 first. It turns files that were staged as new into untracked files, which clean can then remove.

Warning: git clean -f -d deletes untracked files, and Git cannot recover them. Preview first. Ignored files such as .env stay, because clean skips them unless you add -x. Do not add -x.

git clean -n -d

git clean -f -d

5. Park the work

Plain git stash leaves untracked files in place. Add -u to include them.

git stash push -u -m "half-finished work"

6. Undo a commit and keep history

git revert HEAD adds a commit that reverses the last one. Use git revert <sha> for an older commit. It needs a clean working tree.

git revert HEAD

7. Last resort

Warning: this discards uncommitted changes to tracked files. It can overwrite untracked files that a commit would replace. It does not remove new untracked files, so pair it with step 4 when needed.

git reset --hard HEAD

Git recovery commands

Commands for the situations that the undo ladder does not cover.

# Undo the last commit, keep its changes staged

git reset --soft HEAD~1

Use this only for a commit you have not pushed.

# Recover a deleted branch or a lost commit

git reflog

git switch -c recovered <sha>

Unreachable reflog entries expire after 30 days. Reachable entries last 90 days.

# Abort a merge that goes wrong

git merge --abort

Then merge in smaller pieces, so each review stays small.

# Detached HEAD: go back to a branch

git switch main

# Or keep the work on a new branch first

git switch -c save-my-work

A secret reached a commit. Rotate the secret first. Once it is rotated, it can no longer be used for access. Then remove the file from history with git filter-repo, following GitHub's guide. The guide's sensitive-data option needs git filter-repo 2.47 or later. Rewriting history changes every commit after the file, so coordinate before you force-push. The security page covers secret handling.

Git stash: a short hold, not a plan

Use stash for minutes or hours. Use a branch or a worktree for longer work.

When you code by hand, you change one thing at a time. An agent can change many files in one turn. When that breaks something, a stash lets you set the work aside and try the agent's approach on a clean tree.

# Stash tracked changes and untracked files

git stash push -u -m "half-finished booking form"

Plain git stash leaves untracked files in place.

# See what is in the stash

git stash list

# Bring the newest stash back and remove it

git stash pop

On a conflict, the stash stays in the list. Resolve the conflict, then run git stash drop.

# Bring the stash back and keep the entry

git stash apply

If the stash no longer applies cleanly, run git stash branch with a new branch name. It creates a branch at the commit the stash was made on.

Warning: do not add -a (--all) when .env exists. It stashes ignored files and then removes them from the folder.

Use case: You have half-finished work, and the agent proposes a different approach. Stash your work with -u, try the agent's approach on a clean tree, and if it fails, pop the stash to get back to where you were.

Agent-Era Tools: Checkpoints, Worktrees and Context

Checkpoints and rewind: what they cover

Agent checkpoints are a fast undo for one session. They do not replace git.

FeatureClaude Code checkpointsCursor checkpointsGit commits
What they saveFiles, on every prompt that starts a turnFiles, before significant agent changesCommits you choose to make
How you restoreType /rewind, or press Esc twice on an empty prompt. Restore code, conversation or both.Files only. The conversation is not restored.Commands such as git restore, git revert and git reset
GapsFiles changed only by Bash commands are not tracked. Most subagent edits are not restored. Edits from other concurrent sessions and manual edits are not captured. Symlinked and hard-linked files are skipped.Undo only. Use it for agent changes, not for history.Only what you commit. Uncommitted work has no history.
RoleQuick undo inside one sessionQuick undo of agent changesPermanent history you can share
  • Claude Code keeps the 100 most recent checkpoints in a session. It deletes them about 30 days after the session last saved one. Set cleanupPeriodDays higher to keep them longer.
  • After a rewind, run git status. Checkpoints miss the gaps listed above, so the tree can still hold changes.
"For permanent version history and collaboration, continue using version control, such as Git."
"Only use them for undoing Agent changes; use Git for permanent version control."

Parallel agents: one worktree per agent

Two agents in one folder overwrite each other's files. A branch alone does not prevent it. A worktree gives each agent its own folder and its own branch.

# Claude Code: worktree in .claude/worktrees/booking-slot on branch worktree-booking-slot

claude --worktree booking-slot

# Claude Code: a worktree for pull request 1234, in .claude/worktrees/pr-1234

claude --worktree "#1234"

# Plain git: any agent, any editor

git worktree add ../bookly-slot -b feature/book-slot

  • A new worktree is a fresh checkout, so gitignored files such as .env are missing. List them in a .worktreeinclude file (gitignore syntax) to copy them in.
  • New worktrees start from the remote default branch. Set worktree.baseRef to "head" to start from your current commit, including unpushed commits.
  • In Cursor, the /worktree and /best-of-n skills work with worktrees. Bring results back with /apply-worktree, and remove one with /delete-worktree. Cursor caps the count at 25 worktrees per machine by default.
  • Subagents can run in their own worktree too. The Claude Code deep dive covers that setting.
Warning: removing a worktree deletes its directory and its branch, with all the work in them. Merge or push first. On exit from an interactive session, a clean unnamed worktree is removed with its branch. A worktree with changes asks whether to keep or remove it. Non-interactive -p runs never clean up. Run git worktree remove, and git worktree unlock first if the worktree is locked.

Other ways to run agents in parallel

  • Worktrees isolate file edits. Subagents split work inside one session.
  • /batch <instruction> splits one large mechanical change into 5 to 30 units. It shows the plan, runs each unit in its own worktree, and opens a pull request per unit.
  • claude agents (research preview) shows background sessions on one screen.
  • Each parallel agent uses its own usage, so a batch costs the sum of its units. Check your usage before a large /batch run.
Before an unattended run, decide what the agent may touch: a worktree, and the one branch it may push to. Claude Code's docs ask this question before any unattended run.

Context files: keep them short and specific

A context file (CLAUDE.md, AGENTS.md or a similar file) is read before the agent works. It is guidance, not enforcement.

  • Size: Short. Longer files use more context, and the agent follows them less well. Each tool's own limit, and where it reads the file, are in the context-file table on the Planning page.
  • Put in: the exact test, typecheck and lint commands, and how to run one test file. Add the places where the code misleads, the decisions that are not in the repo, and anything you have corrected twice.
  • Leave out: architecture and file layout that the agent can read itself.
  • Enforce hard rules elsewhere: guidance can be ignored. A rule that must never break needs a hook or a deny rule. The Claude Code deep dive covers hooks.
A study from an ETH Zurich group found that context files do not generally improve task success rates. It also found that they raise inference cost by over 20% on average. Keep the file to commands, traps and tooling that the agent cannot find itself.

AGENTS.md is one of the inaugural projects of the Agentic AI Foundation, which the Linux Foundation announced on December 9, 2025. OpenAI and Anthropic are among its founding members.

How each agent loads its own file, including CLAUDE.md imports and the Codex AGENTS.md rules, is on the agent pages: the Claude Code deep dive and the Codex deep dive.

Hand-off notes between sessions

A new session starts without the working state of the last one. A short note in the repo gives it that state.

  • At the end of each session, write a note: the branch or worktree, the check that passes, what is still open, and the next command to run.
  • Keep the note in a feature doc, not in the context file. The context file holds stable rules. The note changes every session.
  • The next session reads the note first, then runs the check before it changes anything.

Review Every Task

The review loop: a fresh reviewer before merge

A reviewer with a fresh context has not seen the reasoning that wrote the code, so it is less likely to agree with the code by default.

  • /code-review runs the review in a background subagent with its own context window. It follows your CLAUDE.md, and /review is an alias.
  • The Claude Code docs say the review subagent "never saw your conversation. It isn't swayed by the reasoning that produced the code."
  • --fix applies the findings. A background --fix run edits files outside the session checkpoints, so use git to revert a bad run.
  • --comment posts the findings to a GitHub pull request as inline comments.
  • Review on five dimensions: correctness, architecture, security, maintainability and scope. Name the dimensions that matter for the task in the review request.
For a spec review, write the requirements in a SPEC.md. Ask a subagent to check that every requirement is implemented and that the listed edge cases have tests. Tell it to report gaps that affect correctness and to skip style.

Review the diff against the task's acceptance check, not against the agent's summary. The summary describes what the agent meant to do.

AI review tools and their plans

Prices as each vendor lists them. Check the vendor's page before you buy, because plans change.

ToolRuns onPrice basisNotes
Claude Code Code ReviewGitHub pull requests. Team and Enterprise plans.Token usage through usage credits. No flat price per review.Several agents review in parallel. A second step removes false positives. Posts inline comments ranked by severity and a check run named "Claude Code Review". Never approves or blocks. Does not build or run your code.
GitHub Copilot code reviewGitHub pull requests. Reviews only when assigned, by default.AI credits. GitHub's estimated average per review: $0.25 USD (Lite), $1.50 USD (Balanced), $10 USD (Max).Not included in Copilot Free. Its approvals do not count toward required approvals by default. Reviews a pull request once unless you set it to review every push.
CodeRabbitPull requestsPer user per month. Essentials $24 on annual billing or $30 monthly. Team $48 annual or $60 monthly. Advanced $72 annual. Enterprise custom.14-day trial. Free for public repositories. Reviews beyond the hourly allowance can cost $0.25 per reviewed file. Only developers who create pull requests are charged.
Cursor BugbotPull requestsUsage-based. Rates are on the Cursor pricing page.Reviews each update, or on a pull request comment: cursor review or bugbot run. Autofix pushes fixes, and existing-branch mode is capped at 3 attempts per pull request.
AI review is not a gate. Claude Code's docs say a review with no findings does not mean the code is error-free or secure.
GitHub says Copilot "might not catch every problem and can make mistakes. Validate its feedback and supplement it with human review."

Review checklist for every task

You do not need to understand every line. Run this five-point check on every agent change before you commit.

1Does it work? Run the acceptance check yourself. Click through the feature and try to break it.
2Does it match existing code? Does it follow the same patterns as the rest of the project?
3Any hardcoded values? Look for API keys, URLs, or credentials embedded in the code. The security page covers secrets.
4Are dependencies real? Confirm each new package exists and is maintained. One study of 16 code models and 576,000 code samples found at least 5.2% hallucinated package names for commercial models and 21.7% for open-source models. A name that someone registers becomes a supply-chain attack. The security page covers the defence.
5Ask a fresh reviewer. Run /code-review, or paste the diff into a new session with: "Review this code for security vulnerabilities, bugs, and potential issues."

What the data says about AI-written code

Each figure comes from one source with its own limits. Read the caveat before you repeat a number.

  • CodeRabbit (December 17, 2025). 470 open-source GitHub pull requests: 320 co-authored with AI, 150 human-only. AI pull requests averaged 10.83 issues, against 6.45, about 1.7 times as many. Logic and correctness findings were 75% more common, and security findings were up to 2.74 times as common. CodeRabbit sells an AI review tool. Its authors cannot guarantee that every pull request labeled human was written by a human.
  • GitClear (2026 edition, vendor data). Block duplication up 81% since 2023. Copy and paste within a commit up 41%. Two-week churn up 15%. Moved (refactored) lines fell from 21% of changed lines in 2022 to 3.8% in 2026 so far. GitClear uses its own classification.
  • A counterpoint (arXiv 2603.27130, submitted March 28, 2026). A study of real repositories finds that AI-versus-human differences on code-level metrics are "rather small". Use it to avoid overstating the vendor numbers above.
  • METR (July 10, 2025). 16 experienced developers worked on 246 real issues. With AI allowed, they took 19% longer, although they expected a 24% speedup and still believed afterwards that AI had sped them up by 20%. The trial used early-2025 tools. Use it to measure your own work, not to trust how fast it feels.

Red flags to watch for

  • The same fix suggested three times in a row without resolving the issue.
  • The agent says "Fixed!" or "This should work now" without showing a passing run.
  • An API method you have never seen in a library you use. Confirm it in the official docs.
  • The agent contradicts an instruction it followed correctly earlier in the session.
  • A version claim, such as "added in version 3.2", that you have not confirmed.

Before you accept a result: run the code yourself, check the official docs for any API you do not recognize, and ask a fresh reviewer to read the diff.

Debugging When the Loop Stalls

The debugging loop

Use this instead of pasting the error back and hoping for a fix.

1Reproduce the bug. Write the command or the steps that fail, and paste the failing output into the prompt.
2Ask for hypotheses before a fix. Use the reflect-first prompt below.
3Add logs that test the top hypothesis. Cursor's Debug Mode does this for you, as described below.
4Read the logs, then make one small fix. Keep the change small enough to review in one pass.
5Run the check. If it fails, count the failed corrections.
6After two failed corrections, stop. Run /clear and write a better prompt. Name the file, describe the symptom, say what fixed looks like, and give a command that passes or fails.

# Reflect-first prompt

List 5-7 possible sources of this problem. Pick the 1-2 most likely. Add logs to validate before implementing a fix.

Cursor Debug Mode is an Agent mode. Pick it in the mode picker, or press Shift+Tab to rotate the Agent modes. It proposes hypotheses, adds log statements that send data to a local debug server, gives you reproduction steps, reads the logs, and makes a small targeted fix. It removes the instrumentation after you confirm. Use it for reproducible bugs with an unclear cause, race conditions, performance problems and regressions.

Change the method before you change the framework.

Debugging patterns that work and patterns that waste credits

Effective approaches

  • Run /clear between unrelated tasks. Most current models have a 1M-token window and compact automatically, so running out is rare.
  • Commit or checkpoint before a risky change, so you can revert it.
  • Screenshot visual bugs and paste them into the chat. Vision-capable models read layout bugs better from a screenshot than from a text description.
  • Ask for hypotheses before a fix, with the reflect-first prompt above.
  • Get a second opinion from a fresh context: /code-review runs in a subagent that has not seen your reasoning.

Patterns that waste credits

  • The copy-paste loop: pasting error messages back without a new hypothesis. It works for simple issues and spirals on architecture problems.
  • The debugging death spiral: the agent fixes a bug, creates a new one, fixes that, and creates another. After two failed corrections, stop and reset the prompt.
  • Trying to fix everything at once. Isolate one issue before you ask for help.
  • Large tasks. Keep each task to one check that passes or fails.

Browser DevTools: minimum viable knowledge

Chrome opens DevTools with F12 or Ctrl+Shift+I (Cmd+Option+I on Mac). The console opens with Ctrl+Shift+J (Cmd+Option+J on Mac).

Console (most important)

Red text is an error. Copy the red error message exactly, including the file name and line number, and paste it into your coding agent. Yellow is a warning. White is information, and you can usually ignore it.

Network

Filter by Fetch/XHR to see only API calls. Red rows are failed requests. Click a row for details. Status codes: 200 = OK, 400 = bad request, 401 = not authenticated, 403 = authenticated but not allowed, 404 = not found, 500 = server error.

Elements

Hover an element to see its boundaries. Click it to see its CSS. Toggle a property on or off to test a change live. Changes disappear on reload.

Application

Look at local storage, session storage and cookies. Anyone who opens DevTools can read the keys stored here. The security page covers how to keep secrets on the server.

Error message dictionary for vibe coders

The errors you meet most often and what they mean.

CORS error

Access to fetch has been blocked by CORS policy

Your web app is calling a server that does not allow your app's origin. You cannot fix this from the frontend alone. The API server must send CORS headers that allow your origin.

Null/Undefined

Cannot read properties of undefined/null

Your code reads data that does not exist yet. This usually happens before API data has loaded. Fix it with optional chaining: user?.name instead of user.name.

401/403

Unauthorized / Forbidden

401: You are not authenticated. 403: You are authenticated but not allowed. Check that auth tokens are present and not expired, and that your access rules, such as Supabase Row Level Security, allow this request. The security page covers those rules.

404

Not found

The URL or API endpoint does not exist. Check the URL for typos, confirm the route exists, and confirm the server is running.

500

Internal server error

Something crashed on the server, so the fault is not in the frontend. Read your host's function or server logs for the stack trace.

Hydration

Hydration mismatch (Next.js and React)

The server rendered one version of the page and the browser rendered another. Common causes: browser-only code such as window or localStorage during server rendering, a typeof window check, Date() output, invalid HTML nesting, and browser extensions. Fixes: move the code into useEffect, load the component with dynamic(..., { ssr: false }), or add suppressHydrationWarning to the element. That prop is a one-level escape hatch.

Env vars

process.env.NEXT_PUBLIC_XXX is not defined

Next.js inlines NEXT_PUBLIC_ variables into the JavaScript bundle when you run next build. Add the variable to your host, then rebuild and redeploy. A dynamic lookup such as process.env[varName] is not inlined.

Module

Module not found: Can't resolve 'xxx'

A required package is missing from package.json. Run the build and read the missing-module error, then install the package with npm install <package>. Import paths are case-sensitive, so check the spelling of each path too.

Tool-specific debugging notes

Short notes for the tools that readers ask about most. Plan prices and limits are on the tools page.

  • Switch to Plan mode after one or two failed attempts. Lovable's docs say this is usually faster than trying again.
  • Repeated guesses "tend to pile up code that hides the real problem."
  • The account includes 10 free fixes. Each one is available again 24 hours after use.
  • Version history and "Revert and resend" restore a working state.

  • Use Debug Mode for reproducible bugs with an unclear cause. It is described above.
  • The old "Debug with AI" button is not in the current Cursor docs. Use Debug Mode instead.
  • Press Shift+Tab to rotate the Agent modes.

  • Windsurf is now Devin Desktop. Devin Local is the local agent in Devin Desktop.

  • Be specific about what the agent must not change. The July 2025 incident happened during a code freeze.
  • Replit later separated development and production databases. Keep them apart in your own project too.
  • Commit your work to git before a large agent change, so a bad change has a saved version to return to.

  • Credits reset monthly, and unused credits expire when they reset.
  • Moving to a higher monthly plan carries unused credits one more cycle. Bonus credits never carry over.
  • Stop a failing loop after two corrections. Each extra attempt spends credits.

The "log everything" habit

Log before and after each critical operation. The log shows which step failed.

Silent failure (bad)

async function chargeUser(userId) {

  const user = await getUser(userId);

  await createPayment(...);

  await updateSubscription(userId);

}

// If this fails, you have NO idea where

Observable (good)

async function chargeUser(userId) {

  console.log("Charging user:", userId);

  try {

    const user = await getUser(userId);

    console.log("User found:", user.id);

    const payment = await createPayment(...);

    console.log("Payment created:", payment.id);

    await updateSubscription(userId);

    console.log("Subscription updated");

  } catch (err) {

    console.error("Charge failed:", userId);

    throw err;

  }

}

Log IDs only. Never log an email address, a token, or a whole user object.

Screenshot debugging

Vision-capable models read layout bugs better from a screenshot than from a text description. In Claude Code, a browser screenshot next to the mockup can serve as the check, and /verify builds and runs the app.

1Step 1

Take a screenshot of the broken UI. Crop it to show the problem area.

2Step 2

Paste the screenshot into the agent's chat, next to the mockup if you have one.

3Step 3

Describe what is wrong and what it should look like. Ask for evidence: the command it ran and its output, or a new screenshot.

"Rubber duck" bug report for an agent

When you are stuck, paste this structured report into the agent instead of describing the problem loosely.

Structured bug report for an agent:

Goal: What I'm trying to accomplish

Code: [paste the relevant function or component]

Expected: What should happen

Actual: What actually happens

Error: [paste the full error message, if any]

Already tried: What you have attempted, and the result of each attempt

Environment: Framework version, Node version, OS

The report gives the agent the context it needs on the first try, so it does not spend turns asking questions you could have answered in the prompt.

Common Traps and Limits

The "rewrite from scratch" trap

The agent hits a complexity wall, and you want to rewrite everything. Do not. Add tests to the existing code, fix the worst bugs first, then refactor in small steps. Joel Spolsky wrote that rewriting from scratch is "the single worst strategic mistake that any software company can make."

Running a local model (optional)

Ollama runs models on your own machine, with no per-token fee.

On Linux, install Ollama with the official command below. macOS and Windows use the installer instead.

# Linux install

curl -fsSL https://ollama.com/install.sh | sh

# A coding model: 19 GB, 256K context window

ollama run qwen3-coder:30b

Ollama v0.14.0 or later can launch qwen3-coder from Claude Code through Ollama's Anthropic API compatibility. A smaller option, deepseek-r1:7b, is 4.7 GB. A local run keeps prompts on your machine. For the agent comparison, see the tools page.

Warning signs the loop is no longer enough

These signs show up on work that outgrew the loop. They are judgment, not thresholds.

  • The agent keeps breaking existing features when it adds new ones.
  • You spend more time debugging than building.
  • Users report security issues or data exposure.
  • Performance degrades noticeably as the user count grows.
  • Every bug fix creates a cascade of new bugs.

When these signs appear, read the architecture page before you add another feature.

Next step

With the loop in place, the next page, TDD with AI, shows how to write the failing test first, so the agent cannot mark its own work as done.

Common Questions

Git worktree vs branch: which should I use with coding agents?

Use both. A branch keeps one task's commits apart, but two agents on branches in one folder still share the same files and collide. A worktree gives each branch its own folder, so two agents can work on Bookly at once without overwriting each other. Merge each worktree's branch through a pull request when its check passes.

How do I use git worktree with Claude Code?

Run claude --worktree feature-name, or claude -w for short. Claude Code creates the worktree under .claude/worktrees/ on a new branch named worktree-feature-name, and generates a name if you leave it out. List gitignored files such as .env in .worktreeinclude so each worktree gets a copy. Two sessions that edit the same file still conflict.

How do I undo changes made by an AI coding agent?

For one file, run git restore on that file. To discard every change to tracked files, run git restore --source=HEAD --staged --worktree, then preview new untracked files with git clean -n -d before you delete them with git clean -f -d. Git cannot recover deleted untracked files. Agent checkpoints help too, but they miss some edits, so commit each working step.

Do Claude Code checkpoints replace git commits?

No. Claude Code and Cursor both say checkpoints are for undo, and git stays the permanent history. Claude Code does not track files that only a Bash command changed, does not restore most subagent edits, and ignores edits made by other sessions. It keeps the latest 100 checkpoints in a session and deletes them about 30 days after the session last saved one.

Can an AI code reviewer approve a pull request?

It should not be your only gate. In a CodeRabbit report on 470 open-source pull requests, AI co-authored pull requests averaged 10.83 issues, against 6.45 for pull requests labeled human. Claude Code Review never approves or blocks a pull request. GitHub says Copilot approvals do not count toward required approvals by default. Keep a human merge decision on anything that touches payments, auth or data.

What should I do when the AI keeps fixing the same bug?

After two failed corrections, run /clear and write a better prompt instead of a third correction. The new prompt names the file, describes the symptom, says what fixed looks like, and gives a command that passes or fails. For a bug with an unclear cause, Cursor's Debug Mode adds logs, asks you to reproduce the bug, then makes a small fix. Lovable's docs say to switch to Plan mode after one or two failed attempts.