@@ -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