@criogaid/pi-hashline-edit 0.1.2 → 0.2.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 (39) hide show
  1. package/README.md +67 -21
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +85 -8
  4. package/src/core/apply.ts +99 -79
  5. package/src/core/ranges.test.ts +28 -0
  6. package/src/core/ranges.ts +25 -0
  7. package/src/core/text.ts +5 -0
  8. package/src/core/types.ts +37 -20
  9. package/src/integration/grep-rg.test.ts +76 -1
  10. package/src/pi/action-fusion.test.ts +1 -1
  11. package/src/pi/action-fusion.ts +9 -21
  12. package/src/pi/anchor-format.test.ts +30 -0
  13. package/src/pi/anchor-format.ts +28 -0
  14. package/src/pi/config.test.ts +6 -9
  15. package/src/pi/config.ts +4 -4
  16. package/src/pi/edit-tool.ts +90 -99
  17. package/src/pi/execute.test.ts +240 -14
  18. package/src/pi/failure-context.test.ts +99 -62
  19. package/src/pi/failure-context.ts +67 -64
  20. package/src/pi/failure-path.test.ts +3 -2
  21. package/src/pi/file-commit.test.ts +21 -0
  22. package/src/pi/file-commit.ts +35 -3
  23. package/src/pi/grep-tool.ts +75 -48
  24. package/src/pi/grep.test.ts +67 -3
  25. package/src/pi/mutation-result.ts +46 -9
  26. package/src/pi/read-tool.ts +7 -10
  27. package/src/pi/registration.test.ts +15 -2
  28. package/src/pi/render.test.ts +24 -0
  29. package/src/pi/render.ts +18 -4
  30. package/src/pi/replace-tool.ts +134 -130
  31. package/src/pi/replace.test.ts +118 -1
  32. package/src/pi/result-safety.test.ts +241 -8
  33. package/src/pi/rg-line-filter.test.ts +7 -1
  34. package/src/pi/rg-line-filter.ts +9 -11
  35. package/src/pi/rg-line-ranges.test.ts +10 -0
  36. package/src/pi/rg-line-ranges.ts +21 -15
  37. package/src/pi/state.ts +2 -3
  38. package/src/pi/write-tool.ts +10 -44
  39. package/src/pi/write.test.ts +25 -36
@@ -1,7 +1,8 @@
1
1
  import { computeLineHash } from "../core/hash.ts";
2
2
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
3
  import assert from "node:assert/strict";
4
- import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5
+ import { writeFileSync } from "node:fs";
5
6
  import { tmpdir } from "node:os";
6
7
  import { join } from "node:path";
7
8
  import { test } from "node:test";
@@ -9,10 +10,28 @@ import { createActionFusionExecutor } from "./action-fusion.ts";
9
10
  import { makeReplaceTool } from "./replace-tool.ts";
10
11
  import { makeWriteOverride } from "./write-tool.ts";
11
12
  import { makeEditOverride } from "./edit-tool.ts";
12
- import { FileMutationError } from "./file-commit.ts";
13
- import { finalizeMutationResult } from "./mutation-result.ts";
13
+ import { byteRevision, FileMutationError } from "./file-commit.ts";
14
+ import { appendMutationAnchors, finalizeMutationResult, postProcessMutation } from "./mutation-result.ts";
14
15
 
15
- const text = (result: any) => result.content.map((block: any) => block.text ?? "").join("\n");
16
+ const text = (result: any): string => result.content.map((block: any) => block.text ?? "").join("\n");
17
+
18
+ function assertFailureByteBudgets(message: string): void {
19
+ const checksAt = message.indexOf("\nInput-anchor checks (this snapshot):\n");
20
+ const guidanceAt = message.indexOf("\nCheck the intended target before retrying;", checksAt);
21
+ const neighborhoodsAt = message.indexOf("\nAmbiguous-candidate neighborhoods", checksAt);
22
+ assert.ok(checksAt > 0 && guidanceAt > checksAt);
23
+ assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= 16 * 1024);
24
+ assert.ok(Buffer.byteLength(message.slice(checksAt + 1, neighborhoodsAt < 0 ? guidanceAt : neighborhoodsAt)) <= 16 * 1024);
25
+ if (neighborhoodsAt >= 0) {
26
+ const rows = message.slice(neighborhoodsAt, guidanceAt).match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
27
+ assert.ok(rows.length > 0);
28
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= 16 * 1024);
29
+ }
30
+ assert.match(message, /Diagnostic output truncated at 16 KiB/);
31
+ assert.match(message, /Anchor-check output truncated at 16 KiB; omitted entries are not implied matched/);
32
+ const checks = message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? [];
33
+ assert.ok(checks.length > 40 && checks.length < 1000);
34
+ }
16
35
 
