11. Editing Files with apply_patch

Codex edits files through one tool with its own small language, not through shell commands. A patch names every file it touches and anchors every change in context lines, so Codex can check it against the real files, decide on approval, apply it in its own process with sandboxed writes, and fold the result into one diff for the turn.

A model could edit a file with sed -i or a heredoc into cat >. Both work, and both are opaque to the harness. Before such a command runs, Codex cannot tell which files it will change, cannot show you the edit for approval, and cannot check each target against the writable roots. Afterward, it cannot say what changed without rereading the disk.

The apply_patch tool turns an edit into data: a list of hunks, each naming a path and an operation. Codex works out the new content of every file before it decides whether the edit is safe. Changes are anchored on context lines, not line numbers, so the model never counts lines in a file it read several steps ago. This chapter follows one patch from the model to the disk and into the turn’s diff.

The picture

The model sends apply_patch as a freeform call, or as a shell command that exec_command intercepts; both reach parse_patch, then verification against the files, a safety assessment, and an approval decision; ApplyPatchRuntime applies the patch in process with writes through a sandboxed helper, returns an A, M, D summary to the model, and hands the committed delta to the TurnDiffTracker, which emits one unified diff for the turn.

Two entry points feed one path. The normal entry is a freeform tool call whose raw input is the patch; the second is a shell command such as apply_patch <<'EOF', which exec_command diverts before any shell starts. Both pass three gates that can refuse: verification, the safety assessment, and approval. Only then does ApplyPatchRuntime write. It reports twice: a summary goes to the model, and the committed delta goes to the diff tracker, which emits a TurnDiff event.

The patch format

A freeform tool with a grammar

create_apply_patch_freeform_tool in codex-rs/core/src/tools/handlers/apply_patch_spec.rs returns a ToolSpec::Freeform, which goes on the wire with type custom. Its format is a lark grammar read from codex-rs/core/assets/tools/apply_patch.lark, and its description says: “This is a FREEFORM tool, so do not wrap the patch in JSON.”

The freeform design removes a class of failure. A patch is full of quotes, backslashes, and newlines, and inside a JSON string each needs escaping. As a custom tool, the model emits raw text, which the router turns into ToolPayload::Custom { input } (see Chapter 9). The grammar travels with the tool definition; the client code does not show how the server uses it.

start: begin_patch hunk+ end_patch
begin_patch: "*** Begin Patch" LF
end_patch: "*** End Patch" LF?

hunk: add_hunk | delete_hunk | update_hunk
add_hunk: "*** Add File: " filename LF add_line+
delete_hunk: "*** Delete File: " filename LF
update_hunk: "*** Update File: " filename LF change_move? change?

filename: /(.+)/
add_line: "+" /(.*)/ LF -> line

change_move: "*** Move to: " filename LF
change: (change_context | change_line)+ eof_line?
change_context: ("@@" | "@@ " /(.+)/) LF
change_line: ("+" | "-" | " ") /(.*)/ LF
eof_line: "*** End of File" LF

%import common.LF

For a turn with several execution environments, the builder adds an optional *** Environment ID: line after *** Begin Patch. The tool is registered only when the model catalog sets apply_patch_tool_type, whose one variant is Freeform; all 14 bundled models set it.

A real patch

The crate keeps portable fixtures under codex-rs/apply-patch/tests/fixtures/scenarios/, each an input/ tree, a patch.txt, and an expected/ tree. Fixture 002_multiple_operations uses all three hunk kinds:

*** Begin Patch
*** Add File: nested/new.txt
+created
*** Delete File: delete.txt
*** Update File: modify.txt
@@
-line2
+changed
*** End Patch

The input holds delete.txt and a modify.txt with lines line1 and line2. Afterward, nested/new.txt exists, delete.txt is gone, and modify.txt reads line1, changed. In an update chunk, a - line is text to find, a + line its replacement, and a line starting with a space is context that must match and stays unchanged.

Fixture 004_move_to_new_directory adds *** Move to: after the update header, so the file is rewritten at a new path. Fixture 022 ends a chunk with *** End of File, pinning it to the file’s end. An @@ line may carry text, as in @@ def f():: a context line, usually a function header, to find before the chunk’s own lines.

Parsing and its error messages

parse_patch in codex-rs/apply-patch/src/parser.rs trims the input and checks its first and last lines. PARSE_IN_STRICT_MODE is false, so every model gets lenient parsing: a patch wrapped in a <<'EOF' heredoc has the wrapper removed, and whitespace around markers is tolerated.

