Skip to content

fix(agents): apply_patch rewrites bytes on hunk context lines - #116128

Merged
vincentkoc merged 4 commits into
openclaw:mainfrom
yetval:fix/apply-patch-preserve-context-bytes
Jul 30, 2026
Merged

vincentkoc merged 4 commits into
openclaw:mainfrom
yetval:fix/apply-patch-preserve-context-bytes

Conversation

@yetval

@yetval yetval commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

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_patch locates 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 reports Success. 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 edit already has via applyReplacementsPreservingUnchangedLines (#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 as edit.

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_patch update, and only the removed and added lines are rewritten.

Evidence

Root cause

src/agents/apply-patch-update.ts:104 before:

replacements.push([found, pattern.length, newSlice]);
lineIndex = found + pattern.length;

newSlice is chunk.newLines, the model-authored text for the whole span, and found comes from seekSequence, 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:

replacements.push([
  found,
  pattern.length,
  keepContextBytes({
    originalLines,
    matchIndex: found,
    patternLength: pattern.length,
    newSlice,
    contextOldIndexes: chunk.contextOldIndexes,
  }),
]);

keepContextBytes maps each emitted line back to originalLines[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 \r keeps its original terminator. edit is the sibling surface and already has this invariant; apply_patch was 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_patch overwrote trailing whitespace, typographic punctuation, and tab indentation on hunk lines marked as unchanged context, while reporting plain success.
Real environment tested: the shipped apply_patch agent tool built by createApplyPatchTool and driven through its real execute entry point against real files on disk, first on pristine origin/main cdab1764841a369951c6b525719ec6e11983956a and then on the patched tree with identical inputs. Nothing was stubbed: real parser, real tolerant matcher, real host filesystem writes, real python3 compile of the resulting file.
Exact steps or command run after this patch: ./node_modules/.bin/tsx ctx-repro.mts, which creates NOTES.md (two trailing spaces, U+2019) and run.py (tab indentation), calls apply_patch with a hunk that changes one line and carries the rest as context typed in normalized form, then reads both files back and runs python3 -c "import py_compile; py_compile.compile('run.py', doraise=True)".
Evidence after fix:

# BEFORE (pristine main cdab1764841a369951c6b525719ec6e11983956a)
CASE 1 tool result: Success. Updated the following files: | M NOTES.md
CASE 1 file before: "# Notes\nfirst line  \nsecond line  \nIt’s done\nold value\ntail\n"
CASE 1 file after : "# Notes\nfirst line\nsecond line\nIt's done\nnew value\ntail\n"
CASE 2 tool result: Success. Updated the following files: | M run.py
CASE 2 file before: "def run(x):\n\tif x:\n\t\tprepare()\n\t\tvalue = 1\n\t\treturn value\n\treturn 0\n"
CASE 2 file after : "def run(x):\n    if x:\n        prepare()\n        value = 2\n        return value\n\treturn 0\n"
CASE 2 context lines 2,3,5 tabs kept: ["    if x:","        prepare()","        return value"]

# AFTER (this patch, identical inputs)
CASE 1 tool result: Success. Updated the following files: | M NOTES.md
CASE 1 file before: "# Notes\nfirst line  \nsecond line  \nIt’s done\nold value\ntail\n"
CASE 1 file after : "# Notes\nfirst line  \nsecond line  \nIt’s done\nnew value\ntail\n"
CASE 2 tool result: Success. Updated the following files: | M run.py
CASE 2 file before: "def run(x):\n\tif x:\n\t\tprepare()\n\t\tvalue = 1\n\t\treturn value\n\treturn 0\n"
CASE 2 file after : "def run(x):\n\tif x:\n\t\tprepare()\n        value = 2\n\t\treturn value\n\treturn 0\n"
CASE 2 context lines 2,3,5 tabs kept: ["\tif x:","\t\tprepare()","\t\treturn value"]

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.py context lines are byte-identical to the original file instead of being replaced by the retyped patch text, and the intended single line still changes from old value to new value and from value = 1 to value = 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.py case remains mixed on that one line and py_compile still reports a TabError there (it moved from line 6 to line 4); that is the same boundary edit has 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.

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.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 29, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 29, 2026
@yetval
yetval marked this pull request as ready for review July 29, 2026 23:54
@clawsweeper clawsweeper Bot added the P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. label Jul 29, 2026
@clawsweeper

clawsweeper Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 29, 2026, 8:43 PM ET / July 30, 2026, 00:43 UTC.

ClawSweeper review

What this changes

This PR records unchanged update-hunk context lines and reuses the original file bytes for those lines when tolerant apply_patch matching writes the replacement span.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

The 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: yetval (high confidence) for the recent merged apply_patch preservation work; vincentkoc (high confidence) for the current branch’s follow-up tests and rebases; steipete (medium confidence) for the merged sibling edit preservation invariant.

Priority: P0
Reviewed head: c006cc02a3277b9dfb90fc7642f8766b3ee3c482

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-evidenced repair with strong runtime proof; the remaining material confidence step is a refresh against current main.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body shows an after-fix production-tool run against real files and confirms that unchanged context bytes survive while the intended changed lines update; private paths and other sensitive details should remain redacted in any future proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body shows an after-fix production-tool run against real files and confirms that unchanged context bytes survive while the intended changed lines update; private paths and other sensitive details should remain redacted in any future proof.
Evidence reviewed 6 items Patch boundary: The PR adds context-to-old-line indexes while parsing update hunks, then reconstructs replacement output from the matched original lines only for declared context. Added lines remain patch-authored.
Write-back implementation: keepContextBytes receives the matched file lines, match offset, old-pattern length, emitted replacement lines, and parser mapping; it falls back to the patch line for additions or invalid mappings.
Regression coverage: The branch adds direct cases for trailing whitespace, normalized punctuation, tab-indented context, end-of-file replacement, repeated-context chunks, moves, and fuzzy-context insertion behavior.
Findings None None.
Security None None.

How this fits together

OpenClaw’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]
Loading

Before merge

  • Resolve merge risk (P1) - GitHub reports the branch as behind current main; before merge, refresh it against current main and rerun the focused apply_patch cases so this mapping is checked with the latest line-ending implementation.
Agent review details

Security

None.

PR surface

Source +33, Tests +185. Total +218 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 34 1 +33
Tests 2 185 0 +185
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 219 1 +218

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #116124
Summary: This PR is the linked candidate fix for the open report about tolerant apply_patch rewriting unchanged hunk-context bytes; the earlier edit and CRLF fixes are related sibling work, not duplicates.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Land the focused context-byte preservation after rebasing onto current main and confirming the new cases and existing line-ending coverage still pass on that exact head.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Land the focused context-byte preservation after rebasing onto current main and confirming the new cases and existing line-ending coverage still pass on that exact head.

Do we have a high-confidence way to reproduce the issue?

Yes. The PR provides a high-confidence real-filesystem reproduction through the production createApplyPatchTool execution path, with before-and-after output for normalized context and byte-sensitive source files.

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 apply_patch with the already-merged sibling edit invariant without changing explicitly added or replaced patch lines.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 1165be39fffc.

Labels

Label justifications:

  • P0: This PR repairs a default agent coding path that can silently rewrite unrelated file bytes while reporting success, including changes that can make source files invalid.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body shows an after-fix production-tool run against real files and confirms that unchanged context bytes survive while the intended changed lines update; private paths and other sensitive details should remain redacted in any future proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body shows an after-fix production-tool run against real files and confirms that unchanged context bytes survive while the intended changed lines update; private paths and other sensitive details should remain redacted in any future proof.

Evidence

What I checked:

Likely related people:

  • yetval: Authored the linked report and the recently merged apply_patch CRLF-preservation work on the same parser and update-writer path. (role: recent main-path contributor; confidence: high; commits: d258fa8861fa, 8ae0a896bcf9; files: src/agents/apply-patch.ts, src/agents/apply-patch-update.ts, src/agents/apply-patch.test.ts)
  • vincentkoc: Added the branch’s follow-up preservation coverage, performed the two main merges into the branch, and is assigned in the supplied PR timeline. (role: recent branch contributor and reviewer; confidence: high; commits: 38e0fb6832c7, 08af468ef711, c006cc02a327; files: src/agents/apply-patch-context-bytes.test.ts, src/agents/apply-patch.test.ts)
  • steipete: Merged PR fix: improve agent runtime correctness from upstream Pi #99949 introduced the analogous unchanged-byte preservation behavior for the sibling edit implementation that this PR follows. (role: sibling-invariant introducer; confidence: medium; commits: 5ea80c8d80fd; files: src/agents/sessions/tools/edit-diff.ts, src/agents/sessions/tools/edit-replacements.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase or merge current main into the branch and rerun the focused apply_patch regression cases on that exact head.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-07-29T23:52:11.398Z sha d6a9232 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-29T23:58:08.116Z sha d6a9232 :: needs maintainer review before merge. :: none

@vincentkoc vincentkoc self-assigned this Jul 30, 2026
* 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)
@vincentkoc
vincentkoc merged commit 8ce1e18 into openclaw:main Jul 30, 2026
122 of 124 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

apply_patch rewrites bytes on hunk context lines it never marked as changed

2 participants