Skip to content

Commit 6669937

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 78cb053 commit 6669937

3 files changed

Lines changed: 124 additions & 22 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 54 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -81,26 +81,42 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
8181
// messages when a write succeeded but the post-patch checkpoint failed.
8282
const successfulChanges: ApplyPatchFileChange[] = []
8383
const bufferedResults: string[] = []
84-
// Set once the success-path checkpoint/journal flush has been attempted
85-
// so the catch below does not persist the same writes twice.
84+
// Set once the success-path flush actually proceeds to checkpointSave, so
85+
// the catch below does not persist the same writes twice while a
86+
// settings-read rejection before that decision leaves the catch flush
87+
// armed with default-on semantics.
8688
let writeMetadataFlushed = false
89+
// Cached perWriteCheckpoints lookup shared by the success-path flush and
90+
// the catch flush: the catch must not call getState() again, because a
91+
// rejecting settings read must not skip persisting writes already on disk.
92+
let perWriteCheckpoints: boolean | undefined
8793
// Journal payload builder shared by the success-path flush and the
8894
// catch-path flush for writes recorded before an unexpected throw.
8995
const journalEntries = () =>
90-
successfulChanges.map((change) => ({
91-
path: change.movePath ?? change.path,
92-
operation: change.type === "add" ? ("create" as const) : change.type,
93-
...(change.diffStats
94-
? {
95-
diffStats: {
96-
additions: change.diffStats.added,
97-
deletions: change.diffStats.removed,
98-
},
99-
}
100-
: {}),
101-
...(change.diff ? { diff: change.diff } : {}),
102-
...(change.autoApproved ? { autoApproved: true } : {}),
103-
}))
96+
successfulChanges.flatMap((change) => {
97+
const written = {
98+
path: change.movePath ?? change.path,
99+
operation: change.type === "add" ? ("create" as const) : change.type,
100+
...(change.diffStats
101+
? {
102+
diffStats: {
103+
additions: change.diffStats.added,
104+
deletions: change.diffStats.removed,
105+
},
106+
}
107+
: {}),
108+
...(change.diff ? { diff: change.diff } : {}),
109+
...(change.autoApproved ? { autoApproved: true } : {}),
110+
}
111+
// A completed move also DELETES its source: journal that deletion
112+
// after the destination write so a step rollback restores the
113+
// removed file from its pre-step state. A move whose source unlink
114+
// failed left the source on disk and gets no deletion entry.
115+
if (change.movePath && change.moveSourceDeleted) {
116+
return [written, { path: change.path, operation: "delete" as const }]
117+
}
118+
return [written]
119+
})
104120

105121
try {
106122
// Validate required parameters
@@ -242,14 +258,15 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
242258
// pushToolResult. A fully failed patch (nothing written) leaves no
243259
// checkpoint behind.
244260
if (patchSucceeded || successfulChanges.length > 0) {
245-
writeMetadataFlushed = true
246-
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
261+
perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
247262
if (perWriteCheckpoints !== false) {
263+
writeMetadataFlushed = true
248264
// B2: one journal entry per file that was actually written by
249265
// the patch (the simplest correct design for multi-file patches),
250266
// all referencing the single checkpoint above. A no-op update
251267
// contributes no entry because nothing was written. `movePath`,
252-
// when present, is the file's final location. B3a: the per-file
268+
// when present, is the file's final location, and a completed move
269+
// additionally journals its source deletion. B3a: the per-file
253270
// approval diff/stats and auto-approval state, retained by the
254271
// handlers, feed the per-step change card.
255272
// Awaited: a later write must not interleave with this patch's
@@ -275,13 +292,27 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
275292
// error handling: the writes are on disk and the journal must document
276293
// them. A flush already attempted above is not repeated, so a journal
277294
// failure keeps the documented drop-buffered-results behavior.
295+
let reportedError: unknown = error
278296
if (!writeMetadataFlushed && successfulChanges.length > 0) {
279-
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
280297
if (perWriteCheckpoints !== false) {
281-
await checkpointSave(task, false, true, journalEntries()).catch(() => {})
298+
let flushError: unknown
299+
await checkpointSave(task, false, true, journalEntries()).catch((flushFailure) => {
300+
flushError = flushFailure
301+
})
302+
if (flushError !== undefined) {
303+
// The completed write lacks rollback metadata: report the
304+
// persistence failure alongside the bookkeeping error without
305+
// replacing it as the reported failure.
306+
const flushMessage = flushError instanceof Error ? flushError.message : String(flushError)
307+
const baseMessage = error instanceof Error ? error.message : String(error)
308+
console.error("[ApplyPatchTool] catch-path checkpoint flush failed:", flushError)
309+
reportedError = new Error(`${baseMessage} (checkpoint flush also failed: ${flushMessage})`, {
310+
cause: error,
311+
})
312+
}
282313
}
283314
}
284-
await handleError("apply patch", error as Error)
315+
await handleError("apply patch", reportedError as Error)
285316
await task.diffViewProvider.reset()
286317
} finally {
287318
// B2: deferred from the per-file handlers - a queued write must not
@@ -646,6 +677,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
646677
// checkpointed and journaled as a completed move.
647678
try {
648679
await fs.unlink(absolutePath)
680+
change.moveSourceDeleted = true
649681
} catch (error) {
650682
moveSucceeded = false
651683
console.error(`Failed to delete original file after move: ${error}`)

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

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,24 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
578578
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
579579
})
580580

581+
it("journals the source deletion alongside the destination write for a completed move", async () => {
582+
await tool.execute({ patch: movePatch }, mockTask as Task, {
583+
askApproval: mockAskApproval,
584+
handleError: mockHandleError,
585+
pushToolResult: mockPushToolResult,
586+
toolCallId: "test-tool-call-id",
587+
})
588+
589+
// A completed move touches two journal-relevant paths: the
590+
// destination write (carrying the content diff) and the source
591+
// deletion (a pure delete record). Step rollback restores the
592+
// removed source from these entries.
593+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
594+
expect.objectContaining({ path: "src/moved.ts", operation: "update" }),
595+
expect.objectContaining({ path: "src/test.ts", operation: "delete" }),
596+
])
597+
})
598+
581599
it("awaits the patch checkpoint before execute settles", async () => {
582600
type SaveResult = Awaited<ReturnType<typeof checkpointSave>>
583601
let resolveSave: (value: SaveResult | PromiseLike<SaveResult>) => void = () => {}
@@ -642,6 +660,50 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
642660
expect(mockTask.processQueuedMessages).toHaveBeenCalled()
643661
})
644662

