Skip to content

fix(agents): clarify errors for malformed JSON-string edits - #163577

Merged
altaywtf merged 2 commits into
openclaw:mainfrom
GoldArowana:fix/edit-json-parse-diagnostic
Oct 6, 2026
Merged

altaywtf merged 2 commits into
openclaw:mainfrom
GoldArowana:fix/edit-json-parse-diagnostic

Conversation

@GoldArowana

@GoldArowana GoldArowana commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #153486

What Problem This Solves

The edit tool reports a generic replacement validation error when a JSON-string edits value cannot be parsed, hiding the actual problem.

User Impact

Malformed serialized edits now receive a JSON parse hint before editing starts. Valid legacy oldText/newText replacements still work, including deletion with an empty newText.

Why This Change Was Made

Surface parse failures after the existing JSON escape repair only when no complete legacy pair is available. Preserve the existing fallback and valid-input behavior. The restored merge integrates upstream snapshot c190df12716a17d23a1c00eaf106044d2f2c9317, retaining all six PR regressions and upstream's consolidated legacy-input cases.

Evidence

Published head: 28fb89aa96a2303eff09a41f096c0ed9b3f57968, tree b69c46c9d35afdb4236144e97b340a1f926feba8. One normal Git push updated the original fork branch on 2026-10-04. Git and GitHub both confirmed the exact head; the original commit bytes, ordered parents, and author/committer Jin Long <[email protected]> were preserved.

  • Four malformed-input regressions exercise the real tool invocation boundary, assert that execution never starts, and leave the file unchanged. Two additional cases preserve complete legacy-pair replacement and deletion.
  • The same candidate source passed 85 focused tests across four edit-related files in 40.7 seconds on Linux, plus production Knip files/dependencies, formatting, lint, and diff checks. This unchanged-source proof was verified and reused from the continuation package.
  • Earlier Linux cloud validation passed core production types and 27/27 consuming test-type graphs, taking 65.33 and 1324.51 seconds respectively. The earlier resource-killed type attempts remain recorded as failures.
  • All 34 native changed-check plan items completed in stages: 24 + 1 + 9. The original aggregate exited 1 at dead-export cache initialization (ENOENT) after 24 successful items. With the task-local tool/cache environment corrected, all three native Knip export scans passed in 112.12 seconds, followed by the nine remaining checks. The original aggregate is not reported as exit 0; source inputs were unchanged and no guard was skipped.
  • The actual native pre-commit content/format hook passed on the two-file staged delta against c190df127…, leaving the candidate tree unchanged. The commit was restored intact without creating or rewriting a commit.
  • Independent source review found no actionable P0–P2 issues. The earlier autoreview helper had no findings but one context-incomplete part; it is not counted as a complete helper review.
  • Full local build, full local test suite, candidate-head agent CLI runtime, live LLM, and live Gateway transport were not run as part of local validation. The historical CLI fixture evidence below applies only to 59d3a13….

Current-head CI

Verified on 2026-10-04 13:15 UTC for exact head 28fb89aa96a2303eff09a41f096c0ed9b3f57968: CI run 37204368736, CodeQL, and CodeQL Critical Quality completed successfully. openclaw/ci-gate, dependency-review, and security-sensitive-review statuses are successful. The main CI run recorded 41 successful and 26 skipped jobs, with no failed jobs; skipped checks are not counted as passes. The earlier local validation and historical head59 CI evidence retain their separate scope.

Validation commands and environment

The earlier Linux validation checkout used its own frozen dependencies with Node 24.19.0 and pnpm 12.5.1. The initial aggregate's nested launcher selected global pnpm 11.19.0; follow-up commands used the verified task-local pnpm 12.5.1 entry and writable cache. The final publication used a separate Debian 13 cloud executor without installing dependencies or repeating valid checks.

node scripts/run-vitest.mjs run \
  src/agents/sessions/tools/edit.legacy-input.test.ts \
  src/agents/sessions/tools/edit.test.ts \
  src/agents/sessions/tools/edit-diff.test.ts \
  src/agents/sessions/tools/edit-formatting.test.ts \
  --maxWorkers=1

node scripts/check-changed.mjs --base c190df12716a17d23a1c00eaf106044d2f2c9317 -- \
  src/agents/sessions/tools/edit.ts src/agents/sessions/tools/edit.legacy-input.test.ts

# Follow-up native checks on unchanged source:
node --import tsx scripts/check-deadcode-exports.mts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json \
  src/agents/sessions/tools/edit.legacy-input.test.ts src/agents/sessions/tools/edit.ts
