@criogaid/pi-hashline-edit 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +116 -20
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.ts +1 -3
  10. package/src/core/types.ts +4 -7
  11. package/src/index.ts +9 -11
  12. package/src/integration/config-registration.test.ts +206 -0
  13. package/src/integration/grep-rg.test.ts +73 -60
  14. package/src/integration/large-text.test.ts +9 -8
  15. package/src/integration/replace-package.test.ts +11 -7
  16. package/src/pi/action-fusion.test.ts +110 -34
  17. package/src/pi/action-fusion.ts +77 -114
  18. package/src/pi/anchor-format.test.ts +43 -22
  19. package/src/pi/anchor-format.ts +23 -8
  20. package/src/pi/budgets.ts +7 -2
  21. package/src/pi/config.test.ts +153 -40
  22. package/src/pi/config.ts +87 -41
  23. package/src/pi/e2e-scenarios.test.ts +12 -11
  24. package/src/pi/edit-tool.ts +20 -156
  25. package/src/pi/error-text.ts +10 -5
  26. package/src/pi/execute.test.ts +299 -175
  27. package/src/pi/failure-context.test.ts +7 -2
  28. package/src/pi/failure-context.ts +155 -8
  29. package/src/pi/failure-path.test.ts +33 -26
  30. package/src/pi/file-commit.ts +2 -1
  31. package/src/pi/fusion-card.ts +83 -2
  32. package/src/pi/grep-output.ts +26 -9
  33. package/src/pi/grep-render.ts +6 -5
  34. package/src/pi/grep-scope.ts +2 -15
  35. package/src/pi/grep-search.ts +29 -15
  36. package/src/pi/grep-tool.ts +94 -78
  37. package/src/pi/grep.test.ts +357 -320
  38. package/src/pi/mutation-outcome.testing.ts +22 -0
  39. package/src/pi/mutation-result.test.ts +51 -2
  40. package/src/pi/mutation-result.ts +62 -55
  41. package/src/pi/mutation-runner.ts +16 -33
  42. package/src/pi/pi.test.ts +10 -5
  43. package/src/pi/read-tool.ts +61 -33
  44. package/src/pi/registration.test.ts +1 -5
  45. package/src/pi/render.test.ts +16 -8
  46. package/src/pi/render.ts +4 -91
  47. package/src/pi/replace-regex.ts +54 -0
  48. package/src/pi/replace-tool.ts +24 -58
  49. package/src/pi/replace-worker.ts +2 -2
  50. package/src/pi/replace.test.ts +62 -58
  51. package/src/pi/result-safety.test.ts +124 -84
  52. package/src/pi/rg-line-ranges.ts +3 -2
  53. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  54. package/src/pi/{rg-line-filter.ts → rg-process.ts} +35 -4
  55. package/src/pi/rg-text-view.ts +17 -33
  56. package/src/pi/schema.ts +2 -10
  57. package/src/pi/write-tool.ts +1 -2
  58. package/src/pi/write.test.ts +10 -9
  59. package/src/core/index.ts +0 -14
  60. package/src/pi/state.ts +0 -26
@@ -7,17 +7,21 @@ import { writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { test } from "node:test";
10
- import { createActionFusionExecutor } from "./action-fusion.ts";
10
+ import { createActionFusionExecutor, THEN_RUN_STALE } from "./action-fusion.ts";
11
11
  import { makeReplaceTool } from "./replace-tool.ts";
12
12
  import { makeWriteOverride } from "./write-tool.ts";
13
13
  import { makeEditOverride } from "./edit-tool.ts";
14
14
  import { byteRevision, FileMutationError } from "./file-commit.ts";
15
15
  import {
16
- appendMutationAnchors,
17
- finalizeMutationResult,
16
+ commitFreshness,
17
+ finalizeMutation,
18
18
  postProcessMutation,
19
+ staleTargetNotice,
20
+ type MutationOutcome,
19
21
  } from "./mutation-result.ts";
20
22
  import { callTool } from "./tool-call.testing.ts";
23
+ import { DEFAULT_CONFIG } from "./config.ts";
24
+ import { publishedMutation } from "./mutation-outcome.testing.ts";
21
25
 
22
26
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
23
27
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
@@ -77,7 +81,7 @@ test("replace withholds anchors in progress and after commands change or remove
77
81
  return "done";
78
82
  });
