@criogaid/pi-hashline-edit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * pi integration tests for the `replace` tool: literal replaceAll, regex with
3
- * capture groups, flags, the maxMatches guard, 0-match / invalid-pattern
3
+ * capture groups, flags, 0-match / invalid-pattern
4
4
  * failures (signaled by throwing — pi's failure contract), diff + fresh-anchor
5
5
  * return, and chaining a hashline `edit` on an anchor returned by `replace`.
6
6
  *
@@ -11,469 +11,853 @@ import assert from "node:assert/strict";
11
11
  import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
12
12
  import { tmpdir } from "node:os";
13
13
  import { join } from "node:path";
14
- import { initTheme } from "@earendil-works/pi-coding-agent";
14
+ import { initTheme, type Theme } from "@earendil-works/pi-coding-agent";
15
15
  import { makeReplaceTool } from "./replace-tool.ts";
16
16
  import { makeEditOverride } from "./edit-tool.ts";
17
17
  import { validateToolArguments } from "@earendil-works/pi-ai";
18
+ import { callTool } from "./tool-call.testing.ts";
18
19
  import { createActionFusionExecutor } from "./action-fusion.ts";
20
+ import { generateMutationDetails } from "./mutation-result.ts";
19
21
 
20
22
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
21
- const dir = await mkdtemp(join(tmpdir(), "hl-replace-"));
22
- try {
23
- return await fn(dir);
24
- } finally {
25
- await rm(dir, { recursive: true, force: true });
26
- }
23
+ const dir = await mkdtemp(join(tmpdir(), "hl-replace-"));
24
+ try {
25
+ return await fn(dir);
26
+ } finally {
27
+ await rm(dir, { recursive: true, force: true });
28
+ }
27
29
  }
28
30
 
29
31
  const call = (tool: any, params: any) => tool.execute("0", params, undefined, undefined);
30
32
 
31
33
  /** Extract a `LINE#HASH` anchor for `line` from a result text block. */
32
34
  function anchorLine(block: string, line: number) {
33
- const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
34
- if (!m) throw new Error(`line ${line} anchor not found in block`);
35
- return `${line}#${m[1]}`;
35
+ const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
36
+ if (!m) throw new Error(`line ${line} anchor not found in block`);
37
+ return `${line}#${m[1]}`;
36
38
  }
37
39
 
38
- const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s };
40
+ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
39
41
 
40
42
  // renderResult delegates to pi's renderDiff, which reads the global TUI theme
41
43
  // singleton — initialize it once for this test process (watcher off by default).
42
44
  initTheme();
43
45
 
44
- test("replace guidance distinguishes literal LF from a visible escape", () => {
45
- const tool = makeReplaceTool(process.cwd());
46
- const description = JSON.stringify(tool.parameters.properties.find);
47
- assert.match(description, /In literal mode \(default\), an actual LF matches a line boundary/);
48
- assert.match(description, /backslash followed by n matches those two source characters/);
49
- assert.match(description, /In regex mode/);
46
+ test("replace find guidance distinguishes literal escapes and regex line anchors", () => {
47
+ const tool = makeReplaceTool(process.cwd());
48
+ const description: unknown = Reflect.get(
49
+ tool.parameters.properties.replacements.items.properties.find,
50
+ "description",
51
+ );
52
+ assert.ok(typeof description === "string");
53
+ assert.match(description, /JavaScript regex/);
54
+ assert.match(description, /not grep's ripgrep syntax/);
55
+ assert.match(description, /CRLF.*LF.*\\n/);
56
+ assert.match(description, /literal mode.*backslash followed by n.*two characters/);
57
+ assert.match(description, /regex mode.*\^ and \$.*m flag.*per line/);
50
58
  });
51
59
 
60
+ test("replace schema requires a non-empty replacements array", () => {
61
+ for (const fusion of [undefined, createActionFusionExecutor()]) {
62
+ const tool = makeReplaceTool(process.cwd(), fusion);
63
+ assert.equal(Object.hasOwn(tool.parameters.properties, "find"), false);
64
+ const check = (args: Parameters<typeof validateToolArguments>[1]["arguments"]) =>
65
+ validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
66
+ assert.doesNotThrow(() =>
67
+ check({ path: "f.txt", replacements: [{ find: "old", replace: "new" }] }),
68
+ );
69
+ const invalidArgs: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
70
+ { path: "f.txt", find: "old", replace: "new" },
71
+ { path: "f.txt", replacements: [] },
72
+ { path: "f.txt", replacements: [{ find: "old", replace: "new" }], find: "old" },
73
+ { path: "f.txt", replacements: '[{"find":"old","replace":"new"}]' },
74
+ ...[1, null, false].map((maxMatches) => ({
75
+ path: "f.txt",
76
+ replacements: [{ find: "old", replace: "new", maxMatches }],
77
+ })),
78
+ ];
79
+ for (const args of invalidArgs) {
80
+ assert.throws(() => check(args));
81
+ }
82
+ }
83
+ });
84
+
85
+ test("replace schema rejects empty paths, empty find, and unsupported flags", () => {
86
+ const tool = makeReplaceTool(process.cwd());
87
+ for (const args of [
88
+ { path: "", replacements: [{ find: "old", replace: "new" }] },
89
+ { path: "f.txt", replacements: [{ find: "", replace: "new" }] },
90
+ { path: "f.txt", replacements: [{ find: "old", replace: "new", flags: "x" }] },
91
+ ]) {
92
+ assert.throws(
93
+ () =>
94
+ validateToolArguments(tool, {
95
+ type: "toolCall",
96
+ id: "invalid",
97
+ name: "replace",
98
+ arguments: args,
99
+ }),
100
+ /Validation failed/,
101
+ JSON.stringify(args),
102
+ );
103
+ }
104
+ });
105
+
106
+ test("replace rejects top-level rules without publishing", async () =>
107
+ withDir(async (dir) => {
108
+ const file = join(dir, "f.txt");
109
+ await writeFile(file, "old\n");
110
+ await assert.rejects(
111
+ callTool(makeReplaceTool(dir), {
112
+ path: file,
113
+ find: "old",
114
+ replace: "new",
115
+ }),
116
+ /Validation failed for tool "replace"[\s\S]*replacements/,
117
+ );
118
+ assert.equal(await readFile(file, "utf8"), "old\n");
119
+ }));
120
+
121
+ test("replace rejects unsupported per-rule fields before publishing", async () =>
122
+ withDir(async (dir) => {
123
+ const file = join(dir, "f.txt");
124
+ const before = "foo foo foo\n";
125
+ await writeFile(file, before);
126
+ const tool = makeReplaceTool(dir);
127
+ for (const maxMatches of [1, null, false]) {
128
+ await assert.rejects(
129
+ callTool(tool, { path: file, replacements: [{ find: "foo", replace: "bar", maxMatches }] }),
130
+ /Validation failed for tool "replace"[\s\S]*maxMatches/,
131
+ );
132
+ assert.equal(await readFile(file, "utf8"), before);
133
+ }
134
+ }));
135
+
136
+ test("replace rejects unwritable text and invalid regex before reading a missing target", async () =>
137
+ withDir(async (dir) => {
138
+ const file = join(dir, "missing.txt");
139
+ const tool = makeReplaceTool(dir);
140
+ const valid = { path: file, replacements: [{ find: "x", replace: "y", regex: true }] };
141
+ assert.equal(tool.prepareArguments(valid), valid);
142
+ for (const [rule, expected] of [
143
+ [
144
+ { find: "x", replace: "\0" },
145
+ /Invalid argument replacements\[0\]\.replace: UNSUPPORTED_TEXT:/,
146
+ ],
147
+ [
148
+ { find: "x", replace: "\ud800" },
149
+ /Invalid argument replacements\[0\]\.replace: INVALID_UNICODE:/,
150
+ ],
151
+ [
152
+ { find: "(", replace: "x", regex: true },
153
+ /Invalid argument replacements\[0\]\.find: invalid regex/,
154
+ ],
155
+ ] as const) {
156
+ await assert.rejects(callTool(tool, { path: file, replacements: [rule] }), expected);
157
+ await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
158
+ }
159
+ await assert.rejects(
160
+ callTool(tool, {
161
+ path: file,
162
+ replacements: [{ find: "(", replace: "x", regex: true, flags: "z" }],
163
+ }),
164
+ /Validation failed for tool "replace":[\s\S]*replacements\.0\.flags: must match pattern/,
165
+ );
166
+ await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
167
+ }));
168
+
52
169
  test("replace literal: replaces all occurrences", async () => {
53
- await withDir(async (dir) => {
54
- const f = join(dir, "f.txt");
55
- await writeFile(f, "foo bar foo baz foo\n");
56
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "foo", replace: "qux" });
57
- assert.equal(r.isError, undefined);
58
- assert.equal(await readFile(f, "utf-8"), "qux bar qux baz qux\n");
59
- assert.match(r.content[0].text, /3 matches/);
60
- });
170
+ await withDir(async (dir) => {
171
+ const f = join(dir, "f.txt");
172
+ await writeFile(f, "foo bar foo baz foo\n");
173
+ const r: any = await call(makeReplaceTool(dir), {
174
+ path: "f.txt",
175
+ replacements: [{ find: "foo", replace: "qux" }],
176
+ });
177
+ assert.equal(r.isError, undefined);
178
+ assert.equal(await readFile(f, "utf-8"), "qux bar qux baz qux\n");
179
+ assert.match(r.content[0].text, /3 matches/);
180
+ });
61
181
  });