17
36
  test("replace withholds anchors in progress and after commands change or remove the file", async () => {
18
37
  const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
@@ -38,7 +57,8 @@ test("replace withholds anchors in progress and after commands change or remove
38
57
  assert.equal(result.details.actionFusion.freshness, state);
39
58
  assert.equal(result.details.publication, "PUBLISHED");
40
59
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
41
- assert.match(text(result), /Re-read/);
60
+ assert.equal((text(result).match(/Re-read/g) ?? []).length, 1);
61
+ assert.equal((text(result).match(/\[then_run:stale\]/g) ?? []).length, 1);
42
62
  for (const update of updates) assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
43
63
  }
44
64
  }
@@ -108,15 +128,24 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
108
128
  const result = await tool.execute(name, { path, ...args }, undefined, undefined, { cwd: dir });
109
129
  const output = text(result);
110
130
  assert.ok(Buffer.byteLength(output) < 17 * 1024);
111
- assert.match(output, /omitted|truncated/i);
131
+ assert.match(output, new RegExp(`^${name === "edit" ? 2 : 1}#[0-9A-Z]+$`, "m"));
132
+ assert.doesNotMatch(output, /omitted|truncated/i);
112
133
  assert.doesNotMatch(output, /\d+#[0-9A-Z]+│界/);
113
134
  assert.ok((await readFile(path, "utf8")).includes(long));
135
+ await writeFile(path, `remove\n${long}\n`);
136
+ const deletion = name === "edit"
137
+ ? { edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove")}` }] }
138
+ : { find: "remove\n", replace: "" };
139
+ const deleted = await tool.execute(name, { path, ...deletion }, undefined, undefined, { cwd: dir });
140
+ assert.ok(Buffer.byteLength(text(deleted)) < 17 * 1024);
141
+ assert.match(text(deleted), /additional anchors omitted: 16 KiB limit/);
142
+ assert.doesNotMatch(text(deleted), /^\d+#[0-9A-Z]+/m);
114
143
  }
115
144
  await writeFile(path, "current\n");
116
145
  await assert.rejects(makeEditOverride(dir).execute("errors", {
117
146
  path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })),
118
147
  }, undefined, undefined, { cwd: dir }), (error: Error) => {
119
- assert.ok(Buffer.byteLength(error.message) <= 16 * 1024);
148
+ assertFailureByteBudgets(error.message);
120
149
  assert.match(error.message, /omitted|truncated/i);
121
150
  return true;
122
151
  });
@@ -157,7 +186,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
157
186
  await assert.rejects(makeEditOverride(dir).execute("ambiguous", {
158
187
  path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: `50#${computeLineHash(50, "same")}` })),
159
188
  }, undefined, undefined, { cwd: dir }), (error: Error) => {
160
- assert.ok(Buffer.byteLength(error.message) <= 16 * 1024);
189
+ assertFailureByteBudgets(error.message);
161
190
  assert.match(error.message, /ambiguous checksum matches/);
162
191
  assert.match(error.message, /candidates omitted/);
163
192
  assert.doesNotMatch(error.message, /same content/);
@@ -167,3 +196,207 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
167
196
  await rm(dir, { recursive: true, force: true });
168
197
  }
169
198
  });
