◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

AI Coding Assistants and Agents

Coding assistants grew from autocomplete into agents that read a code base, edit files, run the tests and iterate. This chapter shows how they work inside, how to use them well, how to review what they produce, and where they still fail.

Level
●●●●● Easy
Reading
12 min
To learn it well
1 hour to read, then daily practice
↗ Plan a path here

Read first

AI Agents

This leads to

—
The full path from zero — 10 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Prompt Engineering
  7. Structured Output and JSON
  8. Chain-of-Thought and Reasoning Prompts
  9. Tool Use and Function Calling
  10. AI Agents
  11. AI Coding Assistants and Agents

Read them roughly in this order. See it on the concept map →

Why it matters

Software is where AI agents work best today. Code has a property most tasks lack: you can check it automatically. Run the tests, run the type checker, run the program, and you learn within seconds whether a change worked. That fast, honest feedback is exactly what the agent loop needs, so coding has become the proving ground for agents.

The tools have moved quickly. In 2021 GitHub Copilot suggested the next few lines as you typed. By 2025 coding agents such as Claude Code, OpenAI's Codex, Cursor's agent mode, Aider and others could take a request like "add CSV export to the reports page, with tests", explore the repository, edit several files, run the test suite, fix what broke and hand back a finished change. Many professional developers now use them daily. Knowing how they work is useful even if you never build one: it tells you how to give them good instructions, and what to check before you trust their output.

The intuition

There are three generations of tool, and they map onto three kinds of human help:

  1. Code completion is a fast typist reading over your shoulder. It predicts the next line or block from the surrounding code. It is fast, it is right often, and it needs nothing from you except a good start. Under the hood it is plain next-token prediction, often with "fill in the middle" training so it can use the code after the cursor too.
  2. Chat assistants are a knowledgeable colleague you can ask. You paste code and a question, and you get an explanation or a snippet back. You do the copying, running and checking.
  3. Coding agents are a junior developer given a ticket. They find the relevant files themselves, make changes, run the tests and keep going until done. They can do much more, and they can go wrong in much bigger ways.

The junior-developer analogy holds up well. They are quick and widely read, and they don't get tired. They also don't know your team's conventions unless someone tells them. They sometimes "fix" a failing test by changing the test. And they need code review.

Your request "Fix mean(); tests must pass" Instructions file CLAUDE.md / AGENTS.md Model plans the next step permission: ask or allow? Gather context glob · grep · read file (agentic search) Edit str_replace: unique old text → new text Run tests · linter · type check build · git Repository committed first, so every change is a reviewable diff sandbox search, read feedback FAIL: line 2, expected 3, got 4.0
Fig. 1 A coding agent's loop. The model gathers context by searching and reading files, edits with precise replacements, and runs tests or commands. Test output is the feedback that tells it whether to stop or try again. The permission layer decides which actions need your approval.

Key idea A coding agent is the agent loop with tools for searching, reading, editing and running code. It is only as good as its feedback. Tests and a clear definition of "done" turn a guessing machine into one that checks its own work.

How it works

The tools

Look inside any coding agent and you'll find a small set of tools:

  • Search: find files by name pattern (glob) and find text inside files (grep, ripgrep). Agents use these constantly to locate the code that matters.
  • Read: show a file, or a range of lines, with line numbers.
  • Edit: change a file. Making this reliable turned out to be hard (see below).
  • Run: execute shell commands, such as tests, linters, builds, git, or the program itself.
  • Optional extras: web fetch for documentation, MCP servers for issue trackers or browsers, and sub-agents that search a large code base and report back.

The agent can't read a million-line repository at once, so how does it find the right code? There are two approaches. Early tools built an embedding index of the code base and retrieved chunks by semantic similarity, much like Retrieval-Augmented Generation. Many current agents mostly use agentic search instead: the model itself runs grep and glob, reads what it finds and follows the trail, much as a developer would. Agentic search needs no index that can go stale and handles exact identifiers well. It costs more tool calls.

Agents also read an instructions file at the start of each session: a Markdown file in the repository (CLAUDE.md for Claude Code, AGENTS.md as a cross-tool convention) that records how to build and test, coding conventions, and things to avoid. It is the onboarding document you would give a new colleague, written for the model.

Editing: the edit format

How should a model change a file? The obvious answer, "write out the whole new file", is slow and expensive for large files, and models sometimes silently drop parts of the file when rewriting it. The edit format is the convention the agent uses to express a change. Common ones:

  • Whole file: simple, wasteful, risky for big files.
  • Search and replace: give an exact snippet of the old text and its replacement. The tool refuses if the snippet doesn't appear exactly once, which catches the model's mistakes about what the file contains. Claude Code's edit tool works this way.
  • Unified diff: the format git diff prints. It is compact, but models often get the line numbers and context lines slightly wrong.

The Aider project documented that the choice of edit format changes a model's measured coding success noticeably. Even here, interface design matters as much as model intelligence, which is the agent-computer interface lesson again.

Feedback: tests close the loop