62
182
 
63
- test("literal multiline replace matches LF and CRLF while retaining local separators", async () => withDir(async (dir) => {
64
- const file = join(dir, "mixed.txt");
65
- await writeFile(file, "\uFEFFhead\r\nold\r\none\r\nmid\nold\none\nend\r\n");
66
- const result: any = await call(makeReplaceTool(dir), { path: "mixed.txt", find: "old\none", replace: "NEW\nX" });
67
- assert.match(result.content[0].text, /2 matches/);
68
- assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
69
- await call(makeReplaceTool(dir), { path: "mixed.txt", find: "NEW\r\nX", replace: "done" });
70
- assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\ndone\r\nmid\ndone\nend\r\n");
71
- }));
72
-
73
- test("both replacement modes preserve each matched separator", async () => withDir(async (dir) => {
74
- const file = join(dir, "mixed.txt");
75
- for (const regex of [false, true]) {
76
- await writeFile(file, "a\r\nb\nc\r\ntail\n");
77
- await call(makeReplaceTool(dir), { path: "mixed.txt", find: "a\nb\nc", replace: "x\ny\nz\nextra", regex });
78
- assert.equal(await readFile(file, "utf8"), "x\r\ny\nz\nextra\r\ntail\n");
79
- }
80
- }));
81
-
82
- test("literal replacement uses one LF view and preserves raw bytes across query styles", async () => withDir(async (dir) => {
83
- const file = join(dir, "f.txt");
84
- for (const find of ["a\nb\nc", "a\r\nb\r\nc", "a\r\nb\nc"]) {
85
- const before = "\uFEFFhead\r\na\r\nb\nc\rtail";
86
- await writeFile(file, before);
87
- const result = await call(makeReplaceTool(dir), { path: file, find, replace: find });
88
- assert.equal(await readFile(file, "utf8"), before);
89
- assert.match(result.content[0].text, /no net change/);
90
- }
91
- for (const [before, find, replacement, expected] of [
92
- ["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
93
- ["a\nb", "a\r\nb", "A\r\nB", "A\nB"],
94
- ["a\r\nb", "\n", "", "ab"],
95
- ["a\r\nb", "\n", "\n", "a\r\nb"],
96
- ["a\rb\r\r\nc", "a\rb\r\r\nc", "x\ry\r\r\nz", "x\ry\r\r\nz"],
97
- ]) {
98
- await writeFile(file, before);
99
- await call(makeReplaceTool(dir), { path: file, find, replace: replacement });
100
- assert.equal(await readFile(file, "utf8"), expected);
101
- }
102
- }));
103
-
104
- test("mixed literal and regex batches share raw offsets after CRLF normalization", async () => withDir(async (dir) => {
105
- const file = join(dir, "f.txt");
106
- await writeFile(file, "😀\r\na\r\nb\r\nc");
107
- await call(makeReplaceTool(dir), { path: file, replacements: [
108
- { find: "a\nb", replace: "A\nB" },
109
- { find: "(c)$", replace: "$1!", regex: true },
110
- ] });
111
- assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
112
- const before = await readFile(file, "utf8");
113
- await assert.rejects(call(makeReplaceTool(dir), { path: file, replacements: [
114
- { find: "A\nB", replace: "x" },
115
- { find: "\\nB", replace: "y", regex: true },
116
- ] }), /overlap/);
117
- assert.equal(await readFile(file, "utf8"), before);
118
- }));
183
+ test("literal multiline replace matches LF and CRLF while retaining local separators", async () =>
184
+ withDir(async (dir) => {
185
+ const file = join(dir, "mixed.txt");
186
+ await writeFile(file, "\uFEFFhead\r\nold\r\none\r\nmid\nold\none\nend\r\n");
187
+ const result: any = await call(makeReplaceTool(dir), {
188
+ path: "mixed.txt",
189
+ replacements: [{ find: "old\none", replace: "NEW\nX" }],
190
+ });
191
+ assert.match(result.content[0].text, /2 matches/);
192
+ assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
193
+ await call(makeReplaceTool(dir), {
194
+ path: "mixed.txt",
195
+ replacements: [{ find: "NEW\r\nX", replace: "done" }],
196
+ });
197
+ assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\ndone\r\nmid\ndone\nend\r\n");
198
+ }));
199
+
200
+ test("both replacement modes preserve each matched separator", async () =>
201
+ withDir(async (dir) => {
202
+ const file = join(dir, "mixed.txt");
203
+ for (const regex of [false, true]) {
204
+ await writeFile(file, "a\r\nb\nc\r\ntail\n");
205
+ await call(makeReplaceTool(dir), {
206
+ path: "mixed.txt",
207
+ replacements: [{ find: "a\nb\nc", replace: "x\ny\nz\nextra", regex }],
208
+ });
209
+ assert.equal(await readFile(file, "utf8"), "x\r\ny\nz\nextra\r\ntail\n");
210
+ }
211
+ }));
212
+
213
+ test("literal replacement uses one LF view and preserves raw bytes across query styles", async () =>
214
+ withDir(async (dir) => {
215
+ const file = join(dir, "f.txt");
216
+ for (const find of ["a\nb\nc", "a\r\nb\r\nc", "a\r\nb\nc"]) {
217
+ const before = "\uFEFFhead\r\na\r\nb\nc\rtail";
218
+ await writeFile(file, before);
219
+ const result = await call(makeReplaceTool(dir), {
220
+ path: file,
221
+ replacements: [{ find, replace: find }],
222
+ });
223
+ assert.equal(await readFile(file, "utf8"), before);
224
+ assert.match(result.content[0].text, /no net change/);
225
+ }
226
+ for (const [before, find, replacement, expected] of [
227
+ ["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
228
+ ["a\nb", "a\r\nb", "A\r\nB", "A\nB"],
229
+ ["a\r\nb", "\n", "", "ab"],
230
+ ["a\r\nb", "\n", "\n", "a\r\nb"],
231
+ ["a\rb\r\r\nc", "a\rb\r\r\nc", "x\ry\r\r\nz", "x\ry\r\r\nz"],
232
+ ]) {
233
+ await writeFile(file, before);
234
+ await call(makeReplaceTool(dir), {
235
+ path: file,
236
+ replacements: [{ find, replace: replacement }],
237
+ });
238
+ assert.equal(await readFile(file, "utf8"), expected);
239
+ }
240
+ }));
241
+
242
+ test("mixed literal and regex batches share raw offsets after CRLF normalization", async () =>
243
+ withDir(async (dir) => {
244
+ const file = join(dir, "f.txt");
245
+ await writeFile(file, "😀\r\na\r\nb\r\nc");
246
+ await call(makeReplaceTool(dir), {
247
+ path: file,
248
+ replacements: [
249
+ { find: "a\nb", replace: "A\nB" },
250
+ { find: "(c)$", replace: "$1!", regex: true },
251
+ ],
252
+ });
253
+ assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
254
+ const before = await readFile(file, "utf8");
255
+ await assert.rejects(
256
+ call(makeReplaceTool(dir), {
257
+ path: file,
258
+ replacements: [
259
+ { find: "A\nB", replace: "x" },
260
+ { find: "\\nB", replace: "y", regex: true },
261
+ ],
262
+ }),
263
+ /overlap/,
264
+ );
265
+ assert.equal(await readFile(file, "utf8"), before);
266
+ }));
119
267
 
120
268
  test("replace literal: $ in replacement stays literal (no expansion)", async () => {
121
- await withDir(async (dir) => {
122
- const f = join(dir, "f.txt");
123
- await writeFile(f, "cost: $5 here\n");
124
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "$5", replace: "$10" });
125
- assert.equal(r.isError, undefined);
126
- // literal mode: "$10" inserted verbatim, NOT interpreted as group-10 + "0"
127
- assert.equal(await readFile(f, "utf-8"), "cost: $10 here\n");
128
- });
269
+ await withDir(async (dir) => {
270
+ const f = join(dir, "f.txt");
271
+ await writeFile(f, "cost: $5 here\n");
272
+ const r: any = await call(makeReplaceTool(dir), {
273
+ path: "f.txt",
274
+ replacements: [{ find: "$5", replace: "$10" }],
275
+ });
276
+ assert.equal(r.isError, undefined);
277
+ // literal mode: "$10" inserted verbatim, NOT interpreted as group-10 + "0"
278
+ assert.equal(await readFile(f, "utf-8"), "cost: $10 here\n");
279
+ });
129
280
  });
