Skip to content

Commit 78275a3

Browse files
committed
fix(tools): journal move source deletion and harden catch-path flush per review
- Journal a completed move's source deletion alongside the destination write (byte-identical builder logic) so step rollback restores the removed source; a move whose unlink failed gets no deletion entry - Set writeMetadataFlushed only when the flush proceeds to checkpointSave and cache perWriteCheckpoints for the catch flush (a rejecting settings read no longer skips persisting writes already on disk) - Report a catch-path checkpoint flush failure alongside the bookkeeping error instead of swallowing it
1 parent 65324b7 commit 78275a3

3 files changed

Lines changed: 104 additions & 34 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 50 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,34 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
7171
const { patch } = params
7272
const { handleError, pushToolResult } = callbacks
7373

74-
// Declared outside the try so the catch can persist write metadata
75-
// recorded before an unexpected throw.
74+
// Set once the success-path flush actually proceeds to checkpointSave, so
75+
// the catch below does not persist the same writes twice while a
76+
// settings-read rejection before that decision leaves the catch flush
77+
// armed with default-on semantics.
7678
let writeMetadataFlushed = false
79+
// Cached perWriteCheckpoints lookup shared by the success-path flush and
80+
// the catch flush: the catch must not call getState() again, because a
81+
// rejecting settings read must not skip persisting writes already on disk.
82+
let perWriteCheckpoints: boolean | undefined
7783
const successfulChanges: { change: ApplyPatchFileChange; diffStats?: DiffStats }[] = []
84+
// Journal payload builder shared by the success-path flush and the
85+
// catch-path flush for writes recorded before an unexpected throw.
86+
const journalEntries = () =>
87+
successfulChanges.flatMap(({ change, diffStats }) => {
88+
const written = {
89+
path: change.movePath ?? change.path,
90+
operation: change.type === "add" ? ("create" as const) : change.type,
91+
diffStats: diffStats ? { additions: diffStats.added, deletions: diffStats.removed } : undefined,
92+
}
93+
// A completed move also DELETES its source: journal that deletion
94+
// after the destination write so a step rollback restores the
95+
// removed file from its pre-step state. A move whose source unlink
96+
// failed left the source on disk and gets no deletion entry.
97+
if (change.movePath && change.moveSourceDeleted) {
98+
return [written, { path: change.path, operation: "delete" as const, diffStats: undefined }]
99+
}
100+
return [written]
101+
})
78102

79103
try {
80104
// Validate required parameters
@@ -206,31 +230,21 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
206230
// pushToolResult. A fully failed patch (nothing written) leaves no
207231
// checkpoint behind.
208232
if (patchSucceeded || successfulChanges.length > 0) {
209-
writeMetadataFlushed = true
210-
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
233+
perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
211234
if (perWriteCheckpoints !== false) {
235+
writeMetadataFlushed = true
212236
// B2: one journal entry per file that was actually written by
213237
// the patch (the simplest correct design for multi-file patches),
214238
// all referencing the single checkpoint above. A no-op update
215239
// contributes no entry because nothing was written. `movePath`,
216-
// when present, is the file's final location. Each entry
217-
// carries the approval-diff statistics the handler computed.
240+
// when present, is the file's final location, and a completed move
241+
// additionally journals its source deletion. Each entry carries the
242+
// approval-diff statistics the handler computed.
218243
// Await so the checkpoint (staging + commit + journal)
219244
// completes before queued messages are processed below;
220245
// otherwise a queued write's own checkpoint could interleave
221246
// with this commit.
222-
await checkpointSave(
223-
task,
224-
false,
225-
true,
226-
successfulChanges.map(({ change, diffStats }) => ({
227-
path: change.movePath ?? change.path,
228-
operation: change.type === "add" ? "create" : change.type,
229-
diffStats: diffStats
230-
? { additions: diffStats.added, deletions: diffStats.removed }
231-
: undefined,
232-
})),
233-
).catch(() => {})
247+
await checkpointSave(task, false, true, journalEntries()).catch(() => {})
234248
}
235249
}
236250

@@ -249,24 +263,27 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
249263
// the generic error handling: the writes are on disk and the journal
250264
// must document them. A flush that already ran (or was skipped by the
251265
// setting) is not attempted twice.
266+
let reportedError: unknown = error
252267
if (!writeMetadataFlushed && successfulChanges.length > 0) {
253-
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
254268
if (perWriteCheckpoints !== false) {
255-
await checkpointSave(
256-
task,
257-
false,
258-
true,
259-
successfulChanges.map(({ change, diffStats }) => ({
260-
path: change.movePath ?? change.path,
261-
operation: change.type === "add" ? "create" : change.type,
262-
diffStats: diffStats
263-
? { additions: diffStats.added, deletions: diffStats.removed }
264-
: undefined,
265-
})),
266-
).catch(() => {})
269+
let flushError: unknown
270+
await checkpointSave(task, false, true, journalEntries()).catch((flushFailure) => {
271+
flushError = flushFailure
272+
})
273+
if (flushError !== undefined) {
274+
// The completed write lacks rollback metadata: report the
275+
// persistence failure alongside the bookkeeping error without
276+
// replacing it as the reported failure.
277+
const flushMessage = flushError instanceof Error ? flushError.message : String(flushError)
278+
const baseMessage = error instanceof Error ? error.message : String(error)
279+
console.error("[ApplyPatchTool] catch-path checkpoint flush failed:", flushError)
280+
reportedError = new Error(`${baseMessage} (checkpoint flush also failed: ${flushMessage})`, {
281+
cause: error,
282+
})
283+
}
267284
}
268285
}
269-
await handleError("apply patch", error as Error)
286+
await handleError("apply patch", reportedError as Error)
270287
await task.diffViewProvider.reset()
271288
}
272289
}
@@ -584,6 +601,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
584601
// checkpointed and journaled as a completed move.
585602
try {
586603
await fs.unlink(absolutePath)
604+
change.moveSourceDeleted = true
587605
} catch (error) {
588606
moveSucceeded = false
589607
console.error(`Failed to delete original file after move: ${error}`)

‎src/core/tools/__tests__/applyPatchTool.execute.spec.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -543,10 +543,13 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
543543
"utf8",
544544
)
545545
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
546-
// B2: the journal entry for a successful move is keyed by the
547-
// destination path and carries the approval-diff statistics.
546+
// B2: the journal entries for a successful move are the destination
547+
// write (keyed by the final path, carrying the approval-diff
548+
// statistics) and the source deletion (a pure delete record that
549+
// lets a step rollback restore the removed file).
548550
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
549551
{ path: "src/moved.ts", operation: "update", diffStats: { additions: 1, deletions: 1 } },
552+
{ path: "src/test.ts", operation: "delete", diffStats: undefined },
550553
])
551554
})
552555

