Skip to content

Commit 67d8525

Browse files
committed
feat(fws): edit and search_replace writes now record the per-write checkpoint and change card (B3a, #1375)
1 parent 341a9c2 commit 67d8525

5 files changed

Lines changed: 322 additions & 0 deletions

File tree

‎src/core/tools/EditTool.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1111
import { fileExistsAtPath } from "../../utils/fs"
1212
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1313
import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats"
14+
import { checkpointSave } from "../../core/checkpoints"
15+
import { checkAutoApproval } from "../auto-approval"
1416
import type { ToolUse } from "../../shared/tools"
1517

1618
import { BaseTool, ToolCallbacks } from "./BaseTool"
@@ -167,6 +169,7 @@ export class EditTool extends BaseTool<"edit"> {
167169
const state = await provider?.getState()
168170
const diagnosticsEnabled = state?.diagnosticsEnabled ?? true
169171
const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
172+
const perWriteCheckpoints = state?.perWriteCheckpoints ?? true
170173
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
171174
state?.experiments ?? {},
172175
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
@@ -229,6 +232,34 @@ export class EditTool extends BaseTool<"edit"> {
229232
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, false)
230233
pushToolResult(message)
231234

235+
if (perWriteCheckpoints) {
236+
// B2: the change-journal entry for this edit is appended inside
237+
// checkpointSave (the hook stays a single call site), keyed by the
238+
// checkpoint commit that call produces. B3a threads the approval
239+
// diff (for the change card) and whether the step was auto-
240+
// approved (auto-approved steps always get the compact card).
241+
const autoApproved =
242+
(
243+
await checkAutoApproval({
244+
state,
245+
cwd: task.cwd,
246+
ask: "tool",
247+
text: completeMessage,
248+
isProtected: isWriteProtected,
249+
})
250+
).decision === "approve"
251+
// Awaited: a later tool block must not interleave with this edit's
252+
// staging/commit/journal/change-card work. checkpointSave never
253+
// rejects (service call wrapped in try/catch upstream).
254+
await checkpointSave(task, false, true, {
255+
path: relPath,
256+
operation: "update",
257+
diffStats: diffStats ? { additions: diffStats.added, deletions: diffStats.removed } : undefined,
258+
...(sanitizedDiff ? { diff: sanitizedDiff } : {}),
259+
...(autoApproved ? { autoApproved: true } : {}),
260+
})
261+
}
262+
232263
await task.diffViewProvider.reset()
233264
this.resetPartialState()
234265

‎src/core/tools/SearchReplaceTool.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1111
import { fileExistsAtPath } from "../../utils/fs"
1212
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1313
import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats"
14+
import { checkpointSave } from "../../core/checkpoints"
15+
import { checkAutoApproval } from "../auto-approval"
1416
import type { ToolUse } from "../../shared/tools"
1517

1618
import { BaseTool, ToolCallbacks } from "./BaseTool"
@@ -163,6 +165,7 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> {
163165
const state = await provider?.getState()
164166
const diagnosticsEnabled = state?.diagnosticsEnabled ?? true
165167
const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
168+
const perWriteCheckpoints = state?.perWriteCheckpoints ?? true
166169
const isPreventFocusDisruptionEnabled = experiments.isEnabled(
167170
state?.experiments ?? {},
168171
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
@@ -225,6 +228,35 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> {
225228
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, false)
226229
pushToolResult(message)
227230

231+
if (perWriteCheckpoints) {
232+
// B2: the change-journal entry for this search-and-replace is appended
233+
// inside checkpointSave (the hook stays a single call site), keyed
234+
// by the checkpoint commit that call produces. B3a threads the
235+
// approval diff (for the change card) and whether the step was auto-
236+
// approved (auto-approved steps always get the compact card).
237+
const autoApproved =
238+
(
239+
await checkAutoApproval({
240+
state,
241+
cwd: task.cwd,
242+
ask: "tool",
243+
text: completeMessage,
244+
isProtected: isWriteProtected,
245+
})
246+
).decision === "approve"
247+
// Awaited: a later tool block must not interleave with this
248+
// search-and-replace's staging/commit/journal/change-card work.
249+
// checkpointSave never rejects (service call wrapped in try/catch
250+
// upstream).
251+
await checkpointSave(task, false, true, {
252+
path: relPath,
253+
operation: "update",
254+
diffStats: diffStats ? { additions: diffStats.added, deletions: diffStats.removed } : undefined,
255+
...(sanitizedDiff ? { diff: sanitizedDiff } : {}),
256+
...(autoApproved ? { autoApproved: true } : {}),
257+
})
258+
}
259+
228260
await task.diffViewProvider.reset()
229261
this.resetPartialState()
230262

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
// npx vitest run core/tools/__tests__/editSearchReplaceTool.changeCard.spec.ts
2+
3+
import type { MockedFunction } from "vitest"
4+
5+
import { fileExistsAtPath } from "../../../utils/fs"
6+
import { checkAutoApproval } from "../../auto-approval"
7+
import { checkpointSave } from "../../checkpoints"
8+
import type { Task } from "../../task/Task"
9+
import { EditTool } from "../EditTool"
10+
import type { ToolCallbacks } from "../BaseTool"
11+
import { SearchReplaceTool } from "../SearchReplaceTool"
12+
13+
/**
14+
* The shared surface of the two string-replacement edit tools: both execute a
15+
* single `old_string` -> `new_string` replacement and report through the same
16+
* ToolCallbacks, which is all the change-card tests exercise.
17+
*/
18+
interface EditLikeTool {
19+
execute(
20+
params: { file_path: string; old_string: string; new_string: string },
21+
task: Task,
22+
callbacks: ToolCallbacks,
23+
): Promise<void>
24+
}
25+
26+
vi.mock("fs/promises", () => ({
27+
default: {
28+
// Contains exactly one occurrence of the old_string below.
29+
readFile: vi.fn().mockResolvedValue("old line\n"),
30+
},
31+
}))
32+
33+
vi.mock("../../../utils/fs", () => ({
34+
fileExistsAtPath: vi.fn().mockResolvedValue(true),
35+
}))
36+
37+
vi.mock("../../prompts/responses", () => ({
38+
formatResponse: {
39+
toolError: vi.fn((msg: string) => `Error: ${msg}`),
40+
rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`),
41+
createPrettyPatch: vi.fn(() => "mock-diff"),
42+
},
43+
}))
44+
45+
vi.mock("../../diff/stats", () => ({
46+
// The real DiffStats shape is { added, removed } (the tool maps it to the
47+
// change-card { additions, deletions } pair).
48+
sanitizeUnifiedDiff: vi.fn((diff: string) => diff),
49+
computeDiffStats: vi.fn(() => ({ added: 1, removed: 1 })),
50+
}))
51+
52+
vi.mock("../../checkpoints", () => ({
53+
checkpointSave: vi.fn().mockResolvedValue(undefined),
54+
}))
55+
56+
vi.mock("../../auto-approval", () => ({
57+
checkAutoApproval: vi.fn().mockResolvedValue({ decision: "ask" }),
58+
}))
59+
60+
interface Stubs {
61+
mockTask: Pick<
62+
Task,
63+
| "cwd"
64+
| "consecutiveMistakeCount"
65+
| "recordToolError"
66+
| "rooIgnoreController"
67+
| "rooProtectedController"
68+
| "processQueuedMessages"
69+
| "didEditFile"
70+
| "diffViewProvider"
71+
| "providerRef"
72+
| "fileContextTracker"
73+
>
74+
mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise<unknown>>
75+
mockGetState: MockedFunction<() => Promise<Record<string, unknown>>>
76+
}
77+
78+
/**
79+
* Structural stubs for the prevent-focus-disruption save path: the real
80+
* DiffViewProvider is out of scope here, so vi.fn() doubles stand in for the
81+
* members the edit tools touch.
82+
*/
83+
function buildStubs(): Stubs {
84+
const mockSaveDirectly = vi.fn().mockResolvedValue({
85+
newProblemsMessage: "",
86+
userEdits: undefined,
87+
finalContent: "new line\n",
88+
})
89+
const diffViewProviderStub = {
90+
editType: undefined as "create" | "modify" | undefined,
91+
originalContent: undefined as string | undefined,
92+
open: vi.fn().mockResolvedValue(undefined),
93+
update: vi.fn().mockResolvedValue(undefined),
94+
scrollToFirstDiff: vi.fn(),
95+
saveDirectly: mockSaveDirectly,
96+
saveChanges: vi.fn().mockResolvedValue({
97+
newProblemsMessage: "",
98+
userEdits: undefined,
99+
finalContent: "new line\n",
100+
}),
101+
revertChanges: vi.fn().mockResolvedValue(undefined),
102+
pushToolWriteResult: vi.fn().mockResolvedValue("Saved file"),
103+
reset: vi.fn().mockResolvedValue(undefined),
104+
}
105+
const mockGetState = vi.fn().mockResolvedValue({
106+
diagnosticsEnabled: true,
107+
writeDelayMs: 1000,
108+
// Exercise the focus-disruption (saveDirectly) save path.
109+
experiments: { preventFocusDisruption: true },
110+
})
111+
const mockTask: Stubs["mockTask"] = {
112+
cwd: "/workspace/project",
113+
consecutiveMistakeCount: 0,
114+
recordToolError: vi.fn(),
115+
rooIgnoreController: {
116+
validateAccess: vi.fn().mockReturnValue(true),
117+
} as unknown as Task["rooIgnoreController"],
118+
rooProtectedController: {
119+
isWriteProtected: vi.fn().mockReturnValue(false),
120+
} as unknown as Task["rooProtectedController"],
121+
processQueuedMessages: vi.fn(),
122+
didEditFile: false,
123+
diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"],
124+
providerRef: {
125+
deref: vi.fn().mockReturnValue({
126+
getState: mockGetState,
127+
}),
128+
} as unknown as Task["providerRef"],
129+
fileContextTracker: {
130+
trackFileContext: vi.fn().mockResolvedValue(undefined),
131+
} as unknown as Task["fileContextTracker"],
132+
}
133+
return { mockTask, mockSaveDirectly, mockGetState }
134+
}
135+
136+
function cardTests(getTool: () => EditLikeTool) {
137+
const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction<typeof fileExistsAtPath>
138+
const mockCheckpointSave = checkpointSave as MockedFunction<typeof checkpointSave>
139+
const mockCheckAutoApproval = checkAutoApproval as MockedFunction<typeof checkAutoApproval>
140+
141+
let tool: EditLikeTool
142+
let stubs: Stubs
143+
let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise<boolean>>
144+
let mockHandleError: MockedFunction<(...args: unknown[]) => Promise<void>>
145+
let mockPushToolResult: MockedFunction<(...args: unknown[]) => void>
146+
147+
beforeEach(() => {
148+
vi.clearAllMocks()
149+
mockedFileExistsAtPath.mockResolvedValue(true)
150+
stubs = buildStubs()
151+
tool = getTool()
152+
mockAskApproval = vi.fn().mockResolvedValue(true)
153+
mockHandleError = vi.fn().mockResolvedValue(undefined)
154+
mockPushToolResult = vi.fn()
155+
})
156+
157+
it("records a per-write checkpoint with the approval diff after a successful write", async () => {
158+
await tool.execute(
159+
{ file_path: "src/thing.ts", old_string: "old line", new_string: "new line" },
160+
stubs.mockTask as Task,
161+
{
162+
askApproval: mockAskApproval,
163+
handleError: mockHandleError,
164+
pushToolResult: mockPushToolResult,
165+
},
166+
)
167+
168+
expect(mockCheckpointSave).toHaveBeenCalledTimes(1)
169+
expect(mockCheckpointSave).toHaveBeenCalledWith(stubs.mockTask, false, true, {
170+
path: "src/thing.ts",
171+
operation: "update",
172+
diffStats: { additions: 1, deletions: 1 },
173+
diff: "mock-diff",
174+
})
175+
})
176+
177+
it("marks auto-approved steps so the card renders compact", async () => {
178+
mockCheckAutoApproval.mockResolvedValueOnce({ decision: "approve" })
179+
180+
await tool.execute(
181+
{ file_path: "src/thing.ts", old_string: "old line", new_string: "new line" },
182+
stubs.mockTask as Task,
183+
{
184+
askApproval: mockAskApproval,
185+
handleError: mockHandleError,
186+
pushToolResult: mockPushToolResult,
187+
},
188+
)
189+
190+
expect(mockCheckpointSave).toHaveBeenCalledTimes(1)
191+
expect(mockCheckpointSave.mock.calls[0]?.[3]).toEqual(expect.objectContaining({ autoApproved: true }))
192+
})
193+
194+
it("skips the checkpoint when perWriteCheckpoints is explicitly disabled", async () => {
195+
stubs.mockGetState.mockResolvedValueOnce({
196+
diagnosticsEnabled: true,
197+
writeDelayMs: 1000,
198+
experiments: { preventFocusDisruption: true },
199+
perWriteCheckpoints: false,
200+
})
201+
202+
await tool.execute(
203+
{ file_path: "src/thing.ts", old_string: "old line", new_string: "new line" },
204+
stubs.mockTask as Task,
205+
{
206+
askApproval: mockAskApproval,
207+
handleError: mockHandleError,
208+
pushToolResult: mockPushToolResult,
209+
},
210+
)
211+
212+
expect(mockCheckpointSave).not.toHaveBeenCalled()
213+
// The write itself still happens (the setting gates the checkpoint only),
214+
// and auto-approval is never consulted when there is no card to build.
215+
expect(stubs.mockSaveDirectly).toHaveBeenCalled()
216+
expect(mockCheckAutoApproval).not.toHaveBeenCalled()
217+
})
218+
219+
it("records nothing when the approval is declined", async () => {
220+
mockAskApproval.mockResolvedValue(false)
221+
222+
await tool.execute(
223+
{ file_path: "src/thing.ts", old_string: "old line", new_string: "new line" },
224+
stubs.mockTask as Task,
225+
{
226+
askApproval: mockAskApproval,
227+
handleError: mockHandleError,
228+
pushToolResult: mockPushToolResult,
229+
},
230+
)
231+
232+
expect(mockCheckpointSave).not.toHaveBeenCalled()
233+
expect(stubs.mockSaveDirectly).not.toHaveBeenCalled()
234+
})
235+
}
236+
237+
describe("EditTool.execute - per-write checkpoint and change card (B3a, epic #1375)", () => {
238+
cardTests(() => new EditTool())
239+
})
240+
241+
describe("SearchReplaceTool.execute - per-write checkpoint and change card (B3a, epic #1375)", () => {
242+
cardTests(() => new SearchReplaceTool())
243+
})

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ vi.mock("../../diff/stats", () => ({
5959
computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })),
6060
}))
6161

62+
vi.mock("../../checkpoints", () => ({
63+
checkpointSave: vi.fn().mockResolvedValue(undefined),
64+
}))
65+
66+
vi.mock("../../auto-approval", () => ({
67+
checkAutoApproval: vi.fn().mockResolvedValue({ decision: "ask" }),
68+
}))
69+
6270
vi.mock("vscode", () => ({
6371
window: {
6472
showWarningMessage: vi.fn().mockResolvedValue(undefined),

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ vi.mock("../../diff/stats", () => ({
5959
computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })),
6060
}))
6161

62+
vi.mock("../../checkpoints", () => ({
63+
checkpointSave: vi.fn().mockResolvedValue(undefined),
64+
}))
65+
66+
vi.mock("../../auto-approval", () => ({
67+
checkAutoApproval: vi.fn().mockResolvedValue({ decision: "ask" }),
68+
}))
69+
6270
vi.mock("vscode", () => ({
6371
window: {
6472
showWarningMessage: vi.fn().mockResolvedValue(undefined),

0 commit comments

Comments
 (0)