79
83
  const result = await invoke(
80
- makeReplaceTool(dir, fusion),
84
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
81
85
  "replace",
82
86
  {
83
87
  path,
@@ -92,8 +96,16 @@ test("replace withholds anchors in progress and after commands change or remove
92
96
  assert.equal(result.details.actionFusion.freshness, state);
93
97
  assert.equal(result.details.publication, "PUBLISHED");
94
98
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
95
- assert.equal((text(result).match(/Re-read/g) ?? []).length, 1);
96
- assert.equal((text(result).match(/\[then_run:stale\]/g) ?? []).length, 1);
99
+ assert.deepEqual(result.content[1], {
100
+ type: "text",
101
+ text: staleTargetNotice(THEN_RUN_STALE),
102
+ });
103
+ assert.equal(
104
+ result.content.filter(
105
+ (block: any) => block.type === "text" && block.text.includes(THEN_RUN_STALE),
106
+ ).length,
107
+ 1,
108
+ );
97
109
  for (const update of updates)
98
110
  assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
99
111
  }
@@ -159,47 +171,59 @@ test("progress callback failures preserve publication and do not prevent the com
159
171
  }
160
172
  });
161
173
 
162
- test("standalone and Fusion finalizers suppress anchors unless commit observations agree", async () => {
174
+ test("standalone and Fusion finalizers use commit freshness with or without anchors", async () => {
163
175
  const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
164
176
  try {
165
- for (const observedRevision of ["published", "external", undefined]) {
166
- const mutation = {
167
- content: [{ type: "text" as const, text: "saved" }],
168
- details: {
169
- publication: "PUBLISHED" as const,
170
- publishedRevision: "published",
171
- observedRevision,
172
- },
173
- };
174
- const finalize = (result: AgentToolResult<typeof mutation.details>, expose: boolean) => ({
175
- ...result,
176
- content: [{ type: "text" as const, text: `saved${expose ? " ANCHOR" : ""}` }],
177
- });
178
- const standalone = finalizeMutationResult(mutation, finalize);
179
- const fused = await createActionFusionExecutor()({
180
- toolCallId: "no-command",
181
- absolutePath: join(dir, "file"),
182
- thenRun: undefined,
183
- mutate: async () => mutation,
184
- finalizeMutation: finalize,
185
- signal: undefined,
186
- ctx: ctx(dir),
187
- });
188
- for (const result of [standalone, fused]) {
189
- assert.equal(text(result).includes("ANCHOR"), observedRevision === "published");
190
- assert.equal(result.details.publication, "PUBLISHED");
191
- if (observedRevision !== "published") assert.match(text(result), /Re-read/);
177
+ for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
178
+ for (const observedRevision of ["published", "external"]) {
179
+ for (const anchors of [" ANCHOR", undefined]) {
180
+ const mutation = {
181
+ result: {
182
+ content: [{ type: "text", text: "saved" }],
183
+ details: {
184
+ publication: "UNKNOWN",
185
+ publishedRevision: "ignored",
186
+ observedRevision: "ignored",
187
+ },
188
+ },
189
+ commit: {
190
+ publication,
191
+ publishedRevision: "published",
192
+ observedRevision,
193
+ created: false,
194
+ },
195
+ anchors,
196
+ } satisfies MutationOutcome<unknown>;
197
+ const fresh = observedRevision === "published";
198
+ assert.equal(commitFreshness(mutation.commit), fresh ? "unchanged" : "changed");
199
+ const standalone = finalizeMutation(
200
+ mutation,
201
+ commitFreshness(mutation.commit) === "unchanged",
202
+ );
203
+ const fused = await createActionFusionExecutor()({
204
+ toolCallId: "no-command",
205
+ absolutePath: join(dir, "file"),
206
+ thenRun: undefined,
207
+ mutate: async () => mutation,
208
+ signal: undefined,
209
+ ctx: ctx(dir),
210
+ });
211
+ const expectedContent = [{ type: "text", text: `saved${fresh ? (anchors ?? "") : ""}` }];
212
+ if (!fresh) expectedContent.push({ type: "text", text: staleTargetNotice() });
213
+ assert.deepEqual(standalone.content, expectedContent);
214
+ assert.deepEqual(fused.content, expectedContent);
215
+ assert.deepEqual(standalone.details, mutation.result.details);
216
+ assert.deepEqual(fused.details, {
217
+ ...mutation.result.details,
218
+ actionFusion: {
219
+ publication,
220
+ command: "not_requested",
221
+ freshness: fresh ? "unchanged" : "changed",
222
+ },
223
+ });
224
+ assert.deepEqual(mutation.result.content, [{ type: "text", text: "saved" }]);
225
+ }
192
226
  }
193
- assert.throws(
194
- () =>
195
- finalizeMutationResult(mutation, () => {
196
- throw new Error("formatting failed");
197
- }),
198
- (error: any) =>
199
- error instanceof FileMutationError &&
200
- error.publication === "PUBLISHED" &&
201
- /publication=PUBLISHED/.test(error.message),
202
- );
203
227
  }
204
228
  } finally {
205
229
  await rm(dir, { recursive: true, force: true });
@@ -216,7 +240,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
216
240
  const result =
217
241
  name === "edit"
218
242
  ? await invoke(
219
- makeEditOverride(dir),
243
+ makeEditOverride(dir, DEFAULT_CONFIG),
220
244
  name,
221
245
  { path, edits: [{ op: "append", body: [long] }] },
222
246
  undefined,
@@ -224,7 +248,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
224
248
  ctx(dir),
225
249
  )
226
250
  : await invoke(
227
- makeReplaceTool(dir),
251
+ makeReplaceTool(dir, DEFAULT_CONFIG),
228
252
  name,
229
253
  { path, replacements: [{ find: "before", replace: long }] },
230
254
  undefined,
@@ -241,15 +265,15 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
241
265
  const deleted =
242
266
  name === "edit"
243
267
  ? await invoke(
244
- makeEditOverride(dir),
268
+ makeEditOverride(dir, DEFAULT_CONFIG),
245
269
  name,
246
- { path, edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove")}` }] },
270
+ { path, edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove", 4)}` }] },
247
271
  undefined,
248
272
  undefined,
249
273
  ctx(dir),
250
274
  )
251
275
  : await invoke(
252
- makeReplaceTool(dir),
276
+ makeReplaceTool(dir, DEFAULT_CONFIG),
253
277
  name,
254
278
  { path, replacements: [{ find: "remove\n", replace: "" }] },
255
279
  undefined,
@@ -263,7 +287,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
263
287
  await writeFile(path, "current\n");
264
288
  await assert.rejects(
265
289
  invoke(
266
- makeEditOverride(dir),
290
+ makeEditOverride(dir, DEFAULT_CONFIG),
267
291
  "errors",
268
292
  {
269
293
  path,
@@ -300,12 +324,12 @@ test("unpaired surrogate arguments are rejected before Fusion", async () => {
300
324
  await writeFile(path, "original\n");
301
325
  const cases = [
302
326
  {
303
- tool: makeEditOverride(dir, fusion),
327
+ tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
304
328
  args: { path, edits: [{ op: "append", body: ["\ud800"] }], then_run: { command: "check" } },
305
329
  field: "edits[0].body[0]",
306
330
  },
307
331
  {
308
- tool: makeReplaceTool(dir, fusion),
332
+ tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
309
333
  args: {
310
334
  path,
311
335
  replacements: [{ find: "original", replace: "\udfff" }],
@@ -345,13 +369,13 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
345
369
  await writeFile(path, lines.join("\n"));
346
370
  await assert.rejects(
347
371
  invoke(
348
- makeEditOverride(dir),
372
+ makeEditOverride(dir, DEFAULT_CONFIG),
349
373
  "ambiguous",
350
374
  {
351
375
  path,
352
376
  edits: Array.from({ length: 1000 }, () => ({
353
377
  op: "delete",
354
- anchor: `50#${computeLineHash(50, "same")}`,
378
+ anchor: `50#${computeLineHash(50, "same", 4)}`,
355
379
  })),
356
380
  },
357
381
  undefined,
@@ -387,12 +411,12 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async ()
387
411
  );
388
412
  const cases = [
389
413
  {
390
- tool: makeEditOverride(dir, fusion),
414
+ tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
391
415
  args: { path, edits: [{ op: "append", body: ["\0"] }], then_run: { command: "check" } },
392
416
  field: "edits[0].body[0]",
393
417
  },
394
418
  {
395
- tool: makeReplaceTool(dir, fusion),
419
+ tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
396
420
  args: {
397
421
  path,
398
422
  replacements: [{ find: "original", replace: "\0" }],
@@ -440,7 +464,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
440
464
  );
441
465
  await assert.rejects(
442
466
  callTool(
443
- makeReplaceTool(dir, fusion),
467
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
444
468
  {
445
469
  path,
446
470
  replacements: [{ find: "^.", replace: "x", regex: true }],
@@ -483,22 +507,36 @@ test("shared result building preserves publication and appends anchors only to t
483
507
  ],
484
508
  details: {},
485
509
  };
510
+ const outcome = publishedMutation("saved", result, " ANCHOR");
486
511
  assert.deepEqual(
487
- appendMutationAnchors(result, " ANCHOR", true).content.map((block: any) => block.text),
512
+ finalizeMutation(outcome, true).content.map((block: any) => block.text),
488
513
  ["summary ANCHOR", "command"],
489
514
  );
490
- assert.deepEqual(appendMutationAnchors(result, " ANCHOR", false), result);
515
+ assert.deepEqual(finalizeMutation(outcome, false).content, [
516
+ ...result.content,
517
+ { type: "text", text: staleTargetNotice() },
518
+ ]);
491
519
  assert.equal(result.content[0].text, "summary");
492
520
  });
493
521
 
522
+ type Fusion = Parameters<typeof makeWriteOverride>[1];
494
523
  const noOpCases = [
495
524
  {
496
- makeTool: makeEditOverride,
525
+ makeTool: (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
497
526
  params: {
498
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "same")}`, body: ["same"] }],
527
+ edits: [
528
+ {
529
+ op: "replace",
530
+ anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
531
+ body: ["same"],
532
+ },
533
+ ],
499
534
  },
500
535
  },
501
- { makeTool: makeReplaceTool, params: { replacements: [{ find: "same", replace: "same" }] } },
536
+ {
537
+ makeTool: (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
538
+ params: { replacements: [{ find: "same", replace: "same" }] },
539
+ },
502
540
  { makeTool: makeWriteOverride, params: { content: "same\n" } },
503
541
  ];
504
542
 
@@ -615,15 +653,15 @@ test("mutation anchors omit unchanged positions across distant changes", async (
615
653
  const result =
616
654
  name === "edit"
617
655
  ? await invoke(
618
- makeEditOverride(dir),
656
+ makeEditOverride(dir, DEFAULT_CONFIG),
619
657
  name,
620
658
  {
621
659
  path,
622
660
  edits: [
623
661
  {
624
662
  op: "replace",
625
- anchor: `1#${computeLineHash(1, before[0])}`,
626
- end: `100#${computeLineHash(100, before[99])}`,
663
+ anchor: `1#${computeLineHash(1, before[0], 4)}`,
664
+ end: `100#${computeLineHash(100, before[99], 4)}`,
627
665
  body: after,
628
666
  },
629
667
  ],
@@ -633,7 +671,7 @@ test("mutation anchors omit unchanged positions across distant changes", async (
633
671
  ctx(dir),
634
672
  )
635
673
  : await invoke(
636
- makeReplaceTool(dir),
674
+ makeReplaceTool(dir, DEFAULT_CONFIG),
637
675
  name,
638
676
  {
639
677
  path,
@@ -648,20 +686,20 @@ test("mutation anchors omit unchanged positions across distant changes", async (
648
686
  );
649
687
  const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
650
688
  assert.deepEqual(returned, [
651
- `1#${computeLineHash(1, after[0])}`,
652
- `100#${computeLineHash(100, after[99])}`,
689
+ `1#${computeLineHash(1, after[0], 4)}`,
690
+ `100#${computeLineHash(100, after[99], 4)}`,
653
691
  ]);
654
692
  assert.doesNotMatch(text(result), /omitted/);
655
693
  // An omitted stable row keeps its old anchor; a changed row uses the returned anchor.
656
694
  await invoke(
657
- makeEditOverride(dir),
695
+ makeEditOverride(dir, DEFAULT_CONFIG),
658
696
  "chain",
659
697
  {
660
698
  path,
661
699
  edits: [
662
700
  {
663
701
  op: "replace",
664
- anchor: `50#${computeLineHash(50, before[49])}`,
702
+ anchor: `50#${computeLineHash(50, before[49], 4)}`,
665
703
  body: ["stable anchor reused"],
666
704
  },
667
705
  { op: "replace", anchor: returned[1], body: ["fresh anchor reused"] },
@@ -692,18 +730,20 @@ test("mutation anchors retain a deletion successor but omit stable rows and dele
692
730
  const result =
693
731
  name === "edit"
694
732
  ? await invoke(
695
- makeEditOverride(dir),
733
+ makeEditOverride(dir, DEFAULT_CONFIG),
696
734
  name,
697
735
  {
698
736
  path,
699
- edits: [{ op: "delete", anchor: `${line}#${computeLineHash(line, "remove")}` }],
737
+ edits: [
738
+ { op: "delete", anchor: `${line}#${computeLineHash(line, "remove", 4)}` },
739
+ ],
700
740
  },
701
741
  undefined,
702
742
  undefined,
703
743
  ctx(dir),
704
744
  )
705
745
  : await invoke(
706
- makeReplaceTool(dir),
746
+ makeReplaceTool(dir, DEFAULT_CONFIG),
707
747
  name,
708
748
  { path, replacements: [{ find: "remove\n", replace: "" }] },
709
749
  undefined,
@@ -713,7 +753,7 @@ test("mutation anchors retain a deletion successor but omit stable rows and dele
713
753
  const rows = text(result)
714
754
  .split("\n")
715
755
  .filter((row) => /^\d+#/.test(row));
716
- assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c")}│c`]);
756
+ assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c", 4)}│c`]);
717
757
  }
718
758
  }
719
759
  } finally {
@@ -727,13 +767,13 @@ test("mutation anchors retain deletion successor even when deleted line content
727
767
  const path = join(dir, "edit.txt");
728
768
  const lines = ["a", "duplicate", "duplicate", "d"];
729
769
  await writeFile(path, lines.join("\n") + "\n");
730
- const tool = makeEditOverride(dir);
770
+ const tool = makeEditOverride(dir, DEFAULT_CONFIG);
731
771
  const result = await invoke(
732
772
  tool,
733
773
  "edit",
734
774
  {
735
775
  path,
736
- edits: [{ op: "delete", anchor: `2#${computeLineHash(2, "duplicate")}` }],
776
+ edits: [{ op: "delete", anchor: `2#${computeLineHash(2, "duplicate", 4)}` }],
737
777
  },
738
778
  undefined,
739
779
  undefined,
@@ -742,7 +782,7 @@ test("mutation anchors retain deletion successor even when deleted line content
742
782
  const rows = text(result)
743
783
  .split("\n")
744
784
  .filter((row) => /^\d+#/.test(row));
745
- assert.deepEqual(rows, [`2#${computeLineHash(2, "duplicate")}│duplicate`]);
785
+ assert.deepEqual(rows, [`2#${computeLineHash(2, "duplicate", 4)}│duplicate`]);
746
786
  } finally {
747
787
  await rm(dir, { recursive: true, force: true });
748
788
  }
@@ -759,7 +799,7 @@ test("compact mutation anchors exceed forty rows while respecting the byte budge
759
799
  const result =
760
800
  name === "edit"
761
801
  ? await invoke(
762
- makeEditOverride(dir),
802
+ makeEditOverride(dir, DEFAULT_CONFIG),
763
803
  name,
764
804
  { path, edits: [{ op: "append", body: inserted }] },
765
805
  undefined,
@@ -767,7 +807,7 @@ test("compact mutation anchors exceed forty rows while respecting the byte budge
767
807
  ctx(dir),
768
808
  )
769
809
  : await invoke(
770
- makeReplaceTool(dir),
810
+ makeReplaceTool(dir, DEFAULT_CONFIG),
771
811
  name,
772
812
  { path, replacements: [{ find: "before", replace: inserted.join("\n") }] },
773
813
  undefined,
@@ -789,7 +829,7 @@ test("compact mutation anchors exceed forty rows while respecting the byte budge
789
829
  }
790
830
  const finalLines = (await readFile(path, "utf8")).trimEnd().split("\n");
791
831
  for (const [, line, hash] of rows)
792
- assert.equal(hash, computeLineHash(Number(line), finalLines[Number(line) - 1]));
832
+ assert.equal(hash, computeLineHash(Number(line), finalLines[Number(line) - 1], 4));
793
833
  }
794
834
  }
795
835
  } finally {
@@ -803,15 +843,15 @@ test("oversized deletion successors do not suppress later editable anchors", asy
803
843
  const path = join(dir, "fixture.txt");
804
844
  const long = "x".repeat(17000);
805
845
  await writeFile(path, `remove\n${long}\nold\n`);
806
- const tool = makeEditOverride(dir);
846
+ const tool = makeEditOverride(dir, DEFAULT_CONFIG);
807
847
  const result = await invoke(
808
848
  tool,
809
849
  "skip",
810
850
  {
811
851
  path,
812
852
  edits: [
813
- { op: "delete", anchor: `1#${computeLineHash(1, "remove")}` },
814
- { op: "replace", anchor: `3#${computeLineHash(3, "old")}`, body: ["new"] },
853
+ { op: "delete", anchor: `1#${computeLineHash(1, "remove", 4)}` },
854
+ { op: "replace", anchor: `3#${computeLineHash(3, "old", 4)}`, body: ["new"] },
815
855
  ],
816
856
  },
817
857
  undefined,
@@ -821,7 +861,7 @@ test("oversized deletion successors do not suppress later editable anchors", asy
821
861
  const output = text(result);
822
862
  assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
823
863
  const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
824
- assert.equal(anchor, `2#${computeLineHash(2, "new")}`);
864
+ assert.equal(anchor, `2#${computeLineHash(2, "new", 4)}`);
825
865
  assert.match(output, /additional anchors omitted: 16 KiB limit/);
826
866
  assert.ok(Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= 16 * 1024);
827
867
  await invoke(
@@ -1,4 +1,5 @@
1
1
  import { mergeRanges, type HalfOpenRange } from "../core/ranges.ts";
2
+ import { searchChangedError } from "./error-text.ts";
2
3
 
3
4
  interface RgSubmatch {
4
5
  start: number;
@@ -57,7 +58,7 @@ export function submatchesToLineRanges(
57
58
  if (start === end) {
58
59
  if (fileLineCount === 0) continue;
59
60
  const line = eventStartLine + countLfBefore(lineBreaks, start);
60
- if (line > fileLineCount) throw new Error("File changed during search; rerun the query.");
61
+ if (line > fileLineCount) throw searchChangedError();
61
62
  ranges.push([line, line + 1]);
62
63
  recordColumn(line, start);
63
64
  continue;
@@ -65,7 +66,7 @@ export function submatchesToLineRanges(
65
66
  const first = eventStartLine + countLfBefore(lineBreaks, start);
66
67
  const last = eventStartLine + countLfBefore(lineBreaks, end - 1);
67
68
  if (first > fileLineCount || last > fileLineCount) {
68
- throw new Error("File changed during search; rerun the query.");
69
+ throw searchChangedError();
69
70
  }
70
71
  ranges.push([first, last + 1]);
71
72
  recordColumn(first, start);
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { assertRgSucceeded, resolveIgnoreCase, type RunText } from "./rg-line-filter.ts";
3
+ import { assertRgSucceeded, resolveIgnoreCase, type RunText } from "./rg-process.ts";
4
4
 
5
5
  const lineModes = { literal: false, multiline: false } as const;
6
6
 
@@ -1,3 +1,11 @@
1
+ /**
2
+ * ripgrep process layer: spawning and cancelling rg, bounded record and
3
+ * stderr reading, shared arguments, matcher-mode probes, and rg JSON string
4
+ * decoding. Knows nothing about anchors or output formatting.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
8
+
1
9
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
10
  import type { Readable } from "node:stream";
3
11
  import { escapeRegex } from "../core/text.ts";
@@ -5,6 +13,7 @@ import { throwIfCancelled } from "./error-text.ts";
5
13
 
6
14
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
7
15
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
16
+ const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`;
8
17
  /** Retained ripgrep stderr; diagnostics beyond this are dropped. */
9
18
  export const MAX_RG_STDERR_BYTES = 64 * 1024;
10
19
  /** Probe runs read only a short stdout; more means an unexpected rg mode. */
@@ -91,11 +100,11 @@ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGene
91
100
  pending = Buffer.alloc(0);
92
101
  let at: number;
93
102
  while ((at = buf.indexOf(delimiter)) !== -1) {
94
- if (at > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
103
+ if (at > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
95
104
  yield buf.subarray(0, at);
96
105
  buf = buf.subarray(at + 1);
97
106
  }
98
- if (buf.length > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
107
+ if (buf.length > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
99
108
  pending = buf;
100
109
  }
101
110
  if (pending.length) yield pending;
@@ -131,7 +140,7 @@ async function runDelimited(
131
140
  }
132
141
  }
133
142
 
134
- /** @internal — shared process boundary for JSONL searches and regex validation. */
143
+ /** @internal — shared process boundary for JSONL searches. */
135
144
  export function runRg(
136
145
  rgPath: string,
137
146
  args: string[],
@@ -190,7 +199,7 @@ export const runText: RunText = async (rgPath, args, input, signal) => {
190
199
  process.child.stdin.end(input);
191
200
  const result = await process.done;
192
201
  throwIfCancelled(signal);
193
- if (result.error) throw result.error;
202
+ if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
194
203
  if (bytes > MAX_RG_PROBE_OUTPUT_BYTES)
195
204
  throw new Error("Unexpected ripgrep probe output overflow");
196
205
  return {
@@ -211,6 +220,28 @@ export function matcherArgs(modes: SearchModes): string[] {
211
220
  ];
212
221
  }
213
222
 
223
+ /** Compile the patterns with rg's default engine against empty input; code 2 with a parse error means invalid regex. */
224
+ export async function probeRegex(
225
+ rgPath: string,
226
+ patterns: readonly string[],
227
+ multiline: boolean,
228
+ signal?: AbortSignal,
229
+ ): Promise<Pick<TextRunResult, "code" | "stderr">> {
230
+ return runText(
231
+ rgPath,
232
+ [
233
+ ...DEFAULT_RG_MODE_ARGS,
234
+ multiline ? "--multiline" : "--no-multiline",
235
+ "--quiet",
236
+ ...patterns.flatMap((pattern) => ["-e", pattern]),
237
+ "--",
238
+ "-",
239
+ ],
240
+ Buffer.alloc(0),
241
+ signal,
242
+ );
243
+ }
244
+
214
245
  /** Resolve rg's query-level default case flag; inline regex flags still apply normally. */
215
246
  export async function resolveIgnoreCase(
216
247
  rgPath: string,