The parsing itself is a state machine, StreamingPatchParser, with modes NotStarted, StartedPatch, AddFile, DeleteFile, UpdateFile, and EndedPatch. It streams because it serves a second caller: ApplyPatchArgumentDiffConsumer feeds it argument deltas while the model is still writing and emits a PatchApplyUpdated preview at most every 500 ms, behind the apply_patch_streaming_events flag.

The model is the main reader of these errors, and the core wraps each as apply_patch verification failed: {err}. The table lists the messages and their triggers.

Message (abridged) Trigger
The first line of the patch must be '*** Begin Patch' JSON wrapper, code fence, or prose first
The last line of the patch must be '*** End Patch' Truncated patch or trailing text
'...' is not a valid hunk header A line outside any hunk
Update file hunk for path '...' is empty Update header with no chunk
Unexpected line found in update hunk A line without space, +, or - while the current chunk is still empty
Expected update hunk to start with a @@ context marker Such a line after the chunk has lines, or a non-@@ line after *** End of File

Hunk errors carry a line number, as in invalid hunk at line 2, .... Verification later refuses two hunks on one path with multiple operations target {path}, and the safety check rejects a patch with no hunks as empty patch.

Placing a hunk in the file

Walking the chunks

An update hunk holds UpdateFileChunk values, each with an optional change_context, old_lines, new_lines, and an is_end_of_file flag. compute_replacements in file_update.rs walks them with a cursor that only moves forward, so chunks must appear in file order.

For each chunk, it first finds the change_context line, if any, and moves the cursor past it, or fails with Failed to find context '{ctx}' in {path}. A chunk with no old lines is appended at the end of the file. Otherwise it searches for old_lines from the cursor; if that fails and the pattern ends with an empty string, it retries without it, since that string often stands for the final newline. A chunk that still has no match fails with Failed to find expected lines in {path}: plus the old lines.

Context lines inside a matched chunk keep the file’s text, not the patch’s. SourceFile in text_file.rs stores each line with its own ending, and inserted lines take the file’s first ending, so CRLF and mixed files survive an edit (fixtures 023 and 024).

seek_sequence: four passes from strict to loose

seek_sequence finds where a run of pattern lines occurs. It makes up to four passes over the candidate positions and returns the first position matched by the first pass that finds any match:

  1. Exact. Each file line equals its pattern line.
  2. Trailing whitespace ignored. Both sides are compared after trim_end.
  3. Surrounding whitespace ignored. Both sides are compared after trim.
  4. Unicode punctuation normalized. Both sides are trimmed, then U+2010 to U+2015 and U+2212 become -, U+2018 to U+201B become ', U+201C to U+201F become ", and thirteen space characters (U+00A0, U+2002 to U+200A, U+202F, U+205F, U+3000) become a plain space.

Let the file have lines and the pattern , searched from cursor , with to the four comparisons. The first candidate position is

and the match is

where is the smallest pass number whose set is not empty. If all four sets are empty, there is no match. An empty pattern matches at , and a pattern with never matches.

Two consequences follow. A loose match early in the file never beats an exact match later, because each pass scans every position first. And an end-of-file chunk tests position only. The doc comment above the function describes three passes and says an end-of-file search falls back to start; the code has a fourth pass and no fallback, and the code is what runs.

The loose passes exist because models copy context imperfectly; a comment says the last one “mirrors the fuzzy behaviour of git apply”. The cost: passes 3 and 4 ignore indentation, so in Python or YAML a pattern can match at the wrong nesting level, and replacement lines keep the model’s indentation.

From tool call to files on disk

Verify, assess, approve, apply

ApplyPatchHandler in codex-rs/core/src/tools/handlers/apply_patch.rs accepts only Custom payloads and parses the patch once to pick its environment. It then follows these steps:

  1. prepare_patch_request calls parse_patch and verify_apply_patch_args, which reads every target and computes an ApplyPatchFileChange per path. Errors surface before any write, for example apply_patch verification failed: Failed to read file to update /tmp/x/missing.txt: No such file or directory (os error 2).
  2. prepare_verified_patch picks a sandbox route, ExecutorManaged for a remote environment or Platform for a local one, and computes extra write permissions for the parents of targets that are not yet writable.
  3. patch_approval_requirement calls assess_patch_safety and maps its answer to an ExecApprovalRequirement.
  4. execute_prepared_patch starts a FileChange item and runs ToolOrchestrator::run with an ApplyPatchRuntime.
  5. ToolEmitter::finish formats the output, completes the item, and updates the turn diff.