node scripts/check-native-state-schema-version.mjs
pnpm check:database-first-legacy-stores
pnpm check:media-download-helpers
pnpm check:runtime-sidecar-loaders
pnpm check:import-cycles
pnpm lint:webhook:no-low-level-body-read
pnpm lint:auth:no-pairing-store-group
pnpm lint:auth:pairing-account-scope

Historical runtime verification (59d3a13)

Verified head 59d3a13a81d7fbac7999f31d8099998e739d462d on macOS with Node 24.19.0 through the supported local agent CLI:

pnpm openclaw --profile edit-json-proof agent --local --agent main \
  --session-id edit-json-proof \
  --message 'Run the three supplied edit fixture cases, then finish.' \
  --thinking off --timeout 180 --json

The run used isolated config, state, and workspace directories. A localhost OpenAI-compatible HTTP fixture supplied three deterministic edit calls. The OpenClaw CLI, openclaw agent harness, argument preparation, filesystem operations, and tool-result transport ran unchanged. Only model responses were simulated; this is not live LLM or Gateway transport proof.

Each file initially contained "alpha\nbefore\nomega\n". The following results were captured from the next HTTP request OpenClaw sent to the provider, rather than inferred from the final assistant text:

1. Arguments: {"path":"malformed.txt","edits":"[{bad json"}
   Model-visible tool result:
   Could not parse edits as JSON. Provide a complete JSON array of replacements.
   File afterward: "alpha\nbefore\nomega\n"
   SHA-256 before and after:
   56fa7c50da8fd7051b598876229b707046f59cefc388ed95fc62ff83aeda4dc7

2. Arguments: {"path":"legacy-replace.txt","edits":"[{bad json","oldText":"before","newText":"after"}
   Model-visible tool result:
   Successfully replaced 1 block(s) in legacy-replace.txt.
   File afterward: "alpha\nafter\nomega\n"

3. Arguments: {"path":"legacy-delete.txt","edits":"[{bad json","oldText":"before","newText":""}
   Model-visible tool result:
   Successfully replaced 1 block(s) in legacy-delete.txt.
   File afterward: "alpha\n\nomega\n"

The persisted agent transcript independently records these three tool results with isError: true, false, and false. The run completed four assistant turns, exited 0, and took 15.783 seconds wall time after the runtime build. No tracked files changed.

Historical CI failure

The type-check job failed at src/gateway/worker-environments/worker-turn-launcher.claim-recovery.test.ts:346: appendMessage does not exist on Promise<SessionManager>.

CI tested merge commit 3abe74c4a4064ef7136c9dab8e11469517286dde. The failing test file is byte-identical to its upstream parent 3932cbe4c91c5f3838a141f6a8cdeeb48fdf50b6 (blob 03590b533fc515682a7ef9072978adb10db25087). The merge delta contains only the two edit-related files in this PR. This identifies a separate upstream test error in that historical run; it does not describe current-head CI.

@clawsweeper

clawsweeper Bot commented Oct 2, 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.

@GoldArowana
GoldArowana marked this pull request as ready for review October 2, 2026 14:35
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Oct 2, 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 Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 12:48 PM ET / 16:48 UTC (Revision 4).

ClawSweeper review

What this changes

The agent’s file-edit tool reports malformed JSON-string replacements clearly while preserving legacy replacement and deletion inputs.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main and the latest release still swallow malformed serialized-edit parse errors. The updated patch has no actionable findings, and the earlier runtime proof remains applicable to its unchanged preparation and execution logic.

Priority: P2
Reviewed head: 51213dceafabe3270bfdb5c1b3bbf5471064ae3f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct repair with meaningful regression coverage and reusable production-path proof.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The historical supported local-agent CLI trace exercises the real edit preparer, filesystem execution, and provider-visible tool results on macOS, showing the parse hint with unchanged bytes and successful legacy replacement/deletion. Both production implementations are identical at the reviewed head, so this scoped proof remains reusable; model responses were simulated. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The historical supported local-agent CLI trace exercises the real edit preparer, filesystem execution, and provider-visible tool results on macOS, showing the parse hint with unchanged bytes and successful legacy replacement/deletion. Both production implementations are identical at the reviewed head, so this scoped proof remains reusable; model responses were simulated. No stored-data contract changes.
Evidence reviewed 9 items Verified introduced change: The pinned merge-base-to-head diff adds the parse diagnostic and six regression cases. The verified test-merge delta preserves the same production change without removing base-only work.
Still needed on current main: Fetched main retains the empty catch after JSON escape repair. A complete legacy string pair still supplies the fallback; this PR changes only the error when that pair is unavailable.
Latest release also lacks the diagnostic: The v2026.9.8 source retains the empty parse-error catch; the requested diagnostic is not already shipped in the supplied latest release.
Findings None None.
Security None None.

