Skip to content

How AI Coding Agents Work and Fail

Summary

Explains how large language models and coding agents work, why they drift and give confident wrong answers, and how instruction files and plans keep an agent on track.

Concepts Covered

This chapter covers the following 23 concepts from the learning graph:

Concept Concept Impact Score
Large Language Model 130
AI Coding Agent 64
Vibe Coding 2
Agent Harness 1
Context Window 11
Token 7
Token Cost 6
Context Drift 5
Hallucination 17
Confident Wrong Answer 11
Prompt 20
Agent Instructions 19
Project Instruction File 16
CLAUDE.md 4
AGENTS.md 4
Plan Before Code 13
Agent Tool Use 6
Agent Permissions 3
Subagent 1
Agent Memory 4
Judgment as the Constraint 1
Trust in Agent Output 10
Model Selection 1

Prerequisites

This chapter builds on concepts from:


A House-Sitter and a Note on the Fridge

A family is getting ready for a week away. They have hired a house-sitter, a cheerful college student who comes well recommended. She is quick and willing, and she can do almost anything you ask. The night before they leave, the father walks her through the house and talks for forty minutes. Feed the dog twice a day. The basil on the porch needs water every morning, and the plastic fern by the stairs needs none. Never let the cat out the back door, because the back yard opens onto a busy road. The thermostat is touchy. The office stays shut.

By Thursday a few things have gone sideways. The cat got out the back door on Wednesday and came home on its own, by luck. When the mother texts to ask whether the plants are getting water, the sitter answers at once: "Yes, all of them, every morning!" She has been watering the plastic fern. And she has used a slow afternoon to reorganize the pantry by color, which nobody asked for, and now nobody can find the rice.

Welcome to Chapter 4

Sawyer waving welcome Your agent is a lot like this sitter: quick, willing, and new to your house. This chapter shows why it forgets your rules and sounds sure when it's wrong. By the end you'll have three cheap habits that keep it working for you, and you'll know which of its claims need a test before you believe them.

None of this means the sitter is careless. She was handed forty minutes of spoken instructions in one go, and the early ones faded under the later ones. She answered the plant question the way most people would, with what she believed. She saw a free afternoon and filled it with something that looked helpful.

The next time the family travels, they do three things differently. They tape a one-page note to the fridge with the rules that must not be broken, written at the top in large letters. They ask the sitter to text a short plan each morning before she starts. They also keep the office door locked.

An AI coding agent is a lot like that sitter. It is fast, willing and able, and it has never been to your house before. This chapter explains how it works, why it forgets, and why it can be sure of things that aren't true. Then it shows how a note on the fridge, a morning plan and a locked door keep it working for you.

What a Large Language Model Does

The engine inside every AI coding agent is a large language model, often shortened to LLM. A large language model is a computer program trained on a huge amount of text to predict what text should come next. Given the words so far, it produces the most likely continuation, one small piece at a time. Claude, GPT and Gemini are large language models. "Large" refers to the billions of internal settings the model has. It also refers to the amount of text it learned from, which includes much of the public web, books and a great deal of open-source code.

That one skill, predicting the next piece of text, turns out to cover a lot of ground. To continue a question well, the model has to produce something that reads like an answer. To continue a half-written function well, it has to produce code that fits. Training on billions of examples of explanations, arguments and working programs gives the model patterns it can apply to text it has never seen. That's why it can write a new route for your app, explain an error message, or draft a test.

Three facts about how a model works matter for everything else in this chapter.

  1. It works from patterns, not from looking things up. When a model writes the name of a function in a library, it isn't checking the library. It is producing what a function name in that spot usually looks like. Most of the time that matches the library. Sometimes it doesn't.
  2. It has no memory between conversations. A model doesn't learn from your session. Tomorrow it knows nothing about today unless something hands today back to it.
  3. It sounds equally sure whether it is right or wrong. The model produces fluent, confident text either way, because confident text is what its training data mostly contains.

Tokens

A model doesn't read words the way you do. It reads tokens. A token is a small chunk of text, often a whole short word, part of a longer word, a space with a word, or a piece of punctuation, that a model reads and writes as one unit. In English, one token is roughly four characters, or about three-quarters of a word. Code usually takes more tokens per line than plain English, because it is full of symbols, short names and spacing.

Here is a rough sense of size for things you hand an agent every day. The counts are estimates using the rule of thumb above; each model splits text a little differently.

Text Rough size Rough tokens
A one-line request: "Add a timeout to the photo check" 7 words 10
One page of this book 500 words 650
A 300-line adapter file in TypeScript about 9,000 characters 2,500 to 3,000
The output of a full test run with one failure a few hundred lines 5,000 to 15,000
A large codebase read end to end hundreds of files millions

Tokens matter for two reasons, both covered in the next section. A model can only hold so many of them at once, and you pay for every one.

Prompts

Everything a model reads before it answers is its prompt. A prompt is the text given to a model as input, which the model continues to produce its answer. When you type "Add a timeout to the photo check" into an agent, that sentence is part of the prompt. So is a great deal you never see, as the section on the harness will show.

Because the model continues whatever it is given, the prompt shapes the answer more than anything else you control. A vague prompt gets the most likely answer to a vague question. A specific prompt narrows the likely answers down to the one you want. Compare two ways of asking for the same change in the dating-safety app:

Weak prompt Stronger prompt
"Make the photo check more reliable." "The image-search adapter sometimes hangs for 40 seconds. Add a 10-second timeout. When the timeout fires, mark the photo check 'not checked'. Never score it as passed. Add a test that simulates a hang and checks the result is 'not checked'. Change only the image-search adapter and its test."

