Build an Autonomous Coding Agent · 50 min · Python · pytest · subprocess
Execution Engine
Writing directly to a file the agent is modifying is the single fastest way to turn a bug into a corrupted repository.
Hiring signal: Backup-verify-replace file modification and a real test-driven fix loop are what separate a coding agent you'd actually trust on your own repo from one you'd only run in a sandbox you don't care about.
What you will learn
- Implement backup-verify-replace file modification with diff generation
- Run the real test suite as a subprocess and parse pass/fail results structurally
- Build the iterative fix loop: fail, read error, regenerate, retry, with a hard cap
Introduction
A validated plan is still just a description of intent. Today the agent actually writes to files — and this is the lesson where getting it wrong has real consequences, not just a confusing error message.
Backup before you touch anything
import shutil
import difflib
def modify_file_safely(path: str, new_content: str) -> str:
backup_path = path + ".bak"
shutil.copy2(path, backup_path)
with open(path, "r", encoding="utf-8") as f:
old_content = f.read()
with open(path, "w", encoding="utf-8") as f:
f.write(new_content)
diff = "\n".join(difflib.unified_diff(
old_content.splitlines(), new_content.splitlines(),
fromfile=f"{path} (before)", tofile=f"{path} (after)", lineterm="",
))
return diff
The .bak copy exists so restore_from_backup (Lesson 5) has something to restore FROM if a later step in a multi-file plan fails — this is what makes rollback possible at all. The diff isn't optional polish either: it's the artifact that lets you (or the agent's own summary in Lesson 6) show exactly what changed, which matters enormously when you're trusting an agent's judgment about your own code.
This is the exact mistake the SPEC's hotspot list warns about
Writing open(path, "w").write(new_content) directly, with no backup step, works fine right up until a bug in the agent's generated code corrupts a file you have no way to recover — because you overwrote the only copy. The backup-before-write pattern above costs one extra line (shutil.copy2) and is the entire difference between "recoverable mistake" and "lost work." Do not skip this to move faster through the lesson.
Unlock the full lesson
You've read the first 2 sections. The rest of this lesson covers Running tests as ground truth, The fix loop: bounded, and honest when it gives up, What You're Building — plus a hands-on lab, quiz, and project artifact.
Create a free account to unlock Phase 0 and Phase 1 of every course — no credit card.
Browse all courses · View pricing · DeVenture Academy