After editing, a good agent runs the relevant tests or the type checker. If they fail, the error message is a precise observation: file, line, expected versus actual. The agent reads it and tries again. A task with tests is a task the agent can verify. A task without tests ("make the UI nicer") leaves the agent judging its own work, which it does poorly.

Permissions and sandboxes

An agent that can run shell commands can also run rm -rf or push to production. Coding agents therefore have permission modes: ask before every edit or command, allow edits but ask before commands, or run fully automatically. Fully automatic is only sensible inside a sandbox: an isolated container or virtual machine with no access to secrets or production systems, and limited network access. Version control is your undo button. Commit before an agent starts, and review its changes as a diff.

Measuring coding agents: SWE-bench

How do we know these agents are improving? HumanEval (OpenAI, 2021) gave 164 small hand-written Python functions to complete, checked by unit tests. It was soon too easy. SWE-bench (Princeton, 2023) took 2,294 real GitHub issues from 12 popular Python repositories. The agent gets the repository and the issue text and must produce a patch. The patch is judged by running the project's tests: tests that failed before the real fix must now pass, and tests that passed before must still pass. In the original paper the best model resolved under 2% of issues. SWE-bench Verified (August 2024) is a subset of 500 issues that human engineers checked to be clear and fairly testable. By 2025 the leading agents resolved well over half of them. Check the current leaderboard rather than any number printed in a book.

Repository at the commit before the real fix Issue text "mean() is wrong for two numbers…" Agent explores, edits Patch a git diff Fail-to-pass tests added with the real fix; failed before. Must now pass Pass-to-pass tests already passing; catch new breakage. Must still pass Resolved only if both hold score = % of issues resolved (Verified subset: 500 human-checked issues) The agent never sees the tests. Full benchmark: 2,294 real GitHub issues from 12 popular Python projects (2023).
Fig. 2 How SWE-bench scores a coding agent. The agent sees only the repository and the issue text. Its patch is applied and two sets of hidden tests are run: tests the real fix made pass, which must now pass, and tests that already passed, which must not break.

Do they make developers faster?

Less obviously than you would think. In a 2025 randomised trial by METR, 16 experienced open-source developers worked on 246 real tasks in projects they knew well. Allowing AI tools (mainly Cursor with Claude models, as of early 2025) made them 19% slower on average. Before starting, they had predicted a 24% speed-up, and afterwards they still believed they had been about 20% faster. That doesn't mean coding agents are useless. The setting was experts in large, familiar code bases with high quality standards, and the tools have improved since. But it is a strong warning that feeling productive and being productive differ. Measure on your own work.

In code

A miniature coding agent's tool layer: a search-and-replace edit tool that refuses ambiguous edits, and a test runner whose output is the feedback. As in AI Agents, a scripted list of steps stands in for the model so the loop is checkable offline. Runs as written.

import pathlib, subprocess, sys, tempfile

repo = pathlib.Path(tempfile.mkdtemp())
(repo / "stats.py").write_text("def mean(xs):\n    return sum(xs) / len(xs) + 1\n")   # a bug
(repo / "test_stats.py").write_text(
    "from stats import mean\nassert mean([2, 4]) == 3, mean([2, 4])\nprint('all tests pass')\n")

def read_file(path):
    return (repo / path).read_text()

def str_replace(path, old, new):
    text = (repo / path).read_text()
    if text.count(old) != 1:                         # refuse ambiguous or missing edits
        return f"Error: old text found {text.count(old)} times; it must be unique"
    (repo / path).write_text(text.replace(old, new))
    return "edited"

def run_tests():
    r = subprocess.run([sys.executable, "test_stats.py"], cwd=repo, capture_output=True, text=True)
    return "PASS: " + r.stdout.strip() if r.returncode == 0 else "FAIL: " + r.stderr.strip().splitlines()[-1]

TOOLS = {"read_file": read_file, "str_replace": str_replace, "run_tests": run_tests}

script = [  # what a model might do; a real agent chooses each step from the last result
    ("run_tests", {}),
    ("read_file", {"path": "stats.py"}),
    ("str_replace", {"path": "stats.py", "old": "xs", "new": "values"}),   # ambiguous: refused
    ("str_replace", {"path": "stats.py", "old": " + 1", "new": ""}),
    ("run_tests", {}),
]
for step, (tool, args) in enumerate(script, 1):
    result = TOOLS[tool](**args)
    print(f"{step}. {tool}{args or ''} -> {result!r}")
    if result.startswith("PASS"):
        break
# 1. run_tests -> 'FAIL: AssertionError: 4.0'
# 2. read_file{'path': 'stats.py'} -> 'def mean(xs):\n    return sum(xs) / len(xs) + 1\n'
# 3. str_replace{'path': 'stats.py', 'old': 'xs', 'new': 'values'} -> 'Error: old text found 3 times; it must be unique'
# 4. str_replace{'path': 'stats.py', 'old': ' + 1', 'new': ''} -> 'edited'
# 5. run_tests -> 'PASS: all tests pass'