130
281
 
131
282
  test("replace literal: case-insensitive via flags", async () => {
132
- await withDir(async (dir) => {
133
- const f = join(dir, "f.txt");
134
- await writeFile(f, "Foo fOo FOO\n");
135
- await call(makeReplaceTool(dir), { path: "f.txt", find: "foo", replace: "x", flags: "i" });
136
- assert.equal(await readFile(f, "utf-8"), "x x x\n");
137
- });
283
+ await withDir(async (dir) => {
284
+ const f = join(dir, "f.txt");
285
+ await writeFile(f, "Foo fOo FOO\n");
286
+ await call(makeReplaceTool(dir), {
287
+ path: "f.txt",
288
+ replacements: [{ find: "foo", replace: "x", flags: "i" }],
289
+ });
290
+ assert.equal(await readFile(f, "utf-8"), "x x x\n");
291
+ });
292
+ });
293
+
294
+ test("replace aborts catastrophic regex without blocking the event loop or publishing", async () => {
295
+ await withDir(async (dir) => {
296
+ const file = join(dir, "f.txt");
297
+ const before = `${"a".repeat(30)}!`;
298
+ await writeFile(file, before);
299
+ const controller = new AbortController();
300
+ const timer = setTimeout(() => controller.abort(), 100);
301
+ const start = performance.now();
302
+ try {
303
+ await assert.rejects(
304
+ makeReplaceTool(dir).execute(
305
+ "abort",
306
+ { path: file, replacements: [{ find: "^(a+)+$", replace: "x", regex: true }] },
307
+ controller.signal,
308
+ undefined,
309
+ { cwd: dir } as Parameters<ReturnType<typeof makeReplaceTool>["execute"]>[4],
310
+ ),
311
+ (error: unknown) =>
312
+ error instanceof Error &&
313
+ error.message === `Operation aborted before apply; ${file} was not changed.`,
314
+ );
315
+ assert.ok(performance.now() - start < 2000);
316
+ assert.equal(await readFile(file, "utf8"), before);
317
+ } finally {
318
+ clearTimeout(timer);
319
+ }
320
+ });
321
+ });
322
+ test("replace times out catastrophic regex without publishing", async () => {
323
+ await withDir(async (dir) => {
324
+ const file = join(dir, "f.txt");
325
+ const before = `${"a".repeat(35)}!`;
326
+ await writeFile(file, before);
327
+ await assert.rejects(
328
+ call(makeReplaceTool(dir), {
329
+ path: file,
330
+ replacements: [{ find: "^(a+)+$", replace: "x", regex: true }],
331
+ }),
332
+ (error: unknown) =>
333
+ error instanceof Error &&
334
+ error.message === `Replace ${file}: regex evaluation timed out after 5000ms`,
335
+ );
336
+ assert.equal(await readFile(file, "utf8"), before);
337
+ });
138
338
  });
139
339
 
140
340
  test("replace regex: capture groups in replacement", async () => {
141
- await withDir(async (dir) => {
142
- const f = join(dir, "f.txt");
143
- await writeFile(f, "name: alice\nname: bob\n");
144
- await call(makeReplaceTool(dir), {
145
- path: "f.txt",
146
- find: "name: (\\w+)",
147
- replace: "user: $1",
148
- regex: true,
149
- });
150
- assert.equal(await readFile(f, "utf-8"), "user: alice\nuser: bob\n");
151
- });
341
+ await withDir(async (dir) => {
342
+ const f = join(dir, "f.txt");
343
+ await writeFile(f, "name: alice\nname: bob\n");
344
+ await call(makeReplaceTool(dir), {
345
+ path: "f.txt",
346
+ replacements: [{ find: "name: (\\w+)", replace: "user: $1", regex: true }],
347
+ });
348
+ assert.equal(await readFile(f, "utf-8"), "user: alice\nuser: bob\n");
349
+ });
152
350
  });
153
351
 
