Repository navigation
fix(agents): apply_patch rewrites bytes on hunk context lines - #116128
Conversation
A fuzzy apply_patch update replaced the entire matched span with the model-authored patch text, so trailing whitespace, typographic punctuation, and tab indentation on lines the hunk marked as context were overwritten while the tool reported plain success. The parser now records which emitted lines came in as context and which old line each one came from, and the update applier keeps the file's own bytes for those lines. Added and removed lines are still written from the patch.
|
Codex review: needs maintainer review before merge. Reviewed July 29, 2026, 8:43 PM ET / July 30, 2026, 00:43 UTC. ClawSweeper reviewWhat this changesThis PR records unchanged update-hunk context lines and reuses the original file bytes for those lines when tolerant Merge readinessThe patch appears to fix a real default-path silent file-corruption bug with a focused parser-to-writer boundary and strong after-fix runtime evidence. No discrete correctness or security defect is evident in the submitted diff; keep this PR open for maintainer review after its current-main refresh. Likely related people: Priority: P0 Review scores
Verification
How this fits togetherOpenClaw’s agent coding tools parse model-generated patches, match update hunks against workspace files, and write the resulting contents through host or sandbox filesystem operations. The changed boundary preserves original bytes for hunk lines that the patch explicitly declares unchanged while still applying additions and removals. flowchart LR
Patch[Agent patch input] --> Parser[Update-hunk parser]
Parser --> Metadata[Context-line mapping]
Patch --> Matcher[Tolerant matcher]
File[Original workspace file] --> Matcher
File --> Writer[Replacement builder]
Metadata --> Writer
Matcher --> Writer
Writer --> Result[Updated file and tool result]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +33, Tests +185. Total +218 across 4 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land the focused context-byte preservation after rebasing onto current Do we have a high-confidence way to reproduce the issue? Yes. The PR provides a high-confidence real-filesystem reproduction through the production Is this the best way to solve the issue? Yes. Recording context ownership in the parser and preserving those bytes only at the replacement writer is the narrowest maintainable fix; it aligns AGENTS.md: unclear because the file could not be read completely. Codex review notes: model internal, reasoning high; reviewed against 1165be39fffc. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
* origin/main: (23 commits) refactor(channels): own account config mutations (openclaw#115970) fix(discord): keep activity receipts in adopted threads (openclaw#116119) fix(feishu): preserve card actions through mention gating (openclaw#116105) perf(gateway): cache lazy server methods import (openclaw#116060) refactor: keep update timing constants private fix: reject stale update reconciliation refactor: keep update status response private fix: bound update status reconciliation fix: preserve uncertain update outcomes refactor: keep update reconciliation within size budgets fix: release update reconciliation on access loss docs: note control ui update reconciliation test: cover both managed update response orders fix: reconcile ambiguous gateway updates fix(codex): prevent approval promotion from blocking unattended runs (openclaw#116117) fix(daemon): require system-scope ownership before removing the user unit fix(daemon): only treat same-canonical-name user+system units as dueling fix(daemon): detect and resolve dueling user+system systemd gateway units fix(macos): back off approval socket retries (openclaw#116125) test: add stalled provider response body timeout coverage ...
* origin/main: fix(ui): make model setup actionable before selection (openclaw#116079)
…aw#116128) * fix(agents): apply_patch rewrites bytes on hunk context lines A fuzzy apply_patch update replaced the entire matched span with the model-authored patch text, so trailing whitespace, typographic punctuation, and tab indentation on lines the hunk marked as context were overwritten while the tool reported plain success. The parser now records which emitted lines came in as context and which old line each one came from, and the update applier keeps the file's own bytes for those lines. Added and removed lines are still written from the patch. * test(agents): cover apply_patch context preservation --------- Co-authored-by: Vincent Koc <[email protected]>
Closes #116124
What Problem This Solves
Fixes an issue where users editing files with an agent would silently lose bytes on lines the patch never marked as changed. When
apply_patchlocates an update hunk through its tolerant matcher instead of an exact match, the whole matched span is replaced with the model's own patch text, so trailing whitespace, typographic punctuation, and tab indentation on context lines are overwritten with whatever the model retyped. The tool still reportsSuccess. Updated the following files: M <file>, so neither the agent nor the operator sees that unrelated bytes changed. On a tab-indented source file this can turn a working file into one that no longer compiles.Why This Change Was Made
The parser already knows which hunk lines came in as context (leading space) and which came in as additions, but it discarded that distinction before the write-back. The chunk now records, for every line it emits, the index of the old line it came from when that line was context, and the update applier uses those indexes to keep the file's own bytes for context lines while still writing added lines from the patch. Exact matches are unaffected because the file bytes and the patch text are identical there. This mirrors the ownership boundary
editalready has viaapplyReplacementsPreservingUnchangedLines(#89994, PR #99949) without adding a second normalization policy. Non-goal: the indentation of lines the hunk explicitly marked as changed is still written as the model typed it, same asedit.User Impact
Agent patches no longer damage lines they were not asked to touch. Markdown hard line breaks, curly quotes and other typographic punctuation, tab indentation, and mixed line endings on context lines survive a fuzzy
apply_patchupdate, and only the removed and added lines are rewritten.Evidence
Root cause
src/agents/apply-patch-update.ts:104before:newSliceischunk.newLines, the model-authored text for the whole span, andfoundcomes fromseekSequence, which walks an increasingly tolerant normalizer ladder (value,trimEnd,trim,normalizePunctuation(trim)). Every difference those normalizers ignored in order to find the match is then written to disk from the model's side.Fix
after:
keepContextBytesmaps each emitted line back tooriginalLines[found + oldIndex]when the parser recorded it as context, and leaves added lines alone.Why this is the right boundary
The parser is the only place that knows the
' '/'+'/'-'marker, so it is where the context relation is recorded; the applier is the only place that owns the write-back. The insertion branch (chunk.oldLines.length === 0) has no context span and is untouched. CRLF and mixed-ending handling added by #115943 and #116011 is preserved and now also benefits, since a context line whose only difference was a trailing\rkeeps its original terminator.editis the sibling surface and already has this invariant;apply_patchwas the remaining independent implementation.Verification
node scripts/run-vitest.mjs src/agents/apply-patch.test.ts- 52 passed with the patch; the 3 new cases fail on pristine main (3 failed | 49 passed) and pass with the patch.node scripts/run-vitest.mjs src/agents/apply-patch-paths.test.ts- passed.Real behavior proof
Behavior addressed:
apply_patchoverwrote trailing whitespace, typographic punctuation, and tab indentation on hunk lines marked as unchanged context, while reporting plain success.Real environment tested: the shipped
apply_patchagent tool built bycreateApplyPatchTooland driven through its realexecuteentry point against real files on disk, first on pristine origin/maincdab1764841a369951c6b525719ec6e11983956aand then on the patched tree with identical inputs. Nothing was stubbed: real parser, real tolerant matcher, real host filesystem writes, realpython3compile of the resulting file.Exact steps or command run after this patch:
./node_modules/.bin/tsx ctx-repro.mts, which createsNOTES.md(two trailing spaces, U+2019) andrun.py(tab indentation), callsapply_patchwith a hunk that changes one line and carries the rest as context typed in normalized form, then reads both files back and runspython3 -c "import py_compile; py_compile.compile('run.py', doraise=True)".Evidence after fix:
Observed result after fix: with identical inputs, the two trailing spaces on lines 2 and 3, the U+2019 apostrophe on line 4, and the tab indentation on the three
run.pycontext lines are byte-identical to the original file instead of being replaced by the retyped patch text, and the intended single line still changes fromold valuetonew valueand fromvalue = 1tovalue = 2.What was not tested: the indentation of the line the hunk explicitly marked as changed is still taken from the patch text, so the
run.pycase remains mixed on that one line andpy_compilestill reports a TabError there (it moved from line 6 to line 4); that is the same boundaryedithas and is out of scope here. I also did not exercise the sandboxed filesystem bridge path beyond existing coverage, multi-file patches, or a full build.