Step 1 is the habit that matters most: run the tests before editing, so you know what "broken" looks like. Step 3 shows why the edit tool insists on a unique match. A blind replace-all would have renamed the parameter in three places, which was not the intended change.

Using coding agents well

  • Write the instructions file. Build and test commands, style rules, directories to avoid. A few dozen lines save many corrections.
  • Give it a way to check its work. Point it at the tests, or ask it to write a failing test first and then make it pass.
  • Ask for a plan before code on anything non-trivial, and correct the plan. That is cheaper than correcting the code.
  • Keep tasks small and specific. "Add a --json flag to the export command that writes the same fields as the CSV" beats "improve export".
  • Commit often, so a wrong turn costs one git reset.
  • Start a fresh session for a new task, so stale context from the last one doesn't mislead it.

Reviewing what it produces

Read the diff as you would a stranger's pull request:

  1. Does it do what was asked, and only that? Look for unrequested refactors.
  2. Were tests changed? Weakened assertions, deleted tests or new skip markers are red flags.
  3. Do the functions, libraries and versions it uses actually exist? Check imports and new dependencies.
  4. Are errors handled, or silently swallowed?
  5. Security: input validation, SQL built by string concatenation, secrets in code, overly broad permissions.
  6. Would you understand this code in six months? Agents often produce verbose, over-defensive code.

Common pitfalls

  • Plausible but wrong. Code that reads well and passes a shallow test can still mishandle edge cases. Ask for tests of edge cases (empty input, unicode, time zones) explicitly.
  • Invented APIs. Models sometimes call library functions that don't exist, or use an older version's API. Running the code catches most of these. Reading the docs catches the rest.
  • Made-up packages. Models sometimes suggest dependencies that don't exist, and attackers have registered such names with malicious code (called "slopsquatting"). Check every new dependency before installing it.
  • Tampering with the check. Told to make the tests pass, agents sometimes edit the tests or special-case the test inputs. Say "don't modify tests" and check the diff.
  • Scope creep and context drift. Long sessions wander. Restate the goal, or start fresh.
  • Over-trust. The METR result shows how easy it is to feel faster without being faster.

Watch out Never run an agent in fully automatic mode on a machine with production credentials, SSH keys or customer data. A prompt injection hidden in a README, an issue or a web page the agent reads can make it run commands on your behalf. Use a sandbox or container, limit network access, and keep approval switched on for anything that leaves the machine.

Where it leads

A bit of history

OpenAI's Codex model (2021), a GPT-3 fine-tuned on public code, powered GitHub Copilot, whose preview launched in June 2021, and was measured with the new HumanEval benchmark. DeepMind's AlphaCode (2022) reached roughly median human performance in programming competitions by sampling huge numbers of candidate programs and filtering them. Chat-based coding help followed ChatGPT in late 2022. Agentic tools appeared in 2023 and 2024: Aider pioneered terminal-based pair programming with git integration, Cognition's Devin (March 2024) was announced as an "AI software engineer", and SWE-agent showed that interface design mattered. In 2025 agentic coding went mainstream with Claude Code, OpenAI's Codex agent, and agent modes in Cursor, VS Code and other editors, and SWE-bench Verified scores rose steeply through the year.

Try it

  1. Add a grep(pattern) tool to the mini agent that returns path:line: text for every match in the repo. Use it to find where mean is defined.
  2. Add a second test that checks mean([]) raises ValueError. Run the script: the old fix now fails the suite. Write the extra script steps that make it pass.
  3. Pick a small real task in one of your own projects. Do it once by hand and once with a coding agent, timing both and counting how many corrections the agent needed. Was it faster?

Hint for 2: the edit must replace the return line with an if not xs: raise ValueError(...) check followed by the return. Your old string must be unique.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why has coding become the main proving ground for AI agents?

  2. A search-and-replace edit tool refuses an edit because the old text appears 3 times in the file. Why is this refusal useful?

  3. You want to let a coding agent run fully automatically without approvals. Where is that sensible?

  4. In the 2025 METR trial, experienced developers using AI tools on familiar projects were 19% slower, yet believed they were about 20% faster. What is the lesson?

  5. Reviewing an agent's diff, you see a test's assertion was loosened and a new skip marker was added. How should you read this?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Claude Code: Best practices for agentic coding

Anthropic · 2025 · Beginner · Free

Concrete workflows for coding agents: CLAUDE.md files, explore-plan-code-commit, test-driven loops, course-correcting early, and running agents safely.

Tool

Aider

Paul Gauthier and contributors · Intermediate · Free

An open-source AI pair programmer in the terminal that works with many models and commits each change to git. Its docs on edit formats and its leaderboards are instructive.

Paper

Evaluating Large Language Models Trained on Code

Chen et al. (OpenAI) · 2021 · Intermediate · Free

The Codex paper: a GPT model fine-tuned on public code, the HumanEval benchmark of 164 hand-written problems, and the pass@k metric.

Docs

Claude Code documentation

Anthropic · Beginner · Free

Docs for Anthropic's terminal-based coding agent: setup, permission modes, memory files, MCP servers, sub-agents, hooks and the Agent SDK.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/coding-agents.md