Sub topic 2
Why Prompts Alone Drift
This chapter assumes you have written code professionally in at least one language, use Git, have prompted an AI coding assistant before, and know what an automated test is. It explains why open-ended prompts give inconsistent results from coding agents. It also shows which parts of that inconsistency a written spec removes.
What "drift" means
Drift is the gap between what you wanted and what the agent built. The gap grows as a session gets longer, as the project gets bigger, or as you repeat a request on different days. Three kinds of drift show up in practice:
- Interpretation drift. The agent reads an ambiguous request one way, and you meant another. Two runs of the same prompt may produce two different readings.
- Session drift. Decisions made early in a conversation get forgotten, contradicted, or quietly reversed later.
- Code-versus-intent drift. The code changes over many prompts, and nobody can say what the system is supposed to do any more.
The rest of the chapter explains the mechanisms behind each kind. Later chapters show how a spec addresses them.
Why a prompt underspecifies the task
A prompt is a short description of a long chain of decisions. Take this request:
Add password reset by email to the app.The sentence leaves many questions open:
- How long should the reset link stay valid?
- Should the link work more than once?
- What should the page show when the email is not registered?
- Where are tokens stored, and are they hashed?
- Which tests should exist when the work is done?
A human colleague would ask some of these questions, and would answer others from knowledge of your team. An agent usually does neither. It fills each gap with a plausible default taken from its training data and from whatever files it happened to read. Each default is reasonable on its own. Together they may not match your product.
Some defaults carry security consequences. If the agent returns "no account with that email" for an unregistered address, it leaks which emails have accounts. The prompt never asked for that behavior. It also never forbade it.
How the agent's view of the project is limited
A coding agent works inside a context window. That is the fixed amount of text the model can consider at one time. The window holds your messages, the agent's earlier replies, tool output, and the file contents it has read. Several effects follow from this limit.
The agent sees a slice of the codebase
The agent does not read your whole repository. It searches, opens a few files, and works from what it found. If a convention lives in a file it never opened, the agent cannot follow it. For example, your team may wrap all database access in a repository layer. An agent that never opened that layer may write raw queries inside a route handler.
Long sessions push out early content
As a conversation grows, the tool must shorten it. Tools do this by dropping old turns or by replacing them with a summary. A summary keeps the gist and loses details. A constraint such as "never log email addresses" may disappear when the early turns are summarized. Even before anything is dropped, models often pay less attention to text in the middle of a long context than to text at the start or end. Do not rely on a rule you stated once, forty messages ago.
Each session starts fresh
A new session does not remember the last one. If the agent made a design choice on Monday, it has no memory of that choice on Tuesday unless the choice is written into a file the agent reads. Without such a file, you must restate the decision each time, and you will forget some of them.
Sampling makes repeat runs differ
Language models generate text by sampling from a probability distribution. Even with the same prompt and the same files, two runs may differ in structure, naming, and edge-case handling. Lowering the sampling temperature reduces this variation but does not remove it. Agent loops add a second source of variation: an early tool call that returns different output, or a different file opened first, changes everything that follows.
This matters most for the parts of the task the prompt left open. A tightly specified behavior, such as "the link expires after 30 minutes", tends to come out the same across runs. An unspecified behavior varies, and it varies silently.
How drift accumulates across a series of prompts
Most real work is a series of prompts, not one. The following sequence is typical.
- You ask for password reset. The agent builds it with a default 24-hour token lifetime.
- You notice the lifetime is too long and say "make the token expire sooner."
- The agent picks 15 minutes in the token module. Elsewhere, the email template still says "valid for 24 hours."
- You ask for tests. The agent writes tests that match the code as it now stands, including the 15-minute value and the inconsistent text.
- A teammate asks a different agent session to add a resend feature. It reads the template and implements a 24-hour window.
At no step did anyone make an obviously wrong decision. The failure came from there being no single place that records what the system should do. Each prompt was interpreted against the current code, and the current code was already off.
Step 4 deserves attention. Tests written after the code, by the same agent, tend to confirm what the code does instead of what it should do. They pass, and they give false confidence. This is a recurring weakness of the prompt-then-test pattern.
The loop at the bottom is the important part. Each pass reads the previous pass's output as if it were the truth, so errors feed back into later work.
What a spec changes
A spec is a written statement of intended behavior that lives in the repository and that the agent reads before it acts. It changes the situation in four ways.
| Source of drift | Prompt only | With a spec |
|---|---|---|
| Ambiguous request | Agent picks a default | Behavior is stated, so there is less to guess |
| Forgotten decision | Lost when the context shrinks | Stored in a file the agent can reread |
| New session | Starts with no memory | Starts by reading the same spec |
| Tests mirror the code | Tests confirm whatever was built | Tests derive from stated criteria |
| Disagreement | Found late, in code review or production | Found early, in the spec review |
Two points in this table are easy to miss.
First, the spec does not make the model deterministic. The agent can still produce different code on different runs. What the spec fixes is the target, and it gives you a way to check a run against that target.
Second, the spec moves the cost of disagreement earlier. Reading a half-page requirement and saying "no, links should be single-use" takes a minute. Finding the same problem in a 600-line diff takes much longer, and the agent may already have built further work on top of it.
A before-and-after example
Here is the earlier prompt, rewritten as a short requirement. It uses the WHEN/IF ... THEN ... SHALL phrasing that a later chapter covers in detail.
### Requirement 1: Password reset
**User story:** As a registered user, I want to reset my password by email, so that I can regain access to my account.
#### Acceptance criteria
1. WHEN a user submits a registered email address THEN the system SHALL send a reset link that expires after 30 minutes.
2. WHEN a user submits an unregistered email address THEN the system SHALL return the same response as for a registered address.
3. IF a reset link has already been used THEN the system SHALL reject any further use of that link.Compare it with the one-line prompt. Each open question from earlier now has an answer:
- The link lifetime is 30 minutes (criterion 1).
- The link works once (criterion 3).
- The response does not reveal whether an email is registered (criterion 2).
Each criterion also describes something a test can check. That property lets you turn the criteria into tests before the agent writes any code, so the tests express the intent and not the implementation. Here is a small example of what such tests can look like.
from datetime import datetime, timedelta, timezone
import pytest
TOKEN_TTL = timedelta(minutes=30)
class TokenError(Exception):
pass
class ResetTokens:
def __init__(self):
self._issued = {}
self._used = set()
def issue(self, token, now):
self._issued[token] = now
def redeem(self, token, now):
if token in self._used:
raise TokenError("already used")
issued = self._issued.get(token)
if issued is None or now - issued > TOKEN_TTL:
raise TokenError("expired or unknown")
self._used.add(token)
T0 = datetime(2026, 1, 1, tzinfo=timezone.utc)
def test_token_expires_after_30_minutes():
tokens = ResetTokens()
tokens.issue("abc", T0)
tokens.redeem("abc", T0 + timedelta(minutes=29)) # still valid
tokens.issue("def", T0)
with pytest.raises(TokenError):
tokens.redeem("def", T0 + timedelta(minutes=31))
def test_token_can_be_used_only_once():
tokens = ResetTokens()
tokens.issue("abc", T0)
tokens.redeem("abc", T0)
with pytest.raises(TokenError):
tokens.redeem("abc", T0)Run it with pytest. In the earlier drift story, step 3 would now fail: a 15-minute or 24-hour lifetime breaks the 29-minute and 31-minute checks in the first test. The disagreement shows up as a failing test, not as a surprise in production.
Limits of this argument
A spec is not free, and it does not solve every problem.
- A spec can be wrong. If the requirement is wrong, the agent builds the wrong thing faithfully. The review gates in a later chapter exist for this reason.
- A spec can be too heavy. Writing three documents for a one-line bug fix costs more than it saves. The right-sizing chapter covers this.
- A spec can go stale. If the code changes and the spec does not, you have recreated the drift problem in a new place. The spec-drift chapter covers how to prevent that.
Prompts are still useful. Exploration, throwaway scripts, and small changes inside well-understood code are fine to prompt directly. The case for specs is strongest when the work spans several sessions, touches security or data, or is done by more than one person or agent.
Check yourself
Exercise
An agent session adds a feature on Monday and chooses to store timestamps in UTC. On Wednesday, a new session adds a related feature and stores local time. Name the mechanism that caused this, and name one way to prevent it.
Show answer
The Wednesday session started with no memory of Monday's decision, and the decision was not written anywhere the agent reads. The prevention is to record the decision in a file the agent reads at the start of every session, such as a spec's design section or a project instruction file, for example "Store all timestamps in UTC."
Exercise
A teammate says, "We don't need a spec. After the agent writes the code, I ask it to write tests, and they all pass." Give two reasons this does not show the code is correct.
Show answer
First, tests written from the code, by the same agent, tend to describe what the code does and not what it should do, so a misreading of the requirement is built into both. Second, the tests encode whatever defaults the agent chose for the points the prompt left open, so they pass regardless of whether those defaults match your intent. Tests derived from written acceptance criteria avoid both problems.
Exercise
Rewrite the prompt "Add rate limiting to the login endpoint" as two acceptance criteria in WHEN/IF ... THEN ... SHALL form. Pick concrete numbers.
Show answer
Example answer: 1. WHEN a client makes more than 5 failed login attempts from one IP address within 10 minutes THEN the system SHALL reject further login attempts from that address with HTTP 429 until the 10-minute window ends. 2. WHEN a client is rejected for rate limiting THEN the system SHALL include a Retry-After header stating the seconds remaining. Any numbers are acceptable if each criterion describes one observable behavior that a test can check.