Skip to content

Commit 802352d

Browse files
S4b (Zoo-Code-Org#1375): a committed publish is not undone by a cancellation
The guarded path already treats the commit as the point of no return - that is what CommittedWriteBufferConflictError names - but revertChanges() did not. The modify branch wrote originalContent back through an unguarded updatedDocument.save(), the one writer left using the call the comment above saveChanges says every other path avoids, and the create branch unlinked a file the session had just published with no version check on either. A cancellation that landed after the publish therefore replaced accepted content with the pre-edit bytes, or deleted the accepted file, and the caller was told neither. revertChanges() now keeps a committed publish: it clears the dirty flag from the published bytes only while the buffer still holds exactly what landed (text typed after the accept survives), tidies the session as before, and reports CommittedWriteBufferConflictError with a detail line naming the window. The same error now carries that detail at the two saveDirectly sites, the diff-view save and the move, so one name and one set of no-retry instructions covers every committed-write conflict instead of three windows describing it three ways. saveChanges() stopped discarding revertDocument's verdict. A buffer that stays dirty after close-and-reopen holds the bytes the guard published, so the save closes it, reopens from the published bytes and reports the conflict instead of proceeding into the save-over and returning ordinary success. saveDirectly already honoured the verdict; the asymmetry was the bug. open() creates the placeholder with wx: the absence above it is a classification, not a reservation, and a plain write truncated a file that won the race, after which the stat-matched observation described content open() never wrote. A lost race is reported rather than absorbed. apply_patch names the half-applied move: the destination committed, the source unlink never ran, so both paths appear in the report and the shared no-retry guidance stays attached, because the model's next instinct is to re-apply the patch. Gates: DiffViewProvider 168 passed (5 rows new), applyPatchTool.execute 33 passed (1 new), revertChanges callers (writeToFileTool, editFileTool, editTool, searchReplaceTool) 113 passed | 5 skipped, applyDiff guardedWrite + failureReporting + apply-patch + guardedWrite 116 passed, task abort races 9 passed. No it.runIf(win32) gate anywhere. eslint --prune-suppressions --max-warnings=0 exit 0 on all five touched files with src/eslint-suppressions.json identical to HEAD; prettier --check clean; tsc --noEmit -p . shows only the local junction diagnostic (activate/registerCommands.ts(88,102) TS2739). Controls, each failing for the reason its row describes: committed rule forced off -> the two new revertChanges rows report 'expected undefined to be an instance of CommittedWriteBufferConflictError' and the three teardown-ownership rows report 'expected fulfilled to be rejected'; rule forced on -> the pre-commit restore row plus 12 rows that depend on the restore path fail; verdict observed but ignored -> only the new saveChanges row fails; placeholder written without wx -> the four placeholder rows fail on the call shape, and dropping only the EEXIST translation fails the new race row on the message; move wrapper removed -> the new apply_patch row fails on the missing source path. Three pre-existing rows changed by design rather than to make them green: the three teardown-ownership rows now hold the cancellation's outcome (Promise.allSettled plus an instanceof check) because their scenario is a cancellation landing after the publish; their serialization, preview-restore and single-finalization assertions are untouched. Three open() rows assert the wx call shape for the same reason. Surfaced for the owner, not fixed here: Task.ts:3799 swallows revertChanges with .catch(console.error) on the disposal path while Task.ts:4168 propagates it on the abort path, so disposal will not see this signal. Whether disposal should swallow a 'committed, not undone' report is the disposal contract owner's call. Review rows 4507760734, 4507764622, 4507851689, 4507851696, 4507851698, 4507855182.
1 parent a150900 commit 802352d

5 files changed

Lines changed: 372 additions & 29 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1414
import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats"
1515
import { versionTokenOfStat } from "../../utils/versionToken"
1616
import { canonicalizeForApproval, GuardRejectedError, errorCode } from "./guardedWrite"
17+
import { CommittedWriteBufferConflictError } from "../../integrations/editor/committedWriteBufferConflictError"
1718
import { BaseTool, ToolCallbacks } from "./BaseTool"
1819
import type { ToolUse } from "../../shared/tools"
1920
import { ApplyPatchError, parsePatch, ParseError, processAllHunks } from "./apply-patch"
@@ -623,19 +624,35 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
623624
}
624625
}
625626
}
626-
await task.diffViewProvider.saveDirectly(
627-
change.movePath,
628-
newContent,
629-
false,
630-
diagnosticsEnabled,
631-
writeDelayMs,
632-
"create",
633-
sourceComplete,
634-
// Guaranteed by the refusal above: this destination is inside a workspace root,
635-
// so the guard's own containment check is what applies and no approval is claimed.
636-
false,
637-
undefined,
638-
)
627+
try {
628+
await task.diffViewProvider.saveDirectly(
629+
change.movePath,
630+
newContent,
631+
false,
632+
diagnosticsEnabled,
633+
writeDelayMs,
634+
"create",
635+
sourceComplete,
636+
// Guaranteed by the refusal above: this destination is inside a workspace root,
637+
// so the guard's own containment check is what applies and no approval is claimed.
638+
false,
639+
undefined,
640+
)
641+
} catch (error) {
642+
if (error instanceof CommittedWriteBufferConflictError) {
643+
// The destination committed and the source unlink below never runs, so the move is
644+
// half-applied: the content is at the new path and the source is still on disk. A model
645+
// that re-applies the patch duplicates the change at the destination while a third path
646+
// still holds the pre-move bytes, so both paths are named and the shared error keeps its
647+
// no-retry guidance.
648+
throw new CommittedWriteBufferConflictError(
649+
moveAbsolutePath,
650+
`apply_patch move: ${change.movePath} committed but ${change.path} was not removed, so the move ` +
651+
"is incomplete: read both paths before continuing.",
652+
)
653+
}
654+
throw error
655+
}
639656
} else {
640657
// Write to new path and delete old file
641658
const parentDir = path.dirname(moveAbsolutePath)

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { Task } from "../../task/Task"
1010
import { ObservationRegistry } from "../../task/observationRegistry"
1111
import { guardedWrite } from "../guardedWrite"
1212
import { ApplyPatchTool } from "../ApplyPatchTool"
13+
import { CommittedWriteBufferConflictError } from "../../../integrations/editor/committedWriteBufferConflictError"
1314

1415
// The vi.mock factory exposes the fs/promises functions under a `default`
1516
// property (matching the SUT's default import), which the static module type
@@ -737,6 +738,44 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => {
737738
expect(reg.get(destKey)?.complete).toBe(true)
738739
expect(mockHandleError).not.toHaveBeenCalled()
739740
})
741+
// Row 4507855182 (measured): the destination commits and the source unlink below never runs,
742+
// so a move that hits a buffer conflict is half-applied. The report has to name both paths
743+
// and keep the shared error's no-retry guidance, because the model's next instinct is to
744+
// re-apply the patch - which would duplicate the change at the destination.
745+
it("move: a committed destination with the source still on disk names both paths", async () => {
746+
const sourceKey = path.resolve("/workspace/project", "src/old.ts")
747+
const destKey = path.resolve("/workspace/project", "src/new.ts")
748+
const reg = mockTask.observationRegistry
749+
reg.observe(sourceKey, "7:4242:1234:1700000000123456789:1700000000789999999", true)
750+
mockSaveDirectly.mockRejectedValueOnce(
751+
new CommittedWriteBufferConflictError(
752+
destKey,
753+
"saveDirectly: the buffer held unsaved edits that differ from the content the guard published.",
754+
),
755+
)
756+
mockedFsPromises.default.unlink.mockClear()
757+
758+
await tool.execute({ patch: movePatch }, mockTask as Task, {
759+
askApproval: mockAskApproval,
760+
handleError: mockHandleError,
761+
pushToolResult: mockPushToolResult,
762+
toolCallId: "test-tool-call-id",
763+
})
764+
765+
expect(mockHandleError).toHaveBeenCalledWith(
766+
"apply patch",
767+
expect.objectContaining({ name: "CommittedWriteBufferConflictError" }),
768+
)
769+
const reported = (mockHandleError.mock.calls[0]?.[1] ?? new Error("")) as Error
770+
expect(reported.message).toContain("src/new.ts committed but")
771+
expect(reported.message).toContain("src/old.ts was not removed")
772+
expect(reported.message).toContain("do not retry")
773+
// The half-applied state is stated, not implied: the source was never unlinked, and the
774+
// destination's tool-recorded observation is withdrawn by the finally sweep, so it cannot
775+
// authorize a later edit of content the model never read.
776+
expect(mockedFsPromises.default.unlink).not.toHaveBeenCalled()
777+
expect(reg.get(destKey)).toBeUndefined()
778+
})
740779