199
+
200
+ test("all mutation tools report NUL rejection through the shared Fusion lifecycle", async () => {
201
+ const dir = await mkdtemp(join(tmpdir(), "hashline-nul-"));
202
+ try {
203
+ const path = join(dir, "file.txt");
204
+ await writeFile(path, "original\n");
205
+ let commands = 0;
206
+ for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
207
+ const events: string[] = [];
208
+ const fusion = createActionFusionExecutor(async () => { commands++; return "unexpected"; }, (event) => events.push(event.command));
209
+ const tool = makeTool(dir, fusion);
210
+ const args = tool.name === "edit" ? { edits: [{ op: "append", body: ["\0"] }] }
211
+ : tool.name === "replace" ? { find: "original", replace: "\0" } : { content: "\0" };
212
+ await assert.rejects(tool.execute("nul", { path, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }),
213
+ (error: any) => error.publication === "NOT_PUBLISHED" && error.command === "skipped" && /NUL/.test(error.message));
214
+ assert.deepEqual(events, ["waiting", "skipped"]);
215
+ assert.equal(await readFile(path, "utf8"), "original\n");
216
+ }
217
+ assert.equal(commands, 0);
218
+ } finally {
219
+ await rm(dir, { recursive: true, force: true });
220
+ }
221
+ });
222
+
223
+ test("shared result building preserves publication and appends anchors only to the summary", () => {
224
+ for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
225
+ const cause = new Error("render failed");
226
+ assert.throws(() => postProcessMutation("replace", publication, () => { throw cause; }),
227
+ (error: any) => error instanceof FileMutationError && error.stage === "post_process" && error.publication === publication && error.cause === cause);
228
+ }
229
+ const result = { content: [{ type: "text" as const, text: "summary" }, { type: "text" as const, text: "command" }], details: {} };
230
+ assert.deepEqual(appendMutationAnchors(result, " ANCHOR", true).content.map((block: any) => block.text), ["summary ANCHOR", "command"]);
231
+ assert.deepEqual(appendMutationAnchors(result, " ANCHOR", false), result);
232
+ assert.equal(result.content[0].text, "summary");
233
+ });
234
+
235
+ const noOpCases = [
236
+ { makeTool: makeEditOverride, params: { edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "same")}`, body: ["same"] }] } },
237
+ { makeTool: makeReplaceTool, params: { find: "same", replace: "same" } },
238
+ { makeTool: makeWriteOverride, params: { content: "same\n" } },
239
+ ];
240
+
241
+ test("all mutation tools succeed without rewriting on no-op, with and without Fusion", async () => {
242
+ const dir = await mkdtemp(join(tmpdir(), "hashline-noop-"));
243
+ try {
244
+ for (const { makeTool, params } of noOpCases) {
245
+ for (const mode of ["standalone", "fusion", "command"]) {
246
+ const path = join(dir, "same.txt");
247
+ await writeFile(path, "same\n");
248
+ const before = await stat(path);
249
+ let commands = 0;
250
+ const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
251
+ const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
252
+ const result = await tool.execute(tool.name, { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) }, undefined, undefined, { cwd: dir });
253
+ assert.match(text(result), /no net change/);
254
+ assert.equal(result.details.publication, "NOT_PUBLISHED");
255
+ const revision = byteRevision(Buffer.from("same\n"));
256
+ for (const key of ["baseRevision", "publishedRevision", "observedRevision", "revision"]) assert.equal(result.details[key], revision);
257
+ assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
258
+ assert.equal(commands, mode === "command" ? 1 : 0);
259
+ if (mode !== "standalone") {
260
+ assert.equal(result.details.actionFusion.command, mode === "command" ? "succeeded" : "not_requested");
261
+ assert.equal(result.details.actionFusion.freshness, "unchanged");
262
+ }
263
+ const after = await stat(path);
264
+ assert.deepEqual([after.ino, after.mtimeMs, after.ctimeMs], [before.ino, before.mtimeMs, before.ctimeMs]);
265
+ assert.equal(await readFile(path, "utf8"), "same\n");
266
+ }
267
+ }
268
+ } finally { await rm(dir, { recursive: true, force: true }); }
269
+ });
270
+
271
+ test("no-op Fusion still detects external changes and reports command failures", async () => {
272
+ const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
273
+ try {
274
+ for (const { makeTool, params } of noOpCases) {
275
+ for (const scenario of ["before", "during", "failed"]) {
276
+ const path = join(dir, "same.txt");
277
+ await writeFile(path, "same\n");
278
+ let commands = 0;
279
+ const fusion = createActionFusionExecutor(async () => {
280
+ commands++;
281
+ if (scenario === "failed") throw new Error("check failed");
282
+ await writeFile(path, "external\n");
283
+ return "done";
284
+ }, (progress) => {
285
+ if (scenario === "before" && progress.mutationCompleted && progress.command === "waiting") writeFileSync(path, "external\n");
286
+ });
287
+ const tool: any = makeTool(dir, fusion);
288
+ const result = await tool.execute(tool.name, { path, ...params, then_run: { command: "check" } }, undefined, undefined, { cwd: dir });
289
+ assert.equal(result.details.publication, "NOT_PUBLISHED");
290
+ assert.equal(commands, scenario === "before" ? 0 : 1);
291
+ assert.equal(result.details.actionFusion.command, scenario === "before" ? "skipped" : scenario === "failed" ? "failed" : "succeeded");
292
+ assert.equal(result.details.actionFusion.freshness, scenario === "failed" ? "unchanged" : "changed");
293
+ }
294
+ }
295
+ } finally { await rm(dir, { recursive: true, force: true }); }
296
+ });
297
+
298
+ test("mutation anchors omit unchanged positions across distant changes", async () => {
299
+ const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delta-"));
300
+ try {
301
+ const before = Array.from({ length: 100 }, (_, index) => `row ${index + 1}`);
302
+ const after = [...before];
303
+ after[0] = "changed first";
304
+ after[99] = "changed last";
305
+ for (const name of ["edit", "replace"]) {
306
+ const path = join(dir, `${name}.txt`);
307
+ await writeFile(path, before.join("\r\n") + "\r\n");
308
+ const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
309
+ const params = name === "edit"
310
+ ? { edits: [{ op: "replace", anchor: `1#${computeLineHash(1, before[0])}`, end: `100#${computeLineHash(100, before[99])}`, body: after }] }
311
+ : { replacements: [{ find: before[0] + "\r\n", replace: after[0] + "\r\n" }, { find: before[99], replace: after[99] }] };
312
+ const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
313
+ const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
314
+ assert.deepEqual(returned, [`1#${computeLineHash(1, after[0])}`, `100#${computeLineHash(100, after[99])}`]);
315
+ assert.doesNotMatch(text(result), /omitted/);
316
+ // An omitted stable row keeps its old anchor; a changed row uses the returned anchor.
317
+ await makeEditOverride(dir).execute("chain", { path, edits: [
318
+ { op: "replace", anchor: `50#${computeLineHash(50, before[49])}`, body: ["stable anchor reused"] },
319
+ { op: "replace", anchor: returned[1], body: ["fresh anchor reused"] },
320
+ ] }, undefined, undefined, { cwd: dir });
321
+ const final = (await readFile(path, "utf8")).split("\r\n");
322
+ assert.equal(final[49], "stable anchor reused");
323
+ assert.equal(final[99], "fresh anchor reused");
324
+ }
325
+ } finally { await rm(dir, { recursive: true, force: true }); }
326
+ });
327
+
328
+ test("mutation anchors retain a deletion successor but omit stable rows and deleted EOF", async () => {
329
+ const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delete-"));
330
+ try {
331
+ for (const name of ["edit", "replace"]) {
332
+ for (const atEnd of [false, true]) {
333
+ const path = join(dir, `${name}.txt`);
334
+ const lines = atEnd ? ["a", "c", "remove"] : ["a", "remove", "c", "d"];
335
+ await writeFile(path, lines.join("\n") + "\n");
336
+ const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
337
+ const line = atEnd ? 3 : 2;
338
+ const params = name === "edit"
339
+ ? { edits: [{ op: "delete", anchor: `${line}#${computeLineHash(line, "remove")}` }] }
340
+ : { find: "remove\n", replace: "" };
341
+ const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
342
+ const rows = text(result).split("\n").filter((row) => /^\d+#/.test(row));
343
+ assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c")}│c`]);
344
+ }
345
+ }
346
+ } finally { await rm(dir, { recursive: true, force: true }); }
347
+ });
348
+
349
+ test("compact mutation anchors exceed forty rows while respecting the byte budget", async () => {
350
+ const dir = await mkdtemp(join(tmpdir(), "hashline-compact-budget-"));
351
+ try {
352
+ for (const name of ["edit", "replace"]) {
353
+ for (const count of [80, 3000]) {
354
+ const path = join(dir, `${name}.txt`);
355
+ await writeFile(path, "before\n");
356
+ const inserted = Array.from({ length: count }, (_, i) => `changed ${i}`);
357
+ const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
358
+ const params = name === "edit"
359
+ ? { edits: [{ op: "append", body: inserted }] }
360
+ : { find: "before", replace: inserted.join("\n") };
361
+ const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
362
+ const output = text(result);
363
+ const rows = [...output.matchAll(/^(\d+)#([0-9A-Z]+)$/gm)];
364
+ assert.ok(rows.length > 40);
365
+ assert.doesNotMatch(output, /│/);
366
+ const anchorBlock = output.slice(output.indexOf("\nUpdated anchors:"));
367
+ assert.ok(Buffer.byteLength(anchorBlock) <= 16 * 1024);
368
+ if (count === 80) {
369
+ assert.equal(rows.length, count);
370
+ assert.doesNotMatch(output, /omitted/);
371
+ } else {
372
+ assert.ok(rows.length < count);
373
+ assert.match(output, /additional anchors omitted: 16 KiB limit/);
374
+ }
375
+ const finalLines = (await readFile(path, "utf8")).trimEnd().split("\n");
376
+ for (const [, line, hash] of rows) assert.equal(hash, computeLineHash(Number(line), finalLines[Number(line) - 1]));
377
+ }
378
+ }
379
+ } finally { await rm(dir, { recursive: true, force: true }); }
380
+ });
381
+
382
+ test("oversized deletion successors do not suppress later editable anchors", async () => {
383
+ const dir = await mkdtemp(join(tmpdir(), "hashline-skip-long-anchor-"));
384
+ try {
385
+ const path = join(dir, "fixture.txt");
386
+ const long = "x".repeat(17000);
387
+ await writeFile(path, `remove\n${long}\nold\n`);
388
+ const tool = makeEditOverride(dir);
389
+ const result = await tool.execute("skip", { path, edits: [
390
+ { op: "delete", anchor: `1#${computeLineHash(1, "remove")}` },
391
+ { op: "replace", anchor: `3#${computeLineHash(3, "old")}`, body: ["new"] },
392
+ ] }, undefined, undefined);
393
+ const output = text(result);
394
+ assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
395
+ const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
396
+ assert.equal(anchor, `2#${computeLineHash(2, "new")}`);
397
+ assert.match(output, /additional anchors omitted: 16 KiB limit/);
398
+ assert.ok(Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= 16 * 1024);
399
+ await tool.execute("retry", { path, edits: [{ op: "replace", anchor, body: ["verified"] }] }, undefined, undefined);
400
+ assert.equal(await readFile(path, "utf8"), `${long}\nverified\n`);
401
+ } finally { await rm(dir, { recursive: true, force: true }); }
402
+ });
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { resolveIgnoreCase, type RunText } from "./rg-line-filter.ts";
3
+ import { assertRgSucceeded, resolveIgnoreCase, type RunText } from "./rg-line-filter.ts";
4
4
 
5
5
  const regexMode = { engine: "default", multiline: false, literal: false } as const;
6
6
  const literalMode = { ...regexMode, literal: true } as const;
@@ -77,3 +77,9 @@ test("smart-case probe normalizes cancellation without fallback", async () => {
77
77
  };
78
78
  await assert.rejects(resolveIgnoreCase("rg", ["foo"], regexMode, undefined, controller.signal, run), /Operation aborted/);
79
79
  });
80
+
81
+ test("search exit status accepts no matches and preserves failure diagnostics", () => {
82
+ for (const code of [0, 1]) assert.doesNotThrow(() => assertRgSucceeded({ code, stderr: "" }));
83
+ assert.throws(() => assertRgSucceeded({ code: 2, stderr: " regex parse error\n" }), /^Error: regex parse error$/);
84
+ assert.throws(() => assertRgSucceeded({ code: null, stderr: "" }), /ripgrep exited with code null/);
85
+ });
@@ -1,5 +1,6 @@
1
1
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import type { Readable } from "node:stream";
3
+ import { escapeRegex } from "../core/text.ts";
3
4
 
4
5
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--crlf"];
5
6
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
@@ -154,8 +155,11 @@ export function runRgPaths(
154
155
  });
155
156
  }
