How to Debug AI-Generated Code
A repeatable method for tracking down bugs in AI-generated code — reproduce, isolate, prompt with real context, and verify with a test.
Why AI-generated bugs are a different shape
Bugs you write yourself usually come from a mental model you can retrace. Bugs in AI-generated code are different — the code can look completely plausible while quietly handling an edge case wrong, because the model pattern-matched to a common solution instead of reasoning about your specific requirements. This is exactly why the honesty section on /ai-coding matters: review is not optional.
Step 1: Reproduce it reliably before touching anything
Don't ask an AI tool to fix a bug you've only seen once and can't reproduce. Find the exact input or steps that trigger it first — a fix for a bug you can't reproduce is a fix you can't verify.
Step 2: Give the AI the real error and the relevant code, not a vague description
"It's broken" produces a guess. The actual stack trace, the failing input, and the specific function produce a real fix. Paste in what you have — don't summarize it from memory.
This function is returning the wrong total when a coupon is expired —
it should ignore the discount entirely, but it's still applying it.
Function:
[paste calculateTotal from lib/pricing.ts]
Failing case: calculateTotal([{ price: 100, qty: 1 }], "EXPIRED10")
Expected: 100
Actual: 90
Find the bug and explain what was wrong before fixing it.Step 3: Read the explanation and the diff before accepting
A good fix comes with an explanation of what was actually wrong. If the explanation doesn't match the code that changed, or if it changed something unrelated to the bug, don't accept it — ask again with more precision.
Step 4: Add logging when the AI's fix doesn't work first try
If a fix doesn't resolve the actual failing case, don't just ask it to "try again" — give it more signal. A quick log statement at the point of failure often reveals the real problem faster than another guess would.
function calculateTotal(items: CartItem[], coupon?: string) {
console.log("calculateTotal called with", { items, coupon, isExpired: isCouponExpired(coupon) })
// ...
}Step 5: Write a regression test so it can't come back silently
Once you understand the actual bug, turn the failing case into a permanent test. This is the step people skip most often, and it's the reason the same bug reappears three weeks later after another AI-driven change.
import { describe, expect, it } from "vitest"
import { calculateTotal } from "./pricing"
describe("calculateTotal", () => {
it("ignores the discount when the coupon has expired", () => {
const items = [{ price: 100, qty: 1 }]
expect(calculateTotal(items, "EXPIRED10")).toBe(100)
})
it("applies the discount when the coupon is valid", () => {
const items = [{ price: 100, qty: 1 }]
expect(calculateTotal(items, "SAVE10")).toBe(90)
})
})When to debug it yourself instead of asking again
- After two failed attempts on the same bug — a third identical prompt rarely produces a different result
- When the bug is in logic you don't fully understand yet — debug it yourself first so you actually understand what you're shipping
- Anything touching money, auth, or user data — verify the fix by reading it line by line, not by trusting a confident explanation
A pre-ship checklist for AI-touched code
- The specific bug case now passes, and you verified it yourself — not just trusted the AI's word
- A regression test exists for it
- You read the full diff, not just the lines the AI highlighted
- Nothing unrelated to the bug was changed
Tools used in this tutorial
Claude Code
A terminal-based agentic coding tool from Anthropic that reads, edits and runs code in your own repository.
Cursor
An AI-native code editor built on VS Code, with deep inline editing, chat, and agent capabilities.
OpenAI Codex
OpenAI's cloud and CLI coding agent that can work on tasks in an isolated sandboxed environment.
Prompts to pair with this
Debug a React state bug with a systematic root-cause prompt
Forces a systematic root-cause investigation of a React state or rendering bug instead of a surface-level patch that might mask the real issue.
Copy promptdebuggingDiagnose and fix a Next.js hydration mismatch error
Walks an AI through correctly diagnosing a Next.js hydration mismatch and fixing the root cause, instead of silencing it with suppressHydrationWarning.
Copy prompttestingGenerate a thorough unit test suite for existing code
Generates a unit test suite that actually covers edge cases and failure paths for existing code, instead of only testing the happy path.
Copy promptRelated tutorials
Getting Started with Claude Code
Install Claude Code, set project-level conventions, and complete your first real task inside an existing codebase.
BeginnerGit Basics for AI-Assisted Coding
Git isn't optional once an AI tool is editing your code for you — it's the only reliable way to review, commit and roll back changes.
BeginnerHow to Build a Simple AI Agent
Build a working agent loop — tool definitions, a system prompt, execution, and the guardrails that keep it from doing something destructive.
AdvancedReady to build the next one?
Browse the full tutorial library or grab a ready-made prompt for your next step.