Skip to content

fix(edit): recover malformed replacement string literals - #153692

Merged
obviyus merged 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/edit-string-json-repair
Sep 20, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/edit-string-json-repair

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Related: #153486

What Problem This Solves

Fixes: replacement lists sent to the edit tool as a JSON string fail before editing when their string literals contain unescaped control characters or invalid backslash escapes.

User Impact

The tool can recover those bounded encoding errors and apply the complete replacement set. Valid JSON escapes, ordinary arrays, and valid JSON-string arrays retain their existing meaning. Incomplete structures are not completed or partially recovered. Existing legacy-pair fallback and whole-set mutation checks are unchanged.

This does not improve the generic malformed-JSON diagnostic requested in #153486; that issue remains open. It is not universal malformed-input recovery.

Why This Change Was Made

The existing argument preparer now uses the existing JSON string-literal repair owner with valid-control-escape preservation, followed by a complete JSON parse and the unchanged array/schema checks. It does not complete partial structures, unwrap object wrappers, change shared-parser defaults, or relax provider transport parsing and filesystem authority.

Evidence

  • Actual supported pnpm openclaw agent exec, a maintained local Responses HTTP fixture, the registered edit tool, and independent file readback: a valid outer tool call containing raw newlines in the nested replacement string produced an error result and unchanged bytes before the fix, then applied the exact requested bytes afterward.
  • Thirteen CLI cases cover canonical arrays, valid string arrays, literal/control escapes, mixed recovery, invalid backslashes, truncated sets, non-array wrappers, missing/overlapping targets, workspace containment, strict outer-argument rejection, and the existing legacy-pair fallback. The repaired candidate passed all thirteen with actual tool results captured in the next provider request and retained transcript.
  • Malformed outer arguments remain rejected before any tool. The existing replay-safe response-repair retry remains unchanged; no tool result or file mutation occurs in that control.
  • 134 focused edit/diff/formatting/parser tests passed; the new regression fails on original normalization. Scoped type-aware lint, formatting, whitespace, both source line-limit ratchets, executable-runtime builds, and supported-wrapper readiness passed.

The provider is a controlled local fixture. No production-frequency, particular live-model, or native-harness compatibility claim is made.

…them

Models that send the edit tool's replacements as a JSON string produced a
malformed payload whenever a replacement value spanned lines, because the raw
newline is not a legal control character inside a JSON string literal. The bare
JSON.parse threw, the catch swallowed it, and the whole edit set was dropped:
the model got a generic 'edits must contain at least one replacement' error and
the turn was wasted.

The string is a completed tool-call argument buffer, so route it through the
existing repair owner in its authoritative mode before parsing. Valid payloads
are unaffected: repairJson leaves them byte-identical, and structurally corrupt
payloads still fail as before.
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 20, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 20, 2026
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 20, 2026, 10:52 AM ET / 14:52 UTC (Revision 4).

ClawSweeper review

What this changes

The edit tool repairs malformed string literals in serialized replacement lists while preserving valid escapes, with regression coverage for exact file contents.

Merge readiness

✅ Ready for maintainer review

Keep open: current main and the latest release still reject these recoverable replacement strings. No blocking defect was found, and the prior request to preserve the separate diagnostic issue is resolved.

Priority: P2
Reviewed head: 5516d3fbb27f98f330c394e99631100d40630261

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful file-content coverage and reported production-path proof; no additional blocking change was identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied body records supported CLI execution through a real local HTTP transport and the registered edit tool, with failed unchanged-file behavior before the fix and exact file readback afterward; thirteen scenarios cover recovery and rejection boundaries. These are reported production-path observations, not reviewer-executed runs.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied body records supported CLI execution through a real local HTTP transport and the registered edit tool, with failed unchanged-file behavior before the fix and exact file readback afterward; thirteen scenarios cover recovery and rejection boundaries. These are reported production-path observations, not reviewer-executed runs.
Evidence reviewed 8 items Verified introduced change: The pinned merge-base-to-head production diff adds the existing repair helper with preserveValidControlEscapes enabled. Array acceptance, legacy-pair handling, validation, and execution remain unchanged.
Still necessary on main: Fetched main still calls JSON.parse directly on string-form edits; raw control characters and invalid escapes therefore remain unrecovered.
Latest release comparison: The supplied latest release, v2026.9.5, also uses direct JSON.parse for serialized edits; it does not contain this recovery.
Findings None None.
Security None None.

