Use AI to understand code
By Flavio
Updated
Tagged: AI
How I use coding agents to understand existing code before changing it: focused questions, tracing data and side effects, and reviews in a fresh session.
Most people open an AI chat and ask it to write something. I do that too, but more often I do the opposite: I point the agent at code that already exists and ask questions until I understand how it works. Once I have a clear picture, if something needs to change, I let it write.
The code that comes out is useful, sure, but what stays with me after the session ends is the understanding of the codebase.
Writing is the easy part now
I ship a lot of code with coding agents, in Cursor, Claude, and Codex. They’re fast, and they’re perfectly happy to produce a diff I haven’t read. When that work happens outside the editor, the checks still need a place, which I wrote about in What changes when you stop opening the code editor?.
I noticed this years ago, when generated code didn’t feel mine and I had to go back and read it after the fact. If you still want to maintain the project next month, that reading isn’t optional.
So I flipped the order. I use the agent to build a mental model of the code first, then I let it write, and then I ask it more questions about what it wrote.
Give it the repo
A pasted snippet isn’t enough for this. If I ask “does this leak data?” and the model only sees one function, it can only answer about that function. Meanwhile, the leak might be three files away, and the permission check might live in a helper nobody calls anymore.
So I open the whole project in the agent and let it read. I want it to follow the call into the query, the email, the cookie, wherever the data goes. I also keep the project facts in an AGENTS.md file so it doesn’t have to rediscover how the site builds every time.
Ask one sharp question
Asking “explain this file” just gives me a summary, which is the file rewritten in English. I still don’t know how it behaves. The same habit helps when you want a particular behavior from an agent, something I wrote about in What teaching can tell us about prompting.
Instead, I ask one specific question at a time:
- What happens when this webhook arrives twice?
- Where does this email go after we store it?
- If this function returns 200, did the user get access?
- Does the error reach the person who paid, or only my logs?
After five or six answers like these, I can see how the system works. The model is good at this kind of tracing. It jumps from a function to an HTTP call to a database query to a user-facing error without losing the thread, which is what I struggle to do in my head on a first read.
Build the map in layers
I don’t ask for the whole architecture at once. Instead, I go in four passes.
First, I ask about the entry point:
What starts this flow, and what input crosses the boundary?
Name the route, event, command, or component.
Next, I follow the data:
Trace `orderId` from the request to storage.
List every function that transforms or validates it.
After that, I trace the side effects:
Which operations leave this process?
Include database writes, network calls, emails, and queue messages.
Finally, I ask about failure paths:
For each side effect, what happens if it succeeds and the next step fails?
Going in that order leaves me with a clear path through the code instead of a pile of files.
I always ask for file paths and function names in the answer. If a claim comes with a location, I can open it and check, whereas a claim without one is easy for the model to make up.
Ask for evidence, not confidence
Models use the same confident tone for facts and guesses, so I ask the agent to separate them in its output:
Answer in three parts:
1. Confirmed behavior, with file and function references
2. Assumptions you could not verify
3. The smallest commands or tests that would resolve those assumptions
The answer can still be wrong, of course, but now I can see which parts the model checked and which parts it assumed.
Suppose the agent says a webhook is deduplicated. I ask where the durable key is stored. If it points at an in-memory Set, the behavior is local to one process and gone on the next restart, so the deduplication only sounds like a guarantee. If it points at a unique database constraint, I can open the migration and the insert and confirm it.
A real walkthrough
Let’s take a real example: a purchase webhook I have on this site. Paddle hits /purchase, and we grant course access and send an email.
Here’s a simplified version of the decision in the middle:
if (body.alert_name) {
return Response.json({
message: `Ignoring account alert: ${body.alert_name}`,
})
}
const productId = body.p_product_id
If I drop this on an agent and ask what it does, I get a paragraph about ignoring account alerts. That’s right, but it’s not enough, so I ask the follow-up questions myself:
- Why are there two payloads for one purchase?
- What happens if we handle both?
- Does the in-memory
Setthat dedups emails survive across Cloudflare isolates? - If the newsletter subscribe fails, do we still write the access record?
- If the access record fails, did the buyer already get the email?
That last one matters, because the buyer thinks they’re in while my retrieval page might not list the course yet.
None of those answers live in one function. You find them by following the path from the request to the email, and that’s where the agent helps me most.
Attack a change
When an agent proposes a change, asking “does this look good?” almost always gets me a yes. So I ask it to attack the change instead:
- What existing behavior does this touch?
- Can we fold this into a function we already have?
- Does a failure show up in the UI, or does it fail silently?
- Is this query doing more work than it needs?
Then I read the answers with some suspicion. Ask a model for risks and it’ll find risks, real or not, and it can still miss the one that matters. My job is to check each one against the code and keep the ones that hold up.
I do this in a fresh chat when I can. The session that wrote the code is biased toward defending it, while a new session only sees the diff and the repo.
Plan before you generate
The same habit works before any code exists. Before I let an agent add a feature, I ask what’s already there:
- Is there a helper for this?
- Which pages call this function today?
- If we change the return shape, who breaks?
I also ask it to lay out the tradeoffs upfront, like KV vs. D1, cookie vs. server session, or one endpoint vs. two. I want to be the one who picks, because if I skip this step the model decides for me and I inherit a design I never agreed to.
A short written brief helps here too: the facts, the constraints, and a request for the agent to list its assumptions before it starts.
Tests are another way to ask
Asking an agent to “write tests” rarely gives me anything useful. Asking it to “write a test that proves a duplicate webhook doesn’t send a second email” is much better, because it’s a question about behavior written as a test.
If the test is hard to write, that’s usually a sign I don’t understand the behavior yet, and finding that out before the change is much cheaper than finding out after. Even then, I still read the tests carefully, because a model can easily write one that passes while proving the wrong thing.
Turn the model into a debugger
When code fails, I give the agent the evidence in the order the program produced it:
- the command I ran
- the complete error, not just one line
- the expected behavior
- the smallest input that reproduces it
- any recent change that might be related
Then I ask for competing explanations:
Give me the three most likely causes.
For each cause, name one observation that would prove or disprove it.
Do not change files yet.
This works much better than “fix the bug” because it keeps diagnosis separate from implementation.
If two explanations predict the same observation, the test isn’t telling me much, so I ask for a check that separates them. For example, a failed API call might come from invalid input, an expired credential, or a network failure. Logging the status code separates the first two from the third, and inspecting the response body and credential expiry separates the first from the second.
The model is good at designing the experiment, but I still have to run it to get the answer.
Read the diff as a story
A diff tells me what changed, but not whether the new behavior is complete. So I ask the agent to walk the diff in execution order:
Trace one successful request through this diff.
Then trace one invalid request and one dependency failure.
Point out any branch that has no test.
This catches a common problem: the happy path changed in one file, while error mapping, cleanup, or the caller stayed on the old contract.
I also ask what didn’t change. If a return type changed and none of the callers were updated, either the change is backwards compatible or we missed something, and I want to know which.
Compare the explanation with runtime behavior
Static reading has its limits. Dynamic configuration, framework routing, generated code, and environment variables can all change what runs, so the agent might trace the obvious function while production calls a different one.
I verify the map with small runtime checks:
- run the focused test
- call the endpoint with a known input
- inspect the response status and headers
- add a temporary breakpoint
- check which handler appears in the stack trace
- inspect a database row before and after
If HTTP is still a bit foggy, the free HTTP course helps, because status codes and headers become evidence you can read. For general code reading, the free JavaScript course builds the vocabulary the model assumes you have.
So the loop is: ask, look at what the program does, and compare the two.
Do not outsource the judgment
It’s easy to ask the model whether permissions are enforced downstream, get a yes, and relax.
The model can trace a call, but it can’t be the authority on whether your product is safe. You still need to open the other file, try the request yourself, and look at the header in the response.
I wrote about hardening public form endpoints for this reason. Body size limits, allowlists, and rate limits are things you verify by sending a request, not things you accept because the explanation sounded right.
The same goes for “is there a leak?” Ask the agent, then grep the codebase and check the logs. An email address in a console.log is a leak if those logs leave your machine.
This does not teach you how to read
If you’re learning to code, be careful with this habit.
You can collect answers and feel like you understand the codebase without ever practicing reading code yourself. Then you open the next file with no chat window and you’re stuck again.
My advice is to try first. Read the function, guess what it does, then ask and compare your guess with the answer. That’s how you get a feel for when the answer is nonsense, and you need that.
The fundamentals matter for the same reason, and I listed the ones I’d still learn in The 10 fundamentals still worth learning when AI writes the code. My free JavaScript and Git courses exist so you can notice when the model is wrong.
Common mistakes
Don’t start by asking for a summary of a file. Summaries compress syntax and rarely explain behavior that crosses files, so ask about one path, one value, or one failure instead.
The same goes for open-ended risk questions. Ask “what could go wrong?” and you’ll get a generic list that could fit any application. Ask which risks are reachable in this code, and make the model trace the route from input to consequence.
Another easy trap is letting the same session review code it just wrote. It already has a story about why the code works, so start a fresh session and hand it the repository and the diff.
If the agent can’t explain the current path yet, don’t let it rewrite the code. Narrow the question until the explanation holds up, then ask for the change.
Be careful with generated tests too. A test written from the same wrong assumption just confirms that wrong assumption, so compare it with the requirement and make sure at least one case fails on purpose.
And don’t paste secrets into the context. The agent almost never needs real credentials or customer data to explain a path, so give it redacted payloads and local fixtures.
How I use this every day
I run a bunch of small sites, and I’m usually the only person in the repo.
In a typical session, I open a project in Cursor and point at a function I haven’t touched in months. I ask what it does, what it doesn’t do, who calls it, and what happens when it fails.
If I’m about to change it, I ask what else that change will touch. Then I write a short plan, or I let the agent write one and cut it down. After that, I let it implement one slice, review the diff, and ask it to try to break its own change so I can fix what turns up.
I don’t do any of this for a one-off script I’m going to delete tonight. It takes time, and it’s only worth it for code I’ll have to live with.
It’s also a poor fit when you already know the path cold. If I wrote the function this morning, I don’t need a tour. I just want a second pair of eyes on the one thing I might have missed.
Code is the byproduct
I still want the feature shipped, but I don’t want a repository I can’t explain.
What I take away from a session is a clear picture of how the system works. The files on disk are a side effect of that, and they’re better files because I understood what they had to do.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: