Panda <xp>

AI Coding Agents: How They Work and How to Use Them Well

Me

Lucas Lauriano

10 min read

Share

How an AI coding agent works under the hood (plan, act, verify) and seven practices for using Claude Code, Codex or Cursor without reverting commits.

AI Coding Agents

I've been working on a personal project called Lumne.io, a career platform. At one point I asked an AI agent to create a new section of Lumne's Career University, the platform's public content area, in all three languages. It delivered routes, pages and copy in no time. Everything compiled beautifully. Only after the deploy did I notice that the sitemap and hreflang tags for one of the languages pointed to URLs that didn't exist.

The agent did exactly what I asked. The problem was what I didn't ask: I never told it how to check its own work. That episode sums up what separates people who get good results from coding agents from people who spend their days reverting commits.

What a coding agent does under the hood

In AI Engineering (chapter 6), Chip Huyen defines an agent as a language model with access to an environment and a set of tools. The model decides the next step. The tools let that step have an effect in the real world.

In a coding agent like Claude Code, Codex or Cursor's agent mode, the environment is your repository and your terminal. The tools are similar across all of them:

  • Read files and search the code.
  • Edit and create files.
  • Run shell commands: tests, build, lint, git.
  • Query external sources, sometimes through MCP servers.

Huyen splits tools into three groups: those that extend the model's knowledge (reading a file, searching the docs), those that extend its capabilities (running code) and write actions (editing a file, committing, sending a message). The last group needs the most care, because it changes the state of the system.

One detail changes how you think about all this: the model never executes anything. Maarten Grootendorst and Jay Alammar show this in An Illustrated Guide to AI Agents (chapter 5, Tooling). The model generates structured text saying which tool it wants to call and with which arguments. A program around it, the orchestrator, reads that request, runs the actual function and puts the result back into the conversation history. The agent is that whole package: the model, the tools and the loop that connects them.

How an agent uses a tool
How an agent uses a tool

The agent loop: plan, act, verify

The most common pattern behind these agents is called ReAct (Reason + Act). Huyen describes the loop like this: the model thinks about the next step, takes an action, observes the result and repeats until it's done.

As text, the diagram looks like this:

  1. Plan. The model reads the task and the context and decides what to do.
  2. Act. It asks for a tool: read a file, edit another, run a command.
  3. Observe. The result goes back into the context.
  4. Verify. It checks whether the goal was met. If not, it goes back to step 1.
AI Coding Agent Loop
AI Coding Agent Loop

Step 4 is the one that fails most often in practice. The agent can only verify what it can measure. If there's no test, build or check it can run, verification turns into "the code looks right". That's exactly what happened with my sitemap.

The code below shows this loop without any framework. It doesn't depend on a specific provider: the callModel function is an adapter you plug into whatever API you use.

