Skip to content

Commit f653f86

Browse files
fix(apply-patch): refuse a move whose destination names the file it moves from
The move branch compared change.path with change.movePath as strings and, finding two strings, published the destination and then unlinked the source. Under an alias the two strings name one file: the write lands, the unlink at the end of the branch removes what was just written, and the bookkeeping below counts both paths as published, so the tool reports a move that deleted the file. Nothing in a patch says a move onto the file it came from is a delete, so the pair is now refused at ApplyPatchTool.ts:594-:643, between the outside-workspace refusal (:584-:592) and the destination save (:645). The order is the point: the refusal lands before the content is published, before the unlink, and before the tracker or the write result hears about the file, which leaves every file exactly as it was found. Sameness is asked of the filesystem, not of the strings. identityOf (:618) takes a bigint stat of each spelling and sorts a failure into absent (ENOENT) or refused (everything else); _sameFileIdentity (:36) compares dev+ino as bigints, the pair the write owner compares at safeWriteText.ts:247-:265, and requires both fields to actually be bigints before comparing. The bigints are why the compare is not numeric: 2^53 and 2^53+1 are the same double, so a large inode can make two files look alike or one file look like two. The two spellings are deliberately not canonicalized first - canonicalizing answers "which file does this name refer to", which is the question the write owner asks under its own lock, and folding the alias here would leave the identity question unasked while refusing moves that ought to happen. What changes for a caller: - a same-file move is a tool error naming both identities ("... the two paths name the same file (dev .., ino ..), so the move would publish onto it and then unlink what it just published"), with the mistake counter, the tool-error record, the error say, the tool result and the diff-view reset: the shape the outside-workspace refusal above it already uses. - a spelling the filesystem will not stat is also a refusal, and that is new surface: nothing used to ask, so nothing could refuse. A refusal is not read as "different files" - guessing is what produced the deletion. Neither stat is allowed to throw through this handler, because an exception here would replace the tool error the user should get. - an absent source (ENOENT) is not this row's claim and its handling is unchanged. Tests. Five rows in applyPatchTool.execute.spec.ts: the three consequences of a same-file move (nothing is written, the source is not unlinked, one refusal is reported rather than two published files), the alias case that must still move (a junction directory on the destination side over two different inodes - destination published, source unlinked, file context tracked), and an identity refusal (the destination's stat answers EACCES: the move is a tool error and the provider's handleError is never reached). A fifth row guards the numeric range: it seeds BASE_INO = 2n ** 53n and NEIGHBOUR_INO = BASE_INO + 1n and asserts before the move that Number(BASE_INO) equals Number(NEIGHBOUR_INO), so the fixture announces if it ever stops demonstrating a rounded collision instead of passing quietly. Three corrections the rows forced, all in the doubles: - the fs/promises double answered one identity for every path. That was a question nothing was asking. It now answers per spelling, and the five destination observation-token seeds that carried the source's inode (4242) carry the destination's own (4343): those seeds had been asserting the collision by accident. - the guarded-write beforeEach re-arms the default stat implementation, because vi.clearAllMocks() keeps implementations and a row that installs its own would leak forward. - writeFile was added to the mockedFsPromises cast (ReturnType<typeof vi.fn>, reason in the comment: the module's writeFile is an overload set a double cannot express). Controls measured, each a temporary revert of one boundary against the shipped text: identity taken from the two strings being equal - 3 failed | 41 passed: exactly the three consequence rows, a stat refusal read as "absent" - 1 failed | 43 passed: exactly the row that names the refusal, identity compared as rounded Numbers - 1 failed | 43 passed: exactly the safe-integer row. A fourth variant is recorded for what it does not prove: dropping the ino half of the compare reddened 13 rows, because fixture pairs that collide on inode have nothing to do with identity. That is a whole-feature revert rather than a control of this boundary, and it is not counted. Restored: 44 passed (44), product file byte-identical to the controlled text. Said plainly: the typeof-bigint guards in _sameFileIdentity are exercised by no row. A stat taken with { bigint: true } always answers bigints; the guards make a double that answers numbers fail the identity test loudly rather than match loosely. Lanes: measured on the tree this push carries - 13 writer-family files (applyPatchTool.execute, applyPatchTool.partial, guardedWrite, DiffViewProvider, safeWriteText, safeWriteText.stagingAlias, safeWriteJson.lockKey, safeWriteJson.stagingDirectory and the five TaskHistoryStore specs) - 518 passed (518), of which applyPatchTool.execute.spec.ts is 44 passed (44). tsc --noEmit -p . reports only the junction artefact at activate/registerCommands.ts(88,102); eslint --prune-suppressions --max-warnings=0 exits 0 on both touched files and src/eslint-suppressions.json equals HEAD; prettier --check clean on both. No it.runIf added or removed by this commit, and nothing here is gated on a platform label - the ubuntu and windows lanes execute both suites. The alias row's geometry is the double's inode table, not a link on disk: this lane cannot create a file symlink (fs.symlink answers EPERM here, as the alias rows in safeWriteText.spec record) and a mocked stat would not be exercised by a real junction either. What the row proves is that the compare is asked about identities rather than spellings; the link itself is proven by the rows that take the filesystem for real.
1 parent c72de0c commit f653f86

