Skip to content

Commit 2e00da1

Browse files
committed
fix(diff-view,tools): recognise the session's own Auto Save, gate re-observation on basis authority
Round 6 of the Zoo-Code-Org#1916 review (two Majors on caabad3), landed as one head. - revertChanges(): a rejection never publishes, so the rollback bound to openToken while Auto Save of the diff's modified document - which is the real file URI - had already put this session's proposed edit on disk and moved the version. The rollback now recognises its own bytes the way adoptAlreadyPublishedContent() does: a stat-bracketed read under the same lock, compared against the encoded text of the buffer exactly as the publish path would write it, encoding and line endings included. When they match, that version is the session's own write and the restore - or, on the create path, the unlink - binds to it instead of reporting a conflict no peer caused. Bytes that match neither the buffer nor what the session left are a peer write, and RollbackConflictError still stands. - saveDirectly(): the basis re-observation is gated on the caller's authority over the basis (reobserveBasis) instead of on writeKind. writeKind says how the content is shaped, not whether the writer saw the bytes it is building on, which is why gating on it gave two reviews opposite answers about the same line. EditTool, SearchReplaceTool, EditFileTool and ApplyPatchTool pass true: they compose their content from bytes they just read. WriteToFileTool passes false: its bytes are the model's, so a stale, partial or absent model observation reaches guardedWrite unchanged, as it already does on the diff-view path. ApplyDiffTool passes false: it must keep the observation its own read earned, so a stale token stays stale and a partial read stays partial.
1 parent caabad3 commit 2e00da1

10 files changed

Lines changed: 385 additions & 30 deletions

File tree

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,10 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
211211
diagnosticsEnabled,
212212
writeDelayMs,
213213
"edit",
214+
// ApplyDiffTool composes the patch from the bytes its own read produced, and the
215+
// guard must judge that observation: a stale token stays stale, a partial read stays
216+
// partial. This caller does not re-observe the basis.
217+
false,
214218
)
215219
} else {
216220
// Original behavior with diff view

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
222222
diagnosticsEnabled,
223223
writeDelayMs,
224224
"create",
225+
// The patch was applied to the bytes this tool just read, so it may re-observe what
226+
// that read proves about the current version.
227+
true,
225228
)
226229
} else {
227230
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
@@ -425,6 +428,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
425428
diagnosticsEnabled,
426429
writeDelayMs,
427430
"create",
431+
// The patch was applied to the bytes this tool just read, so it may re-observe what
432+
// that read proves about the current version.
433+
true,
428434
)
429435
} else {
430436
// Write to new path and delete old file
@@ -453,6 +459,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
453459
diagnosticsEnabled,
454460
writeDelayMs,
455461
"update",
462+
// The patch was applied to the bytes this tool just read, so it may re-observe what
463+
// that read proves about the current version.
464+
true,
456465
)
457466
} else {
458467
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)

