// npx vitest run core/tools/__tests__/applyPatchTool.execute.spec.ts import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import path from "path" import * as fsPromises from "fs/promises" import type { Task } from "../../task/Task" import { ObservationRegistry } from "../../task/observationRegistry" import { guardedWrite, type GuardedWriteKind, type GuardedWriteOptions } from "../guardedWrite" import { ApplyPatchTool } from "../ApplyPatchTool" import { CommittedWriteBufferConflictError } from "../../../integrations/editor/committedWriteBufferConflictError" import { PostCommitDurabilityError } from "../../../services/file-safety/safeWriteText" // The vi.mock factory exposes the fs/promises functions under a `default` // property (matching the SUT's default import), which the static module type // does not declare; cast once at this boundary rather than at each call site. const mockedFsPromises = vi.mocked( fsPromises as unknown as { default: { access: MockedFunction readFile: ReturnType stat: ReturnType unlink: MockedFunction // Added for the outside-workspace refusal row: the refused destination must not be canonicalised. realpath: ReturnType // Added for the same-file move rows, which ask whether any write landed at the destination. // Typed loosely because fsPromises.writeFile carries an overload set that MockedFunction // would collapse to one arbitrary member; the rows only ever ask whether it was called. writeFile: ReturnType // Added for the flag-off move rows: the raw branch mkdirs the destination's parent before // writing, and the rows ask whether that mkdir ran. Typed loosely for the same reason as // writeFile above - fsPromises.mkdir is overloaded and the rows only ever ask about calls. mkdir: ReturnType } }, ) vi.mock("fs/promises", () => { // The SUT imports the module two ways: applyPatchTool uses the default // export, safeWriteText uses the namespace. Both must see the same doubles. const doubles = { // The target exists on disk, so the completeness gate applies to the // follow-up guarded write in the partial-observation test. access: vi.fn().mockResolvedValue(undefined), // Raw bytes: the SUT reads without an encoding so a strict decoder can see the file as // the file is, and this double has to answer the same way the real readFile() does. readFile: vi.fn().mockResolvedValue(Buffer.from("original file content\n")), // On-disk identity for the S2 self-read observation (the hunk read stats before and after; // equal tokens record the observe) and for the move handler's same-file check. Answered per // path by _identityOf below. stat: vi.fn((target: unknown) => Promise.resolve(_identityOf(String(target)))), unlink: vi.fn().mockResolvedValue(undefined), // resolveLockKey canonicalizes the lock key, so the guard needs these // even when no symlink is involved. lstat: vi.fn().mockResolvedValue({ isSymbolicLink: () => false }), readlink: vi.fn().mockRejectedValue(new Error("not a symbolic link")), realpath: vi.fn(async (p: string) => String(p)), // safeWriteText creates the backup directory before publishing. mkdir: vi.fn().mockResolvedValue(undefined), // The flag-off move branch (ApplyPatchTool.ts:610-:612) publishes with a raw // fs.writeFile, so the double set needs writeFile as well as mkdir. writeFile: vi.fn().mockResolvedValue(undefined), } return { default: doubles, ...doubles } }) // Mock the shared advisory lock that the guarded-write path uses; the real // proper-lockfile would try to create a lock directory on the mocked fs. vi.mock("../../../utils/fileLock", () => ({ withFileLock: vi.fn(async (filePath: string, operation: (p: string) => Promise) => operation(filePath)), })) vi.mock("../../../utils/fs", () => ({ fileExistsAtPath: vi.fn().mockResolvedValue(true), })) vi.mock("../../../utils/pathUtils", () => ({ isPathOutsideWorkspace: vi.fn().mockReturnValue(false), })) // The identity a path answers with. It used to be ONE identity for every path (ino 4242 // everywhere), which was harmless only because nothing asked the question: two names on a // filesystem are two files unless something links them, and the move handler now asks which of the // two its source and its destination are. The double distinguishes exactly the pair the move rows // publish onto - src/new.ts, and the same basename reached through a link of its directory - and // leaves every other path the identity the registry token strings below spell out. A row that wants // two names for one file re-arms stat and says so in its own comment. const _MOVE_SOURCE_INO = 4242n const _MOVE_DESTINATION_INO = 4343n const _MOVE_ALIAS_DESTINATION_INO = 4444n interface FileIdentity { dev: bigint ino: bigint size: bigint mtimeNs: bigint ctimeNs: bigint } function _identityOf(target: string): FileIdentity { const resolvedNew = path.resolve("/workspace/project", "src/new.ts") const resolvedAliasNew = path.resolve("/workspace/project", "src/aliasDir/new.ts") const ino = target === resolvedNew ? _MOVE_DESTINATION_INO : target === resolvedAliasNew ? _MOVE_ALIAS_DESTINATION_INO : _MOVE_SOURCE_INO return { dev: 7n, ino, size: 1234n, mtimeNs: 1_700_000_000_123_456_789n, ctimeNs: 1_700_000_000_789_999_999n, } } describe("ApplyPatchTool.execute - delete file success path", () => { const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction let tool: ApplyPatchTool let mockTask: Pick< Task, | "cwd" | "consecutiveMistakeCount" | "recordToolUsage" | "recordToolError" | "rooIgnoreController" | "rooProtectedController" | "say" | "processQueuedMessages" | "didEditFile" | "observationRegistry" > let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> beforeEach(() => { vi.clearAllMocks() mockedFileExistsAtPath.mockResolvedValue(true) mockedIsPathOutsideWorkspace.mockReturnValue(false) mockTask = { cwd: "/workspace/project", consecutiveMistakeCount: 0, observationRegistry: new ObservationRegistry(), recordToolUsage: vi.fn(), recordToolError: vi.fn(), rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true), } as unknown as Task["rooIgnoreController"], rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false), } as unknown as Task["rooProtectedController"], say: vi.fn().mockResolvedValue(undefined), processQueuedMessages: vi.fn(), didEditFile: false, } mockAskApproval = vi.fn().mockResolvedValue(true) mockHandleError = vi.fn().mockResolvedValue(undefined) mockPushToolResult = vi.fn() tool = new ApplyPatchTool() }) it("deletes the file and records no local tool usage on success", async () => { const patch = `*** Begin Patch *** Delete File: src/obsolete.ts *** End Patch` await tool.execute({ patch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockAskApproval).toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) expect(mockTask.didEditFile).toBe(true) expect(mockHandleError).not.toHaveBeenCalled() // Usage is recorded once at the central presentAssistantMessage // attribution point, not locally by the handler. expect(mockTask.recordToolUsage).not.toHaveBeenCalled() expect(mockTask.recordToolError).not.toHaveBeenCalled() }) }) describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction let tool: ApplyPatchTool let mockTask: Pick< Task, | "cwd" | "consecutiveMistakeCount" | "recordToolError" | "rooIgnoreController" | "rooProtectedController" | "say" | "processQueuedMessages" | "didEditFile" | "diffViewProvider" | "providerRef" | "fileContextTracker" | "observationRegistry" > let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> let mockSaveChanges: MockedFunction<(...args: unknown[]) => Promise> let mockGetState: MockedFunction<() => Promise> let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> const updatePatch = `*** Begin Patch *** Update File: src/thing.ts @@ -original file content +modified file content *** End Patch` const addPatch = `*** Begin Patch *** Add File: src/new.ts +new line one +new line two *** End Patch` const movePatch = `*** Begin Patch *** Update File: src/old.ts *** Move to: src/new.ts @@ -original file content +modified file content *** End Patch` // One patch, one file, two reads: the first update publishes in place, the second // updates the same path again and moves it. apply_patch reads the file per update // entry, so this patch is the shape behind the finding at ApplyPatchTool.ts:701 - // the same path read twice in one execute, and the row below changes the file // between those reads. const updateThenMovePatch = `*** Begin Patch *** Update File: src/old.ts @@ -original file content +modified file content *** Update File: src/old.ts *** Move to: src/new.ts @@ -original file content +modified file content *** End Patch` // One path, two updates, and a write by somebody else between the reads: apply_patch reads the // file per update entry, so the first hunk's content came from a version that is no longer on // disk when its publish runs. The first row below refuses that state. The fixture spells out // which read saw which bytes, so the refusal is about the two versions and not about a chunk // that failed to match: the second hunk targets the content the other writer left. const samePathTwoUpdatesPatch = `*** Begin Patch *** Update File: src/thing.ts @@ -original file content +modified first content *** Update File: src/thing.ts @@ -written by another writer +modified second content *** End Patch` // The same divergence reached through a read that publishes nothing. A delete records the content it // removes and publishes by unlinking, so its own read is not a publish - but the registry keeps one // entry per path, and the guarded publish runs on that standing entry, so a delete read that sees a // newer version still re-bases the publish the update read queued. The rows below take both // directions: one version between the reads publishes, two versions refuse. const updateThenDeletePatch = `*** Begin Patch *** Update File: src/thing.ts @@ -original file content +modified file content *** Delete File: src/thing.ts *** End Patch` // A move that publishes onto a path this same patch also updates, in the two orders the patch // can spell it. The row pair below takes both: the move first is the state where the update's // queued bytes no longer describe the destination, and the update first is the control that // keeps the ordinary shape valid. const moveThenUpdateDestinationPatch = `*** Begin Patch *** Update File: src/old.ts *** Move to: src/new.ts @@ -original file content +modified moved content *** Update File: src/new.ts @@ -original file content +modified second content *** End Patch` // The same two changes the other way round: the in-place update of the destination is read and // saved before anything publishes at that path, so its queued content still describes the file // its save runs on. const updateDestinationThenMovePatch = `*** Begin Patch *** Update File: src/new.ts @@ -original file content +modified second content *** Update File: src/old.ts *** Move to: src/new.ts @@ -original file content +modified moved content *** End Patch` // A delete on its own: one read, one unlink, no content the tool built and no compare-and-swap. const deleteOnlyPatch = `*** Begin Patch *** Delete File: src/thing.ts *** End Patch` // The destination spelled through a link of the same directory, naming its own file: the other // direction of the pair the same-file rows pin below. const moveThroughAliasPatch = `*** Begin Patch *** Update File: src/old.ts *** Move to: src/aliasDir/new.ts @@ -original file content +modified file content *** End Patch` const mismatchedSecondPatch = `*** Begin Patch *** Update File: src/first.ts @@ -original file content +modified first content *** Update File: src/second.ts @@ -context the mocked file does not contain +modified second content *** End Patch` const twoUpdatePatch = `*** Begin Patch *** Update File: src/first.ts @@ -original file content +modified first content *** Update File: src/second.ts @@ -original file content +modified second content *** End Patch` beforeEach(() => { vi.clearAllMocks() mockedFileExistsAtPath.mockResolvedValue(true) // The outside-workspace double is module-level, and vi.clearAllMocks() keeps implementations, // so a row that flips it has to find it back at false. Restored here rather than per row so the // next row does not have to know a neighbour changed it. vi.mocked(isPathOutsideWorkspace).mockReturnValue(false) // vi.clearAllMocks() keeps implementations, and rows below re-arm stat with a one-file-two- // names answer. Restoring the default here means a row does not have to know what a neighbour // installed. mockedFsPromises.default.stat.mockImplementation((target: unknown) => Promise.resolve(_identityOf(String(target))), ) // The vanished-destination row arms an ENOENT answer at the destination; the double keeps // implementations across rows, so the resolve-by-default is restored here rather than // leaving the next row to know its neighbour probed the same name. mockedFsPromises.default.access.mockImplementation(() => Promise.resolve()) mockSaveDirectly = vi.fn().mockResolvedValue({ newProblemsMessage: "", userEdits: undefined, finalContent: "new content", }) mockSaveChanges = vi.fn().mockResolvedValue({ newProblemsMessage: "", userEdits: undefined, finalContent: "new content", }) mockGetState = vi.fn().mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, // Exercise the focus-disruption (saveDirectly) save path. experiments: { preventFocusDisruption: true }, }) // Structural stubs for the guarded-write path: the real DiffViewProvider is // out of scope here, so vi.fn() doubles stand in for the members the tool // touches (the saveDirectly double also records the writeKind plumbing). const diffViewProviderStub = { editType: undefined as "create" | "modify" | undefined, originalContent: undefined as string | undefined, saveDirectly: mockSaveDirectly, saveChanges: mockSaveChanges, open: vi.fn().mockResolvedValue(undefined), update: vi.fn().mockResolvedValue(undefined), scrollToFirstDiff: vi.fn(), pushToolWriteResult: vi.fn().mockResolvedValue("Saved file"), revertChanges: vi.fn().mockResolvedValue(undefined), reset: vi.fn().mockResolvedValue(undefined), } mockTask = { cwd: "/workspace/project", consecutiveMistakeCount: 0, observationRegistry: new ObservationRegistry(), recordToolError: vi.fn(), rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true), } as unknown as Task["rooIgnoreController"], rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false), } as unknown as Task["rooProtectedController"], say: vi.fn().mockResolvedValue(undefined), processQueuedMessages: vi.fn(), didEditFile: false, diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"], providerRef: { deref: vi.fn().mockReturnValue({ getState: mockGetState, }), } as unknown as Task["providerRef"], fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined), } as unknown as Task["fileContextTracker"], } mockAskApproval = vi.fn().mockResolvedValue(true) mockHandleError = vi.fn().mockResolvedValue(undefined) mockPushToolResult = vi.fn() tool = new ApplyPatchTool() }) it("update: publishes the targeted hunk through the guarded saveDirectly with edit kind", async () => { await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/thing.ts", "modified file content\n", false, true, 1000, "edit", undefined, false, undefined, ) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockTask.didEditFile).toBe(true) expect(mockHandleError).not.toHaveBeenCalled() }) // Row 4507764645: the finally sweep withdraws the read behind a publish that never // landed. When the guarded commit landed and only the durability step failed, the guard // re-records at the committed token, and the sweep must leave that entry alone - the // stored entry is no longer the one the tool recorded, so the withdrawal does not fit. it("update: a publish that committed without durability keeps the re-recorded observation", async () => { const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // The double stands in for the guard's own pair of actions - re-record at the // committed token, then report the durability failure - so this row tests the sweep's // identity key, which is ApplyPatchTool's half of the rule. mockSaveDirectly.mockImplementationOnce(async () => { reg.observe(targetKey, "committed-token", false) throw new PostCommitDurabilityError( targetKey, new Error("EBADF: bad file descriptor"), null, "committed-token", ) }) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "PostCommitDurabilityError" }), ) expect(reg.get(targetKey)?.version).toBe("committed-token") expect(mockPushToolResult).not.toHaveBeenCalled() }) it("update: keeps a partial observation partial so a later full-file write is still rejected", async () => { // The hunk read is the tool's own read, not a model read. Upgrading the // model's partial view to complete here would let a later write_to_file // replace the file with content built from the slice the model saw. const key = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry reg.observe(key, "7:4242:1234:1700000000123456789:1700000000789999999", false) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(key)?.complete).toBe(false) // The targeted hunk itself is still allowed, guarded as an edit. expect(mockSaveDirectly).toHaveBeenCalledWith( "src/thing.ts", "modified file content\n", false, true, 1000, "edit", undefined, false, undefined, ) await expect(guardedWrite(mockTask as Task, "src/thing.ts", "full replacement", "update")).rejects.toThrow( "File was only partially read (line slice, range, truncated view, or indentation block) -- " + "a full-file replacement needs the complete content; re-read the whole file, then retry.", ) }) it("update: keeps a complete observation complete across the tool's own hunk read", async () => { // Completeness is the model's, not the tool's: a complete read stays complete // and a partial one stays partial, so a later full-file write is still gated. const key = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry reg.observe(key, "7:4242:1234:1700000000123456789:1700000000789999999", true) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(key)?.complete).toBe(true) }) it("update: a hunk read with no prior observation records a partial observation", async () => { // Nothing was earned before, so there is nothing to carry. The tool read the whole // file for its own hunk matching, but the model only ever saw the patch context, so // this read cannot grant authority for a later full-file replacement. The targeted // patch itself is still allowed: the "edit" guard accepts a partial observation. const key = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(key)?.complete).toBe(false) // The guard reads the same entry: a partial observation authorizes targeted edits on // the view the model saw, but not a full-file replacement. expect(reg.has(key)).toBe(true) }) it("update: does not carry completeness across a version the model never read", async () => { // The model earned completeness on a different version than the one the patch // helper read: the intervening change was never seen, so a later full-file // replacement must still fail closed. const key = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry reg.observe(key, "7:4242:1234:1700000000123456789:1700000000789999998", true) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(key)?.complete).toBe(false) await expect(guardedWrite(mockTask as Task, "src/thing.ts", "full replacement", "update")).rejects.toThrow( "File was only partially read (line slice, range, truncated view, or indentation block) -- " + "a full-file replacement needs the complete content; re-read the whole file, then retry.", ) }) it("update: withdraws the hunk-read observation when the user denies the publish", async () => { // apply_patch read the file to compute the hunk, so the tool owns that observation. // The user said no, nothing published, and a leftover partial entry would let a later // edit, search_replace, edit_file or apply_diff publish against a version the model // never read. This is the exit that made apply_patch the remaining tool-read path. const key = path.resolve(mockTask.cwd, "src/thing.ts") const reg = mockTask.observationRegistry mockAskApproval.mockResolvedValue(false) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") expect(reg.has(key)).toBe(false) }) it("update: withdraws the hunk-read observation when the publish throws", async () => { // The outer-catch exit: the hunk read happened, the save blew up before publishing, // and the observation must not survive as authority for a later write. const key = path.resolve(mockTask.cwd, "src/thing.ts") const reg = mockTask.observationRegistry mockSaveDirectly.mockRejectedValue(new Error("extension host went away")) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalled() expect(reg.has(key)).toBe(false) }) it("withdraws observations for files read before a hunk failure", async () => { // processAllHunks throws on the second file context mismatch, so the first file was // read, observed and then never published. Its leftover entry is the state a later // targeted edit would wrongly accept. const firstKey = path.resolve(mockTask.cwd, "src/first.ts") const secondKey = path.resolve(mockTask.cwd, "src/second.ts") const reg = mockTask.observationRegistry await tool.execute({ patch: mismatchedSecondPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to process patch")) expect(reg.has(firstKey)).toBe(false) expect(reg.has(secondKey)).toBe(false) }) it("keeps the observation of a path that published while withdrawing a denied one", async () => { // Two updates in one patch: the first approves and publishes, the second is denied. // Withdrawal is scoped by path and by the exact stored entry, so the published file // keeps the observation its publish ran on (partial, as the hunk read recorded it) // while the denied path is left with nothing. const publishedKey = path.resolve(mockTask.cwd, "src/first.ts") const deniedKey = path.resolve(mockTask.cwd, "src/second.ts") const reg = mockTask.observationRegistry mockAskApproval.mockResolvedValueOnce(true).mockResolvedValueOnce(false) await tool.execute({ patch: twoUpdatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.has(publishedKey)).toBe(true) expect(reg.get(publishedKey)?.complete).toBe(false) expect(reg.has(deniedKey)).toBe(false) }) it("update: observes the hunk read so the guarded publish is not unobserved", async () => { await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) // The hunk read doubles as the S2 observation (ReadFileTool contract): // stable pre/post stats record the version token, so the in-place modify // publish is not rejected as an unobserved write. const observed = mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts")) expect(observed?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") }) // Hands the save double to the guard the tool is really talking to. The double forwards the // kind, content and completeness exactly as the tool chose them, so a publish that asked for // create semantics is refused by the create guard and one that asked for edit semantics by the // edit guard. Rows that pin a remediation used to write the expected text into the double by // hand, which let either guard pass. (Row 4753503048.) The argument list is taken as unknown // and narrowed here, because the double itself is an untyped vi.fn(). const isGuardedWriteKind = (value: unknown): value is GuardedWriteKind => value === "create" || value === "update" || value === "edit" const delegateSaveDoubleToGuard = ( onCall?: (relPath: string, writeKind: GuardedWriteKind) => void, ): { errors: unknown[] } => { const errors: unknown[] = [] mockSaveDirectly.mockImplementation(async (...args: unknown[]) => { const [ relPath, content, , , , writeKind, completeOverride, approvedOutsideWorkspace, approvedCanonicalTarget, ] = args if (typeof relPath !== "string" || typeof content !== "string" || !isGuardedWriteKind(writeKind)) { throw new Error(`unexpected saveDirectly arguments: ${JSON.stringify(args.slice(0, 6))}`) } const options: GuardedWriteOptions = {} if (typeof approvedOutsideWorkspace === "boolean") { options.approvedOutsideWorkspace = approvedOutsideWorkspace } if (typeof approvedCanonicalTarget === "string") { options.approvedCanonicalTarget = approvedCanonicalTarget } onCall?.(relPath, writeKind) try { await guardedWrite( mockTask as Task, relPath, content, writeKind, typeof completeOverride === "boolean" ? completeOverride : undefined, options, ) } catch (error) { errors.push(error) throw error } return { newProblemsMessage: "", userEdits: undefined, finalContent: content } }) return { errors } } // Answers both destination probes as an absent file does. The move handler reads the // destination's identity (ApplyPatchTool.ts:677-:685) and the create guard asks fs.access // twice - once for the freshness test (guardedWrite.ts:645 via :155), once inside // createIfAbsent (:200). The committed fixture answered all three with "present" while these // rows seeded no destination observation, which is exactly the state the create guard // refuses. Every other path keeps answering what it answered before, so source probes are // left alone. const armDestinationAbsent = (destKey: string): void => { const enoent = (): Error => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) mockedFsPromises.default.stat.mockImplementation((target: unknown) => String(target) === destKey ? Promise.reject(enoent()) : Promise.resolve(_identityOf(String(target))), ) mockedFsPromises.default.access.mockImplementation((target: unknown) => String(target) === destKey ? Promise.reject(enoent()) : Promise.resolve(undefined), ) } it("update: does not observe when the pre- and post-read tokens disagree", async () => { // The file changed mid-read: pre/post stats differ, so no observation is // recorded and the guarded publish surfaces the unobserved-existing // remediation instead of publishing against a stale version. const statMock = mockedFsPromises.default.stat statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) // The refusal is the guard's own. An update hunk publishes as an edit, so the remediation // is the edit one; the create guard's text written here by hand would have let a publish // that asked for create semantics pass this row unchanged. (Row 4753503048.) const guardSeen = delegateSaveDoubleToGuard() await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) // Assert the exact rejection that reached handleError: the text the edit guard actually // produces, plus the identity of the object the guard threw and the tool reported. expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError", message: "File not read yet -- read the file, then retry.", }), ) expect(mockHandleError.mock.calls[0]?.[1]).toBe(guardSeen.errors[0]) }) it("update: does not observe when the post-read stat rejects", async () => { // The pre-read stat succeeds and the read itself succeeds, but the post-read // stat fails, so the read cannot be tied to a version token and no // observation is recorded. The guarded publish then fails closed against the // existing, unobserved file rather than publishing content built from an // unverifiable read. const statMock = mockedFsPromises.default.stat statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) statMock.mockRejectedValueOnce(new Error("EACCES: permission denied")) // The refusal is the guard's own. An update hunk publishes as an edit, so the remediation // is the edit one; the create guard's text written here by hand would have let a publish // that asked for create semantics pass this row unchanged. (Row 4753503048.) const guardSeen = delegateSaveDoubleToGuard() await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError", message: "File not read yet -- read the file, then retry.", }), ) expect(mockHandleError.mock.calls[0]?.[1]).toBe(guardSeen.errors[0]) }) it("update: does not observe when the pre-read stat rejects", async () => { // The mirror of the post-read case: the FIRST bracketing stat fails, so there is // no baseline token to compare the read against. The hunk read still happens and // the patch still reaches the guarded publish, but nothing is observed - the // publish fails closed against the existing, unobserved file. const statMock = mockedFsPromises.default.stat statMock.mockRejectedValueOnce(new Error("EACCES: permission denied")) statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) // The refusal is the guard's own. An update hunk publishes as an edit, so the remediation // is the edit one; the create guard's text written here by hand would have let a publish // that asked for create semantics pass this row unchanged. (Row 4753503048.) const guardSeen = delegateSaveDoubleToGuard() await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) // The read was not skipped: the publish was still attempted through the guard. expect(mockSaveDirectly).toHaveBeenCalled() expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError", message: "File not read yet -- read the file, then retry.", }), ) expect(mockHandleError.mock.calls[0]?.[1]).toBe(guardSeen.errors[0]) }) it("refuses two updates of one path when the file changed between the reads", async () => { // Row 4753503024 (Major - Data Integrity & Integration - Heavy lift) is headed "Same-path // hunks can publish stale content." and asks that each save check "the version its own // content came from", or that the call "refuse when reads of the same path observe // different versions". The registry keeps one entry per path, so the second read below // replaces the token the first read verified while the content that read produced is // still queued for publish: the first publish would compare against the version the // second read found and write bytes built from the older one, the change the other // writer landed would vanish, and the tool would report success. This row pins the // refusal alternative the row allows. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // Read one answers with the identity every committed row uses, so its pair agrees and // verifies. Both stats of read two answer with a newer version that agrees with itself: // the file really did move, and this read can prove it. The bytes change with the // version, because it is the content a publish would have written that has to stay // honest here. let sourceStats = 0 let sourceReads = 0 const newerIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === targetKey && ++sourceStats > 2) { return Promise.resolve(newerIdentity) } return sharedIdentity(target) }) mockedFsPromises.default.readFile.mockImplementation(() => { sourceReads += 1 return Promise.resolve( Buffer.from(sourceReads === 1 ? "original file content\n" : "written by another writer\n"), ) }) try { await tool.execute({ patch: samePathTwoUpdatesPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "two-updates-one-path-changed-between-reads", }) // Both reads ran, each bracketed by its own pair of probes: the refusal is about the two // versions those reads named, not about a read that never happened. expect(sourceReads).toBe(2) expect(sourceStats).toBe(4) // Nothing was published and no approval was asked: the refusal lands while the patch is // still being processed, before either hunk is offered to the user. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockAskApproval).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain( "Cannot apply patch to src/thing.ts: the file changed between two reads of this path", ) expect(reported).toContain("re-read the file and re-apply the patch") expect(reported).not.toContain("Saved file") // The refusal is a tool error the model is told about, not an exception handed to // handleError, and it is counted as a mistake exactly once. expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") expect(mockTask.consecutiveMistakeCount).toBe(1) // The observation this call recorded is withdrawn with the refusal, so it cannot // authorize a later write of content nobody has in hand. expect(reg.get(targetKey)).toBeUndefined() } finally { // Hand the doubles back whatever the assertions decide: beforeEach clears calls but // keeps implementations, so an implementation left running answers every later row as // well, and a mutant reading then reports rows it did not touch. mockedFsPromises.default.stat.mockImplementation(sharedIdentity) mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) } }) it("refuses the patch when the delete read of the same path sees a newer version", async () => { // Row 4754923949 (Major - Data Integrity & Integration - Heavy lift, the reviewer's own labels) is // headed "The update can overwrite a newer file version." and says: "The delete read stores the // newer file version in the observation registry, which keeps one entry per path. The update then // publishes content built from the older version. The change made by the other writer is lost, and // the tool reports success." It asks for the design decision first: "Either refuse the update when // a later read of the same path sees a different version, or keep the update's verified baseline // through the delete read. Then change the test to assert that behavior." // // The refusal is the choice, and the reason is that the other choice does not save the operation. // Keep the update on its own verified baseline and the publish still compares against a version that // is no longer on disk: guardedWrite.ts:299 answers "Stale version ... re-read the file, then // retry", but only after the user approved and after the diff view opened, so the same refusal costs // an approval, an opened tab and a reverted buffer. Refusing inside the read lands where the // two-update refusal of row 4753503024 already lands - before any approval, before any write - and // the model's remediation is the same single re-read either way. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // Read one answers with the identity every committed row uses, so its pair agrees and verifies. Both // stats of read two - the delete's - answer with a newer version that agrees with itself: the file // really did move, and this read can prove it. The bytes change with the version, because it is the // content a publish would have written that has to stay honest here. let sourceStats = 0 let sourceReads = 0 const newerIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === targetKey && ++sourceStats > 2) { return Promise.resolve(newerIdentity) } return sharedIdentity(target) }) mockedFsPromises.default.readFile.mockImplementation(() => { sourceReads += 1 return Promise.resolve( Buffer.from(sourceReads === 1 ? "original file content\n" : "written by another writer\n"), ) }) try { await tool.execute({ patch: updateThenDeletePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-after-update-with-a-write-in-between", }) // Both reads ran, each bracketed by its own pair of probes: the refusal is about the two versions // those reads named, not about a read that never happened. expect(sourceReads).toBe(2) expect(sourceStats).toBe(4) // The persist path, both halves of it. The update published nothing - no guarded save and no // saveChanges fallback - so no content built from the older version reached the disk. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() // And the delete unlinked nothing: it is the second hunk of the same patch, and the refusal stops // the patch while it is still being read, so the file the other writer changed is still there for // the model to re-read before it decides again. expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) expect(mockTask.fileContextTracker.trackFileContext).not.toHaveBeenCalled() // Nothing was offered to the user: a patch about to be refused must not spend an approval. expect(mockAskApproval).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain( "Cannot apply patch to src/thing.ts: the file changed between two reads of this path", ) expect(reported).toContain("re-read the file and re-apply the patch") expect(reported).not.toContain("Saved file") expect(reported).not.toContain("Successfully deleted") // The refusal is a tool error the model is told about, not an exception handed to handleError, and // it is counted as a mistake exactly once. expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") expect(mockTask.consecutiveMistakeCount).toBe(1) // Neither read's observation survives the refusal. The update read recorded one entry, the delete // read replaced it with another (one entry per path), and both were recorded by this call: a // leftover partial entry would authorize a later edit of content nobody in this call still holds. expect(reg.get(targetKey)).toBeUndefined() } finally { // Hand the doubles back whatever the assertions decide: beforeEach clears calls but keeps // implementations, so an implementation left running answers every later row as well, and a mutant // reading then reports rows it did not touch. mockedFsPromises.default.stat.mockImplementation(sharedIdentity) mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) } }) it("lets a delete follow an update of one path when both reads saw one version", async () => { // The scope of the refusal above, pinned from the other side: what refuses is the disagreement // between the two reads, not the presence of two reads. Nothing moved here - every probe answers // with the identity this file's default double gives and every read the same bytes - so the update // publishes on the version it read and the delete then unlinks. // // This is also where the published content and the baseline are pinned, the half of row 4754923949 // that says of the row it replaces: "It checks one edit save, the unlink, and the success message. It // does not check the published content or its baseline, so it cannot detect the stale write." const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // The baseline has to be read where the publish happens. A save double that ignores the registry // lets any token pass at save time, provided the registry ends up holding the expected one - the // objection in row 4758418963. This capture runs inside mockSaveDirectly, before the guard would // have compared, so it records the entry the publish actually ran against. const baselineAtSave: { version?: string; complete?: boolean } = {} mockSaveDirectly.mockImplementationOnce(async () => { const standing = mockTask.observationRegistry.get(targetKey) baselineAtSave.version = standing?.version baselineAtSave.complete = standing?.complete return { newProblemsMessage: "", userEdits: undefined, finalContent: "modified file content\n", } }) await tool.execute({ patch: updateThenDeletePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-after-update-without-a-write-in-between", }) // The persist call in full: the path the patch named, the content the update read built from the // version it verified, and edit semantics - an update hunk is a targeted change, not a full-file // replacement. The seventh parameter is completeOverride and the eighth is the approval flag for a // target outside every workspace root; the row pins both rather than leaving them out. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/thing.ts", "modified file content\n", false, true, 1000, "edit", undefined, false, undefined, ) // The baseline the guard would compare against, taken inside the save double instead of after // execute() returns (guardedWrite.ts:604, :627 read the entry at publish time). It is the version // both reads verified: read two cannot have re-based it, because it read the same file. Row // 4758418963 is this change - the same fact, measured where the publish uses it. expect(baselineAtSave.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") // And partial stays partial at save time: this entry came from the tool's own hunk read, which // earned no completeness the model had not already had, so the guarded edit publishes under a // partial view rather than authorising a later full-file replacement. expect(baselineAtSave.complete).toBe(false) // The entry still names that version once execute() returns, so the capture above is not merely // the last thing anybody wrote to the registry. expect(reg.get(targetKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(targetKey) // Both operations were offered to the user: nothing was refused on the way. expect(mockAskApproval).toHaveBeenCalledTimes(2) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Successfully deleted src/thing.ts") expect(reported).not.toContain("the file changed between two reads") expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) }) it("refuses the patch when a delete read verifies a version the update read never proved", async () => { // Row 4758418988 (Major - Data Integrity & Integration - Quick win): "Suppose an update reads // src/thing.ts, but its post-read stat fails. The update still queues content without a // queuedPublishVersions entry. If another writer appends a line before the following delete // reads the file, the delete records the newer token. The "edit" guard then accepts that token // for the older update content. If the user approves the update and declines the delete, the // appended line is lost." The content stayed queued because readFile hands its bytes back // whichever way the stats answer; what was missing was any record that no version had been // proven for them. The delete read publishes nothing of its own, yet its observe writes the // entry the update's save compares against (ApplyPatchTool.ts:231, then guardedWrite.ts:604 and // :627), so a newer token sitting there authorizes the older bytes and the appended line is gone. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // The model read this path in full at the version the default identity names, so nothing in the // state is stale except what the failed pair leaves unproven. reg.observe(targetKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // Stat 1 is the update read's pre-read and answers with the version the model read. Stat 2 is its // post-read and cannot answer. Stats 3 and 4 are the delete read's pair and agree on the version // the other writer produced - the sequence the finding spells out, in the order it spells it. const movedIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } const verdicts: string[] = [] const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) let targetStats = 0 mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) !== targetKey) return sharedIdentity(target) if (++targetStats === 1) { verdicts.push("update pre-read: version the model read") return Promise.resolve(_identityOf(targetKey)) } if (targetStats === 2) { verdicts.push("update post-read: refused to answer") return Promise.reject(Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })) } verdicts.push("delete read: newer version") return Promise.resolve(movedIdentity) }) try { await tool.execute({ patch: updateThenDeletePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-verified-what-the-update-read-could-not", }) // Refused before anything was offered to the user and before anything was written, so the // half-approval that loses the appended line never happens. expect(mockAskApproval).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Failed to process patch") expect(reported).toContain("two stats never named one version") expect(reported).toContain("src/thing.ts") expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(1) // The answers this row armed, read back from the double: a failed pair and a verified pair are // the only two facts the row rests on, so it pins them from the double rather than by claim. expect(verdicts).toEqual([ "update pre-read: version the model read", "update post-read: refused to answer", "delete read: newer version", "delete read: newer version", ]) // What the refused call leaves behind. The refusal runs before this read's observe, so the // model's own entry survives exactly as it was earned - version and full-read flag intact - // rather than being re-based onto a token the model never saw. The next tool to touch this // path is refused or authorised on the model's own read, as if this call had never run. expect(reg.get(targetKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") expect(reg.get(targetKey)?.complete).toBe(true) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("refuses the patch when a delete read verifies a version a disagreed update pair left unproven", async () => { // The same queue with the other way for the pair to fail: both stats answered and they named // different versions. Neither shape may leave the queue silent about the bytes it staged, // because the later verified read does the same thing to the one entry per path whichever way // the earlier pair failed. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const movedIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } const verdicts: string[] = [] const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) let targetStats = 0 mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) !== targetKey) return sharedIdentity(target) if (++targetStats === 1) { verdicts.push("update pre-read: version the model read") return Promise.resolve(_identityOf(targetKey)) } verdicts.push("newer version") return Promise.resolve(movedIdentity) }) try { await tool.execute({ patch: updateThenDeletePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-verified-what-a-disagreed-update-pair-could-not", }) expect(mockAskApproval).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("two stats never named one version") expect(mockHandleError).not.toHaveBeenCalled() // Probes 1 and 2 disagree; probes 3 and 4 are the delete read agreeing on the newer version. expect(verdicts).toEqual([ "update pre-read: version the model read", "newer version", "newer version", "newer version", ]) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("still publishes both updates when the unverified read is the last read of its path", async () => { // The scope of the refusal above, taken from the side the finding does not reach. What the // marker refuses is a LATER read of the same path bringing a fresh token into the one entry per // path. When the unverified publish read is the last read of that path, that state never // arrives, and the shipped contract stands: a read that cannot verify records no observation and // the guard decides what to do about it - the design "update: does not observe when the post-read // stat rejects" pins, and the design the move rows pin when they keep publishing after a later // read of the same source fails verification. Refusing every unverifiable publish read at the // read would turn those rows inside out for a state with no queued content to re-base, so this // row pins both halves of the limit: the unverified path still publishes, and the marker does // not travel to a second file. const firstKey = path.resolve("/workspace/project", "src/first.ts") const secondKey = path.resolve("/workspace/project", "src/second.ts") const reg = mockTask.observationRegistry const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) let firstStats = 0 mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === firstKey && ++firstStats === 2) { return Promise.reject(Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })) } return sharedIdentity(target) }) try { await tool.execute({ patch: twoUpdatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "unverified-read-was-the-last-read-of-its-path", }) expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls.map((call) => String(call[0]))).toEqual([ "src/first.ts", "src/second.ts", ]) expect(mockHandleError).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).not.toContain("two stats never named one version") // The unverified read recorded nothing for its own path - that is the guard's business, not // this refusal's - and the verified read of the other file recorded its own version. expect(reg.has(firstKey)).toBe(false) expect(reg.get(secondKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") expect(mockTask.consecutiveMistakeCount).toBe(0) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("delete: unlinks a file whose version moved after the model read it, asking no guard", async () => { // The standalone delete case, in its own row as row 4754923949 asks ("Keep the standalone delete // case in a separate test"). A delete publishes by unlinking (ApplyPatchTool.ts:487): the version its // own read saw is the version it removes, so no content built from an older read is written over // another writer's change - that change is deleted, which is what the patch asked for. The stale // version here is the point: it is the state the refusal above keys on, and a delete alone must not // be refused by it. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry // The model read this path in full at the version every committed row uses; the disk moved on to the // identity this row arms for every probe of the path. reg.observe(targetKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) const movedIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => String(target) === targetKey ? Promise.resolve(movedIdentity) : sharedIdentity(target), ) try { await tool.execute({ patch: deleteOnlyPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-with-a-stale-model-observation", }) // No guarded save was asked for at all: a delete never reaches the compare-and-swap the refusal // above protects, so there is no baseline for it to get wrong. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(targetKey) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Successfully deleted src/thing.ts") expect(reported).not.toContain("the file changed between two reads") expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) // What the read does leave behind: the entry now names the version the delete read verified, and // only that - the model's completeness was earned on the version it read, not on this one, so a // later full-file write to a recreated path stays gated. expect(reg.get(targetKey)?.version).toBe("7:4242:1235:1700000000222000000:1700000000333000000") expect(reg.get(targetKey)?.complete).toBe(false) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) await tool.execute({ patch: addPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/new.ts", "new line one\nnew line two\n", true, true, 1000, "create", undefined, false, undefined, ) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockTask.didEditFile).toBe(true) expect(mockHandleError).not.toHaveBeenCalled() }) it("move: publishes the destination through the guarded saveDirectly with create kind", async () => { // The destination is a fresh path: nothing was read there and nothing is there, which is // the one state a create publish needs no observation for. Arming it for real is what // keeps the guard's verdict - not the double's - in charge of whether this publishes. const destKey = path.resolve("/workspace/project", "src/new.ts") armDestinationAbsent(destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) // The source had no prior observation, so the hunk read records a partial // observation: the model only saw the patch context, not the whole source. The // destination is still published (create kind), but the completeness flag stays false. expect(mockSaveDirectly).toHaveBeenCalledWith( "src/new.ts", "modified file content\n", false, true, 1000, "create", false, false, undefined, ) }) it("move: refuses a destination that names the same file as its source, and writes nothing to it", async () => { // One file under two names: on a real filesystem that is a hard link, or the destination // spelled through a link of the source's own directory. The filesystem in this spec is its // doubles, so the row states the geometry outright - one identity armed for both spellings - // and the row below pins the opposite geometry, a destination spelled through an alias that // is its own file. Which of the two it is cannot be read off the strings. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") mockedFsPromises.default.stat.mockImplementation(() => Promise.resolve(_identityOf(sourceKey))) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-destination-is-the-source", }) // Consequence one, the file at the shared path: the patched content never lands there. The // save is what would have written it and the refusal runs before the save, so the file keeps // the bytes it had before the patch and the tool claims no edit. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("the two paths name the same file")) expect(mockHandleError).not.toHaveBeenCalled() // Both spellings were put to the filesystem: the check asks about the pair, not about one of // them while taking the strings' word for the other. expect(mockedFsPromises.default.stat).toHaveBeenCalledWith(sourceKey, { bigint: true }) expect(mockedFsPromises.default.stat).toHaveBeenCalledWith(destKey, { bigint: true }) }) it("move: reverts the dirty source buffer before discarding the session on a refused same-file move", async () => { // The rows above pin what the refusal did NOT do to files; this row chases the half the // reviewer named: with focus disruption prevention off, the approval flow had already // applied the proposed text to the open source document, and the refusal only reached // reset(). The provider's tab-close step skips dirty tabs, so the refused text stayed // in the buffer, and the next save - the user's or the editor's auto-save - would have // published to disk exactly what this refusal turned down. The buffer arithmetic lives in // DiffViewProvider; the obligation at this layer is a call order, and the row pins it on // the named provider doubles: the buffer got the proposed text, the tool reverted it, and // only then discarded the session. Arming the flag off is what makes a buffer exist at // all - every other move row above runs with prevention on and never opens one. const sourceKey = path.resolve("/workspace/project", "src/old.ts") mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: { preventFocusDisruption: false }, }) mockedFsPromises.default.stat.mockImplementation(() => Promise.resolve(_identityOf(sourceKey))) // Cleanup answers on a gate: the row must see the discard's start line while the revert // is still in flight. Invocation order alone cannot tell an awaited cleanup from a fired // one when both doubles resolve immediately - a tool that called revertChanges without // awaiting it would keep the same order and still discard over a buffer holding the // refused text. The gate makes the pending window observable. const revertSpy = vi.mocked(mockTask.diffViewProvider.revertChanges) const resetSpy = vi.mocked(mockTask.diffViewProvider.reset) let releaseRevert: () => void = () => {} const revertGate = new Promise((resolve) => { releaseRevert = resolve }) revertSpy.mockImplementation(() => revertGate) const run = tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "refused-same-file-move-reverts-buffer", }) // The pending window is read inside try so the cleanup contract survives a failed // assertion: whichever line below throws, finally still answers the gate and still // awaits the call. Otherwise a failing waitFor or a wrong count leaves tool.execute // parked on a promise nobody will resolve, and the row reports while cleanup is owed. try { await vi.waitFor(() => { expect(revertSpy).toHaveBeenCalledTimes(1) }) // The refusal reached cleanup and cleanup has not answered: the discard has not started. // A fire-and-forget revert would already have reset the session by this line. expect(resetSpy).toHaveBeenCalledTimes(0) } finally { releaseRevert() await run } // The precondition the revert exists for: the buffer really received the proposed text // before the refusal answered. Without this line the order below could be vacuously // true in a configuration where nothing ever dirtied the buffer. expect(vi.mocked(mockTask.diffViewProvider.update)).toHaveBeenCalledWith( expect.stringContaining("modified file content"), true, ) // The discard ran exactly once, behind the revert that had to answer first. expect(revertSpy).toHaveBeenCalledTimes(1) expect(resetSpy).toHaveBeenCalledTimes(1) expect(revertSpy.mock.invocationCallOrder[0]).toBeLessThan(resetSpy.mock.invocationCallOrder[0]) // And the refusal still wrote nothing anywhere: the revert is a buffer operation, not // a save. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) }) it("move: reverts the dirty source buffer on every refused destination move", async () => { // The reviewer's note below the same-file refusal says the neighbouring refusals in the // move branch carry the same omission - the rooignore, write-protected, and // outside-workspace returns all reach reset() with the refused text still applied to // the open buffer - and the same fix applies there. Each phase below arms one refusal // cause with the buffer dirtied (flag off, like the row above) and re-checks the same // obligations: an awaited revert - the discard may not start while cleanup is still // pending - ahead of the discard, and the cause's own error reported. The // guards also answer for the source path earlier in the flow, so each cause is armed // per candidate path and never for the source itself. The provider doubles are cleared // between phases so every count below belongs to one refusal. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: { preventFocusDisruption: false }, }) const revertSpy = vi.mocked(mockTask.diffViewProvider.revertChanges) const resetSpy = vi.mocked(mockTask.diffViewProvider.reset) const updateSpy = vi.mocked(mockTask.diffViewProvider.update) const moveKey = path.resolve("/workspace/project", "src/new.ts") const runRefusal = async (arm: () => void, message: string, toolCallId: string) => { revertSpy.mockClear() resetSpy.mockClear() updateSpy.mockClear() mockPushToolResult.mockClear() // The cause doubles answer for the whole flow, and mockClear keeps implementations: // restore all three guards to their permissive answers first, then let this phase arm // only its own cause - otherwise the previous phase's refusal answer would fire first. vi.mocked(mockTask.rooIgnoreController!.validateAccess).mockReturnValue(true) vi.mocked(mockTask.rooProtectedController!.isWriteProtected).mockReturnValue(false) vi.mocked(isPathOutsideWorkspace).mockReturnValue(false) arm() // Cleanup on a gate, as in the same-file row: while the revert is pending the // discard must not have started; that is what an awaited cleanup looks like from // outside, and it is the part invocation order cannot show on its own. let releaseRevert: () => void = () => {} const revertGate = new Promise((resolve) => { releaseRevert = resolve }) revertSpy.mockImplementation(() => revertGate) const run = tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId, }) // Same discipline as the same-file row above: the pending window lives inside try // and the gate answer plus the await live in finally, so a failed assertion in any // phase cannot leave that phase execute waiting on a gate nobody will open. try { await vi.waitFor(() => { expect(revertSpy).toHaveBeenCalledTimes(1) }) expect(resetSpy).toHaveBeenCalledTimes(0) } finally { releaseRevert() await run } expect(updateSpy).toHaveBeenCalledWith(expect.stringContaining("modified file content"), true) expect(revertSpy).toHaveBeenCalledTimes(1) expect(resetSpy).toHaveBeenCalledTimes(1) expect(revertSpy.mock.invocationCallOrder[0]).toBeLessThan(resetSpy.mock.invocationCallOrder[0]) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining(message)) } // Phase one: the destination is rooignored. The source itself stays readable - the // early access guard also consults this double, and the refusal this row tests is // the move-specific one. await runRefusal( () => vi .mocked(mockTask.rooIgnoreController!.validateAccess) .mockImplementation((candidate: string) => candidate !== "src/new.ts"), "Access blocked by .rooignore", "refused-rooignored-destination-reverts", ) // Phase two: the destination is write-protected; only the move candidate trips it. await runRefusal( () => vi .mocked(mockTask.rooProtectedController!.isWriteProtected) .mockImplementation((candidate: string) => candidate === "src/new.ts"), "write-protected", "refused-protected-destination-reverts", ) // Phase three: the destination is outside every workspace root; the source path // stays inside, so the flow reaches the move guard before refusing. await runRefusal( () => vi.mocked(isPathOutsideWorkspace).mockImplementation((candidate: string) => candidate === moveKey), "outside workspace", "refused-outside-destination-reverts", ) }) it("move: does not unlink the source when the destination names the same file", async () => { // Consequence two. The unlink at the end of this branch is the statement that deleted what // the publish had just written to the same inode; with the pair refused before the publish, // the file is still where both names point and nothing has been removed. const sourceKey = path.resolve("/workspace/project", "src/old.ts") mockedFsPromises.default.stat.mockImplementation(() => Promise.resolve(_identityOf(sourceKey))) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-destination-is-the-source-no-unlink", }) expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() // The opened diff view is discarded rather than left open over an un-published file. expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") }) it("move: reports one refusal rather than two published files for one changed file", async () => { // Consequence three, and the half a reviewer can check without a filesystem: the tool's own // report. pushToolWriteResult builds the published-files message and trackFileContext is what // records each published path as edited, so a move that published onto the source and then // unlinked it would have reported two files for the one file the patch changed. const sourceKey = path.resolve("/workspace/project", "src/old.ts") mockedFsPromises.default.stat.mockImplementation(() => Promise.resolve(_identityOf(sourceKey))) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-destination-is-the-source-report", }) expect(mockPushToolResult).toHaveBeenCalledTimes(1) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Cannot move src/old.ts onto src/new.ts"), ) expect(mockTask.diffViewProvider.pushToolWriteResult).not.toHaveBeenCalled() expect(mockTask.fileContextTracker.trackFileContext).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) // The mistake counter is deliberately not asserted. This refusal raises it and the end-of- // loop statement at ApplyPatchTool.ts:242 clears it again inside the same call, so reading // the counter after the call would pin :242 rather than the refusal. }) it("move: two files whose identities differ above the safe-integer range are not treated as one", async () => { // Why the identity is read as bigints rather than numbers. An NTFS or ReFS file identity can // sit above Number.MAX_SAFE_INTEGER, and two such files one apart round to the same // Number: 2^53 and 2^53 + 1 are one double. A compare that goes through Number would call these // two files one file and refuse this move; the compare beside this row keeps them apart. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const BASE_INO = 2n ** 53n const NEIGHBOUR_INO = BASE_INO + 1n // Both names have to be there for the identity compare to be the subject at all, and a present // destination is writable by a create publish only when it was read in full: with a partial // source view, moving onto an existing destination is refused outright // (ApplyPatchTool.ts:757-:766). So the source read is recorded complete and both entries are // seeded at the very tokens the stats below answer with - the seventh argument below then // reports true because the source view really was complete. const reg = mockTask.observationRegistry reg.observe(sourceKey, `7:${String(BASE_INO)}:1234:1700000000123456789:1700000000789999999`, true) reg.observe(destKey, `7:${String(NEIGHBOUR_INO)}:1234:1700000000123456789:1700000000789999999`, true) mockedFsPromises.default.stat.mockImplementation((target: unknown) => Promise.resolve( String(target) === destKey ? { ..._identityOf(destKey), ino: NEIGHBOUR_INO } : { ..._identityOf(sourceKey), ino: BASE_INO }, ), ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-identities-above-safe-integer-range", }) expect(Number(BASE_INO), "the fixture no longer demonstrates a rounded collision").toBe(Number(NEIGHBOUR_INO)) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/new.ts", "modified file content\n", false, true, 1000, "create", true, false, undefined, ) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) }) it("move: publishes a destination spelled through a link of the source's directory when it is its own file", async () => { // The other direction of the same rule, and the one a string compare gets wrong: // src/aliasDir/new.ts is its own file even though its spelling runs through a link of the // source's directory, so the move has to happen: content published at the destination, the // source unlinked, a report produced. Refusing this pair would be the spelling-instead-of- // identity bug in reverse, and it is why the check asks the filesystem. // Both spellings have to name a file for the compare to be asked at all, and a present // destination is writable by a create publish only when it was read in full; with a partial // source view the move onto an existing destination is refused outright // (ApplyPatchTool.ts:757-:766). The source read is therefore recorded complete, and the // destination gets a complete observation at the token its own identity answers with. const reg = mockTask.observationRegistry reg.observe( path.resolve("/workspace/project", "src/old.ts"), "7:4242:1234:1700000000123456789:1700000000789999999", true, ) reg.observe( path.resolve("/workspace/project", "src/aliasDir/new.ts"), "7:4444:1234:1700000000123456789:1700000000789999999", true, ) await tool.execute({ patch: moveThroughAliasPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-destination-through-directory-alias", }) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/aliasDir/new.ts", "modified file content\n", false, true, 1000, "create", true, false, undefined, ) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(path.resolve("/workspace/project", "src/old.ts")) expect(mockTask.didEditFile).toBe(true) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Saved file")) expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledWith("src/aliasDir/new.ts", "roo_edited") }) it("move: refuses with a tool error when the filesystem will not say what the destination refers to", async () => { // The failure surface the identity check adds, pinned where it is visible. A destination // whose identity the filesystem withholds used to be moved blindly; now the move is refused, // and refused as a tool error - the shape the note above the outside-workspace refusal says a // destination read failure should produce, rather than an exception reaching handleError. const destKey = path.resolve("/workspace/project", "src/new.ts") const eacces = Object.assign(new Error("EACCES: permission denied, stat '" + destKey + "'"), { code: "EACCES", }) mockedFsPromises.default.stat.mockImplementation((target: unknown) => String(target) === destKey ? Promise.reject(eacces) : Promise.resolve(_identityOf(String(target))), ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-destination-identity-refused", }) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("the filesystem would not say what either path refers to"), ) expect(mockHandleError).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) }) it("move: refuses a same-file destination on the raw write path too, not only the guarded one", async () => { // The refusal sits above the isPreventFocusDisruptionEnabled split (:646 vs. :727), so a // flag-off run refuses for the same reason a flag-on run does. Until this row every test in // this file ran with the flag on, which made that symmetry a claim about line numbers rather // than something anyone had checked. The flag-off branch publishes with a raw mkdir plus // fs.writeFile rather than through the diff view, so those are the calls this row expects not // to see. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") // The harness arms preventFocusDisruption on for every row. The binding holds the function // object the provider stub captured, so a row has to change what that function resolves // to rather than re-point the binding. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: { preventFocusDisruption: false }, }) mockedFsPromises.default.stat.mockImplementation(() => Promise.resolve(_identityOf(sourceKey))) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-destination-is-the-source", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("the two paths name the same file")) expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockedFsPromises.default.mkdir).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) // Both spellings went to the filesystem before the refusal, here as on the other path. expect(mockedFsPromises.default.stat).toHaveBeenCalledWith(sourceKey, { bigint: true }) expect(mockedFsPromises.default.stat).toHaveBeenCalledWith(destKey, { bigint: true }) }) it("move: publishes through the raw write path when the flag is off and the two spellings name different files", async () => { // The other half of the coverage, and the half that says the refusal did not become a ban: // with different inodes this is an ordinary move, and the branch that answers for it is the // mkdir + fs.writeFile one. The saveDirectly double staying unused is what pins the branch. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") // The harness arms preventFocusDisruption on for every row. The binding holds the function // object the provider stub captured, so a row has to change what that function resolves // to rather than re-point the binding. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: { preventFocusDisruption: false }, }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-between-different-files", }) expect(mockedFsPromises.default.mkdir).toHaveBeenCalledWith(path.dirname(destKey), { recursive: true }) expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith(destKey, "modified file content\n", "utf8") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Saved file")) expect(mockTask.didEditFile).toBe(true) }) it("move: treats a destination that is not there as not-the-source on the raw write path", async () => { // Absence is answered the same way on both paths: a destination that is not there is not the // source, so the identity read returns "absent" and the move proceeds. The row that arms an // EACCES destination pins the other answer the filesystem can give. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const enoent = Object.assign(new Error("ENOENT: no such file or directory, stat '" + destKey + "'"), { code: "ENOENT", }) // The harness arms preventFocusDisruption on for every row. The binding holds the function // object the provider stub captured, so a row has to change what that function resolves // to rather than re-point the binding. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: { preventFocusDisruption: false }, }) mockedFsPromises.default.stat.mockImplementation((target: unknown) => String(target) === destKey ? Promise.reject(enoent) : Promise.resolve(_identityOf(String(target))), ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-destination-absent", }) expect(mockTask.recordToolError).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).toHaveBeenCalledWith(destKey, "modified file content\n", "utf8") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) }) it("move: rejects a partial source onto an observed destination before changing any state", async () => { // The destination content is the source file plus one hunk, so it can only be // as complete as the view the model had of the source. Rejecting before the // registry is modified keeps a full destination read intact, and the message // must name the source, because re-reading the destination cannot restore the // source's completeness and would loop. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", false) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) // Nothing was downgraded: the destination keeps the completeness the model earned. expect(reg.get(destKey)?.complete).toBe(true) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ message: "Cannot move a partially read file onto src/new.ts: re-read the whole source (src/old.ts) first, then retry.", }), ) }) it("move: carries the source's completeness when the observed destination was deleted", async () => { // The destination was read and then deleted, so its observation is stale but the // create guard permits the publish. Rejecting here would refuse a move onto an // absent path; the content is still only as complete as the source view, so the // source's completeness is carried instead of the destination's stale one. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", false) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) // The destination was read and then deleted, so it has to stay absent for every probe that // asks - the move's own and the guard's two - not just for the first one. A one-shot // ENOENT was consumed by the move's probe and left the guard's freshness test answering // "present", the state the guard refuses for a partial observation. armDestinationAbsent(destKey) const completeAtPublish: Array = [] mockSaveDirectly.mockImplementationOnce(async () => { completeAtPublish.push(reg.get(destKey)?.complete) return { newProblemsMessage: "", userEdits: undefined, finalContent: "new content" } }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(completeAtPublish).toEqual([false]) expect(mockHandleError).not.toHaveBeenCalled() }) it("move: propagates a non-ENOENT destination access error before changing the observation", async () => { // An ELOOP is not an absence verdict. Reading it as "the destination is gone" // would mark the observation partial and let the publish run against a path the // tool never actually observed. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", false) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) mockedFsPromises.default.access.mockRejectedValueOnce( Object.assign(new Error("ELOOP: too many symbolic links"), { code: "ELOOP" }), ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(destKey)?.complete).toBe(true) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ message: "ELOOP: too many symbolic links" }), ) }) it("move: refuses a destination outside every workspace root without canonicalising or publishing it", async () => { // Row 4507855163. The refusal at ApplyPatchTool.ts:564 sits above the experiment-flag branch at :575, // so both modes share one code path and the flag-off twin below is the other half of that claim. // Only the destination reads as outside a root: leaving the source inside means a canonicalisation // of the source cannot stand in for the destination being canonicalised. const destKey = path.resolve("/workspace/project", "src/new.ts") const outside = vi.mocked(isPathOutsideWorkspace) outside.mockImplementation((candidate: string) => candidate === destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-outside-workspace-destination", }) expect(outside).toHaveBeenCalledWith(destKey) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Cannot move file to path outside workspace: src/new.ts"), ) // The refused destination is never canonicalised. realpathNearest used to run at this point, so a // destination whose name could not be resolved surfaced an exception where the user should get the // tool error above. expect(mockedFsPromises.default.realpath).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") // The mistake counter is deliberately not asserted here. The refusal raises it at :565 and the // end-of-loop statement at :242 clears it again inside the same call, so reading the counter // after this call would pin :242 rather than the refusal. expect(mockHandleError).not.toHaveBeenCalled() }) it("move: a complete source read keeps the destination complete", async () => { const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry // The destination is fresh: a create onto an absent path needs no prior read, so the // completeness this row reports is earned by the source read alone. armDestinationAbsent(destKey) reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) mockSaveDirectly.mockImplementationOnce(async () => { reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) return { newProblemsMessage: "", userEdits: undefined, finalContent: "new content" } }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(destKey)?.complete).toBe(true) expect(mockHandleError).not.toHaveBeenCalled() }) // Rows 4507760687 follow-up (4507979054): the rows above pin what the registry holds at publish time. // These two pin the value the tool hands the guard as its completeness authorization - the seventh // argument - which the registry rows cannot see because a mocked save does not consult it. That is // the whole case for keeping both: one row reads the state, these read the argument that state came // from. Two situations pass false at all: the partial source view below, and a full-read entry whose // version this call could not verify - the stale-entry row added for the finding at // ApplyPatchTool.ts:655 pins the second. it("move: authorizes the destination publish as complete when the source was read in full", async () => { const sourceKey = path.resolve("/workspace/project", "src/old.ts") mockTask.observationRegistry.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // Fresh destination, read in full at the source: this is the pair of facts that makes the // complete claim true, and the guard has to be able to write the destination for the // publish to be a publish at all. armDestinationAbsent(path.resolve("/workspace/project", "src/new.ts")) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-complete-source-argument", }) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/new.ts", "modified file content\n", false, true, 1000, "create", true, false, undefined, ) }) it("move: authorizes the destination publish as partial when the source view was partial and the destination was absent", async () => { // The create guard permits publishing onto an absent path, so the partial source view has to travel // with the publish instead of being refused: this is the case the argument exists to express, and // one of the two cases in which the shipped code passes false; the stale-entry row below is // the other. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", false) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) // Absent for every probe, not for the first one only: the guard asks the same question the // move does, and a one-shot ENOENT left it a present file to replace with a partial view. armDestinationAbsent(destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-partial-source-absent-destination-argument", }) // The destination's own stale completeness is not what authorizes the publish - the source view is - // so the argument is false even though the destination had been read as complete before it vanished. expect(mockSaveDirectly.mock.calls[0]?.[6]).toBe(false) expect(mockSaveDirectly.mock.calls[0]?.[5]).toBe("create") expect(mockHandleError).not.toHaveBeenCalled() }) it("move: refuses complete authority to a stale read entry when the post-read verification fails", async () => { // The entry is seeded with a token the run never reads: it names a version from before this // execute, while the pre-read stat answers with the current identity. So the entry really is // stale, and the row is about what a failed verification does with a stale entry: the hunk // read ran on the current bytes and its post-read verification failed with EIO, so no // observation was recorded and the stale entry survived whole. Granting its completeness to // the guard would let the move publish bytes from a version the model never saw in full as a // complete read - exactly the claim the seventh argument makes. The destination had been read // as complete and then vanished: its entry is seeded, and the probe the move path itself // consults (fs.access at the destination) answers ENOENT, so the absence is established by // the probe rather than asserted in prose. What this layer owes is the honest argument - // false - not a refusal, and not a clean verdict the tool lost the standing for when its // verification lost the version. The companion row below pins the other stale condition - an // entry describing a version a publish re-recorded past every verified read of this execute - // because the two states are produced by different mechanisms and a grant must die on each. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1690000000000000000:1690000000000000001", true) reg.observe(destKey, "7:4343:1234:1690000000000000002:1690000000000000003", true) // Fail only the stat that follows the hunk read. The pre-read stat, and everything after // - the same-file identity pair the move check asks - keep answering with the per-path // identity the committed rows rely on, so the flow reaches the publish like any other move. // The destination's own stat answers ENOENT as well, because that is what the access probe // below already answers: a row that says the destination is gone has to say it gone to both // primitives, or the guard reads a present file at the very path the move just deleted. let sourceStats = 0 mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === sourceKey && ++sourceStats === 2) { return Promise.reject(Object.assign(new Error("EIO: i/o error, stat failed"), { code: "EIO" })) } if (String(target) === destKey) { return Promise.reject(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })) } return Promise.resolve(_identityOf(String(target))) }) // The destination is gone: the move consults fs.access at the destination once a destination // entry exists, and only for the destination does the double answer ENOENT. mockedFsPromises.default.access.mockImplementation((target: unknown) => { if (String(target) === destKey) { return Promise.reject(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })) } return Promise.resolve() }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-stale-entry-failed-verification-argument", }) // The publish the patch authorized still happens - a destination the probe confirms absent is // the create guard's own business, not a reason to refuse. What changes is what the tool // claims about completeness: the stale entry's flag does not travel to the guard. expect(mockedFsPromises.default.access).toHaveBeenCalledWith(destKey) expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[6]).toBe(false) expect(mockSaveDirectly.mock.calls[0]?.[5]).toBe("create") // The move completed: destination written through the guard, source unlinked, report made. expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockHandleError).not.toHaveBeenCalled() // The stale source entry is untouched by the tool's refusal to trust it: it still claims the // version and the full read it was earned on. This row pins that the fix withholds the // argument, not that it rewrites the model's own earned state. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1690000000000000000:1690000000000000001") // The vanished destination entry keeps its version but loses the flag, and that is the // shipped design rather than an accident of this cell: with an incomplete source view the // move carries the source's completeness onto the destination, so a read-then-deleted entry // is honestly downgraded to partial instead of keeping authority for bytes nobody compared // against it. The probe verdict (absent) decides reject-versus-proceed; it does not spare // the flag. expect(reg.get(destKey)?.complete).toBe(false) expect(reg.get(destKey)?.version).toBe("7:4343:1234:1690000000000000002:1690000000000000003") }) it("move: refuses complete authority when a publish re-recorded the source past the version the hunk reads verified", async () => { // The other stale condition, produced by a different mechanism: every verified hunk read // records exactly the version it verified, so the registry entry and the token stay in step - // until a committed publish re-records the source at the version it wrote. The guarded-write // contract does re-record after commit (the durability rows above pin that), and the publish // double models it here: the in-place update publishes, then the second update moves the same // path. By the time the move branch asks, the entry describes the published version, and the // only token the reads left standing names the pre-publish version the hunk read verified. // The entry claims completeness for a version this execute never verified in full: the honest // argument is again false. A grant that compares only the flag - the stale-entry grant a // version-blind change would introduce - is visible exactly here, because this is the only // shipped flow in which a standing token and a stale entry coexist when the move asks. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry // Current at seeding: matches the identity the pre-read stats answer with, so the reads // carry completeness forward honestly and the staleness is introduced by the publish below, // not by a token nobody can match. reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The in-place publish (first save) re-records the source at the version it committed - // what guardedWrite does after a committed publish. The second save is the move publish and // falls back to the plain double. mockSaveDirectly.mockImplementationOnce(async () => { reg.observe(sourceKey, "7:4242:1234:1700000000222000000:1700000000333000000", true) return { newProblemsMessage: "", userEdits: undefined, finalContent: "modified file content\n" } }) await tool.execute({ patch: updateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-entry-re-recorded-past-verified-token", }) // Both publishes ran: the in-place update (which re-recorded) first, then the move. expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockSaveDirectly.mock.calls[1]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[1]?.[5]).toBe("create") // The destination has no registry entry, so the move branch never probes it and the create // publish proceeds; what the row pins is that the entry's fresh flag does not travel to the // guard on the strength of a token from an older verified version. expect(mockSaveDirectly.mock.calls[1]?.[6]).toBe(false) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockHandleError).not.toHaveBeenCalled() // The re-recorded entry keeps the version and flag the publish earned for it; the tool // withholds the argument, it does not edit the history away. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1700000000222000000:1700000000333000000") }) it("refuses an in-place update whose path a move earlier in the same patch already published", async () => { // Row 4758418975 (Major - Data Integrity & Integration - Heavy lift): the patch moves // src/old.ts onto an existing src/new.ts and then updates src/new.ts. Every hunk read runs // before any publish, so the update read records the version the destination held before the // move, while the bytes the update built come from that older reading. The move's guarded // publish then refreshes the standing entry to the token it wrote (guardedWrite.ts:710), and // the entry and the disk move together: the edit guard compares the entry against the disk, // finds them equal, and publishes content built from the pre-move file over the file the move // just published. Only queuedPublishVersions still names the version the queued bytes came // from, so that is the compare this row pins. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry // Both names seeded current at the identity their stats answer with, so every read here // carries completeness honestly and the only stale thing in the state is the destination's // version once the move has published. reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) // The move's create publish, answered as the guard answers a committed publish: the // destination is re-recorded at the token the rename produced. Without that refresh this is // not the state the finding describes, because the refreshed entry is exactly what makes the // edit guard's own compare match. The calls are recorded so the row says which saves ran. const movedToken = "7:4343:1235:1700000000222000000:1700000000333000000" const published: { relPath: string; writeKind: unknown; content: unknown }[] = [] mockSaveDirectly.mockImplementation(async (...args: unknown[]) => { const [relPath, content, , , , writeKind] = args if (relPath === "src/new.ts" && writeKind === "create") { reg.observe(destKey, movedToken, true) } published.push({ relPath: String(relPath), writeKind, content }) return { newProblemsMessage: "", userEdits: undefined, finalContent: String(content) } }) await tool.execute({ patch: moveThenUpdateDestinationPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-published-the-destination-the-update-read-is-built-from-older", }) // One save ran: the move's. The update that would have written stale bytes over the moved // content never reached the guard, and it never asked the user to approve them either. expect(published.map((call) => [call.relPath, call.writeKind])).toEqual([["src/new.ts", "create"]]) expect(mockAskApproval).toHaveBeenCalledTimes(1) // The refusal is the tool's own and names the path whose queued content went stale. expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("another change in this patch published src/new.ts"), }), ) // What the patch leaves is the moved file, half-applied rather than silently overwritten: // the move completed and its own success was reported, and the entry still names the version // the move published instead of being re-based back onto the version the update read. expect(reg.get(destKey)?.version).toBe(movedToken) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).not.toContain("modified second content") }) it("publishes both changes when the update of the destination is read and saved before the move", async () => { // The scope of the refusal above, taken from the other side: what refuses is that an earlier // change published this path after this hunk read it, not that a move in the same patch // happens to name the path. Spell the two changes in the other order and nothing is stale - // the in-place update reads and publishes the version it read, and the move that lands on the // path afterwards publishes its own bytes, which is the order the patch asked for. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) const movedToken = "7:4343:1235:1700000000222000000:1700000000333000000" const published: { relPath: string; writeKind: unknown; content: unknown }[] = [] mockSaveDirectly.mockImplementation(async (...args: unknown[]) => { const [relPath, content, , , , writeKind] = args if (relPath === "src/new.ts" && writeKind === "create") { reg.observe(destKey, movedToken, true) } published.push({ relPath: String(relPath), writeKind, content }) return { newProblemsMessage: "", userEdits: undefined, finalContent: String(content) } }) await tool.execute({ patch: updateDestinationThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "update-of-the-destination-read-and-saved-before-the-move", }) // Both saves ran, in the order the patch spells them, and each published the content its own // read built. expect(published.map((call) => [call.relPath, call.writeKind])).toEqual([ ["src/new.ts", "edit"], ["src/new.ts", "create"], ]) expect(published.map((call) => String(call.content))).toEqual([ "modified second content\n", "modified moved content\n", ]) expect(mockHandleError).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenLastCalledWith("Saved file") expect(reg.get(destKey)?.version).toBe(movedToken) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) }) it("move: drops the verified token when a later read of the same file fails verification", async () => { // Finding 4746890721 (ApplyPatchTool.ts:701): the token map the move consults is // filled by any earlier verified read during this execute, and a read whose stat pair // cannot agree recorded no observation - but it also withdrew nothing. The first hunk // read of the patch below verifies and stores its version; the file then changes; the // second read of the same path fails its verification. The stored token named the // very version the model's full-read entry claims, so an uncleared token let the move // hand the guard a complete claim for content this call read from a version the model // never saw. The publish still runs - what the create guard makes of the destination // is its own business - and what this layer owes is the honest argument. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // Read one answers with the identity every committed row uses, so its pair agrees and // verifies. Read two pre-reads a changed version and post-reads a newer one still, so // its pair cannot name a version at all. Later stats - the move's same-file identity // pair - keep answering with the committed per-path identities, like every other row. let sourceStats = 0 mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === sourceKey) { sourceStats += 1 if (sourceStats === 3) { return Promise.resolve({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, }) } if (sourceStats === 4) { return Promise.resolve({ dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_444_000_000n, ctimeNs: 1_700_000_000_555_000_000n, }) } } return Promise.resolve(_identityOf(String(target))) }) await tool.execute({ patch: updateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-cleared-by-failed-verification", }) // Both publishes ran: the in-place update first, then the move onto the destination. expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockSaveDirectly.mock.calls[1]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[1]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. // With the token still standing the entry version equals it and the argument is // true - the grant this finding refuses. A failed read must withdraw it, so the // honest claim here is false. expect(mockSaveDirectly.mock.calls[1]?.[6]).toBe(false) // The move completed, and the model's earned entry is untouched: what the failed // read withdraws is this execute's map entry, not the read the model actually made. expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(reg.get(sourceKey)?.complete).toBe(true) expect(mockHandleError).not.toHaveBeenCalled() }) it("move: withdraws the stored token when the later read rejects at its pre-read", async () => { // Finding 4747783171 asks for the probe that rejects after an earlier read already verified. // The two neighbours of this state are pinned above: one rejects the only read this execute // makes, so no token was stored yet and the withdrawal has nothing to act on there; the other // rejects nothing - its later pair answers with two different versions, which runs the // disagreed-pair clear rather than the clear for a probe that could not answer at all. Here // the in-place update read verifies first and stores its version, and the move read of the // same path pre-reads an EIO while its post-read answers normally: the pair names no version, // verification did not happen, and a standing token describes a version this call cannot // connect to the bytes it found. It is withdrawn, and the move hands the guard false. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The in-place update read is stats one and two and answers with the identity every // committed row uses, so its pair agrees and verifies. Stat 3 belongs to the move // read of the same path and rejects with EIO. let sourceStats = 0 // The move asks the filesystem what each of its two names refers to, so the destination has // a probe of its own in this state. The patch is about to create that path, and a double // that answers it with a file identity describes a file already sitting there beside a // publish the guard is about to run in create mode - the one state the create guard // refuses. The answer is recorded so the row cannot drift back to the lying world. const destKey = path.resolve("/workspace/project", "src/new.ts") const destStatAnswers: string[] = [] const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === sourceKey && ++sourceStats === 3) { return Promise.reject(Object.assign(new Error("EIO: i/o error, stat failed"), { code: "EIO" })) } if (String(target) === destKey) { destStatAnswers.push("ENOENT") return Promise.reject( Object.assign(new Error("ENOENT: no such file or directory, stat"), { code: "ENOENT" }), ) } return sharedIdentity(target) }) await tool.execute({ patch: updateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-withdrawn-by-rejected-preread", }) // Both publishes ran: the in-place update first, then the move onto the destination. expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockSaveDirectly.mock.calls[1]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[1]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. With // the stored token still standing the entry version equals it and the argument is true; // a probe that could not answer must withdraw it, so the honest claim is false. expect(mockSaveDirectly.mock.calls[1]?.[6]).toBe(false) // The move completed and the model earned entry is untouched: what the rejected probe // withdraws is this execute map entry, not the read the model actually made. expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(reg.get(sourceKey)?.complete).toBe(true) // The destination was probed and answered absent: that is the only state a create-mode // publish tells the truth about. The answer comes from the double itself, so pinning it // here is what stops the fixture from describing the path as present again in silence. expect(destStatAnswers).toEqual(["ENOENT"]) // The destination access probe at ApplyPatchTool.ts:729 belongs to the branch that // downgrades an existing destination the model had read. This state observes the source // only, so that branch never runs and the shared access double is never asked about the // destination. Pinned rather than answered, because the fixture makes no claim about a // probe this state does not make. expect(mockedFsPromises.default.access.mock.calls.map((call) => String(call[0]))).not.toContain(destKey) expect(mockHandleError).not.toHaveBeenCalled() // Hand the stat double back: beforeEach clears calls but keeps implementations, so an // implementation set inside one row answers for every later row as well. mockedFsPromises.default.stat.mockImplementation(sharedIdentity) }) it("move: withdraws the stored token when the later read rejects at its post-read", async () => { // The other member of the pair, and the one a withdrawal keyed on the pre-read alone would // miss: the pre-read of the move read answers with the file identity while the post-read // rejects with EIO. The in-place update read verified and stored its version first. A probe // that cannot answer says nothing about the version the pair was meant to prove, so the // standing token is withdrawn for exactly the reason the disagreed pair withdraws its own, // and the honest argument to the create guard is false. The publish still runs: what the // guard makes of the destination is the guard business, not a reason to claim a full read. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The in-place update read is stats one and two and answers with the identity every // committed row uses, so its pair agrees and verifies. Stat 4 belongs to the move // read of the same path and rejects with EIO. let sourceStats = 0 // The move asks the filesystem what each of its two names refers to, so the destination has // a probe of its own in this state. The patch is about to create that path, and a double // that answers it with a file identity describes a file already sitting there beside a // publish the guard is about to run in create mode - the one state the create guard // refuses. The answer is recorded so the row cannot drift back to the lying world. const destKey = path.resolve("/workspace/project", "src/new.ts") const destStatAnswers: string[] = [] const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === sourceKey && ++sourceStats === 4) { return Promise.reject(Object.assign(new Error("EIO: i/o error, stat failed"), { code: "EIO" })) } if (String(target) === destKey) { destStatAnswers.push("ENOENT") return Promise.reject( Object.assign(new Error("ENOENT: no such file or directory, stat"), { code: "ENOENT" }), ) } return sharedIdentity(target) }) await tool.execute({ patch: updateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-withdrawn-by-rejected-postread", }) // Both publishes ran: the in-place update first, then the move onto the destination. expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockSaveDirectly.mock.calls[1]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[1]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. With // the stored token still standing the entry version equals it and the argument is true; // a probe that could not answer must withdraw it, so the honest claim is false. expect(mockSaveDirectly.mock.calls[1]?.[6]).toBe(false) // The move completed and the model earned entry is untouched: what the rejected probe // withdraws is this execute map entry, not the read the model actually made. expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(reg.get(sourceKey)?.complete).toBe(true) // The destination was probed and answered absent: that is the only state a create-mode // publish tells the truth about. The answer comes from the double itself, so pinning it // here is what stops the fixture from describing the path as present again in silence. expect(destStatAnswers).toEqual(["ENOENT"]) // The destination access probe at ApplyPatchTool.ts:729 belongs to the branch that // downgrades an existing destination the model had read. This state observes the source // only, so that branch never runs and the shared access double is never asked about the // destination. Pinned rather than answered, because the fixture makes no claim about a // probe this state does not make. expect(mockedFsPromises.default.access.mock.calls.map((call) => String(call[0]))).not.toContain(destKey) expect(mockHandleError).not.toHaveBeenCalled() // Hand the stat double back: beforeEach clears calls but keeps implementations, so an // implementation set inside one row answers for every later row as well. mockedFsPromises.default.stat.mockImplementation(sharedIdentity) }) // Row 4507855182 (measured): the destination commits and the source unlink below never runs, // so a move that hits a buffer conflict is half-applied. The report has to name both paths // and keep the shared error's no-retry guidance, because the model's next instinct is to // re-apply the patch - which would duplicate the change at the destination. it("move: a committed destination with the source still on disk names both paths", async () => { const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The subject is a destination that committed and then conflicted with unsaved buffer // edits, so the destination is a present file the guard had to be willing to write: // that needs a complete observation at its own token. The withdrawal asserted below is // still the point - it starts here and the finally sweep removes it. reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) mockSaveDirectly.mockRejectedValueOnce( new CommittedWriteBufferConflictError( destKey, "saveDirectly: the buffer held unsaved edits that differ from the content the guard published.", ), ) mockedFsPromises.default.unlink.mockClear() await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "CommittedWriteBufferConflictError" }), ) const reported = (mockHandleError.mock.calls[0]?.[1] ?? new Error("")) as Error expect(reported.message).toContain("src/new.ts committed but") expect(reported.message).toContain("src/old.ts was not removed") expect(reported.message).toContain("do not retry") // The half-applied state is stated, not implied: the source was never unlinked. The // destination keeps the entry the model earned on its own read - a move this layer refused // does not rewrite a read it never touched. This is where honest arming changed what the // row can claim: the committed fixture asserted undefined here, and that was only true // because the row had put nothing at the destination at all, so there was nothing to // withdraw and no state the guard was ever being asked to write. expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(reg.get(destKey)?.complete).toBe(true) expect(reg.get(destKey)?.version).toBe("7:4343:1234:1700000000123456789:1700000000789999999") }) it("move: the destination cannot claim completeness when the source was never observed", async () => { // The hunk read records no observation when its stat fails, so the model has // no authority over the source content the move carried over. Nothing is // recorded for the destination before the write chain runs, so the guard still // refuses a full-file write to a file the model never read. const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry mockedFsPromises.default.stat.mockImplementationOnce(() => Promise.reject(new Error("stat failed"))) const observedAtPublish: boolean[] = [] const guardSeen = delegateSaveDoubleToGuard(() => observedAtPublish.push(reg.has(destKey))) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(path.resolve("/workspace/project", "src/old.ts"))).toBeUndefined() expect(observedAtPublish).toEqual([false]) // The guard ran inside the tool's own publish, so its refusal is reported the way every // other guard refusal is - through handleError, naming the destination - and the // source unlink never happens because the move never published. (Row 4753503083: the // success double let the tool unlink src/old.ts and the rejection was only checked // afterwards, from outside the publish.) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError", message: "File already exists at src/new.ts and was not read before this write -- read the file first, then retry.", }), ) expect(mockHandleError.mock.calls[0]?.[1]).toBe(guardSeen.errors[0]) expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(reg.get(destKey)).toBeUndefined() }) it("move: leaves an unobserved destination alone when the source read was partial", async () => { // The publish records an observation only when it can compute the new on-disk // token. With nothing recorded for the destination there is nothing to // downgrade, and the carry must not dereference a missing observation. const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry // Nothing was read at the destination and nothing is there: the pair the create guard // accepts without an observation. Arm the second half, or this is a publish the double // granted and the guard would have refused. armDestinationAbsent(destKey) reg.observe( path.resolve("/workspace/project", "src/old.ts"), "7:4242:1234:1700000000123456789:1700000000789999999", false, ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(reg.get(destKey)).toBeUndefined() expect(mockHandleError).not.toHaveBeenCalled() }) // The destination publishes before the source unlink is attempted, so a failed unlink // leaves the source sitting on disk with its original bytes. Nothing was published at // that path, and the only thing still able to authorize a later edit is the partial // observation this call recorded for itself, so it has to be withdrawn here. it("move: withdraws the source observation when its unlink fails after the destination published", async () => { const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry // The destination is fresh, so the publish this row orders against the source unlink is // one the guard would actually perform rather than one only the double accepted. armDestinationAbsent(path.resolve("/workspace/project", "src/new.ts")) const events: string[] = [] mockedFsPromises.default.unlink.mockImplementationOnce(async () => { events.push("unlink") throw Object.assign(new Error("EPERM: operation not permitted, unlink"), { code: "EPERM" }) }) mockSaveDirectly.mockImplementationOnce(async () => { events.push("save") return { newProblemsMessage: "", userEdits: undefined, finalContent: "new content" } }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockSaveDirectly).toHaveBeenCalled() // The order the finding rests on: the destination publishes first and only then is the // source unlink attempted, once, against the source path. (Row 4753503104.) expect(events).toEqual(["save", "unlink"]) expect(mockedFsPromises.default.unlink).toHaveBeenCalledTimes(1) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockHandleError).not.toHaveBeenCalled() expect(reg.has(sourceKey)).toBe(false) // The consequence the finding names: with the source observation gone, a follow-up // targeted write to the source needs a real read instead of riding on the leftover. await expect(guardedWrite(mockTask as Task, "src/old.ts", "full replacement", "update")).rejects.toThrow( "File already exists at src/old.ts and was not read before this write -- read the file first, then retry.", ) }) it("update: surfaces the unobserved-existing remediation as a tool error", async () => { // The row has to earn its refusal for real: on the shared identity the read records an // observation and the guard accepts the write, so the bracketing pair below is made to // disagree and nothing is observed. Handing the publish to the guard is what exposed this // - the injected rejection had been standing in for a state the row never armed. const statMock = mockedFsPromises.default.stat statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) // The refusal is the guard's own. An update hunk publishes as an edit, so the remediation // is the edit one; the create guard's text written here by hand would have let a publish // that asked for create semantics pass this row unchanged. (Row 4753503048.) const guardSeen = delegateSaveDoubleToGuard() await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError", message: "File not read yet -- read the file, then retry.", }), ) expect(mockHandleError.mock.calls[0]?.[1]).toBe(guardSeen.errors[0]) expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") }) it("update: surfaces the stale-version remediation as a tool error", async () => { const guardError = new Error( "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", ) mockSaveDirectly.mockRejectedValue(guardError) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) }) it("update: the diff-view save selects the same edit guard as the guarded save", async () => { // With focus-disruption prevention off the tool saves through the diff view. // A partial read must not be rejected there, otherwise the patch the user // approved is thrown away. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockSaveChanges).toHaveBeenCalledWith(true, 1000, "edit", false, undefined) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockHandleError).not.toHaveBeenCalled() }) it("add: the diff-view save uses the create guard for a new file", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) await tool.execute({ patch: addPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockSaveChanges).toHaveBeenCalledWith(true, 1000, "create", false, undefined) expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") expect(mockHandleError).not.toHaveBeenCalled() }) // The two rows below pin the flag-off move branch as it ships: a raw fs.mkdir plus // fs.writeFile, with no guard, no completeness carry and no compare-and-swap. They // document current behaviour - main's ApplyPatchTool (blob 2713e08ffe8d) writes the // flag-off move with `await fs.writeFile(moveAbsolutePath, newContent, "utf8")` at // :422 - and they are not a claim that this is the contract the branch should keep. // Routing this branch through the guarded publish is a deliberate improvement and // should turn these rows red; reading them as endorsement of the raw write would // make that improvement look like a regression. it("flag-off move: publishes through fs.mkdir then fs.writeFile, with no guard and no completeness carry", async () => { mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) // The cast above declares access/stat/unlink only because nothing else on the // mocked module was reached before this branch was exercised; writeFile is read // through its own narrow view of the doubles. const writeDoubles = vi.mocked( fsPromises as unknown as { default: { writeFile: ReturnType; mkdir: ReturnType } }, ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-plain-write", }) expect(writeDoubles.default.mkdir).toHaveBeenCalledWith( path.dirname(path.resolve("/workspace/project", "src/new.ts")), { recursive: true }, ) expect(writeDoubles.default.writeFile).toHaveBeenCalledWith( path.resolve("/workspace/project", "src/new.ts"), "modified file content\n", "utf8", ) // No guard runs here: the guarded publish lives behind saveDirectly, and this // shape reaches neither the guarded save nor the diff-view save. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalled() }) it("flag-off move: an existing destination is never consulted before the write", async () => { mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-destination-present", }) // The access double resolves, so the destination reads as present on disk, yet // nothing asks: the branch does not read it, stat it, or guard against publishing // over content the model never saw. expect(mockedFsPromises.default.access).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalled() }) it("flag-off move: refuses a destination outside every workspace root before mkdir or writeFile", async () => { // The twin of the guarded row above. The refusal is above the experiment-flag branch, so the raw // publish path never sees an outside-workspace destination either: no directory is created, nothing // is written, and the source is left where it was. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) const destKey = path.resolve("/workspace/project", "src/new.ts") vi.mocked(isPathOutsideWorkspace).mockImplementation((candidate: string) => candidate === destKey) const writeDoubles = vi.mocked( fsPromises as unknown as { default: { writeFile: ReturnType; mkdir: ReturnType } }, ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-outside-workspace-destination", }) expect(mockPushToolResult).toHaveBeenCalledWith( expect.stringContaining("Cannot move file to path outside workspace: src/new.ts"), ) expect(writeDoubles.default.mkdir).not.toHaveBeenCalled() expect(writeDoubles.default.writeFile).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch") expect(mockHandleError).not.toHaveBeenCalled() }) // The hunk read is the content the guarded publish republishes. An ASCII hunk can match a // file whose bytes somewhere else cannot be decoded, and reading those bytes as UTF-8 // substitutes them, so the write would change bytes the patch never mentioned. The refusal has // to land before the read is recorded as an observation, or the substituted version becomes // the version a later full-file write is allowed to publish. const undecodableTail = (): Buffer => Buffer.concat([Buffer.from("original file content\n"), Buffer.from([0xc3, 0x28])]) const undecodableUpdatePatch = `*** Begin Patch *** Update File: src/thing.ts @@ -original file content +modified file content *** End Patch` const deleteThingPatch = `*** Begin Patch *** Delete File: src/thing.ts *** End Patch` const runPatch = async (patch: string): Promise => { await tool.execute({ patch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) } it("update: refuses a file it cannot decode rather than publishing replacement characters", async () => { mockedFsPromises.default.readFile.mockResolvedValue(undecodableTail()) await runPatch(undecodableUpdatePatch) const pushed = String(mockPushToolResult.mock.calls[0]?.[0] ?? "") expect(pushed).toContain("not valid UTF-8") // 0xC3 0x28 is not a valid sequence and it sits at byte 22 - past the line the hunk // matched. The hunk is ASCII and matched fine, which is the case the row is about: the // bytes at fault are ones the patch never mentions. expect(pushed).toContain("byte 22") expect(pushed).toContain("src/thing.ts") // Nothing published and nothing asked: the refusal happens while the hunks are still // being processed, before any publish prompt exists. expect(mockAskApproval).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() // The read must not survive as an observation: the version it saw is the version a // later full-file write would be permitted to publish. expect(mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts"))).toBeUndefined() expect(mockTask.consecutiveMistakeCount).toBe(1) expect(mockTask.didEditFile).toBe(false) }) it("update: a file that legitimately contains a replacement character still publishes", async () => { // U+FFFD written as EF BF BD is valid UTF-8. The refusal is about bytes that cannot be // decoded, not about a character appearing in the text - a check on the decoded string // would refuse this file for no reason. // EF BF BD is U+FFFD written as bytes: the file legitimately contains the character, and // those bytes are valid UTF-8. (A \uFFFD... escape here would be ambiguous - FFFE is a // legal 4-digit escape - so the sequence is spelled in bytes on purpose.) const replacementCharacterIsLegitimate = Buffer.concat([ Buffer.from("original file content\n"), Buffer.from([0xef, 0xbf, 0xbd]), Buffer.from("end\n"), ]) mockedFsPromises.default.readFile.mockResolvedValue(replacementCharacterIsLegitimate) await runPatch(undecodableUpdatePatch) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/thing.ts", "modified file content\n\uFFFDend\n", // The tail the patch never mentioned travels through the publish unchanged: // that is what a file that legitimately contains a replacement character looks like. false, true, 1000, "edit", undefined, false, undefined, ) expect(mockTask.consecutiveMistakeCount).toBe(0) }) it("delete: an undecodable file is still deleted, because nothing republishes its bytes", async () => { // Narrowing, not blanket refusal: the delete publishes by unlinking, so the reading is a // snapshot and the bytes nobody can name are not rewritten by anything this tool does. mockedFsPromises.default.readFile.mockResolvedValue(undecodableTail()) await runPatch(deleteThingPatch) expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(path.resolve("/workspace/project", "src/thing.ts")) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Successfully deleted")) expect(mockTask.consecutiveMistakeCount).toBe(0) }) })