How this fits together

The file-edit tool receives replacement arguments from an agent, prepares and validates them, then applies changes to a file. Its error results return to the model so it can correct invalid arguments.

flowchart TD
  A[Agent replacement arguments] --> B[Repair and parse serialized edits]
  B --> C{Parse succeeds or legacy pair exists}
  C -->|Neither| D[Return actionable parse error]
  C -->|Yes| E[Validate and apply replacements]
  E --> F[Verify file and return result]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +6, Tests +48. Total +54 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 7 1 +6
Tests 1 49 1 +48
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 56 2 +54

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #153486
Summary: This PR addresses the diagnostic requested by the canonical issue; the earlier merged repair handles a separate malformed-string recovery case.

Members:

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

Technical review

Best possible solution:

Keep the diagnostic in the existing argument preparer, preserving bounded JSON repair, strict replacement validation, and legacy fallback behavior.

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

Yes: a malformed serialized edits value without a complete legacy pair reaches main’s empty parse-error catch and then generic validation. This is source-established; no current-main runtime reproduction was executed here.

Is this the best way to solve the issue?

Yes: handling the failed parse in the existing preparer gives the model an actionable error without changing valid input semantics or adding another normalization owner.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This improves a concrete agent-tool error with limited blast radius and preserves successful editing behavior.
  • 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 (terminal): The historical supported local-agent CLI trace exercises the real edit preparer, filesystem execution, and provider-visible tool results on macOS, showing the parse hint with unchanged bytes and successful legacy replacement/deletion. Both production implementations are identical at the reviewed head, so this scoped proof remains reusable; model responses were simulated. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The historical supported local-agent CLI trace exercises the real edit preparer, filesystem execution, and provider-visible tool results on macOS, showing the parse hint with unchanged bytes and successful legacy replacement/deletion. Both production implementations are identical at the reviewed head, so this scoped proof remains reusable; model responses were simulated. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • wangmiao0668000666: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • mfurkanakinci: 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-10-02T14:40:59.065Z sha 59d3a13 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-02T15:14:52.683Z sha 59d3a13 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-04T13:22:16.167Z sha 28fb89aa96a2303eff09a41f096c0ed9b3f57968 :: needs maintainer review 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 Oct 2, 2026
@altaywtf
altaywtf force-pushed the fix/edit-json-parse-diagnostic branch from 28fb89a to 51213dc Compare October 6, 2026 16:42
@altaywtf

altaywtf commented Oct 6, 2026

Copy link
Copy Markdown
Member

@clawsweeper re-review

Rebased onto current main. Independent P0–P2 review is clean; fresh Linux regression tests, formatting, and lint pass. Please review the updated head.

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@altaywtf
altaywtf merged commit 307a14f into openclaw:main Oct 6, 2026
112 checks passed
@altaywtf

altaywtf commented Oct 6, 2026

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit that referenced this pull request Oct 6, 2026
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546': (30 commits)
  fix(ci): clear MCP audit and service-worker test blockers (#166217)
  test(gateway): wait for steering admission in FIFO fixtures
  fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358)
  perf(worktrees): avoid full session parsing during GC (#166072)
  fix(update): recover stopped legacy managed services (#166232)
  perf(gateway): stream bounded link preview metadata (#166195)
  perf(diagnostics): release completed Git operation state (#166214)
  chore(deps): update fs-safe to 0.24.1 and clone plugin source captures (#166189)
  feat(clients): adopt worker-local inference placement (#163647)
  test: serialize PowerShell completion process suites (#166229)
  test: stabilize release timing boundaries (#166218)
  refactor(sessions): persist run outcomes only; liveness comes from the run registry (#165733)
  test(gateway): prove mention refresh after config retargeting
  fix(team-reports): keep the missed closed day when catch-up runs after midnight (#165780)
  test(gateway): join WebChat queue admission and drain completion
  fix(logging): reject blank diagnostic stability query fields (#145532)
  fix(agents): report unparseable serialized edit arguments (#163577)
  improve(anthropic): log Claude Code version probe failures (#157697)
  fix(agents): clarify prompt-size provider failures (#159712)
  fix(memory): re-throw non-ENOENT/ENOTDIR errors in root memory file lookup (#107921)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
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: S 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.

[Bug]: Edit tool silently drops model-sent JSON-string edits, fails with confusing validation error

2 participants