Previous article:Git Diff Tools for AI Coding Agents: Status, Parsed Patches, and Change Summaries
Next article:AI Coding Agent Security: Approval Gates and Workspace Sandbox in TypeScript
中文版:Patch Editing:安全应用 Unified Diff
Introduction
Day 11: validate and apply multi-file unified diffs without partial writes. This chapter keeps the implementation deliberately small: the point is to make one boundary explicit, testable, and easy to inspect before adding more autonomy.

Why patches are safer than whole-file replacement
A coding agent is more than a model response. It needs a runtime that can turn a request into controlled work, preserve the intermediate state, and explain what happened afterwards. Day 11 focuses on that runtime boundary instead of hiding it behind a single prompt.
model patch → parse → validate all files → apply in memory → write → inspect diff
Prepare every change before writing
The implementation uses explicit data structures and narrow interfaces. The model proposes the next step; the harness owns validation, execution, limits, and structured results. That separation lets the same capability work in a CLI today and in a richer product surface later.
- Use unified diff hunks to constrain the intended edit.
- Validate every target before making any write.
- Return a recoverable failure when a hunk cannot apply cleanly.
Validate paths and failed hunks
Reliability comes from treating failure paths as normal paths. Inputs are bounded, unsafe or malformed requests produce recoverable errors, and the run records enough evidence to let a developer understand the decision. This is especially important when later steps can touch a real workspace.
npm run dev -- "apply a small patch to a fixture file"
npm run dev -- --tool apply_patch --tool-input '{"patch":"diff --git a/demos/day-11/fixture.txt b/demos/day-11/fixture.txt\n--- a/demos/day-11/fixture.txt\n+++ b/demos/day-11/fixture.txt\n@@ -1,3 +1,3 @@\n Day 11 fixture\n-status: pending\n+status: patched\n Keep this file small.","dryRun":true}'
Model proposes a patch
Harness validates paths
Patch engine matches hunks
Harness writes files
Git tools verify resulting diff
Dry runs and the next safety layer
With this layer in place, later chapters can add capability without weakening the boundary: tools can be registered and observed, context can be measured, writes can require approval, and every run can be replayed. The result is not a general autonomous system; it is a compact harness whose behavior remains understandable.
Key takeaways
- Build the execution boundary before adding more tools or model freedom.
- Keep model intent separate from runtime authority.
- Make limits, validation, and failure results visible.
- Use structured observations to support debugging and future extensions.
Demo
The accompanying implementation and runnable examples are available in the cli-harness repository.
Comments