How this fits together

The edit tool receives model-requested file replacements through the agent runtime. Its argument preparer normalizes inputs before schema validation, target matching, and queued file writes.

flowchart TD
  A[Model edit request] --> B[Argument preparation]
  B --> C[Repair serialized replacement strings]
  C --> D[Complete parsing and schema validation]
  D --> E[Validate all replacement targets]
  E --> F[Queued file write and readback]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +2, Tests +16. Total +18 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 4 2 +2
Tests 1 16 0 +16
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 20 2 +18

Review metrics

None.

Technical review

Best possible solution:

Keep bounded string repair in the existing edit argument preparer, preserving literal text and complete-set validation while leaving clearer unrecoverable-input diagnostics to the related issue.

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

Yes: current-main normalization directly parses serialized edits, so a replacement string containing a raw newline fails before editing. The PR reports a matching before/after CLI run; this read-only review did not rerun it.

Is this the best way to solve the issue?

Yes: reusing the existing string-literal repair owner with escape preservation is a narrow fix that retains complete parsing and downstream validation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2f0ac62d528d.

Labels

Label justifications:

  • P2: This bounded repair prevents avoidable failed edit calls without changing configuration or filesystem permissions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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): The supplied body records supported CLI execution through a real local HTTP transport and the registered edit tool, with failed unchanged-file behavior before the fix and exact file readback afterward; thirteen scenarios cover recovery and rejection boundaries. These are reported production-path observations, not reviewer-executed runs.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied body records supported CLI execution through a real local HTTP transport and the registered edit tool, with failed unchanged-file behavior before the fix and exact file readback afterward; thirteen scenarios cover recovery and rejection boundaries. These are reported production-path observations, not reviewer-executed runs.

Evidence

What I checked:

  • Verified introduced change: The pinned merge-base-to-head production diff adds the existing repair helper with preserveValidControlEscapes enabled. Array acceptance, legacy-pair handling, validation, and execution remain unchanged. (src/agents/sessions/tools/edit.ts:157, 5516d3fbb27f)
  • Still necessary on main: Fetched main still calls JSON.parse directly on string-form edits; raw control characters and invalid escapes therefore remain unrecovered. (src/agents/sessions/tools/edit.ts:156, 2f0ac62d528d)
  • Latest release comparison: The supplied latest release, v2026.9.5, also uses direct JSON.parse for serialized edits; it does not contain this recovery. (src/agents/sessions/tools/edit.ts:156, ec9c1a13db89)
  • Existing repair owner and dependency boundary: repairJson escapes raw string control characters and invalid backslashes without completing structures. Its preservation option disables the Windows-path heuristic. This implementation is owned by the target repository's AI package; no Codex dependency contract or native-harness compatibility claim is involved. (packages/ai/src/utils/json-parse.ts:40, 5516d3fbb27f)
  • Production integration and regression coverage: The agent loop invokes argument preparation before validation. The new edit test checks actual file readback after mixed malformed newlines, valid control escapes after a path-like prefix, and literal backslash-n replacements. No new test-only production seam is introduced. (src/agents/sessions/tools/edit.test.ts:393, 5516d3fbb27f)
  • Recorded production-path observations: The complete supplied PR body at context sourceRevision e3bf417dfda1187dd49eba69c0ea0d4c3b782ffc51a629f9b9ba21ee70cf3103 reports supported CLI execution through a local Responses HTTP fixture and the registered edit tool: unchanged bytes with an error before the fix, exact requested bytes afterward, and thirteen passing scenarios including malformed-input rejection and containment. This review inspected the reported observations; it did not execute the fixture or independently inspect the retained transcripts. (5516d3fbb27f)

