@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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 (66) hide show
  1. package/README.md +134 -30
  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.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -1,14 +1,25 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { generateDiffString, initTheme } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ generateDiffString,
5
+ initTheme,
6
+ type ToolDefinition,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { TSchema } from "typebox";
4
9
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
5
10
  import { displayCarriageReturns } from "./anchor-format.ts";
6
11
  import { makeEditOverride } from "./edit-tool.ts";
7
12
  import { makeReplaceTool } from "./replace-tool.ts";
8
- import { renderDiffPreview, withMutationStatus } from "./render.ts";
13
+ import { renderDiffPreview } from "./render.ts";
14
+ import { withMutationStatus } from "./fusion-card.ts";
9
15
  import { makeWriteOverride } from "./write-tool.ts";
10
16
  import { generateMutationDetails } from "./mutation-result.ts";
11
17
  import type { ActionFusionDetails } from "./action-fusion.ts";
18
+ import { DEFAULT_CONFIG } from "./config.ts";
19
+ import { toDisplayLines } from "./grep-render.ts";
20
+ import { makeReadOverride } from "./read-tool.ts";
21
+ import { callTool } from "./tool-call.testing.ts";
22
+ import { renderToolError } from "./render.ts";
12
23
 
13
24
  const versions = { publishedRevision: "r", observedRevision: "r" };
14
25
  const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
@@ -18,7 +29,10 @@ const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
18
29
 