154
352
  test("replace regex: multiline flag matches line-anchored pattern", async () => {
155
- await withDir(async (dir) => {
156
- const f = join(dir, "f.txt");
157
- await writeFile(f, "a\nb\nc\n");
158
- // without `m`, ^a$ wouldn't match (a isn't at end of string); with `m` it does
159
- await call(makeReplaceTool(dir), { path: "f.txt", find: "^a$", replace: "A", regex: true, flags: "m" });
160
- assert.equal(await readFile(f, "utf-8"), "A\nb\nc\n");
161
- });
353
+ await withDir(async (dir) => {
354
+ const f = join(dir, "f.txt");
355
+ await writeFile(f, "a\nb\nc\n");
356
+ // without `m`, ^a$ wouldn't match (a isn't at end of string); with `m` it does
357
+ await call(makeReplaceTool(dir), {
358
+ path: "f.txt",
359
+ replacements: [{ find: "^a$", replace: "A", regex: true, flags: "m" }],
360
+ });
361
+ assert.equal(await readFile(f, "utf-8"), "A\nb\nc\n");
362
+ });
162
363
  });
163
364
 
164
365
  test("replace regex: dotall flag makes . match newlines", async () => {
165
- await withDir(async (dir) => {
166
- const f = join(dir, "f.txt");
167
- await writeFile(f, "a\nb\n");
168
- // a.b only matches across the newline with the `s` (dotall) flag
169
- await call(makeReplaceTool(dir), { path: "f.txt", find: "a.b", replace: "X", regex: true, flags: "s" });
170
- assert.equal(await readFile(f, "utf-8"), "X\n");
171
- });
366
+ await withDir(async (dir) => {
367
+ const f = join(dir, "f.txt");
368
+ await writeFile(f, "a\nb\n");
369
+ // a.b only matches across the newline with the `s` (dotall) flag
370
+ await call(makeReplaceTool(dir), {
371
+ path: "f.txt",
372
+ replacements: [{ find: "a.b", replace: "X", regex: true, flags: "s" }],
373
+ });
374
+ assert.equal(await readFile(f, "utf-8"), "X\n");
375
+ });
172
376
  });
173
377
 
174
378
  test("replace: 0 matches throws", async () => {
175
- await withDir(async (dir) => {
176
- const f = join(dir, "f.txt");
177
- await writeFile(f, "a\nb\n");
178
- await assert.rejects(
179
- call(makeReplaceTool(dir), { path: "f.txt", find: "zzz", replace: "y" }),
180
- /no matches/,
181
- );
182
- assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
183
- });
379
+ await withDir(async (dir) => {
380
+ const f = join(dir, "f.txt");
381
+ await writeFile(f, "a\nb\n");
382
+ await assert.rejects(
383
+ call(makeReplaceTool(dir), { path: "f.txt", replacements: [{ find: "zzz", replace: "y" }] }),
384
+ /no matches/,
385
+ );
386
+ assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
387
+ });
184
388
  });
185
389
 
186
390
  test("replace: empty find throws", async () => {
187
- await withDir(async (dir) => {
188
- await writeFile(join(dir, "f.txt"), "a\n");
189
- await assert.rejects(
190
- call(makeReplaceTool(dir), { path: "f.txt", find: "", replace: "x" }),
191
- /`find` is empty/,
192
- );
193
- });
391
+ await withDir(async (dir) => {
392
+ await writeFile(join(dir, "f.txt"), "a\n");
393
+ await assert.rejects(
394
+ callTool(makeReplaceTool(dir), { path: "f.txt", replacements: [{ find: "", replace: "x" }] }),
395
+ /Validation failed for tool "replace"[\s\S]*find/,
396
+ );
397
+ });
194
398
  });
195
399
 
196
- test("replace: maxMatches guard throws before writing", async () => {
197
- await withDir(async (dir) => {
198
- const f = join(dir, "f.txt");
199
- await writeFile(f, "a".repeat(20) + "\n");
200
- await assert.rejects(
201
- call(makeReplaceTool(dir), { path: "f.txt", find: "a", replace: "b", maxMatches: 5 }),
202
- /exceed `maxMatches`/,
203
- );
204
- assert.equal(await readFile(f, "utf-8"), "a".repeat(20) + "\n", "file untouched when guard trips");
205
- });
400
+ test("replace: handles large match counts without an arbitrary cap", async () => {
401
+ await withDir(async (dir) => {
402
+ const f = join(dir, "f.txt");
403
+ await writeFile(f, "a\n".repeat(2500));
404
+ const result: any = await call(makeReplaceTool(dir), {
405
+ path: "f.txt",
406
+ replacements: [{ find: "a", replace: "b" }],
407
+ });
408
+ assert.match(result.content[0].text, /Replaced f\.txt \(2500 matches\)\./);
409
+ assert.equal(await readFile(f, "utf-8"), "b\n".repeat(2500));
410
+ });
206
411
  });
207
412
 
208
413
  test("replace: invalid regex throws a friendly message", async () => {
209
- await withDir(async (dir) => {
210
- await writeFile(join(dir, "f.txt"), "a\n");
211
- await assert.rejects(
212
- call(makeReplaceTool(dir), { path: "f.txt", find: "(unclosed", replace: "x", regex: true }),
213
- /invalid regex/,
214
- );
215
- });
414
+ await withDir(async (dir) => {
415
+ await writeFile(join(dir, "f.txt"), "a\n");
416
+ await assert.rejects(
417
+ call(makeReplaceTool(dir), {
418
+ path: "f.txt",
419
+ replacements: [{ find: "(unclosed", replace: "x", regex: true }],
420
+ }),
421
+ /invalid regex/,
422
+ );
423
+ });
216
424
  });
217
425
 
218
426
  test("replace: invalid flag char throws", async () => {
219
- await withDir(async (dir) => {
220
- await writeFile(join(dir, "f.txt"), "a\n");
221
- await assert.rejects(
222
- call(makeReplaceTool(dir), { path: "f.txt", find: "a", replace: "x", flags: "z" }),
223
- /invalid regex flag/,
224
- );
225
- });
427
+ await withDir(async (dir) => {
428
+ await writeFile(join(dir, "f.txt"), "a\n");
429
+ await assert.rejects(
430
+ callTool(makeReplaceTool(dir), {
431
+ path: "f.txt",
432
+ replacements: [{ find: "a", replace: "x", flags: "z" }],
433
+ }),
434
+ /Validation failed for tool "replace"[\s\S]*flags/,
435
+ );
436
+ });
226
437
  });
227
438
 
228
439
  test("replace: count-but-no-net-change does not rewrite and reports it", async () => {
229
- await withDir(async (dir) => {
230
- const f = join(dir, "f.txt");
231
- await writeFile(f, "xx\n");
232
- // $& = whole match = "x", so the text is unchanged despite 2 matches
233
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "x", replace: "$&", regex: true });
234
- assert.equal(r.isError, undefined);
235
- assert.equal(await readFile(f, "utf-8"), "xx\n");
236
- assert.match(r.content[0].text, /no net change/);
237
- });
440
+ await withDir(async (dir) => {
441
+ const f = join(dir, "f.txt");
442
+ await writeFile(f, "xx\n");
443
+ // $& = whole match = "x", so the text is unchanged despite 2 matches
444
+ const r: any = await call(makeReplaceTool(dir), {
445
+ path: "f.txt",
446
+ replacements: [{ find: "x", replace: "$&", regex: true }],
447
+ });
448
+ assert.equal(r.isError, undefined);
449
+ assert.equal(await readFile(f, "utf-8"), "xx\n");
450
+ assert.match(r.content[0].text, /no net change/);
451
+ });
238
452
  });
