@criogaid/pi-hashline-edit 0.10.0 → 0.11.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 (94) hide show
  1. package/README.md +4 -3
  2. package/README.zh-CN.md +4 -3
  3. package/package.json +1 -1
  4. package/src/core/apply.test.ts +2 -2
  5. package/src/core/apply.ts +2 -2
  6. package/src/core/character-set.test.ts +2 -3
  7. package/src/core/character-set.ts +1 -1
  8. package/src/core/ranges.test.ts +2 -1
  9. package/src/core/ranges.ts +1 -1
  10. package/src/core/types.ts +1 -1
  11. package/src/index.ts +8 -8
  12. package/src/integration/config-registration.test.ts +8 -10
  13. package/src/integration/fusion-dispatch.test.ts +2 -2
  14. package/src/integration/grep-errors.test.ts +3 -3
  15. package/src/integration/grep-flags.test.ts +5 -5
  16. package/src/integration/grep-js-completeness.test.ts +12 -11
  17. package/src/integration/grep-line-candidates.test.ts +3 -2
  18. package/src/integration/grep-matrix.test.ts +5 -4
  19. package/src/integration/grep-order.test.ts +4 -4
  20. package/src/integration/grep-path-matrix.test.ts +5 -4
  21. package/src/integration/grep-prefilter-coverage.test.ts +4 -3
  22. package/src/integration/grep-process-limits.test.ts +2 -4
  23. package/src/integration/grep-regex.test.ts +10 -10
  24. package/src/integration/grep-rg.test.ts +50 -48
  25. package/src/integration/grep-scan-budget.test.ts +8 -8
  26. package/src/integration/grep-translation.test.ts +8 -7
  27. package/src/integration/large-text.test.ts +5 -5
  28. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  29. package/src/integration/mutation-file-types.testing.ts +4 -4
  30. package/src/integration/npm-package.testing.ts +3 -3
  31. package/src/integration/publication-read-changes.test.ts +54 -54
  32. package/src/integration/read-changes.test.ts +4 -4
  33. package/src/integration/replace-worker-boundary.test.ts +1 -1
  34. package/src/integration/report-replay.test.ts +5 -6
  35. package/src/integration/utf8-errors.test.ts +4 -4
  36. package/src/pi/AGENTS.md +6 -5
  37. package/src/pi/action-fusion.test.ts +125 -105
  38. package/src/pi/action-fusion.testing.ts +38 -0
  39. package/src/pi/action-fusion.ts +9 -21
  40. package/src/pi/argument-diagnostics.ts +4 -3
  41. package/src/pi/argument-format.test.ts +19 -18
  42. package/src/pi/argument-validation.test.ts +218 -139
  43. package/src/pi/budgets.ts +1 -4
  44. package/src/pi/codemode.test.ts +7 -2
  45. package/src/pi/config.test.ts +2 -1
  46. package/src/pi/config.ts +8 -3
  47. package/src/pi/diagnostic-buffer.test.ts +23 -13
  48. package/src/pi/edit-tool.ts +47 -62
  49. package/src/pi/error-text.ts +7 -2
  50. package/src/pi/execute.test.ts +174 -157
  51. package/src/pi/failure-context.test.ts +4 -3
  52. package/src/pi/failure-context.ts +1 -1
  53. package/src/pi/failure-path.test.ts +37 -37
  54. package/src/pi/file-commit.test.ts +47 -19
  55. package/src/pi/file-commit.ts +36 -9
  56. package/src/pi/fusion-card.test.ts +22 -21
  57. package/src/pi/grep-candidates.test.ts +18 -20
  58. package/src/pi/grep-candidates.ts +8 -13
  59. package/src/pi/grep-matrix.test.ts +3 -3
  60. package/src/pi/grep-order.test.ts +12 -11
  61. package/src/pi/grep-output.ts +36 -15
  62. package/src/pi/grep-reread.ts +7 -2
  63. package/src/pi/grep-rg.testing.ts +70 -0
  64. package/src/pi/grep-scope.ts +4 -4
  65. package/src/pi/grep-search.ts +8 -11
  66. package/src/pi/grep-tool.ts +23 -39
  67. package/src/pi/grep.test.ts +102 -116
  68. package/src/pi/model-budgets.test.ts +2 -1
  69. package/src/pi/mutation-outcome.testing.ts +0 -1
  70. package/src/pi/mutation-result.test.ts +8 -8
  71. package/src/pi/mutation-result.ts +1 -1
  72. package/src/pi/mutation-runner.ts +9 -5
  73. package/src/pi/output-budgets.test.ts +53 -31
  74. package/src/pi/pi.test.ts +18 -13
  75. package/src/pi/read-tool.ts +13 -18
  76. package/src/pi/read.test.ts +22 -41
  77. package/src/pi/registration.test.ts +25 -19
  78. package/src/pi/render.test.ts +51 -32
  79. package/src/pi/render.ts +7 -4
  80. package/src/pi/replace-regex.ts +1 -1
  81. package/src/pi/replace-tool.ts +6 -16
  82. package/src/pi/replace.test.ts +45 -34
  83. package/src/pi/report-failure.testing.ts +9 -1
  84. package/src/pi/report-schema.ts +205 -83
  85. package/src/pi/report.test.ts +66 -64
  86. package/src/pi/report.ts +23 -17
  87. package/src/pi/result-safety.test.ts +121 -100
  88. package/src/pi/rg-process.test.ts +2 -2
  89. package/src/pi/rg-process.ts +9 -15
  90. package/src/pi/schema.ts +23 -0
  91. package/src/pi/tool-factories.testing.ts +59 -0
  92. package/src/pi/write-tool.ts +9 -15
  93. package/src/pi/write.test.ts +30 -31
  94. package/src/testing/run-tests.ts +1 -1