156
157
 
157
- function escapeRegex(text: string): string {
158
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
+ /** Accept both matches and no matches; callers handle intentional early stops separately. */
159
+ export function assertRgSucceeded(result: Pick<RgRunResult, "code" | "stderr">): void {
160
+ if (result.code !== 0 && result.code !== 1) {
161
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
162
+ }
159
163
  }
160
164
 
161
165
  interface TextRunResult {
@@ -267,9 +271,7 @@ export async function resolveIgnoreCase(
267
271
  signal,
268
272
  );
269
273
  checkAbort(signal);
270
- if (result.code !== 0 && result.code !== 1) {
271
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
272
- }
274
+ assertRgSucceeded(result);
273
275
  const lines = result.stdout.replace(/\r\n/g, "\n").split("\n");
274
276
  if (lines.some((line) => line !== "" && line !== "a")) throw new Error("Unexpected smart-case probe output");
275
277
  return lines.includes("a");
@@ -292,9 +294,7 @@ export async function validatePatterns(
292
294
  signal,
293
295
  );
294
296
  checkAbort(signal);
295
- if (result.code !== 0 && result.code !== 1) {
296
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
297
- }
297
+ assertRgSucceeded(result);
298
298
  }
299
299
  }
300
300
 
@@ -349,9 +349,7 @@ export function createLinePredicate(
349
349
  matches.push(event.type === "match");
350
350
  return true;
351
351
  });
