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