The weak prompt leaves the model to guess what "reliable" means. In the code it has seen, "reliable" most often means "retry until it works" or "return a default value." The stronger prompt names the problem and the fix. It also names the rule that must hold, the test that proves it, and the edge of the change. Each of those details removes a wrong answer the model might otherwise have picked.

Tell your agent

"Before you start on my request, repeat it back to me in your own words: what you'll change, which files you expect to touch, what rule must hold afterward, and what test will prove it. If any part of my request is unclear, ask me instead of guessing."

The Context Window and What It Costs

The model's working space has a hard edge. The context window is the largest amount of text, counted in tokens, that a model can take in at one time: your messages, its own replies, every file it has read and every command output it has seen in the session. In 2026, common context windows run from about 200,000 tokens to a million. That sounds like a lot. A busy agent session fills it faster than you'd think, because reading files and running tests pours tokens in.

Think of the context window as the sitter's working memory for the week. Whatever is inside it, the model can use. Whatever falls outside it, the model has never heard of.

What Happens When the Window Fills

When a session grows past the window, something has to go. Agents handle this in different ways. Some stop and tell you to start a new session. Many squeeze the older part of the conversation into a short summary, a step often called compaction, and keep going. A summary keeps the main goals of the earlier work. It tends to lose the details, and an instruction you typed early in the session is exactly the kind of detail that gets lost.

Even inside the window, not every token gets equal attention. In 2023, Nelson Liu and colleagues at Stanford published a study called "Lost in the Middle." They found that models use information at the start and end of a long input better than information buried in the middle. An instruction from an hour ago may still be in the window and still get less weight than the test output from a minute ago.

Token Cost

Every token has a price. Token cost is the money charged for using a model, figured from the number of tokens it reads (input tokens) and writes (output tokens), each at a price per million tokens set by the model's provider. Output tokens usually cost several times as much as input tokens. Bigger, more capable models cost more per token than smaller ones.

The part that surprises people is how input adds up during an agent session. Each time the agent takes a step, the model reads the whole conversation so far, not just the newest message. A session where the context averages 100,000 tokens and the agent takes 50 steps reads about 5 million input tokens:

\[ 50 \text{ steps} \times 100{,}000 \text{ tokens per step} = 5{,}000{,}000 \text{ input tokens} \]

At an illustrative price of $3 per million input tokens, that is $15 for one afternoon's session, before any output tokens. Many providers charge less for context the model read a moment ago, a discount called caching. That helps, but a long, busy session is still the most expensive way to work. Prices change often, so check your provider's price page rather than trusting any number in a book, including this one.

27 Million Tokens in an Afternoon

The author of this book once built a working prototype of a "deep research" tool, a program that takes a question, searches the web, reads what it finds, and writes a report. He built it in about four hours with an AI agent, test by test, and the tests passed. When he looked at the usage afterward, the work had burned through 27 million tokens.

Nothing in the code was broken. The tests checked that the tool produced a report, and it did. What the code lacked was any limit. There was no cap on how many tokens one research run could use, no cap on how many steps the research loop could take, and no cap on how long it could run. Each search led to more pages to read, each page went back into the model, and the context grew with every pass.

Numbers like that are easy to reach. A loop that makes 300 model calls with about 90,000 tokens in context each time reads 27 million tokens. Tests that check what a program produces don't see what it costs, so a passing test suite said nothing about the bill.

The lesson from this story has two halves. For the agent you build with, long sessions cost more per step than short ones, so starting fresh sessions for fresh tasks saves money as well as attention. For any AI feature inside your app, such as the dating-safety app's message check, every model call needs a limit on tokens, steps and time. Chapter 13 shows how to set those limits and the spend alerts that back them up.

Tell your agent

"Find every place in this app that calls an AI model. For each call, tell me whether there is a limit on the tokens it can use, a limit on how many times it can loop or retry, and a timeout. List any call that has none of the three. Don't change anything yet."

From Model to Agent

A model on its own can only produce text. It can write a perfect fix for a bug and have no way to save it to a file. An agent is what lets it act.

An AI coding agent is a program that wraps a large language model in a loop and gives it tools. With them it can read your code, change files, run commands and check the results on its own, step after step, until a task is done. Claude Code, Cursor's agent, GitHub Copilot's agent mode, OpenAI's Codex and Replit's agent are all AI coding agents. You give the agent a goal. It decides what to look at, makes a change, runs the tests, reads what happened, and tries again if needed.

The loop is the whole difference. A chat assistant hands you code and stops, and you paste it in and see whether it works. An agent pastes it in itself, runs it, reads the error, and fixes it before it reports back. That is why an agent can build a feature in an afternoon. It is also why a mistake can travel further before you see it.

The Harness

The model is one part of an agent. The agent harness is all the software around the model that turns it into an agent. It includes the loop that keeps it going, the tools it can call, and the instructions loaded before your first message. It also holds the rules about what needs your permission, and the code that trims or summarizes the conversation when the context window fills. When two agents use the same model and behave very differently, the harness is usually why. The harness decides what the model sees and what it is allowed to do, which is most of what decides what it does.

The harness assembles the prompt the model reads at each step. It usually holds the harness's own standing instructions and your project instruction file, which this chapter covers later. It also holds a list of the tools available, the conversation so far, and the results of every tool the agent has used. Your request is a small part of it.

Look at what the model was handed

Sawyer thinking it over Think of the model as a skilled worker who sees only the pages the harness hands over. When an agent does something odd, ask what was on those pages before you blame the model, because that's the part you can change.

Agent Tool Use

The tools are how the model reaches the world. Agent tool use is the way an agent acts outside the model. The model writes a structured request to use a tool, such as "read this file" or "run this command." The harness carries it out, and the result goes back into the context for the model's next step. The model never touches your files directly. It asks, and the harness does it.

