@@ -11,6 +11,8 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1111import { fileExistsAtPath } from "../../utils/fs"
1212import { EXPERIMENT_IDS , experiments } from "../../shared/experiments"
1313import { sanitizeUnifiedDiff , computeDiffStats } from "../diff/stats"
14+ import { versionTokenOfStat } from "../../utils/versionToken"
15+ import { GuardRejectedError , errorCode } from "./guardedWrite"
1416import { BaseTool , ToolCallbacks } from "./BaseTool"
1517import type { ToolUse } from "../../shared/tools"
1618import { parsePatch , ParseError , processAllHunks } from "./apply-patch"
@@ -85,10 +87,30 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
8587 return
8688 }
8789
88- // Process each hunk
90+ // Process each hunk. The read doubles as the S2 observation for the
91+ // guarded publish (ReadFileTool contract: stat before and after the
92+ // read, observe only when the on-disk version is unchanged between the
93+ // two stats). Without it, the in-place modify publish is an unobserved
94+ // write and the composed chat-diff default rejects it ("File already
95+ // exists ... and was not read before this write") even though this tool
96+ // just read the exact content the patch was applied to.
8997 const readFile = async ( filePath : string ) : Promise < string > => {
9098 const absolutePath = path . resolve ( task . cwd , filePath )
91- return await fs . readFile ( absolutePath , "utf8" )
99+ const preReadStats = await fs . stat ( absolutePath , { bigint : true } ) . catch ( ( ) => undefined )
100+ const content : string = await fs . readFile ( absolutePath , "utf8" )
101+ const postReadStats = await fs . stat ( absolutePath , { bigint : true } ) . catch ( ( ) => undefined )
102+ if ( preReadStats && postReadStats ) {
103+ const preReadToken = versionTokenOfStat ( preReadStats )
104+ if ( preReadToken === versionTokenOfStat ( postReadStats ) ) {
105+ // The tool's own hunk read, not a model read: keep the completeness the
106+ // model earned, and only on the version it was earned on. A file the model
107+ // never read, or a version that moved since, stays partial.
108+ const prior = task . observationRegistry . get ( absolutePath )
109+ const complete = prior ?. complete === true && prior . version === preReadToken
110+ task . observationRegistry . observe ( absolutePath , preReadToken , complete )
111+ }
112+ }
113+ return content
92114 }
93115
94116 let changes : ApplyPatchFileChange [ ]
@@ -214,9 +236,20 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
214236
215237 // Save the changes
216238 if ( isPreventFocusDisruptionEnabled ) {
217- await task . diffViewProvider . saveDirectly ( relPath , newContent , true , diagnosticsEnabled , writeDelayMs )
239+ // Guarded publish: the patch supplies the complete new content, so create-guard
240+ // semantics apply (an unobserved existing target is rejected, not overwritten).
241+ await task . diffViewProvider . saveDirectly (
242+ relPath ,
243+ newContent ,
244+ true ,
245+ diagnosticsEnabled ,
246+ writeDelayMs ,
247+ "create" ,
248+ )
218249 } else {
219- await task . diffViewProvider . saveChanges ( diagnosticsEnabled , writeDelayMs )
250+ // The add path publishes a whole new file, so create-guard semantics
251+ // apply here as well.
252+ await task . diffViewProvider . saveChanges ( diagnosticsEnabled , writeDelayMs , "create" )
220253 }
221254
222255 // Track file edit operation
@@ -408,12 +441,59 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
408441
409442 // Save new content to the new path
410443 if ( isPreventFocusDisruptionEnabled ) {
444+ // The destination content is the source file plus one targeted hunk, so it can
445+ // only be as complete as the view the model had of the source. Carry that
446+ // completeness to the destination BEFORE the guarded publish: the guard decides
447+ // completeness at publish time, so a partial view must already be recorded when
448+ // the per-path chain runs. Downgrading only after saveDirectly leaves a window
449+ // in which a concurrent writer sees the destination as complete for content the
450+ // model never fully read.
451+ const sourceObs = task . observationRegistry . get ( absolutePath )
452+ const sourceComplete = sourceObs !== undefined && sourceObs . complete === true
453+ if ( ! sourceComplete ) {
454+ // Only carry completeness the model already had for the destination. An
455+ // unobserved destination stays unobserved so the guard's "read before a
456+ // full-file write" rule still applies; recording a partial observation here
457+ // would hand the model authority to edit a file it never read.
458+ const destObs = task . observationRegistry . get ( moveAbsolutePath )
459+ if ( destObs !== undefined ) {
460+ let destAbsent = false
461+ try {
462+ await fs . access ( moveAbsolutePath )
463+ } catch ( error : unknown ) {
464+ // Only an access error that means "not there" is an absence verdict. An
465+ // ELOOP or EACCES is a real I/O failure: reading it as absent would mark
466+ // the destination partial and let the publish run against a path the tool
467+ // never actually observed.
468+ if ( errorCode ( error ) !== "ENOENT" ) throw error
469+ destAbsent = true
470+ }
471+ if ( ! destAbsent ) {
472+ // Replacing an existing destination with content built from a partial
473+ // source view must be re-authorized by reading the source in full. Reject
474+ // before any state changes and name the source: a remediation that names
475+ // only the destination sends the model to re-read the wrong file, and a
476+ // downgrade that survives a rejected publish loses a full destination read.
477+ throw new GuardRejectedError (
478+ `Cannot move a partially read file onto ${ change . movePath } : re-read the whole source (${ change . path } ) first, then retry.` ,
479+ change . movePath ,
480+ )
481+ }
482+ // The destination was read and then deleted: the create guard permits the
483+ // publish, and the content is still only as complete as the view the model
484+ // had of the source, so carry the source's completeness instead of the
485+ // destination's stale one.
486+ task . observationRegistry . observe ( moveAbsolutePath , destObs . version , false )
487+ }
488+ }
411489 await task . diffViewProvider . saveDirectly (
412490 change . movePath ,
413491 newContent ,
414492 false ,
415493 diagnosticsEnabled ,
416494 writeDelayMs ,
495+ "create" ,
496+ sourceComplete ,
417497 )
418498 } else {
419499 // Write to new path and delete old file
@@ -433,9 +513,22 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
433513 } else {
434514 // Save changes to the same file
435515 if ( isPreventFocusDisruptionEnabled ) {
436- await task . diffViewProvider . saveDirectly ( relPath , newContent , false , diagnosticsEnabled , writeDelayMs )
516+ // Guarded publish: an update hunk is a targeted change, so it is guarded
517+ // as an edit -- a partial observation authorizes it and stays partial. A
518+ // stale observed version is still rejected with the re-read hint.
519+ await task . diffViewProvider . saveDirectly (
520+ relPath ,
521+ newContent ,
522+ false ,
523+ diagnosticsEnabled ,
524+ writeDelayMs ,
525+ "edit" ,
526+ )
437527 } else {
438- await task . diffViewProvider . saveChanges ( diagnosticsEnabled , writeDelayMs )
528+ // The diff-view save is the same targeted hunk as the guarded save above:
529+ // it must select the same edit guard, otherwise a partial read is
530+ // rejected and the approved patch is thrown away.
531+ await task . diffViewProvider . saveChanges ( diagnosticsEnabled , writeDelayMs , "edit" )
439532 }
440533
441534 await task . fileContextTracker . trackFileContext ( relPath , "roo_edited" as RecordSource )
0 commit comments