239
453
 
240
454
  test("replace: returns details.diff (string) + patch + firstChangedLine", async () => {
241
- await withDir(async (dir) => {
242
- const f = join(dir, "f.txt");
243
- await writeFile(f, "a\nb\nc\n");
244
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "b", replace: "B" });
245
- assert.equal(typeof r.details.diff, "string");
246
- assert.equal(typeof r.details.patch, "string");
247
- assert.equal(typeof r.details.firstChangedLine, "number");
248
- });
455
+ await withDir(async (dir) => {
456
+ const f = join(dir, "f.txt");
457
+ await writeFile(f, "a\nb\nc\n");
458
+ const r: any = await call(makeReplaceTool(dir), {
459
+ path: "f.txt",
460
+ replacements: [{ find: "b", replace: "B" }],
461
+ });
462
+ assert.equal(typeof r.details.diff, "string");
463
+ assert.equal(typeof r.details.patch, "string");
464
+ assert.equal(typeof r.details.firstChangedLine, "number");
465
+ });
249
466
  });
250
467
 
251
468
  test("replace: returns fresh anchors for the changed region", async () => {
252
- await withDir(async (dir) => {
253
- const f = join(dir, "f.txt");
254
- await writeFile(f, "a\nb\nc\n");
255
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "b", replace: "B" });
256
- const out: string = r.content[0].text;
257
- assert.match(out, /Updated anchors/);
258
- // line 2 now holds "B"; its anchor must be present and correct
259
- const a2 = anchorLine(out, 2);
260
- assert.match(a2, /^2#[0-9A-Z]{2,8}$/);
261
- assert.match(out, new RegExp(`^${a2}$`, "m"));
262
- assert.doesNotMatch(out, /│B/);
263
- });
469
+ await withDir(async (dir) => {
470
+ const f = join(dir, "f.txt");
471
+ await writeFile(f, "a\nb\nc\n");
472
+ const r: any = await call(makeReplaceTool(dir), {
473
+ path: "f.txt",
474
+ replacements: [{ find: "b", replace: "B" }],
475
+ });
476
+ const out: string = r.content[0].text;
477
+ assert.match(out, /Updated anchors/);
478
+ // line 2 now holds "B"; its anchor must be present and correct
479
+ const a2 = anchorLine(out, 2);
480
+ assert.match(a2, /^2#[0-9A-Z]{2,8}$/);
481
+ assert.match(out, new RegExp(`^${a2}$`, "m"));
482
+ assert.doesNotMatch(out, /│B/);
483
+ });
264
484
  });
265
485
 
266
486
  test("replace: changed-region anchor chains a subsequent hashline edit without a re-read", async () => {
267
- await withDir(async (dir) => {
268
- const f = join(dir, "f.txt");
269
- await writeFile(f, "old old old\n");
270
- const replace = makeReplaceTool(dir);
271
- const r1: any = await call(replace, { path: "f.txt", find: "old", replace: "new" });
272
- const out: string = r1.content[0].text;
273
- // line 1 is the changed line; chain an edit on its returned anchor
274
- const a1 = anchorLine(out, 1);
275
- const edit = makeEditOverride(dir);
276
- const r2: any = await call(edit, {
277
- path: "f.txt",
278
- edits: [{ op: "replace", anchor: a1, body: ["NEW NEW NEW"] }],
279
- });
280
- assert.equal(r2.isError, undefined);
281
- assert.equal(await readFile(f, "utf-8"), "NEW NEW NEW\n");
282
- });
487
+ await withDir(async (dir) => {
488
+ const f = join(dir, "f.txt");
489
+ await writeFile(f, "old old old\n");
490
+ const replace = makeReplaceTool(dir);
491
+ const r1: any = await call(replace, {
492
+ path: "f.txt",
493
+ replacements: [{ find: "old", replace: "new" }],
494
+ });
495
+ const out: string = r1.content[0].text;
496
+ // line 1 is the changed line; chain an edit on its returned anchor
497
+ const a1 = anchorLine(out, 1);
498
+ const edit = makeEditOverride(dir);
499
+ const r2: any = await call(edit, {
500
+ path: "f.txt",
501
+ edits: [{ op: "replace", anchor: a1, body: ["NEW NEW NEW"] }],
502
+ });
503
+ assert.equal(r2.isError, undefined);
504
+ assert.equal(await readFile(f, "utf-8"), "NEW NEW NEW\n");
505
+ });
283
506
  });
284
507
 
285
508
  test("replace: multiline replacement (changes line count) still reports a correct span", async () => {
286
- await withDir(async (dir) => {
287
- const f = join(dir, "f.txt");
288
- await writeFile(f, "a\nb\nc\n");
289
- // replace "b" with two lines → line count grows; changed region must cover the insertion
290
- const r: any = await call(makeReplaceTool(dir), { path: "f.txt", find: "b", replace: "B1\nB2" });
291
- assert.equal(await readFile(f, "utf-8"), "a\nB1\nB2\nc\n");
292
- const out: string = r.content[0].text;
293
- // the two inserted/changed lines (2 and 3) should both be anchored
294
- assert.doesNotThrow(() => anchorLine(out, 2));
295
- assert.doesNotThrow(() => anchorLine(out, 3));
296
- });
509
+ await withDir(async (dir) => {
510
+ const f = join(dir, "f.txt");
511
+ await writeFile(f, "a\nb\nc\n");
512
+ // replace "b" with two lines → line count grows; changed region must cover the insertion
513
+ const r: any = await call(makeReplaceTool(dir), {
514
+ path: "f.txt",
515
+ replacements: [{ find: "b", replace: "B1\nB2" }],
516
+ });
517
+ assert.equal(await readFile(f, "utf-8"), "a\nB1\nB2\nc\n");
518
+ const out: string = r.content[0].text;
519
+ // the two inserted/changed lines (2 and 3) should both be anchored
520
+ assert.doesNotThrow(() => anchorLine(out, 2));
521
+ assert.doesNotThrow(() => anchorLine(out, 3));
522
+ });
297
523
  });
298
524
 
299
525
  test("replace renderResult: renders the diff without throwing", async () => {
300
- await withDir(async (dir) => {
301
- const f = join(dir, "f.txt");
302
- await writeFile(f, "a\nb\nc\n");
303
- const tool = makeReplaceTool(dir);
304
- const r: any = await call(tool, { path: "f.txt", find: "b", replace: "B" });
305
- // @ts-ignore — drive the renderer with a stub theme
306
- const comp: any = tool.renderResult(
307
- { content: r.content, details: r.details },
308
- { isPartial: false, expanded: true },
309
- stubTheme,
310
- { isError: r.isError ?? false, state: {}, invalidate: () => {} },
311
- );
312
- assert.ok(typeof comp?.text === "string");
313
- assert.ok(comp.text.includes("B"), "rendered diff should contain the new content");
314
- });
526
+ await withDir(async (dir) => {
527
+ const f = join(dir, "f.txt");
528
+ await writeFile(f, "a\nb\nc\n");
529
+ const tool = makeReplaceTool(dir);
530
+ const r: any = await call(tool, { path: "f.txt", replacements: [{ find: "b", replace: "B" }] });
531
+ const comp = tool.renderResult(
532
+ { content: r.content, details: r.details },
533
+ { isPartial: false, expanded: true },
534
+ stubTheme,
535
+ {
536
+ args: { path: "f.txt", replacements: [{ find: "b", replace: "B" }] },
537
+ isError: r.isError ?? false,
538
+ state: {},
539
+ invalidate: () => {},
540
+ } as Parameters<typeof tool.renderResult>[3],
541
+ );
542
+ assert.match(comp.render(80).join("\n"), /B/, "rendered diff should contain the new content");
543
+ });
315
544
  });