Common tools in a coding agent are:

  • Read a file and search the codebase for a word or pattern.
  • Edit a file or write a new one.
  • Run a shell command, a typed instruction to the computer like the ones you'd type in a terminal window, such as running the test suite, a database migration, or git commit.
  • Fetch a web page, such as a vendor's API documentation.
  • Start a subagent, covered later in this chapter.

Each tool is a power you are lending the agent. Reading a file can't hurt anything. Running a shell command can do anything you could do at your keyboard, including deleting files or pushing to production. The section on permissions comes back to this.

One Loop Through a Bug Fix

Here is what happens, step by step, when the builder of the dating-safety app types the stronger prompt from earlier: add a 10-second timeout to the image-search adapter and mark the check "not checked" when it fires.

  1. The harness builds the prompt: its own instructions, the project instruction file, the tool list and the builder's request. It sends this to the model.
  2. The model replies with a tool request: search the codebase for the image-search adapter. The harness runs the search and adds the result to the context.
  3. The model asks to read the adapter file. The harness reads it and adds its contents.
  4. The model asks to edit the file, adding the timeout and the "not checked" result. The harness checks whether edits need the builder's approval, asks if so, and applies the edit.
  5. The model asks to write a new test that simulates a hang. The harness writes it.
  6. The model asks to run the test suite. The harness checks permission, runs it, and adds the output. One test fails, because the new test expects the label "not checked" and the code returns "not_checked."
  7. The model reads the failure, asks to fix the label, and asks to run the tests again. They pass.
  8. The model writes a summary for the builder. The loop ends.

The loop took eight steps, and the model never touched a file. Every action went through the harness. Every tool result, from the file contents to the test output, went into the context window and stayed there. That is why this short fix might use 40,000 tokens of context by the end.

You can step through this loop yourself in the simulation below.

Diagram: Step Through the Agent Loop

Run the Step Through the Agent Loop MicroSim Fullscreen

Step Through the Agent Loop

Type: microsim sim-id: agent-loop-stepper
Library: p5.js
Status: Specified
Bloom Level: Understand
Bloom Verb: classify
Learning Objective: The learner will classify each of the ten actions in one agent bug-fix loop as done by the model, the harness or a tool, with at least eight of ten correct.

Prerequisites: large language model, AI coding agent, agent harness, agent tool use, context window, prompt (all defined in the sections above).

Evidence of Mastery: At each of ten steps, before the step is shown happening, the learner picks who does it: Model, Harness or Tool. A pick is correct when it matches the "Who" column in Content. Mastery is 8 of 10 correct on the first pass. Watching the context meter grow is exploration, not evidence.

Misconceptions: (1) The model reads and edits files directly. (2) The builder's request is most of what the model reads. (3) The model decides on its own whether an action needs permission.

Instructional Rationale: The model and the harness are easy to merge into one "AI" in the learner's mind. Asking the learner to name the actor before each step forces the separation, and the growing context meter shows why tool results, not the request, fill the window.

Content:

The task shown at the top throughout: "Add a 10-second timeout to the image-search adapter. When it fires, mark the photo check 'not checked'. Add a test."

Step Action shown to the learner Who Tokens added to context Context after step Why (feedback)
1 Builds the prompt from standing instructions, the project instruction file, the tool list and the builder's request Harness 12,000 12,000 The harness assembles everything the model reads. The request is about 40 of these tokens.
2 Decides the first move is to search the code for the image-search adapter, and writes a search request Model 100 12,100 Deciding what to do next is the model's job. It writes a request; it doesn't search.
3 Searches the codebase and returns two matching file names Tool 300 12,400 The search tool does the work and the harness puts the result in the context.
4 Reads the adapter file and returns its 300 lines Tool 2,800 15,200 File contents enter the context through a tool.
5 Writes the new timeout code and requests an edit Model 600 15,800 The model writes the change as a request.
6 Checks whether file edits need the builder's approval, asks, and applies the edit Harness 200 16,000 Permission rules live in the harness, not the model.
7 Runs the test suite and returns the output, with one failure: expected "not checked", got "not_checked" Tool 9,000 25,000 Test output is often the biggest thing in the context.
8 Reads the failure and writes a fix to the label Model 400 25,400 Reading results and choosing a fix is the model's work.
9 Runs the tests again and returns the output, all passing Tool 9,000 34,400 A second test run adds as much as the first.
10 Writes the summary for the builder Model 500 34,900 The final report is model text, and it is only as accurate as the model's reading of the context.

Provenance: The task and the 10-second timeout come from the section "Prompts" and Chapter 1's worked trade-off. The token counts are illustrative estimates using the rule of thumb in the section "Tokens" and must be labeled "illustrative token counts."

Rules: Each step has exactly one correct actor. Context after a step = context after the previous step + tokens added. The context meter's scale runs from 0 to 200,000 tokens, labeled "illustrative 200,000-token window."

Learner Activity:

  1. The learner sees the task and step 1's action text, with the actor hidden.
  2. The learner picks Model, Harness or Tool.
  3. The sim reveals the correct actor and the Why text, animates the action, and adds its tokens to the context meter.
  4. The learner presses Next. Steps run in the fixed order 1 to 10.
  5. After step 10, a summary shows the learner's score, the final context of 34,900 tokens, and the share of it that came from tool results (21,100 of 34,900, about 60 percent).

Feedback: Ten steps, fixed order, one pick each; picks can't be changed after reveal. Correct: "Right. " followed by the Why text. Incorrect: "This one is the [correct actor]. " followed by the Why text. A running count "Correct: n of 10" is shown. At the end, "Mastery reached" shows at 8 or more.

Starting State: The task card, an empty context meter at 0, and step 1's action text. The prompt reads "Who does this: the model, the harness or a tool?"