The safety assessment

assess_patch_safety in codex-rs/core/src/safety.rs returns AutoApprove, AskUser, or Reject. It auto-approves when every target, including each move destination, is writable and a sandbox can enforce that policy (or the profile is Disabled or External, which apply no outer sandbox). The table shows the outcome per approval policy when a sandbox is available.

Approval policy All targets writable Some target not writable
Never Auto-approve Reject
OnRequest Auto-approve Ask the user
Granular, sandbox approval off Auto-approve Reject
Granular, sandbox approval on Auto-approve Ask the user
UnlessTrusted Ask the user Ask the user

AutoApprove becomes Skip with bypass_sandbox: false, AskUser becomes NeedsApproval, and Reject returns patch rejected: {reason}, for example “writing outside of the project; rejected by user approval settings”. Auto-approval still runs sandboxed; a code comment notes that a writable-looking path may be a hard link to a file outside the writable roots. Chapter 13 covers approvals.

In-process apply, sandboxed writes

ApplyPatchRuntime::run in codex-rs/core/src/tools/runtimes/apply_patch.rs starts no apply_patch process. It calls codex_apply_patch::apply_patch_with_options directly, with the turn environment’s ExecutorFileSystem and a FileSystemSandboxContext for this attempt. The patch logic runs in the Codex process; the writes go through the filesystem abstraction, where the sandbox applies.

For a local environment, a policy without full-disk write access makes should_write_into_sandbox true, and each write goes to SandboxedFileSystem. That type runs one helper process per operation: the Codex executable with the hidden argument --codex-run-as-fs-helper, wrapped by the platform sandbox (see Chapter 14), with the request as JSON on standard input. For a remote environment, the runtime reports uses_executor_managed_process_sandbox, and the executor enforces the policy. The same patch code serves both.

Application is not atomic. Hunks apply in order with no rollback, and fixture 015_failure_after_partial_success_leaves_changes checks that a file added before a failing update stays. AppliedPatchDelta records what was committed; its exact flag turns false when a failed write might have changed a file anyway, or when a target’s prior content cannot be read or the target is not a regular file. A likely sandbox denial becomes SandboxErr::Denied, after which the orchestrator may ask to retry unsandboxed. On success, the model receives the summary from print_summary in the standard exec frame (wall time illustrative), as a custom_tool_call_output item:

Exit code: 0
Wall time: 0.1 seconds
Output:
Success. Updated the following files:
A nested/new.txt
M modify.txt
D delete.txt

The shell route: interception

The default base instructions in codex-rs/protocol/src/prompts/base_instructions/default.md still show apply_patch as a command array, and models often write apply_patch <<'EOF' in a shell. Run as ordinary commands, these would skip verification, the safety check, and the turn diff. Codex applies the interceptor pattern instead: ExecCommandHandler calls intercept_apply_patch after it builds the argument vector and before it spawns anything.

maybe_parse_apply_patch in codex-rs/apply-patch/src/invocation.rs recognizes ["apply_patch", "<patch>"] (or applypatch), and shell vectors such as ["bash", "-lc", script], ["pwsh", "-Command", script], and ["cmd", "/c", script]. A Tree-sitter query then accepts exactly one top-level statement, apply_patch <<'EOF' ... EOF, optionally preceded by cd <path> &&. Anything else, such as echo hi; apply_patch ..., runs as an ordinary command (see Chapter 10). A vector that is itself a bare patch is refused with patch detected without explicit call to apply_patch. Rerun as ["apply_patch", "<patch>"].

An intercepted patch joins the freeform path at prepare_parsed_patch, with any cd directory applied. The outer command already passed the Bash hooks, so interception runs PreToolUse hooks again under the name apply_patch. The model still sees an exec_command output, but InterceptedApplyPatchOutput reports committed_tool_name as apply_patch for hooks and telemetry.

The turn diff

TurnDiffTracker in codex-rs/core/src/turn_diff_tracker.rs builds one unified diff for the turn. The turn loop creates it once per turn, so steered input does not reset it. It keeps baseline_by_path, the content first seen for each path, and current_by_path, the latest content, and always diffs one against the other. An add followed by an update therefore shows as one new file.

The tracker never rereads the workspace. It learns only from committed AppliedPatchDelta values, a small case of event sourcing: the diff is a fold over change events, so it cannot race with another process editing a file. Exactness guards the fold:

