@criogaid/pi-hashline-edit 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +279 -0
  3. package/package.json +50 -0
  4. package/src/core/apply.test.ts +327 -0
  5. package/src/core/apply.ts +264 -0
  6. package/src/core/hash.test.ts +54 -0
  7. package/src/core/hash.ts +68 -0
  8. package/src/core/index.ts +13 -0
  9. package/src/core/lines.test.ts +33 -0
  10. package/src/core/lines.ts +52 -0
  11. package/src/core/types.ts +87 -0
  12. package/src/index.ts +44 -0
  13. package/src/integration/grep-rg.test.ts +390 -0
  14. package/src/pi/action-fusion.test.ts +244 -0
  15. package/src/pi/action-fusion.ts +284 -0
  16. package/src/pi/config.test.ts +22 -0
  17. package/src/pi/config.ts +56 -0
  18. package/src/pi/edit-tool.ts +367 -0
  19. package/src/pi/execute.test.ts +521 -0
  20. package/src/pi/failure-context.test.ts +88 -0
  21. package/src/pi/failure-context.ts +98 -0
  22. package/src/pi/failure-path.test.ts +60 -0
  23. package/src/pi/file-commit.test.ts +200 -0
  24. package/src/pi/file-commit.ts +185 -0
  25. package/src/pi/fusion-card.test.ts +69 -0
  26. package/src/pi/fusion-card.ts +78 -0
  27. package/src/pi/grep-tool.ts +795 -0
  28. package/src/pi/grep.test.ts +515 -0
  29. package/src/pi/pi.test.ts +19 -0
  30. package/src/pi/read-tool.ts +178 -0
  31. package/src/pi/registration.test.ts +41 -0
  32. package/src/pi/render.ts +103 -0
  33. package/src/pi/replace-tool.ts +303 -0
  34. package/src/pi/replace.test.ts +287 -0
  35. package/src/pi/rg-line-filter.test.ts +79 -0
  36. package/src/pi/rg-line-filter.ts +358 -0
  37. package/src/pi/rg-line-ranges.test.ts +30 -0
  38. package/src/pi/rg-line-ranges.ts +106 -0
  39. package/src/pi/state.ts +27 -0
  40. package/src/pi/write-tool.ts +83 -0
  41. package/src/pi/write.test.ts +126 -0
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Explicit integration coverage for the platform rg bundled by @vscode/ripgrep.
3
+ * This suite is excluded from the default test script.
4
+ */
5
+ import { test } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { lstat, mkdir, mkdtemp, readFile, readlink, realpath, rm, symlink, writeFile } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { rgPath } from "@vscode/ripgrep";
11
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
12
+ import { makeEditOverride } from "../pi/edit-tool.ts";
13
+ import { COMMON_RG_ARGS, createLinePredicate, resolveIgnoreCase, runRg } from "../pi/rg-line-filter.ts";
14
+
15
+ const REGEX_MODE = { engine: "default", multiline: false, literal: false } as const;
16
+
17
+ test("real rg emits anchored matches from a temporary directory", async () => {
18
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-integration-"));
19
+ try {
20
+ const file = join(directory, "fixture.ts");
21
+ await writeFile(file, "needle\nother\n");
22
+ const tool = makeGrepOverrideWithBackend(directory, {});
23
+
24
+ for (const pattern of ["needle", ["needle"]]) {
25
+ const result: any = await tool.execute("0", { pattern }, undefined, undefined);
26
+ assert.match(result.content[0].text, /fixture\.ts · 1 match/);
27
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│needle/);
28
+ }
29
+ } finally {
30
+ await rm(directory, { recursive: true, force: true });
31
+ }
32
+ });
33
+
34
+ test("real rg and line filters share case and Unicode semantics", async () => {
35
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-"));
36
+ try {
37
+ await writeFile(join(directory, "fixture.ts"), "FOO abc\nfoo BAR\nfoo bar\nK zip\nk zip\n");
38
+ const tool = makeGrepOverrideWithBackend(directory, {});
39
+ for (const ignoreCase of [undefined, true, false]) {
40
+ const expectedCount = ignoreCase === false ? 2 : 3;
41
+ for (const query of [
42
+ { pattern: "foo\\S*" },
43
+ { pattern: ["foo\\S*", "\\S+"], matchMode: "all" },
44
+ ]) {
45
+ const result: any = await tool.execute("0", { ...query, ignoreCase }, undefined, undefined);
46
+ assert.match(result.content[0].text, new RegExp(`fixture\\.ts · ${expectedCount} matches`));
47
+ assert.equal(result.content[0].text.includes("FOO abc"), ignoreCase !== false);
48
+ }
49
+ const excluded: any = await tool.execute("0", {
50
+ pattern: "foo\\S*", excludePattern: "bar", ignoreCase,
51
+ }, undefined, undefined);
52
+ assert.match(excluded.content[0].text, /fixture\.ts · 1 match/);
53
+ assert.ok(excluded.content[0].text.includes(ignoreCase === false ? "foo BAR" : "FOO abc"));
54
+ }
55
+ const unicodeAll: any = await tool.execute("0", {
56
+ pattern: ["k", "zip"], matchMode: "all",
57
+ }, undefined, undefined);
58
+ assert.match(unicodeAll.content[0].text, /fixture\.ts · 2 matches/);
59
+ assert.ok(unicodeAll.content[0].text.includes("K zip"));
60
+
61
+ const unicodeExcluded: any = await tool.execute("0", {
62
+ pattern: "zip", excludePattern: "k",
63
+ }, undefined, undefined);
64
+ assert.equal(unicodeExcluded.content[0].text, "No matches found");
65
+ } finally {
66
+ await rm(directory, { recursive: true, force: true });
67
+ }
68
+ });
69
+
70
+ test("real rg resolves regex-aware smart-case decisions", async () => {
71
+ const cases = new Map<string, boolean>([
72
+ ["foo", true],
73
+ ["Foo", false],
74
+ ["foo\\S*", true],
75
+ ["foo\\D+", true],
76
+ ["foo\\W+", true],
77
+ ["foo\\p{Lu}*", true],
78
+ ["(?P<UPPER>foo)$", true],
79
+ ["foo[A-Z]", false],
80
+ ["\\x66oo", true],
81
+ ["\\x46oo", false],
82
+ ["\\w", false],
83
+ ["\\p{Lu}", false],
84
+ ]);
85
+ for (const [pattern, expected] of cases) {
86
+ assert.equal(await resolveIgnoreCase(rgPath!, [pattern], REGEX_MODE, undefined), expected, pattern);
87
+ }
88
+ assert.equal(await resolveIgnoreCase(rgPath!, ["foo\\S*"], { ...REGEX_MODE, literal: true }, undefined), false);
89
+ assert.equal(await resolveIgnoreCase(rgPath!, ["(a)", "Foo"], REGEX_MODE, undefined), false);
90
+ });
91
+
92
+ test("real rg owns AND and exclusion regex semantics", async () => {
93
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-filter-"));
94
+ try {
95
+ await writeFile(join(directory, "fixture.ts"), "FOO abc\nfoo BAR\nfoo bar\n");
96
+ const tool = makeGrepOverrideWithBackend(directory, {});
97
+ const rustSyntax: any = await tool.execute("0", {
98
+ pattern: ["(?P<name>foo)\\S*", "BAR"],
99
+ matchMode: "all",
100
+ }, undefined, undefined);
101
+ assert.match(rustSyntax.content[0].text, /│foo BAR/);
102
+ assert.doesNotMatch(rustSyntax.content[0].text, /│foo bar/);
103
+
104
+ await assert.rejects(
105
+ tool.execute("0", {
106
+ pattern: "missing",
107
+ excludePattern: "queueTool(",
108
+ literal: false,
109
+ }, undefined, undefined),
110
+ /regex parse error/,
111
+ );
112
+ } finally {
113
+ await rm(directory, { recursive: true, force: true });
114
+ }
115
+ });
116
+
117
+ test("owned rg processes ignore RIPGREP_CONFIG_PATH", async () => {
118
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-config-"));
119
+ const previous = process.env.RIPGREP_CONFIG_PATH;
120
+ try {
121
+ const config = join(directory, "ripgreprc");
122
+ await writeFile(config, "--ignore-case\n--fixed-strings\n--invert-match\n--pcre2\n");
123
+ await writeFile(join(directory, "fixture.ts"), "FOO\nfoo\nbar\n");
124
+ process.env.RIPGREP_CONFIG_PATH = config;
125
+ const tool = makeGrepOverrideWithBackend(directory, {});
126
+ const result: any = await tool.execute("0", {
127
+ pattern: ["^foo$", "foo"],
128
+ matchMode: "all",
129
+ }, undefined, undefined);
130
+ assert.match(result.content[0].text, /fixture\.ts · 2 matches/);
131
+ assert.match(result.content[0].text, /│foo/);
132
+ assert.match(result.content[0].text, /│FOO/);
133
+ assert.doesNotMatch(result.content[0].text, /│bar/);
134
+ } finally {
135
+ if (previous === undefined) delete process.env.RIPGREP_CONFIG_PATH;
136
+ else process.env.RIPGREP_CONFIG_PATH = previous;
137
+ await rm(directory, { recursive: true, force: true });
138
+ }
139
+ });
140
+
141
+ test("real rg validates its own regex syntax and limits automatic literal fallback", async () => {
142
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-regex-"));
143
+ try {
144
+ await writeFile(join(directory, "fixture.ts"), "FOO\nfoo\nqueueTool(\nfoo(?=bar)\n");
145
+ const tool = makeGrepOverrideWithBackend(directory, {});
146
+ for (const pattern of ["(?i)^foo$", "(?P<name>foo)$"]) {
147
+ const result: any = await tool.execute("0", { pattern }, undefined, undefined);
148
+ assert.match(result.content[0].text, /│foo/);
149
+ assert.doesNotMatch(result.content[0].text, /Invalid regex/);
150
+ }
151
+ for (const pattern of ["queueTool(", "foo(?=bar)"]) {
152
+ const result: any = await tool.execute("0", { pattern }, undefined, undefined);
153
+ assert.ok(result.content[0].text.includes(`│${pattern}`));
154
+ assert.match(result.content[0].text, /Invalid regex; searched all patterns as literal text/);
155
+ await assert.rejects(
156
+ tool.execute("0", { pattern, literal: false }, undefined, undefined),
157
+ /regex parse error/,
158
+ );
159
+ }
160
+ const missing: any = await tool.execute("0", { pattern: "missing(" }, undefined, undefined);
161
+ assert.match(missing.content[0].text, /No matches found\n\n\[Invalid regex/);
162
+ const explicit: any = await tool.execute("0", { pattern: "queueTool(", literal: true }, undefined, undefined);
163
+ assert.match(explicit.content[0].text, /│queueTool\(/);
164
+ assert.doesNotMatch(explicit.content[0].text, /Invalid regex/);
165
+ } finally {
166
+ await rm(directory, { recursive: true, force: true });
167
+ }
168
+ });
169
+
170
+ test("real rg preserves CRLF end anchors in main searches, AND filters, and exclusions", async () => {
171
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-crlf-"));
172
+ try {
173
+ await writeFile(join(directory, "fixture.ts"), "alpha beta drop\r\nalpha beta\r\nalpha only");
174
+ const tool = makeGrepOverrideWithBackend(directory, {});
175
+ for (const pattern of [["alpha", "beta$"], ["beta$", "alpha"], ["beta$"]]) {
176
+ const result = await tool.execute("0", { pattern, matchMode: "all" }, undefined, undefined);
177
+ assert.match(result.content[0].text, /fixture\.ts · 1 match/);
178
+ assert.match(result.content[0].text, /2#[0-9A-Z]+│alpha beta$/);
179
+ }
180
+ const excluded = await tool.execute("0", {
181
+ pattern: "alpha", excludePattern: "beta$",
182
+ }, undefined, undefined);
183
+ assert.match(excluded.content[0].text, /fixture\.ts · 2 matches/);
184
+ assert.doesNotMatch(excluded.content[0].text, /2#[0-9A-Z]+│/);
185
+ assert.match(excluded.content[0].text, /3#[0-9A-Z]+│alpha only$/);
186
+ } finally {
187
+ await rm(directory, { recursive: true, force: true });
188
+ }
189
+ });
190
+
191
+ test("real rg reaches a late survivor with two bounded filter invocations", async () => {
192
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-batches-"));
193
+ try {
194
+ await writeFile(join(directory, "fixture.ts"), "foo skip\n".repeat(4096) + "foo keep\n");
195
+ let invocations = 0;
196
+ const tool = makeGrepOverrideWithBackend(directory, {
197
+ createLinePredicate(...args) {
198
+ const predicate = createLinePredicate(...args);
199
+ return async (lines) => {
200
+ invocations++;
201
+ return predicate(lines);
202
+ };
203
+ },
204
+ });
205
+ const result = await tool.execute("0", {
206
+ pattern: "foo", excludePattern: "skip", literal: true, ignoreCase: false, limit: 1,
207
+ }, undefined, undefined);
208
+ assert.match(result.content[0].text, /4097#[0-9A-Z]+│foo keep/);
209
+ assert.equal(invocations, 2);
210
+ } finally {
211
+ await rm(directory, { recursive: true, force: true });
212
+ }
213
+ });
214
+
215
+ test("shared rg runner stops and cleans up after limits, callback failures, and cancellation", async () => {
216
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-process-"));
217
+ try {
218
+ const file = join(directory, "fixture.txt");
219
+ await writeFile(file, "needle\n".repeat(10_000));
220
+ const args = [...COMMON_RG_ARGS, "--engine=default", "--no-multiline", "--json", "-e", "needle", "--", file];
221
+ const stopped = await runRg(rgPath, args, undefined, () => false);
222
+ assert.equal(stopped.stopped, true);
223
+ await assert.rejects(runRg(rgPath, args, undefined, () => {
224
+ throw new Error("callback failed");
225
+ }), /callback failed/);
226
+ const controller = new AbortController();
227
+ await assert.rejects(runRg(rgPath, args, controller.signal, () => {
228
+ controller.abort();
229
+ return true;
230
+ }), /Operation aborted/);
231
+ await assert.rejects(runRg(join(directory, "missing-rg"), [], undefined, () => true), /Failed to run ripgrep/);
232
+ } finally {
233
+ await rm(directory, { recursive: true, force: true });
234
+ }
235
+ });
236
+
237
+ test("noIgnore searches ignored files while explicit excluding globs still apply", async () => {
238
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-ignore-"));
239
+ try {
240
+ await writeFile(join(directory, ".ignore"), "ignored.txt\n");
241
+ await writeFile(join(directory, "ignored.txt"), "needle\n");
242
+ const tool = makeGrepOverrideWithBackend(directory, {});
243
+ const normal: any = await tool.execute("0", { pattern: "needle" }, undefined, undefined);
244
+ assert.equal(normal.content[0].text, "No matches found");
245
+ const included: any = await tool.execute("0", { pattern: "needle", noIgnore: true }, undefined, undefined);
246
+ assert.match(included.content[0].text, /ignored\.txt · 1 match/);
247
+ const excluded: any = await tool.execute("0", { pattern: "needle", noIgnore: true, glob: "!ignored.txt" }, undefined, undefined);
248
+ assert.equal(excluded.content[0].text, "No matches found");
249
+ } finally {
250
+ await rm(directory, { recursive: true, force: true });
251
+ }
252
+ });
253
+
254
+ test("follow returns a resolved target path that edit can update without replacing the link", async (t) => {
255
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-follow-"));
256
+ try {
257
+ const root = join(directory, "root");
258
+ const target = join(directory, "target");
259
+ const link = join(root, "link");
260
+ const secondLink = join(root, "second-link");
261
+ await mkdir(root);
262
+ await mkdir(target);
263
+ const targetFile = join(target, "linked.txt");
264
+ await writeFile(targetFile, "needle\n");
265
+ try {
266
+ await symlink(target, link, process.platform === "win32" ? "junction" : "dir");
267
+ await symlink(target, secondLink, process.platform === "win32" ? "junction" : "dir");
268
+ } catch (error: any) {
269
+ if (["EPERM", "EACCES", "ENOTSUP"].includes(error?.code)) return t.skip("symbolic link creation unavailable");
270
+ throw error;
271
+ }
272
+ const grep = makeGrepOverrideWithBackend(root, {});
273
+ const hidden: any = await grep.execute("0", { pattern: "needle" }, undefined, undefined);
274
+ assert.equal(hidden.content[0].text, "No matches found");
275
+ const found: any = await grep.execute("0", { pattern: "needle", follow: true }, undefined, undefined);
276
+ const [header, anchored] = found.content[0].text.split("\n");
277
+ const resultPath = header.slice(0, header.lastIndexOf(" · "));
278
+ assert.equal(resultPath, await realpath(targetFile));
279
+ assert.equal(found.content[0].text.match(/ · 1 match/g)?.length, 1);
280
+ const anchor = anchored.slice(0, anchored.indexOf("│"));
281
+ const edit: any = makeEditOverride(root);
282
+ await edit.execute("0", { path: resultPath, edits: [{ op: "replace", anchor, body: ["updated"] }] }, undefined, undefined);
283
+ assert.equal(await readFile(targetFile, "utf8"), "updated\n");
284
+ assert.equal((await lstat(link)).isSymbolicLink(), true);
285
+ assert.equal(await readlink(link), target);
286
+ assert.equal((await lstat(secondLink)).isSymbolicLink(), true);
287
+ } finally {
288
+ await rm(directory, { recursive: true, force: true });
289
+ }
290
+ });
291
+
292
+ test("PCRE2 applies to main, AND, exclusion, backreference, and inherited smart-case matches", async () => {
293
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-pcre2-"));
294
+ try {
295
+ await writeFile(join(directory, "fixture.txt"), "FOO abc\nfoo BAR\nfoobar\nfoofoo\n");
296
+ const tool = makeGrepOverrideWithBackend(directory, {});
297
+ const main: any = await tool.execute("0", { pattern: "foo(?=bar)", pcre2: true }, undefined, undefined);
298
+ assert.match(main.content[0].text, /│foobar/);
299
+ const all: any = await tool.execute("0", { pattern: ["foo", "(?<=foo)bar"], matchMode: "all", pcre2: true }, undefined, undefined);
300
+ assert.match(all.content[0].text, /fixture\.txt · 1 match/);
301
+ assert.match(all.content[0].text, /│foobar/);
302
+ const excluded: any = await tool.execute("0", { pattern: "foo", excludePattern: "(?<=foo)bar", pcre2: true }, undefined, undefined);
303
+ assert.doesNotMatch(excluded.content[0].text, /│foobar/);
304
+ const backreference: any = await tool.execute("0", { pattern: "(foo)\\1", pcre2: true }, undefined, undefined);
305
+ assert.match(backreference.content[0].text, /│foofoo/);
306
+ const inherited: any = await tool.execute("0", { pattern: "foo\\S*", excludePattern: "bar", pcre2: true }, undefined, undefined);
307
+ assert.match(inherited.content[0].text, /│FOO abc/);
308
+ assert.doesNotMatch(inherited.content[0].text, /│foo BAR/);
309
+ await assert.rejects(tool.execute("0", { pattern: "(", pcre2: true }, undefined, undefined), /PCRE2: error compiling pattern/);
310
+ await assert.rejects(tool.execute("0", { pattern: "foo", pcre2: true, literal: true }, undefined, undefined), /cannot be combined/);
311
+ } finally {
312
+ await rm(directory, { recursive: true, force: true });
313
+ }
314
+ });
315
+
316
+ test("multiline combines physical line sets for all, exclusion, limit, and PCRE2", async () => {
317
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-multiline-"));
318
+ try {
319
+ await writeFile(join(directory, "fixture.txt"), "alpha\r\nbeta\r\ngamma\r\n");
320
+ await writeFile(join(directory, "eof.txt"), "last line");
321
+ const tool = makeGrepOverrideWithBackend(directory, {});
322
+ const match: any = await tool.execute("0", { pattern: "alpha\\r?\\nbeta", multiline: true, literal: false }, undefined, undefined);
323
+ assert.match(match.content[0].text, /fixture\.txt · 2 matches/);
324
+ assert.match(match.content[0].text, /1#[0-9A-Z]+│alpha/);
325
+ assert.match(match.content[0].text, /2#[0-9A-Z]+│beta/);
326
+ const all: any = await tool.execute("0", {
327
+ pattern: ["alpha\\r?\\nbeta", "beta\\r?\\ngamma"], matchMode: "all", multiline: true, literal: false,
328
+ }, undefined, undefined);
329
+ assert.match(all.content[0].text, /fixture\.txt · 1 match/);
330
+ assert.match(all.content[0].text, /2#[0-9A-Z]+│beta/);
331
+ const excluded: any = await tool.execute("0", {
332
+ pattern: "alpha\\r?\\nbeta", excludePattern: "beta", multiline: true, literal: false,
333
+ }, undefined, undefined);
334
+ assert.match(excluded.content[0].text, /fixture\.txt · 1 match/);
335
+ assert.match(excluded.content[0].text, /1#[0-9A-Z]+│alpha/);
336
+ const limited: any = await tool.execute("0", {
337
+ pattern: "(?s)alpha.*gamma", multiline: true, pcre2: true, limit: 2, outputMode: "count",
338
+ }, undefined, undefined);
339
+ assert.match(limited.content[0].text, /fixture\.txt: 2/);
340
+ assert.match(limited.content[0].text, /2 matches limit reached/);
341
+ const eof: any = await tool.execute("0", { pattern: "\\z", path: "eof.txt", multiline: true, pcre2: true }, undefined, undefined);
342
+ assert.match(eof.content[0].text, /1#[0-9A-Z]+│last line/);
343
+ } finally {
344
+ await rm(directory, { recursive: true, force: true });
345
+ }
346
+ });
347
+
348
+ test("complex searches reject file changes and propagate cancellation", async () => {
349
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-complex-state-"));
350
+ try {
351
+ const file = join(directory, "fixture.txt");
352
+ await writeFile(file, "foo bar\n");
353
+ let scans = 0;
354
+ const changing = makeGrepOverrideWithBackend(directory, {
355
+ async runRg(path, args, signal, onLine) {
356
+ const result = await runRg(path, args, signal, onLine);
357
+ if (args.includes("--threads=1") && scans++ === 0) await writeFile(file, "changed content\n");
358
+ return result;
359
+ },
360
+ });
361
+ await assert.rejects(changing.execute("0", {
362
+ pattern: ["foo", "bar"], matchMode: "all", pcre2: true, ignoreCase: false,
363
+ }, undefined, undefined), /File changed during search/);
364
+
365
+ await writeFile(file, "foo bar\n");
366
+ const controller = new AbortController();
367
+ const cancelling = makeGrepOverrideWithBackend(directory, {
368
+ runRg(path, args, signal, onLine) {
369
+ if (args.includes("--threads=1")) controller.abort();
370
+ return runRg(path, args, signal, onLine);
371
+ },
372
+ });
373
+ await assert.rejects(cancelling.execute("0", {
374
+ pattern: "foo(?= bar)", pcre2: true, ignoreCase: false,
375
+ }, controller.signal, undefined), /Operation aborted/);
376
+ } finally {
377
+ await rm(directory, { recursive: true, force: true });
378
+ }
379
+ });
380
+
381
+ test("owned rg rejects an oversized JSONL record", async () => {
382
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-record-limit-"));
383
+ try {
384
+ await writeFile(join(directory, "large.txt"), `needle${"x".repeat(17 * 1024 * 1024)}\n`);
385
+ const tool = makeGrepOverrideWithBackend(directory, {});
386
+ await assert.rejects(tool.execute("0", { pattern: "needle", literal: true }, undefined, undefined), /record exceeds 16 MiB/);
387
+ } finally {
388
+ await rm(directory, { recursive: true, force: true });
389
+ }
390
+ });
@@ -0,0 +1,244 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import assert from "node:assert/strict";
5
+ import { test } from "node:test";
6
+ import { makeEditOverride } from "./edit-tool.ts";
7
+ import { makeReplaceTool } from "./replace-tool.ts";
8
+ import { makeWriteOverride } from "./write-tool.ts";
9
+ import { computeLineHash } from "../core/hash.ts";
10
+ import type { ActionFusionProgress } from "./action-fusion.ts";
11
+ import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, THEN_RUN_FAILED, THEN_RUN_SKIPPED, THEN_RUN_SUCCEEDED } from "./action-fusion.ts";
12
+
13
+ async function tempDir(): Promise<string> {
14
+ return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
15
+ }
16
+
17
+ const ctx = (cwd: string) => ({ cwd }) as any;
18
+
19
+ test("actionFusion schemas and shared usage guidance are opt-in for every mutation tool", () => {
20
+ const fusion = createActionFusionExecutor();
21
+ for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
22
+ const disabled = makeTool("/tmp") as any;
23
+ const enabled = makeTool("/tmp", fusion) as any;
24
+ assert.equal(disabled.parameters.properties.then_run, undefined);
25
+ assert.ok(enabled.parameters.properties.then_run);
26
+ assert.deepEqual(enabled.promptGuidelines, [...(disabled.promptGuidelines ?? []), ...ACTION_FUSION_GUIDELINES]);
27
+ assert.ok(!(disabled.promptGuidelines ?? []).some((line: string) => ACTION_FUSION_GUIDELINES.includes(line)));
28
+ }
29
+ });
30
+
31
+ test("edit and replace share one embedded executor and preserve mutation results", async () => {
32
+ const dir = await tempDir();
33
+ try {
34
+ const calls: string[] = [];
35
+ const fusion = createActionFusionExecutor(async (_id, input) => {
36
+ calls.push(input.command);
37
+ return "checked";
38
+ });
39
+ const edit = makeEditOverride(dir, fusion) as any;
40
+ const replace = makeReplaceTool(dir, fusion) as any;
41
+ await writeFile(join(dir, "edit.txt"), "before\n");
42
+ await writeFile(join(dir, "replace.txt"), "before\n");
43
+ const editResult = await edit.execute("edit-1", { path: "edit.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check edit" } }, undefined, undefined, ctx(dir));
44
+ const replaceResult = await replace.execute("replace-1", { path: "replace.txt", find: "before", replace: "after", then_run: { command: "check replace" } }, undefined, undefined, ctx(dir));
45
+ assert.match(editResult.content.at(-1).text, new RegExp(THEN_RUN_SUCCEEDED));
46
+ assert.match(editResult.content.map((block: any) => block.text ?? "").join("\n"), /Updated anchors/);
47
+ assert.match(replaceResult.content.at(-1).text, new RegExp(THEN_RUN_SUCCEEDED));
48
+ assert.deepEqual(calls, ["check edit", "check replace"]);
49
+ assert.equal((await readFile(join(dir, "edit.txt"), "utf8")), "before\nafter\n");
50
+ assert.equal((await readFile(join(dir, "replace.txt"), "utf8")), "after\n");
51
+ } finally {
52
+ await rm(dir, { recursive: true, force: true });
53
+ }
54
+ });
55
+
56
+ test("mutation failure skips the command and command failure does not roll back", async () => {
57
+ const dir = await tempDir();
58
+ try {
59
+ let calls = 0;
60
+ const commandFailure = "compiler: unexpected token\nCommand exited with code 7";
61
+ const fusion = createActionFusionExecutor(async () => { calls++; throw new Error(commandFailure); });
62
+ await assert.rejects(
63
+ fusion({ toolCallId: "x", absolutePath: join(dir, "missing.txt"), thenRun: { command: "check" }, mutate: async () => { throw new Error("anchor mismatch: current 1#ABCD"); }, signal: undefined, ctx: ctx(dir) }),
64
+ (error: Error) => error.message.includes(THEN_RUN_SKIPPED) && error.message.includes("anchor mismatch: current 1#ABCD"),
65
+ );
66
+ assert.equal(calls, 0);
67
+ const target = join(dir, "changed.txt");
68
+ await writeFile(target, "changed\n");
69
+ const result = await fusion({ toolCallId: "y", absolutePath: target, thenRun: { command: "check" }, mutate: async () => ({ content: [{ type: "text", text: "mutation" }], details: { ok: true } }), signal: undefined, ctx: ctx(dir) });
70
+ assert.equal(result.content[0].type === "text" && result.content[0].text, "mutation");
71
+ const diagnostic = result.content[1].type === "text" ? result.content[1].text : "";
72
+ assert.ok(diagnostic.includes(THEN_RUN_FAILED) && diagnostic.includes(commandFailure));
73
+ assert.equal(await readFile(target, "utf8"), "changed\n");
74
+ assert.equal(calls, 1);
75
+ } finally {
76
+ await rm(dir, { recursive: true, force: true });
77
+ }
78
+ });
79
+
80
+ test("cancelled calls do not mutate or run the command", async () => {
81
+ const dir = await tempDir();
82
+ try {
83
+ const controller = new AbortController();
84
+ controller.abort();
85
+ let mutated = false;
86
+ let commanded = false;
87
+ const fusion = createActionFusionExecutor(async () => { commanded = true; return ""; });
88
+ await assert.rejects(fusion({ toolCallId: "x", absolutePath: join(dir, "cancelled.txt"), thenRun: { command: "check" }, mutate: async () => { mutated = true; return { content: [], details: undefined }; }, signal: controller.signal, ctx: ctx(dir) }));
89
+ assert.equal(mutated, false);
90
+ assert.equal(commanded, false);
91
+ } finally {
92
+ await rm(dir, { recursive: true, force: true });
93
+ }
94
+ });
95
+
96
+ test("default runner executes a real local command", async () => {
97
+ const dir = await tempDir();
98
+ try {
99
+ const target = join(dir, "real.txt");
100
+ await writeFile(target, "before\n");
101
+ const fusion = createActionFusionExecutor();
102
+ const result = await fusion({
103
+ toolCallId: "real",
104
+ absolutePath: target,
105
+ thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
106
+ mutate: async () => { await writeFile(target, "after\n"); return { content: [{ type: "text", text: "mutated" }], details: { ok: true } }; },
107
+ signal: undefined,
108
+ ctx: { ...ctx(dir), sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined } } as any,
109
+ });
110
+ const output = result.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("\n");
111
+ assert.match(output, /real runner/);
112
+ } finally {
113
+ await rm(dir, { recursive: true, force: true });
114
+ }
115
+ });
116
+
117
+ test("marks anchors stale when then_run changes the target", async () => {
118
+ const dir = await tempDir();
119
+ try {
120
+ const target = join(dir, "stale.txt");
121
+ await writeFile(target, "before\n");
122
+ const fusion = createActionFusionExecutor(async () => { await writeFile(target, "changed by command\n"); return "changed"; });
123
+ const result = await fusion({
124
+ toolCallId: "stale",
125
+ absolutePath: target,
126
+ thenRun: { command: "mutate target" },
127
+ mutate: async () => { await writeFile(target, "after mutation\n"); return { content: [{ type: "text", text: "mutated" }], details: {} }; },
128
+ signal: undefined,
129
+ ctx: ctx(dir),
130
+ });
131
+ const output = result.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("\n");
132
+ assert.match(output, /\[then_run:stale\]/);
133
+ assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
134
+ } finally {
135
+ await rm(dir, { recursive: true, force: true });
136
+ }
137
+ });
138
+
139
+ test("Action Fusion omits structured anchors when target freshness is unknown", async () => {
140
+ const dir = await tempDir();
141
+ try {
142
+ const missing = join(dir, "never-created.txt");
143
+ let commands = 0;
144
+ const fusion = createActionFusionExecutor(async () => { commands++; return "unexpected"; });
145
+ const result = await fusion({
146
+ toolCallId: "unknown",
147
+ absolutePath: missing,
148
+ thenRun: { command: "check" },
149
+ mutate: async () => ({ content: [{ type: "text", text: "mutated" }], details: {} }),
150
+ finalizeMutation: (mutation, publishAnchors) => ({
151
+ ...mutation,
152
+ content: [{ type: "text", text: `mutated${publishAnchors ? " ANCHOR" : ""}` }],
153
+ }),
154
+ signal: undefined,
155
+ ctx: ctx(dir),
156
+ });
157
+ const output = result.content.map((block) => block.type === "text" ? block.text : "").join("\n");
158
+ assert.equal(commands, 0);
159
+ assert.equal((result.details as any).actionFusion.freshness, "unknown");
160
+ assert.doesNotMatch(output, /ANCHOR/);
161
+ assert.match(output, /Pre-command anchors are omitted/);
162
+ } finally {
163
+ await rm(dir, { recursive: true, force: true });
164
+ }
165
+ });
166
+
167
+ test("edit omits Updated anchors when then_run changes the target", async () => {
168
+ const dir = await tempDir();
169
+ try {
170
+ const target = join(dir, "edit-stale.txt");
171
+ await writeFile(target, "before\n");
172
+ const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); return "changed"; });
173
+ const result = await makeEditOverride(dir, fusion).execute("edit-stale", {
174
+ path: "edit-stale.txt",
175
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before")}`, body: ["after"] }],
176
+ then_run: { command: "change target" },
177
+ }, undefined, undefined, ctx(dir));
178
+ const output = result.content.map((block: any) => block.text ?? "").join("\n");
179
+ assert.equal(result.details.actionFusion.freshness, "changed");
180
+ assert.match(output, /Pre-command anchors are omitted/);
181
+ assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
182
+ assert.equal(await readFile(target, "utf8"), "command changed\n");
183
+ } finally {
184
+ await rm(dir, { recursive: true, force: true });
185
+ }
186
+ });
187
+
188
+ test("all mutation tools forward command progress before completion in RPC mode", async () => {
189
+ const dir = await tempDir();
190
+ try {
191
+ const events: ActionFusionProgress[] = [];
192
+ const updates: any[] = [];
193
+ const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
194
+ assert.equal(events.at(-1)?.command, "running");
195
+ onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
196
+ assert.match(updates.at(-1).content.at(-1).text, /live output/);
197
+ assert.equal(events.at(-1)?.output, "live output");
198
+ return "final output";
199
+ }, (event) => events.push(event));
200
+ const cases = [
201
+ { tool: makeEditOverride(dir, fusion), input: { edits: [{ op: "append", body: ["after"] }] } },
202
+ { tool: makeReplaceTool(dir, fusion), input: { find: "before", replace: "after" } },
203
+ { tool: makeWriteOverride(dir, fusion), input: { content: "after\n" } },
204
+ ];
205
+ for (const { tool, input } of cases) {
206
+ events.length = 0;
207
+ updates.length = 0;
208
+ await writeFile(join(dir, "progress.txt"), "before\n");
209
+ await tool.execute(tool.name, { path: "progress.txt", ...input, then_run: { command: "check" } }, undefined, (update: any) => updates.push(update), { cwd: dir, mode: "rpc" });
210
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "running", "running", "succeeded"]);
211
+ assert.equal(events.at(-1)?.output, "final output");
212
+ assert.equal(events.at(-1)?.publication, "PUBLISHED");
213
+ assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
214
+ }
215
+ } finally {
216
+ await rm(dir, { recursive: true, force: true });
217
+ }
218
+ });
219
+
220
+ test("progress reports skipped mutations and failed commands without rolling back", async () => {
221
+ const dir = await tempDir();
222
+ try {
223
+ const events: ActionFusionProgress[] = [];
224
+ let commands = 0;
225
+ const fusion = createActionFusionExecutor(async () => { commands++; throw new Error("diagnostic\nCommand exited with code 7"); }, (event) => events.push(event));
226
+ await assert.rejects(makeEditOverride(dir, fusion).execute("skip", { path: "missing.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check" } }, undefined, undefined, ctx(dir)));
227
+ assert.equal(commands, 0);
228
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
229
+ events.length = 0;
230
+ await writeFile(join(dir, "replace.txt"), "original\n");
231
+ await assert.rejects(makeReplaceTool(dir, fusion).execute("replace-skip", { path: "replace.txt", find: "missing", replace: "changed", then_run: { command: "check" } }, undefined, undefined, ctx(dir)), /no matches/);
232
+ assert.equal(commands, 0);
233
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
234
+ assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "original\n");
235
+ events.length = 0;
236
+ const failed = await makeWriteOverride(dir, fusion).execute("fail", { path: "failed.txt", content: "published\n", then_run: { command: "check" } }, undefined, undefined, ctx(dir));
237
+ assert.equal(failed.details.actionFusion.command, "failed");
238
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "running", "failed"]);
239
+ assert.match(events.at(-1)!.output, /diagnostic[\s\S]*code 7/);
240
+ assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
241
+ } finally {
242
+ await rm(dir, { recursive: true, force: true });
243
+ }
244
+ });