@@ -1,9 +1,9 @@
1
1
  /** Isolate a FIFO open so a regression cannot stall the parent runner's I/O threads. */
2
2
  import assert from "node:assert/strict";
3
3
  import { join } from "node:path";
4
- import { makeEditOverride } from "../pi/edit-tool.ts";
5
- import { makeReplaceTool } from "../pi/replace-tool.ts";
6
- import { DEFAULT_CONFIG } from "../pi/config.ts";
4
+ import { makeEditOverride } from "../pi/tool-factories.testing.ts";
5
+ import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
6
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
7
7
  import { callTool } from "../pi/tool-call.testing.ts";
8
8
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
9
9
 
@@ -12,7 +12,7 @@ assert.ok(directory);
12
12
  const cases = [
13
13
  {
14
14
  tool: makeEditOverride(directory, DEFAULT_CONFIG),
15
- args: { edits: [{ action: "append", body: ["after"] }] },
15
+ args: { steps: [{ action: "append", lines: ["after"] }] },
16
16
  },
17
17
  {
18
18
  tool: makeReplaceTool(directory, DEFAULT_CONFIG),
@@ -5,7 +5,7 @@ import { test } from "node:test";
5
5
  import type { ToolCall } from "@earendil-works/pi-ai";
6
6
  import { loadInstalledExtension } from "../testing/extension-loader.testing.ts";
7
7
  import { openTestSession, responseStream, SESSION_TIMEOUT_MS } from "../testing/session.testing.ts";
8
- import { decodeReport } from "../pi/report.ts";
8
+ import { reportOf } from "../pi/report.ts";
9
9
 
10
10
  test("packed extension completes file, worker, and command operations", {
11
11
  timeout: SESSION_TIMEOUT_MS,
@@ -64,7 +64,7 @@ test("packed extension completes file, worker, and command operations", {
64
64
  assert.equal(anchor("grep"), anchor("read"));
65
65
  return call("edit", "edit", {
66
66
  path: "fixture.txt",
67
- edits: [{ action: "replace", anchor: anchor("grep"), body: ["edited"] }],
67
+ steps: [{ action: "replace", anchor: anchor("grep"), lines: ["edited"] }],
68
68
  });
69
69
  },
70
70
  () =>
@@ -88,7 +88,7 @@ test("packed extension completes file, worker, and command operations", {
88
88
  for (const id of ["write", "read", "grep", "edit", "replace"]) result(id);
89
89
  const command = result("write")
90
90
  .content.map((block) =>
91
- block.type === "text" ? decodeReport(block.text, "write")?.then_run : undefined,
91
+ block.type === "text" ? reportOf({ content: [block] }, "write")?.then_run : undefined,
92
92
  )
93
93
  .find((facts) => facts !== undefined);
94
94
  assert.equal(command?.status, "succeeded");
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "../pi/action-fusion.testing.ts";
1
2
  /** Real file-handle races at publication and Fusion observation boundaries. */
2
3
  import assert from "node:assert/strict";
3
4
  import fs from "node:fs";
@@ -8,14 +9,14 @@ import { join } from "node:path";
8
9
  import { test, type TestContext } from "node:test";
9
10
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
10
11
  import { createActionFusionExecutor } from "../pi/action-fusion.ts";
11
- import { DEFAULT_CONFIG } from "../pi/config.ts";
12
- import { makeEditOverride } from "../pi/edit-tool.ts";
12
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
13
+ import { makeEditOverride } from "../pi/tool-factories.testing.ts";
13
14
  import { reportOf } from "../pi/report.ts";
14
15
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
15
- import { PUBLICATION_NEXT, REREAD } from "../pi/report-schema.ts";
16
- import { makeReplaceTool } from "../pi/replace-tool.ts";
16
+ import { PUBLICATION_NEXT } from "../pi/report-schema.ts";
17
+ import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
17
18
  import { callTool, createToolContext } from "../pi/tool-call.testing.ts";
18
- import { makeWriteOverride } from "../pi/write-tool.ts";
19
+ import { makeWriteOverride } from "../pi/tool-factories.testing.ts";
19
20
 
20
21
  const BEFORE = "before\n";
21
22
  const PUBLISHED = "before\nafter\n";
@@ -41,22 +42,25 @@ async function withDisturbedRead<T>(
41
42
  run: () => Promise<T>,
42
43
  ): Promise<T> {
43
44
  const nativeOpen = fs.promises.open;
45
+ const expectedBytes = Buffer.from(expected);
44
46
  let disturbed = false;
45
47
  t.mock.method(fs.promises, "open", async (...args: Parameters<typeof nativeOpen>) => {
46
48
  const handle = await nativeOpen(...args);
47
49
  if (args[0] === path) {
48
- const nativeRead = handle.readFile;
49
- t.mock.method(handle, "readFile", async (...readArgs: Parameters<typeof nativeRead>) => {
50
- const bytes = await nativeRead.apply(handle, readArgs);
51
- assert.ok(Buffer.isBuffer(bytes));
52
- if (!disturbed && ready(bytes)) {
50
+ const nativeRead = handle.read.bind(handle);
51
+ const chunks: Buffer[] = [];
52
+ t.mock.method(handle, "read", async (...readArgs: Parameters<typeof nativeRead>) => {
53
+ const result = await nativeRead(...readArgs);
54
+ chunks.push(Buffer.from(result.buffer as Uint8Array).subarray(0, result.bytesRead));
55
+ const bytes = Buffer.concat(chunks);
56
+ if (!disturbed && bytes.length >= expectedBytes.length && ready(bytes)) {
53
57
  disturbed = true;
54
- assert.deepEqual(bytes, Buffer.from(expected));
58
+ assert.deepEqual(bytes, expectedBytes);
55
59
  if (disturbance === "I/O failure") throw READ_FAILURE;
56
60
  if (disturbance === "delete") fs.unlinkSync(path);
57
61
  else fs.appendFileSync(path, CONCURRENT_APPEND);
58
62
  }
59
- return bytes;
63
+ return result;
60
64
  });
61
65
  }
62
66
  return handle;
@@ -88,7 +92,7 @@ const mutationCases = [
88
92
  name: "edit",
89
93
  make: (cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>) =>
90
94
  makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
91
- args: { edits: [{ action: "append", body: ["after"] }] },
95
+ args: { steps: [{ action: "append", lines: ["after"] }] },
92
96
  },
93
97
  {
94
98
  name: "replace",
@@ -132,18 +136,21 @@ for (const fused of [false, true]) {
132
136
  t,
133
137
  mutation.name === "write create" ? undefined : BEFORE,
134
138
  );
135
- const fusion = fused
136
- ? createActionFusionExecutor(async () =>
137
- assert.fail("command must not run without then_run"),
138
- )
139
- : undefined;
139
+ const executeTool: SessionCommand = async () =>
140
+ assert.fail("command must not run without then_run");
141
+ const fusion = fused ? createActionFusionExecutor(() => {}) : undefined;
140
142
  const result = await withDisturbedRead(
141
143
  t,
142
144
  path,
143
145
  PUBLISHED,
144
146
  disturbance,
145
147
  (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
146
- () => callTool(mutation.make(directory, fusion), { path, ...mutation.args }),
148
+ () =>
149
+ callTool(
150
+ mutation.make(directory, fusion),
151
+ { path, ...mutation.args },
152
+ { ctx: { cwd: directory, executeTool } },
153
+ ),
147
154
  );
148
155
  assert.equal(result.isError, undefined);
149
156
  const report = reportOf(
@@ -151,7 +158,7 @@ for (const fused of [false, true]) {
151
158
  mutation.name === "edit" ? "edit" : mutation.name === "replace" ? "replace" : "write",
152
159
  );
153
160
  assert.equal(report?.publication, "PUBLISHED");
154
- assert.equal(report?.next, REREAD);
161
+ assert.match(report?.next ?? "", /Read the file before further edits/);
155
162
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
156
163
  assert.equal(report?.then_run, undefined);
157
164
  assert.equal(report?.freshness, "changed");
@@ -171,18 +178,13 @@ for (const observation of [1, 2]) {
171
178
  let mutationCompleted = false;
172
179
  let observations = 0;
173
180
  let commands = 0;
174
- const fusion = createActionFusionExecutor(
175
- async () => {
176
- commands++;
177
- return {
178
- status: "succeeded",
179
- result: { content: [{ type: "text", text: "checked" }] },
180
- };
181
- },
182
- (progress) => {
183
- if (progress.mutationCompleted) mutationCompleted = true;
184
- },
185
- );
181
+ const executeTool: SessionCommand = async () => {
182
+ commands++;
183
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
184
+ };
185
+ const fusion = createActionFusionExecutor((progress) => {
186
+ if (progress.mutationCompleted) mutationCompleted = true;
187
+ });
186
188
  const ctx = await createToolContext(directory, t);
187
189
  const result = await withDisturbedRead(
188
190
  t,
@@ -199,7 +201,7 @@ for (const observation of [1, 2]) {
199
201
  mode: "overwrite",
200
202
  then_run: { command: "check" },
201
203
  },
202
- { ctx },
204
+ { ctx: { ...ctx, executeTool } },
203
205
  ),
204
206
  );
205
207
  assert.equal(commands, 0);
@@ -211,7 +213,7 @@ for (const observation of [1, 2]) {
211
213
  assert.equal(report?.freshnessError?.message, READ_FAILURE.message);
212
214
  assert.equal(report?.freshnessError?.code, "EIO");
213
215
  }
214
- assert.equal(report?.next, REREAD);
216
+ assert.match(report?.next ?? "", /Read the file before further edits/);
215
217
  assert.doesNotMatch(text(result), /retry the tool/);
216
218
  await assertTarget(path, PUBLISHED, disturbance);
217
219
  });
@@ -226,10 +228,11 @@ test("disturbance during post-command freshness read → retains publication and
226
228
  async (t) => {
227
229
  const { directory, path } = await targetFile(t, BEFORE);
228
230
  let commands = 0;
229
- const fusion = createActionFusionExecutor(async () => {
231
+ const executeTool: SessionCommand = async () => {
230
232
  commands++;
231
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
232
- });
233
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
234
+ };
235
+ const fusion = createActionFusionExecutor(() => {});
233
236
  const ctx = await createToolContext(directory, t);
234
237
  const result = await withDisturbedRead(
235
238
  t,
@@ -246,7 +249,7 @@ test("disturbance during post-command freshness read → retains publication and
246
249
  mode: "overwrite",
247
250
  then_run: { command: "check" },
248
251
  },
249
- { ctx },
252
+ { ctx: { ...ctx, executeTool } },
250
253
  ),
251
254
  );
252
255
  assert.equal(commands, 1);
@@ -256,7 +259,7 @@ test("disturbance during post-command freshness read → retains publication and
256
259
  reportOf(result, "write")?.freshness,
257
260
  disturbance === "I/O failure" ? "unknown" : "changed",
258
261
  );
259
- assert.equal(reportOf(result, "write")?.next, REREAD);
262
+ assert.match(reportOf(result, "write")?.next ?? "", /Read the file before further edits/);
260
263
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
261
264
  await assertTarget(path, PUBLISHED, disturbance);
262
265
  },
@@ -269,15 +272,11 @@ test("other I/O failure during post-publication read → retains the published p
269
272
  await t.test(fused ? "Fusion enabled" : "plain", async (t) => {
270
273
  const { directory, path } = await targetFile(t, BEFORE);
271
274
  let commands = 0;
272
- const fusion = fused
273
- ? createActionFusionExecutor(async () => {
274
- commands++;
275
- return {
276
- status: "succeeded",
277
- result: { content: [{ type: "text", text: "checked" }] },
278
- };
279
- })
280
- : undefined;
275
+ const executeTool: SessionCommand = async () => {
276
+ commands++;
277
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
278
+ };
279
+ const fusion = fused ? createActionFusionExecutor(() => {}) : undefined;
281
280
  const ctx = await createToolContext(directory, t);
282
281
  await withDisturbedRead(
283
282
  t,
@@ -295,7 +294,7 @@ test("other I/O failure during post-publication read → retains the published p
295
294
  mode: "overwrite",
296
295
  ...(fused ? { then_run: { command: "check" } } : {}),
297
296
  },
298
- { ctx },
297
+ { ctx: { ...ctx, executeTool } },
299
298
  ),
300
299
  "POST_PROCESS_FAILED",
301
300
  (report) => {
@@ -418,10 +417,11 @@ test("file changes after the editable snapshot → rejects publication against t
418
417
  test("concurrent change during editable snapshot read → skips Fusion with NOT_PUBLISHED and retry advice", async (t) => {
419
418
  const { directory, path } = await targetFile(t, BEFORE);
420
419
  let commands = 0;
421
- const fusion = createActionFusionExecutor(async () => {
420
+ const executeTool: SessionCommand = async () => {
422
421
  commands++;
423
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
424
- });
422
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
423
+ };
424
+ const fusion = createActionFusionExecutor(() => {});
425
425
  const ctx = await createToolContext(directory, t);
426
426
  await withDisturbedRead(
427
427
  t,
@@ -435,10 +435,10 @@ test("concurrent change during editable snapshot read → skips Fusion with NOT_
435
435
  makeEditOverride(directory, DEFAULT_CONFIG, fusion),
436
436
  {
437
437
  path,
438
- edits: [{ action: "append", body: ["after"] }],
438
+ steps: [{ action: "append", lines: ["after"] }],
439
439
  then_run: { command: "check" },
440
440
  },
441
- { ctx },
441
+ { ctx: { ...ctx, executeTool } },
442
442
  ),
443
443
  "FILE_CHANGED",
444
444
  (report) => {
@@ -6,9 +6,9 @@ import { syncBuiltinESMExports } from "node:module";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { test } from "node:test";
9
- import { DEFAULT_CONFIG } from "../pi/config.ts";
10
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
11
- import { makeReadOverride } from "../pi/read-tool.ts";
9
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
10
+ import { makeGrepOverride } from "../pi/tool-factories.testing.ts";
11
+ import { makeReadOverride } from "../pi/tool-factories.testing.ts";
12
12
  import { callTool } from "../pi/tool-call.testing.ts";
13
13
  import { withFileRead } from "../pi/file-read.ts";
14
14
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
@@ -30,7 +30,7 @@ test("read or grep scan truncated across a UTF-8 sequence → reports file chang
30
30
  assert.equal(isUtf8(source), true);
31
31
  const tools = [
32
32
  makeReadOverride(directory, DEFAULT_CONFIG),
33
- makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {}),
33
+ makeGrepOverride(directory, DEFAULT_CONFIG),
34
34
  ];
35
35
  for (const tool of tools) {
36
36
  await t.test(tool.name, async () => {
@@ -3,7 +3,7 @@ import { Worker } from "node:worker_threads";
3
3
  import { test } from "node:test";
4
4
  import { HashlineError } from "../core/errors.ts";
5
5
  import { runRegexReplacements } from "../pi/replace-regex.ts";
6
- import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
6
+ import { DEFAULT_OUTPUT_BUDGETS } from "../pi/tool-factories.testing.ts";
7
7
  import { causeOf } from "../pi/report-cause.ts";
8
8
  import type { Cause } from "../pi/report-schema.ts";
9
9
 
@@ -6,12 +6,11 @@ import { test } from "node:test";
6
6
  import { stripVTControlCharacters } from "node:util";
7
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
8
8
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
9
- import { DEFAULT_CONFIG } from "../pi/config.ts";
10
- import { makeEditOverride } from "../pi/edit-tool.ts";
9
+ import { DEFAULT_CONFIG, makeEditOverride } from "../pi/tool-factories.testing.ts";
11
10
  import { reportOf } from "../pi/report.ts";
12
11
  import { openTestSession, responseStream } from "../testing/session.testing.ts";
13
12
 
14
- const args = { path: "target.txt", edits: [{ action: "append", body: [] }] };
13
+ const args = { path: "target.txt", steps: [{ action: "append", lines: [] }] };
15
14
 
16
15
  test("live preparation failure → replays diagnostic after fresh registration", async (t) => {
17
16
  initTheme("dark");
@@ -52,7 +51,7 @@ test("live preparation failure → replays diagnostic after fresh registration",
52
51
  const replay = { content: structuredClone(live.content), details: undefined };
53
52
  const serialized = JSON.stringify(replay);
54
53
  const report = reportOf(replay, "edit");
55
- assert.equal(report?.issues?.[0].field, "edits[0].body");
54
+ assert.equal(report?.issues?.[0].field, "steps[0].lines");
56
55
  assert.equal(report?.issues?.[0].reason, "is empty");
57
56
 
58
57
  const second = await openTestSession(t, {
@@ -80,8 +79,8 @@ test("live preparation failure → replays diagnostic after fresh registration",
80
79
  isError: true,
81
80
  });
82
81
  const shown = stripVTControlCharacters(component.render(240).join("\n"));
83
- assert.match(shown, /edits\[0\]\.body: is empty/);
84
- assert.equal(shown.split("edits[0].body: is empty").length - 1, 1);
82
+ assert.match(shown, /steps\[0\]\.lines: is empty/);
83
+ assert.equal(shown.split("steps[0].lines: is empty").length - 1, 1);
85
84
  assert.doesNotMatch(shown, /"issues":/);
86
85
  assert.equal(JSON.stringify(decoded), serialized);
87
86
  }
@@ -4,9 +4,9 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { test } from "node:test";
7
- import { DEFAULT_CONFIG } from "../pi/config.ts";
8
- import { makeEditOverride } from "../pi/edit-tool.ts";
9
- import { makeReplaceTool } from "../pi/replace-tool.ts";
7
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
8
+ import { makeEditOverride } from "../pi/tool-factories.testing.ts";
9
+ import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
10
10
  import { byteRevision } from "../pi/file-revision.ts";
11
11
  import { callTool } from "../pi/tool-call.testing.ts";
12
12
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
@@ -32,7 +32,7 @@ test("valid UTF-8 exceeding the runtime string limit → mutations retain the si
32
32
  await t.test(tool.name, async () => {
33
33
  const args =
34
34
  tool.name === "edit"
35
- ? { path, edits: [{ action: "append", body: ["tail"] }] }
35
+ ? { path, steps: [{ action: "append", lines: ["tail"] }] }
36
36
  : { path, replacements: [{ literal: true, find: "中文", replace: "汉字" }] };
37
37
  await expectToolFailure(callTool(tool, args), "FILESYSTEM_ERROR", (report) => {
38
38
  assert.doesNotMatch(JSON.stringify(report), /UNSUPPORTED_ENCODING/);
package/src/pi/AGENTS.md CHANGED
@@ -10,7 +10,7 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
10
10
 
11
11
  - Tool files (`read-tool.ts`, `grep-tool.ts`, `edit-tool.ts`, `replace-tool.ts`, `write-tool.ts`) define TypeBox schemas and each mutation tool's description names its alternative (edit ↔ replace ↔ write). Each tool's `prepareArguments` comes from `argument-validation.ts`, then Pi validates against the schema again, and only then calls `execute`. Caller arguments are never rewritten. Each tool supplies only the semantic checks the schema cannot express or name precisely: edit rejects fields an operation's `action` does not take or requires but lacks, empty bodies, body lines that cannot be written as UTF-8, line numbers beyond the safe-integer range, anchors of another hash length, and reversed ranges; replace rejects unwritable replacement text; replace and grep share `checkRegexArguments`, which reports flags V8 rejects and compiles regex-mode patterns; write rejects unwritable content. File-dependent checks stay in execution. Shared integer rules live in `schema.ts`. Every tool declares `STRICT_SAMPLING` from `schema.ts` (mutation tools through `mutationToolBase`) and keeps its parameters convertible by Pi's strict converter: no object or array unions, so grep's multi-valued fields are arrays only and each edit item is one flat object whose `EDIT_OPS` table, not the schema, fixes the fields per action. Constrained sampling and some gateways emit keys alphabetically, so the item's discriminator keeps the alphabetically first key.
12
12
  - `argument-validation.ts` owns every tool's `prepareArguments` hook, issue collection, bounded diagnostic output, and the Pi schema validation adapter. Tools report semantic field issues through its callback and do not throw during collection. Successful schema conversion informs those checks without changing caller arguments. Observe prepared failures without reimplementing coercion or optional-null rules.
13
- - `argument-diagnostics.ts` owns failure-only schema projection and structured aggregation. Top-level tool fields have independent schemas; failure diagnosis derives field schemas with TypeBox and keeps Pi's coercion and per-field error limits. Derive choices and the explanations of missing, undeclared, and pattern-mismatched fields from the declared schema: when a schema reason does not say how to correct the value, a missing or pattern-mismatched field's `fix` is its description (each choice's value and description), and an undeclared field's `fix` lists its object's accepted fields. A declared field is applicable even when absent, so a tool check may require it. An issue on a whole object leaves its fields' diagnostics in place. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
13
+ - `argument-diagnostics.ts` owns failure-only schema projection and structured aggregation. Top-level tool fields have independent schemas; failure diagnosis derives field schemas with TypeBox and keeps Pi's coercion and per-field error limits. Derive choices and the explanations of missing, undeclared, pattern-mismatched, and out-of-choice fields from the declared schema: when a schema reason does not say how to correct the value, the `fix` of a missing field, a pattern mismatch, or a value outside the field's choices is the field's description (each choice's value and description), and an undeclared field's `fix` lists its object's accepted fields. A declared field is applicable even when absent, so a tool check may require it. An issue on a whole object leaves its fields' diagnostics in place. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
14
14
  - `argument-error.ts` owns the JSON argument-error envelope and its byte budget: retain exact field paths, omit whole issues with explicit counts, and never truncate serialized JSON or repeat the call's arguments. Preparation failures use the same envelope.
15
15
 
16
16
  ## Mutations
@@ -23,9 +23,9 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
23
23
 
24
24
  ## grep
25
25
 
26
- - Split into `grep-tool` (schema and execution order), `grep-scope` (paths and glob admission), `grep-candidates` (candidate strategy, fallback, whole-scope scan budget, and the empty-scope guard), `grep-search` (queue backpressure, worker pool, per-file matches with their revisions), `grep-reread` (content mode's bounded second read of each matched file and its revision check), `grep-output` (payload rows, file-header format and its parser, and every grep report fact, including empty and incomplete searches), and `grep-render` (TUI rows). Grep scans each candidate file once through `text-stream.ts` (via `scanTextFile`) for NUL, UTF-8 validity, its revision, and the lossy LF view it matches; content mode reads each matched file again in `grep-reread`. Each stage returns its warnings, ordered within the stage, in its result rather than appending to a shared list; `grep-tool` joins them in stage order. README defines resource limits and physical-line reporting; document file and worker budgets there.
26
+ - Split into `grep-tool` (schema and execution order), `grep-scope` (paths and glob admission), `grep-candidates` (candidate strategy, fallback, whole-scope scan budget, and the empty-scope guard), `grep-search` (queue backpressure, worker pool, per-file matches with their revisions), `grep-reread` (content mode's bounded second read of each matched file and its revision check), `grep-output` (payload rows, file-header format and its parser, and every grep report fact, including empty and incomplete searches), and `grep-render` (TUI rows). Grep scans each candidate file once through `text-stream.ts` (via `scanTextFile`) for NUL, UTF-8 validity, its revision, and the lossy LF view it matches; content mode reads each matched file again in `grep-reread`. Each stage returns ordered `SearchWarning` records (`{ path?, reason }`) in its result rather than composing sentences; `grep-tool` joins stages in order, and only `grep-output` formats diagnostics with cwd-relative paths, de-duplicates them, and applies the field budget. README defines resource limits and physical-line reporting; document file and worker budgets there.
27
27
  - Without `multiline`, `rg-regex.ts` translates each pattern into rg patterns that list every line the query matches: keep a construct only where both engines give it the same meaning over the original line bytes (CRLF, malformed UTF-8, surrogate halves included), and otherwise widen it; never narrow. Bound string expansion and emitted patterns. Preserve every alternative. A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
28
- - `rg-process.ts` is the ripgrep process layer: spawning, bounded reading, and parsing rg's output protocols (`runRgPaths` reads NUL-delimited paths; `runRgLines` reads the per-file line numbers of `LINE_LISTING_ARGS`). It knows no candidate strategy. Keep the injectable `GrepBackend` and completed-run diagnostics here. Scope flags are produced only in `grep-scope.ts` and never parsed back.
28
+ - `rg-process.ts` is the ripgrep process layer: spawning, bounded reading, and parsing rg's output protocols (`runRgPaths` reads NUL-delimited paths; `runRgLines` reads the per-file line numbers of `LINE_LISTING_ARGS`). It knows no candidate strategy. Completed-run diagnostics leave this layer as reason-only warning data; path formatting belongs to `grep-output`. Scope flags are produced only in `grep-scope.ts` and never parsed back.
29
29
  - `grep-candidates.ts` decides which rg runs to make: line candidates through `rg-regex.ts` (workers re-check only those lines through `searchLines`), else candidate files (`--files-with-matches` over the necessary literals, or `--files` when none is necessary or they exceed `MAX_RG_PATTERN_UNITS`). Byte-level pattern flags are defined once there.
30
30
  - Keep grep matching in the bounded, cancellable worker pool of `grep-search.ts`: a lazily started pool, each worker sending `core/search.ts` whole lines in bounded requests, or the whole file for a multiline query. Commit file results, warnings, and fatal failures in listing order; retire a worker after a fatal file result, but propagate cancellation without waiting for earlier files.
31
31
  - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
@@ -36,10 +36,11 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
36
36
 
37
37
  ## Reports and rendering
38
38
 
39
- - `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). Checked report types retain their tool or error-code variant; absent fields remain readable as undefined. Types derive from it. Its closed wire schemas validate text-only reports, enforce legal tool names, and require code-specific facts.
40
- - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order) and omits the call's own `tool`/`path` from every result text while retaining them in `details.report`; renderers pass their tool name to decode text-only reports. `reportResult` appends a success report after the tool's payload; every tool's `execute` runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
39
+ - `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), its schema, audience, and model decision purpose, every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). `FACT_FIELDS` is the required declaration point; model omission is derived from its audience together with the call fields, so `report.ts` does not maintain a second field set. Checked report types retain their tool or error-code variant; absent fields remain readable as undefined. Types derive from it. Its closed wire schemas validate text-only reports, enforce legal tool names, and require code-specific facts.
40
+ - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). It filters the derived model omission set (`MODEL_OMITTED_FIELDS`) and omits the call's own `tool`/`path` plus TUI-only facts from result text while retaining them in `details.report`; renderers pass their tool name to decode text-only reports. `reportResult` appends a success report after the tool's payload; every tool's `execute` runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
41
41
  - `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Failure rendering uses `details.report`; Pi raises argument errors before execution, so text-only argument rejections decode from the final content block with `decodeReport`. Report text omits its tool, so every `decodeReport` call supplies the originating call's tool name. Invalid text-only reports remain raw.
42
42
  - `report-cause.ts` transports structured causes without Pi runtime imports, preserving cause chains with cycle protection; reports and worker replies share it. Native failures state the original diagnostic and errno once in `message`, retaining only an actual underlying `Error.cause`.
43
+ - To add or change a report field: (1) declare it in `FACT_FIELDS` under its owning layer's group, including its audience and, for model-visible facts, the non-empty decision it changes; (2) list it in each `SUCCESS_DEFINITIONS` tool or `ERROR_DEFINITIONS` code that carries it; (3) when it needs recovery, add one `OUTCOME_NEXT` rule or the code's `next`, never a sentence at the producing site; (4) produce it in that one layer, bounded by the call's budget, omitting whole items with a count; (5) leave `render.ts` alone unless a card presents the fact another way, and then name it in that card's shown set; (6) check the README passage for the tool. The model omission set is derived from the declarations; do not add a parallel list in `report.ts`. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
43
44
  - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
44
45
 
45
46
  ## Budgets and config