pub fn track_delta(&mut self, environment_id: &str, delta: &AppliedPatchDelta) {
    if !self.valid {
        return;
    }

    if !delta.is_exact() {
        self.invalidate();
        return;
    }

    for change in delta.changes() {
        self.apply_change(environment_id, change);
    }
    self.refresh_unified_diff();
}

An inexact delta invalidates the tracker for the rest of the turn, which then reports no diff rather than a wrong one. A moved and edited file renders as diff --git a/src.txt b/dst.txt; a pure rename renders nothing.

render_diff writes Git’s format: a diff --git line, a new file mode 100644 or deleted file mode 100644 line where needed, an index line, and a unified diff with three lines of context under a 100 ms DIFF_TIMEOUT. The index line carries Git blob object IDs:

Here is the content in bytes, its length, its decimal digits, NUL the zero byte, and concatenation; a missing side uses ZERO_OID, forty zeros. The test accumulates_add_then_update_as_single_add adds a.txt with foo, then adds bar. Its expected diff follows, with the object ID computed for this book by git hash-object:

diff --git a/a.txt b/a.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3bd1f0e29744a1f32b08d5650e62e2e62afb177c
--- /dev/null
+++ b/a.txt
@@ -0,0 +1,2 @@
+foo
+bar

emit_patch_end in codex-rs/core/src/tools/events.rs completes the FileChange item as Completed, Failed, or Declined, feeds the tracker, and sends EventMsg::TurnDiff when the tracker changed and a diff exists now or existed before. The design has one blind spot: an edit made by sed -i through exec_command produces no delta and never appears in the turn diff.

Status at commit 081295be9d. The freeform apply_patch tool: IMPLEMENTED, registered for all 14 bundled models. Thirteen of them set tool_mode to code_mode_only, so they call apply_patch from JavaScript inside exec (see Chapter 12). apply_patch_streaming_events: UNDER DEVELOPMENT, off by default. apply_patch_freeform and apply_patch_preserve_line_endings: REMOVED; line endings are always preserved. Read in code, not run.

What breaks

Symptom Cause Check
The first line of the patch must be '*** Begin Patch' Patch wrapped in JSON, fences, or prose parser.rs check_start_and_end_lines_strict
Failed to find expected lines in <path> Old lines absent after four passes seek_sequence.rs; reread the file
Failed to find context '<ctx>' in <path> @@ anchor missing, or chunks out of order file_update.rs compute_replacements
patch rejected: writing outside of the project; ... Target outside writable roots under Never safety.rs assess_patch_safety
patch rejected: empty patch Begin and End markers with no hunks safety.rs action.is_empty()
patch detected without explicit call to apply_patch Bare patch passed to exec_command invocation.rs ImplicitInvocation
Some files edited after a failed call Hunks apply in order, no rollback Fixture 015_failure_after_partial_success_leaves_changes
Turn diff missing a change Shell edit, or tracker invalidated turn_diff_tracker.rs track_delta

Code map

What it is Where Identifier
Patch grammar sent to the model codex:codex-rs/core/assets/tools/apply_patch.lark change_context
Parser state machine codex:codex-rs/apply-patch/src/streaming_parser.rs StreamingPatchParser
Four-pass line matching codex:codex-rs/apply-patch/src/seek_sequence.rs seek_sequence
Chunk placement codex:codex-rs/apply-patch/src/file_update.rs compute_replacements
Handler, verification, interception codex:codex-rs/core/src/tools/handlers/apply_patch.rs intercept_apply_patch
Safety assessment codex:codex-rs/core/src/safety.rs assess_patch_safety
In-process application codex:codex-rs/core/src/tools/runtimes/apply_patch.rs ApplyPatchRuntime
Per-turn unified diff codex:codex-rs/core/src/turn_diff_tracker.rs TurnDiffTracker

Recall check

Why is apply_patch a freeform tool rather than a JSON function?
The model emits raw patch text with no JSON escaping, and a Lark grammar travels with the tool definition.

In what order does seek_sequence try its matches?
Exact, trailing whitespace ignored, surrounding whitespace ignored, then Unicode punctuation normalized; each pass scans every position first.

What happens when a target is outside the writable roots under OnRequest?
assess_patch_safety returns AskUser, which becomes NeedsApproval; under Never it rejects instead.

How do writes stay sandboxed when the patch logic runs inside Codex?
Each local write under a restricted policy goes to a helper process started with --codex-run-as-fs-helper inside the platform sandbox.

Why does an edit made with sed -i never appear in the turn diff?
TurnDiffTracker learns only from committed apply_patch deltas and never rereads the workspace.