19
30
  test("mutation headers refresh in place and retain isolated per-call counts", () => {
20
31
  initTheme("dark");
21
- for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
32
+ for (const tool of [
33
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG),
34
+ makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
35
+ ]) {
22
36
  const args = {
23
37
  path: "a.txt",
24
38
  edits: [{ op: "append" as const, body: ["new"] }],
@@ -54,7 +68,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
54
68
 
55
69
  test("edit call titles show structured batches and tolerate invalid partial input", () => {
56
70
  initTheme("dark");
57
- const tool = makeEditOverride(process.cwd());
71
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
58
72
  const edits = [
59
73
  { op: "replace" as const, anchor: "1#AB", body: ["new"] },
60
74
  { op: "append" as const, body: ["more"] },
@@ -73,7 +87,7 @@ test("edit call titles show structured batches and tolerate invalid partial inpu
73
87
 
74
88
  test("mutation card owns stale-anchor notices without internal status", () => {
75
89
  initTheme("dark");
76
- const tool = withMutationStatus(makeEditOverride(process.cwd()));
90
+ const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
77
91
  const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
78
92
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
79
93
  const card = tool.renderCall!(args, theme, context);
@@ -103,7 +117,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
103
117
 
104
118
  test("mutation card omits status when then_run was not requested", () => {
105
119
  initTheme("dark");
106
- const tool = withMutationStatus(makeEditOverride(process.cwd()));
120
+ const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
107
121
  const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
108
122
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
109
123
  const card = tool.renderCall!(args, theme, context);
@@ -180,7 +194,10 @@ test("mutation previews hide CRLF boundaries even with mixed endings or an unter
180
194
  assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
181
195
  assert.match(details.diff, /␍/);
182
196
  assert.ok(details.patch.includes("-old\r\n"));
183
- for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
197
+ for (const tool of [
198
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG),
199
+ makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
200
+ ]) {
184
201
  for (const expanded of [false, true]) {
185
202
  const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
186
203
  const rendered = tool.renderResult(
@@ -207,7 +224,7 @@ test("diff previews retain standalone CR and literal control-picture characters"
207
224
  { publishedRevision: "r", observedRevision: "r" },
208
225
  "PUBLISHED",
209
226
  );
210
- const tool = makeEditOverride(process.cwd());
227
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
211
228
  const result = tool.renderResult(
212
229
  { content: [], details },
213
230
  { expanded: true, isPartial: false },
@@ -225,7 +242,7 @@ test("diff previews retain standalone CR and literal control-picture characters"
225
242
 
226
243
  test("withMutationStatus renderResult initializes mutationShell defensively", () => {
227
244
  initTheme("dark");
228
- const tool = withMutationStatus(makeEditOverride(process.cwd()));
245
+ const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
229
246
  const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
230
247
  const container = tool.renderResult!(
231
248
  {
@@ -244,3 +261,120 @@ test("withMutationStatus renderResult initializes mutationShell defensively", ()
244
261
  assert.ok(context.state.mutationShell);
245
262
  assert.ok(context.state.mutationShell.box);
246
263
  });
264
+
265
+ test("grep renders anchored and plain groups with shared width and folded indentation", () => {
266
+ initTheme("dark");
267
+ const notice =
268
+ "[Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors]";
269
+ const raw = [
270
+ "valid.ts · 2 matches",
271
+ "9#ABCD│ alpha",
272
+ "10#ABCD│ beta",
273
+ "",
274
+ "invalid.txt · 2 matches",
275
+ "100│\tbad �",
276
+ "7│\t\tother",
277
+ notice,
278
+ ].join("\n");
279
+ assert.deepEqual(toDisplayLines(raw, theme), [
280
+ theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
281
+ theme.fg("dim", " 9: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "alpha"),
282
+ theme.fg("dim", " 10: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", " beta"),
283
+ theme.fg("toolOutput", ""),
284
+ theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
285
+ theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
286
+ theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
287
+ theme.fg("warning", notice),
288
+ ]);
289
+ });
290
+
291
+ test("grep renders plain and anchored rows in one group without exposing hashes", () => {
292
+ initTheme("dark");
293
+ const raw = "mixed.txt · 2 matches\n1#ABCD│alpha\n12│ 7#ABCD│literal content";
294
+ assert.deepEqual(toDisplayLines(raw, theme), [
295
+ theme.fg("success", "mixed.txt") + theme.fg("dim", " · 2 matches"),
296
+ theme.fg("dim", " 1: ") + theme.fg("toolOutput", "alpha"),
297
+ theme.fg("dim", " 12: ") + theme.fg("toolOutput", " 7#ABCD│literal content"),
298
+ ]);
299
+ });
300
+
301
+ test("all file tools expose validation causes in collapsed and expanded error cards", async () => {
302
+ initTheme("dark");
303
+ const cwd = process.cwd();
304
+ const tools = [
305
+ makeReadOverride(cwd, DEFAULT_CONFIG),
306
+ withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
307
+ withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
308
+ withMutationStatus(makeWriteOverride(cwd)),
309
+ ];
310
+ for (const tool of tools) {
311
+ for (const fused of [false, true]) {
312
+ const args = {
313
+ path: "unused.txt",
314
+ content: "unused",
315
+ edits: [{ op: "append" as const, body: ["unused"] }],
316
+ replacements: [{ find: "unused", replace: "unused" }],
317
+ unexpected: true,
318
+ ...(fused ? { then_run: { command: "must-not-run" } } : {}),
319
+ };
320
+ let errorText = "";
321
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
322
+ assert.ok(error instanceof Error);
323
+ errorText = error.message;
324
+ return true;
325
+ });
326
+ const cause = errorText.split("\n").find((line) => line.includes("unexpected"));
327
+ assert.ok(cause);
328
+ for (const expanded of [false, true]) {
329
+ const context = {
330
+ args,
331
+ state: {},
332
+ toolCallId: "validation",
333
+ invalidate() {},
334
+ lastComponent: undefined,
335
+ cwd,
336
+ executionStarted: true,
337
+ argsComplete: true,
338
+ isPartial: false,
339
+ expanded,
340
+ showImages: false,
341
+ isError: true,
342
+ };
343
+ const call = tool.renderCall?.(args, theme, context);
344
+ // Pi supplies no tool-specific details when argument validation fails.
345
+ const renderError = tool.renderResult as NonNullable<
346
+ ToolDefinition<TSchema, undefined>["renderResult"]
347
+ >;
348
+ const result = renderError(
349
+ { content: [{ type: "text", text: errorText }], details: undefined },
350
+ { isPartial: false, expanded },
351
+ theme,
352
+ context,
353
+ );
354
+ const card = tool.renderShell === "self" ? call : result;
355
+ assert.ok(card);
356
+ assert.ok(
357
+ card.render(200).join("\n").includes(cause),
358
+ `${tool.name} hid the validation cause`,
359
+ );
360
+ }
361
+ }
362
+ }
363
+ });
364
+
365
+ test("expanded errors retain every text block while collapsed errors stay bounded", () => {
366
+ initTheme("dark");
367
+ const diagnosticLineCount = 80;
368
+ const result = {
369
+ content: [
370
+ { type: "text" as const, text: "Error header\n" + "context\n".repeat(diagnosticLineCount) },
371
+ { type: "text" as const, text: "Final cause: permission denied" },
372
+ ],
373
+ };
374
+ const collapsed = renderToolError(result, theme, false).render(120).join("\n");
375
+ const expanded = renderToolError(result, theme, true).render(120).join("\n");
376
+ assert.match(collapsed, /Error header/);
377
+ assert.doesNotMatch(collapsed, /Final cause/);
378
+ assert.match(expanded, /Final cause: permission denied/);
379
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
380
+ });
package/src/pi/render.ts CHANGED
@@ -1,10 +1,7 @@
1
1
  /**
2
2
  * Shared helpers for the hashline-aware tool renderers.
3
3
  *
4
- * The model-facing `content` text uses the `LINE#HASH│content` anchor format so
5
- * an anchor can be copied straight into an edit op. The user-facing TUI
6
- * renderers (read, grep) strip that prefix back to a clean ` N: content` form.
7
- * Parsing the anchor format in one place keeps read and grep in sync.
4
+ * Mutation previews and shared error presentation for the user-facing TUI.
8
5
  *
9
6
  * @module pi-hashline-edit/pi
10
7
  */
@@ -12,35 +9,15 @@
12
9
  import {
13
10
  renderDiff,
14
11
  type Theme,
15
- type ToolDefinition,
16
12
  type ToolRenderResultOptions,
17
13
  } from "@earendil-works/pi-coding-agent";
18
14
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
- import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
20
- import type { TSchema } from "typebox";
21
-
22
- const HASHLINE_RE = /^(\d+)#[A-Za-z0-9]+│(.*)$/;
23
-
24
- export interface HashlineRow {
25
- /** Line number as written in the anchor (string form). */
26
- lineNo: string;
27
- /** Line content with the `LINE#HASH│` prefix removed. */
28
- content: string;
29
- }
30
-
31
- /**
32
- * Parse a `LINE#HASH│content` anchor line.
33
- *
34
- * @returns the row, or `null` for non-anchor lines (headers, notices, free
35
- * text) so callers can fall through to their own formatting.
36
- */
37
- export function parseHashline(line: string): HashlineRow | null {
38
- const m = line.match(HASHLINE_RE);
39
- return m ? { lineNo: m[1], content: m[2] } : null;
40
- }
15
+ import { Text, type Component } from "@earendil-works/pi-tui";
41
16
 
42
17
  /** Max diff lines shown when a result is rendered collapsed. */
43
18
  const MAX_COLLAPSED_DIFF_LINES = 24;
19
+ /** Collapsed tool output and errors share a bounded preview. */
20
+ const MAX_COLLAPSED_OUTPUT_LINES = 15;
44
21
 
45
22
  /**
46
23
  * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
@@ -66,15 +43,10 @@ export interface DiffCounts {
66
43
  removed: number;
67
44
  }
68
45
 
69
- interface MutationRenderState {
46
+ /** Row-local render state shared by the mutation call and result renderers. */
47
+ export interface MutationRenderState {
70
48
  diffCounts?: DiffCounts;
71
49
  callText?: Text;
72
- mutationShell?: {
73
- box: Box;
74
- call?: Component;
75
- result?: Component;
76
- fileState?: { freshness?: string };
77
- };
78
50
  }
79
51
 
80
52
  /** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
@@ -135,14 +107,35 @@ export function renderMutationCall<TArgs>(
135
107
  return text;
136
108
  }
137
109
 
138
- /** Keep model-facing diagnostic details out of the compact error row. */
110
+ /** Render a bounded preview; expanding reveals every supplied line. */
111
+ export function renderOutputPreview(
112
+ lines: readonly string[],
113
+ expanded: boolean,
114
+ theme: Theme,
115
+ ): Text {
116
+ const shown = expanded ? lines : lines.slice(0, MAX_COLLAPSED_OUTPUT_LINES);
117
+ const more =
118
+ shown.length < lines.length
119
+ ? `\n${theme.fg("muted", `… (${lines.length - shown.length} more lines)`)}`
120
+ : "";
121
+ return new Text(shown.join("\n") + more, 0, 0);
122
+ }
123
+
124
+ /** Preserve diagnostic causes and recovery hints from every text block. */
139
125
  export function renderToolError(
140
126
  result: Pick<AgentToolResult<unknown>, "content">,
141
127
  theme: Theme,
128
+ expanded: boolean,
142
129
  ): Text {
143
- const content = result.content?.[0];
144
- const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
145
- return new Text(theme.fg("error", text), 0, 0);
130
+ const text = result.content
131
+ .filter((block) => block.type === "text")
132
+ .map((block) => block.text)
133
+ .join("\n");
134
+ return renderOutputPreview(
135
+ (text || "Error").split("\n").map((line) => theme.fg("error", line)),
136
+ expanded,
137
+ theme,
138
+ );
146
139
  }
147
140
 
148
141
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
@@ -162,7 +155,7 @@ export function renderMutationResult<TArgs>(
162
155
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED")
163
156
  return new Text(theme.fg("warning", pending), 0, 0);
164
157
  const content = result.content?.[0];
165
- if (context.isError) return renderToolError(result, theme);
158
+ if (context.isError) return renderToolError(result, theme, expanded);
166
159
  const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
167
160
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
168
161
  publishDiffCounts(diff, context, (counts) => {
@@ -175,60 +168,3 @@ export function renderMutationResult<TArgs>(
175
168
  }
176
169
  return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
177
170
  }
178
-
179
- /** Keep the mutation card's background independent of the fused command's lifetime. */
180
- export function withMutationStatus<TParams extends TSchema, TDetails>(
181
- tool: ToolDefinition<TParams, TDetails, MutationRenderState>,
182
- ): ToolDefinition<TParams, TDetails, MutationRenderState> {
183
- return {
184
- ...tool,
185
- renderShell: "self",
186
- renderCall(args, theme, context) {
187
- const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
188
- shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
189
- shell.box.clear();
190
- shell.box.addChild(shell.call);
191
- shell.box.setBgFn((line: string) =>
192
- theme.bg(
193
- context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
194
- line,
195
- ),
196
- );
197
- return shell.box;
198
- },
199
- renderResult(result, options, theme, context) {
200
- const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
201
- const details = result.details as
202
- | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
203
- | undefined;
204
- const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
205
- // Fused errors retain combined details for the model; show the mutation's summary here.
206
- const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
207
- shell.result = fusedError
208
- ? renderToolError(result, theme)
209
- : tool.renderResult!(result, { ...options, isPartial }, theme, {
210
- ...context,
211
- isPartial,
212
- lastComponent: shell.result,
213
- });
214
- // Pi runs renderCall first; update its box in place without invalidating the tool row.
215
- shell.box.addChild(shell.result);
216
- const file = details?.actionFusion ?? shell.fileState;
217
- if (file) {
218
- shell.fileState = { freshness: file.freshness };
219
- if (file.freshness === "changed" || file.freshness === "missing") {
220
- shell.box.addChild(
221
- new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
222
- );
223
- }
224
- }
225
- shell.box.setBgFn((line: string) =>
226
- theme.bg(
227
- isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
228
- line,
229
- ),
230
- );
231
- return new Container();
232
- },
233
- };
234
- }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Run a replace batch that contains regex rules in a worker thread, so a
3
+ * catastrophic pattern can be stopped by the configured timeout or by
4
+ * cancellation. The worker (`replace-worker.mjs` → `replace-worker.ts`) calls
5
+ * the same `core/replace.ts` engine that literal-only batches run in-process.
6
+ *
7
+ * @module pi-hashline-edit/pi
8
+ */
9
+
10
+ import { Worker } from "node:worker_threads";
11
+ import type { applyReplacements, Replacement } from "../core/replace.ts";
12
+ import { cancellationError, throwIfCancelled } from "./error-text.ts";
13
+
14
+ type ReplaceResult = ReturnType<typeof applyReplacements>;
15
+
16
+ export async function runRegexReplacements(
17
+ source: string,
18
+ rules: readonly Replacement[],
19
+ timeoutMs: number,
20
+ signal: AbortSignal | undefined,
21
+ ): Promise<ReplaceResult> {
22
+ throwIfCancelled(signal);
23
+ const worker = new Worker(new URL("./replace-worker.mjs", import.meta.url), {
24
+ workerData: { source, rules },
25
+ });
26
+ return new Promise((resolve, reject) => {
27
+ let settled = false;
28
+ const finish = (result: ReplaceResult | Error, terminate = false) => {
29
+ if (settled) return;
30
+ settled = true;
31
+ clearTimeout(timer);
32
+ signal?.removeEventListener("abort", abort);
33
+ const complete = () => (result instanceof Error ? reject(result) : resolve(result));
34
+ if (terminate) void worker.terminate().then(complete, reject);
35
+ else complete();
36
+ };
37
+ const abort = () => finish(cancellationError(), true);
38
+ const timer = setTimeout(
39
+ () => finish(new Error(`regex evaluation timed out after ${timeoutMs}ms`), true),
40
+ timeoutMs,
41
+ );
42
+ worker.on("message", (message: { result?: ReplaceResult; error?: string }) => {
43
+ if (message.error !== undefined) finish(new Error(message.error));
44
+ else if (message.result) finish(message.result);
45
+ else finish(new Error("Regex worker returned an invalid result"));
46
+ });
47
+ worker.on("error", (error) =>
48
+ finish(error instanceof Error ? error : new Error(String(error))),
49
+ );
50
+ worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
51
+ signal?.addEventListener("abort", abort, { once: true });
52
+ if (signal?.aborted) abort();
53
+ });
54
+ }
@@ -18,7 +18,7 @@
18
18
  *
19
19
  * Concurrency: read-modify-write is wrapped in Pi's withFileMutationQueue
20
20
  * (shared with `edit`), so a `replace` and an `edit` on the same file never
21
- * interleave. Regex batches run in a cancellable worker with a time limit.
21
+ * interleave. Regex batches run in a cancellable worker with a time limit (replace-regex).
22
22
  *
23
23
  * @module pi-hashline-edit/pi
24
24
  */
@@ -31,12 +31,13 @@ import {
31
31
  } from "@earendil-works/pi-coding-agent";
32
32
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
33
33
  import { Type, type Static } from "typebox";
34
- import { Worker } from "node:worker_threads";
35
34
  import { splitLines } from "../core/lines.ts";
36
- import { applyReplacements, buildRegex, type Replacement } from "./replace-apply.ts";
35
+ import { applyReplacements, buildRegex } from "../core/replace.ts";
36
+ import { runRegexReplacements } from "./replace-regex.ts";
37
37
  import { unwritableTextReason } from "../core/text.ts";
38
38
  import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
39
39
  import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
40
+ import type { HashlineEditConfig } from "./config.ts";
40
41
  import {
41
42
  formatDiffCounts,
42
43
  renderMutationCall,
@@ -51,12 +52,8 @@ import {
51
52
  type MutationTarget,
52
53
  type TextMutationDetails,
53
54
  } from "./mutation-runner.ts";
54
- import {
55
- cancellationError,
56
- errorMessage,
57
- invalidArgument,
58
- throwIfCancelled,
59
- } from "./error-text.ts";
55
+ import { errorMessage } from "../core/errors.ts";
56
+ import { invalidArgument, throwIfCancelled } from "./error-text.ts";
60
57
  type ReplaceDetails = TextMutationDetails;
61
58
  type ReplaceRenderContext = Parameters<
62
59
  NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
@@ -111,49 +108,6 @@ function createReplaceSchema(actionFusion: boolean) {
111
108
  }
112
109
  type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
113
110
 
114
- const REGEX_TIMEOUT_MS = 5_000;
115
-
116
- async function applyRegexReplacements(
117
- source: string,
118
- rules: readonly Replacement[],
119
- signal: AbortSignal | undefined,
120
- ): Promise<{ text: string; count: number }> {
121
- throwIfCancelled(signal);
122
- const worker = new Worker(new URL("./replace-worker.mjs", import.meta.url), {
123
- workerData: { source, rules },
124
- });
125
- return new Promise((resolve, reject) => {
126
- let settled = false;
127
- const finish = (result: { text: string; count: number } | Error, terminate = false) => {
128
- if (settled) return;
129
- settled = true;
130
- clearTimeout(timer);
131
- signal?.removeEventListener("abort", abort);
132
- const complete = () => (result instanceof Error ? reject(result) : resolve(result));
133
- if (terminate) void worker.terminate().then(complete, reject);
134
- else complete();
135
- };
136
- const abort = () => finish(cancellationError(), true);
137
- const timer = setTimeout(
138
- () => finish(new Error(`regex evaluation timed out after ${REGEX_TIMEOUT_MS}ms`), true),
139
- REGEX_TIMEOUT_MS,
140
- );
141
- worker.on(
142
- "message",
143
- (message: { result?: { text: string; count: number }; error?: string }) => {
144
- if (message.error !== undefined) finish(new Error(message.error));
145
- else if (message.result) finish(message.result);
146
- else finish(new Error("Regex worker returned an invalid result"));
147
- },
148
- );
149
- worker.on("error", (error) =>
150
- finish(error instanceof Error ? error : new Error(String(error))),
151
- );
152
- worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
153
- signal?.addEventListener("abort", abort, { once: true });
154
- if (signal?.aborted) abort();
155
- });
156
- }
157
111
  /**
158
112
  * Bound candidate anchors by stripping common prefix/suffix lines in O(n).
159
113
  * For a pure deletion, retain its first surviving successor. Shifted suffixes
@@ -243,7 +197,11 @@ function checkReplaceArguments(args: unknown): void {
243
197
  });
244
198
  }
245
199
 
246
- export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
200
+ export function makeReplaceTool(
201
+ cwd: string,
202
+ config: HashlineEditConfig,
203
+ fusion?: ActionFusionExecutor,
204
+ ) {
247
205
  const parameters = createReplaceSchema(fusion !== undefined);
248
206
  return {
249
207
  name: "replace" as const,
@@ -252,7 +210,7 @@ export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
252
210
  "Replace every match of one or more literal or JavaScript-regex rules in a file. Overlapping matches or a rule with no match reject the whole call. Returns a diff and fresh anchors.",
253
211
  promptSnippet: "Replace matching text across a file",
254
212
  promptGuidelines: [
255
- "Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
213
+ "Use replace for repeated literal or regex substitutions, or short changes inside long lines; use edit for line or block changes, insertions, and deletions.",
256
214
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
257
215
  ],
258
216
  parameters,
@@ -294,8 +252,7 @@ export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
294
252
  {
295
253
  cwd,
296
254
  fusion,
297
- reportsAnchors: true,
298
- run: (mutationParams, target) => runReplace(target, mutationParams.replacements),
255
+ run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
299
256
  },
300
257
  { toolCallId, params, signal, onUpdate, ctx },
301
258
  );
@@ -303,15 +260,24 @@ export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
303
260
  };
304
261
  }
305
262
 
306
- function runReplace(target: MutationTarget, rules: ReplaceParams["replacements"]) {
307
- const anchorFormatter = createAnchorFormatter();
263
+ function runReplace(
264
+ target: MutationTarget,
265
+ rules: ReplaceParams["replacements"],
266
+ config: HashlineEditConfig,
267
+ ) {
268
+ const anchorFormatter = createAnchorFormatter(config.hashLen);
308
269
 
309
270
  return runTextMutation("replace", target, async (currentText) => {
310
271
  let newText: string;
311
272
  let count: number;
312
273
  try {
313
274
  ({ text: newText, count } = rules.some((rule) => rule.regex === true)
314
- ? await applyRegexReplacements(currentText, rules, target.signal)
275
+ ? await runRegexReplacements(
276
+ currentText,
277
+ rules,
278
+ config.replace.regexTimeoutMs,
279
+ target.signal,
280
+ )
315
281
  : applyReplacements(currentText, rules));
316
282
  } catch (error) {
317
283
  throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
@@ -1,6 +1,6 @@
1
1
  import { parentPort, workerData } from "node:worker_threads";
2
- import { applyReplacements } from "./replace-apply.ts";
3
- import { errorMessage } from "./error-text.ts";
2
+ import { applyReplacements } from "../core/replace.ts";
3
+ import { errorMessage } from "../core/errors.ts";
4
4
 
5
5
  try {
6
6
  const { source, rules } = workerData;