@criogaid/pi-hashline-edit 0.10.0 → 0.12.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 (103) hide show
  1. package/README.md +21 -7
  2. package/README.zh-CN.md +22 -8
  3. package/package.json +7 -6
  4. package/src/core/AGENTS.md +2 -2
  5. package/src/core/apply.test.ts +4 -4
  6. package/src/core/apply.ts +3 -3
  7. package/src/core/character-set.test.ts +2 -3
  8. package/src/core/character-set.ts +1 -1
  9. package/src/core/ranges.test.ts +2 -1
  10. package/src/core/ranges.ts +1 -1
  11. package/src/core/regex.ts +6 -2
  12. package/src/core/replace.test.ts +51 -0
  13. package/src/core/replace.ts +10 -4
  14. package/src/core/types.ts +1 -1
  15. package/src/index.ts +9 -9
  16. package/src/integration/config-registration.test.ts +8 -10
  17. package/src/integration/fusion-dispatch.test.ts +2 -2
  18. package/src/integration/grep-errors.test.ts +3 -3
  19. package/src/integration/grep-flags.test.ts +5 -5
  20. package/src/integration/grep-js-completeness.test.ts +12 -11
  21. package/src/integration/grep-line-candidates.test.ts +5 -3
  22. package/src/integration/grep-matrix.test.ts +5 -4
  23. package/src/integration/grep-order.test.ts +4 -4
  24. package/src/integration/grep-path-matrix.test.ts +5 -4
  25. package/src/integration/grep-prefilter-coverage.test.ts +17 -5
  26. package/src/integration/grep-process-limits.test.ts +2 -4
  27. package/src/integration/grep-regex.test.ts +10 -10
  28. package/src/integration/grep-rg.test.ts +93 -48
  29. package/src/integration/grep-scan-budget.test.ts +8 -8
  30. package/src/integration/grep-translation.test.ts +8 -7
  31. package/src/integration/large-text.test.ts +5 -5
  32. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  33. package/src/integration/mutation-file-types.testing.ts +4 -4
  34. package/src/integration/npm-package.test.ts +12 -10
  35. package/src/integration/npm-package.testing.ts +151 -4
  36. package/src/integration/publication-read-changes.test.ts +54 -54
  37. package/src/integration/read-changes.test.ts +4 -4
  38. package/src/integration/replace-worker-boundary.test.ts +1 -1
  39. package/src/integration/report-replay.test.ts +9 -6
  40. package/src/integration/utf8-errors.test.ts +4 -4
  41. package/src/pi/AGENTS.md +13 -12
  42. package/src/pi/action-fusion.test.ts +125 -105
  43. package/src/pi/action-fusion.testing.ts +38 -0
  44. package/src/pi/action-fusion.ts +9 -21
  45. package/src/pi/argument-diagnostics.ts +4 -3
  46. package/src/pi/argument-format.test.ts +19 -18
  47. package/src/pi/argument-validation.test.ts +281 -139
  48. package/src/pi/argument-validation.ts +21 -31
  49. package/src/pi/budgets.ts +1 -4
  50. package/src/pi/codemode.test.ts +7 -2
  51. package/src/pi/config.test.ts +2 -1
  52. package/src/pi/config.ts +8 -3
  53. package/src/pi/diagnostic-buffer.test.ts +23 -13
  54. package/src/pi/edit-tool.ts +48 -63
  55. package/src/pi/error-text.ts +7 -2
  56. package/src/pi/execute.test.ts +178 -157
  57. package/src/pi/failure-context.test.ts +5 -4
  58. package/src/pi/failure-context.ts +1 -1
  59. package/src/pi/failure-path.test.ts +37 -37
  60. package/src/pi/file-commit.test.ts +47 -19
  61. package/src/pi/file-commit.ts +36 -9
  62. package/src/pi/fusion-card.test.ts +22 -21
  63. package/src/pi/fusion-card.ts +9 -5
  64. package/src/pi/grep-candidates.test.ts +18 -20
  65. package/src/pi/grep-candidates.ts +13 -17
  66. package/src/pi/grep-matrix.test.ts +3 -3
  67. package/src/pi/grep-order.test.ts +12 -11
  68. package/src/pi/grep-output.ts +45 -17
  69. package/src/pi/grep-reread.ts +7 -2
  70. package/src/pi/grep-rg.testing.ts +70 -0
  71. package/src/pi/grep-scope.ts +10 -10
  72. package/src/pi/grep-search.ts +8 -11
  73. package/src/pi/grep-tool.ts +40 -53
  74. package/src/pi/grep.test.ts +141 -116
  75. package/src/pi/model-budgets.test.ts +2 -1
  76. package/src/pi/mutation-outcome.testing.ts +0 -1
  77. package/src/pi/mutation-result.test.ts +8 -8
  78. package/src/pi/mutation-result.ts +1 -1
  79. package/src/pi/mutation-runner.ts +10 -6
  80. package/src/pi/output-budgets.test.ts +53 -31
  81. package/src/pi/pi.test.ts +18 -13
  82. package/src/pi/read-tool.ts +13 -18
  83. package/src/pi/read.test.ts +67 -41
  84. package/src/pi/registration.test.ts +25 -19
  85. package/src/pi/render.test.ts +94 -32
  86. package/src/pi/render.ts +7 -4
  87. package/src/pi/replace-regex.ts +1 -1
  88. package/src/pi/replace-tool.ts +6 -16
  89. package/src/pi/replace.test.ts +45 -34
  90. package/src/pi/report-failure.testing.ts +9 -1
  91. package/src/pi/report-schema.ts +225 -86
  92. package/src/pi/report.test.ts +81 -87
  93. package/src/pi/report.ts +35 -22
  94. package/src/pi/result-safety.test.ts +121 -100
  95. package/src/pi/rg-process.test.ts +2 -2
  96. package/src/pi/rg-process.ts +9 -15
  97. package/src/pi/rg-regex.test.ts +13 -0
  98. package/src/pi/rg-regex.ts +2 -2
  99. package/src/pi/schema.ts +23 -0
  100. package/src/pi/tool-factories.testing.ts +59 -0
  101. package/src/pi/write-tool.ts +9 -15
  102. package/src/pi/write.test.ts +30 -31
  103. package/src/testing/run-tests.ts +1 -1
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import { rejectsArgument } from "./argument-error.testing.ts";
2
3
  import { computeLineHash } from "../core/hash.ts";