352
- if (result.code !== 0 && result.code !== 1) {
353
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
354
- }
352
+ assertRgSucceeded(result);
355
353
  if (matches.length !== lines.length) throw new Error("rg predicate ended before all responses");
356
354
  return matches;
357
355
  };
@@ -28,3 +28,13 @@ test("rejects malformed ranges and rg byte offsets", () => {
28
28
  assert.throws(() => normalizeRanges([[0, 1]]), /Invalid physical line range/);
29
29
  assert.throws(() => submatchesToLineRanges(Buffer.from("a"), 1, [{ start: 0, end: 2 }], 1), /Invalid rg submatch/);
30
30
  });
31
+
32
+ test("match columns translate UTF-8 bytes to UTF-16 positions and retain EOF previews", () => {
33
+ const columns = new Map<number, number>();
34
+ const bytes = Buffer.from("😀界needle\ntail\n");
35
+ submatchesToLineRanges(bytes, 1, [{ start: 7, end: 13 }, { start: bytes.length, end: bytes.length }], 2, columns);
36
+ assert.deepEqual([...columns], [[1, 3], [2, 4]]);
37
+ const first = new Map<number, number>();
38
+ submatchesToLineRanges(bytes, 1, [{ start: 0, end: 13 }], 2, first);
39
+ assert.equal(first.get(1), 0);
40
+ });
@@ -1,4 +1,6 @@
1
- export type LineRange = readonly [start: number, endExclusive: number];
1
+ import { mergeRanges, type HalfOpenRange } from "../core/ranges.ts";
2
+
3
+ export type LineRange = HalfOpenRange;
2
4
 
