@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,634 +0,0 @@
1
- import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
2
- import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
3
- /** Tool-level replace contracts: byte preservation, matching, and failures. */
4
- import { test } from "node:test";
5
- import assert from "node:assert/strict";
6
- import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
- import { initTheme, type Theme } from "@earendil-works/pi-coding-agent";
10
- import { makeReplaceTool } from "./tool-factories.testing.ts";
11
- import { validateToolArguments } from "@earendil-works/pi-ai";
12
- import { callTool } from "./tool-call.testing.ts";
13
- import { createActionFusionExecutor } from "./action-fusion.ts";
14
- import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
15
- import { reportOf } from "./report.ts";
16
-
17
- async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
18
- const dir = await mkdtemp(join(tmpdir(), "hl-replace-"));
19
- try {
20
- return await fn(dir);
21
- } finally {
22
- await rm(dir, { recursive: true, force: true });
23
- }
24
- }
25
-
26
- const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
27
-
28
- const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
29
-
30
- // renderResult delegates to pi's renderDiff, which reads the global TUI theme
31
- // singleton — initialize it once for this test process (watcher off by default).
32
- initTheme();
33
-
34
- test("replace rejects invalid rule shapes → precise fields and no publication or commands", async () =>
35
- withDir(async (dir) => {
36
- const path = join(dir, "f.txt");
37
- await writeFile(path, "old\n");
38
- let commands = 0;
39
- const executeTool: SessionCommand = async () => {
40
- commands++;
41
- return commandCompletion({ content: [] });
42
- };
43
- const fusion = createActionFusionExecutor(() => {});
44
- const rule = { literal: true, find: "old", replace: "new" };
45
- for (const executor of [undefined, fusion]) {
46
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG, executor);
47
- for (const [args, field, reason] of [
48
- [{ find: "old", replace: "new" }, "replacements", /required/],
49
- [{ replacements: [] }, "replacements", /./],
50
- [{ replacements: [rule], find: "old" }, "find", /not allowed/],
51
- [{ replacements: JSON.stringify([rule]) }, "replacements[0]", /object/],
52
- ...[1, null, false].map(
53
- (maxMatches) =>
54
- [
55
- { replacements: [{ ...rule, maxMatches }] },
56
- "replacements[0].maxMatches",
57
- /not allowed/,
58
- ] as const,
59
- ),
60
- [{ path: "", replacements: [rule] }, "path", /./],
61
- [{ replacements: [{ ...rule, find: "" }] }, "replacements[0].find", /./],
62
- ] as const) {
63
- await assert.rejects(
64
- callTool(
65
- tool,
66
- {
67
- path,
68
- ...args,
69
- ...(executor ? { then_run: { command: "check" } } : {}),
70
- },
71
- { ctx: { cwd: dir, executeTool } },
72
- ),
73
- rejectsArgument(field, reason),
74
- );
75
- assert.equal(await readFile(path, "utf8"), "old\n");
76
- }
77
- }
78
- assert.equal(commands, 0);
79
- }));
80
-
81
- test("replace rules omit literal or retain regex → reject before publication and fused commands", async () =>
82
- withDir(async (dir) => {
83
- const path = join(dir, "f.txt");
84
- await writeFile(path, "old\n");
85
- let commands = 0;
86
- const executeTool: SessionCommand = async () => {
87
- commands++;
88
- return commandCompletion({ content: [] });
89
- };
90
- const tool = makeReplaceTool(
91
- dir,
92
- DEFAULT_CONFIG,
93
- createActionFusionExecutor(() => {}),
94
- );
95
- for (const [rule, field, reason] of [
96
- [{ find: "old", replace: "new" }, "literal", /required/],
97
- [{ find: "old", replace: "new", literal: true, regex: true }, "regex", /not allowed/],
98
- [{ find: "old", replace: "new", literal: true, regex: false }, "regex", /not allowed/],
99
- ] as const) {
100
- await assert.rejects(
101
- callTool(
102
- tool,
103
- {
104
- path,
105
- replacements: [{ find: "old", literal: true, replace: "first" }, rule],
106
- then_run: { command: "check" },
107
- },
108
- { ctx: { cwd: dir, executeTool } },
109
- ),
110
- rejectsArgument(`replacements[1].${field}`, reason),
111
- );
112
- assert.equal(await readFile(path, "utf8"), "old\n");
113
- }
114
- assert.equal(commands, 0);
115
- }));
116
-
117
- test("replace rejects unwritable text and invalid regex before reading a missing target", async () =>
118
- withDir(async (dir) => {
119
- const file = join(dir, "missing.txt");
120
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
121
- for (const [rule, expected] of [
122
- [
123
- { literal: true, find: "x", replace: "\0" },
124
- rejectsArgument("replacements[0].replace", /NUL/),
125
- ],
126
- [
127
- { literal: true, find: "x", replace: "\ud800" },
128
- rejectsArgument("replacements[0].replace", /losslessly.*UTF-8/),
129
- ],
130
- [
131
- { find: "(", replace: "x", literal: false },
132
- rejectsArgument("replacements[0].find", /Invalid regular expression/i),
133
- ],
134
- ] as const) {
135
- await assert.rejects(callTool(tool, { path: file, replacements: [rule] }), expected);
136
- await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
137
- }
138
- }));
139
-
140
- test("replace literal: replaces all occurrences", async () => {
141
- await withDir(async (dir) => {
142
- const f = join(dir, "f.txt");
143
- await writeFile(f, "foo bar foo baz foo\n");
144
- const r: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
145
- path: "f.txt",
146
- replacements: [{ literal: true, find: "foo", replace: "qux" }],
147
- });
148
- assert.equal(r.isError, undefined);
149
- assert.equal(await readFile(f, "utf-8"), "qux bar qux baz qux\n");
150
- assert.equal(reportOf(r, "replace")?.matches, 3);
151
- });
152
- });
153
-
154
- test("literal multiline replace matches LF and CRLF while retaining local separators", async () =>
155
- withDir(async (dir) => {
156
- const file = join(dir, "mixed.txt");
157
- await writeFile(file, "\uFEFFhead\r\nold\r\none\r\nmid\nold\none\nend\r\n");
158
- const result: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
159
- path: "mixed.txt",
160
- replacements: [{ literal: true, find: "old\none", replace: "NEW\nX" }],
161
- });
162
- assert.equal(reportOf(result, "replace")?.matches, 2);
163
- assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
164
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
165
- path: "mixed.txt",
166
- replacements: [{ literal: true, find: "NEW\r\nX", replace: "done" }],
167
- });
168
- assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\ndone\r\nmid\ndone\nend\r\n");
169
- }));
170
-
171
- test("both replacement modes preserve each matched separator", async () =>
172
- withDir(async (dir) => {
173
- const file = join(dir, "mixed.txt");
174
- for (const literal of [true, false]) {
175
- await writeFile(file, "a\r\nb\nc\r\ntail\n");
176
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
177
- path: "mixed.txt",
178
- replacements: [{ find: "a\nb\nc", replace: "x\ny\nz\nextra", literal }],
179
- });
180
- assert.equal(await readFile(file, "utf8"), "x\r\ny\nz\nextra\r\ntail\n");
181
- }
182
- }));
183
-
184
- test("literal replacement uses one LF view and preserves raw bytes across query styles", async () =>
185
- withDir(async (dir) => {
186
- const file = join(dir, "f.txt");
187
- for (const find of ["a\nb\nc", "a\r\nb\r\nc", "a\r\nb\nc"]) {
188
- const before = "\uFEFFhead\r\na\r\nb\nc\rtail";
189
- await writeFile(file, before);
190
- const result = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
191
- path: file,
192
- replacements: [{ literal: true, find, replace: find }],
193
- });
194
- assert.equal(await readFile(file, "utf8"), before);
195
- assert.equal(reportOf(result, "replace")?.matches, 1);
196
- assert.equal(reportOf(result, "replace")?.publication, "NOT_PUBLISHED");
197
- }
198
- for (const [before, find, replacement, expected] of [
199
- ["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
200
- ["a\nb", "a\r\nb", "A\r\nB", "A\nB"],
201
- ["a\r\nb", "\n", "", "ab"],
202
- ["a\r\nb", "\n", "\n", "a\r\nb"],
203
- ["a\rb\r\r\nc", "a\rb\r\r\nc", "x\ry\r\r\nz", "x\ry\r\r\nz"],
204
- ]) {
205
- await writeFile(file, before);
206
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
207
- path: file,
208
- replacements: [{ literal: true, find, replace: replacement }],
209
- });
210
- assert.equal(await readFile(file, "utf8"), expected);
211
- }
212
- }));
213
-
214
- test("mixed literal and regex batches share raw offsets after CRLF normalization", async () =>
215
- withDir(async (dir) => {
216
- const file = join(dir, "f.txt");
217
- await writeFile(file, "😀\r\na\r\nb\r\nc");
218
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
219
- path: file,
220
- replacements: [
221
- { literal: true, find: "a\nb", replace: "A\nB" },
222
- { find: "(c)$", replace: "$1!", literal: false },
223
- ],
224
- });
225
- assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
226
- const before = await readFile(file, "utf8");
227
- const failed = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
228
- path: file,
229
- replacements: [
230
- { literal: true, find: "A\nB", replace: "x" },
231
- { find: "\\nB", replace: "y", literal: false },
232
- ],
233
- });
234
- assert.equal(failed.isError, true);
235
- assert.equal(reportOf(failed, "replace")?.error, "OVERLAPPING_MATCHES");
236
- assert.deepEqual(reportOf(failed, "replace")?.conflict, ["replacements[0]", "replacements[1]"]);
237
- assert.equal(reportOf(failed, "replace")?.line, 2);
238
- assert.ok(reportOf(failed, "replace")?.next);
239
- assert.equal(await readFile(file, "utf8"), before);
240
- }));
241
-
242
- test("replace literal: $ in replacement stays literal (no expansion)", async () => {
243
- await withDir(async (dir) => {
244
- const f = join(dir, "f.txt");
245
- await writeFile(f, "cost: $5 here\n");
246
- const r: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
247
- path: "f.txt",
248
- replacements: [{ literal: true, find: "$5", replace: "$1|$<name>|$&|$$" }],
249
- });
250
- assert.equal(r.isError, undefined);
251
- assert.equal(await readFile(f, "utf-8"), "cost: $1|$<name>|$&|$$ here\n");
252
- });
253
- });
254
-
255
- test("replace literal: case-insensitive via flags", async () => {
256
- await withDir(async (dir) => {
257
- const f = join(dir, "f.txt");
258
- await writeFile(f, "Foo fOo FOO\n");
259
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
260
- path: "f.txt",
261
- replacements: [{ literal: true, find: "foo", replace: "x", flags: "i" }],
262
- });
263
- assert.equal(await readFile(f, "utf-8"), "x x x\n");
264
- });
265
- });
266
-
267
- test("replace aborts catastrophic regex without blocking the event loop or publishing", async () => {
268
- await withDir(async (dir) => {
269
- const file = join(dir, "f.txt");
270
- const before = `${"a".repeat(30)}!`;
271
- await writeFile(file, before);
272
- const controller = new AbortController();
273
- const timer = setTimeout(() => controller.abort(), 100);
274
- const start = performance.now();
275
- try {
276
- const failed = await callTool(
277
- makeReplaceTool(dir, DEFAULT_CONFIG),
278
- { path: file, replacements: [{ find: "^(a+)+$", replace: "x", literal: false }] },
279
- { toolCallId: "abort", signal: controller.signal, ctx: { cwd: dir } },
280
- );
281
- assert.equal(failed.isError, true);
282
- assert.equal(reportOf(failed, "replace")?.error, "OPERATION_ABORTED");
283
- assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
284
- assert.ok(performance.now() - start < 2000);
285
- assert.equal(await readFile(file, "utf8"), before);
286
- } finally {
287
- clearTimeout(timer);
288
- }
289
- });
290
- });
291
- test("replace times out catastrophic regex at the configured limit without publishing", async () => {
292
- await withDir(async (dir) => {
293
- const file = join(dir, "f.txt");
294
- const before = `${"a".repeat(35)}!`;
295
- await writeFile(file, before);
296
- const config = { ...DEFAULT_CONFIG, replace: { regexTimeoutMs: 1_000 } };
297
- const failed = await call(makeReplaceTool(dir, config), {
298
- path: file,
299
- replacements: [{ find: "^(a+)+$", replace: "x", literal: false }],
300
- });
301
- assert.equal(failed.isError, true);
302
- assert.equal(reportOf(failed, "replace")?.error, "REGEX_TIMEOUT");
303
- assert.equal(reportOf(failed, "replace")?.timeoutMs, config.replace.regexTimeoutMs);
304
- assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
305
- assert.equal(await readFile(file, "utf8"), before);
306
- });
307
- });
308
-
309
- test("replace regex: capture groups in replacement", async () => {
310
- await withDir(async (dir) => {
311
- const f = join(dir, "f.txt");
312
- await writeFile(f, "name: alice\nname: bob\n");
313
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
314
- path: "f.txt",
315
- replacements: [{ find: "name: (\\w+)", replace: "user: $1", literal: false }],
316
- });
317
- assert.equal(await readFile(f, "utf-8"), "user: alice\nuser: bob\n");
318
- });
319
- });
320
-
321
- test("replace regex: multiline flag matches line-anchored pattern", async () => {
322
- await withDir(async (dir) => {
323
- const f = join(dir, "f.txt");
324
- await writeFile(f, "a\nb\nc\n");
325
- // without `m`, ^a$ wouldn't match (a isn't at end of string); with `m` it does
326
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
327
- path: "f.txt",
328
- replacements: [{ find: "^a$", replace: "A", literal: false, flags: "m" }],
329
- });
330
- assert.equal(await readFile(f, "utf-8"), "A\nb\nc\n");
331
- });
332
- });
333
-
334
- test("replace regex: dotall flag makes . match newlines", async () => {
335
- await withDir(async (dir) => {
336
- const f = join(dir, "f.txt");
337
- await writeFile(f, "a\nb\n");
338
- // a.b only matches across the newline with the `s` (dotall) flag
339
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
340
- path: "f.txt",
341
- replacements: [{ find: "a.b", replace: "X", literal: false, flags: "s" }],
342
- });
343
- assert.equal(await readFile(f, "utf-8"), "X\n");
344
- });
345
- });
346
-
347
- test("replace finds no matches → returns failure and leaves file untouched", async () => {
348
- await withDir(async (dir) => {
349
- const f = join(dir, "f.txt");
350
- await writeFile(f, "a\nb\n");
351
- const failed = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
352
- path: "f.txt",
353
- replacements: [{ literal: true, find: "zzz", replace: "y" }],
354
- });
355
- assert.equal(failed.isError, true);
356
- assert.equal(reportOf(failed, "replace")?.error, "NO_MATCH");
357
- assert.deepEqual(reportOf(failed, "replace")?.unmatched, ["replacements[0]"]);
358
- assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
359
- assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
360
- });
361
- });
362
-
363
- test("replace: count-but-no-net-change does not rewrite and reports it", async () => {
364
- await withDir(async (dir) => {
365
- const f = join(dir, "f.txt");
366
- await writeFile(f, "xx\n");
367
- // $& = whole match = "x", so the text is unchanged despite 2 matches
368
- const r: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
369
- path: "f.txt",
370
- replacements: [{ find: "x", replace: "$&", literal: false }],
371
- });
372
- assert.equal(r.isError, undefined);
373
- assert.equal(await readFile(f, "utf-8"), "xx\n");
374
- assert.equal(reportOf(r, "replace")?.publication, "NOT_PUBLISHED");
375
- assert.equal(reportOf(r, "replace")?.matches, 2);
376
- assert.equal(r.details.diff, "");
377
- });
378
- });
379
-
380
- test("multiline replacement → preserves the surrounding file text", async () => {
381
- await withDir(async (dir) => {
382
- const f = join(dir, "f.txt");
383
- await writeFile(f, "a\nb\nc\n");
384
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
385
- path: "f.txt",
386
- replacements: [{ literal: true, find: "b", replace: "B1\nB2" }],
387
- });
388
- assert.equal(await readFile(f, "utf-8"), "a\nB1\nB2\nc\n");
389
- });
390
- });
391
-
392
- test("replace header retains the rule count when a long path wraps", () => {
393
- const tool = makeReplaceTool(process.cwd(), DEFAULT_CONFIG);
394
- const args = {
395
- path: "x".repeat(68),
396
- replacements: [
397
- { literal: true, find: "first", replace: "second" },
398
- { literal: true, find: "third", replace: "fourth" },
399
- ],
400
- };
401
- const header = tool.renderCall(args, stubTheme, {
402
- state: {},
403
- } as Parameters<typeof tool.renderCall>[2]);
404
- assert.match(header.render(120).join("\n"), /2 rules/);
405
- assert.match(header.render(80).join("\n"), /2\s+rules/);
406
- });
407
-
408
- test("replacement batches → evaluate every rule against one snapshot", async () =>
409
- withDir(async (dir) => {
410
- const file = join(dir, "batch.txt");
411
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
412
- const args = {
413
- path: file,
414
- replacements: [
415
- { literal: true, find: "foo", replace: "bar" },
416
- { literal: true, find: "bar", replace: "baz" },
417
- ],
418
- };
419
- validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
420
- await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
421
- const result = await call(tool, args);
422
- assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
423
- assert.equal(reportOf(result, "replace")?.matches, 3);
424
- assert.match(result.details.diff, /^\+2 baz/m);
425
- }));
426
-
427
- test("invalid batches reject every change and never run a fused command", async () =>
428
- withDir(async (dir) => {
429
- const file = join(dir, "batch.txt");
430
- const before = "foo bar foo";
431
- await writeFile(file, before);
432
- let commands = 0;
433
- const executeTool: SessionCommand = async () => {
434
- commands++;
435
- return commandCompletion({ content: [{ type: "text", text: "done" }] });
436
- };
437
- const tool = makeReplaceTool(
438
- dir,
439
- DEFAULT_CONFIG,
440
- createActionFusionExecutor(() => {}),
441
- );
442
- const first = { literal: true, find: "bar", replace: "changed" };
443
- const cases = [
444
- [
445
- rejectsArgument("replacements[1].find", /Invalid regular expression/i),
446
- [{ replacements: [first, { find: "(", replace: "x", literal: false }] }],
447
- ],
448
- [
449
- rejectsArgument("replacements[1].replace", /NUL/),
450
- [{ replacements: [first, { literal: true, find: "foo", replace: "\0" }] }],
451
- ],
452
- [
453
- rejectsArgument("replacements[1].replace", /losslessly.*UTF-8/),
454
- [{ replacements: [first, { literal: true, find: "foo", replace: "\ud800" }] }],
455
- ],
456
- [
457
- rejectsArguments(),
458
- [
459
- { replacements: [first, { literal: true, find: "", replace: "x" }] },
460
- { replacements: [first, { literal: true, find: "foo" }] },
461
- { replacements: [] },
462
- { replacements: [first], find: "foo", replace: "x" },
463
- { replacements: [first], flags: "i" },
464
- {},
465
- ],
466
- ],
467
- ] as const;
468
- for (const [rule, code] of [
469
- [{ literal: true, find: "missing", replace: "x" }, "NO_MATCH"],
470
- [{ literal: true, find: "bar foo", replace: "x" }, "OVERLAPPING_MATCHES"],
471
- [{ literal: true, find: "bar", replace: "x" }, "OVERLAPPING_MATCHES"],
472
- ] as const) {
473
- const failed = await callTool(
474
- tool,
475
- { path: file, replacements: [first, rule], then_run: { command: "check" } },
476
- { ctx: { ...{ cwd: dir }, executeTool } },
477
- );
478
- assert.equal(failed.isError, true);
479
- assert.equal(reportOf(failed, "replace")?.error, code);
480
- assert.equal(reportOf(failed, "replace")?.then_run?.status, "skipped");
481
- assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
482
- assert.equal(await readFile(file, "utf8"), before);
483
- }
484
- for (const [expected, inputs] of cases) {
485
- for (const args of inputs) {
486
- await assert.rejects(
487
- callTool(
488
- tool,
489
- { path: file, ...args, then_run: { command: "check" } },
490
- { ctx: { ...{ cwd: dir }, executeTool } },
491
- ),
492
- expected,
493
- );
494
- assert.equal(await readFile(file, "utf8"), before);
495
- }
496
- }
497
- assert.equal(commands, 0);
498
- }));
499
-
500
- test("adjacent matches and zero-width boundaries have deterministic batch semantics", async () =>
501
- withDir(async (dir) => {
502
- const file = join(dir, "batch.txt");
503
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
504
- for (const rules of [
505
- [
506
- { literal: true, find: "a", replace: "b" },
507
- { literal: true, find: "b", replace: "a" },
508
- ],
509
- [
510
- { literal: true, find: "b", replace: "a" },
511
- { literal: true, find: "a", replace: "b" },
512
- ],
513
- ]) {
514
- await writeFile(file, "ab");
515
- await call(tool, { path: file, replacements: rules });
516
- assert.equal(await readFile(file, "utf8"), "ba");
517
- }
518
- for (const find of ["^", "(?=b)", "$"]) {
519
- await writeFile(file, "ab");
520
- const args = {
521
- path: file,
522
- replacements: [
523
- { literal: true, find: "ab", replace: "X" },
524
- { find, replace: "!", literal: false },
525
- ],
526
- };
527
- if (find === "$") {
528
- await call(tool, args);
529
- assert.equal(await readFile(file, "utf8"), "X!");
530
- } else {
531
- const failed = await call(tool, args);
532
- assert.equal(failed.isError, true);
533
- assert.equal(reportOf(failed, "replace")?.error, "OVERLAPPING_MATCHES");
534
- assert.equal(await readFile(file, "utf8"), "ab");
535
- }
536
- }
537
- await writeFile(file, "ab");
538
- const failed = await call(tool, {
539
- path: file,
540
- replacements: [
541
- { find: "^", replace: "x", literal: false },
542
- { find: "(?=a)", replace: "y", literal: false },
543
- ],
544
- });
545
- assert.equal(failed.isError, true);
546
- assert.equal(reportOf(failed, "replace")?.error, "OVERLAPPING_MATCHES");
547
- assert.equal(await readFile(file, "utf8"), "ab");
548
- }));
549
-
550
- test("regex templates agree with native replacement in single and snapshot batch modes", async () =>
551
- withDir(async (dir) => {
552
- const file = join(dir, "regex.txt");
553
- const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
554
- const template =
555
- "$$|$&|$`|$'|$0|$00|$01|$1|$2|$10|$12|$99|$<x>|$<missing>|$<>|$<$&>|$<unclosed$1|$";
556
- for (const [source, find, flags] of [
557
- ["ab b#", "(?<x>a)?b", "g"],
558
- ["ab b#", "(a)?b", "g"],
559
- ["ab#", "ab", "g"],
560
- ["abcdefghijkl#", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)", "g"],
561
- ["ab ab#", "(?<=a)(b)", "g"],
562
- ["ab#", "(?=b)", "g"],
563
- ["😀#", "(?=[^#])", "gu"],
564
- ["aab#", "(a)", "gy"],
565
- ]) {
566
- const rule = { find, replace: template, literal: false, flags };
567
- const expected = source.replace(new RegExp(find, flags), template);
568
- for (const batch of [false, true]) {
569
- await writeFile(file, source);
570
- // The second rule changes only the original final sentinel, not copies inserted by $' or $`.
571
- const args = batch
572
- ? { replacements: [rule, { find: "#$", replace: "!", literal: false }] }
573
- : { replacements: [rule] };
574
- await call(tool, { path: file, ...args });
575
- assert.equal(
576
- await readFile(file, "utf8"),
577
- batch ? expected.slice(0, -1) + "!" : expected,
578
- `${find}/${flags}; batch=${batch}`,
579
- );
580
- }
581
- }
582
- }));
583
-
584
- test("successful batches run one command against the complete result", async () =>
585
- withDir(async (dir) => {
586
- const file = join(dir, "batch.txt");
587
- await writeFile(file, "foo bar");
588
- let commands = 0;
589
- const executeTool: SessionCommand = async (_name, input) => {
590
- assert.deepEqual(input, { command: "check" });
591
- commands++;
592
- assert.equal(await readFile(file, "utf8"), "bar baz");
593
- return commandCompletion({ content: [{ type: "text", text: "checked" }] });
594
- };
595
- const tool = makeReplaceTool(
596
- dir,
597
- DEFAULT_CONFIG,
598
- createActionFusionExecutor(() => {}),
599
- );
600
- const result = await tool.execute(
601
- "0",
602
- {
603
- path: file,
604
- replacements: [
605
- { literal: true, find: "foo", replace: "bar" },
606
- { literal: true, find: "bar", replace: "baz" },
607
- ],
608
- then_run: { command: "check" },
609
- },
610
- undefined,
611
- undefined,
612
- { ...({ cwd: dir } as Parameters<typeof tool.execute>[4]), executeTool },
613
- );
614
- assert.equal(commands, 1);
615
- assert.equal(reportOf(result, "replace")?.then_run?.status, "succeeded");
616
- assert.equal(reportOf(result, "replace")?.then_run?.output, "checked");
617
- }));
618
-
619
- test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () =>
620
- withDir(async (dir) => {
621
- const path = join(dir, "f.txt");
622
- const before = "a\r\nb\rc\r\r\n";
623
- await writeFile(path, before);
624
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
625
- path,
626
- replacements: [{ find: "(b\rc\r)\\n", replace: "$1\n", literal: false }],
627
- });
628
- assert.equal(await readFile(path, "utf8"), before);
629
- await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
630
- path,
631
- replacements: [{ find: "(?=\\n)", replace: "!", literal: false }],
632
- });
633
- assert.equal(await readFile(path, "utf8"), "a!\r\nb\rc\r!\r\n");
634
- }));
@@ -1,27 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
- import type { ErrorCode, Report } from "./report-schema.ts";
4
- import { detailsReport } from "./report.ts";
5
-
6
- /** Assert execution failures through the returned model/TUI report, without changing tool semantics. */
7
- export async function expectToolFailure(
8
- pending: Promise<AgentToolResult<unknown> & { isError?: boolean }>,
9
- code: ErrorCode,
10
- inspect?: (report: Report) => void,
11
- ): Promise<Report> {
12
- const result = await pending;
13
- assert.equal(result.isError, true);
14
- const details = result.details;
15
- assert.ok(typeof details === "object" && details !== null && "report" in details);
16
- const value = details.report;
17
- assert.ok(typeof value === "object" && value !== null && "tool" in value);
18
- const tool = (["read", "grep", "edit", "replace", "write"] as const).find(
19
- (name) => name === value.tool,
20
- );
21
- assert.ok(tool);
22
- const report = detailsReport(details, tool);
23
- assert.ok(report);
24
- assert.equal(report.error, code);
25
- inspect?.(report);
26
- return report;
27
- }