Likely related people:

  • lraesly: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (3 earlier review cycles)
  • reviewed 2026-09-20T12:49:21.638Z sha 78f9654 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-20T13:00:24.156Z sha 78f9654 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-20T13:19:15.956Z sha 78f9654 :: needs changes before merge. :: none

@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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 20, 2026
@obviyus obviyus self-assigned this Sep 20, 2026
@obviyus obviyus changed the title fix(agents): repair string-form edit arguments instead of discarding them fix(edit): recover malformed replacement string literals Sep 20, 2026
@obviyus

obviyus commented Sep 20, 2026

Copy link
Copy Markdown
Collaborator

landpr-approve-unrelated-red
pr: 153692
head: 5516d3f
run: 35517378321 attempt: 1
failed: checks-node-compact-large-27 job=106095621044 conclusion=failure
failed: checks-node-compact-large-30 job=106095622201 conclusion=failure
check: openclaw/ci-gate

@obviyus
obviyus merged commit 75b463e into openclaw:main Sep 20, 2026
234 of 238 checks passed
@obviyus

obviyus commented Sep 20, 2026

Copy link
Copy Markdown
Collaborator

Merged as 75b463e. Thanks @wangmiao0668000666 for the fix.

Serialized edit replacement lists now recover bounded string-literal encoding errors while preserving valid escapes and the existing schema/filesystem checks. The supported CLI before/after proof covered 13 cases; 134 focused tests passed and the regression failed before the fix. Exact-head review found no blocking issues. CI finished with two causally unrelated test failures, covered by the recorded scoped exception; it was not all green.

#153486 remains open because its broader malformed-input diagnostic request is not resolved by this change.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@obviyus Thank you for reviewing and merging #153692! I appreciate the careful review and the help getting this fix landed.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…3692)

Related: openclaw#153486

## What Problem This Solves

Fixes: replacement lists sent to the `edit` tool as a JSON string fail before editing when their string literals contain unescaped control characters or invalid backslash escapes.

## User Impact

The tool can recover those bounded encoding errors and apply the complete replacement set. Valid JSON escapes, ordinary arrays, and valid JSON-string arrays retain their existing meaning. Incomplete structures are not completed or partially recovered. Existing legacy-pair fallback and whole-set mutation checks are unchanged.

This does not improve the generic malformed-JSON diagnostic requested in openclaw#153486; that issue remains open. It is not universal malformed-input recovery.

## Why This Change Was Made

The existing argument preparer now uses the existing JSON string-literal repair owner with valid-control-escape preservation, followed by a complete JSON parse and the unchanged array/schema checks. It does not complete partial structures, unwrap object wrappers, change shared-parser defaults, or relax provider transport parsing and filesystem authority.

## Evidence

- Actual supported `pnpm openclaw agent exec`, a maintained local Responses HTTP fixture, the registered edit tool, and independent file readback: a valid outer tool call containing raw newlines in the nested replacement string produced an error result and unchanged bytes before the fix, then applied the exact requested bytes afterward.
- Thirteen CLI cases cover canonical arrays, valid string arrays, literal/control escapes, mixed recovery, invalid backslashes, truncated sets, non-array wrappers, missing/overlapping targets, workspace containment, strict outer-argument rejection, and the existing legacy-pair fallback. The repaired candidate passed all thirteen with actual tool results captured in the next provider request and retained transcript.
- Malformed outer arguments remain rejected before any tool. The existing replay-safe response-repair retry remains unchanged; no tool result or file mutation occurs in that control.
- 134 focused edit/diff/formatting/parser tests passed; the new regression fails on original normalization. Scoped type-aware lint, formatting, whitespace, both source line-limit ratchets, executable-runtime builds, and supported-wrapper readiness passed.

The provider is a controlled local fixture. No production-frequency, particular live-model, or native-harness compatibility claim is made.

Co-authored-by: Ayaan Zaidi <[email protected]>
@wangmiao0668000666
wangmiao0668000666 deleted the fix/edit-string-json-repair branch October 28, 2026 07:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

2 participants