Chapter Anchors: The worked example in the chapter has eight steps and says the fix might use 40,000 tokens of context; the sim splits the same fix into ten finer steps ending at 34,900 tokens, under that figure. The timeout is 10 seconds. The failing test expected "not checked" and got "not_checked."

Tell your agent

"Show me the list of tools you can use in this project and which ones need my approval before you use them. Then, for the last task you did, list every tool call you made in order and what each one returned, in one line each."

Vibe Coding

Many apps start with a way of working that has its own name. Vibe coding is building software by describing what you want to an AI agent and accepting what it produces without reading the code. You judge the result only by whether the app seems to work. The computer scientist Andrej Karpathy gave it the name in February 2025, describing a way of working where you give in to the flow and forget that the code exists.

Vibe coding is a fine way to make a two-way door. A weekend prototype, a one-off script, or a first draft of a results page can all be vibe coded with little risk, and Chapter 1's set-based design gets cheaper because of it. It is the wrong way to build a must-be-right part. You can't tell by using the app whether sign-in checks every route, or whether a failed vendor call reads as "not checked." In both cases the broken version looks the same as the working one.

How Agents Fail

Agents fail in a few regular ways, and each one comes from the facts about models in the first section. Once you know the ways, you can spot them early.

Context Drift

The sitter forgot the back door because it was one instruction among forty minutes of others, given at the very start. Agents forget the same way. Context drift is the slow loss, over a long session, of instructions and facts given early on, either because they were summarized away when the context window filled or because newer material drew the model's attention. The agent doesn't announce that it has forgotten. It just starts acting as if the instruction was never given.

Here is how drift might look in the dating-safety app. Early in a long session, the builder types: "Remember, a check that didn't run is never counted as passed." The agent follows that rule for the image-search adapter in the first hour. Two hours and many files later, it adds a timeout to the people-search adapter and returns "passed" when the timeout fires. The rule was summarized away, and the agent wrote the most common pattern from its training instead. This is a hypothetical; it shows the mechanism, not a recorded event.

The defense is to keep the rules that matter out of the chat and in a place the harness loads every time, which is the project instruction file covered below. Short sessions help too. A fresh session for each task starts with a clean window and the instruction file at the top.

The simulation below shows the same rule surviving or fading depending on where it lives.

Diagram: Context Window Fill and Drift

Run the Context Window Fill and Drift MicroSim Fullscreen

Context Window Fill and Drift

Type: microsim sim-id: context-window-drift
Library: p5.js
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain why a rule typed early in a chat can drop out of an agent's context in a long session while the same rule in a project instruction file stays, by predicting at three checkpoints whether the agent can still see the rule.

Prerequisites: token, context window, compaction, context drift, project instruction file (all defined in the chapter prose before this block; project instruction file is introduced by name in the section "Context Drift" and defined fully later).

Evidence of Mastery: At three checkpoints the learner predicts "the agent can see the rule" or "the agent can't see the rule" before the sim reveals it. A prediction is correct when it matches the Checkpoints table. Then the learner picks the explanation that fits from four statements. Mastery is 3 of 3 predictions correct and the correct explanation chosen.

Misconceptions: (1) Anything said in the session stays available until the session ends. (2) A bigger window means drift can't happen. (3) The agent will say when it has forgotten something.

Instructional Rationale: Drift is invisible in a real session, because nothing announces it. Showing the window as a fill meter, with each turn as a block and the rule highlighted, makes the loss visible at the moment of compaction. Predicting first makes the learner commit to a model of the window before seeing it.

Content:

Session turns, in order:

Turn What happens Tokens added
0 Harness standing instructions loaded 10,000
0 Project instruction file loaded (1,500 tokens; contains the rule only when the setting below is "Instruction file") 1,500
1 Builder types the session's goals. When the setting is "Chat, turn 1", this message includes: "A check that didn't run is never counted as passed." 400
2 Agent reads six adapter files 30,000
3 Agent runs the test suite 12,000
4 Builder asks for a retry on the photo check 300
5 Agent edits the photo adapter and reads two more files 25,000
6 Agent runs the tests 15,000
7 Builder asks about the Stripe payment webhook 300
8 Agent reads the webhook code and Stripe's documentation 40,000
9 Agent runs the tests 20,000
10 Builder asks for a timeout on the people-search check 300
11 Agent reads the people-search adapter and its logs 45,000
12 Agent writes the timeout handling 18,000

Adjustable quantities:

Quantity Min Max Step Default Unit
Context window size 100,000 400,000 50,000 200,000 tokens
Where the rule lives — — — Chat, turn 1 choice: "Chat, turn 1" or "Instruction file"

Checkpoints, all at the default window of 200,000 tokens:

# Setting After turn Correct prediction Reason
1 Chat, turn 1 5 Can see the rule 79,200 tokens used; nothing has been summarized yet.
2 Chat, turn 1 12 Can't see the rule Turn 12 pushes the total to 217,800, past 200,000. Turns 1 to 6 are replaced by a summary that keeps goals, not rules.
3 Instruction file 12 Can see the rule The instruction file is never summarized away, so the rule stays.

Explanation choices (correct answer is B):

  • A. The agent decided the rule no longer applied.
  • B. When the window filled, the oldest turns were replaced by a short summary, and the rule typed in turn 1 was a detail the summary dropped. The instruction file is kept whole.
  • C. The people-search adapter is exempt from the rule.
  • D. The builder typed the rule too briefly.

Feedback for wrong choices: A: "The agent doesn't decide this. The harness trimmed the context, and the rule went with it." C: "The rule covers every check." D: "The wording was fine. Where it lived was the problem."

Provenance: The rule is the no-false-all-clear product rule from research/seed-notes.md and Chapter 1. The turn list, token counts, the 200,000-token default and the summary behavior are illustrative and must be labeled "illustrative session." Compaction behavior varies by agent.