@@ -586,6 +589,47 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
586589
expect(mockHandleError).toHaveBeenCalledWith("apply patch", expect.anything())
587590
})
588591

592+
it("flushes the recorded write from the catch path when the settings read rejects", async () => {
593+
// The handler's settings lookup succeeds; the success-path flush's
594+
// lookup rejects. The flush flag must not have been set before that
595+
// rejection, so the catch path still persists the write already on
596+
// disk using the cached (undefined = default-on) setting.
597+
const getState = vi.fn().mockResolvedValueOnce({}).mockRejectedValueOnce(new Error("state boom"))
598+
mockTask.providerRef = { deref: vi.fn().mockReturnValue({ getState }) } as unknown as Task["providerRef"]
599+
600+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
601+
askApproval: mockAskApproval,
602+
handleError: mockHandleError,
603+
pushToolResult: mockPushToolResult,
604+
toolCallId: "test-tool-call-id",
605+
})
606+
607+
expect(mockedCheckpointSave).toHaveBeenCalledTimes(1)
608+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
609+
{ path: "src/test.ts", operation: "update", diffStats: { additions: 1, deletions: 1 } },
610+
])
611+
})
612+
613+
it("reports the catch-path flush failure alongside the bookkeeping error", async () => {
614+
vi.mocked(mockTask.fileContextTracker.trackFileContext).mockRejectedValueOnce(new Error("tracker boom"))
615+
mockedCheckpointSave.mockRejectedValueOnce(new Error("journal boom"))
616+
617+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
618+
askApproval: mockAskApproval,
619+
handleError: mockHandleError,
620+
pushToolResult: mockPushToolResult,
621+
toolCallId: "test-tool-call-id",
622+
})
623+
624+
// The user must see that the completed write lacks rollback
625+
// metadata: the reported error keeps the original message and
626+
// appends the persistence failure instead of replacing it.
627+
expect(mockHandleError).toHaveBeenCalledTimes(1)
628+
const reported = mockHandleError.mock.calls[0][1] as Error
629+
expect(reported.message).toContain("tracker boom")
630+
expect(reported.message).toContain("checkpoint flush also failed: journal boom")
631+
})
632+
589633
it("records one journal write per file change for a multi-file patch", async () => {
590634
// src/a.ts does not exist (add); src/b.ts does (update).
591635
mockedFileExistsAtPath.mockImplementation((filePath: string) =>
@@ -707,6 +751,8 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
707751
// The copy succeeded but the source still exists, so the move is
708752
// reported as a failed tool error - but the destination write was
709753
// made on disk and must still be covered by the checkpoint/journal.
754+
// The single-entry payload below also guards that the source
755+
// deletion is NOT journaled: the source was never removed.
710756
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
711757
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
712758
expect.objectContaining({ path: "src/new-location.ts", operation: "update" }),

‎src/core/tools/apply-patch/apply.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ export interface ApplyPatchFileChange {
2929
originalContent?: string
3030
/** New content (for add/update) */
3131
newContent?: string
32+
/**
33+
* Set by the tool handler when a move's source unlink succeeded: the
34+
* change journal then records the source deletion alongside the
35+
* destination write so a step rollback can restore the removed file.
36+
*/
37+
moveSourceDeleted?: boolean
3238
}
3339

3440
/**

0 commit comments

Comments
 (0)