Skip to content

fix: preserve untouched bytes outside fuzzy-match span in edit tool (#116459) - #116509

Merged
vincentkoc merged 2 commits into
openclaw:mainfrom
licheer-zte:fix/fuzzy-edit-preserve-untouched-bytes-116459
Jul 31, 2026
Merged

vincentkoc merged 2 commits into
openclaw:mainfrom
licheer-zte:fix/fuzzy-edit-preserve-untouched-bytes-116459

Conversation

@licheer-zte

@licheer-zte licheer-zte commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #116459

What Problem This Solves

Fixes a data-loss bug where a fuzzy-matched edit call could silently rewrite
unrelated bytes on the matched line. A harmless formatting mismatch in
oldText, such as a plain space instead of NBSP, caused the write path to
rebuild the line from NFKC-normalized content and alter fullwidth punctuation,
halfwidth katakana, smart quotes, dashes, and other source text the edit did not
target.

Why This Change Was Made

Fuzzy normalization remains the authoritative lookup contract, but normalized
matches are now translated back to stable boundaries in the original source.
The mapper:

  • verifies grapheme-segment NFKC against whole-string NFKC before using it;
  • maps complete expansions and contractions back to their full source range;
  • rejects matches that start or end inside an NFKC expansion;
  • uses directional boundaries around trimmed suffixes so EOF and line-end bytes
    are not accidentally consumed; and
  • applies exact and fuzzy replacements directly to the original content.

Host workspace edits, sandbox edits, and TUI previews all use this shared
mapping path.

User Impact

Fuzzy edits now preserve every byte outside the selected source span. Ambiguous
partial-normalization matches fail with an actionable error instead of guessing
and corrupting a workspace file.

Evidence

Reviewed head: bba4f5f76cd0467e8e0afb4daa198750154a5085

Focused regression proof

src/agents/sessions/tools/edit-diff.test.ts
  23/23 passed

src/agents/sessions/tools/edit.test.ts
  48/48 passed

src/agents/agent-tools.sandbox-mounted-paths.workspace-only.test.ts
  9/9 passed

Total: 80/80 passed

Coverage includes real escaped Unicode, NBSP, smart quotes, complete and partial
NFKC expansions, combining sequences, supplementary characters, trailing bytes
at EOF, interior trim folding, CRLF, mixed exact/fuzzy batches, real host
write/readback, returned diff/patch round-trip, TUI preview, and the real sandbox
filesystem bridge.

Real edit write/readback

The production createEditTool test writes a real temporary workspace file,
executes the fuzzy edit, reads the file back, and verifies:

before:
export const RETRY<NBSP>MAX = 3; // 再試行(最大3回)アイウ — 設定

after:
export const RETRY_MAX = 5; // 再試行(最大3回)アイウ — 設定

The returned diff retains the original fullwidth punctuation, halfwidth
katakana, and em dash, and applying the returned patch reproduces the exact
on-disk bytes.

Review and static proof

  • git diff --check: passed
  • oxfmt --check on all five touched files: passed
  • fresh Codex autoreview: no findings, patch correct, confidence 0.94
  • sanitized AWS allocation was attempted with public networking, no Tailscale,
    no instance role, and no hydration; allocation failed before code execution
    because the coordinator had no EC2 credential source
  • secretless exact-head pull-request CI is running as the remote fallback

[AI-assisted]

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Jul 30, 2026
@licheer-zte licheer-zte reopened this Jul 30, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 30, 2026, 11:10 PM ET / July 31, 2026, 03:10 UTC.

ClawSweeper review

What this changes

The PR maps fuzzy edit matches from normalized text back to original source spans so host, sandbox, and preview edits replace only the requested bytes while retaining unrelated Unicode and line-ending bytes.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This PR remains necessary: it is the active candidate fix for the linked fuzzy-edit data-loss report, and the latest review cycle’s prior blockers are addressed. The contributor and a member supplied focused real write/readback evidence for the current head; the remaining action is normal maintainer review of the compatibility boundary before merge.

Priority: P1
Reviewed head: bba4f5f76cd0467e8e0afb4daa198750154a5085

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has targeted shared-path coverage and convincing current-head runtime proof, with a compatibility-focused merge refresh still warranted.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.
Evidence reviewed 5 items Linked bug and active fix candidate: The PR body uses closing syntax for the linked report and changes the same fuzzy replacement path described there: rebuilding touched lines from normalized content could alter bytes outside the requested span.
Prior review continuity: The latest completed ClawSweeper review at the current head recorded no outstanding findings after earlier cycles required same-line span mapping and rejection of partial NFKC expansion boundaries.
Real behavior proof: A member’s current-head runtime note reports direct production createEditTool writes to temporary host files, byte-identical untouched Unicode suffixes, patch round-tripping, and safe rejection of a partial ligature match before a complete-span retry succeeds.
Findings None None.
Security None None.

How this fits together

The agent-facing edit tool searches workspace content for requested text, applies replacements, then returns a diff and patch describing the write. Fuzzy matching is used when visually equivalent Unicode, punctuation, spaces, or trailing whitespace prevent an exact match; this PR changes the bridge from fuzzy match coordinates to source-file mutation.

flowchart LR
  A[Agent edit request] --> B[Exact or fuzzy matching]
  B --> C[Normalized match span]
  C --> D[Original source boundaries]
  D --> E[Workspace or sandbox write]
  D --> F[Diff and patch preview]
Loading

Before merge

  • Resolve merge risk (P1) - Fuzzy matching is compatibility-sensitive: the PR intentionally rejects normalized matches that begin or end inside an NFKC expansion, so maintainers should confirm the actionable error remains limited to ambiguous partial spans while complete normalization-equivalent spans continue to work.
  • Resolve merge risk (P1) - The branch is based on an older main SHA than the supplied current main; refresh the merge result and rerun focused coverage at the merged head before landing.
Agent review details

Security

None.

PR surface

Source +98, Tests +202. Total +300 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 195 97 +98
Tests 3 202 0 +202
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 397 97 +300

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/agents/agent-tools.sandbox-mounted-paths.workspace-only.test.ts, serialized state: src/agents/sessions/tools/edit-diff.ts, serialized state: src/agents/sessions/tools/edit-replacements.ts, serialized state: src/agents/sessions/tools/edit.test.ts, unknown-data-model-change: src/agents/sessions/tools/edit-diff.test.ts, unknown-data-model-change: src/agents/sessions/tools/edit-diff.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh and merge with boundary coverage (recommended)
    Rebase or refresh against current main, then retain the focused checks proving complete-span fuzzy edits work and partial NFKC spans fail with the actionable error.
  2. Pause for contract clarification
    Pause only if maintainers want fuzzy matching to support partial normalization expansions rather than reject them, because that requires choosing a different user-visible matching contract.

Technical review

Best possible solution:

Land a source-span-based fuzzy replacement path that preserves every untouched source byte, accepts complete normalization-equivalent matches, and returns a clear retry instruction only for ambiguous partial-normalization boundaries.

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

Yes. The linked report gives a concrete fuzzy edit using a plain space against an NBSP-containing source line, and the supplied current-head evidence shows direct host-file write/readback plus the shared sandbox bridge coverage.

Is this the best way to solve the issue?

Yes. Mapping fuzzy-match coordinates back to original source boundaries is the narrowest shared fix because host writes, sandbox edits, and previews already converge on the same edit-diff path; rebuilding normalized touched lines cannot preserve unrelated bytes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0a44e8bb5f7b.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The patch addresses an agent edit workflow that can silently modify unrelated workspace-file bytes on a normal fuzzy-match path.
  • merge-risk: 🚨 compatibility: The fuzzy-match contract changes for ambiguous partial Unicode-normalization spans, which now fail rather than guessing a source range.
  • 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 (live_output): A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.
  • proof: sufficient: Contributor real behavior proof is sufficient. A member supplied current-head production createEditTool host-file write/readback evidence, verified byte-identical untouched Unicode, validated the returned patch, and showed an ambiguous partial-NFKC edit rejects without changing the file; redact paths and private values if any further evidence is posted.

Evidence

What I checked:

  • Linked bug and active fix candidate: The PR body uses closing syntax for the linked report and changes the same fuzzy replacement path described there: rebuilding touched lines from normalized content could alter bytes outside the requested span. (src/agents/sessions/tools/edit-diff.ts:1, bba4f5f76cd0)
  • Prior review continuity: The latest completed ClawSweeper review at the current head recorded no outstanding findings after earlier cycles required same-line span mapping and rejection of partial NFKC expansion boundaries. (src/agents/sessions/tools/edit-diff.ts:1, bba4f5f76cd0)
  • Real behavior proof: A member’s current-head runtime note reports direct production createEditTool writes to temporary host files, byte-identical untouched Unicode suffixes, patch round-tripping, and safe rejection of a partial ligature match before a complete-span retry succeeds. (src/agents/sessions/tools/edit.test.ts:1, bba4f5f76cd0)
  • Focused regression coverage: The PR adds coverage at the shared edit-diff layer, the production host edit-tool path, and the sandbox filesystem bridge, matching the claimed host/sandbox/preview ownership boundary. (src/agents/agent-tools.sandbox-mounted-paths.workspace-only.test.ts:138, bba4f5f76cd0)
  • Feature-history signal: The current-head follow-up commit is authored by vincentkoc and specifically names stable source-boundary mapping, connecting that reviewer to the final compatibility behavior. (src/agents/sessions/tools/edit-diff.ts:1, bba4f5f76cd0)

Likely related people:

  • vincentkoc: Assigned to this PR, authored the current-head follow-up that establishes stable source boundaries, and supplied direct runtime proof for the affected edit-tool behavior. (role: recent area contributor; confidence: medium; commits: bba4f5f76cd0; files: src/agents/sessions/tools/edit-diff.ts, src/agents/sessions/tools/edit.test.ts)
  • licheer-zte: Authored the original fuzzy-edit preservation change and associated regression coverage; included because the current implementation history in the supplied PR context directly attributes the initial patch to this contributor. (role: initial implementation contributor; confidence: medium; commits: c36398a22dfc; files: src/agents/sessions/tools/edit-diff.ts, src/agents/sessions/tools/edit-diff.test.ts)

Rank-up moves

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

  • Refresh the branch against current main and rerun the focused edit-diff, host-edit, and sandbox-bridge checks on the merged result.
  • Confirm the partial-normalization error remains actionable while complete NFKC-equivalent spans remain accepted.

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 (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-30T19:28:41.286Z sha 551489d3611459d039a798c345e51ef0b4798121 :: needs real behavior proof before merge. :: [P1] Map same-line normalization offsets before slicing | [P2] Split the unrelated security-scanner change
  • reviewed 2026-07-30T20:11:19.538Z sha 551489d3611459d039a798c345e51ef0b4798121 :: needs real behavior proof before merge. :: [P1] Map same-line normalization offsets before slicing | [P2] Remove the unrelated security-scanner change
  • reviewed 2026-07-30T20:23:27.046Z sha 93660795b777633357800a71d81385ab5e1df54e :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-30T20:30:56.417Z sha 93660795b777633357800a71d81385ab5e1df54e :: needs real behavior proof before merge. :: [P1] Handle partial NFKC expansions when translating fuzzy spans
  • reviewed 2026-07-31T02:15:19.925Z sha 93660795b777633357800a71d81385ab5e1df54e :: needs real behavior proof before merge. :: [P1] Reject fuzzy spans inside NFKC expansions
  • reviewed 2026-07-31T02:50:51.076Z sha 247c30de5fb38b092238d4207b28c9e3e7a1a1c4 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-31T03:00:47.843Z sha bba4f5f :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-31T03:05:26.275Z sha bba4f5f :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 30, 2026
@licheer-zte
licheer-zte force-pushed the fix/fuzzy-edit-preserve-untouched-bytes-116459 branch from 551489d to f3910da Compare July 30, 2026 20:17
@openclaw-barnacle openclaw-barnacle Bot added channel: signal Channel integration: signal size: XS and removed agents Agent runtime and tooling size: L labels Jul 30, 2026
@licheer-zte
licheer-zte force-pushed the fix/fuzzy-edit-preserve-untouched-bytes-116459 branch from f3910da to 8648fb2 Compare July 30, 2026 20:17
@licheer-zte
licheer-zte requested review from a team as code owners July 30, 2026 20:17
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: imessage Channel integration: imessage channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web labels Jul 30, 2026
When an edit tool call falls back to fuzzy matching (e.g. plain space vs
NBSP, straight quotes vs smart quotes), the entire overlapped line was
rebuilt from the NFKC-normalized copy, silently destroying unrelated
bytes on that line — fullwidth punctuation, halfwidth katakana, em-dashes,
and other Unicode characters outside the edited span.

Root cause:
- applyEdits() set replacementBaseContent to
  normalizeForFuzzyMatch(normalizedContent) when any edit needed fuzzy
  matching.
- applyReplacementsPreservingUnchangedLines then emitted untouched lines
  from the original content but rebuilt touched lines wholesale from the
  normalized base, applying NFKC folding to bytes the edit never
  referenced.

Fix:
- normalizeForFuzzyMatch now optionally returns an offset map that
  translates every normalized position back to the original text.
- fuzzyFindText uses this map to translate match indices from fuzzy-
  normalized coordinates to original-content coordinates.
- applyEdits keeps replacementBaseContent as the original (LF-normalized)
  content and uses direct applyReplacements instead of the line-preserving
  variant. Touch-untouched line distinction is no longer needed because
  replacements splice at byte granularity in the original content.

Fixes openclaw#116459
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc

Copy link
Copy Markdown
Member

External runtime proof

Exact head: bba4f5f76cd0467e8e0afb4daa198750154a5085

I invoked the production createEditTool directly from the checked-out head, outside Vitest, against temporary files on the host filesystem. The tool performed the write, the script read the files back from disk, and it validated the returned unified patch with diff.applyPatch.

Fuzzy Unicode edit

Invocation:

{
  "path": "unicode.ts",
  "edits": [
    {
      "oldText": "export const RETRY MAX = 3;",
      "newText": "export const RETRY_MAX = 5;"
    }
  ]
}

Disk readback:

export const RETRY_MAX = 5; // 再試行(最大3回)アイウ — 設定

Runtime assertions:

readbackMatchesExpected: true
untouchedUnicodeSuffixByteIdentical: true
returnedPatchReproducesReadback: true

Returned diff:

-1 export const RETRY MAX = 3; // 再試行(最大3回)アイウ — 設定
+1 export const RETRY_MAX = 5; // 再試行(最大3回)アイウ — 設定

Returned patch:

--- unicode.ts
+++ unicode.ts
@@ -1,1 +1,1 @@
-export const RETRY MAX = 3; // 再試行(最大3回)アイウ — 設定
+export const RETRY_MAX = 5; // 再試行(最大3回)アイウ — 設定

Ambiguous partial-NFKC failure and retry

Rejected invocation:

{"path":"expansion.ts","edits":[{"oldText":"f","newText":"x"}]}

Observed error:

The fuzzy match in expansion.ts crosses an ambiguous Unicode-normalization or trimmed-whitespace boundary. Copy the exact source text or use a span whose normalized boundaries map cleanly.

The disk readback remained byte-identical to const value = fi;\n.

Retry invocation:

{"path":"expansion.ts","edits":[{"oldText":"fi","newText":"pair"}]}

Retry disk readback and returned diff:

const value = pair;
-1 const value = fi;
+1 const value = pair;

Runtime assertions:

rejectionPreservedFileByteIdentically: true
returnedPatchReproducesRetryReadback: true

@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@vincentkoc

Copy link
Copy Markdown
Member

Current-main merge-result validation is complete. bba4f5f76cd0467e8e0afb4daa198750154a5085 merges cleanly with origin/main 7bc216394a19db95fe5e7e6256ba3ce4fe0f334e; synthetic merge tree: 84448c3121e764551ae27fb860abb845f9dd2ff4. Main has no drift in any of the five touched edit/host/sandbox files since the reviewed base, so the exact-head 80/80 focused proof applies unchanged.

@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. 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.

edit: a fuzzy-matched edit rewrites unrelated bytes on the matched line

2 participants