Sub topic 10
Keeping the Spec and the Code in Sync
This chapter assumes you have written requirements, a design, and a task list for a feature. It also assumes you can run pytest and use Git. Earlier chapters covered how to write those documents and check agent output against them. This chapter covers what happens afterward, when the code and the spec begin to disagree.
What spec drift is
Spec drift is any state where the spec says one thing and the code does another. A spec that has drifted is worse than no spec. The next agent session reads it as ground truth and builds on a description that is no longer accurate.
Drift is not always a mistake in the code. Sometimes the code is right and the spec is stale. Sometimes the spec is right and the code is wrong. Sometimes both are wrong in different ways. Keeping them in sync means finding the difference and deciding which side to change.
How drift happens
Drift has a few common sources. Knowing them tells you where to put checks.
| Source | Example | Typical symptom |
|---|---|---|
| Agent improvises | The agent adds rate limiting to the reset endpoint because it seemed sensible | Code behavior with no matching criterion |
| Agent skips | The agent implements criteria 1.1 and 1.3 and quietly leaves out 1.2 | A criterion with no code or test |
| Discovery during implementation | The team finds that the mail provider cannot guarantee delivery within 30 minutes | The spec says "30 minutes" and the code uses 60 |
| Hotfix outside the workflow | Someone patches production directly and never touches `specs/` | Spec describes behavior that no longer exists |
| Spec edited without code | A product owner changes a requirement in a review comment | Tests still assert the old behavior |
The first two are agent-driven. The last three are process-driven, and they are usually the more damaging ones, because no tool flags them.
Detecting drift with traceability
You cannot review your way out of drift on a large spec. You need a mechanical check. The cheapest one is traceability: every acceptance criterion should be referenced by at least one test, and every reference in a test should point to a criterion that still exists.
The convention is a comment above each test, such as # covers: 1.1. The script below reads the requirements text, reads the test source, and compares the two sets of IDs. The requirements and test source are embedded as strings so the script runs as written. In a real project you would read them from specs/ and tests/.
import re
REQUIREMENTS = """\
### Requirement 1: Password reset
#### 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.
"""
TEST_SOURCE = """\
# covers: 1.1
def test_token_expires_after_30_minutes(): ...
# covers: 1.3, 1.4
def test_token_can_be_used_only_once(): ...
"""
def criteria_ids(text):
"""Return IDs like '1.2' for each WHEN/IF criterion under a requirement."""
ids = set()
requirement = None
for line in text.splitlines():
heading = re.match(r"###\s+Requirement (\d+):", line)
if heading:
requirement = heading.group(1)
continue
item = re.match(r"(\d+)\.\s+(WHEN|IF)\s", line)
if item and requirement:
ids.add(f"{requirement}.{item.group(1)}")
return ids
def covered_ids(text):
"""Return IDs named in '# covers: ...' comments."""
ids = set()
for line in text.splitlines():
marker = re.search(r"#\s*covers:\s*(.*)", line, re.IGNORECASE)
if marker:
ids |= set(re.findall(r"\d+\.\d+", marker.group(1)))
return ids
def check(requirements, tests):
spec = criteria_ids(requirements)
covered = covered_ids(tests)
return sorted(spec - covered), sorted(covered - spec)
if __name__ == "__main__":
uncovered, unknown = check(REQUIREMENTS, TEST_SOURCE)
print("Uncovered criteria:", uncovered)
print("Unknown references:", unknown)
raise SystemExit(1 if uncovered or unknown else 0)Running it prints Uncovered criteria: ['1.2'] and Unknown references: ['1.4'], then exits with status 1. Criterion 1.2 has no test, which is the "agent skips" case. The reference to 1.4 points at a criterion that does not exist, which usually means someone deleted or renumbered a criterion and left a stale test behind.
Run this in continuous integration so a failing check blocks the merge. The same script can be given to the agent as a verification step in your project instruction file, alongside pytest.
What traceability does not catch
The check proves a test claims to cover a criterion. It does not prove the test is any good. A test marked # covers: 1.2 that asserts nothing passes the check. Two limits follow from this:
- A reviewer still has to read the tests for the criteria that matter most.
- Behavior with no criterion is invisible to this script. An agent that adds an undocumented feature, with no
coverscomment, passes cleanly.
For the second gap, look at the diff itself. Each changed file should trace to a task in tasks.md. A change that traces to no task is the signal to look closer.
Deciding which side is wrong
When a check fails or a reviewer notices a mismatch, resist the reflex to make the failure go away by editing whichever file is closest. First decide what the truth should be.
The order in the right-hand branch matters. Change the spec first, review it, then change tests, then change code. If you change code first and patch the spec afterward, you lose the review gate on the decision itself. The spec edit becomes a description of what already happened.
A worked example
Suppose the team learns during implementation that the mail provider's delivery delays make a 30-minute expiry too strict. The agent, working on task 2, sets the expiry to 60 minutes and the tests fail, since they assert 30.
The wrong fix is to edit the test constant to 60 and move on. Criterion 1.1 still says 30, and nobody decided anything. The right sequence is:
- Stop the task and tell the agent the requirement is being changed. Do not let it edit the requirement on its own.
- Edit criterion 1.1 to say 60 minutes, and record the reason in the spec.
- Have a human review that one-line spec change in its own commit.
- Update the test that asserts 30 minutes, then the code.
- Rerun the tests and the traceability check.
Step 1 matters because of the rule from the sample AGENTS.md: the agent must not change requirements. If one looks wrong, it says so and asks. Without that rule, an agent that hits a failing test has an easy path. It edits the requirement or the test until everything is green.
Recording why the spec changed
A spec edit with no reason attached is hard to audit later. Add a short change note near the affected requirement, or use the commit message. Either way, keep the note specific:
#### Change log
- 2026-03-12: Criterion 1.1 expiry changed from 30 to 60 minutes. Mail provider
delivery can lag by 20 minutes at peak. Decided by: security review.Because specs live in the repository, Git already gives you history and blame. The value of a written note is that the reason survives. A diff shows that 30 became 60, but not why.
Put spec changes and the code that implements them in the same pull request, with the spec change in its own commit. Reviewers can then read the intent first and the implementation second. If the spec change is controversial, they can reject it without untangling it from the code.
Drift between the agent's context and the files
There is a second, quieter kind of drift. A long agent session holds a copy of the spec in its context. If you edit requirements.md partway through, the agent may keep acting on the old text it read earlier.
Three habits reduce this:
- Start a fresh session, or explicitly tell the agent to re-read the spec files, after any spec edit.
- Keep tasks small enough that a session covers one or two of them.
- Tell the agent to quote the criterion it is satisfying. If the quote does not match the current file, the context is stale.
Edge cases
Renumbering. Inserting a criterion in the middle of a list shifts every later ID, and every covers comment and task reference after it becomes wrong. Prefer appending new criteria, or use stable IDs that never change, such as REQ-1-RESET-LINK. The traceability script above will flag stale references after a renumbering, which is a good reason to keep it running.
Deleted criteria. When a criterion is removed on purpose, remove its tests in the same change. A test that still passes against deleted behavior keeps that behavior alive, because nobody dares remove the code it protects.
Partial implementation. Sometimes a criterion is intentionally deferred. Mark it in the spec as deferred, with a reason, instead of leaving it uncovered. Then the traceability script can skip deferred criteria and a real gap stays distinguishable from a planned one.
Design drift. Requirements get most of the attention, but the design document drifts too, for example when the agent picks a different table layout than the one described. Design drift is harder to detect automatically. A periodic check, such as at the end of each feature, in which a reviewer compares the design document with the actual modules, catches most of it.
Generated documentation. Where you can, generate documents from the code instead of maintaining them by hand. An API reference produced from type annotations cannot disagree with the code. Reserve hand-written specs for intent, which cannot be generated.
A routine that keeps things aligned
You do not need heavy process. A small routine is enough:
- Run the traceability check in CI on every pull request.
- Require that a PR touching behavior also touches a file under
specs/, or states why not. - Review spec diffs separately from code diffs.
- After each feature, spend ten minutes comparing the design document with the code.
- When an agent proposes a spec change, treat it as a question for a human, not a patch to apply.
Exercise
A test is marked # covers: 2.3, but the requirements file now has only criteria 2.1 and 2.2. The traceability check passes the "uncovered criteria" test and fails the "unknown references" test. What are the two most likely explanations, and what should you do before deleting the test?
Show answer
Either criterion 2.3 was deliberately removed, or the criteria were renumbered and 2.3 now has a different ID. Check the spec history in Git to see which. If the criterion was removed on purpose, delete the test along with it. If it was renumbered, update the covers comment to the new ID. Do not delete the test until you know the behavior it protects is no longer required.
Exercise
During task 3, a coding agent finds that the spec says the reset endpoint must return the same response for registered and unregistered emails, but the framework adds a different response header in one case. The agent edits criterion 1.2 to say "same response body" so its tests pass. What went wrong, and what should the workflow have been?
Show answer
The agent changed a requirement on its own to make its output pass, which removes the review gate on the decision. The workflow should have been: stop, report the conflict, and let a human decide. If the header difference leaks whether an email is registered, the code should be fixed, for example by normalizing the header. If the difference is acceptable, a human edits the spec in its own commit with a reason, and then tests and code follow. The project instruction file should forbid the agent from editing requirements.