Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
9110b19 to
a350837
Compare
|
Codex review: found issues before merge. Reviewed August 18, 2026, 10:37 PM ET / August 19, 2026, 02:37 UTC. ClawSweeper reviewWhat this changesStages multi-file apply_patch envelopes before ordered commits so predictable later failures do not leave earlier workspace changes behind. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readinessKeep 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 Review scores
Verification
Live VerificationCommand: Result: FAIL (failed) — execution before step 1 Assertions:
How this fits togetherapply_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]
Decision needed
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
Findings
Agent review detailsSecurityNone. PR surfaceSource +248, Tests +147. Total +395 across 7 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 23da04ba8af4. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
a350837 to
2bd5bee
Compare
|
Refreshed at head 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 Your Resolve merge risk (P1), file-as-parent commit-time failure - fixed. Same repair. Four new cases in 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 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: |
2bd5bee to
4f7339a
Compare
|
Refreshed at head Reject directory Delete File targets during staging (P1) - fixed. You read it correctly: 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 The focused host regression is 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 Gates on this head: |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Verdict at Preserve final-symlink kind in sandbox staging (P1) - not reproducible, rebutting. The premise is that
So the sandbox The host side already carries the regression you asked for and it is green on this head: I did not add a remote-sandbox regression for this, because there is no behavior change to pin: the only sandbox seam involved is 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 Resolve merge risk, production +167 (P1) - answered, still yours to accept. The overlay stays one canonical owner and gained no backend-specific exception: 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: |
|
Correction: my previous comment was wrong and I am withdrawing the rebuttal. You are right. I checked only
So on the remote backend my new I have not pushed a fix, because the repair is not confined to
My preference is 1, and I will implement it with the remote-bridge regression on your word. Tell me which you want, or apply For the record on the other open lines: production is +167 net with the overlay as one canonical owner; the |
|
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. |
…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]>
…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]>
…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]>
…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]>
What Problem This Solves
Fixes #117742.
A multi-file
apply_patchenvelope 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 deletesimportant.txtwhen 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
applyPatchinto stage and commit phases inside one combined mutation queue over every path the envelope touches:stagePatchHunksvalidates 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.commitStagedPatchOpsthen 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.Staged ancestor topology
The first revision of this PR staged file contents but not directory topology. Commit runs
mkdirpfor every created path, so an envelope that addsnodeand thennode/childpassed staging, committednodeas a file, and then failed insidemkdirpwith a preceding delete already durable. The same hole existed whennodewas 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.
stageParentDirswalks 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.existsbecamePatchFileOps.entryKindto make that distinction available: the host backends maplstattofile,directory, orother, and the sandbox backend forwards thetypeitsstatbridge already returns. Symlinks stayotherand 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.
stagedExistsreturned true for any entry, including a directory, so an envelope that deletesimportant.txtand then targets a non-empty directory queued both, and the removal contract rejected the directory only during commit, afterimportant.txtwas already gone.stagedExistsis nowstagedEntryKind, the same overlay-aware lookup returning the entry kind instead of a boolean, and the Delete File branch rejects adirectorytarget 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-recursivefs.rm, and the sandbox bridge removes withforce: false. Deleting a symlink is untouched on the host backends and on the local sandbox bridge. The host backends classify a link throughlstatasother, neverdirectory. The local sandbox bridge is link-preserving for the same reason:resolveAnchoredSandboxEntrycanonicalizes only the parent and applies the basename afterwards, andbuildStatPlanrunsstat -c "%F|%s|%y"without-L, so a link reportssymbolic link, whichcoerceStatTypemaps toother.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 tocanonicalPathbefore statting it, so a symlink to a directory reportsdirectory, while itsremovepins the parent withallowFinalSymlinkForUnlink: trueand unlinks the basename. On that backend the new staging rejection therefore refuses aDelete Filethat the remover would have unlinked.SandboxFsBridge.stathas 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 existingapply-patch-update.tsandapply-patch-file-ops.tsfamily. That dropsapply-patch.tsfrom 673 to 527 lines and clears themax-linesbudget 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_patchcall 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:
Cannot delete <path>: the file was not found.before any hunk commits.Cannot delete <path>: it is a directory, not a file.during staging, instead of surfacing a backenddirectory is not emptyerror after earlier hunks committed. Deleting an empty directory throughDelete Filealso 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.directory component must be a directoryerror 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 inapply-patch-staging.test.tsfail 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.keeps an earlier delete uncommitted when a later delete targets a directoryseedsimportant.txtplus a non-emptynode/, submits a Delete File pair, and asserts both the file and the nested file survive the rejection. On pre-fix code it fails withdirectory is not empty ... The patch was partially applied before this failure: deleted important.txt.node scripts/run-oxlint.mjsclean on all four changed source files, including themax-linesbudget that the parser extraction restored.node scripts/run-tsgo.mjs -p tsconfig.core.jsonand-p test/tsconfig/tsconfig.core.test.jsonboth clean.oxfmtclean on all changed files.entryKindwiring on the sibling surface.apply-patch.test.tstosrc/agents/test-helpers/apply-patch-fixtures.tsso both suites use one copy.agent-tools.create-openclaw-coding-tools.test.tsupdated to the new contract: a conflictingAdd Filenow rejects during staging before any provenance write happens, so no rollback fires.agent-tools.create-openclaw-coding-tools.test.ts > resolves Unicode-equivalent filenames through sandbox operationsfails on this macOS box with and without this patch, from APFS Unicode normalization in thereadtool. 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 Fileon 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:
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 Fileon a symbolic link pointing at a directory still applies, unlinks the link itself, and leaves the aliased data readable, becauselstatclassifies a link asotherand only a realdirectoryis 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.