// 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, type GuardRejectedError } 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 move rows: the publisher creates the destination's parent directory and // commits the staged file by renaming it onto the destination, and the rows ask whether those // ran. Typed loosely for the same reason as writeFile above - both are overloaded and the rows // only ever ask about calls. mkdir: ReturnType rename: 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), // A publish that got past a guard stages beside the destination and commits with a rename, // so nothing ever aims a write at the destination itself. The rows that expect no write at // all are the refusal rows, and they ask this double. writeFile: vi.fn().mockResolvedValue(undefined), // Added for the guarded publish: the publisher commits by renaming its staged file onto // the destination, then removes the staging directory it made. A row that expects a // publish to have landed needs both. rename: vi.fn().mockResolvedValue(undefined), rmdir: vi.fn().mockResolvedValue(undefined), } return { default: doubles, ...doubles } }) // The publisher behind a guarded write stages with the synchronous fs API: it makes its // staging directory, looks at that directory before it writes a byte into it and again just // before the commit rename, opens the staged file, writes it, fsyncs it and closes it // through fs/*Sync, and it asks the target it is replacing for its mode. Nothing in this // file reaches those calls until a write actually gets past a guard, so each double answers // one of the publisher's own questions and reports a file this spec never created. vi.mock("fs", () => { const syncDoubles = { constants: {}, mkdirSync: vi.fn(), chmodSync: vi.fn(), // Every path this spec names is one its doubles made up, so the target whose mode the // publisher asks for is not there: the fresh-target answer keeps the staged file at the // default mode instead of inheriting a mode this spec never set. statSync: vi.fn((target: unknown) => { throw Object.assign(new Error(`ENOENT: no such file or directory, stat '${String(target)}'`), { code: "ENOENT", }) }), // The publisher asks the staging directory it just made what it is: once before any byte goes // into it, and once immediately before the commit rename, refusing when the name answers a // symbolic link or stops answering the directory it created. The double answers a real // directory with one identity, because a different identity between those two looks is // another refusal that no row below asks for. The bigint fields match what the real call // answers for the { bigint: true } option the publisher passes. lstatSync: vi.fn(() => ({ dev: 7n, ino: 8080n, size: 4096n, isDirectory: () => true, isSymbolicLink: () => false, })), openSync: vi.fn(() => 42), fchmodSync: vi.fn(), fstatSync: vi.fn(() => ({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n })), // writeSync reports how many bytes landed and the publisher loops until the buffer is // fully written, so the double has to report the whole remainder or that loop spins. writeSync: vi.fn((_fd: number, _buffer: Buffer, _offset: number, length: number) => length), fsyncSync: vi.fn(), closeSync: vi.fn(), } return { default: syncDoubles, ...syncDoubles } }) // 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` // Row 4509006990: two Update sections for one path with nothing written between the two reads. Both // hunks match the content the first read found, so the second section's content describes the very // version the first section read, and publishing it writes the whole file over what the first // section saved - the tool had already reported that section as saved. The rows below run the // patch in each of the three save modes, then pin the two shapes this refusal does not claim. const twoInPlaceUpdatesPatch = `*** Begin Patch *** Update File: src/thing.ts @@ -original file content +modified first content *** Update File: src/thing.ts @@ -original file content +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. // One path read twice with nothing published between the reads: the first section's hunk replaces the // line with itself, so its publish is skipped ("No changes needed") while its read still verifies and // still fills the version map the move consults. That is the only shipped shape in which two reads of // one path coexist without the earlier one becoming a publish this patch has to refuse (rows // 4775257556 and 4777362968), so the token-withdrawal rows below run on it. const noopUpdateThenMovePatch = `*** Begin Patch *** Update File: src/old.ts @@ -original file content +original file content *** Update File: src/old.ts *** Move to: src/new.ts @@ -original file content +modified file content *** End Patch` 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()) // The canonical-containment row resolves one spelling somewhere else; the resolve-by-default // is restored here for the same reason stat and access are above, so the next row does not // have to know what a neighbour armed. mockedFsPromises.default.realpath.mockImplementation(async (p: string) => String(p)) 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 const publishError = new Error("extension host went away") mockSaveDirectly.mockRejectedValue(publishError) await tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-tool-call-id", }) expect(mockHandleError).toHaveBeenCalledWith("apply patch", publishError) 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), ) } // Absence for a create target, for the rows that need the publish to land: the probes that // ask whether the file is there answer "absent", while a stat afterwards still answers with // the file's identity. A create publish reads the new version token from that very stat, // and that token is what the guard records, so arming the stat to reject as well - which // armDestinationAbsent does - would skip the refresh and leave no observation to assert. const armCreateTargetAbsent = (destKey: string): void => { const enoent = (): Error => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) mockedFsPromises.default.stat.mockImplementation((target: unknown) => 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 the flag-off move through the guarded publish when 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. It is now an ordinary guarded move - the // destination is absent, which is the one state a create publish needs no observation for, and // the content lands through the publisher's commit rename onto the destination rather than // through a write this layer aimed at it. The saveDirectly double staying unused is what pins // the branch: this is the mode that never opened a diff view, not the mode that did. 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 }, }) // The destination answers "not there" to both probes that ask - the move's own identity read // and the create guard's freshness test - so this is a create and not a write over unread // content. armDestinationAbsent(destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-between-different-files", }) // The commit rename is the publish: a staged file first, then that file named at the // destination. The mkdir below is the publisher making the destination's own parent directory // before staging, which is the only reason that call appears at all now. expect(mockedFsPromises.default.mkdir).toHaveBeenCalledWith(path.dirname(destKey), { recursive: true }) expect(mockedFsPromises.default.rename).toHaveBeenCalledWith(expect.any(String), destKey) expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Saved file")) expect(mockTask.didEditFile).toBe(true) }) it("move: treats a destination that is not there as a create on the flag-off move", 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 - and the guard now gets // the same answer the move did, which is the only answer that lets a create publish. 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") // 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 }, }) armDestinationAbsent(destKey) 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.rename).toHaveBeenCalledWith(expect.any(String), destKey) expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() 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 the move whose source a publish in this patch moved past the verified version", async () => { // Rows 4775257556 and 4777362968 removed the carve-out that used to exempt a moving change from // this compare. The state is the same one this row has always built - the in-place publish // re-records the source at the version it committed, while the token the reads left standing // names the pre-publish version the hunk verified - and the move's queued content is that // source plus one hunk, so it is the stale bytes the move would have published at its // destination. The version compare now asks the question it already asked for an in-place // update, and it asks it before the move is offered, so the completeness argument below is // never reached: the state no longer reaches the guard at all. 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. reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The in-place publish (the only save) re-records the source at the version it committed - // what guardedWrite does after a committed publish. 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", }) // One save: the in-place update. The move that would have published the stale bytes at the // destination never reached its approval or its guard. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("another change in this patch published src/old.ts"), }), ) // The source keeps what its publish earned; the tool refuses, it does not edit the history // away, and it leaves the source file on disk rather than half-moving it. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1700000000222000000:1700000000333000000") expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Saved file") expect(reported).not.toContain("modified file content") }) 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("refuses an in-place update of a destination this patch published by moving onto it", async () => { // Row 4777362968: the move now records the path it published. The section after it built // its content from the read it made before the move ran, so publishing it writes the // destination's pre-move content over the file the move just committed - and the tool had // already reported the move as saved. The row above this group arms the post-publish refresh // and is refused by the version compare; this one leaves the save double silent about the // entry, which is what the flag-off save does, so no version compare can see the staleness // and the refusal has to come from this patch's own record of where it published. That // record used to name only in-place publishes (00cda02225), which is the half 4777362968 // found missing for a move. 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 the reads carry // completeness honestly and no entry is stale for a reason this row does not intend. reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) reg.observe(destKey, "7:4343:1234:1700000000123456789:1700000000789999999", true) // The publish double answers like a committed publish that records nothing: a flag-off save // does not re-record the observation, and that is the state where only the published-paths // record can refuse. const published: { relPath: string; writeKind: unknown; content: unknown }[] = [] mockSaveDirectly.mockImplementation(async (...args: unknown[]) => { const [relPath, content, , , , writeKind] = args 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-later-update-is-refused", }) // One save: the move's. The update that would have written the destination's pre-move // content over it asked no approval and reached no guard. expect(published.map((call) => [call.relPath, call.writeKind])).toEqual([["src/new.ts", "create"]]) expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("an earlier change in this patch already published src/new.ts"), }), ) // The destination's entry still names the version the update read made, so the refusal is // the patch's own record and not a version compare - which is what this row is for. expect(reg.get(destKey)?.version).toBe("7:4343:1234:1700000000123456789:1700000000789999999") // The move itself completed: its source is unlinked and its success reported, and the // refused section's content was never reported as saved. expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported.split("Saved file").length - 1).toBe(1) 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. // The fixture is a no-op first section: an update that publishes would now refuse the // move after it (rows 4775257556 and 4777362968), and this row needs both reads of the // path inside one execute with no publish between them. 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: noopUpdateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-cleared-by-failed-verification", }) // One save: the move. The section before it published nothing, so it left nothing // on the record of paths this patch may not publish twice (rows 4775257556 and // 4777362968), and the guard is handed the argument this finding refuses. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[0]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. expect(mockSaveDirectly.mock.calls[0]?.[6]).toBe(false) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("No changes needed for 'src/old.ts'") expect(reported).toContain("Saved file") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) // The registry keeps what the model earned. What the withdrawal acts on is the version // this execute stored for the path, not the entry, and neither a disagreed pair nor a // probe that could not answer rewrites the entry - so the entry still names the seeded // version while the argument handed to the guard above is false. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") expect(mockHandleError).not.toHaveBeenCalled() // Hand the stat double back: beforeEach clears calls but keeps implementations. mockedFsPromises.default.stat.mockImplementation((target: unknown) => Promise.resolve(_identityOf(String(target))), ) }) 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 beside it: 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 first read verifies 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. // The fixture is a no-op first section: an update that publishes would now refuse the move // after it (rows 4775257556 and 4777362968), and this row needs both reads of the path // inside one execute with no publish between them. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The first 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: noopUpdateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-withdrawn-by-rejected-preread", }) // One save: the move. The section before it published nothing, so it left nothing on the // record of paths this patch may not publish twice (rows 4775257556 and 4777362968), and // the guard is handed the argument these findings refuse. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[0]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. expect(mockSaveDirectly.mock.calls[0]?.[6]).toBe(false) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("No changes needed for 'src/old.ts'") expect(reported).toContain("Saved file") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) // 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 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. expect(mockedFsPromises.default.access.mock.calls.map((call) => String(call[0]))).not.toContain(destKey) // The registry keeps what the model earned. What the withdrawal acts on is the version // this execute stored for the path, not the entry, and neither a failed pair nor a probe // that could not answer rewrites the entry - so the entry still names the seeded version // while the argument handed to the guard above is false. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") 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 first read verified and stored its version. 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. // The fixture is a no-op first section, as in the row above: an update that publishes // would now refuse the move after it (rows 4775257556 and 4777362968). const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true) // The first 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: noopUpdateThenMovePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-token-withdrawn-by-rejected-postread", }) // One save: the move. The section before it published nothing, so it left nothing on the // record of paths this patch may not publish twice (rows 4775257556 and 4777362968), and // the guard is handed the argument these findings refuse. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/new.ts") expect(mockSaveDirectly.mock.calls[0]?.[5]).toBe("create") // The seventh argument is the completeness authorization the move hands the guard. expect(mockSaveDirectly.mock.calls[0]?.[6]).toBe(false) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("No changes needed for 'src/old.ts'") expect(reported).toContain("Saved file") expect(mockedFsPromises.default.unlink).toHaveBeenCalledWith(sourceKey) // 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 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. expect(mockedFsPromises.default.access.mock.calls.map((call) => String(call[0]))).not.toContain(destKey) // The registry keeps what the model earned. What the withdrawal acts on is the version // this execute stored for the path, not the entry, and neither a failed pair nor a probe // that could not answer rewrites the entry - so the entry still names the seeded version // while the argument handed to the guard above is false. expect(reg.get(sourceKey)?.complete).toBe(true) expect(reg.get(sourceKey)?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") 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") }) // Rows 4508420822 and 4509011474: the removal of a move's source is a second destruction, // separate from the publish, and it is authorized by the version the hunk read verified. // The rows below arm one stat answer - the probe the removal asks - and leave every other // probe in the patch answering the per-path identity the committed rows use, so the only // difference between these states and a completed move is what the source says about // itself at the moment the tool reaches for the unlink. it("move: leaves the source in place when it changed after the read that built the move", async () => { // The hunk read verified version A of src/old.ts and the destination published the // content built from it. Before the removal asks what is at the source, somebody // else writes that path: the newer bytes were never read by this patch, and // unlinking them here would delete them after the move had reported itself saved. const sourceKey = path.resolve("/workspace/project", "src/old.ts") const reg = mockTask.observationRegistry // A file bigger and newer than the one every committed row uses - a different token // under the spelling the tool compares versions with. const newerIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } // Stats 1 and 2 are the hunk read's pair and agree, which is what earns the version // the removal is conditioned on. Stat 3 is the move branch's own identity question // about the source. Stat 4 is the removal's probe, and it is the one this row arms. let sourceStats = 0 const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === sourceKey && ++sourceStats === 4) { return Promise.resolve(newerIdentity) } return sharedIdentity(target) }) try { await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-source-changed-after-read", }) // The destination published: the half that completed did complete. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/new.ts") // The source is still there: the removal was asked about a version it no longer // holds, so nothing was unlinked. expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Moved src/old.ts to src/new.ts") expect(reported).toContain("src/old.ts was left in place because it changed after this patch read it") expect(reported).toContain("Re-read src/old.ts before removing it or moving it again") // The report a completed move produces would have claimed a finished change, // which is the claim this state cannot make. expect(reported).not.toContain("Saved file") expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("src/old.ts was left in place")) expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) expect(mockTask.didEditFile).toBe(true) // What the source's observation leaves behind: the file still on disk is not the // version this call read, so its entry goes with the sweep instead of authorizing // a later edit of bytes nobody read. expect(reg.get(sourceKey)).toBeUndefined() // The pin on the arm itself: the counter names which ask at this path the row // changed the answer for, so the reported strings above are not the accident of a // probe armed somewhere else in the patch. expect(sourceStats).toBe(4) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("move: leaves the source in place when the filesystem will not say its version", async () => { // The other answer the removal can get: not a different version, no answer at all. // "Cannot tell" is not "unchanged" - an unreadable source is kept for the same reason // a changed one is, and the report says which of the two it is. const sourceKey = path.resolve("/workspace/project", "src/old.ts") let sourceStats = 0 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" })) } return sharedIdentity(target) }) try { await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "move-source-version-unreadable", }) expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain( "src/old.ts was left in place because the filesystem would not say which version it holds now", ) expect(reported).not.toContain("Saved file") expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) // The pin on the arm itself: the counter names which ask at this path the row // changed the answer for, so the reported strings above are not the accident of a // probe armed somewhere else in the patch. expect(sourceStats).toBe(4) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("delete: leaves the file when its version moved between the read and the unlink", async () => { // Row 4508420822 names this shape too - "a standalone delete has the same gap". A // delete publishes nothing, so the only version this call ever proved for the bytes // is the one its own read verified. Stat 3 is the probe the removal asks; stats 1 // and 2 are the read's pair and they agree. const targetKey = path.resolve("/workspace/project", "src/thing.ts") const reg = mockTask.observationRegistry const newerIdentity = { dev: 7n, ino: 4242n, size: 1235n, mtimeNs: 1_700_000_000_222_000_000n, ctimeNs: 1_700_000_000_333_000_000n, } let sourceStats = 0 const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === targetKey && ++sourceStats === 3) { return Promise.resolve(newerIdentity) } return sharedIdentity(target) }) try { await tool.execute({ patch: deleteOnlyPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-source-changed-after-read", }) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Cannot delete src/thing.ts: it changed after this patch read it") expect(reported).toContain("src/thing.ts was left in place with the bytes it holds now") expect(reported).not.toContain("Successfully deleted") expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) expect(mockTask.didEditFile).toBe(false) expect(reg.get(targetKey)).toBeUndefined() // The pin on the arm itself: the counter names which ask at this path the row // changed the answer for, so the reported strings above are not the accident of a // probe armed somewhere else in the patch. expect(sourceStats).toBe(3) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) it("delete: reports a vanished file through the unlink, not as a version that moved", async () => { // The scope of the new check, pinned from the other side. A source that already // went away holds no bytes for the removal to destroy: the probe answers absent, the // unlink still runs, and its own failure - not this check - is what a vanished path // is reported by. Nothing here is claimed as a change nobody made. const targetKey = path.resolve("/workspace/project", "src/thing.ts") let sourceStats = 0 const sharedIdentity = (target: unknown) => Promise.resolve(_identityOf(String(target))) mockedFsPromises.default.stat.mockImplementation((target: unknown) => { if (String(target) === targetKey && ++sourceStats === 3) { return Promise.reject( Object.assign(new Error("ENOENT: no such file or directory, stat"), { code: "ENOENT" }), ) } return sharedIdentity(target) }) try { await tool.execute({ patch: deleteOnlyPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "delete-source-vanished-before-unlink", }) 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("was left in place") expect(mockTask.consecutiveMistakeCount).toBe(0) // The pin on the arm itself: the counter names which ask at this path the row // changed the answer for, so the reported strings above are not the accident of a // probe armed somewhere else in the patch. expect(sourceStats).toBe(3) } finally { mockedFsPromises.default.stat.mockImplementation(sharedIdentity) } }) 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 now: the publish is the guard's. // They used to pin a raw fs.mkdir plus fs.writeFile with no guard, no completeness carry and no // compare-and-swap - main's ApplyPatchTool (blob 2713e08ffe8d) writes the flag-off move with a // raw fs.writeFile(moveAbsolutePath, newContent, "utf8") at :422 - and the comment that sat here // said that routing this branch through the guarded publish should turn them red. It did: both // rows were rewritten rather than deleted, because they still ask the same two questions - is the // destination consulted, and what publishes onto it - and now get the guarded answers. it("flag-off move: publishes through the guard with create kind", async () => { mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) const destKey = path.resolve("/workspace/project", "src/new.ts") armDestinationAbsent(destKey) // The cast below declares only the members these rows ask about: rename is the publish, and // writeFile is the shape this layer used to write in. const writeDoubles = vi.mocked( fsPromises as unknown as { default: { writeFile: ReturnType; rename: ReturnType } }, ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-plain-write", }) // The destination got its content through the publisher's commit rename rather than through a // write this layer aimed at it. Create kind is what the refusal row below evidences: the same // call onto a destination that IS there comes back as the create guard's own remediation. expect(writeDoubles.default.rename).toHaveBeenCalledWith(expect.any(String), destKey) expect(writeDoubles.default.writeFile).not.toHaveBeenCalled() // Neither guarded save is reached: this mode never opened a diff view, so the publish goes to // the guard directly rather than through the diff view's own save. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockSaveChanges).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() expect(mockPushToolResult).toHaveBeenCalled() }) it("flag-off move: a partial source view leaves the destination observation partial", async () => { // The bytes published at the destination are the source file plus one hunk, so they are only // as complete as the view the model had of the source. This mode carried no completeness, and // the guard refreshes the destination observation with whatever the call carries: with no // override it records complete, and that entry is what would let a later full-file write // publish bytes assembled from a slice the model never read whole. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) const sourceKey = path.resolve("/workspace/project", "src/old.ts") const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry // A slice read of the source, recorded at the version that read verified. reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", false) armCreateTargetAbsent(destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-partial-source", }) // The publish landed, through the guard's own commit rename. expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockedFsPromises.default.rename).toHaveBeenCalledWith(expect.any(String), destKey) expect(mockHandleError).not.toHaveBeenCalled() const published = reg.get(destKey) // The destination's own entry, recorded at the token the post-publish stat answers, // not a leftover of the source's. expect(typeof published?.version).toBe("string") expect(published?.version).toContain(":4343:") expect(published?.complete).toBe(false) // Leave the shared doubles as the rows after these expect them: an absence arm changes // implementations, not just recorded calls, and this file clears calls only. mockedFsPromises.default.access.mockResolvedValue(undefined) mockedFsPromises.default.stat.mockImplementation((target: unknown) => Promise.resolve(_identityOf(String(target))), ) }) it("flag-off move: a complete source read carries completeness to the destination", async () => { // The pair the partial row above needs. Without it, passing false unconditionally would // satisfy the finding while refusing a move whose content the model really did read whole. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) 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) armCreateTargetAbsent(destKey) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-complete-source", }) expect(mockedFsPromises.default.rename).toHaveBeenCalledWith(expect.any(String), destKey) const published = reg.get(destKey) expect(typeof published?.version).toBe("string") expect(published?.complete).toBe(true) // Leave the shared doubles as the rows after these expect them: an absence arm changes // implementations, not just recorded calls, and this file clears calls only. mockedFsPromises.default.access.mockResolvedValue(undefined) mockedFsPromises.default.stat.mockImplementation((target: unknown) => Promise.resolve(_identityOf(String(target))), ) }) it("flag-off move: the destination is consulted before anything is staged", async () => { mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) const destKey = path.resolve("/workspace/project", "src/new.ts") 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 a present file, and the guard is now // the thing that asks. Asking is what changed: the raw branch wrote without ever looking, and // the guard refuses what it cannot authorize (the next row pins the verdict), so nothing was // made and nothing was staged. expect(mockedFsPromises.default.access).toHaveBeenCalledWith(destKey) expect(mockedFsPromises.default.mkdir).not.toHaveBeenCalled() expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).not.toHaveBeenCalled() expect(mockHandleError).toHaveBeenCalledTimes(1) }) 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() }) it("flag-off move: the guard refuses an existing destination the model never read", async () => { // The finding's own test. The destination is present - the access double answers "present" for // it, as it does for every path in this spec - and no observation names it, so the content the // move would publish is a full-file replacement of bytes the model never saw. The refusal below // is the create guard's own remediation rather than a message this layer chose to print, which // is why the row asks for the error by the name the guard gives it. const destKey = path.resolve("/workspace/project", "src/new.ts") const reg = mockTask.observationRegistry mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) expect(reg.has(destKey)).toBe(false) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-unobserved-destination", }) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError" }), ) // The row asked for the guard's verdict by name above, so the error class that carries that verdict // is the type this row reads its fields off. const reported = (mockHandleError.mock.calls[0]?.[1] ?? new Error("")) as GuardRejectedError expect(reported.message).toContain("File already exists at src/new.ts") expect(reported.message).toContain("read the file first, then retry") expect(reported.path).toBe("src/new.ts") // Nothing was made, staged, published or removed, and the destination has no observation at // the end that it did not have at the start: the refusal is the whole outcome. expect(mockedFsPromises.default.mkdir).not.toHaveBeenCalled() expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).not.toHaveBeenCalled() expect(reg.has(destKey)).toBe(false) }) it("flag-off move: the guard refuses a destination that resolves to outside the workspace", async () => { // The lexical check this layer runs knows only the spelling the patch named. Here the // destination is spelled inside the workspace and resolves to a file outside every workspace // folder, which is what a link sitting at the destination does. The raw write followed the link; // the guard resolves the same way the publish will and refuses before anything is staged. const destKey = path.resolve("/workspace/project", "src/new.ts") const outsideKey = path.resolve("/outside-the-workspace", "referent.ts") mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) // Only this spelling resolves elsewhere: the workspace root and every other path keep answering // what they answered before, so the refusal is about the destination and not about the lookup. mockedFsPromises.default.realpath.mockImplementation((p: unknown) => String(p) === destKey ? Promise.resolve(outsideKey) : Promise.resolve(String(p)), ) await tool.execute({ patch: movePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-destination-resolves-outside", }) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError" }), ) const reported = (mockHandleError.mock.calls[0]?.[1] ?? new Error("")) as GuardRejectedError expect(reported.message).toContain("resolves through a link to outside the workspace") expect(reported.path).toBe("src/new.ts") expect(mockedFsPromises.default.mkdir).not.toHaveBeenCalled() expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).not.toHaveBeenCalled() }) it("flag-off move: a destination in another workspace folder is refused because core hands the guard no roots", async () => { // The known cost of calling the guard from core rather than from the diff view: guardedWrite // builds its roots from task.cwd plus the additional roots its host caller supplies, and // DiffViewProvider is what passes the other workspace folders. A core tool has no such list to // hand it, so a destination in a second folder - one this layer's own outside-workspace check // accepts, because that check classifies against every folder - is refused instead of published. // The refusal is fail-safe: nothing lands outside the root the task owns. Closing the gap needs // roots to reach the tool, which is plumbing tracked separately. const siblingKey = path.resolve("/workspace/project", "../other-root/new.ts") const siblingPatch = `*** Begin Patch *** Update File: src/old.ts *** Move to: ../other-root/new.ts @@ -original file content +modified file content *** End Patch` mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) // The identity double answers the source's inode for every name it has no opinion about, and // this is one of them; left alone, the same-file check would refuse the move for the wrong // reason. The row states the geometry it means: two names, two files. mockedFsPromises.default.stat.mockImplementation((target: unknown) => String(target) === siblingKey ? Promise.resolve(_identityOf(path.resolve("/workspace/project", "src/new.ts"))) : Promise.resolve(_identityOf(String(target))), ) await tool.execute({ patch: siblingPatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "flag-off-move-destination-in-another-root", }) // A tool-layer refusal would have said "Cannot move file to path outside workspace" and counted // a mistake; this is the guard's verdict, which is why the mistake counter stays where it was. expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "GuardRejectedError" }), ) const reported = (mockHandleError.mock.calls[0]?.[1] ?? new Error("")) as GuardRejectedError expect(reported.message).toContain("Path resolves outside the workspace") expect(reported.path).toBe("../other-root/new.ts") expect(mockTask.recordToolError).not.toHaveBeenCalled() expect(mockedFsPromises.default.mkdir).not.toHaveBeenCalled() expect(mockedFsPromises.default.rename).not.toHaveBeenCalled() expect(mockedFsPromises.default.writeFile).not.toHaveBeenCalled() expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockPushToolResult).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) }) it("update: refuses a second in-place update of a path this patch already published", async () => { // Row 4509006990 (Major - Data Integrity & Integration - Quick win): the hunk reads all run // before any publish (processAllHunks builds every change up front), so both sections of // this patch built their content from the same reading. Publishing the second writes the // whole file over the change the first one committed and drops it, while the tool has // already answered "Saved file" for it. The refusal belongs to the publish stage: the // version compare at ApplyPatchTool.ts:343-354 cannot see this shape, because both sections // verified the SAME version - it refuses only a publish that moved the version the registry // names, and the flag-off save below re-records nothing at all. const targetKey = path.resolve("/workspace/project", "src/thing.ts") // The default experiment arm is preventFocusDisruption on, so the guarded-shaped save double // is what runs here; the row below takes the flag-off arm and the one after it the real guard. // The readFile double keeps its implementation across rows - vi.clearAllMocks() clears calls, // not implementations - so this row states the content both of its hunks match rather than // inheriting whatever a neighbouring row armed. mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) await runPatch(twoInPlaceUpdatesPatch) // One publish, and it is the first section's content. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/thing.ts") expect(mockSaveDirectly.mock.calls[0]?.[1]).toBe("modified first content\n") expect(mockSaveChanges).not.toHaveBeenCalled() // The second section never got its approval: the refusal is offered before the prompt, // so the user is not asked to approve a publish the tool already knows it will refuse. expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("an earlier change in this patch already published src/thing.ts"), }), ) // What the patch leaves is the first change, half-applied rather than silently overwritten: // the same contract row 4758418975 pinned at spec 2290-2309 for the moved-onto case. const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Saved file") expect(reported).not.toContain("modified second content") // The refusal is the tool's own judgement about this patch, not a model mistake, so it does // not inflate the mistake counter, and the path that published keeps its observation. expect(mockTask.consecutiveMistakeCount).toBe(0) expect(mockTask.observationRegistry.get(targetKey)?.version).toBe( "7:4242:1234:1700000000123456789:1700000000789999999", ) }) it("update: refuses the second in-place update after the guarded publish committed the first", async () => { // The same refusal with the save double handed to the real guard, so the first section // commits through the staging rename the guard uses rather than through a plain double. // The guard refreshes the standing entry to the version it wrote (guardedWrite.ts:710), // which is the state row 4758418975 named; what refuses the second section here is that // this patch already published the path, not a version compare. delegateSaveDoubleToGuard() const writeDoubles = vi.mocked(fsPromises as unknown as { default: { rename: ReturnType } }) const targetKey = path.resolve("/workspace/project", "src/thing.ts") // The readFile double keeps its implementation across rows - vi.clearAllMocks() clears calls, // not implementations - so this row states the content both of its hunks match rather than // inheriting whatever a neighbouring row armed. mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) await runPatch(twoInPlaceUpdatesPatch) // One committed publish: one staging rename onto the path, and one save call. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(writeDoubles.default.rename).toHaveBeenCalledTimes(1) expect(writeDoubles.default.rename).toHaveBeenCalledWith(expect.any(String), targetKey) expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("an earlier change in this patch already published src/thing.ts"), }), ) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Saved file") expect(reported).not.toContain("modified second content") }) it("update: refuses the second in-place update on the flag-off save too, not only the guarded one", async () => { // The other save mode: with the flag off the update publishes through the diff view's own // save (ApplyPatchTool.ts:929-935), which re-records nothing, so no version compare // could ever notice the second section's stale content. The refusal is therefore asked // independently of which save runs - the finding's own condition named only the guarded // mode, and losing the change is worse here. mockGetState.mockResolvedValue({ diagnosticsEnabled: true, writeDelayMs: 1000, experiments: {} }) // The readFile double keeps its implementation across rows - vi.clearAllMocks() clears calls, // not implementations - so this row states the content both of its hunks match rather than // inheriting whatever a neighbouring row armed. mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) await runPatch(twoInPlaceUpdatesPatch) expect(mockSaveChanges).toHaveBeenCalledTimes(1) expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("an earlier change in this patch already published src/thing.ts"), }), ) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported).toContain("Saved file") expect(reported).not.toContain("modified second content") }) it("update: publishes both sections when the two updates target two different paths", async () => { // The scope of the refusal above, taken from the other side: what is refused is a second // write onto a path this patch already committed, not a patch that happens to hold two // Update sections. Two paths stay the ordinary shape - both publishes run, both are // reported, and nothing is refused. // The readFile double keeps its implementation across rows - vi.clearAllMocks() clears calls, // not implementations - so this row states the content both of its hunks match rather than // inheriting whatever a neighbouring row armed. mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) await runPatch(twoUpdatePatch) expect(mockSaveDirectly).toHaveBeenCalledTimes(2) expect(mockSaveDirectly.mock.calls.map((call) => String(call[0]))).toEqual(["src/first.ts", "src/second.ts"]) expect(mockAskApproval).toHaveBeenCalledTimes(2) expect(mockHandleError).not.toHaveBeenCalled() expect(mockTask.consecutiveMistakeCount).toBe(0) }) it("update: refuses a move whose source an earlier section already published", async () => { // Rows 4775257556 and 4777362968 overturn the carve-out this row used to pin, which // fc5d6cfb2b wrote into the version compare and 00cda02225 wrote into this refusal: a change // that moves this path publishes at a different path, so it was said not to be the hazard. // The premise is wrong in this direction. Every hunk read runs before any publish // (processAllHunks builds all the change content up front), so the move's content came from // the source as it stood before the earlier section saved it. The move is a publish of that // path's content too - at its destination - and the earlier section's committed bytes are // what it would overwrite there, while the tool had already reported that section as saved. // The row therefore now pins the refusal. What the move was authorized to claim about the // destination is pinned beside it, by the rows that do reach the guard. // The readFile double keeps its implementation across rows - vi.clearAllMocks() clears calls, // not implementations - so this row states the content both of its hunks match rather than // inheriting whatever a neighbouring row armed. mockedFsPromises.default.readFile.mockResolvedValue(Buffer.from("original file content\n")) await runPatch(updateThenMovePatch) // One save: the in-place update. The move was refused before its approval was asked, so the // pre-move content was never published at the destination and the source was never unlinked. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) expect(mockSaveDirectly.mock.calls[0]?.[0]).toBe("src/old.ts") expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled() expect(mockAskApproval).toHaveBeenCalledTimes(1) expect(mockHandleError).toHaveBeenCalledWith( "apply patch", expect.objectContaining({ name: "ApplyPatchError", message: expect.stringContaining("an earlier change in this patch already published src/old.ts"), }), ) // Refusing a change the tool could not apply is not a model mistake, the same way the // second in-place update is not one: nothing reached the approval prompt, and the report // names only the section that was saved. expect(mockTask.consecutiveMistakeCount).toBe(0) const reported = mockPushToolResult.mock.calls.map((call) => String(call[0])).join(" ") expect(reported.split("Saved file").length - 1).toBe(1) expect(reported).not.toContain("modified moved content") }) })