2 files changed

Lines changed: 314 additions & 14 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "fs/promises"
2+
import type { BigIntStats } from "fs"
23
import path from "path"
34

45
import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
@@ -24,6 +25,25 @@ interface ApplyPatchParams {
2425
patch: string
2526
}
2627

28+
/**
29+
* Whether two stats name one file, judged the way the compares around this handler judge it: as
30+
* bigints, because on NTFS and ReFS a file identity can exceed Number.MAX_SAFE_INTEGER and a
31+
* rounded value makes two files look alike or two spellings of one file look different. Both sides
32+
* have to actually carry a bigint identity - a stat that does not is a double that was never asked
33+
* to answer identity, and reading it as "the same file" would refuse ordinary moves for a shape no
34+
* real filesystem produces.
35+
*/
36+
function _sameFileIdentity(left: BigIntStats, right: BigIntStats): boolean {
37+
return (
38+
typeof left.ino === "bigint" &&
39+
typeof right.ino === "bigint" &&
40+
typeof left.dev === "bigint" &&
41+
typeof right.dev === "bigint" &&
42+
left.ino === right.ino &&
43+
left.dev === right.dev
44+
)
45+
}
46+
2747
export class ApplyPatchTool extends BaseTool<"apply_patch"> {
2848
readonly name = "apply_patch" as const
2949

@@ -571,6 +591,57 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
571591
return
572592
}
573593

594+
// A move whose destination names the same file as its source publishes onto that file and
595+
// then unlinks it: the write lands, the unlink at the end of this branch removes what was
596+
// just written, and the bookkeeping below counts both paths as published. No reading of a
597+
// move patch makes deleting the file you just wrote a correct outcome, so the pair is refused
598+
// here - before the save, before the unlink, before the tracker call - which leaves every file
599+
// exactly as it was found.
600+
//
601+
// Sameness is asked of the filesystem rather than of the two strings. Under an alias two
602+
// spellings name one file, and across an alias one spelling names two files, so a string
603+
// compare is wrong in both directions: it would refuse the alias-spelled move that ought to
604+
// happen and allow the two-names-one-file move that ought not. The identity is read as bigints
605+
// for the reason the compare beside it gives (safeWriteText.ts:247-:265): on NTFS and ReFS a
606+
// file identity can exceed Number.MAX_SAFE_INTEGER, and a rounded value makes two files look
607+
// alike or one file look like two.
608+
//
609+
// Both stats are taken on the spellings the patch named, resolved against the workspace and
610+
// deliberately not canonicalized: canonicalizing first would fold an alias's two spellings
611+
// into one string here and leave the identity question unasked.
612+
//
613+
// A refusal to answer is not read as "different files". Neither stat is allowed to throw
614+
// through this handler: an exception here would replace the tool error the user should get,
615+
// which is the mistake the note above the outside-workspace refusal records for canonicalising
616+
// a destination that was about to be refused. Absence is read as what it means - a destination
617+
// that is not there is not the same file as the source - and a refusal refuses the move.
618+
const identityOf = async (target: string): Promise<BigIntStats | "absent" | "refused"> => {
619+
try {
620+
return await fs.stat(target, { bigint: true })
621+
} catch (error: unknown) {
622+
return errorCode(error) === "ENOENT" ? "absent" : "refused"
623+
}
624+
}
625+
const sourceIdentity = await identityOf(absolutePath)
626+
const destinationIdentity = await identityOf(moveAbsolutePath)
627+
const moveRefusal =
628+
sourceIdentity === "refused" || destinationIdentity === "refused"
629+
? "the filesystem would not say what either path refers to, so the tool cannot tell whether the two names are one file"
630+
: sourceIdentity !== "absent" &&
631+
destinationIdentity !== "absent" &&
632+
_sameFileIdentity(sourceIdentity, destinationIdentity)
633+
? `the two paths name the same file (dev ${String(sourceIdentity.dev)}, ino ${String(sourceIdentity.ino)}), so the move would publish onto it and then unlink what it just published`
634+
: undefined
635+
if (moveRefusal !== undefined) {
636+
task.consecutiveMistakeCount++
637+
task.recordToolError("apply_patch")
638+
const errorMessage = `Cannot move ${change.path} onto ${change.movePath}: ${moveRefusal}`
639+
await task.say("error", errorMessage)
640+
pushToolResult(formatResponse.toolError(errorMessage))
641+
await task.diffViewProvider.reset()
642+
return
643+
}
644+
574645
// Save new content to the new path
575646
if (isPreventFocusDisruptionEnabled) {
576647
// The destination content is the source file plus one targeted hunk, so it can

0 commit comments

Comments
 (0)