663+
it("flushes the recorded write from the catch path when the settings read rejects", async () => {
664+
// The handler's settings lookup succeeds; the success-path flush's
665+
// lookup rejects. The flush flag must not have been set before that
666+
// rejection, so the catch path still persists the write already on
667+
// disk using the cached (undefined = default-on) setting.
668+
const getState = vi.fn().mockResolvedValueOnce({}).mockRejectedValueOnce(new Error("state boom"))
669+
mockTask.providerRef = { deref: vi.fn().mockReturnValue({ getState }) } as unknown as Task["providerRef"]
670+
671+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
672+
askApproval: mockAskApproval,
673+
handleError: mockHandleError,
674+
pushToolResult: mockPushToolResult,
675+
toolCallId: "test-tool-call-id",
676+
})
677+
678+
expect(mockedCheckpointSave).toHaveBeenCalledTimes(1)
679+
expect(mockedCheckpointSave).toHaveBeenCalledWith(
680+
mockTask as Task,
681+
false,
682+
true,
683+
expect.arrayContaining([expect.objectContaining({ path: "src/test.ts", operation: "update" })]),
684+
)
685+
})
686+
687+
it("reports the catch-path flush failure alongside the bookkeeping error", async () => {
688+
vi.mocked(mockTask.fileContextTracker.trackFileContext).mockRejectedValueOnce(new Error("tracker boom"))
689+
mockedCheckpointSave.mockRejectedValueOnce(new Error("journal boom"))
690+
691+
await tool.execute({ patch: updatePatch }, mockTask as Task, {
692+
askApproval: mockAskApproval,
693+
handleError: mockHandleError,
694+
pushToolResult: mockPushToolResult,
695+
toolCallId: "test-tool-call-id",
696+
})
697+
698+
// The user must see that the completed write lacks rollback
699+
// metadata: the reported error keeps the original message and
700+
// appends the persistence failure instead of replacing it.
701+
expect(mockHandleError).toHaveBeenCalledTimes(1)
702+
const reported = mockHandleError.mock.calls[0][1] as Error
703+
expect(reported.message).toContain("tracker boom")
704+
expect(reported.message).toContain("checkpoint flush also failed: journal boom")
705+
})
706+
645707
it("records one journal write per file change for a multi-file patch", async () => {
646708
// src/a.ts does not exist (add); src/b.ts does (update).
647709
mockedFileExistsAtPath.mockImplementation((filePath: string) =>
@@ -824,6 +886,8 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
824886
// The copy succeeded but the source still exists, so the move is
825887
// reported as a failed tool error - but the destination write was
826888
// made on disk and must still be covered by the checkpoint/journal.
889+
// The single-entry payload below also guards that the source
890+
// deletion is NOT journaled: the source was never removed.
827891
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
828892
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
829893
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
@@ -38,6 +38,12 @@ export interface ApplyPatchFileChange {
3838
diffStats?: { added: number; removed: number }
3939
/** B3a: whether this file's approval was auto-approved. */
4040
autoApproved?: boolean
41+
/**
42+
* Set by the tool handler when a move's source unlink succeeded: the
43+
* change journal then records the source deletion alongside the
44+
* destination write so a step rollback can restore the removed file.
45+
*/
46+
moveSourceDeleted?: boolean
4147
}
4248

4349
/**

0 commit comments

Comments
 (0)