Why it matters
A coding agent can be built from three tools: read a file region, apply a patch, run a command. Everything else (search, symbol lookup, test selection) improves efficiency but does not change the shape. Getting these three right is therefore the highest-leverage work in a harness, and getting them wrong produces the two signature failures: patches applied to the wrong place, and confident reports about code that was never run.
The ordering is not incidental. Reading first changes what the model believes; editing without reading is guessing; executing without editing tests nothing. The invariant that ties them together is simple and worth enforcing in code rather than in a prompt.
Mental model
A surgeon working through a laparoscope: look, cut, look again. The instrument is small, the field of view is narrow, and every action is followed by a fresh view before the next decision.
The analogy breaks on memory and consent. A surgeon holds a continuous spatial model and knows the anatomy. The agent holds a transcript and reconstructs the file from text it saw several turns ago, which may already be out of date. That is why the harness, not the model, must guarantee freshness.
How it works
Step 1 of 7
Three primitives, three refusals
Read, edit and execute are the irreducible set, and each one has a refusal that costs a turn: no edit without a read, no patch on a stale version, no success without an exit code.
question · current
A change is needed
Each edit is classified on its own. A read from ten turns ago is not a read of this revision, so a session-level flag would let the second edit through on a stale anchor.
Root of the hierarchy
Also in focus
- Read the range
- Apply the patch
- Run the narrowest falsifying command
Figure. The loop as three decisions, each with a refusal that turns a silent corruption into a cheap error: no edit without a read, no patch on a stale version, no success without an exit code and a collected test count. The three crossed branches are the shortcuts each refusal exists to stop.
What to notice. The range read, the version token and the command contract are the page's own protocol; no counts are drawn because the page publishes none. This is a decision structure, not the order of turns: each refusal fires at the boundary it guards, and a refusal costs one turn rather than a restart. Omitted: the patch format itself and the sandbox implementation, which the page covers as tool design.
Text version
A read, edit and execute decision tree. The root is a needed change, decided per edit rather than per session. If the path has not been read this revision, a read stage returns a range and a version token. If it has, a patch is applied only when the version matches; a mismatch is rejected as a stale read and asks for a re-read. After the patch, the narrowest falsifying command runs and the exit code is read as data. A non-zero code returns to one hypothesis and one patch. A zero code reaches a gate that asks whether the runner collected any tests: yes reaches the narrow check passed stop point, and no is silent success, where nothing ran. Three crossed branches are edit from the last read, rewrite the whole file, and read stdout while skipping the exit code. A final gate widens to the package suite once the narrow check passes.
- Read with a range. Return line numbers, content and a version token: a hash of the file, or mtime plus size. Whole-file reads are acceptable only below a size threshold.
- Make the read cheap and repeatable. Reads should have no side effects and no cost beyond tokens, so the agent can re-read after every change without thinking about budget.
- Edit with an anchor. A patch identifies its target by content or by line range plus expected version. If the version does not match, reject the patch and tell the model what changed.
- Write the patch, not the file. Return the hunks that were applied and the new version token, so the next edit can be validated against reality.
- Execute narrowly. Run the smallest command that can falsify the change: one test file, a type check on the package, a lint on the touched directory.
- Feed back faithfully. Return exit code, stdout and stderr, truncated at the boundary with a path to the full log. Do not paraphrase a failure into "the build failed".
- Repeat, then widen. Once the narrow check passes, run the broader suite before declaring done.
class Workspace:
def read(self, path: str, start: int | None = None, end: int | None = None) -> dict:
text = self.fs.read(path)
lines = text.splitlines()
chunk = lines[(start or 1) - 1 : end or len(lines)]
return {
"path": path,
"range": [start or 1, end or len(lines)],
"total_lines": len(lines),
"version": sha256(text),
"content": "\n".join(f"{i:>5} {l}" for i, l in enumerate(chunk, start=start or 1)),
}
def edit(self, path: str, expected_version: str, patch: str) -> dict:
text = self.fs.read(path)
if sha256(text) != expected_version:
return {"ok": False, "code": "stale_read", "remedy": "read the file again"}
updated, applied = apply_unified_diff(text, patch)
if not applied:
return {"ok": False, "code": "anchor_not_found", "remedy": "read the region again"}
self.fs.write(path, updated)
return {"ok": True, "hunks": applied, "version": sha256(updated)}
def run(self, cmd: list[str], timeout_s: int = 120) -> dict:
result = self.sandbox.exec(cmd, timeout=timeout_s, cwd=self.root)
return {
"exit_code": result.code,
"stdout": truncate(result.stdout, 8_000, spill_to=self.log_path("stdout")),
"stderr": truncate(result.stderr, 8_000, spill_to=self.log_path("stderr")),
}The version check is the important line. Without it, two parallel edits, or an edit after a formatter ran, silently apply to the wrong offsets. With it, the model gets a stale_read error, re-reads, and repairs in one turn. That is a cheap failure converted from a silent corruption.
Trade-offs
| Choice | Good for | Cost | Fails when |
|---|---|---|---|
| Whole-file read and rewrite | Small files, generated code | Tokens, reformatting noise, lost comments | The file is large or shared |
| Range read plus patch | Most edits | More turns, anchor failures | The target region is hard to identify |
| Content-anchored replacement | Stable, unique snippets | Ambiguity when the snippet repeats | The same line appears many times |
| Line-range patch with version check | Fast iteration | Breaks after any concurrent write | Another process formats or writes the file |
| Execute via shell | Any language, any tool | Security surface, non-determinism | The workspace is untrusted or shared |
Good for
Small files, generated code
Cost
Tokens, reformatting noise, lost comments
Fails when
The file is large or shared
- The file is large or shared
- The target region is hard to identify
- The same line appears many times
- Another process formats or writes the file
- The workspace is untrusted or shared
Figure. Each choice with what it buys, what it costs, and the case where it loses.
What to notice. The fourth column is the decision: if the losing case describes your situation, the choice is wrong.
Text version
Four trade-offs: Whole-file read and rewrite is good for Small files, generated code, costs Tokens, reformatting noise, lost comments, and fails when The file is large or shared. Range read plus patch is good for Most edits, costs More turns, anchor failures, and fails when The target region is hard to identify. Content-anchored replacement is good for Stable, unique snippets, costs Ambiguity when the snippet repeats, and fails when The same line appears many times. Line-range patch with version check is good for Fast iteration, costs Breaks after any concurrent write, and fails when Another process formats or writes the file. Execute via shell is good for Any language, any tool, costs Security surface, non-determinism, and fails when The workspace is untrusted or shared
Failure modes
- Edit without read. The model patches a region from memory and lands in the wrong function. Debug: log every edit and check whether a read of that path preceded it in the same session; enforce the invariant if the rate is non-trivial.
- Stale anchor. A formatter ran between read and edit, and the patch applies to the wrong lines or fails. Debug: count
stale_readrejections per session; a high rate means your edit protocol is not version-aware. - Silent success. The command exited zero but did nothing, because the test filter matched no tests. Debug: require the runner to report the number of collected tests and fail when it is zero.
- Observation paraphrase. The harness summarises stderr and drops the assertion diff, so the model repairs the wrong thing. Debug: compare what the harness returned with the raw log for ten failing runs.
In production
Execution is the slowest and least predictable part of the loop, so give it a timeout and a concurrency limit per session. Cold caches make the first test run much slower than the rest; keep the workspace warm across turns rather than recreating it.
Track edit success rate (applied on first attempt), stale-read rate, and commands per task. A rising command count with flat success usually means the agent is guessing at test invocations; give it a project-level command hint instead of more retries. And log the exact command line for every execution: without it, a verification claim cannot be audited after the fact.
Common misconceptions
People think: The hard part is generating a correct patch.
Actually: Applying a patch safely to a changing file, and knowing whether it worked, is where most reliability is won. Generation quality is necessary but not sufficient.
People think: If a command exits zero, the change is verified.
Actually: Zero can mean no tests ran, the wrong target was tested, or the failure was swallowed. Verification requires knowing what executed and what it asserted.
Interview angle
Expect "what tools would you give a coding agent?" The weak answer is a long list. The strong answer is three primitives, an invariant (fresh read before write), and a feedback contract (structured observations with exit codes). Then explain how you would prevent an edit from landing in the wrong place. See agentic coding interview questions, patch editing and tool ergonomics.
Sources
- Yang et al., SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering — shows measurable performance differences from file viewer and edit command design.
- Anthropic, Claude Code best practices — read-before-edit and run-the-check guidance from a production harness.
- Wang et al., Executable Code Actions Elicit Better LLM Agents — argues for executable actions with real feedback over simulated ones.
- Git, git-diff documentation — how unified diffs are produced and what the context lines mean in practice.