Rules: Total = sum of tokens of every block currently in the window. Blocks are added in turn order. When adding a turn would make total > window size, compaction runs before the turn is added: the oldest chat turns (starting at turn 1; never turn 0 blocks) are removed one at a time, and a single 3,000-token summary block is added, until total + the new turn's tokens <= 70 percent of window size. If a summary block already exists, its 3,000 tokens are counted once and later compactions merge into it. The summary keeps each removed turn's one-line goal and drops any rule text. The rule is visible when the block holding it is in the window. At the default settings, compaction runs before turn 12: the total after turn 11 is 199,800, turn 12 would bring it to 217,800, and removing turns 1 to 6 (82,700 tokens) and adding the 3,000-token summary leaves 120,100 + 18,000 = 138,100, which is <= 140,000. At a window of 250,000 or more, no compaction happens in this session.

Learner Activity:

  1. The sim sets checkpoint 1's setting and plays turns 0 to 5, filling the meter block by block. The rule's block is highlighted.
  2. The learner predicts whether the agent can see the rule, then the sim reveals it.
  3. The sim continues to checkpoint 2, playing turns 6 to 12, and pauses before revealing. The learner predicts; the sim shows the compaction, with turns 1 to 6 folding into one summary block and the highlight disappearing.
  4. Checkpoint 3 replays the session with the rule in the instruction file. The learner predicts; the sim shows the highlighted block staying at the top through compaction.
  5. The learner picks one of the four explanations.
  6. Free exploration unlocks: the learner changes the window size and where the rule lives and replays the session. The learner should notice that a larger window delays compaction but the rule in chat is still only as safe as the session is short.

Feedback: Three predictions in fixed order, one attempt each, then one explanation question with one attempt. Correct prediction: "Right. " followed by the Reason text. Incorrect: "Not this time. " followed by the Reason text. Explanation feedback as listed in Content. Answers are revealed after each attempt. A count "Predictions correct: n of 3" is shown.

Starting State: An empty context meter labeled "illustrative 200,000-token window," the turn list, and the setting "Chat, turn 1." The prompt reads "The builder typed a rule in the first message. Will the agent still see it at the end of the session?"

Chapter Anchors: The hypothetical in the section "Context Drift": a rule typed early, followed in the first hour, lost two hours later on the people-search timeout. The chapter gives common context windows as about 200,000 tokens to a million.

Hallucination

The sitter never invented a pet, but a model can invent almost anything. A hallucination is output from a model that states something made up as if it were fact. It might be a function that doesn't exist, a setting a library never had, a field a vendor's API never returns, a file that isn't in the project, or a source that was never written. It happens because the model produces what is likely, not what it has checked. A plausible name for a function is very likely text. Whether that function exists is a separate question the model doesn't ask unless a tool makes it.

In code, hallucinations show up in a few familiar places:

  • Invented library functions. The agent calls searchImages({ timeoutMs: 10000 }) on a vendor's client library that has no such option. The option is ignored and the hang continues.
  • Invented API fields. The agent reads response.data.matches from a vendor whose responses put results under results. The code reads an empty value and reports no matches. In the dating-safety app, this is the same failure as a vendor error read as "no results," which Chapter 9 treats in detail.
  • Invented packages. The agent adds a package name that sounds right but doesn't exist, or worse, one that someone has registered under that name to catch exactly this mistake. Chapter 16 covers that risk.

Agents catch more of their own hallucinations than chat assistants do, because the loop gives them a way to find out. An invented function fails when the tests run, and the agent can read the error and fix it. The hallucinations that get through are the ones no test exercises, like an invented field that produces an empty but valid-looking result.

The invention no test catches

Sawyer pointing out a pitfall Watch out for an invented field or option that quietly returns nothing, because no test fails and the agent never finds out. The first time an agent uses a vendor's field or option, ask it to show you where the vendor's documentation names it.

Confident Wrong Answers

When the mother asked about the plants, the sitter said "yes, all of them" with complete confidence, and she was wrong. A confident wrong answer is a model's incorrect claim stated with the same certainty and fluency as a correct one, with nothing in the wording that warns you. A hallucination is one kind. The more common kind is a wrong claim about code or work that exists. "All tests pass" when the tests weren't run. "This route checks sign-in" when it checks only in the browser. "Every adapter handles errors" when about two dozen catch blocks swallow errors without a word.

That last example comes from the dating-safety app, which had about 24 bare catch blocks, places where the code caught an error and did nothing with it. Ask an agent "Does this code handle errors?" and it may well say yes, because each of those blocks does catch an error. The claim is technically about real code and it is wrong in the way that matters. This is the most dangerous failure in this section, because it arrives looking exactly like a right answer.

The fix is to ask for evidence instead of conclusions. "Do the tests pass?" invites a yes. "Run the tests and paste the last twenty lines of output" can't be answered with a yes.

Scope Creep in a Diff

The pantry got reorganized because the sitter saw something she could improve. Agents do the same. Ask for a timeout on one adapter and the diff, the list of changed lines, may also rename variables in three other files, update a package, reformat a config file and "clean up" a function nearby. Each change might be fine. Together they make the diff too big to review, and a bad change can hide among the harmless ones. Chapter 5 shows how to read a diff. The habit that matters here is to name the edge of a change in the prompt, such as "change only the image-search adapter and its test." When the diff touches more, ask why.

The simulation below lets you practice telling these failures apart.

Diagram: Spot the Agent Failure

Run the Spot the Agent Failure MicroSim Fullscreen

Spot the Agent Failure

Type: microsim sim-id: spot-the-agent-failure
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: differentiate
Learning Objective: The learner will differentiate context drift, hallucination, confident wrong answers, scope creep and sound agent work in ten short agent reports from the dating-safety app, with at least eight of ten correct.