316
545
 
317
546
  test("replace renderResult: renders the error line without throwing", async () => {
318
- await withDir(async (dir) => {
319
- const f = join(dir, "f.txt");
320
- await writeFile(f, "a\n");
321
- const tool = makeReplaceTool(dir);
322
- let thrown: any;
323
- const r: any = await call(tool, { path: "f.txt", find: "zzz", replace: "y" }).catch((e: any) => {
324
- thrown = e;
325
- return null;
326
- });
327
- assert.ok(thrown, "expected the call to throw");
328
- // @ts-ignore — simulate how the framework hands the thrown message to renderResult
329
- const comp: any = tool.renderResult(
330
- { content: [{ type: "text", text: thrown.message }] },
331
- { isPartial: false, expanded: false },
332
- stubTheme,
333
- { isError: true },
334
- );
335
- assert.ok(typeof comp?.text === "string");
336
- });
547
+ await withDir(async (dir) => {
548
+ const f = join(dir, "f.txt");
549
+ await writeFile(f, "a\n");
550
+ const tool = makeReplaceTool(dir);
551
+ let thrown: any;
552
+ const r: any = await call(tool, {
553
+ path: "f.txt",
554
+ replacements: [{ find: "zzz", replace: "y" }],
555
+ }).catch((e: any) => {
556
+ thrown = e;
557
+ return null;
558
+ });
559
+ assert.ok(thrown, "expected the call to throw");
560
+ const comp = tool.renderResult(
561
+ {
562
+ content: [{ type: "text", text: thrown.message }],
563
+ details: generateMutationDetails(
564
+ "f.txt",
565
+ "a\n",
566
+ "a\n",
567
+ { publishedRevision: "r", observedRevision: "r" },
568
+ "PUBLISHED",
569
+ ),
570
+ },
571
+ { isPartial: false, expanded: false },
572
+ stubTheme,
573
+ {
574
+ args: { path: "f.txt", replacements: [{ find: "zzz", replace: "y" }] },
575
+ isError: true,
576
+ } as Parameters<typeof tool.renderResult>[3],
577
+ );
578
+ assert.match(comp.render(80).join("\n"), /zero matches|no matches|match/i);
579
+ });
337
580
  });
338
581
 
339
582
  test("replace header: renderResult refreshes the call header in place — no invalidate", async () => {
340
- await withDir(async (dir) => {
341
- const f = join(dir, "f.txt");
342
- await writeFile(f, "a\nb\nc\n");
343
- const tool = makeReplaceTool(dir);
344
- const args = { path: "f.txt", find: "b", replace: "B1\nB2" };
345
- const r: any = await call(tool, args);
346
- let invalidated = false;
347
- const context: any = { args, isError: false, state: {}, invalidate: () => { invalidated = true; } };
348
- const header: any = tool.renderCall(args, stubTheme, context);
349
- assert.ok(!header.text.includes("+2"), "pre-execution header must not show counts");
350
- tool.renderResult({ content: r.content, details: r.details }, { isPartial: false, expanded: true }, stubTheme, context);
351
- assert.deepEqual(context.state.diffCounts, { added: 2, removed: 1 });
352
- assert.ok(header.text.includes("+2"), "header should show added count");
353
- assert.ok(header.text.includes("-1"), "header should show removed count");
354
- assert.ok(!invalidated, "renderResult must not call invalidate");
355
- });
583
+ await withDir(async (dir) => {
584
+ const f = join(dir, "f.txt");
585
+ await writeFile(f, "a\nb\nc\n");
586
+ const tool = makeReplaceTool(dir);
587
+ const args = { path: "f.txt", replacements: [{ find: "b", replace: "B1\nB2" }] };
588
+ const r: any = await call(tool, args);
589
+ let invalidated = false;
590
+ const context: any = {
591
+ args,
592
+ isError: false,
593
+ state: {},
594
+ invalidate: () => {
595
+ invalidated = true;
596
+ },
597
+ };
598
+ const header: any = tool.renderCall(args, stubTheme, context);
599
+ assert.match(header.text, /1 rule\b/);
600
+ assert.ok(!header.text.includes("+2"), "pre-execution header must not show counts");
601
+ tool.renderResult(
602
+ { content: r.content, details: r.details },
603
+ { isPartial: false, expanded: true },
604
+ stubTheme,
605
+ context,
606
+ );
607
+ assert.deepEqual(context.state.diffCounts, { added: 2, removed: 1 });
608
+ assert.ok(header.text.includes("+2"), "header should show added count");
609
+ assert.ok(header.text.includes("-1"), "header should show removed count");
610
+ assert.ok(!invalidated, "renderResult must not call invalidate");
611
+ });
612
+ });
613
+
614
+ test("replace header retains the rule count when a long path wraps", () => {
615
+ const tool = makeReplaceTool(process.cwd());
616
+ const args = {
617
+ path: "x".repeat(68),
618
+ replacements: [
619
+ { find: "first", replace: "second" },
620
+ { find: "third", replace: "fourth" },
621
+ ],
622
+ };
623
+ const header = tool.renderCall(args, stubTheme, {} as Parameters<typeof tool.renderCall>[2]);
624
+ assert.match(header.render(120).join("\n"), /2 rules/);
625
+ assert.match(header.render(80).join("\n"), /2\s+rules/);
356
626
  });
357
627
 
