Skip to content

Commit 94206fb

Browse files
u917 name the edit kind on apply_diff guarded publishes
ApplyDiffTool published its accepted hunk through DiffViewProvider.saveChanges on the "update" default, through saveDirectly on the "create" default, and recorded no observation for the file its hunks were matched against. Once the diff view published through guardedWrite, both defaults read the publish as a full-file replacement, so a partial observation - the preview's own stat-matched read, a line slice, or an indentation block - made apply_diff fail behind the re-read-the-whole-file remediation, and the model never received the {"path":...,"operation":"modified"} tool result the mocked-provider suite replays for apply diff. The four apply_diff cases timed out on that refusal at 7e5415a while the same host and mock ran them green at its first parent. Name "edit" on both publishes, as ApplyPatchTool and SearchReplaceTool do, and record the tool's own read as a stat-matched, incomplete observation so the edit guard has a token to compare against without claiming completeness the hunk never earned. applyDiffTool.writeKind spec pins both kinds, the observation its own read records, the carried completeness, and the S2 bracket that records nothing.
1 parent 7e5415a commit 94206fb

3 files changed

Lines changed: 289 additions & 2 deletions

File tree

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1313
import { unescapeHtmlEntities } from "../../utils/text-normalization"
1414
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1515
import { computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats"
16+
import { versionTokenOfStat } from "../../utils/versionToken"
1617
import type { DiffResult, ToolUse } from "../../shared/tools"
1718

1819
import { BaseTool, ToolCallbacks } from "./BaseTool"
@@ -74,7 +75,29 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
7475
return
7576
}
7677

78+
// The tool's own read is what the diff hunks are matched against, and the guarded publish below
79+
// consumes an observation: leave it unrecorded and the approved publish is an unobserved write the
80+
// guard refuses, even though this tool just read the exact bytes the patch was applied to. Record
81+
// it stat-matched (S2) and incomplete -- a hunk read authorises only the lines the patch touched,
82+
// so it must not become authority for a later full-file replacement. A prior observation is
83+
// carried, partial stays partial and complete stays complete, only while it still describes the
84+
// version this read published; an older one is left exactly as the model earned it, since
85+
// refreshing it here would hand the guarded save a compare-and-swap token for content the model
86+
// never saw. Same policy as ApplyPatchTool's read.
87+
const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
7788
const originalContent: string = await fs.readFile(absolutePath, "utf-8")
89+
const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
90+
if (preReadStats && postReadStats) {
91+
const preReadToken = versionTokenOfStat(preReadStats)
92+
if (preReadToken === versionTokenOfStat(postReadStats)) {
93+
const prior = task.observationRegistry.get(absolutePath)
94+
if (prior === undefined) {
95+
task.observationRegistry.observe(absolutePath, preReadToken, false)
96+
} else if (prior.version === preReadToken) {
97+
task.observationRegistry.observe(absolutePath, preReadToken, prior.complete === true)
98+
}
99+
}
100+
}
78101

79102
// Apply the diff to the original content
80103
const diffResult = (await task.diffStrategy?.applyDiff(
@@ -186,6 +209,10 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
186209
false,
187210
diagnosticsEnabled,
188211
writeDelayMs,
212+
// An apply_diff publish is a targeted hunk over content this tool read, so it is guarded as an
213+
// edit: a partial observation authorises it and stays partial. On the "create" default the guard
214+
// reads it as a fresh file and refuses the diff the user just approved.
215+
"edit",
189216
)
190217
} else {
191218
// Original behavior with diff view
@@ -224,8 +251,12 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
224251
return
225252
}
226253

227-
// Call saveChanges to update the DiffViewProvider properties
228-
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs)
254+
// Call saveChanges to update the DiffViewProvider properties. The save is the same targeted hunk
255+
// as the guarded save above, so it must select the same edit guard: on the "update" default the
256+
// guard reads the accepted preview as a full-file replacement and demands a complete observation
257+
// the model never earned, which throws the approved diff away behind a re-read-the-whole-file
258+
// remediation.
259+
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs, "edit")
229260
}
230261