Prerequisites: context drift, hallucination, confident wrong answer, scope creep in a diff (all defined in the section "How Agents Fail").

Evidence of Mastery: For each of ten report cards, the learner picks one label: Context drift, Hallucination, Confident wrong answer, Scope creep, or Sound. A pick is correct when it matches the Label column in Content. Mastery is 8 of 10 correct on the first attempt. Opening the "What the builder asked" hint is exploration, not evidence.

Misconceptions: (1) A report that sounds sure is probably right. (2) A large diff means the agent worked hard. (3) Every agent mistake is a hallucination.

Instructional Rationale: The four failures look alike on the surface: each is an agent report that reads well. Differentiating them requires the learner to compare what was asked, what was said and what was done, which is the Analyze skill the chapter's habits depend on.

Content:

Each card shows what the builder asked, the agent's report, and one fact the builder found on checking.

# Builder asked Agent reported What the builder found Label Why (feedback)
1 Add a timeout to the people-search check "Done. On timeout the check returns passed so the scan can finish." Two hours earlier in the session the builder had said a check that didn't run is never counted as passed Context drift The rule was given early and lost; the agent fell back on a common pattern.
2 Add a timeout to the image-search call "Added timeoutMs: 10000 to the search call." The vendor's client library has no timeoutMs option, and the call still hangs Hallucination The option was invented. It looks plausible, and it does nothing.
3 Check that the payment webhook is tested "Yes, the webhook is fully tested." No test file mentions the webhook Confident wrong answer A false claim about real code, stated with full certainty.
4 Fix a typo on the results page "Fixed the typo. Also renamed the scoring helpers, updated three packages and reformatted the server config for consistency." The diff touches 14 files Scope creep The request was one word on one page. The rest is unrequested change.
5 Add a test for the no-locate rule "Added a test that runs a scan with a people-search result containing an address and checks that no address appears in the report. Ran it: 1 passed. Output pasted below." The test exists, and the pasted output matches a fresh run Sound The agent did what was asked and showed evidence.
6 Read the image-search vendor's results "Results are in response.data.matches." The vendor's documentation puts results under results; the code reads an empty value Hallucination The field name was made up.
7 Does every adapter handle errors? "Yes, every adapter wraps its call in a try/catch." Many of those catch blocks are empty and swallow the error Confident wrong answer Each block catches an error, so the claim sounds true, but the errors are dropped.
8 Add a retry to the SMS adapter "Added a retry. I also switched the app from Express to a different server framework, since it's faster." The whole server was rewritten Scope creep Replacing the server framework is far outside a retry.
9 Run the tests after the change "All tests pass." The session log shows the tests were never run after the last edit Confident wrong answer A claim of a result that never happened.
10 Late in a long session, add a new check; at the start, the builder had said "every new check starts switched off until I turn it on" "Added the new check. It runs on every scan." The check is switched on for every member Context drift An early instruction was lost as the session grew.

Provenance: Cards 1, 3, 7 and 10 draw on the dating-safety app's facts in research/seed-notes.md (no false all-clear; payment webhook untested; about 24 bare catch blocks). Card 1's scenario is the hypothetical from the section "Context Drift," and cards 2 and 6 use the hypothetical examples from the section "Hallucination"; all three are tagged "Hypothetical example from the chapter." Cards 4, 5, 8, 9 and 10's switched-off detail are illustrative and must be labeled "illustrative."

Rules: Each card has exactly one correct label. Use these tie-breaks: if the agent invented a name, option, field, file or package, the label is Hallucination even if it was stated confidently. If the agent ignored an instruction given earlier in the session, the label is Context drift. If the agent made a false claim about real code or about work done, the label is Confident wrong answer. If the agent changed more than was asked, the label is Scope creep. If none applies, the label is Sound. Five labels: Context drift (cards 1, 10), Hallucination (cards 2, 6), Confident wrong answer (cards 3, 7, 9), Scope creep (cards 4, 8), Sound (card 5).

Learner Activity:

  1. The learner sees card 1: the request, the agent's report and the finding.
  2. The learner picks one of the five labels and presses Check.
  3. The sim shows whether the pick is correct and the Why text.
  4. The learner moves to the next card. Cards come in the fixed order 1 to 10.
  5. After card 10, a summary shows the score and the five labels with their one-line definitions from the chapter.

Feedback: Ten cards, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "This one is [correct label]. " followed by the Why text. If the learner labels card 5 as anything but Sound, add: "Not every report is a failure. Evidence you can check is what makes this one sound." A running count "Correct: n of 10" is shown, with "Mastery reached" at 8 or more.

Starting State: Card 1 and five label buttons. The prompt reads "What went wrong here, if anything?"

Chapter Anchors: The dating-safety app had about 24 bare catch blocks. The chapter's hallucination examples are searchImages({ timeoutMs: 10000 }) and response.data.matches against a vendor that uses results.

Tell your agent

"Don't tell me the tests pass. Run them and paste the last twenty lines of output. Then list every file your last change touched, with one line saying why each one needed to change. Flag any change I didn't ask for."

Telling an Agent What You Want

The family's second trip went better because of a note on the fridge. Agents have the same thing, and it is the single cheapest habit in this book.

Agent Instructions

Agent instructions are any standing guidance given to an agent about how to work: the rules, conventions, product limits and habits it should follow on every task, as opposed to the one task in front of it. "Use TypeScript." "Run the tests before you say a task is done." "A check that didn't run is never counted as passed." "Never return an address, workplace or location." Instructions can be typed into a chat, but chat is the place they are most likely to drift away. They hold best in a file.

Good instructions are short, specific and checkable. "Write clean code" gives the model nothing to act on. "Every adapter must turn a failed call into a 'not checked' result, never a pass" gives it a rule and a way to tell whether it was followed. Put the rules where a mistake hurts most at the top, the same way the family put the cat rule at the top of the note.