3
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
@@ -10,26 +11,26 @@ import { join } from "node:path";
10
11
  import { test } from "node:test";
11
12
  import { outputBudgetsFor } from "./budgets.ts";
12
13
  import { createActionFusionExecutor } from "./action-fusion.ts";
13
- import { makeReplaceTool } from "./replace-tool.ts";
14
- import { makeWriteOverride } from "./write-tool.ts";
15
- import { makeEditOverride } from "./edit-tool.ts";
16
- import { decodeReport, reportOf } from "./report.ts";
17
- import { REREAD } from "./report-schema.ts";
14
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
15
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
16
+ import { makeEditOverride } from "./tool-factories.testing.ts";
17
+ import { reportOf } from "./report.ts";
18
+
18
19
  import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
19
- import { DEFAULT_CONFIG } from "./config.ts";
20
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
20
21
 
21
22
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
22
23
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
23
24
 
24
25
  const anchorBudget = outputBudgetsFor(4096);
25
26
  const anchorBatchSize: unknown = Reflect.get(
26
- makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.edits,
27
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.steps,
27
28
  "maxItems",
28
29
  );
29
30
  assert.ok(typeof anchorBatchSize === "number");
30
31
 
31
32
  function assertFailureByteBudgets(message: string): void {
32
- const report = decodeReport(message, "edit");
33
+ const report = reportOf({ content: [{ type: "text", text: message }] }, "edit");
33
34
  assert.ok(report);
34
35
  assert.equal(report.error, "ANCHOR_MISMATCH");
35
36
  assert.ok(report.failures && report.failures.length > 0);
@@ -54,16 +55,24 @@ test("edit and replace commands change or remove the file → withhold anchors a
54
55
  const path = join(dir, `${toolName}-${state}-${fails}.txt`);
55
56
  await writeFile(path, "before\n");
56
57
  const updates: AgentToolResult<unknown>[] = [];
57
- const fusion = createActionFusionExecutor(async (_input, _signal, _ctx, onUpdate) => {
58
+ const executeTool: SessionCommand = async (_name, _input, options) => {
58
59
  if (state === "changed") await writeFile(path, "command output\n");
59
60
  else {
60
61
  await rm(path);
61
62
  if (state === "unknown") await mkdir(path);
62
63
  }
63
- onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
64
- if (fails) throw new Error("command failed");
65
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
66
- });
64
+ options?.onUpdate?.({
65
+ content: [{ type: "text", text: "progress" }],
66
+ details: undefined,
67
+ });
68
+ if (fails)
69
+ return commandCompletion(
70
+ { content: [{ type: "text", text: "command failed" }] },
71
+ true,
72
+ );
73
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
74
+ };
75
+ const fusion = createActionFusionExecutor(() => {});
67
76
  const tool =
68
77
  toolName === "edit"
69
78
  ? makeEditOverride(dir, DEFAULT_CONFIG, fusion)
@@ -71,11 +80,11 @@ test("edit and replace commands change or remove the file → withhold anchors a
71
80
  const args =
72
81
  toolName === "edit"
73
82
  ? {
74
- edits: [
83
+ steps: [
75
84
  {
76
85
  action: "replace",
77
86
  anchor: `1#${computeLineHash(1, "before", DEFAULT_CONFIG.hashLen)}`,
78
- body: ["after"],
87
+ lines: ["after"],
79
88
  },
80
89
  ],
81
90
  }
@@ -85,14 +94,15 @@ test("edit and replace commands change or remove the file → withhold anchors a
85
94
  { path, ...args, then_run: { command: "check" } },
86
95
  {
87
96
  onUpdate: (update: AgentToolResult<unknown>) => updates.push(update),
88
- ctx: context,
97
+ ctx: { ...context, executeTool },
89
98
  },
90
99
  );
91
100
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
92
101
  const report = reportOf(result, toolName);
93
102
  assert.equal(report?.freshness, state);
94
103
  assert.equal(report?.publication, "PUBLISHED");
95
- assert.equal(report?.next, state === "missing" ? undefined : REREAD);
104
+ if (state === "missing") assert.equal(report?.next, undefined);
105
+ else assert.match(report?.next ?? "", /Read the file before further edits/);
96
106
  assert.equal(report?.then_run?.status, fails ? "failed" : "succeeded");
97
107
  if (fails) assert.equal(report?.then_run?.output, "command failed");
98
108
  assert.equal(result.content.length, 1);
@@ -118,13 +128,11 @@ test("progress callback failures → preserve publication and allow the command"
118
128
  const fail = () => {
119
129
  throw new Error("display unavailable");
120
130
  };
121
- const fusion = createActionFusionExecutor(
122
- async () => {
123
- commands++;
124
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
125
- },
126
- callback === "reporter" ? fail : undefined,
127
- );
131
+ const executeTool: SessionCommand = async () => {
132
+ commands++;
133
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
134
+ };
135
+ const fusion = createActionFusionExecutor(callback === "reporter" ? fail : () => {});
128
136
  const path = join(dir, callback);
129
137
  const result = await callTool(
130
138
  makeWriteOverride(dir, fusion),
@@ -134,13 +142,18 @@ test("progress callback failures → preserve publication and allow the command"
134
142
  mode: "create",
135
143
  then_run: { command: "check" },
136
144
  },
137
- { onUpdate: callback === "update" ? fail : undefined, ctx: await ctx(dir, t) },
145
+ {
146
+ onUpdate: callback === "update" ? fail : undefined,
147
+ ctx: { ...(await ctx(dir, t)), executeTool },
148
+ },
138
149
  );
139
150
  assert.equal(commands, 1);
140
151
  assert.equal(await readFile(path, "utf8"), "saved\n");
141
- assert.equal(reportOf(result, "write")?.publication, "PUBLISHED");
142
- assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
143
- assert.match(text(result), /display unavailable/);
152
+ const report = reportOf(result, "write");
153
+ assert.equal(report?.publication, "PUBLISHED");
154
+ assert.equal(report?.then_run?.status, "succeeded");
155
+ assert.equal(report?.progressError?.message, "display unavailable");
156
+ assert.doesNotMatch(text(result), /display unavailable/);
144
157
  }
145
158
  } finally {
146
159
  await rm(dir, { recursive: true, force: true });
@@ -156,7 +169,7 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
156
169
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
157
170
  {
158
171
  path,
159
- edits: Array.from({ length: anchorBatchSize }, () => ({
172
+ steps: Array.from({ length: anchorBatchSize }, () => ({
160
173
  action: "delete",
161
174
  anchor: "1#XXXX",
162
175
  })),
@@ -175,13 +188,11 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
175
188
  try {
176
189
  let commands = 0;
177
190
  const events: string[] = [];
178
- const fusion = createActionFusionExecutor(
179
- async () => {
180
- commands++;
181
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
182
- },
183
- (event) => events.push(event.command),
184
- );
191
+ const executeTool: SessionCommand = async () => {
192
+ commands++;
193
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
194
+ };
195
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
185
196
  const path = join(dir, "file.txt");
186
197
  await writeFile(path, "original\n");
187
198
  const cases = [
@@ -189,10 +200,10 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
189
200
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
190
201
  args: {
191
202
  path,
192
- edits: [{ action: "append", body: ["\ud800"] }],
203
+ steps: [{ action: "append", lines: ["\ud800"] }],
193
204
  then_run: { command: "check" },
194
205
  },
195
- field: "edits[0].body[0]",
206
+ field: "steps[0].lines[0]",
196
207
  },
197
208
  {
198
209
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
@@ -211,7 +222,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
211
222
  ];
212
223
  for (const { tool, args, field } of cases) {
213
224
  await assert.rejects(
214
- callTool(tool, args, { ctx: await ctx(dir, t) }),
225
+ callTool(tool, args, { ctx: { ...(await ctx(dir, t)), executeTool } }),
215
226
  (error: unknown) =>
216
227
  error instanceof Error &&
217
228
  rejectsArgument(field, /encoded losslessly/)(error) &&
@@ -237,7 +248,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
237
248
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
238
249
  {
239
250
  path,
240
- edits: Array.from({ length: anchorBatchSize }, () => ({
251
+ steps: Array.from({ length: anchorBatchSize }, () => ({
241
252
  action: "delete",
242
253
  anchor: `50#${computeLineHash(50, "same", 4)}`,
243
254
  })),
@@ -263,18 +274,20 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
263
274
  await writeFile(path, "original\n");
264
275
  let commands = 0;
265
276
  const events: string[] = [];
266
- const fusion = createActionFusionExecutor(
267
- async () => {
268
- commands++;
269
- return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
270
- },
271
- (event) => events.push(event.command),
272
- );
277
+ const executeTool: SessionCommand = async () => {
278
+ commands++;
279
+ return commandCompletion({ content: [{ type: "text", text: "unexpected" }] });
280
+ };
281
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
273
282
  const cases = [
274
283
  {
275
284
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
276
- args: { path, edits: [{ action: "append", body: ["\0"] }], then_run: { command: "check" } },
277
- field: "edits[0].body[0]",
285
+ args: {
286
+ path,
287
+ steps: [{ action: "append", lines: ["\0"] }],
288
+ then_run: { command: "check" },
289
+ },
290
+ field: "steps[0].lines[0]",
278
291
  },
279
292
  {
280
293
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
@@ -293,7 +306,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
293
306
  ];
294
307
  for (const { tool, args, field } of cases) {
295
308
  await assert.rejects(
296
- callTool(tool, args, { ctx: await ctx(dir, t) }),
309
+ callTool(tool, args, { ctx: { ...(await ctx(dir, t)), executeTool } }),
297
310
  (error: unknown) =>
298
311
  error instanceof Error &&
299
312
  rejectsArgument(field, /NUL/)(error) &&
@@ -316,13 +329,11 @@ test("Fusion skips the command when a replacement produces unencodable text", as
316
329
  await writeFile(path, before);
317
330
  let commands = 0;
318
331
  const events: string[] = [];
319
- const fusion = createActionFusionExecutor(
320
- async () => {
321
- commands++;
322
- return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
323
- },
324
- (event) => events.push(event.command),
325
- );
332
+ const executeTool: SessionCommand = async () => {
333
+ commands++;
334
+ return commandCompletion({ content: [{ type: "text", text: "unexpected" }] });
335
+ };
336
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
326
337
  const result = await callTool(
327
338
  makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
328
339
  {
@@ -330,7 +341,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
330
341
  replacements: [{ find: "^.", replace: "x", literal: false }],
331
342
  then_run: { command: "check" },
332
343
  },
333
- { ctx: await ctx(dir, t) },
344
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
334
345
  );
335
346
  assert.equal(result.isError, true);
336
347
  assert.equal(reportOf(result, "replace")?.error, "INVALID_UNICODE");
@@ -358,10 +369,11 @@ test("result generation fails after a real mutation → preserves publication an
358
369
  let targetReads = 0;
359
370
  let injected = false;
360
371
  let commands = 0;
361
- const fusion = createActionFusionExecutor(async () => {
372
+ const executeTool: SessionCommand = async () => {
362
373
  commands++;
363
- return { status: "succeeded", result: { content: [] } };
364
- });
374
+ return commandCompletion({ content: [] });
375
+ };
376
+ const fusion = createActionFusionExecutor(() => {});
365
377
  try {
366
378
  t.mock.method(fs, "open", async (...args: Parameters<typeof nativeOpen>) => {
367
379
  if (String(args[0]) === path) targetReads++;
@@ -387,7 +399,7 @@ test("result generation fails after a real mutation → preserves publication an
387
399
  replacements: [{ literal: true, find: "before\n", replace: content }],
388
400
  then_run: { command: "check" },
389
401
  },
390
- { ctx: context },
402
+ { ctx: { ...context, executeTool } },
391
403
  );
392
404
  const report = reportOf(result, "replace");
393
405
  assert.equal(injected, true, `diff injection after ${targetReads} target reads`);
@@ -415,11 +427,11 @@ const noOpCases = [
415
427
  {
416
428
  makeTool: (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
417
429
  params: {
418
- edits: [
430
+ steps: [
419
431
  {
420
432
  action: "replace",
421
433
  anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
422
- body: ["same"],
434
+ lines: ["same"],
423
435
  },
424
436
  ],
425
437
  },
@@ -440,17 +452,22 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
440
452
  await writeFile(path, "same\n");
441
453
  const before = await stat(path);
442
454
  let commands = 0;
443
- const fusion = createActionFusionExecutor(async () => {
455
+ const executeTool: SessionCommand = async () => {
444
456
  commands++;
445
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
446
- });
457
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
458
+ };
459
+ const fusion = createActionFusionExecutor(() => {});
447
460
  const tool = makeTool(dir, mode === "standalone" ? undefined : fusion);
448
461
  const result = await callTool(
449
462
  tool,
450
463
  { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) },
451
- { ctx: await ctx(dir, t) },
464
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
452
465
  );
453
466
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
467
+ assert.match(
468
+ reportOf(result, tool.name)?.next ?? "",
469
+ /file already has this content.*do not repeat/i,
470
+ );
454
471
  assert.ok(result.details);
455
472
  assert.equal(Reflect.get(result.details, "diff"), tool.name === "write" ? undefined : "");
456
473
  assert.equal(reportOf(result, tool.name)?.freshness, undefined);
@@ -481,31 +498,29 @@ test("delete and append change only line endings → publishes with an empty dif
481
498
  const path = join(dir, `${mode}.txt`);
482
499
  await writeFile(path, "same\r\nsame\n");
483
500
  let commands = 0;
484
- const fusion = createActionFusionExecutor(
485
- async () => {
486
- commands++;
487
- assert.equal(await readFile(path, "utf8"), "same\nsame\r\n");
488
- return { status: "succeeded", result: { content: [] } };
489
- },
490
- (progress) => {
491
- if (mode === "stale" && progress.mutationCompleted && progress.command === "waiting")
492
- writeFileSync(path, "external\n");
493
- },
494
- );
501
+ const executeTool: SessionCommand = async () => {
502
+ commands++;
503
+ assert.equal(await readFile(path, "utf8"), "same\nsame\r\n");
504
+ return commandCompletion({ content: [] });
505
+ };
506
+ const fusion = createActionFusionExecutor((progress) => {
507
+ if (mode === "stale" && progress.mutationCompleted && progress.command === "waiting")
508
+ writeFileSync(path, "external\n");
509
+ });
495
510
  const result = await callTool(
496
511
  makeEditOverride(dir, DEFAULT_CONFIG, mode === "standalone" ? undefined : fusion),
497
512
  {
498
513
  path,
499
- edits: [
514
+ steps: [
500
515
  {
501
516
  action: "delete",
502
517
  anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
503
518
  },
504
- { action: "append", body: ["same"] },
519
+ { action: "append", lines: ["same"] },
505
520
  ],
506
521
  ...(["command", "stale"].includes(mode) ? { then_run: { command: "check" } } : {}),
507
522
  },
508
- { ctx: context },
523
+ { ctx: { ...context, executeTool } },
509
524
  );
510
525
  const report = reportOf(result, "edit");
511
526
  assert.equal(result.isError, undefined);
@@ -516,7 +531,8 @@ test("delete and append change only line endings → publishes with an empty dif
516
531
  report?.then_run?.status,
517
532
  mode === "command" ? "succeeded" : mode === "stale" ? "skipped" : undefined,
518
533
  );
519
- assert.equal(report?.next, mode === "stale" ? REREAD : undefined);
534
+ if (mode === "stale") assert.match(report?.next ?? "", /Read the file before further edits/);
535
+ else assert.equal(report?.next, undefined);
520
536
  assert.equal(commands, mode === "command" ? 1 : 0);
521
537
  assert.equal(
522
538
  await readFile(path, "utf8"),
@@ -536,27 +552,22 @@ test("no-op Fusion still detects external changes and reports command failures",
536
552
  const path = join(dir, "same.txt");
537
553
  await writeFile(path, "same\n");
538
554
  let commands = 0;
539
- const fusion = createActionFusionExecutor(
540
- async () => {
541
- commands++;
542
- if (scenario === "failed") throw new Error("check failed");
543
- await writeFile(path, "external\n");
544
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
545
- },
546
- (progress) => {
547
- if (
548
- scenario === "before" &&
549
- progress.mutationCompleted &&
550
- progress.command === "waiting"
551
- )
552
- writeFileSync(path, "external\n");
553
- },
554
- );
555
+ const executeTool: SessionCommand = async () => {
556
+ commands++;
557
+ if (scenario === "failed")
558
+ return commandCompletion({ content: [{ type: "text", text: "check failed" }] }, true);
559
+ await writeFile(path, "external\n");
560
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
561
+ };
562
+ const fusion = createActionFusionExecutor((progress) => {
563
+ if (scenario === "before" && progress.mutationCompleted && progress.command === "waiting")
564
+ writeFileSync(path, "external\n");
565
+ });
555
566
  const tool = makeTool(dir, fusion);
556
567
  const result = await callTool(
557
568
  tool,
558
569
  { path, ...params, then_run: { command: "check" } },
559
- { ctx: await ctx(dir, t) },
570
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
560
571
  );
561
572
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
562
573
  assert.equal(commands, scenario === "before" ? 0 : 1);
@@ -568,6 +579,16 @@ test("no-op Fusion still detects external changes and reports command failures",
568
579
  reportOf(result, tool.name)?.freshness,
569
580
  scenario === "failed" ? undefined : "changed",
570
581
  );
582
+ if (scenario === "failed")
583
+ assert.match(
584
+ reportOf(result, tool.name)?.next ?? "",
585
+ /file already has this content.*do not repeat/i,
586
+ );
587
+ else
588
+ assert.match(
589
+ reportOf(result, tool.name)?.next ?? "",
590
+ /Read the file before further edits/,
591
+ );
571
592
  }
572
593
  }
573
594
  } finally {
@@ -17,9 +17,9 @@ test("grep search exit status → accepts no matches and preserves failure diagn
17
17
  [2, false, " regex parse error\n", "regex parse error"],
18
18
  [null, true, " regex parse error\n", "regex parse error"],
19
19
  ] as const) {
20
- assert.equal(
20
+ assert.deepEqual(
21
21
  searchDiagnostic({ code, stderr, stopped }),
22
- expected,
22
+ expected === undefined ? undefined : { reason: expected },
23
23
  JSON.stringify({ code, stderr, stopped }),
24
24
  );
25
25
  }
@@ -12,7 +12,7 @@ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
12
12
  import { spawn, type ChildProcessByStdio } from "node:child_process";
13
13
  import type { Readable } from "node:stream";
14
14
  import { HashlineError } from "../core/errors.ts";
15
- import { throwIfCancelled } from "./error-text.ts";
15
+ import { throwIfCancelled, type SearchWarning } from "./error-text.ts";
16
16
  import { formatByteSize } from "./budgets.ts";
17
17
 
18
18
  /**
@@ -23,11 +23,11 @@ import { formatByteSize } from "./budgets.ts";
23
23
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
24
24
  /** Leave room for rg's arguments and paths on hosts with small command-line limits. */
25
25
  export const MAX_RG_PATTERN_UNITS = 24 * 1024;
26
- export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
26
+ const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
27
27
  const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${formatByteSize(MAX_RG_RECORD_BYTES)}.`;
28
28
 
29
29
  /** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
30
- export const MAX_RG_STDERR_BYTES = 64 * 1024;
30
+ const MAX_RG_STDERR_BYTES = 64 * 1024;
31
31
 
32
32
  interface ExitResult {
33
33
  code: number | null;
@@ -47,20 +47,14 @@ export interface RgRunResult {
47
47
  stopped: boolean;
48
48
  }
49
49
 
50
- /** @internal — injectable process boundary for deterministic tests. */
51
- export interface GrepBackend {
52
- runRgPaths: typeof runRgPaths;
53
- runRgLines: typeof runRgLines;
54
- }
55
-
56
50
  /** An incomplete run's diagnostic, surfaced without discarding confirmed matches. */
57
- export function searchDiagnostic(result: RgRunResult): string | undefined {
58
- return (
51
+ export function searchDiagnostic(result: RgRunResult): SearchWarning | undefined {
52
+ const reason =
59
53
  result.stderr.trim() ||
60
54
  (!result.stopped && result.code !== 0 && result.code !== 1
61
55
  ? `ripgrep exited with code ${result.code}.`
62
- : undefined)
63
- );
56
+ : undefined);
57
+ return reason ? { reason } : undefined;
64
58
  }
65
59
 
66
60
  /** spawn reports a failure to start by throwing or by an error event, depending on the errno. */
@@ -153,7 +147,7 @@ async function runRg(
153
147
  }
154
148
  }
155
149
 
156
- /** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
150
+ /** Read NUL-delimited UTF-8 paths from an owned rg process. */
157
151
  export function runRgPaths(
158
152
  args: string[],
159
153
  signal: AbortSignal | undefined,
@@ -187,7 +181,7 @@ export const LINE_LISTING_ARGS = [
187
181
  ];
188
182
 
189
183
  /**
190
- * @internal — read a {@link LINE_LISTING_ARGS} listing. Each file's group is a NUL-terminated
184
+ * Read a {@link LINE_LISTING_ARGS} listing. Each file's group is a NUL-terminated
191
185
  * path, then one `N:` record per matching line ending in a line feed (its content is at most
192
186
  * one byte or an omission notice), then an empty line. onFile receives a file's ascending line
193
187
  * numbers, or undefined once there are more than maxLines.
@@ -49,6 +49,19 @@ test("capture disables i inside a caseless reference → retain the reference's
49
49
  );
50
50
  });
51
51
 
52
+ test("caseless backreference repeats a v string-class capture → retains native case variants", () => {
53
+ const pattern = "([\\q{a}])\\1";
54
+ assert.equal(new RegExp(pattern, "iv").test("aA"), true);
55
+ const candidates = lineCandidatePatterns({
56
+ patterns: [pattern],
57
+ literal: false,
58
+ flags: "iv",
59
+ multiline: false,
60
+ });
61
+ // This ASCII-only translation uses syntax shared by rg and JavaScript.
62
+ assert.ok(candidates?.some((candidate) => new RegExp(candidate).test("aA")));
63
+ });
64
+
52
65
  test("deeply nested pattern → line candidates retain the native match", () => {
53
66
  for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
54
67
  const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
@@ -121,8 +121,8 @@ function nativeFlags(node: AST.Node, ctx: Context): string {
121
121
 
122
122
  function scalarRanges(node: CharacterNode, ctx: Context): Ranges {
123
123
  const ranges = nativeCharacterRanges(node.raw, nativeFlags(node, ctx));
124
- // Case comparison at a reference can widen its capture's original character set.
125
- return ctx.repeated && ctx.ignoreCase && !ignoreCaseAt(node, ctx) ? folded(ranges, ctx) : ranges;
124
+ // Reference comparison can widen even a capture whose native class already uses i.
125
+ return ctx.repeated ? folded(ranges, ctx) : ranges;
126
126
  }
127
127
 
128
128
  const choice = (patterns: readonly string[]): string =>
package/src/pi/schema.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ConstrainedSamplingConfig } from "@earendil-works/pi-ai";
11
+ import { Type, type TLiteral, type TSchemaOptions } from "typebox";
11
12
 
12
13
  /**
13
14
  * Every tool's sampling request: providers that support it enforce the parameter schema while
@@ -19,6 +20,28 @@ export const STRICT_SAMPLING = {
19
20
  strict: "prefer",
20
21
  } as const satisfies ConstrainedSamplingConfig;
21
22
 
23
+ /**
24
+ * A union of string literals that keeps its static type, which TypeBox infers only from a
25
+ * tuple. `describe` gives each choice its own description.
26
+ */
27
+ export function literalUnion<const V extends string>(
28
+ values: readonly V[],
29
+ describe?: (value: V) => string,
30
+ options?: TSchemaOptions,
31
+ ) {
32
+ return Type.Union(
33
+ values.map((value) =>
34
+ describe ? Type.Literal(value, { description: describe(value) }) : Type.Literal(value),
35
+ ) as [TLiteral<V>, ...TLiteral<V>[]],
36
+ options,
37
+ );
38
+ }
39
+
40
+ /** The `path` parameter of the tools that take one file. */
41
+ export function filePathField() {
42
+ return Type.String({ minLength: 1, description: "Path to the file (relative or absolute)" });
43
+ }
44
+
22
45
  /** JSON Schema keywords for an integer in [minimum, maximum]; fractions are rejected, not rounded. */
23
46
  export function integerRange(minimum: number, maximum: number) {
24
47
  return { minimum, multipleOf: 1, maximum };
@@ -0,0 +1,59 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { loadConfig, type HashlineEditConfig } from "./config.ts";
5
+ import { outputBudgetsFor, type OutputBudgetProvider } from "./budgets.ts";
6
+ import { makeReadOverride as read } from "./read-tool.ts";
7
+ import { makeGrepOverride as grep } from "./grep-tool.ts";
8
+ import { makeEditOverride as edit } from "./edit-tool.ts";
9
+ import { makeReplaceTool as replace } from "./replace-tool.ts";
10
+ import { makeWriteOverride as write } from "./write-tool.ts";
11
+ import type { MutationToolEnvironment } from "./mutation-runner.ts";
12
+
13
+ // The runner isolates global settings; create an empty project root for schema defaults.
14
+ const configRoot = mkdtempSync(join(tmpdir(), "hashline-default-config-"));
15
+ export const DEFAULT_CONFIG = (() => {
16
+ try {
17
+ return loadConfig(configRoot);
18
+ } finally {
19
+ rmSync(configRoot, { recursive: true, force: true });
20
+ }
21
+ })();
22
+ export const DEFAULT_OUTPUT_BUDGETS = outputBudgetsFor(undefined);
23
+ export const defaultOutputBudgets = () => outputBudgetsFor(undefined);
24
+
25
+ function toolEnvironment(
26
+ cwd: string,
27
+ config: HashlineEditConfig,
28
+ budgets: OutputBudgetProvider,
29
+ ): { cwd: string; config: HashlineEditConfig; budgets: OutputBudgetProvider } {
30
+ return { cwd, config, budgets };
31
+ }
32
+
33
+ export const makeReadOverride = (
34
+ cwd: string,
35
+ config: HashlineEditConfig,
36
+ budgets = defaultOutputBudgets,
37
+ ) => read(toolEnvironment(cwd, config, budgets));
38
+ export const makeGrepOverride = (
39
+ cwd: string,
40
+ config: HashlineEditConfig,
41
+ budgets = defaultOutputBudgets,
42
+ ) => grep(toolEnvironment(cwd, config, budgets));
43
+ export const makeEditOverride = (
44
+ cwd: string,
45
+ config: HashlineEditConfig,
46
+ fusion: MutationToolEnvironment["fusion"] = undefined,
47
+ budgets = defaultOutputBudgets,
48
+ ) => edit({ ...toolEnvironment(cwd, config, budgets), fusion });
49
+ export const makeReplaceTool = (
50
+ cwd: string,
51
+ config: HashlineEditConfig,
52
+ fusion: MutationToolEnvironment["fusion"] = undefined,
53
+ budgets = defaultOutputBudgets,
54
+ ) => replace({ ...toolEnvironment(cwd, config, budgets), fusion });
55
+ export const makeWriteOverride = (
56
+ cwd: string,
57
+ fusion: MutationToolEnvironment["fusion"] = undefined,
58
+ budgets = defaultOutputBudgets,
59
+ ) => write({ ...toolEnvironment(cwd, DEFAULT_CONFIG, budgets), fusion });