231262
// Track file edit operation

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ vi.mock("@roo-code/telemetry", () => ({
1515
vi.mock("fs/promises", () => ({
1616
default: {
1717
readFile: vi.fn().mockResolvedValue(""),
18+
// ApplyDiffTool brackets its own read with bigint stats to capture the version token its guarded
19+
// publish consumes, so the double carries a stat whose token is reproducible; these cases never
20+
// reach the real guard, only the arguments the tool hands to the save.
21+
stat: vi.fn().mockResolvedValue({ dev: 1n, ino: 2n, size: 4n, mtimeNs: 1000n, ctimeNs: 2000n }),
1822
},
1923
}))
2024

@@ -105,6 +109,12 @@ describe("ApplyDiffTool failure reporting", () => {
105109
recordToolUsage: vi.fn(),
106110
processQueuedMessages: vi.fn(),
107111
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing param error"),
112+
observationRegistry: {
113+
get: vi.fn().mockReturnValue(undefined),
114+
has: vi.fn().mockReturnValue(false),
115+
observe: vi.fn(),
116+
forget: vi.fn(),
117+
},
108118
diffStrategy: undefined,
109119
} as unknown as Task
110120
})
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
// npx vitest run core/tools/__tests__/applyDiffTool.writeKind.spec.ts
2+
3+
import fs from "fs/promises"
4+
import path from "path"
5+
import type { BigIntStats } from "fs"
6+
7+
import type { Task } from "../../task/Task"
8+
import { versionTokenOfStat } from "../../../utils/versionToken"
9+
import { fileExistsAtPath } from "../../../utils/fs"
10+
import { isPathOutsideWorkspace } from "../../../utils/pathUtils"
11+
import type { ToolCallbacks } from "../BaseTool"
12+
import { applyDiffTool } from "../ApplyDiffTool"
13+
14+
// The version token the guarded publish consumes comes from the bigint stats that bracket the
15+
// tool's own read. BigIntStats is a class-backed interface without a public constructor, so a
16+
// plain-object double is the only way to pin that token without real files; single-step
17+
// downcast from Partial to the full type (test-local, per AGENTS.md). Every call returns a
18+
// fresh object so one case cannot leak a mutated stat into the next.
19+
const { readStats, statDouble, armStatDrift } = vi.hoisted(() => {
20+
const base: Partial<BigIntStats> = {
21+
dev: 7n,
22+
ino: 4242n,
23+
size: 1234n,
24+
atimeMs: 1_700_000_000_000n,
25+
mtimeMs: 1_700_000_000_123n,
26+
ctimeMs: 1_700_000_000_789n,
27+
birthtimeMs: 1_700_000_000_000n,
28+
atimeNs: 1_700_000_000_000_000_000n,
29+
mtimeNs: 1_700_000_000_123_456_789n,
30+
ctimeNs: 1_700_000_000_789_999_999n,
31+
birthtimeNs: 1_700_000_000_000_000_000n,
32+
}
33+
const state = { calls: 0, drift: false }
34+
return {
35+
readStats: (overrides: Partial<BigIntStats> = {}): BigIntStats => ({ ...base, ...overrides }) as BigIntStats,
36+
// Arming the drift makes the SECOND of the two bracketing stats disagree, which is the
37+
// S2 condition under which the read records nothing.
38+
statDouble: (): BigIntStats => {
39+
const drifted = state.drift && state.calls > 0
40+
state.calls += 1
41+
return (drifted ? { ...base, mtimeNs: 1_700_000_000_123_456_790n } : { ...base }) as BigIntStats
42+
},
43+
armStatDrift: (drift: boolean): void => {
44+
state.drift = drift
45+
state.calls = 0
46+
},
47+
}
48+
})
49+
50+
vi.mock("@roo-code/telemetry", () => ({
51+
TelemetryService: { instance: { captureDiffApplicationError: vi.fn() } },
52+
}))
53+
54+
vi.mock("fs/promises", () => ({
55+
default: {
56+
readFile: vi.fn().mockResolvedValue("old\n"),
57+
stat: vi.fn().mockImplementation(async () => statDouble()),
58+
},
59+
}))
60+
61+
vi.mock("../../../utils/fs", () => ({
62+
fileExistsAtPath: vi.fn().mockResolvedValue(true),
63+
}))
64+
65+
vi.mock("../../../utils/path", () => ({
66+
getReadablePath: vi.fn((_cwd: string, relPath?: string) => relPath ?? ""),
67+
}))
68+
69+
vi.mock("../../../utils/pathUtils", () => ({
70+
isPathOutsideWorkspace: vi.fn().mockReturnValue(false),
71+
}))
72+
73+
vi.mock("../../prompts/responses", () => ({
74+
formatResponse: {
75+
toolError: vi.fn((message: string) => `Error: ${message}`),
76+
rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`),
77+
createPrettyPatch: vi.fn(() => "mock-diff"),
78+
},
79+
}))
80+
81+
vi.mock("../../diff/stats", () => ({
82+
sanitizeUnifiedDiff: vi.fn((diff: string) => diff),
83+
computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })),
84+
}))
85+
86+
vi.mock("vscode", () => ({
87+
window: { showWarningMessage: vi.fn() },
88+
env: { openExternal: vi.fn() },
89+
Uri: { parse: vi.fn() },
90+
workspace: {
91+
get workspaceFolders() {
92+
return [{ uri: { fsPath: path.resolve(CWD) } }]
93+
},
94+
},
95+
}))
96+
97+
const CWD = "/workspace"
98+
const REL_PATH = "src/index.ts"
99+
const ABSOLUTE_PATH = path.resolve(CWD, REL_PATH)
100+
const DIFF = "<<<<<<< SEARCH\nold\n=======\nnew\n>>>>>>> REPLACE"
101+
const READ_TOKEN = versionTokenOfStat(readStats())
102+
103+
// The two saves and the observation registry are shared spies, so each case asserts on the one
104+
// publish the flow performs; a fresh double per task would let a second, differently-kinded
105+
// publish slip past an assertion that only ever inspected the first.
106+
const saveChanges = vi.fn().mockResolvedValue(undefined)
107+
const saveDirectly = vi.fn().mockResolvedValue(undefined)
108+
const registryGet = vi.fn().mockReturnValue(undefined)
109+
const registryObserve = vi.fn()
110+
const registryHas = vi.fn().mockReturnValue(false)
111+
const askApproval = vi.fn<ToolCallbacks["askApproval"]>().mockResolvedValue(true)
112+
113+
function createTask(preventFocusDisruption = false): Task {
114+
const task = {
115+
cwd: CWD,
116+
consecutiveMistakeCount: 0,
117+
consecutiveMistakeCountForApplyDiff: new Map<string, number>(),
118+
didEditFile: false,
119+
api: { getModel: () => ({ id: "claude-test" }) },
120+
rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true) },
121+
rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false) },
122+
providerRef: {
123+
deref: vi.fn().mockReturnValue({
124+
getState: vi.fn().mockResolvedValue({
125+
diagnosticsEnabled: false,
126+
writeDelayMs: 0,
127+
experiments: { preventFocusDisruption },
128+
}),
129+
}),
130+
},
131+
diffStrategy: {
132+
getName: () => "test",
133+
applyDiff: vi.fn().mockResolvedValue({ success: true, content: "new\n" }),
134+
},
135+
diffViewProvider: {
136+
editType: undefined,
137+
originalContent: "",
138+
open: vi.fn().mockResolvedValue(undefined),
139+
update: vi.fn().mockResolvedValue(undefined),
140+
reset: vi.fn().mockResolvedValue(undefined),
141+
revertChanges: vi.fn().mockResolvedValue(undefined),
142+
saveChanges,
143+
saveDirectly,
144+
scrollToFirstDiff: vi.fn(),
145+
pushToolWriteResult: vi
146+
.fn()
147+
.mockResolvedValue('{"path":"src/index.ts","operation":"modified","notice":"baseline"}'),
148+
},
149+
observationRegistry: {
150+
get: registryGet,
151+
has: registryHas,
152+
observe: registryObserve,
153+
forget: vi.fn(),
154+
},
155+
fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined) },
156+
say: vi.fn().mockResolvedValue(undefined),
157+
ask: vi.fn().mockResolvedValue(undefined),
158+
recordToolError: vi.fn(),
159+
processQueuedMessages: vi.fn(),
160+
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing param error"),
161+
}
162+
// The double provides only the Task members that ApplyDiffTool.execute reads.
163+
return task as unknown as Task
164+
}
165+
166+
async function runExecute(preventFocusDisruption = false): Promise<void> {
167+
await applyDiffTool.execute({ path: REL_PATH, diff: DIFF }, createTask(preventFocusDisruption), {
168+
askApproval,
169+
handleError: vi.fn().mockResolvedValue(undefined),
170+
pushToolResult: vi.fn(),
171+
toolCallId: "tool-call-write-kind",
172+
})
173+
}
174+
175+
// The mocked-provider suite replays an apply_diff turn that is matched on a tool result of
176+
// {"path":...,"operation":"modified"}. While the diff-view save ran on its "update" default the
177+
// guard read the accepted preview as a full-file replacement, refused it behind the partial-read
178+
// remediation, and the tool result the provider was promised never existed. The write kind the
179+
// tool asks for, and the observation its own read records to authorize that kind, are the
180+
// contract these cases pin.
181+
describe("ApplyDiffTool write kind", () => {
182+
beforeEach(() => {
183+
vi.clearAllMocks()
184+
applyDiffTool.resetPartialState()
185+
armStatDrift(false)
186+
registryGet.mockReturnValue(undefined)
187+
registryHas.mockReturnValue(false)
188+
registryObserve.mockImplementation(() => undefined)
189+
saveChanges.mockResolvedValue(undefined)
190+
saveDirectly.mockResolvedValue(undefined)
191+
askApproval.mockResolvedValue(true)
192+
vi.mocked(fs.readFile).mockResolvedValue("old\n")
193+
vi.mocked(fileExistsAtPath).mockResolvedValue(true)
194+
vi.mocked(isPathOutsideWorkspace).mockReturnValue(false)
195+
})
196+
197+
it("publishes the accepted hunk through the diff-view save as an edit", async () => {
198+
await runExecute()
199+
200+
expect(saveChanges).toHaveBeenCalledTimes(1)
201+
expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit")
202+
expect(saveDirectly).not.toHaveBeenCalled()
203+
})
204+
205+
it("publishes the accepted hunk through the guarded direct save as an edit", async () => {
206+
await runExecute(true)
207+
208+
expect(saveDirectly).toHaveBeenCalledTimes(1)
209+
expect(saveDirectly).toHaveBeenCalledWith(REL_PATH, "new\n", false, false, 0, "edit")
210+
expect(saveChanges).not.toHaveBeenCalled()
211+
})
212+
213+
it("records its own read as an incomplete observation so the edit guard accepts the publish", async () => {
214+
await runExecute()
215+
216+
expect(registryObserve).toHaveBeenCalledTimes(1)
217+
expect(registryObserve).toHaveBeenCalledWith(ABSOLUTE_PATH, READ_TOKEN, false)
218+
})
219+
220+
it("keeps a matching complete read complete rather than downgrading it to the hunk", async () => {
221+
registryGet.mockReturnValue({ version: READ_TOKEN, complete: true })
222+
223+
await runExecute()
224+
225+
expect(registryObserve).toHaveBeenCalledTimes(1)
226+
expect(registryObserve).toHaveBeenCalledWith(ABSOLUTE_PATH, READ_TOKEN, true)
227+
})
228+
229+
it("leaves an observation of an older version exactly as the model earned it", async () => {
230+
registryGet.mockReturnValue({ version: "9:9:9:9:9", complete: true })
231+
232+
await runExecute()
233+
234+
expect(registryObserve).not.toHaveBeenCalled()
235+
expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit")
236+
})
237+
238+
it("records nothing when the read is not stat-matched, leaving the publish unobserved", async () => {
239+
armStatDrift(true)
240+
241+
await runExecute()
242+
243+
expect(registryObserve).not.toHaveBeenCalled()
244+
expect(saveChanges).toHaveBeenCalledWith(false, 0, "edit")
245+
})
246+
})

0 commit comments

Comments
 (0)