1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { localExecBackend } from "@dispatch/exec-backend";
import { createLogger, type ToolExecuteContext } from "@dispatch/kernel";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
computeReplacement,
createEditFileTool,
type DiagnosticsHook,
validateArgs,
} from "./edit-file.js";
function stubCtx(overrides?: Partial<ToolExecuteContext>): ToolExecuteContext {
return {
toolCallId: "test-call-1",
onOutput: () => {},
signal: AbortSignal.timeout(5000),
log: createLogger(
{ extensionId: "test" },
{ emit: () => {} },
{ now: () => 0, newId: () => "id" },
),
...overrides,
};
}
/** No-op diagnostics — the post-edit LSP hook returning "no diagnostics". */
const noopDiagnostics: DiagnosticsHook = async () => ({
formatted: "",
slow: false,
timedOut: false,
});
/**
* Build an edit_file tool wired to the real local ExecBackend (node:fs,
* behavior-identical to today's inline calls) and a no-op diagnostics hook.
* No `@dispatch/*` mocking — the real fs edge is exercised, matching the
* constitution's strict-core rule. Tests that need a real diagnostics hook
* build the tool inline.
*/
function makeTool(
diagnostics: DiagnosticsHook = noopDiagnostics,
): ReturnType<typeof createEditFileTool> {
return createEditFileTool({
resolveBackend: () => localExecBackend,
workdir,
diagnostics,
});
}
let workdir: string;
beforeEach(async () => {
workdir = await mkdtemp(join(tmpdir(), "tool-edit-file-test-"));
});
afterEach(async () => {
await rm(workdir, { recursive: true, force: true });
});
describe("validateArgs", () => {
it("returns validated args for valid input", () => {
const result = validateArgs({ path: "f.txt", oldString: "a", newString: "b" });
expect(result).toEqual({ path: "f.txt", oldString: "a", newString: "b", replaceAll: false });
});
it("parses replaceAll true", () => {
const result = validateArgs({
path: "f.txt",
oldString: "a",
newString: "b",
replaceAll: true,
});
expect(result).toEqual({ path: "f.txt", oldString: "a", newString: "b", replaceAll: true });
});
it("defaults replaceAll to false when omitted", () => {
const result = validateArgs({ path: "f.txt", oldString: "a", newString: "b" });
expect(result).toHaveProperty("replaceAll", false);
});
it("returns error for null args", () => {
const result = validateArgs(null);
expect(result).toHaveProperty("error");
});
it("returns error for missing path", () => {
const result = validateArgs({ oldString: "a", newString: "b" });
expect(result).toHaveProperty("error");
});
it("returns error for missing oldString", () => {
const result = validateArgs({ path: "f.txt", newString: "b" });
expect(result).toHaveProperty("error");
});
it("returns error for missing newString", () => {
const result = validateArgs({ path: "f.txt", oldString: "a" });
expect(result).toHaveProperty("error");
});
it("returns error for non-string path", () => {
const result = validateArgs({ path: 123, oldString: "a", newString: "b" });
expect(result).toHaveProperty("error");
});
it("returns error for non-string oldString", () => {
const result = validateArgs({ path: "f.txt", oldString: 123, newString: "b" });
expect(result).toHaveProperty("error");
});
});
describe("computeReplacement", () => {
it("replaces a single occurrence", () => {
const result = computeReplacement("hello world", "world", "there", false);
expect(result).toEqual({ content: "hello there", count: 1 });
});
it("replaces all occurrences when replaceAll is true", () => {
const result = computeReplacement("aaa", "a", "b", true);
expect(result).toEqual({ content: "bbb", count: 3 });
});
it("returns identical error when newString equals oldString", () => {
const result = computeReplacement("hello", "hello", "hello", false);
expect(result).toEqual({ kind: "identical" });
});
it("returns notFound error when oldString is not in content", () => {
const result = computeReplacement("hello", "xyz", "abc", false);
expect(result).toEqual({ kind: "notFound" });
});
it("returns notUnique error when oldString occurs multiple times and replaceAll is false", () => {
const result = computeReplacement("abc abc abc", "abc", "xyz", false);
expect(result).toEqual({ kind: "notUnique", count: 3 });
});
it("replaces only the single match when unique", () => {
const result = computeReplacement("foo bar baz", "bar", "qux", false);
expect(result).toEqual({ content: "foo qux baz", count: 1 });
});
it("handles replaceAll with multiple occurrences", () => {
const result = computeReplacement("one two one two", "two", "three", true);
expect(result).toEqual({ content: "one three one three", count: 2 });
});
it("handles empty oldString as notFound (empty string not searched)", () => {
// empty oldString would cause infinite loop in split, so we treat it as not-found
const result = computeReplacement("hello", "", "x", false);
expect(result).toEqual({ kind: "notFound" });
});
it("handles oldString at start of content", () => {
const result = computeReplacement("hello world", "hello", "goodbye", false);
expect(result).toEqual({ content: "goodbye world", count: 1 });
});
it("handles oldString at end of content", () => {
const result = computeReplacement("hello world", "world", "there", false);
expect(result).toEqual({ content: "hello there", count: 1 });
});
it("handles multiline oldString and newString", () => {
const content = "line1\nold line\nline3";
const result = computeReplacement(content, "old line", "new line", false);
expect(result).toEqual({ content: "line1\nnew line\nline3", count: 1 });
});
});
describe("createEditFileTool", () => {
it("replaces a single occurrence", async () => {
const filePath = join(workdir, "test.txt");
await writeFile(filePath, "hello world\n", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "test.txt", oldString: "world", newString: "there" },
stubCtx(),
);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 1 occurrence");
const content = await readFile(filePath, "utf8");
expect(content).toBe("hello there\n");
});
it("replaces all occurrences when replaceAll is true", async () => {
const filePath = join(workdir, "test.txt");
await writeFile(filePath, "aaa\n", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "test.txt", oldString: "a", newString: "b", replaceAll: true },
stubCtx(),
);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 3 occurrences");
const content = await readFile(filePath, "utf8");
expect(content).toBe("bbb\n");
});
it("errors when oldString is not found", async () => {
const filePath = join(workdir, "test.txt");
await writeFile(filePath, "hello\n", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "test.txt", oldString: "xyz", newString: "abc" },
stubCtx(),
);
expect(result.isError).toBe(true);
expect(result.content).toContain("oldString not found");
});
it("errors when oldString is non-unique and replaceAll is false", async () => {
const filePath = join(workdir, "test.txt");
await writeFile(filePath, "abc abc abc\n", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "test.txt", oldString: "abc", newString: "xyz" },
stubCtx(),
);
expect(result.isError).toBe(true);
expect(result.content).toContain("Found 3 matches");
});
it("errors when newString equals oldString", async () => {
const filePath = join(workdir, "test.txt");
await writeFile(filePath, "hello\n", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "test.txt", oldString: "hello", newString: "hello" },
stubCtx(),
);
expect(result.isError).toBe(true);
expect(result.content).toContain("newString must differ from oldString");
});
it("errors / not-found for a nonexistent file", async () => {
const tool = makeTool();
const result = await tool.execute(
{ path: "nonexistent.txt", oldString: "a", newString: "b" },
stubCtx(),
);
expect(result.isError).toBe(true);
expect(result.content).toContain("not found");
});
it("reads file under ctx.cwd when set", async () => {
const ctxDir = await mkdtemp(join(tmpdir(), "ctx-cwd-test-"));
try {
const filePath = join(ctxDir, "ctx-file.txt");
await writeFile(filePath, "hello world", "utf8");
const tool = makeTool();
const result = await tool.execute(
{ path: "ctx-file.txt", oldString: "world", newString: "there" },
stubCtx({ cwd: ctxDir }),
);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 1 occurrence");
const content = await readFile(filePath, "utf8");
expect(content).toBe("hello there");
} finally {
await rm(ctxDir, { recursive: true, force: true });
}
});
it("falls back to baked workdir when ctx.cwd is omitted", async () => {
const filePath = join(workdir, "baked-file.txt");
await writeFile(filePath, "hello world", "utf8");
const tool = makeTool();
const ctx = stubCtx();
expect(ctx.cwd).toBeUndefined();
const result = await tool.execute(
{ path: "baked-file.txt", oldString: "world", newString: "there" },
ctx,
);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 1 occurrence");
});
it("never throws on bad input (always returns ToolResult)", async () => {
const tool = makeTool();
const inputs = [null, undefined, 42, "string", {}, { path: "" }, { path: 123 }];
for (const input of inputs) {
const result = await tool.execute(input, stubCtx());
expect(result).toHaveProperty("content");
expect(typeof result.content).toBe("string");
}
});
it("concurrencySafe is false", () => {
const tool = makeTool();
expect(tool.concurrencySafe).toBe(false);
});
it("has correct name and parameters shape", () => {
const tool = makeTool();
expect(tool.name).toBe("edit_file");
expect(tool.parameters.type).toBe("object");
expect(tool.parameters.required).toEqual(["path", "oldString", "newString"]);
expect(tool.parameters.properties?.path?.type).toBe("string");
expect(tool.parameters.properties?.oldString?.type).toBe("string");
expect(tool.parameters.properties?.newString?.type).toBe("string");
expect(tool.parameters.properties?.replaceAll?.type).toBe("boolean");
});
it("appends LSP diagnostics to the result when local and errors exist", async () => {
const filePath = join(workdir, "diag.txt");
await writeFile(filePath, "hello world\n", "utf8");
let called = false;
const diagnostics: DiagnosticsHook = async (opts) => {
called = true;
expect(opts.text).toBe("hello there\n");
return { formatted: "⚠️ 2 errors", slow: false, timedOut: false };
};
const tool = makeTool(diagnostics);
const result = await tool.execute(
{ path: "diag.txt", oldString: "world", newString: "there" },
stubCtx(),
);
expect(called).toBe(true);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 1 occurrence");
expect(result.content).toContain("⚠️ 2 errors");
});
it("appends the slow-diagnostics notice when LSP is slow", async () => {
const filePath = join(workdir, "slow.txt");
await writeFile(filePath, "hello\n", "utf8");
const diagnostics: DiagnosticsHook = async () => ({
formatted: "",
slow: true,
timedOut: false,
});
const tool = makeTool(diagnostics);
const result = await tool.execute(
{ path: "slow.txt", oldString: "hello", newString: "hi" },
stubCtx(),
);
expect(result.isError).toBeUndefined();
expect(result.content).toContain("Replaced 1 occurrence");
expect(result.content).toContain("LSP is taking unusually long");
});
it("calls LSP diagnostics when local (computerId undefined)", async () => {
const filePath = join(workdir, "local.txt");
await writeFile(filePath, "hello\n", "utf8");
let called = false;
const diagnostics: DiagnosticsHook = async () => {
called = true;
return { formatted: "", slow: false, timedOut: false };
};
const tool = makeTool(diagnostics);
const result = await tool.execute(
{ path: "local.txt", oldString: "hello", newString: "hi" },
stubCtx(), // computerId omitted → undefined → local
);
expect(called).toBe(true);
expect(result.isError).toBeUndefined();
expect(result.content).toBe('Replaced 1 occurrence in "local.txt".');
});
it("skips LSP diagnostics when computerId is set (remote)", async () => {
const filePath = join(workdir, "remote.txt");
await writeFile(filePath, "hello\n", "utf8");
let called = false;
const diagnostics: DiagnosticsHook = async () => {
called = true;
return { formatted: "DIAG-SHOULD-NOT-APPEAR", slow: false, timedOut: false };
};
const tool = makeTool(diagnostics);
const result = await tool.execute(
{ path: "remote.txt", oldString: "hello", newString: "hi" },
stubCtx({ computerId: "remote-host" }),
);
// Remote: the diagnostics hook is never invoked (LSP servers are local
// processes that can't see remote files over SFTP).
expect(called).toBe(false);
expect(result.isError).toBeUndefined();
// The edit itself still succeeded against the (local) backend.
expect(result.content).toBe('Replaced 1 occurrence in "remote.txt".');
expect(result.content).not.toContain("DIAG-SHOULD-NOT-APPEAR");
const content = await readFile(filePath, "utf8");
expect(content).toBe("hi\n");
});
it("swallows a throwing diagnostics hook (edit already succeeded)", async () => {
const filePath = join(workdir, "throw.txt");
await writeFile(filePath, "hello\n", "utf8");
const diagnostics: DiagnosticsHook = async () => {
throw new Error("LSP exploded");
};
const tool = makeTool(diagnostics);
const result = await tool.execute(
{ path: "throw.txt", oldString: "hello", newString: "hi" },
stubCtx(),
);
expect(result.isError).toBeUndefined();
expect(result.content).toBe('Replaced 1 occurrence in "throw.txt".');
});
});
|