The Project Instruction File

A project instruction file is a plain text file kept in the project's folder that the agent's harness reads at the start of every session, so its contents are in the context window before you type anything. It holds the agent instructions for that project: what the app is, how to run and test it, the conventions to follow, and the rules that must never break. Because the harness loads it fresh each session and keeps it whole, it doesn't drift the way a chat message does. And because it lives in the project, it goes into version control with the code, so it has a history and can be reviewed like any other change.

Two names for this file are common in 2026. CLAUDE.md is the project instruction file read by Claude Code, Anthropic's coding agent. It sits in the project's root folder. Claude Code also reads a personal one kept in a .claude folder inside the builder's home folder, and any it finds in the subfolders it works in. AGENTS.md is a project instruction file with an open, shared name that many coding agents read, including OpenAI's Codex, Cursor and others, so that one file can guide whichever agent a team uses. Claude Code reads AGENTS.md too when a project has no CLAUDE.md. The content of the two is the same kind of thing. Some projects keep one and point the other at it, so there is only one copy of the rules to keep true.

An Instruction File for the Dating-Safety App

Here is what a short project instruction file for the dating-safety app might look like. It is written in Markdown, a plain text format where # starts a heading and - starts a list item. Read the sections from the top: what the app is, how to check work, the product rules, the conventions, and what needs the builder's approval.

# Dating-safety app

Members upload photos, voice clips and text about an online match.
The server runs about eight checks in parallel and returns a trust
score from 0 to 100.

## How to check your work
- Run `npm test` before saying any task is done. Paste the result.
- Run `npm run typecheck` after any change to server code.

## Product rules (never break these)
- Every check has three results: pass, fail, not checked.
  A check that didn't run is NEVER counted as a pass.
  If no check ran, the score is 50.
- Never return an address, workplace or location for anyone.
- Never name a person from an AI guess. The model proposes;
  the code verifies against an evidence URL.
- A member can reach only their own scans. Check on the server.

## Conventions
- Each outside service has one adapter file. Adapters throw on
  failure; they never return an empty result for an error.
- Model prices live in one table. Don't copy them elsewhere.

## Ask before you
- Run or write a database migration.
- Add, remove or upgrade a package.
- Change more than the files the task names.

Notice what the file leaves out. It doesn't explain React or teach the agent to code. It holds what a capable newcomer to this project couldn't guess: the product rules, the habits that catch mistakes, and the doors that are one-way. Most of its rules point at a must-be-right part from Chapter 1. Chapter 17 shows how to turn rules like these into checks that fail the build, which holds them better than any file of words.

Agent Memory

The model remembers nothing between sessions, so anything an agent seems to remember is stored somewhere outside it. Agent memory is information an agent keeps across sessions by writing it to files or a store that the harness loads back later. It includes the project instruction file, notes the agent writes about decisions and lessons, and in some agents a built-in memory feature. Memory is how a lesson learned on Tuesday reaches the session on Friday.

Memory is only as good as what goes into it and whether it stays true. A note that says "the scheduler is fixed" stays in memory after someone breaks it again. Treat memory files like any other document in the project. Keep them short, put them in version control, and fix them when the code changes. Chapter 15 covers keeping documentation true.

Tell your agent

"Create a project instruction file for this app, called CLAUDE.md (or AGENTS.md if you're not Claude Code). Include what the app does in two sentences, the commands to run tests and type checks, every product rule that must never break, and a list of actions you must ask me about first. Keep it under one page. Show it to me before you save it."

Plan Before Code

The family's second change was a text each morning with the day's plan. A plan costs the sitter two minutes and lets the family catch a bad idea before it happens.

Plan before code is the habit of having the agent write out what it intends to do, which files it will change, what could go wrong and how it will check the result, and getting your approval, before it changes any code. Many agents have a planning mode built in, where the agent can read the code but can't edit it. Without one, a prompt that ends "Don't change anything yet; show me your plan" does the same job.

A plan helps in three ways. It catches a misunderstanding while it costs a paragraph instead of a diff. It names the edge of the change, which keeps scope creep out. And it gives you something to check the finished work against.

Planning a Ninth Check

Say the builder wants to add a ninth check to the dating-safety app that looks up whether a match's phone number is a disposable one. Here is a plan an agent might return, and what the builder should look for in it.

  1. Add a new adapter for the phone-lookup vendor, following the pattern of the existing adapters.
  2. Add the check to the list of checks that run in parallel.
  3. Map the vendor's answers to pass, fail and not checked. A vendor error or timeout maps to not checked.
  4. Update the score calculation to include the ninth check.
  5. Add tests: a disposable number fails, a normal number passes, a vendor error gives not checked, and a scan with every vendor down still scores 50.
  6. Files to change: the new adapter, the list of checks, the score calculation, and three test files.
  7. Needs your approval: adding the vendor's package, and storing a new API key.

Reading this plan, the builder can see that step 3 respects the no-false-all-clear rule, and step 5 has a test for it. Step 4 is the line to question. Changing how the score is calculated is a two-way door for future scans and a one-way door for members who already acted on an old score, as Chapter 1's table showed. The builder can ask the agent to show how the scores of a few known scans would change before approving. That one question, asked at the plan stage, costs a minute.

Small Steps

Chapter 1's Hora built her watches in small units that held together when the phone rang. The same habit applies to agents. Once the plan is approved, have the agent do one step, run the tests, and commit before starting the next. A small step keeps each diff small enough to read. It keeps each session short, which means less drift and lower token cost. And it means that when something goes wrong, you lose one step and not the afternoon. Chapter 5 shows how commits make each step a save point.

Tell your agent