TypeScript
// agent-loop.ts
// Node.js 22+, TypeScript 5+
import { readFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const run = promisify(execFile);

type ToolName = "read_file" | "run_tests";
type ToolCall = { name: ToolName; args: Record<string, string> };
type ModelReply = { text: string; toolCall?: ToolCall };
type Message = { role: "system" | "user" | "assistant" | "tool"; content: string };

// Adapter for your LLM provider (Anthropic, OpenAI, Vercel AI SDK...)
export type CallModel = (messages: Message[]) => Promise<ModelReply>;

type Tool = (args: Record<string, string>) => Promise<string>;

const tools: Record<ToolName, Tool> = {
  // Knowledge tool: the agent reads the repository
  read_file: async ({ path }) => readFile(path, "utf8"),

  // Verification tool: the agent finds out whether the code works
  run_tests: async () => {
    try {
      const { stdout } = await run("npm", ["test", "--silent"]);
      return `PASS\n${stdout}`;
    } catch (err: any) {
      return `FAIL\n${err.stdout ?? ""}${err.stderr ?? ""}`;
    }
  },
};

export async function runAgent(task: string, callModel: CallModel, maxSteps = 10) {
  const messages: Message[] = [
    {
      role: "system",
      content: "Plan before acting. Run run_tests before saying you are done.",
    },
    { role: "user", content: task },
  ];

  for (let step = 0; step < maxSteps; step++) {
    const reply = await callModel(messages);
    messages.push({ role: "assistant", content: reply.text });

    // No tool request: the model considers the task complete
    if (!reply.toolCall) return reply.text;

    // The model only asks. This code is what runs the tool.
    const { name, args } = reply.toolCall;
    const output = await tools[name](args);

    // Truncate large outputs so they don't flood the context
    messages.push({ role: "tool", content: output.slice(0, 4000) });
  }

  throw new Error("Step limit reached. Break the task into smaller parts.");
}

Three decisions in this code show up in any production agent: the step limit (maxSteps), truncating long outputs and a verification tool available from the start. Once you understand this loop, you understand why the practices in the next section work.

Why the agent gets things wrong

Before the practices, it helps to understand the failures and why they are predictable.

Context degrades as it grows. Grootendorst and Alammar (chapter 4, Memory) cite the RULER benchmark to show that model performance drops as context grows, an effect known as context rot. They also describe the lost in the middle problem: information in the middle of a long context gets less attention than what's at the beginning and the end. In a long session, a rule you gave in the first message can simply disappear.

An early mistake contaminates the rest. Huyen (chapter 2) calls this the snowball effect: once the model generates a wrong premise, it tends to stay consistent with it. In practice, the agent picks a bad approach in the first step and spends the next ten defending it.

It only verifies what it can measure. Without tests, a typecheck or a build, the agent has no way of knowing it got something wrong.

It reads content that isn't yours. Huyen (chapter 5) describes indirect prompt injection: malicious instructions hidden in external sources, like a web page, a dependency's README or an issue. An agent with write permissions and internet access widens that risk.

How to use AI coding agents: 7 steps

1. Give the agent permanent context

Every agent starts a session knowing nothing about your project. The CLAUDE.md file (in Claude Code) or AGENTS.md (a convention other tools support) is read at the start of every session. In Claude Code in Action (chapter 6), Muminjon Abduraimov and Pablo Farias recommend putting what doesn't change there: commands, ports, conventions.

A lean example:

TypeScript
# CLAUDE.md

## Commands
- `pnpm dev`: starts the app on localhost:3000
- `pnpm test`: tests with Vitest
- `pnpm typecheck`: tsc --noEmit

## Conventions
- Components live in `src/components`, one per folder, with the test next to it.
- No `any`. Types for external data come from Zod schemas.

## Before saying you're done
- Run `pnpm typecheck` and `pnpm test`. Both must pass.

Keep the file short. For the same reason as context rot, a 600-line CLAUDE.md hurts more than it helps. I wrote a whole guide on this: how to write a CLAUDE.md / AGENTS.md that actually works.

2. Plan first, in read-only mode

Abduraimov and Farias (chapters 3 and 4) show Claude Code's Plan Mode: a mode where the agent reads the code and discusses the solution, but doesn't edit or run anything. Other tools have something similar.

I treat the plan as a contract. I ask the agent to list the files it will touch, the order of the changes and how it will verify each one. If the plan is wrong, I fix it right there. Fixing a plan costs one message. Fixing code built on a wrong plan costs the afternoon and a lot more tokens.

3. Break the task into verifiable pieces

A good task for an agent has a beginning, an end and an objective way to know it worked. "Refactor the payments module" is too big. "Extract the fee calculation from checkout.ts into a pure function, with tests covering the current cases" is the right size.

A format that works well for the request:

TypeScript
Goal: extract the fee calculation from src/checkout.ts into src/fees.ts.
Constraints: don't change the public signature of checkout().
Done when: pnpm test passes and the new tests cover the 4 current fee types.
Out of scope: changing the rounding rule.

The "Out of scope" field keeps the agent from solving problems you didn't ask it to solve.

4. Make sure the agent can verify itself

In Refactoring (2nd edition, chapter 4, Building Tests), Martin Fowler argues that self-testing code, with automated tests that check their own results, is what lets you change code safely. The idea matters even more for an agent, which makes many changes in a short time and lacks the intuition of someone who knows the system.

In practice:

  • Write the test, or ask for it, before the change when the behavior already exists.
  • State in the request which command proves the task is done.
  • For things unit tests don't catch (sitemap, SEO, layout), create a simple check the agent can run. In Lumne's case, a script that validates that every sitemap URL returns 200 would have caught the bug from the opening. That's what I implemented afterwards.

5. Control permissions and write actions

Agents have permission levels. For Claude Code, Abduraimov and Farias describe three: the default mode, which asks for confirmation before editing or running anything; acceptEdits, which approves edits automatically; and Plan Mode, which is read-only.

My rule: allowing automatic edits inside the repository is fine when there's git and tests. Commands that reach outside the repository (deploys, database migrations, pushes, calls to production APIs) still require approval. These are Huyen's write actions. They have no "undo".

6. Keep sessions short

One session per task. When the task is done, start a fresh one. If the agent is stuck in a loop trying to fix the same error, stop, clear the context and start over with what you learned. Pushing on with a contaminated session just feeds the snowball effect.

7. Review it like a teammate's PR

The agent's code goes through the same flow as any other code: branch, pull request, review. I read the whole diff. I mainly look for three things: changes outside the scope, tests that were modified to pass and new dependencies nobody asked for. I go through this process in detail in the checklist for reviewing AI-generated code.

A real example: new content blocks on a Sanity site

On the corporate website I built with Next.js, TypeScript and Sanity for a New York client, each Sanity content type has a matching React component. That's what lets editors build pages without a developer.

Creating a new block always involves the same steps: the Sanity schema, the query, the TypeScript type, the component and its registration in the block map. It's a repetitive task with a clear pattern, a great fit for an agent.

The flow I use for this kind of task:

  1. The CLAUDE.md describes where each part lives and points to an existing block as a reference.
  2. In Plan Mode, I ask for the plan for the new block. It lists the five files and I check whether the query follows the same pattern as the others.
  3. I let it run with acceptEdits.
  4. The agent runs typecheck and build. The typecheck catches almost every contract error between the query and the component.
  5. I open the preview, check the block in Sanity Studio and open the PR.

What helped most was pointing to an existing block as an example. With a concrete reference, the agent copies the project's pattern. Without one, it invents its own pattern or hallucinates outright. In my case, I once had to ask for a refactor because it had created schemas with names in Brazilian Portuguese, my native language.

When not to use an agent

A coding agent speeds up tasks with a clear pattern and objective verification. Outside of that, it costs more than it helps. I avoid it in four situations:

  • Architecture decisions. I can talk to the agent to explore options, but the decision and its record are mine.
  • Code I can't review. If I can't judge whether the solution is right, the agent only hides the problem.
  • Systems without tests, in critical areas. Payments, authentication, data migrations. First I build the safety net of tests, then I let the agent in.
  • When I'm learning something new. Writing the code by hand is still the fastest way to understand a technology.

Checklist before handing a task to an agent

  • [ ] The project has a short, up-to-date CLAUDE.md or AGENTS.md.
  • [ ] The task has a goal, constraints, a definition of done and what's out of scope.
  • [ ] There's a command that proves the task is done (test, typecheck, build or script).
  • [ ] I asked for the plan and reviewed it before allowing edits.
  • [ ] Actions outside the repository still require approval.
  • [ ] One session per task.
  • [ ] The result goes into a PR and I read the whole diff.

Decision rule: if you can describe how to verify the task in one line, it's a good candidate for an agent. If you can't, start by writing that check.

Me

Lucas Lauriano

Software Engineer

Senior Software Engineer with over 14 years of experience in the software industry. Specializing in frontend development, with a strong background in JavaScript, React.js, Next.js, React Native, Sanity CMS, TypeScript and Node.js. Having leadership experience in team and project management. Experienced with product decisions and agile culture.