Skip to content

fix(agents): stage apply_patch envelopes so failed patches leave no partial mutations - #122933

Closed
yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/apply-patch-atomic-envelope
Closed

yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/apply-patch-atomic-envelope

Conversation

@yetval

@yetval yetval commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #117742.

A multi-file apply_patch envelope was applied one hunk at a time, committing each mutation immediately. When a later hunk failed (missing file, context mismatch, destination conflict, path policy, abort), everything before it stayed committed while the tool call reported failure. The filed reproduction permanently deletes important.txt when a later hunk targets a nonexistent file, and the rejection text never reveals that the workspace changed. The tool is enabled by default and presented as a one-call multi-file operation, so any agent retrying a failed patch compounds the damage because the expected starting state no longer exists.

Why This Change Was Made

Root cause: parsing catches only structural errors before mutation. Semantic and filesystem errors surface inside later hunks after earlier removals and writes have committed. The per-path mutation queue serializes one path but provides no envelope-level transaction.

The fix splits applyPatch into stage and commit phases inside one combined mutation queue over every path the envelope touches:

return await withFileMutationQueues(queuedPaths, async () => {
  const staged = await stagePatchHunks(resolvedHunks, fileOps, options);
  ...
  await commitStagedPatchOps(staged.ops, fileOps);
  • stagePatchHunks validates every hunk against a virtual overlay of pending contents before anything touches disk: update hunks read and match context in memory, add and move destinations are checked for conflicts, deletes are checked for existence and entry kind, and intra-envelope ordering (documented Delete then Add replacement, update of a file added earlier) resolves through the overlay. Any staging failure rejects with zero mutations.
  • commitStagedPatchOps then executes the precomputed operations in original hunk order. Exclusive creation remains the authoritative guard at commit time, so the existing mid-patch competing-writer behavior is preserved.
  • A commit-phase failure (a true race or I/O error after staging passed) can still leave earlier operations durable; the rejection now names exactly which operations were applied instead of hiding them.
  • Abort is honored during staging and immediately before commit, so an abort can no longer strand a half-applied envelope.

Staged ancestor topology

The first revision of this PR staged file contents but not directory topology. Commit runs mkdirp for every created path, so an envelope that adds node and then node/child passed staging, committed node as a file, and then failed inside mkdirp with a preceding delete already durable. The same hole existed when node was an ordinary pre-existing file on disk, which is a failure main also has today.

The staging owner now models ancestors as well as contents. stageParentDirs walks each create destination's ancestors, consults the overlay first and the backend second, rejects when an ancestor is a file, and records the implicit directories the commit will create so a later hunk cannot occupy one of them. PatchFileOps.exists became PatchFileOps.entryKind to make that distinction available: the host backends map lstat to file, directory, or other, and the sandbox backend forwards the type its stat bridge already returns. Symlinks stay other and are never treated as files, so directory aliases keep resolving exactly as they do on the read path.

Staged Delete File entry kind

The second revision staged deletes on existence alone, which ClawSweeper correctly flagged as P1. stagedExists returned true for any entry, including a directory, so an envelope that deletes important.txt and then targets a non-empty directory queued both, and the removal contract rejected the directory only during commit, after important.txt was already gone.

stagedExists is now stagedEntryKind, the same overlay-aware lookup returning the entry kind instead of a boolean, and the Delete File branch rejects a directory target during staging. That is the exact precondition every backend enforces later: the workspace-scoped host backend rejects a non-empty directory, the unconfined host backend rejects any directory through a non-recursive fs.rm, and the sandbox bridge removes with force: false. Deleting a symlink is untouched on the host backends and on the local sandbox bridge. The host backends classify a link through lstat as other, never directory. The local sandbox bridge is link-preserving for the same reason: resolveAnchoredSandboxEntry canonicalizes only the parent and applies the basename afterwards, and buildStatPlan runs stat -c "%F|%s|%y" without -L, so a link reports symbolic link, which coerceStatType maps to other.

Known open item: remote sandbox directory aliases

The remote bridge does not share that contract. createRemoteShellSandboxFsBridge (src/agents/sandbox/remote-fs-bridge.ts:341) resolves the full container path to canonicalPath before statting it, so a symlink to a directory reports directory, while its remove pins the parent with allowFinalSymlinkForUnlink: true and unlinks the basename. On that backend the new staging rejection therefore refuses a Delete File that the remover would have unlinked. SandboxFsBridge.stat has no link-preserving option and the two in-repo bridges already disagree on final-link semantics under the same method name, so closing this means changing the shared sandbox bridge contract rather than patching apply_patch. That is a maintainer decision and it is open; the options and my preference are in the PR discussion.

Production LOC

Production is 915 lines on main and 1082 lines here, net +167. Most of that is the staging owner this fix requires; there is no smaller expression of an envelope-level transaction than a validated overlay plus an ordered commit list. The entry-kind repair above accounts for 11 of those lines and stays inside the same owner rather than pushing a cross-hunk precondition down into a backend, which cannot enforce it. To keep the owner boundary readable, the envelope parser moved verbatim into a new src/agents/apply-patch-parse.ts, joining the existing apply-patch-update.ts and apply-patch-file-ops.ts family. That drops apply-patch.ts from 673 to 527 lines and clears the max-lines budget the topology fix would otherwise have exceeded, with no suppression added.

Novelty: no open PR touches this behavior. Closed PR #117990 verified write contents after reporting success, a different defect, and merged PR #114911 added exclusive destination creation while explicitly retaining per-hunk sequencing.

User Impact

A failed apply_patch call no longer destroys or mutates workspace files for every predictable failure class: missing update target, context mismatch, add or move destination conflict, delete of a missing file, delete of a directory, a created or existing file standing in as the parent directory of a later hunk, path policy rejection, and abort. In the rare commit-time race window the tool now reports exactly what was applied instead of silently leaving the workspace changed.

Three behavior changes, all rejections that previously happened later and dirtier:

  • Deleting a nonexistent file rejects with Cannot delete <path>: the file was not found. before any hunk commits.
  • Deleting a directory rejects with Cannot delete <path>: it is a directory, not a file. during staging, instead of surfacing a backend directory is not empty error after earlier hunks committed. Deleting an empty directory through Delete File also stops working on the workspace-scoped host backend; it was never a documented patch operation, no coverage depended on it, and the unconfined host backend already rejected it.
  • Nesting a new file under a path that is or becomes a file rejects during staging, naming the offending ancestor and the remedy, instead of surfacing a backend directory component must be a directory error after earlier hunks committed.

Verification

  • node scripts/run-vitest.mjs src/agents/apply-patch.test.ts src/agents/apply-patch-staging.test.ts: 64 passed. 11 of the 12 cases in apply-patch-staging.test.ts fail on pristine main for the intended reason (earlier delete, update, or add left committed; missing-file delete after a committed write; unreported partial application; file-as-parent conflicts and a directory Delete File target committing a preceding delete). The twelfth, an update of a file added earlier in the same envelope, already passes on main and is there as a contract guard.
  • New entry-kind coverage: keeps an earlier delete uncommitted when a later delete targets a directory seeds important.txt plus a non-empty node/, submits a Delete File pair, and asserts both the file and the nested file survive the rejection. On pre-fix code it fails with directory is not empty ... The patch was partially applied before this failure: deleted important.txt.
  • node scripts/run-oxlint.mjs clean on all four changed source files, including the max-lines budget that the parser extraction restored.
  • node scripts/run-tsgo.mjs -p tsconfig.core.json and -p test/tsconfig/tsconfig.core.test.json both clean.
  • oxfmt clean on all changed files.
  • Topology coverage from the previous revision is unchanged: a table-driven pair proving a preceding delete survives when a later add nests under a file created earlier in the envelope and under a file already on disk; an add colliding with a directory an earlier hunk creates; and the same conflict through the sandbox backend, proving the entryKind wiring on the sibling surface.
  • The shared temp-dir and memory-sandbox fixtures moved verbatim from apply-patch.test.ts to src/agents/test-helpers/apply-patch-fixtures.ts so both suites use one copy.
  • One provenance assertion in agent-tools.create-openclaw-coding-tools.test.ts updated to the new contract: a conflicting Add File now rejects during staging before any provenance write happens, so no rollback fires.
  • Pre-existing unrelated local failure: agent-tools.create-openclaw-coding-tools.test.ts > resolves Unicode-equivalent filenames through sandbox operations fails on this macOS box with and without this patch, from APFS Unicode normalization in the read tool. It is untouched by this change.

Real behavior proof

Behavior addressed: A rejected multi-file apply_patch envelope left an earlier destructive hunk committed, permanently deleting a workspace file while the call reported failure, including when a later hunk nested a new file under a path that is or becomes a file, and when a later hunk targeted a directory for deletion.
Real environment tested: Production createApplyPatchTool execution with the default workspace-scoped host filesystem backend, driven on pristine main 9386ac0 and on this branch head 4f7339a with identical inputs; the real patch parser, path guards, staging, commit, and on-disk workspace files stayed real and no external seam was replaced.
Exact steps or command run after this patch: ./node_modules/.bin/tsx apply-patch-envelope-proof.mts, a driver that builds four real workspaces containing important.txt, constructs the tool with createApplyPatchTool({ cwd: workspace }), and submits one envelope per workspace whose first hunk deletes important.txt and whose later hunk fails: an update of a nonexistent file, an add of node followed by an add of node/child, an add of node/child where node is an ordinary file already on disk, and a Delete File targeting a non-empty node directory. A fifth workspace then checks the alias contract: Delete File on a symbolic link whose target is a directory outside the workspace, which must still unlink the link and leave the aliased data untouched.
Evidence after fix:

# BEFORE (pristine main 9386ac096632509203dc94086d86d7b3de8bc30d)
surface=createApplyPatchTool.execute
scenario=filed-report-delete-then-missing-update
  outcome=REJECTED Failed to read file to update /private/tmp/claude-501/-Users-yuvald-work/d2904593-84fd-4eb7-9409-842fbdf6ed18/scratchpad/proof-ws-before/filed-report-delete-then-missing-update/missing.txt: Failed boundary read for /private/tmp/claude-501/-Users-yuvald-work/d2904593-84fd-4eb7-9409-842fbdf6ed18/scratchpad/proof-ws-before/filed-report-delete-then-missing-update/missing.txt (path not found)
  important.txt=<DESTROYED>
  workspace_entries=
scenario=envelope-creates-parent-as-file
  outcome=REJECTED directory component must be a directory
  important.txt=<DESTROYED>
  workspace_entries=node
scenario=existing-file-as-parent
  outcome=REJECTED directory component must be a directory
  important.txt=<DESTROYED>
  workspace_entries=node
scenario=delete-then-directory-delete
  outcome=REJECTED directory is not empty
  important.txt=<DESTROYED>
  node/child.txt=nested-user-data
  workspace_entries=node

# AFTER (head 4f7339a8dd86e0751d53dab0265dbabe88786dea, identical inputs)
surface=createApplyPatchTool.execute
scenario=filed-report-delete-then-missing-update
  outcome=REJECTED Failed to read file to update /private/tmp/claude-501/-Users-yuvald-work/d2904593-84fd-4eb7-9409-842fbdf6ed18/scratchpad/proof-ws-after/filed-report-delete-then-missing-update/missing.txt: Failed boundary read for /private/tmp/claude-501/-Users-yuvald-work/d2904593-84fd-4eb7-9409-842fbdf6ed18/scratchpad/proof-ws-after/filed-report-delete-then-missing-update/missing.txt (path not found)
  important.txt=irreplaceable-user-data
  workspace_entries=important.txt
scenario=envelope-creates-parent-as-file
  outcome=REJECTED Cannot create node/child: node is created as a file earlier in this patch. Reorder the hunks or choose another destination.
  important.txt=irreplaceable-user-data
  workspace_entries=important.txt
scenario=existing-file-as-parent
  outcome=REJECTED Cannot create node/child: node is an existing file, not a directory. Delete it earlier in the same patch or choose another destination.
  important.txt=irreplaceable-user-data
  workspace_entries=important.txt,node
scenario=delete-then-directory-delete
  outcome=REJECTED Cannot delete node: it is a directory, not a file. Delete each file inside it with its own hunk.
  important.txt=irreplaceable-user-data
  node/child.txt=nested-user-data
  workspace_entries=important.txt,node

# ALIAS CONTRACT (head 4f7339a8dd86e0751d53dab0265dbabe88786dea)
surface=createApplyPatchTool.execute
scenario=delete-file-on-directory-alias
  alias_target_kind=directory
  outcome=APPLIED Success. Updated the following files: | D important.txt | D alias
  alias_entry_after=<UNLINKED>
  aliased_data_after=aliased-user-data
  workspace_entries=

Observed result after fix: All four envelopes still reject. On main every one of them permanently destroys important.txt and leaves the workspace holding whatever the failed envelope managed to commit. On this head important.txt survives with its original contents in all four, workspace_entries is exactly the seeded starting state, and the three topology and entry-kind rejections now name the offending path and the remedy instead of surfacing a backend message about a directory component or a directory that is not empty. On the host backends the alias contract is unchanged: Delete File on a symbolic link pointing at a directory still applies, unlinks the link itself, and leaves the aliased data readable, because lstat classifies a link as other and only a real directory is refused. This run does not cover the remote backend, whose differing link semantics are the open item named above.
What was not tested: The sandbox backend commit path was driven only through the in-repo memory bridge rather than a live container or a live remote host, so the remote-bridge link semantics named above are argued from source rather than driven, and abort-triggered variants were not driven live. A commit-phase I/O failure after staging passes can still leave earlier operations durable; that residual race window is reported in the rejection text instead of hidden.

@clawsweeper

clawsweeper Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L labels Aug 13, 2026
@yetval
yetval force-pushed the fix/apply-patch-atomic-envelope branch 2 times, most recently from 9110b19 to a350837 Compare August 13, 2026 02:37
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 13, 2026
@clawsweeper

clawsweeper Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 18, 2026, 10:37 PM ET / August 19, 2026, 02:37 UTC.

ClawSweeper review

What this changes

Stages multi-file apply_patch envelopes before ordered commits so predictable later failures do not leave earlier workspace changes behind.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Needs maintainer review before merge - 9 items remain

Keep open: the staged-overlay direction fixes the central partial-mutation bug, but this head still regresses remote symlink deletion and leaves predictable sandbox topology and commit-race mutation gaps.

Priority: P1
Reviewed head: 4f7339a8dd86e0751d53dab0265dbabe88786dea
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong host proof supports the central repair, but concrete sandbox and commit-race defects still block merge.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body contains real before/after production-tool output for the host partial-mutation repair; it does not cover the remaining remote or local sandbox defects.
Patch quality 🦐 gold shrimp (3/6) 3 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body contains real before/after production-tool output for the host partial-mutation repair; it does not cover the remaining remote or local sandbox defects.
Evidence reviewed 7 items Current-main bug remains: Current main removes each delete hunk immediately, before later-hunk validation, so the linked partial-mutation problem is still active.
Remote final-link regression: The new entry-kind adapter consumes bridge.stat; remote stat canonicalizes the final pathname while remote remove pins the parent and unlinks the raw basename, so a directory symlink is rejected before the operation that previously unlinked it.
Sandbox parent topology gap: Staging accepts every non-null non-file parent kind, but the local bridge reports a final symlink as other while mkdirp requires a real directory; a later create under a symlink to a file can therefore commit an earlier delete before failing.
Findings 3 actionable findings [P1] Preserve final-symlink kind in remote staging
[P1] Reject non-directory sandbox parent aliases during staging
[P2] Report directories created before a commit-race failure
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/agents/apply-patch.test.ts src/agents/apply-patch-staging.test.ts

Result: FAIL (failed) — execution before step 1 run: live-proof package manager pnpm is unavailable after its official installer (curl -fsSL https://get.pnpm.io/install.sh | sh -): command failed without output

live-proof package manager pnpm is unavailable after its official installer (curl -fsSL https://get.pnpm.io/install.sh | sh -): command failed without output

Assertions:

  • FAIL expect_output: passed

How this fits together

apply_patch is the agent’s multi-file workspace editor, translating patch text into guarded host or sandbox mutations. This PR adds a staging layer between parsing and those filesystem operations.

flowchart LR
  A[Patch envelope] --> B[Patch parser]
  B --> C[Staging overlay]
  C --> D{All checks pass?}
  D -- No --> E[Reject without file writes]
  D -- Yes --> F[Ordered commit]
  F --> G[Host or sandbox filesystem]
Loading

Decision needed

Question Recommendation
Should remote SandboxFsBridge stat preserve final symlink identity so SSH Delete File continues to unlink directory aliases? Preserve alias unlink behavior: Make remote stat inspect the pinned parent plus raw basename, then add remote and apply_patch coverage for directory-symlink deletion.

Why: The correct repair changes a shared sandbox contract used beyond apply_patch, so maintainer intent is needed for the permanent compatibility rule.

Before merge

  • Preserve final-symlink kind in remote staging (P1) - entryKind now trusts bridge.stat, but the SSH bridge canonicalizes a final symlink before statting it. A symlink to a directory is therefore rejected during staging even though remove deliberately unlinks that final entry; preserve final-link metadata and cover the remote path.
  • Reject non-directory sandbox parent aliases during staging (P1) - Late finding: this unchanged code accepts every other parent. The local sandbox reports a final symlink as other, but mkdirp requires a directory, so Delete File: important.txt followed by an add beneath a symlink to a regular file still commits the delete before failure. Model parent usability separately and add a real sandbox regression.
  • Report directories created before a commit-race failure (P2) - Late finding: mkdirp can create the parent before exclusive creation loses a race, but the operation is recorded only after creation succeeds. The rejection can therefore omit an already-created directory; track that mutation or clean it up before rethrowing.
  • Resolve merge risk (P1) - Remote SSH sandboxes would stop allowing Delete File to unlink a final symlink to a directory.
  • Resolve merge risk (P1) - A local sandbox symlink to a regular file can still make a later create fail after an earlier delete commits.
  • Resolve merge risk (P1) - A commit-time create race can leave a new parent directory without naming it in the failure.
  • Resolve merge risk (P1) - The bug fix adds 167 production lines; no source-supported net-neutral staging expression was identified.
  • Complete next step (P2) - A maintainer must choose the shared SSH final-link contract before the remaining narrow staging and commit-race repairs can be accepted.

Findings

  • [P1] Preserve final-symlink kind in remote staging — src/agents/apply-patch-file-ops.ts:98
  • [P1] Reject non-directory sandbox parent aliases during staging — src/agents/apply-patch.ts:233-234
  • [P2] Report directories created before a commit-race failure — src/agents/apply-patch.ts:347-354
Agent review details

Security

None.

PR surface

Source +248, Tests +147. Total +395 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 4 613 365 +248
Tests 3 239 92 +147
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 852 457 +395

Review metrics

Metric Value Why it matters
Production vs test LOC production +167, tests +228 The staged overlay is material bug-fix growth and needs complete cross-backend and race-boundary coverage to justify it.

Stored data model

Persistent data-model change detected: serialized state: src/agents/apply-patch-staging.test.ts, serialized state: src/agents/apply-patch.test.ts, serialized state: src/agents/test-helpers/apply-patch-fixtures.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #117742
Summary: This PR is the candidate repair for the canonical partial apply_patch mutation bug; the merged exclusive-create change is adjacent rather than a replacement.

Members:

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

Merge-risk options

Maintainer options:

  1. Complete the cross-backend transaction contract (recommended)
    Preserve remote final-link semantics, validate sandbox parents as directories, and account for mkdirp mutations in commit-race failures before merge.
  2. Pause for the bridge-contract decision
    Do not merge until maintainers decide whether SSH directory aliases retain their existing unlink behavior.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Preserve final-symlink metadata in the remote sandbox bridge; distinguish usable parent directories from final delete entries during staging; add remote/local sandbox regressions; and report or roll back directories created before an exclusive-create race fails.

Technical review

Best possible solution:

Preserve a link-aware shared sandbox contract, distinguish usable parent directories from final delete entries, and track or roll back commit-created directories before landing.

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

Yes, from source: the remote stat/remove mismatch and local sandbox symlink-to-file parent path both deterministically reach a later failure after staging accepts the envelope.

Is this the best way to solve the issue?

No: envelope staging is the right owner, but its entry-kind model must distinguish parent resolution from final delete semantics and include implicit directory mutations.

Full review comments:

  • [P1] Preserve final-symlink kind in remote staging — src/agents/apply-patch-file-ops.ts:98
    entryKind now trusts bridge.stat, but the SSH bridge canonicalizes a final symlink before statting it. A symlink to a directory is therefore rejected during staging even though remove deliberately unlinks that final entry; preserve final-link metadata and cover the remote path.
    Confidence: 0.99
  • [P1] Reject non-directory sandbox parent aliases during staging — src/agents/apply-patch.ts:233-234
    Late finding: this unchanged code accepts every other parent. The local sandbox reports a final symlink as other, but mkdirp requires a directory, so Delete File: important.txt followed by an add beneath a symlink to a regular file still commits the delete before failure. Model parent usability separately and add a real sandbox regression.
    Confidence: 0.97
    Late finding: first raised on code an earlier review cycle already covered.
  • [P2] Report directories created before a commit-race failure — src/agents/apply-patch.ts:347-354
    Late finding: mkdirp can create the parent before exclusive creation loses a race, but the operation is recorded only after creation succeeds. The rejection can therefore omit an already-created directory; track that mutation or clean it up before rethrowing.
    Confidence: 0.95
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 23da04ba8af4.

Labels

Label changes:

  • add merge-risk: 🚨 other: Commit-time mkdirp can leave an unreported directory mutation after a failed envelope.

Label justifications:

  • P1: The PR targets default agent workspace mutations that can silently leave destructive partial results, and uncovered sandbox cases retain that failure mode.
  • merge-risk: 🚨 compatibility: Remote Delete File currently unlinks a final directory symlink but the new staging check rejects it.
  • merge-risk: 🚨 other: Commit-time mkdirp can leave an unreported directory mutation after a failed envelope.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body contains real before/after production-tool output for the host partial-mutation repair; it does not cover the remaining remote or local sandbox defects.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body contains real before/after production-tool output for the host partial-mutation repair; it does not cover the remaining remote or local sandbox defects.

Evidence

What I checked:

  • Current-main bug remains: Current main removes each delete hunk immediately, before later-hunk validation, so the linked partial-mutation problem is still active. (src/agents/apply-patch.ts:204, 23da04ba8af4)
  • Remote final-link regression: The new entry-kind adapter consumes bridge.stat; remote stat canonicalizes the final pathname while remote remove pins the parent and unlinks the raw basename, so a directory symlink is rejected before the operation that previously unlinked it. (src/agents/apply-patch-file-ops.ts:98, 4f7339a8dd86)
  • Sandbox parent topology gap: Staging accepts every non-null non-file parent kind, but the local bridge reports a final symlink as other while mkdirp requires a real directory; a later create under a symlink to a file can therefore commit an earlier delete before failing. (src/agents/apply-patch.ts:233, 4f7339a8dd86)
  • Commit-race disclosure gap: mkdirp can mutate parent topology before exclusive creation fails, but the commit code records an applied operation only after both steps succeed, so the error can omit the new directory. (src/agents/apply-patch.ts:348, 4f7339a8dd86)
  • Prior-review continuity: The two newly identified staging concerns are unchanged from the earlier reviewed head; they are marked late rather than attributed to a new commit. (src/agents/apply-patch.ts:225, 4f7339a8dd86)
  • Area provenance: Remote sandbox history includes hardlink and stat behavior work by Peter Steinberger and NianJiu; Yuval Dinodia authored the merged exclusive-create apply_patch contract. (src/agents/sandbox/remote-fs-bridge.ts:341, 49f77492233a)

Likely related people:

  • Peter Steinberger: Recent history includes remote sandbox hardening and filesystem bridge work relevant to the divergent remote stat/remove behavior. (role: recent sandbox contributor; confidence: high; commits: 49f77492233a, 5a4b412a8e8c; files: src/agents/sandbox/remote-fs-bridge.ts, src/agents/sandbox/fs-bridge-mutation-helper.ts)
  • NianJiu: Authored a prior remote sandbox missing-stat-path repair, directly adjacent to the shared stat contract at issue. (role: remote stat contributor; confidence: medium; commits: 175761d20327; files: src/agents/sandbox/remote-fs-bridge.ts)
  • Yuval Dinodia: Authored the merged exclusive-create patch that established the immediate predecessor file-operation contract. (role: prior apply_patch feature contributor; confidence: high; commits: edf4aca7bc27; files: src/agents/apply-patch.ts, src/agents/apply-patch-file-ops.ts)

Rank-up moves

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

  • Preserve final-link metadata in the remote bridge and prove remote alias deletion.
  • Add a local-sandbox symlink-to-file parent regression.
  • Account for mkdirp mutations when a later exclusive create loses a race.

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 (5 earlier review cycles)
  • reviewed 2026-08-13T03:01:57.935Z sha a35083764533b3a8759cf9fc8cd2385f9ffa8b0f :: needs changes before merge. :: [P1] Validate parent topology in the staged overlay
  • reviewed 2026-08-13T06:20:46.591Z sha 2bd5bee70b28ef7d1907481f4f0b1f6af982b07d :: needs changes before merge. :: [P1] Reject directory Delete File targets during staging
  • reviewed 2026-08-14T16:56:39.013Z sha 4f7339a :: needs changes before merge. :: [P1] Preserve final-symlink kind in sandbox staging
  • reviewed 2026-08-14T17:28:57.389Z sha 4f7339a :: needs changes before merge. :: [P1] Preserve final-symlink kind in remote sandbox staging
  • reviewed 2026-08-14T17:40:22.107Z sha 4f7339a :: found issues before merge. :: [P1] Preserve final-symlink kind in remote sandbox staging

@yetval

yetval commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

Refreshed at head 2bd5bee70b28ef7d1907481f4f0b1f6af982b07d, rebased onto 7620a58b295599d108b2fef056a2edc736933550. Answering the four open items.

Validate parent topology in the staged overlay (P1) - fixed. You were right, and the hole was wider than the reported case. Staging modeled file contents but not ancestors, so commit-time mkdirp was still an unmodeled precondition. stageParentDirs in src/agents/apply-patch.ts now walks every create destination's ancestors, consults the overlay first and the backend second, rejects when an ancestor is a file, and records the implicit directories commit will create so a later hunk cannot occupy one. To let staging tell a file from a directory, PatchFileOps.exists became PatchFileOps.entryKind; host backends map lstat to file/directory/other and the sandbox backend forwards the type its stat bridge already returned. Symlinks stay other and are never treated as files, so directory aliases keep resolving as they do on the read path.

Your node then node/child case is covered, and so is the sibling you did not name: node already existing as an ordinary file on disk hit the same commit-time failure with a preceding delete already durable. Both now reject during staging with zero mutations. Live before/after for both is in the body, pinned to this head.

Resolve merge risk (P1), file-as-parent commit-time failure - fixed. Same repair. Four new cases in src/agents/apply-patch-staging.test.ts: a table-driven pair proving a preceding delete survives when a later add nests under a file created earlier in the envelope and under a file already on disk, an add colliding with a directory an earlier hunk creates, and the same conflict through the sandbox backend to prove the entryKind wiring on that surface. 10 of the 11 cases in that file fail on pristine main for the intended reason; the eleventh (update of a file added earlier) already passes on main and is there as a contract guard.

Resolve merge risk (P1), production growth - answered, and the owner is now complete. Production is 915 lines on main and 1071 here, net +156. The growth condition you set was that the single staging owner fully models the preconditions commit can encounter; ancestor topology was the missing one and it is now modeled in the same owner rather than pushed down to a backend, which cannot enforce a cross-hunk contract. I did not find a smaller expression of an envelope-level transaction than a validated overlay plus an ordered commit list. Alongside it, the envelope parser moved verbatim into a new src/agents/apply-patch-parse.ts, joining the existing apply-patch-update.ts and apply-patch-file-ops.ts family. That drops apply-patch.ts from 673 to 516 lines and clears the max-lines budget the topology fix would otherwise have blown, with no suppression added.

Complete next step (P2) - done. The blocker was the mechanical owner-boundary repair described above.

Rank-up moves - both applied. Implicit parent directories and file-versus-directory conflicts are modeled in the overlay, and the regression preserving a preceding delete on a later file-as-parent conflict is in place for both host and sandbox.

Two notes on the review details rather than the checklist:

Gates on this head: apply-patch.test.ts plus apply-patch-staging.test.ts 63 passed; run-oxlint.mjs clean on all four changed source files including the restored max-lines budget; tsgo clean on tsconfig.core.json and test/tsconfig/tsconfig.core.test.json; oxfmt clean. One unrelated pre-existing local failure is noted in the body: the read tool's Unicode-equivalent filename case fails on this macOS box with and without the patch, from APFS normalization.

@yetval
yetval force-pushed the fix/apply-patch-atomic-envelope branch from 2bd5bee to 4f7339a Compare August 14, 2026 16:50
@yetval

yetval commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Refreshed at head 4f7339a8dd86e0751d53dab0265dbabe88786dea, rebased onto 9386ac096632509203dc94086d86d7b3de8bc30d. Answering both open items.

Reject directory Delete File targets during staging (P1) - fixed. You read it correctly: stagedExists returned a boolean, so any existing entry satisfied a Delete File hunk and a directory was queued for commit behind an earlier delete. stagedExists is now stagedEntryKind, the same overlay-aware lookup returning the entry kind, and the Delete File branch rejects a directory target during staging with Cannot delete <path>: it is a directory, not a file. Delete each file inside it with its own hunk.

Rejecting the entry kind rather than the emptiness is the exact precondition all three backends enforce later, not a superset: the workspace-scoped host backend rejects a non-empty directory, the unconfined host backend rejects any directory through its non-recursive fs.rm, and the sandbox bridge removes with force: false. Staging cannot know a directory will still be non-empty at commit without listing it, and an empty-directory Delete File was never a documented patch operation, has no coverage depending on it, and already failed on the unconfined backend. Symlinks are unaffected: lstat classifies them as other, never directory, so Delete File on a directory alias keeps working exactly as before.

The focused host regression is keeps an earlier delete uncommitted when a later delete targets a directory in src/agents/apply-patch-staging.test.ts. It seeds important.txt plus a non-empty node/, submits your exact envelope, and asserts both files survive. On pre-fix code it fails with directory is not empty ... The patch was partially applied before this failure: deleted important.txt, which is the reported defect verbatim. Live before/after for the same case through createApplyPatchTool is in the body, pinned to this head.

Resolve merge risk (P1) - answered, still an explicit maintainer decision. Production is 915 lines on main and 1082 here, net +167. The entry-kind repair is 11 of those lines and stays inside the staging owner rather than pushing a cross-hunk precondition down into a backend, which cannot enforce it. The growth condition you set was that the single owner fully models the preconditions commit can encounter; contents, ancestor topology, and now Delete File entry kind are all modeled there. I did not find a smaller expression of an envelope-level transaction than a validated overlay plus an ordered commit list, so accepting or rejecting that +167 remains yours.

Rank-up move - applied. Directory Delete File targets are rejected before commit and the focused host regression is in place.

One note carried over from the previous cycle: the Stored data model line flags serialized state in apply-patch-staging.test.ts, apply-patch.test.ts, and apply-patch-fixtures.ts. Those three are test files and the fixture is an in-memory bridge; no persisted schema, store, or on-disk format changes here, so there is no migration or upgrade compatibility surface to prove.

Gates on this head: apply-patch.test.ts plus apply-patch-staging.test.ts 64 passed, 11 of the 12 staging cases failing on pristine main for the intended reason; agent-tools.create-openclaw-coding-tools.test.ts passing apart from one pre-existing macOS APFS Unicode-normalization failure in the read tool that reproduces with and without this patch; run-oxlint.mjs clean on all four changed source files including the restored max-lines budget; tsgo clean on tsconfig.core.json and test/tsconfig/tsconfig.core.test.json; oxfmt clean.

@yetval

yetval commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 14, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@yetval

yetval commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Verdict at 4f7339a8dd86e0751d53dab0265dbabe88786dea. The symlink finding does not reproduce; here is the source and the live run, and the two merge-risk lines are answered below.

Preserve final-symlink kind in sandbox staging (P1) - not reproducible, rebutting. The premise is that bridge.stat canonicalizes the final target. It does not; only the parent is canonicalized, and the basename is applied afterwards on purpose.

  • SandboxFsBridgePathGuard.resolveAnchoredSandboxEntry (src/agents/sandbox/fs-bridge-path-safety.ts:203-222) canonicalizes path.posix.dirname(target.containerPath) and returns { canonicalParentPath, basename }, with the in-code note that mutations are anchored to the canonical parent and the basename is applied after boundary checks. resolveResolvedPath (src/agents/sandbox/fs-bridge.ts:390) is pure lexical mount resolution with no filesystem access.
  • buildStatPlan (src/agents/sandbox/fs-bridge-shell-command-plans.ts:19-28) runs set -eu; cd -- "$1"; LC_ALL=C stat -c "%F|%s|%y" -- "$2" with $1 the canonical parent and $2 the raw basename. There is no -L, and GNU stat does not follow links unless -L is given, so a link prints symbolic link, not directory.
  • coerceStatType (src/agents/sandbox/fs-bridge.ts:405-417) maps that to other, because the match is on the literal substrings directory and file.

So the sandbox entryKind adapter reports other for a directory alias, exactly like the host lstatEntryKind, and the new Delete File check refuses only directory. The remote remove path still unlinks the pinned basename. Nothing in this PR changes that.

The host side already carries the regression you asked for and it is green on this head: allows deleting a symlink itself even if it points outside cwd in src/agents/apply-patch.test.ts builds a symlink whose target is a directory outside the workspace, submits *** Delete File: link, and asserts the link is unlinked and the aliased contents survive. Live run through the production tool on this head, driven the same way as the proof block in the body:

surface=createApplyPatchTool.execute
scenario=delete-file-on-directory-alias
  alias_target_kind=directory
  outcome=APPLIED Success. Updated the following files: | D important.txt | D alias
  alias_entry_after=<UNLINKED>
  aliased_data_after=aliased-user-data
  workspace_entries=

I did not add a remote-sandbox regression for this, because there is no behavior change to pin: the only sandbox seam involved is entryKind, whose remote result for a link is other, and the existing memory-bridge case already proves the entryKind wiring on that surface. If you want the stat contract itself pinned against a future -L regression, that belongs in fs-bridge coverage rather than in apply-patch, and I will add it there on request.

Resolve merge risk, remote symlink deletes (P1) - no such break. Same evidence as above. Remote sandbox users keep the Delete File unlink for a symlink to a directory. The reachable behavior change is narrower than the finding states: a Delete File hunk whose target is a real directory now rejects during staging instead of during commit, and on the workspace-scoped host backend an empty directory that previously removed at commit now rejects. That was never a documented patch operation, no coverage depended on it, and the unconfined host backend already rejected it through its non-recursive fs.rm.

Resolve merge risk, production +167 (P1) - answered, still yours to accept. The overlay stays one canonical owner and gained no backend-specific exception: stagedEntryKind is the single overlay-aware lookup used by both the create and delete paths, and the entry-kind rejection is expressed once, in terms all three backends already enforce later. I did not find a smaller expression of an envelope-level transaction than a validated overlay plus an ordered commit list, so accepting or rejecting that +167 remains a maintainer call.

Complete next step (P2) - no repair needed. The remote final-symlink contract is intact, per the source and the run above.

Body refreshed at this same head with the alias scenario added to the proof block. Gates on this head: apply-patch.test.ts plus apply-patch-staging.test.ts 64 passed, including the directory-alias delete case; agent-tools.create-openclaw-coding-tools.test.ts 119 passed with one pre-existing macOS APFS Unicode-normalization failure in the read tool that reproduces with and without this patch; run-oxlint.mjs clean; tsgo clean on tsconfig.core.json and test/tsconfig/tsconfig.core.test.json; oxfmt clean.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 14, 2026
@yetval

yetval commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Correction: my previous comment was wrong and I am withdrawing the rebuttal. You are right.

I checked only src/agents/sandbox/fs-bridge.ts and missed that there is a second implementation, createRemoteShellSandboxFsBridge in src/agents/sandbox/remote-fs-bridge.ts, which is the bridge the SSH backend wires up (src/agents/sandbox/ssh-backend.ts:23, re-exported from src/agents/sandbox.ts:49). The two bridges do not agree on what stat means:

  • Local/container bridge (fs-bridge.ts:279): resolveAnchoredSandboxEntry canonicalizes only the parent and buildStatPlan runs stat on the raw basename, so a final link reports symbolic link and coerceStatType maps it to other. Link-preserving, as I described.
  • Remote bridge (remote-fs-bridge.ts:341-372): after remotePathExists, it calls resolveCanonicalPath on the full container path and then runs stat -c "%F|%s|%y" on that canonicalPath. A symlink to a directory is therefore reported as directory, exactly as you said, while remove (remote-fs-bridge.ts:264-287) pins the parent with allowFinalSymlinkForUnlink: true and unlinks the basename.

So on the remote backend my new directory rejection does refuse a Delete File that the remote remover would have unlinked. That is a regression this PR introduces, and the live host run I posted does not speak to it, because the host backend uses lstat and never had the problem.

I have not pushed a fix, because the repair is not confined to apply-patch and I would rather not decide the contract for you. SandboxFsBridge.stat has no link-preserving option, and the two in-repo bridges already disagree on final-link semantics under the same method name, so the fix means changing the shared bridge contract. Three shapes, all with real costs:

  1. Add link-preserving entry metadata to the bridge contract and implement it in remote-fs-bridge.stat by statting the pinned parent plus basename instead of canonicalPath, leaving the local bridge as-is since it is already link-preserving, plus a remote-bridge regression. This is the correct owner boundary and it also removes the existing disagreement between the two implementations, but it is a sandbox contract change landing inside an apply_patch fix, and it pushes production past the +167 you are already weighing.
  2. Scope the precondition per backend by asking each PatchFileOps implementation whether a target is removable rather than asking for an entry kind. Smaller, but the remote adapter would have to answer "yes" for directories, so the remote backend keeps the original partial-mutation hole for directory deletes, and the staging owner gains the backend-specific asymmetry you warned about.
  3. Accept the narrowed behavior: directory-alias Delete File stops working on the remote sandbox, in exchange for closing the partial-mutation hole on every backend.

My preference is 1, and I will implement it with the remote-bridge regression on your word. Tell me which you want, or apply @clawsweeper automerge with option 1 as the instruction and I will follow it.

For the record on the other open lines: production is +167 net with the overlay as one canonical owner; the Stored data model flag covers three test and fixture files with no persisted schema, store, or on-disk format change; and the host-side proof in the body stands for the host backends, including the directory-alias delete that still applies and unlinks the link itself.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Aug 14, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Aug 19, 2026
@yetval

yetval commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Closing this while it sits in waiting-on-author state with three actionable findings outstanding. The underlying partial-mutation defect remains tracked in the open issue #117742; the staged-overlay direction and the remaining sandbox findings are documented in the review history here for whoever picks it up next.

@yetval yetval closed this Aug 19, 2026
obviyus added a commit that referenced this pull request Oct 15, 2026
…date hunk cannot apply (#160409)

Related: #117742

## What Problem This Solves

Fixes: a multi-file `apply_patch` call permanently deletes, creates, or rewrites earlier files when a later update hunk targets a missing file or its context lines do not match, while the tool only reports the later error.

## User Impact

User impact: when an update hunk in a patch cannot apply, the whole patch now rejects before any file changes, so the workspace is left exactly as it was and the agent's retry starts from the state it expects.

## Why This Change Was Made

The issue and #127496 leave one durability question open: after a failure that happens while files are being written (I/O error, a competing writer, cancellation mid-commit), should `apply_patch` compensate, or keep the earlier effects and report them? This PR does not make that choice. It implements only the part both options in the ClawSweeper review share, which is also the first step of the repair described in #127496: validate the ordered envelope before writing, while holding the file queues for the whole envelope.

- All hunk targets resolve first, and the patch holds the file-mutation queue for every path it touches for the whole run, so the check reads the same state the writes act on.
- Every update hunk is then computed in order before anything is written, with the same `applyUpdateHunk` the write pass uses. Earlier adds, updates, deletes and moves in the same patch are staged by physical file identity, so an update of a file added or changed earlier in the patch still works, and an update of a file an earlier hunk deletes or moves away rejects up front. A missing file, a context mismatch or invalid UTF-8 rejects with no mutation.
- Links are staged apart from the files they name. Queue identity follows a final symlink, so a link and its target share one key, but deleting the link leaves the target in place. A delete or move of a final symlink therefore stages the link path by its spelling, and later hunks at or under that path (`Add File: link`, `Update File: link`, `Move to: link`, `Add File: dir-link/x.txt`) use that path stage, which starts out removed. The target keeps its own staged contents, so `Delete File: link` followed by a mismatched `Update File: target` now rejects before the link is deleted, and `Delete File: link`, `Add File: link`, `Update File: target` no longer checks the target against the new link contents. The write pass decides whether an update is a move from the same stages, so `Update File: target` with `Move to: link` after `Delete File: link` moves the file instead of rewriting it in place.
- Names of one hardlinked file share staged contents in unrestricted host mode (`workspaceOnly: false`), where an update rewrites the file in place and every name sees it. Each name has its own queue identity, so an update hunk of a hardlinked file (more than one link at the snapshot) stages by the file's device and inode instead, until an earlier hunk in the patch deletes, re-creates or moves that name. `Update File: a` followed by `Update File: b` whose context matches the text written through `a` applies again, as it does on main. Moving one name away leaves the shared contents for the other names. Confined mode refuses hardlink aliases, and the sandbox helpers refuse hardlinked reads and replace files atomically, so neither shares contents across names.
- Path admission for a later hunk runs against the initial snapshot. When an earlier removal changes what admission sees (a symlink or file replaced by a regular file or directory, or the last other name of a hardlink), that hunk repeats strict admission in the write pass right before it runs, after the earlier hunk has removed the path. The link target is never read or written. A later path matches an earlier host symlink removal by the link entry's own identity (`lstat` device and inode) as well as by spelling, so the filesystem decides which spellings name the removed link: on a case-insensitive volume, `Delete File: link.txt` then `Add File: LINK.txt` (or `Add File: D/x.txt` after `Delete File: d`) replaces the link as it does on main. A symlink with more than one hardlinked name matches by spelling only, because its identity also names the entries that stay. Any other admission failure still rejects the whole patch up front, even after an unrelated delete.

Deliberately left out: compensation or a partial-effect result for failures that only show up during the write pass (an add whose destination exists, a delete of a missing file, a move onto an existing file, removing a directory, I/O errors, cancellation between writes). Those still behave as on main and need the maintainer decision above. For the same reason this PR does not close the issue on its own; keeping #117742 open for that decision is fine.

Scope tradeoff for maintainers: landing this PR means accepting a bounded fix. A patch whose update hunk cannot apply now leaves the workspace untouched, but a patch that fails during the write pass can still leave the effects of earlier hunks in place without reporting them, exactly as on main. Closing that gap needs the compensation or partial-effect decision tracked in #127496.

Where the check cannot predict the state it leaves the hunk to the write pass, which stays authoritative, rather than reject a patch the write pass would accept: an update of the other name of a hardlink that an earlier delete frees, and an unreadable new path whose spelling differs only in case from a path an earlier hunk staged (case-insensitive filesystems keep the spelled case in the identity of a missing path).

Design note: I chose a read-only preflight in front of the unchanged write pass over a staged plan with an undo journal. The staged plan must model every backend precondition (entry kinds, parent topology, symlink handling in the sandbox bridges), and #122933 stalled on exactly that.

The branch is rebased onto current main. The patch parser moved unchanged to `src/agents/apply-patch-parse.ts` (main's current parser, which returns the hunk list directly), and the tests this PR adds live in `src/agents/apply-patch.preflight.test.ts`, so both files stay within the line-cap ratchet.

The existing permission-change fence test now expects the abort at the envelope checkpoint: the read that triggers it happens in the preflight, so the rejection is an `AbortError` that carries the permission-change reason as its cause, and the file still stays unchanged.

## Evidence

Real behavior: an isolated Gateway built from each side (own state directory, loopback port, channels skipped) with a keyless local mock model that makes one agent turn call the real `apply_patch` tool with the envelope from the issue (`Delete File: important.txt`, then `Update File: missing.txt`). The workspace is seeded with `important.txt`.

Before (upstream main, no apply_patch changes since):

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: 
== important.txt after: <MISSING>
```

After (this branch, same Gateway setup and turn):

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: important.txt 
== important.txt after: irreplaceable-user-data
```

Control on this branch, a valid envelope (delete, add, then update of the just-added file) still applies in order:

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
== workspace after: notes.txt 
== important.txt after: <MISSING>
```

The Gateway proof above is still valid for this head: its envelope does not involve a link, a hardlink or a path an earlier hunk frees, so it takes the same path as before the link and hardlink staging changes.

Hardlink names in unrestricted mode, same Gateway setup with `tools.exec.applyPatch.workspaceOnly: false`. The workspace holds `original.txt` (`one`) and `alias.txt`, a second hardlink to the same file. The turn sends `Update File: original.txt` (`one` to `two`), then `Update File: alias.txt` (`two` to `three`).

Before (previous head of this branch, rebased onto current main without the hardlink change; main accepts this envelope):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to find expected lines in <workspace>/alias.txt:⏎two"
}
== after: original.txt=one alias.txt=one links=2
```

After (this head):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
M original.txt
M alias.txt
== after: original.txt=three alias.txt=three links=2
```

Tests (`src/agents/apply-patch.preflight.test.ts`, through the real `apply_patch` tool or `applyPatch`):

- Delete before an update of a missing file, and add plus update before a context mismatch: fail on main with the earlier effects committed, pass here. Updates of files added or changed earlier in the same patch, including a move, still apply.
- `Delete File: link.txt` (a symlink to an in-workspace `target.txt`) followed by a mismatched `Update File: target.txt`, or by `Update File: target.txt` / `Move to: link.txt` and a later update of `target.txt`: fail on an earlier head of this branch (the link is deleted before the error) and pass here with the link and target unchanged.
- `Delete File: link.txt`, `Add File: link.txt`, `Update File: target.txt`, `Update File: link.txt`, and `Update File: target.txt` / `Move to: link.txt` after the delete: fail on an earlier head of this branch (false context mismatch on the target, or an in-place rewrite instead of a move) and pass here.
- Outside-link and directory-link replacement (`Delete File: d`, then `Add File: d/x.txt`, `Add File: d/..cache`, `Delete File: d/x.txt`), a regular file replaced by a directory, and both names of a hardlink (re-create the deleted name, or update the other name): sequences main accepts; they fail on earlier heads of this branch, where admission ran only against the snapshot, and pass here.
- A moved symlink path updated again, and an outside-symlink update after an unrelated delete: reject before any mutation.
- Unrestricted mode (`workspaceOnly: false`) with two hardlink names: an update of the second name using text written through the first, alone or after deleting the first name, applies as on main. These cases pass on main, fail on the previous head of this branch, and pass here. A third case (move the first name away, then update the second against the original text) guards that a move does not carry the new contents to the other name.
- A removed outside symlink replaced under different casing (`Delete File: link.txt`, `Add File: LINK.txt`; `Delete File: d`, `Add File: D/x.txt`), gated on a case-insensitive temp volume. Run on macOS 15.7.9 (Intel, case-insensitive APFS) with this head's tests and each side's `src/agents/apply-patch.ts`: main passes both, the previous head of this branch (583baf2) fails both with `Symlink escapes sandbox root`, and this head passes both. The full apply-patch suites pass there on this head (162 passed, 1 Linux-only skip). Linux CI skips these two cases.
- A hardlinked symlink (Linux `link(2)` on a symlink): `Delete File: a` then `Update File: b` for the other name still updates the target, as on main; it fails on an intermediate version of this fix that matched any symlink by identity.
- Fail-to-pass run against main (merge base, Linux): the 7 regression tests above fail on main and pass here. The hardlink cases pass on main and here, and fail when the hardlink staging is removed from this head. The casing cases skip on Linux, so their before/after evidence is the macOS run above.
- `node scripts/run-vitest.mjs src/agents/apply-patch*.test.ts`: 12 files, 161 tests pass on Linux (2 macOS-only skips).
- `pnpm check:changed`: passes on the current head, apart from the dead export scan, which fails only on exports in files this PR does not touch (`src/plugins/config-policy.ts`, `src/media-understanding/defaults.ts`) and was skipped for the rerun.
- Review: a fresh-context code review at high effort, repeated after each round of fixes; its confirmed findings (move detection after a link delete, hardlink and directory-link replacement, held queue keys for removed link paths, case-folded link detection on the host, `..`-prefixed names under a removed link, abort checks during resolution) are fixed and covered above. A fresh-context review of the hardlink change found no correctness issue; it traced further hardlink, symlink and move sequences, which all matched the ordered writer, and the one wording note it raised is applied. A fresh-context review of the casing change found that a hardlinked symlink's identity also names its other entries (a delete of one name then made an update of the other reject); identity matching now requires a single link, with a regression test.

| Test file | `pnpm test <file> --maxWorkers=1` wall | CI seconds | New cases |
| --- | --- | --- | --- |
| `src/agents/apply-patch.preflight.test.ts` | 6.0 s (20 tests, 2 skip on Linux) | pending for this head | 20 cases, each under 15 ms of test time |
| `src/agents/apply-patch.test.ts` | 6.3 s | pending for this head | none (one assertion changed) |




## Maintainer E2E verification

Verified on macOS arm64 through an isolated, built Gateway and the real `openclaw agent` CLI. The Gateway used fresh state, workspace and HOME, loopback-only ports, and a local OpenAI Responses fixture model following the repository's existing HTTP/SSE test contract. No production state, personal API credentials, or CLI-login credentials were used. The model request advertised the real `apply_patch` tool; the next model request contained its actual `function_call_output` from the filesystem operation.

Baseline: `372ff7cacef` (fresh main). Candidate: contributor head merged with that main, then simplified; final head `e8d17b1d604780c1e351f74ef7e221fde5ba1967`. Runtime E2E ran at `6353875b56e` and again at `d908d9ea2d4`; the final commit only restores the existing permission-fence test assertion, without changing production code.

| Real Gateway scenario | Main | Candidate / simplified head |
| --- | --- | --- |
| Delete `important.txt`, then update missing `missing.txt` | Tool reports the missing-file error; `important.txt` is permanently missing | Same tool error; `important.txt` retains `irreplaceable-user-data⏎` |
| Add `created.txt`, rewrite `important.txt`, then fail a later context match | Not rerun on main | Simplified head rejects; only the unchanged original `important.txt` remains |
| Valid delete, add `notes.txt`, then update the newly added file | Not rerun on main | Simplified head succeeds; `notes.txt` contains `final⏎` |

Redacted model-visible failing result on both sides:

```json
{
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
```

The valid control returned:

```text
Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
```

All task-owned Gateways and fixture model servers were stopped. This is deterministic model-boundary proof, not a claim about live model behavior or commit-time rollback.

Checks:
- Baseline full `pnpm build`, candidate and simplified `pnpm build:runtime`: passed.
- All nine `apply-patch*.test.ts` suites were exercised. Initial result: 151 passed, one Linux-only skip, one outdated permission-error assertion failed. After restoring that assertion to main's existing contract, the affected suite passed all 51 tests. The other eight suites' passing results remain applicable.
- `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`: passed.
- `node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.agents-root.json --noEmit`: passed, including after the assertion repair.
- Scoped Oxlint and Oxfmt: passed.
- `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`: passed.
- UI was not changed; no UI typecheck was needed.

## Maintainer simplification

Preserved the contributor's commits and merged current main without rebasing or force-pushing. The merge retains main's `ToolInputError` classification and its already-simplified parser in the extracted parser module. Replaced two temporary-array constructions in patch staging with direct iteration, including removal of the tuple assertion. Restored main's existing permission-change assertion because the current guarded read rejects before the envelope checkpoint; the test still proves the file remains unchanged.

The ordered staging, link/hardlink identity handling, and distinct filesystem regression cases are retained: they preserve accepted ordered patches while adding preflight, rather than pursuing a separate behavior change. No new rollback or partial-effect contract was introduced.

Final diff against the main merge base: production +725/-299 (net +426); tests +434/-0. Parser extraction accounts for +218 production lines; the required ordered preflight and filesystem-identity handling account for the remaining growth. The original `apply-patch.test.ts` has no net diff from main.

No overlap with Pash/Sarah changes in the touched files. Full diff security read found no new network access, credential reads, package/lockfile changes, or build-script changes. The contributor had 123 merged OpenClaw PRs at inspection.

The broader durability decision in #117742 / #127496 remains open: commit-time I/O failures, cancellation between writes, and other write-pass failures can still leave partial effects. This PR is the bounded update-preflight improvement and should not close those issues by itself.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…date hunk cannot apply (openclaw#160409)

Related: openclaw#117742

## What Problem This Solves

Fixes: a multi-file `apply_patch` call permanently deletes, creates, or rewrites earlier files when a later update hunk targets a missing file or its context lines do not match, while the tool only reports the later error.

## User Impact

User impact: when an update hunk in a patch cannot apply, the whole patch now rejects before any file changes, so the workspace is left exactly as it was and the agent's retry starts from the state it expects.

## Why This Change Was Made

The issue and openclaw#127496 leave one durability question open: after a failure that happens while files are being written (I/O error, a competing writer, cancellation mid-commit), should `apply_patch` compensate, or keep the earlier effects and report them? This PR does not make that choice. It implements only the part both options in the ClawSweeper review share, which is also the first step of the repair described in openclaw#127496: validate the ordered envelope before writing, while holding the file queues for the whole envelope.

- All hunk targets resolve first, and the patch holds the file-mutation queue for every path it touches for the whole run, so the check reads the same state the writes act on.
- Every update hunk is then computed in order before anything is written, with the same `applyUpdateHunk` the write pass uses. Earlier adds, updates, deletes and moves in the same patch are staged by physical file identity, so an update of a file added or changed earlier in the patch still works, and an update of a file an earlier hunk deletes or moves away rejects up front. A missing file, a context mismatch or invalid UTF-8 rejects with no mutation.
- Links are staged apart from the files they name. Queue identity follows a final symlink, so a link and its target share one key, but deleting the link leaves the target in place. A delete or move of a final symlink therefore stages the link path by its spelling, and later hunks at or under that path (`Add File: link`, `Update File: link`, `Move to: link`, `Add File: dir-link/x.txt`) use that path stage, which starts out removed. The target keeps its own staged contents, so `Delete File: link` followed by a mismatched `Update File: target` now rejects before the link is deleted, and `Delete File: link`, `Add File: link`, `Update File: target` no longer checks the target against the new link contents. The write pass decides whether an update is a move from the same stages, so `Update File: target` with `Move to: link` after `Delete File: link` moves the file instead of rewriting it in place.
- Names of one hardlinked file share staged contents in unrestricted host mode (`workspaceOnly: false`), where an update rewrites the file in place and every name sees it. Each name has its own queue identity, so an update hunk of a hardlinked file (more than one link at the snapshot) stages by the file's device and inode instead, until an earlier hunk in the patch deletes, re-creates or moves that name. `Update File: a` followed by `Update File: b` whose context matches the text written through `a` applies again, as it does on main. Moving one name away leaves the shared contents for the other names. Confined mode refuses hardlink aliases, and the sandbox helpers refuse hardlinked reads and replace files atomically, so neither shares contents across names.
- Path admission for a later hunk runs against the initial snapshot. When an earlier removal changes what admission sees (a symlink or file replaced by a regular file or directory, or the last other name of a hardlink), that hunk repeats strict admission in the write pass right before it runs, after the earlier hunk has removed the path. The link target is never read or written. A later path matches an earlier host symlink removal by the link entry's own identity (`lstat` device and inode) as well as by spelling, so the filesystem decides which spellings name the removed link: on a case-insensitive volume, `Delete File: link.txt` then `Add File: LINK.txt` (or `Add File: D/x.txt` after `Delete File: d`) replaces the link as it does on main. A symlink with more than one hardlinked name matches by spelling only, because its identity also names the entries that stay. Any other admission failure still rejects the whole patch up front, even after an unrelated delete.

Deliberately left out: compensation or a partial-effect result for failures that only show up during the write pass (an add whose destination exists, a delete of a missing file, a move onto an existing file, removing a directory, I/O errors, cancellation between writes). Those still behave as on main and need the maintainer decision above. For the same reason this PR does not close the issue on its own; keeping openclaw#117742 open for that decision is fine.

Scope tradeoff for maintainers: landing this PR means accepting a bounded fix. A patch whose update hunk cannot apply now leaves the workspace untouched, but a patch that fails during the write pass can still leave the effects of earlier hunks in place without reporting them, exactly as on main. Closing that gap needs the compensation or partial-effect decision tracked in openclaw#127496.

Where the check cannot predict the state it leaves the hunk to the write pass, which stays authoritative, rather than reject a patch the write pass would accept: an update of the other name of a hardlink that an earlier delete frees, and an unreadable new path whose spelling differs only in case from a path an earlier hunk staged (case-insensitive filesystems keep the spelled case in the identity of a missing path).

Design note: I chose a read-only preflight in front of the unchanged write pass over a staged plan with an undo journal. The staged plan must model every backend precondition (entry kinds, parent topology, symlink handling in the sandbox bridges), and openclaw#122933 stalled on exactly that.

The branch is rebased onto current main. The patch parser moved unchanged to `src/agents/apply-patch-parse.ts` (main's current parser, which returns the hunk list directly), and the tests this PR adds live in `src/agents/apply-patch.preflight.test.ts`, so both files stay within the line-cap ratchet.

The existing permission-change fence test now expects the abort at the envelope checkpoint: the read that triggers it happens in the preflight, so the rejection is an `AbortError` that carries the permission-change reason as its cause, and the file still stays unchanged.

## Evidence

Real behavior: an isolated Gateway built from each side (own state directory, loopback port, channels skipped) with a keyless local mock model that makes one agent turn call the real `apply_patch` tool with the envelope from the issue (`Delete File: important.txt`, then `Update File: missing.txt`). The workspace is seeded with `important.txt`.

Before (upstream main, no apply_patch changes since):

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: 
== important.txt after: <MISSING>
```

After (this branch, same Gateway setup and turn):

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: important.txt 
== important.txt after: irreplaceable-user-data
```

Control on this branch, a valid envelope (delete, add, then update of the just-added file) still applies in order:

```
== workspace before: important.txt 
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
== workspace after: notes.txt 
== important.txt after: <MISSING>
```

The Gateway proof above is still valid for this head: its envelope does not involve a link, a hardlink or a path an earlier hunk frees, so it takes the same path as before the link and hardlink staging changes.

Hardlink names in unrestricted mode, same Gateway setup with `tools.exec.applyPatch.workspaceOnly: false`. The workspace holds `original.txt` (`one`) and `alias.txt`, a second hardlink to the same file. The turn sends `Update File: original.txt` (`one` to `two`), then `Update File: alias.txt` (`two` to `three`).

Before (previous head of this branch, rebased onto current main without the hardlink change; main accepts this envelope):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to find expected lines in <workspace>/alias.txt:⏎two"
}
== after: original.txt=one alias.txt=one links=2
```

After (this head):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
M original.txt
M alias.txt
== after: original.txt=three alias.txt=three links=2
```

Tests (`src/agents/apply-patch.preflight.test.ts`, through the real `apply_patch` tool or `applyPatch`):

- Delete before an update of a missing file, and add plus update before a context mismatch: fail on main with the earlier effects committed, pass here. Updates of files added or changed earlier in the same patch, including a move, still apply.
- `Delete File: link.txt` (a symlink to an in-workspace `target.txt`) followed by a mismatched `Update File: target.txt`, or by `Update File: target.txt` / `Move to: link.txt` and a later update of `target.txt`: fail on an earlier head of this branch (the link is deleted before the error) and pass here with the link and target unchanged.
- `Delete File: link.txt`, `Add File: link.txt`, `Update File: target.txt`, `Update File: link.txt`, and `Update File: target.txt` / `Move to: link.txt` after the delete: fail on an earlier head of this branch (false context mismatch on the target, or an in-place rewrite instead of a move) and pass here.
- Outside-link and directory-link replacement (`Delete File: d`, then `Add File: d/x.txt`, `Add File: d/..cache`, `Delete File: d/x.txt`), a regular file replaced by a directory, and both names of a hardlink (re-create the deleted name, or update the other name): sequences main accepts; they fail on earlier heads of this branch, where admission ran only against the snapshot, and pass here.
- A moved symlink path updated again, and an outside-symlink update after an unrelated delete: reject before any mutation.
- Unrestricted mode (`workspaceOnly: false`) with two hardlink names: an update of the second name using text written through the first, alone or after deleting the first name, applies as on main. These cases pass on main, fail on the previous head of this branch, and pass here. A third case (move the first name away, then update the second against the original text) guards that a move does not carry the new contents to the other name.
- A removed outside symlink replaced under different casing (`Delete File: link.txt`, `Add File: LINK.txt`; `Delete File: d`, `Add File: D/x.txt`), gated on a case-insensitive temp volume. Run on macOS 15.7.9 (Intel, case-insensitive APFS) with this head's tests and each side's `src/agents/apply-patch.ts`: main passes both, the previous head of this branch (583baf2) fails both with `Symlink escapes sandbox root`, and this head passes both. The full apply-patch suites pass there on this head (162 passed, 1 Linux-only skip). Linux CI skips these two cases.
- A hardlinked symlink (Linux `link(2)` on a symlink): `Delete File: a` then `Update File: b` for the other name still updates the target, as on main; it fails on an intermediate version of this fix that matched any symlink by identity.
- Fail-to-pass run against main (merge base, Linux): the 7 regression tests above fail on main and pass here. The hardlink cases pass on main and here, and fail when the hardlink staging is removed from this head. The casing cases skip on Linux, so their before/after evidence is the macOS run above.
- `node scripts/run-vitest.mjs src/agents/apply-patch*.test.ts`: 12 files, 161 tests pass on Linux (2 macOS-only skips).
- `pnpm check:changed`: passes on the current head, apart from the dead export scan, which fails only on exports in files this PR does not touch (`src/plugins/config-policy.ts`, `src/media-understanding/defaults.ts`) and was skipped for the rerun.
- Review: a fresh-context code review at high effort, repeated after each round of fixes; its confirmed findings (move detection after a link delete, hardlink and directory-link replacement, held queue keys for removed link paths, case-folded link detection on the host, `..`-prefixed names under a removed link, abort checks during resolution) are fixed and covered above. A fresh-context review of the hardlink change found no correctness issue; it traced further hardlink, symlink and move sequences, which all matched the ordered writer, and the one wording note it raised is applied. A fresh-context review of the casing change found that a hardlinked symlink's identity also names its other entries (a delete of one name then made an update of the other reject); identity matching now requires a single link, with a regression test.

| Test file | `pnpm test <file> --maxWorkers=1` wall | CI seconds | New cases |
| --- | --- | --- | --- |
| `src/agents/apply-patch.preflight.test.ts` | 6.0 s (20 tests, 2 skip on Linux) | pending for this head | 20 cases, each under 15 ms of test time |
| `src/agents/apply-patch.test.ts` | 6.3 s | pending for this head | none (one assertion changed) |




## Maintainer E2E verification

Verified on macOS arm64 through an isolated, built Gateway and the real `openclaw agent` CLI. The Gateway used fresh state, workspace and HOME, loopback-only ports, and a local OpenAI Responses fixture model following the repository's existing HTTP/SSE test contract. No production state, personal API credentials, or CLI-login credentials were used. The model request advertised the real `apply_patch` tool; the next model request contained its actual `function_call_output` from the filesystem operation.

Baseline: `0af05d521e4` (fresh main). Candidate: contributor head merged with that main, then simplified; final head `e8d17b1d604780c1e351f74ef7e221fde5ba1967`. Runtime E2E ran at `6353875b56e` and again at `d908d9ea2d4`; the final commit only restores the existing permission-fence test assertion, without changing production code.

| Real Gateway scenario | Main | Candidate / simplified head |
| --- | --- | --- |
| Delete `important.txt`, then update missing `missing.txt` | Tool reports the missing-file error; `important.txt` is permanently missing | Same tool error; `important.txt` retains `irreplaceable-user-data⏎` |
| Add `created.txt`, rewrite `important.txt`, then fail a later context match | Not rerun on main | Simplified head rejects; only the unchanged original `important.txt` remains |
| Valid delete, add `notes.txt`, then update the newly added file | Not rerun on main | Simplified head succeeds; `notes.txt` contains `final⏎` |

Redacted model-visible failing result on both sides:

```json
{
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
```

The valid control returned:

```text
Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
```

All task-owned Gateways and fixture model servers were stopped. This is deterministic model-boundary proof, not a claim about live model behavior or commit-time rollback.

Checks:
- Baseline full `pnpm build`, candidate and simplified `pnpm build:runtime`: passed.
- All nine `apply-patch*.test.ts` suites were exercised. Initial result: 151 passed, one Linux-only skip, one outdated permission-error assertion failed. After restoring that assertion to main's existing contract, the affected suite passed all 51 tests. The other eight suites' passing results remain applicable.
- `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`: passed.
- `node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.agents-root.json --noEmit`: passed, including after the assertion repair.
- Scoped Oxlint and Oxfmt: passed.
- `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`: passed.
- UI was not changed; no UI typecheck was needed.

## Maintainer simplification

Preserved the contributor's commits and merged current main without rebasing or force-pushing. The merge retains main's `ToolInputError` classification and its already-simplified parser in the extracted parser module. Replaced two temporary-array constructions in patch staging with direct iteration, including removal of the tuple assertion. Restored main's existing permission-change assertion because the current guarded read rejects before the envelope checkpoint; the test still proves the file remains unchanged.

The ordered staging, link/hardlink identity handling, and distinct filesystem regression cases are retained: they preserve accepted ordered patches while adding preflight, rather than pursuing a separate behavior change. No new rollback or partial-effect contract was introduced.

Final diff against the main merge base: production +725/-299 (net +426); tests +434/-0. Parser extraction accounts for +218 production lines; the required ordered preflight and filesystem-identity handling account for the remaining growth. The original `apply-patch.test.ts` has no net diff from main.

No overlap with Pash/Sarah changes in the touched files. Full diff security read found no new network access, credential reads, package/lockfile changes, or build-script changes. The contributor had 123 merged OpenClaw PRs at inspection.

The broader durability decision in openclaw#117742 / openclaw#127496 remains open: commit-time I/O failures, cancellation between writes, and other write-pass failures can still leave partial effects. This PR is the bounded update-preflight improvement and should not close those issues by itself.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 22, 2026
…date hunk cannot apply (#160409)

Related: #117742

Fixes: a multi-file `apply_patch` call permanently deletes, creates, or rewrites earlier files when a later update hunk targets a missing file or its context lines do not match, while the tool only reports the later error.

User impact: when an update hunk in a patch cannot apply, the whole patch now rejects before any file changes, so the workspace is left exactly as it was and the agent's retry starts from the state it expects.

The issue and #127496 leave one durability question open: after a failure that happens while files are being written (I/O error, a competing writer, cancellation mid-commit), should `apply_patch` compensate, or keep the earlier effects and report them? This PR does not make that choice. It implements only the part both options in the ClawSweeper review share, which is also the first step of the repair described in #127496: validate the ordered envelope before writing, while holding the file queues for the whole envelope.

- All hunk targets resolve first, and the patch holds the file-mutation queue for every path it touches for the whole run, so the check reads the same state the writes act on.
- Every update hunk is then computed in order before anything is written, with the same `applyUpdateHunk` the write pass uses. Earlier adds, updates, deletes and moves in the same patch are staged by physical file identity, so an update of a file added or changed earlier in the patch still works, and an update of a file an earlier hunk deletes or moves away rejects up front. A missing file, a context mismatch or invalid UTF-8 rejects with no mutation.
- Links are staged apart from the files they name. Queue identity follows a final symlink, so a link and its target share one key, but deleting the link leaves the target in place. A delete or move of a final symlink therefore stages the link path by its spelling, and later hunks at or under that path (`Add File: link`, `Update File: link`, `Move to: link`, `Add File: dir-link/x.txt`) use that path stage, which starts out removed. The target keeps its own staged contents, so `Delete File: link` followed by a mismatched `Update File: target` now rejects before the link is deleted, and `Delete File: link`, `Add File: link`, `Update File: target` no longer checks the target against the new link contents. The write pass decides whether an update is a move from the same stages, so `Update File: target` with `Move to: link` after `Delete File: link` moves the file instead of rewriting it in place.
- Names of one hardlinked file share staged contents in unrestricted host mode (`workspaceOnly: false`), where an update rewrites the file in place and every name sees it. Each name has its own queue identity, so an update hunk of a hardlinked file (more than one link at the snapshot) stages by the file's device and inode instead, until an earlier hunk in the patch deletes, re-creates or moves that name. `Update File: a` followed by `Update File: b` whose context matches the text written through `a` applies again, as it does on main. Moving one name away leaves the shared contents for the other names. Confined mode refuses hardlink aliases, and the sandbox helpers refuse hardlinked reads and replace files atomically, so neither shares contents across names.
- Path admission for a later hunk runs against the initial snapshot. When an earlier removal changes what admission sees (a symlink or file replaced by a regular file or directory, or the last other name of a hardlink), that hunk repeats strict admission in the write pass right before it runs, after the earlier hunk has removed the path. The link target is never read or written. A later path matches an earlier host symlink removal by the link entry's own identity (`lstat` device and inode) as well as by spelling, so the filesystem decides which spellings name the removed link: on a case-insensitive volume, `Delete File: link.txt` then `Add File: LINK.txt` (or `Add File: D/x.txt` after `Delete File: d`) replaces the link as it does on main. A symlink with more than one hardlinked name matches by spelling only, because its identity also names the entries that stay. Any other admission failure still rejects the whole patch up front, even after an unrelated delete.

Deliberately left out: compensation or a partial-effect result for failures that only show up during the write pass (an add whose destination exists, a delete of a missing file, a move onto an existing file, removing a directory, I/O errors, cancellation between writes). Those still behave as on main and need the maintainer decision above. For the same reason this PR does not close the issue on its own; keeping #117742 open for that decision is fine.

Scope tradeoff for maintainers: landing this PR means accepting a bounded fix. A patch whose update hunk cannot apply now leaves the workspace untouched, but a patch that fails during the write pass can still leave the effects of earlier hunks in place without reporting them, exactly as on main. Closing that gap needs the compensation or partial-effect decision tracked in #127496.

Where the check cannot predict the state it leaves the hunk to the write pass, which stays authoritative, rather than reject a patch the write pass would accept: an update of the other name of a hardlink that an earlier delete frees, and an unreadable new path whose spelling differs only in case from a path an earlier hunk staged (case-insensitive filesystems keep the spelled case in the identity of a missing path).

Design note: I chose a read-only preflight in front of the unchanged write pass over a staged plan with an undo journal. The staged plan must model every backend precondition (entry kinds, parent topology, symlink handling in the sandbox bridges), and #122933 stalled on exactly that.

The branch is rebased onto current main. The patch parser moved unchanged to `src/agents/apply-patch-parse.ts` (main's current parser, which returns the hunk list directly), and the tests this PR adds live in `src/agents/apply-patch.preflight.test.ts`, so both files stay within the line-cap ratchet.

The existing permission-change fence test now expects the abort at the envelope checkpoint: the read that triggers it happens in the preflight, so the rejection is an `AbortError` that carries the permission-change reason as its cause, and the file still stays unchanged.

Real behavior: an isolated Gateway built from each side (own state directory, loopback port, channels skipped) with a keyless local mock model that makes one agent turn call the real `apply_patch` tool with the envelope from the issue (`Delete File: important.txt`, then `Update File: missing.txt`). The workspace is seeded with `important.txt`.

Before (upstream main, no apply_patch changes since):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after:
== important.txt after: <MISSING>
```

After (this branch, same Gateway setup and turn):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: important.txt
== important.txt after: irreplaceable-user-data
```

Control on this branch, a valid envelope (delete, add, then update of the just-added file) still applies in order:

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
== workspace after: notes.txt
== important.txt after: <MISSING>
```

The Gateway proof above is still valid for this head: its envelope does not involve a link, a hardlink or a path an earlier hunk frees, so it takes the same path as before the link and hardlink staging changes.

Hardlink names in unrestricted mode, same Gateway setup with `tools.exec.applyPatch.workspaceOnly: false`. The workspace holds `original.txt` (`one`) and `alias.txt`, a second hardlink to the same file. The turn sends `Update File: original.txt` (`one` to `two`), then `Update File: alias.txt` (`two` to `three`).

Before (previous head of this branch, rebased onto current main without the hardlink change; main accepts this envelope):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to find expected lines in <workspace>/alias.txt:⏎two"
}
== after: original.txt=one alias.txt=one links=2
```

After (this head):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
M original.txt
M alias.txt
== after: original.txt=three alias.txt=three links=2
```

Tests (`src/agents/apply-patch.preflight.test.ts`, through the real `apply_patch` tool or `applyPatch`):

- Delete before an update of a missing file, and add plus update before a context mismatch: fail on main with the earlier effects committed, pass here. Updates of files added or changed earlier in the same patch, including a move, still apply.
- `Delete File: link.txt` (a symlink to an in-workspace `target.txt`) followed by a mismatched `Update File: target.txt`, or by `Update File: target.txt` / `Move to: link.txt` and a later update of `target.txt`: fail on an earlier head of this branch (the link is deleted before the error) and pass here with the link and target unchanged.
- `Delete File: link.txt`, `Add File: link.txt`, `Update File: target.txt`, `Update File: link.txt`, and `Update File: target.txt` / `Move to: link.txt` after the delete: fail on an earlier head of this branch (false context mismatch on the target, or an in-place rewrite instead of a move) and pass here.
- Outside-link and directory-link replacement (`Delete File: d`, then `Add File: d/x.txt`, `Add File: d/..cache`, `Delete File: d/x.txt`), a regular file replaced by a directory, and both names of a hardlink (re-create the deleted name, or update the other name): sequences main accepts; they fail on earlier heads of this branch, where admission ran only against the snapshot, and pass here.
- A moved symlink path updated again, and an outside-symlink update after an unrelated delete: reject before any mutation.
- Unrestricted mode (`workspaceOnly: false`) with two hardlink names: an update of the second name using text written through the first, alone or after deleting the first name, applies as on main. These cases pass on main, fail on the previous head of this branch, and pass here. A third case (move the first name away, then update the second against the original text) guards that a move does not carry the new contents to the other name.
- A removed outside symlink replaced under different casing (`Delete File: link.txt`, `Add File: LINK.txt`; `Delete File: d`, `Add File: D/x.txt`), gated on a case-insensitive temp volume. Run on macOS 15.7.9 (Intel, case-insensitive APFS) with this head's tests and each side's `src/agents/apply-patch.ts`: main passes both, the previous head of this branch (583baf2) fails both with `Symlink escapes sandbox root`, and this head passes both. The full apply-patch suites pass there on this head (162 passed, 1 Linux-only skip). Linux CI skips these two cases.
- A hardlinked symlink (Linux `link(2)` on a symlink): `Delete File: a` then `Update File: b` for the other name still updates the target, as on main; it fails on an intermediate version of this fix that matched any symlink by identity.
- Fail-to-pass run against main (merge base, Linux): the 7 regression tests above fail on main and pass here. The hardlink cases pass on main and here, and fail when the hardlink staging is removed from this head. The casing cases skip on Linux, so their before/after evidence is the macOS run above.
- `node scripts/run-vitest.mjs src/agents/apply-patch*.test.ts`: 12 files, 161 tests pass on Linux (2 macOS-only skips).
- `pnpm check:changed`: passes on the current head, apart from the dead export scan, which fails only on exports in files this PR does not touch (`src/plugins/config-policy.ts`, `src/media-understanding/defaults.ts`) and was skipped for the rerun.
- Review: a fresh-context code review at high effort, repeated after each round of fixes; its confirmed findings (move detection after a link delete, hardlink and directory-link replacement, held queue keys for removed link paths, case-folded link detection on the host, `..`-prefixed names under a removed link, abort checks during resolution) are fixed and covered above. A fresh-context review of the hardlink change found no correctness issue; it traced further hardlink, symlink and move sequences, which all matched the ordered writer, and the one wording note it raised is applied. A fresh-context review of the casing change found that a hardlinked symlink's identity also names its other entries (a delete of one name then made an update of the other reject); identity matching now requires a single link, with a regression test.

| Test file | `pnpm test <file> --maxWorkers=1` wall | CI seconds | New cases |
| --- | --- | --- | --- |
| `src/agents/apply-patch.preflight.test.ts` | 6.0 s (20 tests, 2 skip on Linux) | pending for this head | 20 cases, each under 15 ms of test time |
| `src/agents/apply-patch.test.ts` | 6.3 s | pending for this head | none (one assertion changed) |

Verified on macOS arm64 through an isolated, built Gateway and the real `openclaw agent` CLI. The Gateway used fresh state, workspace and HOME, loopback-only ports, and a local OpenAI Responses fixture model following the repository's existing HTTP/SSE test contract. No production state, personal API credentials, or CLI-login credentials were used. The model request advertised the real `apply_patch` tool; the next model request contained its actual `function_call_output` from the filesystem operation.

Baseline: `372ff7cacef` (fresh main). Candidate: contributor head merged with that main, then simplified; final head `e8d17b1d604780c1e351f74ef7e221fde5ba1967`. Runtime E2E ran at `6353875b56e` and again at `d908d9ea2d4`; the final commit only restores the existing permission-fence test assertion, without changing production code.

| Real Gateway scenario | Main | Candidate / simplified head |
| --- | --- | --- |
| Delete `important.txt`, then update missing `missing.txt` | Tool reports the missing-file error; `important.txt` is permanently missing | Same tool error; `important.txt` retains `irreplaceable-user-data⏎` |
| Add `created.txt`, rewrite `important.txt`, then fail a later context match | Not rerun on main | Simplified head rejects; only the unchanged original `important.txt` remains |
| Valid delete, add `notes.txt`, then update the newly added file | Not rerun on main | Simplified head succeeds; `notes.txt` contains `final⏎` |

Redacted model-visible failing result on both sides:

```json
{
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
```

The valid control returned:

```text
Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
```

All task-owned Gateways and fixture model servers were stopped. This is deterministic model-boundary proof, not a claim about live model behavior or commit-time rollback.

Checks:
- Baseline full `pnpm build`, candidate and simplified `pnpm build:runtime`: passed.
- All nine `apply-patch*.test.ts` suites were exercised. Initial result: 151 passed, one Linux-only skip, one outdated permission-error assertion failed. After restoring that assertion to main's existing contract, the affected suite passed all 51 tests. The other eight suites' passing results remain applicable.
- `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`: passed.
- `node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.agents-root.json --noEmit`: passed, including after the assertion repair.
- Scoped Oxlint and Oxfmt: passed.
- `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`: passed.
- UI was not changed; no UI typecheck was needed.

Preserved the contributor's commits and merged current main without rebasing or force-pushing. The merge retains main's `ToolInputError` classification and its already-simplified parser in the extracted parser module. Replaced two temporary-array constructions in patch staging with direct iteration, including removal of the tuple assertion. Restored main's existing permission-change assertion because the current guarded read rejects before the envelope checkpoint; the test still proves the file remains unchanged.

The ordered staging, link/hardlink identity handling, and distinct filesystem regression cases are retained: they preserve accepted ordered patches while adding preflight, rather than pursuing a separate behavior change. No new rollback or partial-effect contract was introduced.

Final diff against the main merge base: production +725/-299 (net +426); tests +434/-0. Parser extraction accounts for +218 production lines; the required ordered preflight and filesystem-identity handling account for the remaining growth. The original `apply-patch.test.ts` has no net diff from main.

No overlap with Pash/Sarah changes in the touched files. Full diff security read found no new network access, credential reads, package/lockfile changes, or build-script changes. The contributor had 123 merged OpenClaw PRs at inspection.

The broader durability decision in #117742 / #127496 remains open: commit-time I/O failures, cancellation between writes, and other write-pass failures can still leave partial effects. This PR is the bounded update-preflight improvement and should not close those issues by itself.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 5348bbc)
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 22, 2026
…date hunk cannot apply (#160409)

Related: #117742

## What Problem This Solves

Fixes: a multi-file `apply_patch` call permanently deletes, creates, or rewrites earlier files when a later update hunk targets a missing file or its context lines do not match, while the tool only reports the later error.

## User Impact

User impact: when an update hunk in a patch cannot apply, the whole patch now rejects before any file changes, so the workspace is left exactly as it was and the agent's retry starts from the state it expects.

## Why This Change Was Made

The issue and #127496 leave one durability question open: after a failure that happens while files are being written (I/O error, a competing writer, cancellation mid-commit), should `apply_patch` compensate, or keep the earlier effects and report them? This PR does not make that choice. It implements only the part both options in the ClawSweeper review share, which is also the first step of the repair described in #127496: validate the ordered envelope before writing, while holding the file queues for the whole envelope.

- All hunk targets resolve first, and the patch holds the file-mutation queue for every path it touches for the whole run, so the check reads the same state the writes act on.
- Every update hunk is then computed in order before anything is written, with the same `applyUpdateHunk` the write pass uses. Earlier adds, updates, deletes and moves in the same patch are staged by physical file identity, so an update of a file added or changed earlier in the patch still works, and an update of a file an earlier hunk deletes or moves away rejects up front. A missing file, a context mismatch or invalid UTF-8 rejects with no mutation.
- Links are staged apart from the files they name. Queue identity follows a final symlink, so a link and its target share one key, but deleting the link leaves the target in place. A delete or move of a final symlink therefore stages the link path by its spelling, and later hunks at or under that path (`Add File: link`, `Update File: link`, `Move to: link`, `Add File: dir-link/x.txt`) use that path stage, which starts out removed. The target keeps its own staged contents, so `Delete File: link` followed by a mismatched `Update File: target` now rejects before the link is deleted, and `Delete File: link`, `Add File: link`, `Update File: target` no longer checks the target against the new link contents. The write pass decides whether an update is a move from the same stages, so `Update File: target` with `Move to: link` after `Delete File: link` moves the file instead of rewriting it in place.
- Names of one hardlinked file share staged contents in unrestricted host mode (`workspaceOnly: false`), where an update rewrites the file in place and every name sees it. Each name has its own queue identity, so an update hunk of a hardlinked file (more than one link at the snapshot) stages by the file's device and inode instead, until an earlier hunk in the patch deletes, re-creates or moves that name. `Update File: a` followed by `Update File: b` whose context matches the text written through `a` applies again, as it does on main. Moving one name away leaves the shared contents for the other names. Confined mode refuses hardlink aliases, and the sandbox helpers refuse hardlinked reads and replace files atomically, so neither shares contents across names.
- Path admission for a later hunk runs against the initial snapshot. When an earlier removal changes what admission sees (a symlink or file replaced by a regular file or directory, or the last other name of a hardlink), that hunk repeats strict admission in the write pass right before it runs, after the earlier hunk has removed the path. The link target is never read or written. A later path matches an earlier host symlink removal by the link entry's own identity (`lstat` device and inode) as well as by spelling, so the filesystem decides which spellings name the removed link: on a case-insensitive volume, `Delete File: link.txt` then `Add File: LINK.txt` (or `Add File: D/x.txt` after `Delete File: d`) replaces the link as it does on main. A symlink with more than one hardlinked name matches by spelling only, because its identity also names the entries that stay. Any other admission failure still rejects the whole patch up front, even after an unrelated delete.

Deliberately left out: compensation or a partial-effect result for failures that only show up during the write pass (an add whose destination exists, a delete of a missing file, a move onto an existing file, removing a directory, I/O errors, cancellation between writes). Those still behave as on main and need the maintainer decision above. For the same reason this PR does not close the issue on its own; keeping #117742 open for that decision is fine.

Scope tradeoff for maintainers: landing this PR means accepting a bounded fix. A patch whose update hunk cannot apply now leaves the workspace untouched, but a patch that fails during the write pass can still leave the effects of earlier hunks in place without reporting them, exactly as on main. Closing that gap needs the compensation or partial-effect decision tracked in #127496.

Where the check cannot predict the state it leaves the hunk to the write pass, which stays authoritative, rather than reject a patch the write pass would accept: an update of the other name of a hardlink that an earlier delete frees, and an unreadable new path whose spelling differs only in case from a path an earlier hunk staged (case-insensitive filesystems keep the spelled case in the identity of a missing path).

Design note: I chose a read-only preflight in front of the unchanged write pass over a staged plan with an undo journal. The staged plan must model every backend precondition (entry kinds, parent topology, symlink handling in the sandbox bridges), and #122933 stalled on exactly that.

The branch is rebased onto current main. The patch parser moved unchanged to `src/agents/apply-patch-parse.ts` (main's current parser, which returns the hunk list directly), and the tests this PR adds live in `src/agents/apply-patch.preflight.test.ts`, so both files stay within the line-cap ratchet.

The existing permission-change fence test now expects the abort at the envelope checkpoint: the read that triggers it happens in the preflight, so the rejection is an `AbortError` that carries the permission-change reason as its cause, and the file still stays unchanged.

## Evidence

Real behavior: an isolated Gateway built from each side (own state directory, loopback port, channels skipped) with a keyless local mock model that makes one agent turn call the real `apply_patch` tool with the envelope from the issue (`Delete File: important.txt`, then `Update File: missing.txt`). The workspace is seeded with `important.txt`.

Before (upstream main, no apply_patch changes since):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after:
== important.txt after: <MISSING>
```

After (this branch, same Gateway setup and turn):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: important.txt
== important.txt after: irreplaceable-user-data
```

Control on this branch, a valid envelope (delete, add, then update of the just-added file) still applies in order:

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
== workspace after: notes.txt
== important.txt after: <MISSING>
```

The Gateway proof above is still valid for this head: its envelope does not involve a link, a hardlink or a path an earlier hunk frees, so it takes the same path as before the link and hardlink staging changes.

Hardlink names in unrestricted mode, same Gateway setup with `tools.exec.applyPatch.workspaceOnly: false`. The workspace holds `original.txt` (`one`) and `alias.txt`, a second hardlink to the same file. The turn sends `Update File: original.txt` (`one` to `two`), then `Update File: alias.txt` (`two` to `three`).

Before (previous head of this branch, rebased onto current main without the hardlink change; main accepts this envelope):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to find expected lines in <workspace>/alias.txt:⏎two"
}
== after: original.txt=one alias.txt=one links=2
```

After (this head):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
M original.txt
M alias.txt
== after: original.txt=three alias.txt=three links=2
```

Tests (`src/agents/apply-patch.preflight.test.ts`, through the real `apply_patch` tool or `applyPatch`):

- Delete before an update of a missing file, and add plus update before a context mismatch: fail on main with the earlier effects committed, pass here. Updates of files added or changed earlier in the same patch, including a move, still apply.
- `Delete File: link.txt` (a symlink to an in-workspace `target.txt`) followed by a mismatched `Update File: target.txt`, or by `Update File: target.txt` / `Move to: link.txt` and a later update of `target.txt`: fail on an earlier head of this branch (the link is deleted before the error) and pass here with the link and target unchanged.
- `Delete File: link.txt`, `Add File: link.txt`, `Update File: target.txt`, `Update File: link.txt`, and `Update File: target.txt` / `Move to: link.txt` after the delete: fail on an earlier head of this branch (false context mismatch on the target, or an in-place rewrite instead of a move) and pass here.
- Outside-link and directory-link replacement (`Delete File: d`, then `Add File: d/x.txt`, `Add File: d/..cache`, `Delete File: d/x.txt`), a regular file replaced by a directory, and both names of a hardlink (re-create the deleted name, or update the other name): sequences main accepts; they fail on earlier heads of this branch, where admission ran only against the snapshot, and pass here.
- A moved symlink path updated again, and an outside-symlink update after an unrelated delete: reject before any mutation.
- Unrestricted mode (`workspaceOnly: false`) with two hardlink names: an update of the second name using text written through the first, alone or after deleting the first name, applies as on main. These cases pass on main, fail on the previous head of this branch, and pass here. A third case (move the first name away, then update the second against the original text) guards that a move does not carry the new contents to the other name.
- A removed outside symlink replaced under different casing (`Delete File: link.txt`, `Add File: LINK.txt`; `Delete File: d`, `Add File: D/x.txt`), gated on a case-insensitive temp volume. Run on macOS 15.7.9 (Intel, case-insensitive APFS) with this head's tests and each side's `src/agents/apply-patch.ts`: main passes both, the previous head of this branch (583baf2) fails both with `Symlink escapes sandbox root`, and this head passes both. The full apply-patch suites pass there on this head (162 passed, 1 Linux-only skip). Linux CI skips these two cases.
- A hardlinked symlink (Linux `link(2)` on a symlink): `Delete File: a` then `Update File: b` for the other name still updates the target, as on main; it fails on an intermediate version of this fix that matched any symlink by identity.
- Fail-to-pass run against main (merge base, Linux): the 7 regression tests above fail on main and pass here. The hardlink cases pass on main and here, and fail when the hardlink staging is removed from this head. The casing cases skip on Linux, so their before/after evidence is the macOS run above.
- `node scripts/run-vitest.mjs src/agents/apply-patch*.test.ts`: 12 files, 161 tests pass on Linux (2 macOS-only skips).
- `pnpm check:changed`: passes on the current head, apart from the dead export scan, which fails only on exports in files this PR does not touch (`src/plugins/config-policy.ts`, `src/media-understanding/defaults.ts`) and was skipped for the rerun.
- Review: a fresh-context code review at high effort, repeated after each round of fixes; its confirmed findings (move detection after a link delete, hardlink and directory-link replacement, held queue keys for removed link paths, case-folded link detection on the host, `..`-prefixed names under a removed link, abort checks during resolution) are fixed and covered above. A fresh-context review of the hardlink change found no correctness issue; it traced further hardlink, symlink and move sequences, which all matched the ordered writer, and the one wording note it raised is applied. A fresh-context review of the casing change found that a hardlinked symlink's identity also names its other entries (a delete of one name then made an update of the other reject); identity matching now requires a single link, with a regression test.

| Test file | `pnpm test <file> --maxWorkers=1` wall | CI seconds | New cases |
| --- | --- | --- | --- |
| `src/agents/apply-patch.preflight.test.ts` | 6.0 s (20 tests, 2 skip on Linux) | pending for this head | 20 cases, each under 15 ms of test time |
| `src/agents/apply-patch.test.ts` | 6.3 s | pending for this head | none (one assertion changed) |

## Maintainer E2E verification

Verified on macOS arm64 through an isolated, built Gateway and the real `openclaw agent` CLI. The Gateway used fresh state, workspace and HOME, loopback-only ports, and a local OpenAI Responses fixture model following the repository's existing HTTP/SSE test contract. No production state, personal API credentials, or CLI-login credentials were used. The model request advertised the real `apply_patch` tool; the next model request contained its actual `function_call_output` from the filesystem operation.

Baseline: `372ff7cacef` (fresh main). Candidate: contributor head merged with that main, then simplified; final head `e8d17b1d604780c1e351f74ef7e221fde5ba1967`. Runtime E2E ran at `6353875b56e` and again at `d908d9ea2d4`; the final commit only restores the existing permission-fence test assertion, without changing production code.

| Real Gateway scenario | Main | Candidate / simplified head |
| --- | --- | --- |
| Delete `important.txt`, then update missing `missing.txt` | Tool reports the missing-file error; `important.txt` is permanently missing | Same tool error; `important.txt` retains `irreplaceable-user-data⏎` |
| Add `created.txt`, rewrite `important.txt`, then fail a later context match | Not rerun on main | Simplified head rejects; only the unchanged original `important.txt` remains |
| Valid delete, add `notes.txt`, then update the newly added file | Not rerun on main | Simplified head succeeds; `notes.txt` contains `final⏎` |

Redacted model-visible failing result on both sides:

```json
{
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
```

The valid control returned:

```text
Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
```

All task-owned Gateways and fixture model servers were stopped. This is deterministic model-boundary proof, not a claim about live model behavior or commit-time rollback.

Checks:
- Baseline full `pnpm build`, candidate and simplified `pnpm build:runtime`: passed.
- All nine `apply-patch*.test.ts` suites were exercised. Initial result: 151 passed, one Linux-only skip, one outdated permission-error assertion failed. After restoring that assertion to main's existing contract, the affected suite passed all 51 tests. The other eight suites' passing results remain applicable.
- `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`: passed.
- `node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.agents-root.json --noEmit`: passed, including after the assertion repair.
- Scoped Oxlint and Oxfmt: passed.
- `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`: passed.
- UI was not changed; no UI typecheck was needed.

## Maintainer simplification

Preserved the contributor's commits and merged current main without rebasing or force-pushing. The merge retains main's `ToolInputError` classification and its already-simplified parser in the extracted parser module. Replaced two temporary-array constructions in patch staging with direct iteration, including removal of the tuple assertion. Restored main's existing permission-change assertion because the current guarded read rejects before the envelope checkpoint; the test still proves the file remains unchanged.

The ordered staging, link/hardlink identity handling, and distinct filesystem regression cases are retained: they preserve accepted ordered patches while adding preflight, rather than pursuing a separate behavior change. No new rollback or partial-effect contract was introduced.

Final diff against the main merge base: production +725/-299 (net +426); tests +434/-0. Parser extraction accounts for +218 production lines; the required ordered preflight and filesystem-identity handling account for the remaining growth. The original `apply-patch.test.ts` has no net diff from main.

No overlap with Pash/Sarah changes in the touched files. Full diff security read found no new network access, credential reads, package/lockfile changes, or build-script changes. The contributor had 123 merged OpenClaw PRs at inspection.

The broader durability decision in #117742 / #127496 remains open: commit-time I/O failures, cancellation between writes, and other write-pass failures can still leave partial effects. This PR is the bounded update-preflight improvement and should not close those issues by itself.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 5348bbc)
Co-authored-by: RomneyDa <[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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

agents: failed multi-file apply_patch leaves earlier deletions committed

1 participant