3
5
  export interface RgSubmatch {
4
6
  start: number;
@@ -12,17 +14,8 @@ function assertRange(range: LineRange): void {
12
14
  }
13
15
 
14
16
  export function normalizeRanges(ranges: readonly LineRange[]): LineRange[] {
15
- const sorted = ranges.map((range) => {
16
- assertRange(range);
17
- return range;
18
- }).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
19
- const result: LineRange[] = [];
20
- for (const range of sorted) {
21
- const previous = result[result.length - 1];
22
- if (!previous || range[0] > previous[1]) result.push([range[0], range[1]]);
23
- else if (range[1] > previous[1]) result[result.length - 1] = [previous[0], range[1]];
24
- }
25
- return result;
17
+ for (const range of ranges) assertRange(range);
18
+ return mergeRanges(ranges);
26
19
  }
27
20
 
28
21
  export function unionRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
@@ -77,17 +70,23 @@ function zeroWidthLine(bytes: Buffer, offset: number, eventStartLine: number, fi
77
70
  return Math.min(candidate, fileLineCount);
78
71
  }
79
72
 
80
- /** Convert rg UTF-8 byte offsets into normalized 1-based physical line ranges. */
73
+ /** Convert rg byte offsets to physical line ranges; optionally record a match's UTF-16 column on its starting line. */
81
74
  export function submatchesToLineRanges(
82
75
  bytes: Buffer,
83
76
  eventStartLine: number,
84
77
  submatches: readonly RgSubmatch[],
85
78
  fileLineCount: number,
79
+ columns?: Map<number, number>,
86
80
  ): LineRange[] {
87
81
  if (!Number.isSafeInteger(eventStartLine) || eventStartLine < 1 || !Number.isSafeInteger(fileLineCount) || fileLineCount < 0) {
88
82
  throw new Error("Invalid rg physical line metadata");
89
83
  }
90
84
  const ranges: LineRange[] = [];
85
+ const recordColumn = (line: number, offset: number) => {
86
+ if (!columns || columns.has(line)) return;
87
+ const lineStart = offset === 0 ? 0 : bytes.lastIndexOf(10, offset - 1) + 1;
88
+ columns.set(line, bytes.subarray(lineStart, offset).toString("utf8").length);
89
+ };
91
90
  for (const submatch of submatches) {
92
91
  const { start, end } = submatch;
93
92
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end > bytes.length) {
@@ -95,12 +94,19 @@ export function submatchesToLineRanges(
95
94
  }
96
95
  if (start === end) {
97
96
  const line = zeroWidthLine(bytes, start, eventStartLine, fileLineCount);
98
- if (line !== undefined) ranges.push([line, line + 1]);
97
+ if (line !== undefined) {
98
+ ranges.push([line, line + 1]);
99
+ const offset = eventStartLine + countLfBefore(bytes, start) > fileLineCount ? Math.max(0, start - 1) : start;
100
+ recordColumn(line, offset);
101
+ }
99
102
  continue;
100
103
  }
101
104
  const first = eventStartLine + countLfBefore(bytes, start);
102
105
  const last = eventStartLine + countLfBefore(bytes, end - 1);
103
- if (first <= fileLineCount) ranges.push([first, Math.min(last, fileLineCount) + 1]);
106
+ if (first <= fileLineCount) {
107
+ ranges.push([first, Math.min(last, fileLineCount) + 1]);
108
+ recordColumn(first, start);
109
+ }
104
110
  }
105
111
  return normalizeRanges(ranges);
106
112
  }
package/src/pi/state.ts CHANGED
@@ -8,10 +8,9 @@
8
8
  * @module pi-hashline-edit/pi
9
9
  */
10
10
 
11
- import type { HashlineEditConfig } from "./config.ts";
11
+ import { DEFAULT_CONFIG, type HashlineEditConfig } from "./config.ts";
12
12
 
13
13
  const GLOBAL_KEY = "__piHashlineEdit";
14
- const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: false, hashLen: 4, shiftRadius: 15 };
15
14
 