741780
it("move: the destination cannot claim completeness when the source was never observed", async () => {
742781
// The hunk read records no observation when its stat fails, so the model has

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import type { FileObservation } from "../../core/task/observationRegistry"
2626
import { versionTokenOfStat } from "../../utils/versionToken"
2727
import { withFileLock } from "../../utils/fileLock"
2828
import { resolveLockKey } from "../../services/file-safety/safeWriteText"
29-
import { guardedWrite, GuardRejectedError, type GuardedWriteKind } from "../../core/tools/guardedWrite"
29+
import { errorCode, guardedWrite, GuardRejectedError, type GuardedWriteKind } from "../../core/tools/guardedWrite"
3030

3131
import { DecorationController } from "./DecorationController"
3232

@@ -128,6 +128,15 @@ export class DiffViewProvider {
128128
* never unlinked.
129129
*/
130130
private placeholderVersion: string | undefined = undefined
131+
/**
132+
* The publish this session committed: the target and the exact text that landed. A
133+
* cancellation that reaches revertChanges() after a commit must not resurrect
134+
* originalContent through an unguarded document.save(), and must not unlink a file the
135+
* save had already published: the commit is the point of no return, which is what
136+
* CommittedWriteBufferConflictError already names for the no-diff path. Cleared by
137+
* reset(), so a later session cannot inherit it.
138+
*/
139+
private committedPublish: { path: string; content: string } | undefined
131140
/**
132141
* The observation this path had BEFORE open() recorded the preview's own
133142
* version token: null when there was none, undefined when this provider never
@@ -237,7 +246,23 @@ export class DiffViewProvider {
237246

238247
// Make sure the file exists before we open it.
239248
if (!fileExists) {
240-
await fs.writeFile(absolutePath, "")
249+
// Created exclusively. Absence was classified above, and a plain write would silently
250+
// truncate whatever another process created in that window: the placeholder token
251+
// recorded below would then describe the other writer's file, and the guard would
252+
// accept a truncated baseline as the version this edit was built on. A lost race is
253+
// reported, not absorbed.
254+
try {
255+
await fs.writeFile(absolutePath, "", { flag: "wx" })
256+
} catch (error: unknown) {
257+
if (errorCode(error) === "EEXIST") {
258+
throw new Error(
259+
`Cannot open ${absolutePath} for editing: the file already exists. ` +
260+
"It was absent when this session classified it and another create won the race; " +
261+
"read the file before editing it.",
262+
)
263+
}
264+
throw error
265+
}
241266
// S4b follow-up (#44 / epic #1375): the empty placeholder is fully
242267
// known (empty), but verify it with the same S2 stat-matched contract
243268
// as the modify branch above: a stat-mismatched or non-empty read
@@ -637,6 +662,9 @@ export class DiffViewProvider {
637662
approvedCanonicalTarget,
638663
additionalRoots: this.additionalWorkspaceRoots(),
639664
})
665+
// From here the session holds a committed write. A cancellation arriving after this
666+
// point reverts the session, not the publish - see revertChanges.
667+
this.committedPublish = { path: absolutePath, content: editedContent }
640668
} catch (error) {
641669
// Autosave can publish the modified side of the diff before the user
642670
// accepts, so the bytes on disk may already be exactly what this save
@@ -778,7 +806,25 @@ export class DiffViewProvider {
778806
// buffer that moved on stays dirty: the close helpers skip dirty tabs and
779807
// the user's text survives in the editor.
780808
if (updatedDocument.isDirty && updatedDocument.getText() === editedContent) {
781-
await this.revertDocument(updatedDocument)
809+
const reconciled = await this.revertDocument(updatedDocument)
810+
if (!reconciled) {
811+
// The verdict is load-bearing here for the same reason it is in saveDirectly below:
812+
// a buffer that stays dirty holds the bytes the guard just published, and an ordinary
813+
// save - VS Code's own file service, or a later write - can put them back over a newer
814+
// file. Close and reopen from the published bytes; if that still leaves the buffer
815+
// dirty, report the committed-write conflict instead of proceeding into the save-over
816+
// and returning ordinary success, so the caller cannot treat a committed publish as an
817+
// edit it is free to re-apply.
818+
await this.closeFileTab(absolutePath)
819+
await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath))
820+
const reopened = this.findReconciliationDocument(absolutePath)
821+
if (reopened?.isDirty) {
822+
throw new CommittedWriteBufferConflictError(
823+
absolutePath,
824+
"saveChanges: the diff-view save committed its content but could not clear the open buffer.",
825+
)
826+
}
827+
}
782828
}
783829

784830
// A save belongs to one task, so its post-publish cleanup closes only this provider's
@@ -976,8 +1022,37 @@ export class DiffViewProvider {
9761022
this.disposeActiveEditorListener()
9771023
this.cancelDeferredScroll()
9781024

1025+
// A publish that already committed is not undone by a cancellation. The modify branch below
1026+
// would put originalContent back through an unguarded document.save() - the one writer left
1027+
// using the call the comment above saveChanges says every other path avoids - and the create
1028+
// branch would unlink a file the save had just published, which also discards whatever a
1029+
// third party built on it. Same name for the same state as the no-diff path uses: the commit
1030+
// is the point of no return, and the caller that asked for the undo is told so.
1031+
const committedAfterPublish =
1032+
this.committedPublish !== undefined && arePathsEqual(this.committedPublish.path, absolutePath)
1033+
const committedContent = this.committedPublish?.content
9791034
const ownedTeardown = await this.runTeardown(
9801035
async () => {
1036+
if (committedAfterPublish) {
1037+
// Clear the dirty flag from the published bytes rather than writing over them, and only
1038+
// while the buffer still holds exactly what landed: text typed after the accept survives.
1039+
if (updatedDocument.isDirty && updatedDocument.getText() === committedContent) {
1040+
await this.revertDocument(updatedDocument)
1041+
}
1042+
await this.closeOwnDiffView(absolutePath)
1043+
// The tab rules are the modify branch's, because the tab situation is the same: a
1044+
// committed file the user may or may not have touched.
1045+
const committedState = await this.taskRef.deref()?.providerRef.deref()?.getState()
1046+
await this.keepOrCloseEditedFile(
1047+
absolutePath,
1048+
false,
1049+
committedState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
1050+
committedState?.autoCloseZooOpenedFilesAfterUserEdited ??
1051+
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
1052+
committedState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
1053+
)
1054+
return
1055+
}
9811056
if (!fileExists) {
9821057
if (updatedDocument.isDirty) {
9831058
await updatedDocument.save()
@@ -1058,6 +1133,16 @@ export class DiffViewProvider {
10581133
// gets here first claims it; a second waiter joins the claim instead of resetting again.
10591134
await this.finalizeSession(() => this.reset())
10601135
}
1136+
if (committedAfterPublish) {
1137+
// Reported after the pass so the tab work, the preview restore and the reset all still
1138+
// happen: a cancellation that lands on a committed publish closes the session, it just
1139+
// cannot roll the content back. Both the owner and any caller that joined the pass see the
1140+
// same signal, because both were waiting on this outcome.
1141+
throw new CommittedWriteBufferConflictError(
1142+
absolutePath,
1143+
"revertChanges: a cancellation arrived after the guarded publish had committed.",
1144+
)
1145+
}
10611146
}
10621147

10631148
/**
@@ -1788,6 +1873,7 @@ export class DiffViewProvider {
17881873
this.snapshotPreviewTabs = []
17891874
this.placeholderVersion = undefined
17901875
this.preOpenObservation = undefined
1876+
this.committedPublish = undefined
17911877
}
17921878

17931879
/**
@@ -1848,6 +1934,9 @@ export class DiffViewProvider {
18481934
approvedCanonicalTarget,
18491935
additionalRoots: this.additionalWorkspaceRoots(),
18501936
})
1937+
// The publish committed: a later revertChanges on this session reports the committed-write
1938+
// conflict instead of rolling the content back.
1939+
this.committedPublish = { path: absolutePath, content }
18511940

18521941
// The guarded publish wrote the bytes to disk directly. If the target
18531942
// document is already open, its buffer still holds the pre-publish text:
@@ -1867,7 +1956,10 @@ export class DiffViewProvider {
18671956
// The publish already committed: report the committed-write buffer conflict.
18681957
// A generic error would tell the model to retry a non-idempotent edit
18691958
// (SearchReplaceTool/EditTool would re-read and duplicate the change).
1870-
throw new CommittedWriteBufferConflictError(absolutePath)
1959+
throw new CommittedWriteBufferConflictError(
1960+
absolutePath,
1961+
"saveDirectly: the buffer held unsaved edits that differ from the content the guard published.",
1962+
)
18711963
}
18721964
const reconciled = await this.revertDocument(openTarget).catch(() => false)
18731965
if (!reconciled) {
@@ -1885,10 +1977,14 @@ export class DiffViewProvider {
18851977
await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath))
18861978
const reopened = this.findReconciliationDocument(absolutePath)
18871979
if (reopened?.isDirty) {
1888-
throw new Error(
1980+
// Same error the branch above uses: the publish committed, so what the caller must not
1981+
// do is re-apply the edit. The stale-bytes hazard is named in the detail line, and the
1982+
// no-retry guidance comes from the shared error.
1983+
throw new CommittedWriteBufferConflictError(
1984+
absolutePath,
18891985
`saveDirectly: the open document at ${absolutePath} is still dirty after the guarded publish -- ` +
18901986
"reverting and reopening it did not reconcile the buffer, so its stale bytes could overwrite " +
1891-
"the published content on the next save; the write is reported as failed.",
1987+
"the published content on the next save.",
18921988
)
18931989
}
18941990
}

0 commit comments

Comments
 (0)