"Before writing any code for this feature, write a numbered plan: each step, the files it touches, what could go wrong, and the test that will prove it works. Mark any step that is a one-way door. Wait for my approval. Then do one step at a time, run the tests and commit after each one."

Permissions, Subagents and Model Choice

Three settings change how much the agent can do, how much it can hold, and how much it costs.

Agent Permissions

The family locked the office. Agent permissions are the rules in the harness that decide which actions the agent may take on its own, which need your approval each time, and which it may never take. Most agents let you allow reading and searching freely, ask before editing files or running commands, and block certain commands altogether. Some let you allow a specific command, such as running the tests, without asking each time.

Set permissions by the door each action opens. Reading code is a two-way door, so let it run. Running the tests is safe and frequent, so allow it. Database migrations, deleting files, pushing to the main branch, and anything that touches production are one-way doors, so keep them behind a question. An agent that asks permission for everything trains you to click "yes" without reading, which is no protection at all.

Subagents

A subagent is a separate agent, started by the main agent to do one task, that works in its own fresh context window and returns only a short report to the main agent. Say the main agent needs to search fifty files to find every place a vendor is called. A subagent can do the reading, and only its one-page answer lands in the main agent's context. That keeps the main window clear for the task at hand. Subagents are useful for searching, reviewing a diff with fresh eyes, and doing several independent pieces of work at once. Their reports can contain confident wrong answers like any other agent output, so treat them the same way.

Model Selection

Most agents let you choose which model they run. Model selection is the choice of which large language model to use for a task, trading capability against speed and token cost. A larger model reasons better through a tricky bug or a plan with many parts, and costs more and runs slower. A smaller model is quicker and cheaper and is fine for routine edits, renaming, or summarizing logs. A reasonable default is a capable model for planning and must-be-right parts, and a cheaper one for routine work. Model selection is a two-way door: try a model on a task, see how it does, and change it next time.

Tell your agent

"Show me your current permission settings. Then propose changes so that reading files and running the test suite don't need my approval, editing files and running other commands do, and database migrations, deleting files, and pushing to the main branch always need my approval. Show me the exact change to the settings file and wait for my OK before you save it."

Trusting What the Agent Tells You

Every failure in this chapter ends at the same question: when the agent says it's done, how much should you believe it?

Trust in agent output is the amount of checking you give an agent's code or claims before you rely on them, set by how much harm a mistake would do and how easily you could catch it. It isn't a fixed amount. You can take the agent's word on the color of a button, because you'll see the button. You can't take its word that every route checks sign-in, because a route that skips the check looks the same as one that doesn't.

Chapter 1 described Gary Klein's finding that skilled intuition forms only where feedback is fast and clear. Trust in an agent works the same way. Where you see the agent's work right away, you learn how far to trust it. Where the feedback is slow or hidden, trust is a guess, however confident the agent sounds. A builder who has watched the agent's work on the results page for a month has earned a sense of how good it is at layout. That same month teaches nothing about whether its error handling is sound, because error-handling mistakes don't show on the page.

The table below sorts some common agent claims by how to check them.

Agent claim How you'd notice if it were wrong How much to check
"I changed the score's color to green" You see it on the page Look at the page
"I renamed the button to Start scan" You see it Look at the page
"All tests pass" Not unless you run them Ask for the pasted output, or have tests run on every change (Chapter 10)
"The timeout marks the check not checked" Not until a vendor hangs Ask for the test that proves it, and read the test's name and its assert line
"Every route checks the member is signed in" Not until someone tries to get in Ask for a test that calls each route signed out (Chapter 7)
"No secrets are in the code" Not until a key leaks Run a secret scanner (Chapter 6)

The claims you can check by looking are about good-enough-for-now parts. The claims you can't see are about must-be-right parts, because a must-be-right part is often one whose failure doesn't show. So turn every claim in the bottom half of the table into a test or a check that runs on its own. Then the feedback becomes fast, and you can learn how far to trust the agent there too.

Judgment as the Constraint

Chapter 1 used Goldratt's theory of constraints to show that once AI made writing code cheap, the slow step moved to judging what got written. Judgment as the constraint is the idea that, when an agent can produce code faster than a person can check it, the builder's judgment becomes the step that limits how fast good software ships. That judgment covers what to build and whether the result is safe. An agent that writes a feature in ten minutes doesn't help if the builder can't tell for a week whether the feature is safe. The instruction file, the plan and the tests that replace claims all make that judgment faster.

Tell your agent

"For each product rule in our instruction file, find the test that proves the code follows it. Make a table with the rule, the test's name, and whether the test exists and passes. Show me the table and stop. When I say go, write the missing tests one rule at a time, run each one, and show me the output."

Back to the House-Sitter

The family's second trip went well with the same sitter. The rules were on the fridge, where she saw them every morning. Each day began with a plan the family could correct by text. The office was locked. And when they asked about the plants, they asked for a photo.

An agent won't stop forgetting, guessing or tidying the pantry because you ask it to try harder. You can change what it reads, what it may do, how big each step is, and what evidence you ask for. The next chapter adds the piece the family didn't have: a way to put everything back as it was when a change goes wrong.

You can manage the sitter now

Sawyer celebrating You can now name the four ways an agent goes wrong: drift, invention, confident wrong answers and scope creep. You also have the habit that catches each one, which is rules in a file, a plan before code, and evidence instead of claims. Good enough for now, and you know why.

Key Takeaways

  • Put the rules that must not break in a project instruction file, not in the chat, so context drift can't take them.
  • Ask for a plan before code, then work in small steps with fresh sessions.
  • Set agent permissions by the door each action opens: let reads run, keep migrations, deletes and pushes behind a question.
  • Ask for evidence, not conclusions. Turn claims you can't see into tests, so trust in agent output follows fast feedback.
  • Put limits on tokens, steps and time on every model call in your app.

See Annotated References