16
15
  export interface HashlineEditState {
17
16
  config: HashlineEditConfig;
@@ -21,7 +20,7 @@ export function getState(): HashlineEditState {
21
20
  const g = globalThis as Record<string, unknown>;
22
21
  const existing = g[GLOBAL_KEY];
23
22
  if (existing) return existing as HashlineEditState;
24
- const state: HashlineEditState = { config: DEFAULT_CONFIG };
23
+ const state: HashlineEditState = { config: { ...DEFAULT_CONFIG } };
25
24
  g[GLOBAL_KEY] = state;
26
25
  return state;
27
26
  }
@@ -1,11 +1,9 @@
1
1
  import { Type, type Static } from "typebox";
2
2
  import { createWriteToolDefinition, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
3
- import { getState } from "./state.ts";
4
3
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
5
- import { commitFile, FileMutationError, type CommitMode } from "./file-commit.ts";
4
+ import { commitFile, type CommitMode } from "./file-commit.ts";
5
+ import { postProcessMutation } from "./mutation-result.ts";
6
6
  import { canonicalPath } from "./read-tool.ts";
7
- import { computeLineHash, splitLines } from "../core/index.ts";
8
- import { finalizeMutationResult } from "./mutation-result.ts";
9
7
 
10
8
  function createWriteSchema(actionFusion: boolean) {
11
9
  return Type.Object({
@@ -23,13 +21,6 @@ function createWriteSchema(actionFusion: boolean) {
23
21
  const writeSchema = createWriteSchema(false);
24
22
  type WriteParams = Omit<Static<typeof writeSchema>, "then_run"> & { then_run?: ThenRunInput };
25
23
 
26
- function formatAnchors(content: string, hashLen: number): string {
27
- const lines = splitLines(content);
28
- const shown = lines.slice(0, 40).map((line, index) => `${index + 1}#${computeLineHash(index + 1, line, hashLen)}`);
29
- const suffix = lines.length > shown.length ? `\n… (${lines.length - shown.length} more; read again for full anchors)` : "";
30
- return shown.length ? `\nFresh anchors: ${shown.join(", ")}${suffix}` : "";
31
- }
32
-
33
24
  export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
34
25
  const parameters = createWriteSchema(fusion !== undefined);
35
26
  const builtin = createWriteToolDefinition(cwd);
@@ -46,10 +37,7 @@ export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof create
46
37
  async execute(toolCallId: string, params: WriteParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
47
38
  const { then_run, ...mutationParams } = params;
48
39
  if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
49
- if (mutationParams.content.includes("\0")) throw new Error("UNSUPPORTED_TEXT: NUL bytes are not editable.");
50
40
  const absolutePath = canonicalPath(cwd, mutationParams.path);
51
- const hashLen = getState().config.hashLen;
52
- let mutationAnchors = "";
53
41
  const mutate = () => withFileMutationQueue(absolutePath, async () => {
54
42
  signal?.throwIfAborted();
55
43
  const result = await commitFile(absolutePath, mutationParams.content, {
@@ -57,37 +45,15 @@ export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof create
57
45
  expectedRevision: mutationParams.expectedRevision,
58
46
  signal,
59
47
  });
60
- try {
61
- mutationAnchors = formatAnchors(mutationParams.content, hashLen);
62
- return {
63
- content: [{ type: "text" as const, text: `${result.created ? "Created" : "Wrote"} ${mutationParams.path}.\nRevision: ${result.revision}` }],
64
- details: {
65
- path: mutationParams.path,
66
- revision: result.publishedRevision,
67
- baseRevision: result.baseRevision,
68
- publishedRevision: result.publishedRevision,
69
- observedRevision: result.observedRevision,
70
- created: result.created,
71
- publication: result.publication,
72
- },
73
- };
74
- } catch (error) {
75
- throw new FileMutationError("post_process", "PUBLISHED", `file was published but write result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
76
- }
48
+ return postProcessMutation("write", result.publication, () => ({
49
+ content: [{ type: "text" as const, text: result.publication === "NOT_PUBLISHED"
50
+ ? `Wrote ${mutationParams.path} (no net change).`
51
+ : `${result.created ? "Created" : "Wrote"} ${mutationParams.path}.` }],
52
+ details: { path: mutationParams.path, ...result },
53
+ }));
77
54
  });
78
- const finalizeMutation = (result: any, publishAnchors: boolean) => {
79
- const details = result.details as { path: string; revision: string; created: boolean };
80
- const revisionLabel = publishAnchors ? "Revision" : "Mutation revision";
81
- return {
82
- ...result,
83
- content: [{
84
- type: "text" as const,
85
- text: `${details.created ? "Created" : "Wrote"} ${details.path}.\n${revisionLabel}: ${details.revision}${publishAnchors ? mutationAnchors : ""}`,
86
- }],
87
- };
88
- };
89
- if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
90
- return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, finalizeMutation, signal, ctx, onUpdate });
55
+ if (!fusion) return mutate();
56
+ return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, signal, ctx, onUpdate });
91
57
  },
92
58
  };
93
59
  }