‎src/core/tools/EditFileTool.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,9 @@ export class EditFileTool extends BaseTool<"edit_file"> {
446446
// The kind follows what this tool did to the target: a new file is
447447
// created, an existing one is replaced in full from the content it read.
448448
isNewFile ? "create" : "update",
449+
// The whole-file replacement is composed from the file this tool just read, so it may
450+
// re-observe what that read proves about the current version.
451+
true,
449452
)
450453
} else {
451454
// Call saveChanges to update the DiffViewProvider properties

‎src/core/tools/EditTool.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,9 @@ export class EditTool extends BaseTool<"edit"> {
221221
diagnosticsEnabled,
222222
writeDelayMs,
223223
"update",
224+
// The edit was applied to the bytes this tool just read, so it may re-observe what
225+
// that read proves about the current version.
226+
true,
224227
)
225228
} else {
226229
// Call saveChanges to update the DiffViewProvider properties

‎src/core/tools/SearchReplaceTool.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,9 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> {
217217
diagnosticsEnabled,
218218
writeDelayMs,
219219
"update",
220+
// The replacement was built from the bytes this tool just read, so it may re-observe
221+
// what that read proves about the current version.
222+
true,
220223
)
221224
} else {
222225
// Call saveChanges to update the DiffViewProvider properties

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
141141
diagnosticsEnabled,
142142
writeDelayMs,
143143
fileExists ? "update" : "create",
144+
// The published bytes come from the model, not from the read this tool did before
145+
// approval, so this caller has no authority over the basis: a stale, partial, or absent
146+
// model observation must reach the guard unchanged, as it does on the diff-view path.
147+
false,
144148
)
145149
} else {
146150
if (!task.diffViewProvider.isEditing) {

‎src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,9 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => {
167167
true,
168168
1000,
169169
"edit",
170+
// No basis authority: ApplyDiffTool keeps the observation its own read recorded, so the
171+
// guard still judges the patch against the version that read saw.,
172+
false,
170173
)
171174
expect(mockPushToolResult).toHaveBeenCalledWith("Saved file")
172175
expect(mockTask.didEditFile).toBe(true)
@@ -329,6 +332,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => {
329332
true,
330333
1000,
331334
"edit",
335+
false,
332336
)
333337
expect(mockPushToolResult).toHaveBeenCalledWith("Saved file")
334338
expect(stat).toHaveBeenCalledTimes(2)
@@ -367,6 +371,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => {
367371
true,
368372
1000,
369373
"edit",
374+
false,
370375
)
371376
expect(mockPushToolResult).toHaveBeenCalledWith("Saved file")
372377
expect(stat).toHaveBeenCalledTimes(2)

‎src/core/tools/__tests__/editTool.spec.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ describe("editTool", () => {
173173
const calls = (mockTask.diffViewProvider.saveDirectly as unknown as ReturnType<typeof vi.fn>).mock.calls
174174
expect(calls).toHaveLength(1)
175175
expect(calls[0]?.[5]).toBe("update")
176+
// Index 6 is the basis-authority flag: EditTool built this edit from the bytes it just read,
177+
// so it is the kind of caller that may re-observe what that read proves.
178+
expect(calls[0]?.[6]).toBe(true)
176179
expect(mockTask.diffViewProvider.saveChanges).not.toHaveBeenCalled()
177180
})
178181

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 98 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,51 @@ export class DiffViewProvider {
744744
this.lastWrittenToken = versionTokenOfStat(after)
745745
return true
746746
}
747+
/**
748+
* The version this session's own Auto Save left on disk, when the bytes prove it.
749+
*
750+
* A rejection never publishes, so the rollback has no lastWrittenToken to bind to and
751+
* falls back on openToken. Auto Save (afterDelay or onFocusChange) writes the diff's
752+
* modified document - the real file URI - so a rejection can find the proposed edit on
753+
* disk under a token this session never recorded. Those bytes came from this session,
754+
* which makes them a session write rather than a peer mutation: the rollback has to be
755+
* able to recognise them. This is the principle adoptAlreadyPublishedContent() already
756+
* encodes for the publish path, with the same stat-bracketed read.
757+
*
758+
* The comparison is against the encoded text of the buffer exactly as the publish path
759+
* would write it - encoding and line endings included - so a CRLF target is not matched
760+
* against LF text. A disk state that matches neither originalContent nor the buffer is a
761+
* genuine peer write: this answers undefined and the caller keeps reporting
762+
* RollbackConflictError. The bracketed read declines to answer when the version moved
763+
* across the read, because such a token is already unsafe to bind.
764+
*/
765+
private async sessionAutoSavedToken(
766+
absolutePath: string,
767+
bufferText: string,
768+
encoding: string,
769+
): Promise<string | undefined> {
770+
const before = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
771+
if (before === undefined) {
772+
return undefined
773+
}
774+
const disk = await fs.readFile(absolutePath).catch(() => undefined)
775+
if (disk === undefined) {
776+
return undefined
777+
}
778+
const after = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
779+
if (after === undefined || versionTokenOfStat(before) !== versionTokenOfStat(after)) {
780+
return undefined
781+
}
782+
const encodedBuffer = vscode.workspace.encode
783+
? await vscode.workspace.encode(bufferText, { encoding })
784+
: undefined
785+
const bufferBytes = encodedBuffer ?? new Uint8Array(Buffer.from(bufferText, "utf8"))
786+
if (Buffer.compare(Buffer.from(disk), Buffer.from(bufferBytes)) !== 0) {
787+
return undefined
788+
}
789+
return versionTokenOfStat(after)
790+
}
791+
747792
/**
748793
* Whether a byte-for-byte match on disk may be adopted as this save's publish.
749794
*
@@ -1302,7 +1347,23 @@ export class DiffViewProvider {
13021347
// what this session recorded.
13031348
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
13041349
const diskToken = diskStat === undefined ? undefined : versionTokenOfStat(diskStat)
1305-
const oursToken = this.lastWrittenToken ?? this.placeholderVersion
1350+
let oursToken = this.lastWrittenToken ?? this.placeholderVersion
1351+
// The same recognition as the modify rollback: Auto Save writes the create preview's
1352+
// buffer to the real file URI, which moves the token off placeholderVersion and leaves the
1353+
// rejected edit standing in the file this session created. When the file holds exactly the
1354+
// encoded text of that buffer, the version is this session's own write and the unlink may
1355+
// bind to it. Bytes that match neither the placeholder nor the buffer are a peer's, and the
1356+
// conflict stays.
1357+
if (diskToken !== undefined && oursToken !== diskToken) {
1358+
const autoSavedToken = await this.sessionAutoSavedToken(
1359+
absolutePath,
1360+
updatedDocument.getText(),
1361+
updatedDocument.encoding,
1362+
)
1363+
if (autoSavedToken !== undefined && autoSavedToken === diskToken) {
1364+
oursToken = autoSavedToken
1365+
}
1366+
}
13061367
if (oursToken === undefined || diskToken === undefined || diskToken !== oursToken) {
13071368
// Ownership is unknown - this session recorded no token (an
13081369
// identity-only or failed stat-bracketed create), or the disk
@@ -1375,12 +1436,29 @@ export class DiffViewProvider {
13751436
? await vscode.workspace.encode(originalText, { encoding: updatedDocument.encoding })
13761437
: undefined
13771438
const originalBytes = encodedOriginal ?? new Uint8Array(Buffer.from(originalText, "utf8"))
1378-
const expectedToken = this.lastWrittenToken
1439+
let expectedToken = this.lastWrittenToken
13791440
// The CAS needs both sides of the comparison: the version this session
13801441
// left and the version the disk reports. The probe below only decides
13811442
// eligibility - replaceIfVersion re-reads the version under the lock,
13821443
// and that read is the authoritative check the publish is bound to.
13831444
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
1445+
// This session's own Auto Save is not a peer mutation. A rejection never publishes, so
1446+
// lastWrittenToken is undefined here, while Auto Save of the diff's modified document -
1447+
// which is the real file URI - has moved the disk version off openToken and left this
1448+
// session's proposed bytes on disk. When the target holds exactly the encoded text of the
1449+
// buffer being rolled back, that version is this session's own write and the restore may
1450+
// bind to it instead of reporting a conflict no peer caused. Bytes that match neither the
1451+
// buffer nor originalContent are a genuine peer write, and the conflict stays.
1452+
if (expectedToken === undefined && diskStat !== undefined) {
1453+
const autoSavedToken = await this.sessionAutoSavedToken(
1454+
absolutePath,
1455+
updatedDocument.getText(),
1456+
updatedDocument.encoding,
1457+
)
1458+
if (autoSavedToken !== undefined) {
1459+
expectedToken = autoSavedToken
1460+
}
1461+
}
13841462
if (expectedToken === undefined || diskStat === undefined) {
13851463
// One side of the comparison has no version: the session never
13861464
// recorded what it left (a publish whose token read failed), or the
@@ -2238,6 +2316,16 @@ export class DiffViewProvider {
22382316
writeKind: GuardedWriteKind = "create",
22392317
// Completeness the caller earned elsewhere; a move carries the source's
22402318
// view through the publish instead of claiming completeness for lines it never read.
2319+
// Whether this caller may re-observe the target's basis before the guard runs. The axis
2320+
// is the caller's authority over the basis, not writeKind: writeKind says how the content
2321+
// is shaped, not whether the writer saw the bytes it builds on. A caller that composes its
2322+
// content from bytes it just read (EditTool, SearchReplaceTool, EditFileTool,
2323+
// ApplyPatchTool) may record what that read proves about the current version. A caller
2324+
// whose bytes come from somewhere else may not: re-observing for WriteToFileTool (whose
2325+
// content is the model's) or ApplyDiffTool (which must keep the observation its own read
2326+
// earned) would upgrade a stale or partial model observation, or authorize a target the
2327+
// model never read, before the guard ever sees it.
2328+
reobserveBasis: boolean = false,
22412329
completeOverride?: boolean,
22422330
): Promise<{
22432331
newProblemsMessage: string | undefined
@@ -2260,26 +2348,14 @@ export class DiffViewProvider {
22602348
// unreachable and the write cannot be guarded.
22612349
throw new Error("Cannot guard the write: the owning task is no longer available")
22622350
}
2263-
await createDirectoriesForFile(absolutePath)
2264-
// The guard decides from the observation registry, and a direct save has no preview
2265-
// to authorize it: the consumer built `content` from bytes it read outside this class
2266-
// and hands them over as `originalContent`. Bracket that read here - stat, compare the
2267-
// target's current bytes against the basis bytes, stat again - and record what it
2268-
// authorized before publishing. Both sides agreeing on one token AND the target still
2269-
// holding exactly the basis bytes means this publish replaces content the consumer saw in
2270-
// full, which is what a complete observation claims. Anything else - the file moved
2271-
// during the bracket, or the target no longer matches what the content was built from -
2272-
// means the publish rests on a slice of something else, so the observation stays partial
2273-
// and the completeness gate refuses a full-file replacement until the model re-reads.
2274-
// "create" is left alone: an absent target needs no authorization, and a target that is
2275-
// already there must be refused as unobserved rather than quietly overwritten.
2276-
// Only a full-file replacement may have its basis re-observed. An "edit" save is a targeted patch
2277-
// whose authorization comes from the observation the model's own read recorded: ApplyDiffTool
2278-
// deliberately keeps a stale entry so the guard refuses a save against the newer disk version, and
2279-
// keeps complete: false so that a partial read is not silently promoted. Re-bracketing that entry
2280-
// here would refresh the stale token to the current one and upgrade the partial claim before
2281-
// guardedWrite() ever ran - the very blindness the edit kind exists to avoid.
2282-
if (writeKind === "update" && this.originalContent !== undefined) {
2351+
// Re-observe the target only for a caller that built the published content from the
2352+
// bytes it just read. writeKind is not the axis: it describes the shape of the content,
2353+
// not whether the writer saw the basis it is building on, and gating on it made the
2354+
// stale-read and partial-read guarantees depend on which kind string a caller happened
2355+
// to pass. With the flag off the registry keeps whatever the model's own read recorded,
2356+
// so guardedWrite() judges a stale, partial, or absent observation exactly as the
2357+
// diff-view path would.
2358+
if (reobserveBasis && this.originalContent !== undefined) {
22832359
await this.observeDirectSaveBasis(task, absolutePath)
22842360
}
22852361
const landedToken = await guardedWrite(task, relPath, content, writeKind, completeOverride)

0 commit comments

Comments
 (0)