358
- test("replacement batches use one snapshot and return anchors for the final content", async () => withDir(async (dir) => {
359
- const file = join(dir, "batch.txt");
360
- const tool = makeReplaceTool(dir);
361
- const args = { path: file, replacements: [{ find: "foo", replace: "bar" }, { find: "bar", replace: "baz" }] };
362
- validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
363
- await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
364
- const result = await call(tool, args);
365
- assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
366
- assert.match(result.content[0].text, /3 matches/);
367
- assert.match(result.details.diff, /^\+2 baz/m);
368
- await call(makeEditOverride(dir), { path: file, edits: [{ op: "replace", anchor: anchorLine(result.content[0].text, 2), body: ["chained"] }] });
369
- assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nchained\nbar");
370
- assert.match(tool.renderCall(args, stubTheme, {}).text, /2 rules/);
371
- }));
372
-
373
- test("invalid batches reject every change and skip the fused command", async () => withDir(async (dir) => {
374
- const file = join(dir, "batch.txt");
375
- const before = "foo bar foo";
376
- await writeFile(file, before);
377
- let commands = 0;
378
- const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => { commands++; return "done"; }));
379
- const first = { find: "bar", replace: "changed" };
380
- const cases = [
381
- { replacements: [first, { find: "missing", replace: "x" }] },
382
- { replacements: [first, { find: "foo", replace: "x", maxMatches: 1 }] },
383
- { replacements: [first, { find: "(", replace: "x", regex: true }] },
384
- { replacements: [first, { find: "bar foo", replace: "x" }] },
385
- { replacements: [first, { find: "bar", replace: "x" }] },
386
- { replacements: [first, { find: "foo", replace: "\0" }] },
387
- { replacements: [first, { find: "foo", replace: "\ud800" }] },
388
- { replacements: [first, { find: "foo", replace: "x", maxMatches: NaN }] },
389
- { replacements: [first, { find: "foo", replace: "x", maxMatches: Infinity }] },
390
- { replacements: [first, { find: "", replace: "x" }] },
391
- { replacements: [first, { find: "foo" }] },
392
- { replacements: [] },
393
- { replacements: [first], find: "foo", replace: "x" },
394
- { replacements: [first], flags: "i" },
395
- {},
396
- ];
397
- for (const args of cases) {
398
- await assert.rejects(tool.execute("0", { path: file, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }), /then_run:skipped/);
399
- assert.equal(await readFile(file, "utf8"), before);
400
- }
401
- assert.equal(commands, 0);
402
- }));
403
-
404
- test("adjacent matches and zero-width boundaries have deterministic batch semantics", async () => withDir(async (dir) => {
405
- const file = join(dir, "batch.txt");
406
- const tool = makeReplaceTool(dir);
407
- for (const rules of [
408
- [{ find: "a", replace: "b" }, { find: "b", replace: "a" }],
409
- [{ find: "b", replace: "a" }, { find: "a", replace: "b" }],
410
- ]) {
411
- await writeFile(file, "ab");
412
- await call(tool, { path: file, replacements: rules });
413
- assert.equal(await readFile(file, "utf8"), "ba");
414
- }
415
- for (const find of ["^", "(?=b)", "$"]) {
416
- await writeFile(file, "ab");
417
- const args = { path: file, replacements: [{ find: "ab", replace: "X" }, { find, replace: "!", regex: true }] };
418
- if (find === "$") {
419
- await call(tool, args);
420
- assert.equal(await readFile(file, "utf8"), "X!");
421
- } else {
422
- await assert.rejects(call(tool, args), /overlap/);
423
- assert.equal(await readFile(file, "utf8"), "ab");
424
- }
425
- }
426
- await writeFile(file, "ab");
427
- await assert.rejects(call(tool, { path: file, replacements: [{ find: "^", replace: "x", regex: true }, { find: "(?=a)", replace: "y", regex: true }] }), /overlap/);
428
- }));
429
-
430
- test("regex templates agree with native replacement in single and snapshot batch modes", async () => withDir(async (dir) => {
431
- const file = join(dir, "regex.txt");
432
- const tool = makeReplaceTool(dir);
433
- const template = "$$|$&|$`|$'|$0|$00|$01|$1|$2|$10|$12|$99|$<x>|$<missing>|$<>|$<$&>|$<unclosed$1|$";
434
- for (const [source, find, flags] of [
435
- ["ab b#", "(?<x>a)?b", "g"],
436
- ["ab b#", "(a)?b", "g"],
437
- ["ab#", "ab", "g"],
438
- ["abcdefghijkl#", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)", "g"],
439
- ["ab ab#", "(?<=a)(b)", "g"],
440
- ["ab#", "(?=b)", "g"],
441
- ["😀#", "(?=[^#])", "gu"],
442
- ["aab#", "(a)", "gy"],
443
- ]) {
444
- const rule = { find, replace: template, regex: true, flags };
445
- const expected = source.replace(new RegExp(find, flags), template);
446
- for (const batch of [false, true]) {
447
- await writeFile(file, source);
448
- // The second rule changes only the original final sentinel, not copies inserted by $' or $`.
449
- const args = batch ? { replacements: [rule, { find: "#$", replace: "!", regex: true }] } : rule;
450
- await call(tool, { path: file, ...args });
451
- assert.equal(await readFile(file, "utf8"), batch ? expected.slice(0, -1) + "!" : expected, `${find}/${flags}; batch=${batch}`);
452
- }
453
- }
454
- }));
455
-
456
- test("successful batches run one command against the complete result", async () => withDir(async (dir) => {
457
- const file = join(dir, "batch.txt");
458
- await writeFile(file, "foo bar");
459
- let commands = 0;
460
- const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => {
461
- commands++;
462
- assert.equal(await readFile(file, "utf8"), "bar baz");
463
- return "checked";
464
- }));
465
- const result = await tool.execute("0", { path: file, replacements: [{ find: "foo", replace: "bar", maxMatches: 1 }, { find: "bar", replace: "baz", maxMatches: 1 }], then_run: { command: "check" } }, undefined, undefined, { cwd: dir });
466
- assert.equal(commands, 1);
467
- assert.equal(result.details.actionFusion.command, "succeeded");
468
- assert.match(result.content[0].text, /Updated anchors/);
469
- }));
470
-
471
- test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () => withDir(async (dir) => {
472
- const path = join(dir, "f.txt");
473
- const before = "a\r\nb\rc\r\r\n";
474
- await writeFile(path, before);
475
- await call(makeReplaceTool(dir), { path, find: "(b\rc\r)\\n", replace: "$1\n", regex: true });
476
- assert.equal(await readFile(path, "utf8"), before);
477
- await call(makeReplaceTool(dir), { path, find: "(?=\\n)", replace: "!", regex: true });
478
- assert.equal(await readFile(path, "utf8"), "a!\r\nb\rc\r!\r\n");
479
- }));
628
+ test("replacement batches use one snapshot and return anchors for the final content", async () =>
629
+ withDir(async (dir) => {
630
+ const file = join(dir, "batch.txt");
631
+ const tool = makeReplaceTool(dir);
632
+ const args = {
633
+ path: file,
634
+ replacements: [
635
+ { find: "foo", replace: "bar" },
636
+ { find: "bar", replace: "baz" },
637
+ ],
638
+ };
639
+ validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
640
+ await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
641
+ const result = await call(tool, args);
642
+ assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
643
+ assert.match(result.content[0].text, /3 matches/);
644
+ assert.match(result.details.diff, /^\+2 baz/m);
645
+ await call(makeEditOverride(dir), {
646
+ path: file,
647
+ edits: [{ op: "replace", anchor: anchorLine(result.content[0].text, 2), body: ["chained"] }],
648
+ });
649
+ assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nchained\nbar");
650
+ }));
651
+
652
+ test("invalid batches reject every change and never run a fused command", async () =>
653
+ withDir(async (dir) => {
654
+ const file = join(dir, "batch.txt");
655
+ const before = "foo bar foo";
656
+ await writeFile(file, before);
657
+ let commands = 0;
658
+ const tool = makeReplaceTool(
659
+ dir,
660
+ createActionFusionExecutor(async () => {
661
+ commands++;
662
+ return "done";
663
+ }),
664
+ );
665
+ const first = { find: "bar", replace: "changed" };
666
+ const cases = [
667
+ [
668
+ /then_run:skipped/,
669
+ [
670
+ { replacements: [first, { find: "missing", replace: "x" }] },
671
+ { replacements: [first, { find: "bar foo", replace: "x" }] },
672
+ { replacements: [first, { find: "bar", replace: "x" }] },
673
+ ],
674
+ ],
675
+ [
676
+ /Invalid argument replacements\[1\]\.find: invalid regex/,
677
+ [{ replacements: [first, { find: "(", replace: "x", regex: true }] }],
678
+ ],
679
+ [
680
+ /Invalid argument replacements\[1\]\.replace: UNSUPPORTED_TEXT: NUL bytes are not editable\./,
681
+ [{ replacements: [first, { find: "foo", replace: "\0" }] }],
682
+ ],
683
+ [
684
+ /Invalid argument replacements\[1\]\.replace: INVALID_UNICODE: content cannot be encoded losslessly as UTF-8\./,
685
+ [{ replacements: [first, { find: "foo", replace: "\ud800" }] }],
686
+ ],
687
+ [
688
+ /Validation failed for tool "replace"/,
689
+ [
690
+ { replacements: [first, { find: "", replace: "x" }] },
691
+ { replacements: [first, { find: "foo" }] },
692
+ { replacements: [] },
693
+ { replacements: [first], find: "foo", replace: "x" },
694
+ { replacements: [first], flags: "i" },
695
+ {},
696
+ ],
697
+ ],
698
+ ] as const;
699
+ for (const [expected, inputs] of cases) {
700
+ for (const args of inputs) {
701
+ await assert.rejects(
702
+ callTool(
703
+ tool,
704
+ { path: file, ...args, then_run: { command: "check" } },
705
+ {
706
+ ctx: { cwd: dir },
707
+ },
708
+ ),
709
+ expected,
710
+ );
711
+ assert.equal(await readFile(file, "utf8"), before);
712
+ }
713
+ }
714
+ assert.equal(commands, 0);
715
+ }));
716
+
717
+ test("adjacent matches and zero-width boundaries have deterministic batch semantics", async () =>
718
+ withDir(async (dir) => {
719
+ const file = join(dir, "batch.txt");
720
+ const tool = makeReplaceTool(dir);
721
+ for (const rules of [
722
+ [
723
+ { find: "a", replace: "b" },
724
+ { find: "b", replace: "a" },
725
+ ],
726
+ [
727
+ { find: "b", replace: "a" },
728
+ { find: "a", replace: "b" },
729
+ ],
730
+ ]) {
731
+ await writeFile(file, "ab");
732
+ await call(tool, { path: file, replacements: rules });
733
+ assert.equal(await readFile(file, "utf8"), "ba");
734
+ }
735
+ for (const find of ["^", "(?=b)", "$"]) {
736
+ await writeFile(file, "ab");
737
+ const args = {
738
+ path: file,
739
+ replacements: [
740
+ { find: "ab", replace: "X" },
741
+ { find, replace: "!", regex: true },
742
+ ],
743
+ };
744
+ if (find === "$") {
745
+ await call(tool, args);
746
+ assert.equal(await readFile(file, "utf8"), "X!");
747
+ } else {
748
+ await assert.rejects(call(tool, args), /overlap/);
749
+ assert.equal(await readFile(file, "utf8"), "ab");
750
+ }
751
+ }
752
+ await writeFile(file, "ab");
753
+ await assert.rejects(
754
+ call(tool, {
755
+ path: file,
756
+ replacements: [
757
+ { find: "^", replace: "x", regex: true },
758
+ { find: "(?=a)", replace: "y", regex: true },
759
+ ],
760
+ }),
761
+ /overlap/,
762
+ );
763
+ }));
764
+
765
+ test("regex templates agree with native replacement in single and snapshot batch modes", async () =>
766
+ withDir(async (dir) => {
767
+ const file = join(dir, "regex.txt");
768
+ const tool = makeReplaceTool(dir);
769
+ const template =
770
+ "$$|$&|$`|$'|$0|$00|$01|$1|$2|$10|$12|$99|$<x>|$<missing>|$<>|$<$&>|$<unclosed$1|$";
771
+ for (const [source, find, flags] of [
772
+ ["ab b#", "(?<x>a)?b", "g"],
773
+ ["ab b#", "(a)?b", "g"],
774
+ ["ab#", "ab", "g"],
775
+ ["abcdefghijkl#", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)", "g"],
776
+ ["ab ab#", "(?<=a)(b)", "g"],
777
+ ["ab#", "(?=b)", "g"],
778
+ ["😀#", "(?=[^#])", "gu"],
779
+ ["aab#", "(a)", "gy"],
780
+ ]) {
781
+ const rule = { find, replace: template, regex: true, flags };
782
+ const expected = source.replace(new RegExp(find, flags), template);
783
+ for (const batch of [false, true]) {
784
+ await writeFile(file, source);
785
+ // The second rule changes only the original final sentinel, not copies inserted by $' or $`.
786
+ const args = batch
787
+ ? { replacements: [rule, { find: "#$", replace: "!", regex: true }] }
788
+ : { replacements: [rule] };
789
+ await call(tool, { path: file, ...args });
790
+ assert.equal(
791
+ await readFile(file, "utf8"),
792
+ batch ? expected.slice(0, -1) + "!" : expected,
793
+ `${find}/${flags}; batch=${batch}`,
794
+ );
795
+ }
796
+ }
797
+ }));
798
+
799
+ test("successful batches run one command against the complete result", async () =>
800
+ withDir(async (dir) => {
801
+ const file = join(dir, "batch.txt");
802
+ await writeFile(file, "foo bar");
803
+ let commands = 0;
804
+ const tool = makeReplaceTool(
805
+ dir,
806
+ createActionFusionExecutor(async () => {
807
+ commands++;
808
+ assert.equal(await readFile(file, "utf8"), "bar baz");
809
+ return "checked";
810
+ }),
811
+ );
812
+ const result = await tool.execute(
813
+ "0",
814
+ {
815
+ path: file,
816
+ replacements: [
817
+ { find: "foo", replace: "bar" },
818
+ { find: "bar", replace: "baz" },
819
+ ],
820
+ then_run: { command: "check" },
821
+ },
822
+ undefined,
823
+ undefined,
824
+ { cwd: dir } as Parameters<typeof tool.execute>[4],
825
+ );
826
+ assert.equal(commands, 1);
827
+ assert.ok(result.details.actionFusion);
828
+ assert.equal(result.details.actionFusion.command, "succeeded");
829
+ assert.ok(result.content[0].type === "text");
830
+ assert.match(result.content[0].text, /Updated anchors/);
831
+ }));
832
+
833
+ test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () =>
834
+ withDir(async (dir) => {
835
+ const path = join(dir, "f.txt");
836
+ const before = "a\r\nb\rc\r\r\n";
837
+ await writeFile(path, before);
838
+ await call(makeReplaceTool(dir), {
839
+ path,
840
+ replacements: [{ find: "(b\rc\r)\\n", replace: "$1\n", regex: true }],
841
+ });
842
+ assert.equal(await readFile(path, "utf8"), before);
843
+ await call(makeReplaceTool(dir), {
844
+ path,
845
+ replacements: [{ find: "(?=\\n)", replace: "!", regex: true }],
846
+ });
847
+ assert.equal(await readFile(path, "utf8"), "a!\r\nb\rc\r!\r\n");
848
+ }));
849
+
850
+ test("replace rejects JSON-string rules without publishing", async () =>
851
+ withDir(async (dir) => {
852
+ const file = join(dir, "f.txt");
853
+ await writeFile(file, "hello foo world");
854
+ const tool = makeReplaceTool(dir);
855
+ await assert.rejects(
856
+ callTool(tool, {
857
+ path: "f.txt",
858
+ replacements: JSON.stringify([{ find: "foo", replace: "bar" }]),
859
+ }),
860
+ /Validation failed for tool "replace"[\s\S]*replacements/,
861
+ );
862
+ assert.equal(await readFile(file, "utf8"), "hello foo world");
863
+ }));