Skip to content
15 min read45 min build
Prerequisites:ch01-minimal-coding-loopch02-tool-registrych03-planner-task-graphch04-memory-context
What You Will Build

A PatchEngine that parses unified diffs, applies them safely, and reverts on failure

Why This Matters

In Chapters 1-4, your agent wrote files by overwriting them entirely. The writeFile tool takes a path and full content, then replaces whatever was there. This works for creating new files, but it is dangerous for editing existing ones. If the model hallucinates the wrong content, or if two agents edit the same file, data is lost with no way to recover.

Every production coding agent — Claude Code, Codex, Cursor — uses structured patches instead of full file writes. A patch describes only the lines that change, leaves everything else untouched, and can be reverted if something goes wrong. This is the difference between a toy and a tool.

What You Will Build

A PatchEngine class that parses unified diff format, applies hunks to files, verifies the result, and supports rollback. When the LLM wants to edit a file, it produces a diff instead of the full file, and your engine applies it safely.

The cycle is: read the original, save a backup, apply the diff, verify the result. If verification fails, restore from backup.

Story Mode for this chapter is coming soon

We are crafting a fun, code-free explanation with metaphors and interactive mini-games. In the meantime, switch to Builder Mode to start learning.

What's Next

You now have a safe editing layer. The agent can modify files with surgical precision, detect conflicts, and roll back mistakes. But there is a missing piece: who decides whether a patch should be applied at all?

Some changes are low-risk — fixing a typo in a comment. Others are high-risk — modifying authentication logic or running shell commands. You need a policy layer that evaluates tool calls before they execute.

In Chapter 6: Approvals, Policies, and Sandboxing, you will build an approval system that classifies tool calls by risk level and gates dangerous operations behind human review.