@criogaid/pi-hashline-edit 0.7.0 → 0.8.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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { test } from "node:test";
5
5
  import type { ToolCall } from "@earendil-works/pi-ai";
@@ -7,16 +7,10 @@ import { loadInstalledExtension } from "../testing/extension-loader.testing.ts";
7
7
  import { openTestSession, responseStream, SESSION_TIMEOUT_MS } from "../testing/session.testing.ts";
8
8
  import { decodeReport } from "../pi/report.ts";
9
9
 
10
- test("packed extension completes file, worker, command, and context operations", {
10
+ test("packed extension completes file, worker, and command operations", {
11
11
  timeout: SESSION_TIMEOUT_MS,
12
12
  }, async (t) => {
13
13
  const cwd = process.cwd();
14
- await mkdir(join(cwd, ".pi"));
15
- await writeFile(
16
- join(cwd, ".pi", "settings.json"),
17
- JSON.stringify({ hashlineEdit: { forget: true } }),
18
- );
19
- await writeFile(join(cwd, "build.log"), "PACKAGE_LOG_CONTENT ".repeat(200));
20
14
  await writeFile(
21
15
  join(cwd, "check.mjs"),
22
16
  [
@@ -29,7 +23,7 @@ test("packed extension completes file, worker, command, and context operations",
29
23
  const factory = await loadInstalledExtension(process.argv[2]);
30
24
  const { session, model } = await openTestSession(t, {
31
25
  cwd,
32
- tools: ["write", "read", "grep", "edit", "replace", "forget", "bash"],
26
+ tools: ["write", "read", "grep", "edit", "replace", "bash"],
33
27
  configure: (pi) => factory(pi),
34
28
  });
35
29
  const result = (id: string) => {
@@ -76,32 +70,13 @@ test("packed extension completes file, worker, command, and context operations",
76
70
  () =>
77
71
  call("replace", "replace", {
78
72
  path: "fixture.txt",
79
- replacements: [{ find: "(edited)", replace: "$1 after", regex: true }],
73
+ replacements: [{ find: "(edited)", replace: "$1 after", literal: false }],
80
74
  }),
81
- () => call("log-read", "read", { path: "build.log" }),
82
- () => {
83
- const tag = result("log-read")
84
- .content.map((block) =>
85
- block.type === "text" ? decodeReport(block.text, "read")?.resultId : undefined,
86
- )
87
- .find((id) => id !== undefined);
88
- assert.ok(tag);
89
- return call("forget", "forget", { ids: [tag] });
90
- },
91
75
  ];
92
76
  let next = 0;
93
- session.agent.streamFunction = (_model, context) => {
77
+ session.agent.streamFunction = () => {
94
78
  const action = actions[next++];
95
79
  if (action) return responseStream(model, { content: [action()], stopReason: "toolUse" });
96
- const forgotten = context.messages.find(
97
- (message) => message.role === "toolResult" && message.toolCallId === "log-read",
98
- );
99
- assert.ok(forgotten?.role === "toolResult");
100
- assert.equal(forgotten.content.length, 1);
101
- assert.doesNotMatch(JSON.stringify(forgotten.content), /PACKAGE_LOG_CONTENT/);
102
- const receipt = forgotten.content[0];
103
- assert.ok(receipt.type === "text");
104
- assert.equal(decodeReport(receipt.text, forgotten.toolName)?.contentForgotten, true);
105
80
  return responseStream(model, {
106
81
  content: [{ type: "text", text: "Done." }],
107
82
  stopReason: "stop",
@@ -110,7 +85,7 @@ test("packed extension completes file, worker, command, and context operations",
110
85
  await session.prompt("Complete the packaged tool workflow.");
111
86
  assert.equal(session.agent.state.errorMessage, undefined);
112
87
  assert.equal(next, actions.length + 1);
113
- for (const id of ["write", "read", "grep", "edit", "replace", "forget"]) result(id);
88
+ for (const id of ["write", "read", "grep", "edit", "replace"]) result(id);
114
89
  const command = result("write")
115
90
  .content.map((block) =>
116
91
  block.type === "text" ? decodeReport(block.text, "write")?.then_run : undefined,
@@ -119,5 +94,4 @@ test("packed extension completes file, worker, command, and context operations",
119
94
  assert.equal(command?.status, "succeeded");
120
95
  assert.match(command?.output ?? "", /PACKAGE_COMMAND_OK/);
121
96
  assert.equal(await readFile(join(cwd, "fixture.txt"), "utf8"), "edited after\nkeep\n");
122
- assert.equal(await readFile(join(cwd, "build.log"), "utf8"), "PACKAGE_LOG_CONTENT ".repeat(200));
123
97
  });
@@ -8,9 +8,11 @@ import { join } from "node:path";
8
8
  import { test, type TestContext } from "node:test";
9
9
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
10
10
  import { createActionFusionExecutor } from "../pi/action-fusion.ts";
11
+ import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
11
12
  import { DEFAULT_CONFIG } from "../pi/config.ts";
12
13
  import { makeEditOverride } from "../pi/edit-tool.ts";
13
- import { byteRevision, commitFile, FileMutationError } from "../pi/file-commit.ts";
14
+ import { commitFile, FileMutationError } from "../pi/file-commit.ts";
15
+ import { byteRevision } from "../pi/file-revision.ts";
14
16
  import { describeFailure, reportOf } from "../pi/report.ts";
15
17
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
16
18
  import { REREAD } from "../pi/report-schema.ts";
@@ -95,7 +97,7 @@ const mutationCases = [
95
97
  name: "replace",
96
98
  make: (cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>) =>
97
99
  makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
98
- args: { replacements: [{ find: BEFORE, replace: PUBLISHED }] },
100
+ args: { replacements: [{ literal: true, find: BEFORE, replace: PUBLISHED }] },
99
101
  },
100
102
  {
101
103
  name: "write overwrite",
@@ -114,7 +116,7 @@ for (const fused of [false, true]) {
114
116
  for (const mutation of mutationCases) {
115
117
  for (const disturbance of ["append", "delete"] as const) {
116
118
  await t.test(
117
- `${mutation.name}: ${disturbance} → published without a stable revision`,
119
+ `${mutation.name}: ${disturbance} → retains publication and reports changed freshness`,
118
120
  async (t) => {
119
121
  const { directory, path } = await targetFile(
120
122
  t,
@@ -130,17 +132,15 @@ for (const fused of [false, true]) {
130
132
  () => callTool(mutation.make(directory, fusion), { path, ...mutation.args }),
131
133
  );
132
134
  assert.equal(result.isError, undefined);
133
- assert.equal(result.details.publication, "PUBLISHED");
134
- assert.equal(Object.hasOwn(result.details, "observedRevision"), false);
135
- assert.equal(result.details.publishedRevision, byteRevision(PUBLISHED));
136
- if (mutation.name !== "write create")
137
- assert.equal(result.details.baseRevision, byteRevision(BEFORE));
138
- assert.equal(reportOf(result)?.next, REREAD);
135
+ const report = reportOf(
136
+ result,
137
+ mutation.name === "edit" ? "edit" : mutation.name === "replace" ? "replace" : "write",
138
+ );
139
+ assert.equal(report?.publication, "PUBLISHED");
140
+ assert.equal(report?.next, REREAD);
139
141
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
140
- if (fused) {
141
- assert.equal(result.details.actionFusion.command, "not_requested");
142
- assert.equal(result.details.actionFusion.freshness, "changed");
143
- }
142
+ assert.equal(report?.then_run, undefined);
143
+ assert.equal(report?.freshness, "changed");
144
144
  await assertTarget(path, PUBLISHED, disturbance);
145
145
  },
146
146
  );
@@ -160,7 +160,10 @@ for (const observation of [1, 2]) {
160
160
  const fusion = createActionFusionExecutor(
161
161
  async () => {
162
162
  commands++;
163
- return { status: "succeeded", output: "checked" };
163
+ return {
164
+ status: "succeeded",
165
+ result: { content: [{ type: "text", text: "checked" }] },
166
+ };
164
167
  },
165
168
  (progress) => {
166
169
  if (progress.mutationCompleted) mutationCompleted = true;
@@ -186,10 +189,8 @@ for (const observation of [1, 2]) {
186
189
  ),
187
190
  );
188
191
  assert.equal(commands, 0);
189
- assert.equal(result.details.publication, "PUBLISHED");
190
- assert.equal(result.details.actionFusion.publication, "PUBLISHED");
191
- assert.equal(result.details.actionFusion.command, "skipped");
192
- const report = reportOf(result);
192
+ const report = reportOf(result, "write");
193
+ assert.equal(report?.publication, "PUBLISHED");
193
194
  assert.equal(report?.then_run?.status, "skipped");
194
195
  assert.equal(report?.freshness, disturbance === "I/O failure" ? "unknown" : "changed");
195
196
  if (disturbance === "I/O failure") {
@@ -213,7 +214,7 @@ test("disturbance during post-command freshness read → retains publication and
213
214
  let commands = 0;
214
215
  const fusion = createActionFusionExecutor(async () => {
215
216
  commands++;
216
- return { status: "succeeded", output: "checked" };
217
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
217
218
  });
218
219
  const ctx = await createToolContext(directory, t);
219
220
  const result = await withDisturbedRead(
@@ -235,13 +236,13 @@ test("disturbance during post-command freshness read → retains publication and
235
236
  ),
236
237
  );
237
238
  assert.equal(commands, 1);
238
- assert.equal(result.details.publication, "PUBLISHED");
239
- assert.equal(result.details.actionFusion.command, "succeeded");
239
+ assert.equal(reportOf(result, "write")?.publication, "PUBLISHED");
240
+ assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
240
241
  assert.equal(
241
- result.details.actionFusion.freshness,
242
+ reportOf(result, "write")?.freshness,
242
243
  disturbance === "I/O failure" ? "unknown" : "changed",
243
244
  );
244
- assert.equal(reportOf(result)?.next, REREAD);
245
+ assert.equal(reportOf(result, "write")?.next, REREAD);
245
246
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
246
247
  await assertTarget(path, PUBLISHED, disturbance);
247
248
  },
@@ -274,7 +275,7 @@ test("concurrent change during pre-publication revision read → rejects without
274
275
  for (const phase of ["inspect target", "revision recheck", "no-op check"] as const) {
275
276
  await t.test(`${phase} → NOT_PUBLISHED`, async (t) => {
276
277
  const { path } = await targetFile(t, BEFORE);
277
- const revision = byteRevision(BEFORE);
278
+ const revision = byteRevision(Buffer.from(BEFORE));
278
279
  await withDisturbedRead(
279
280
  t,
280
281
  path,
@@ -292,7 +293,7 @@ test("concurrent change during pre-publication revision read → rejects without
292
293
  assert.equal(error.publication, "NOT_PUBLISHED");
293
294
  assert.equal(error.errorCode, "FILE_CHANGED");
294
295
  assert.equal(
295
- describeFailure("write", error, { mutation: true }).next,
296
+ describeFailure("write", error, { budget: DEFAULT_OUTPUT_BUDGETS }).next,
296
297
  "Retry the call.",
297
298
  );
298
299
  return true;
@@ -305,12 +306,43 @@ test("concurrent change during pre-publication revision read → rejects without
305
306
  }
306
307
  });
307
308
 
309
+ test("file changes after the editable snapshot → rejects publication against the read bytes", async (t) => {
310
+ for (const mutation of mutationCases.filter(
311
+ ({ name }) => name === "edit" || name === "replace",
312
+ )) {
313
+ await t.test(mutation.name, async (t) => {
314
+ const { directory, path } = await targetFile(t, BEFORE);
315
+ const nativeOpen = fs.promises.open;
316
+ let targetReads = 0;
317
+ t.mock.method(fs.promises, "open", async (...args: Parameters<typeof nativeOpen>) => {
318
+ if (args[0] === path && ++targetReads === 2) fs.appendFileSync(path, CONCURRENT_APPEND);
319
+ return nativeOpen(...args);
320
+ });
321
+ syncBuiltinESMExports();
322
+ try {
323
+ await expectToolFailure(
324
+ callTool(mutation.make(directory), { path, ...mutation.args }),
325
+ "FILE_CHANGED",
326
+ (report) => {
327
+ assert.equal(report.publication, "NOT_PUBLISHED");
328
+ },
329
+ );
330
+ assert.equal(targetReads, 2);
331
+ await assertTarget(path, BEFORE, "append");
332
+ } finally {
333
+ t.mock.restoreAll();
334
+ syncBuiltinESMExports();
335
+ }
336
+ });
337
+ }
338
+ });
339
+
308
340
  test("concurrent change during editable snapshot read → skips Fusion with NOT_PUBLISHED and retry advice", async (t) => {
309
341
  const { directory, path } = await targetFile(t, BEFORE);
310
342
  let commands = 0;
311
343
  const fusion = createActionFusionExecutor(async () => {
312
344
  commands++;
313
- return { status: "succeeded", output: "checked" };
345
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
314
346
  });
315
347
  const ctx = await createToolContext(directory, t);
316
348
  await withDisturbedRead(
@@ -5,7 +5,10 @@ import { Worker } from "node:worker_threads";
5
5
  for (const { entry, input, expected } of [
6
6
  {
7
7
  entry: "replace-worker.mjs",
8
- input: { source: "before\n", rules: [{ find: "(before)", replace: "$1 after", regex: true }] },
8
+ input: {
9
+ source: "before\n",
10
+ rules: [{ find: "(before)", replace: "$1 after", literal: false }],
11
+ },
9
12
  expected: { text: "before after\n", count: 1 },
10
13
  },
11
14
  {
@@ -3,11 +3,12 @@ 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
7
  import { causeOf } from "../pi/report.ts";
7
8
  import type { Cause } from "../pi/report-schema.ts";
8
9
 
9
10
  const timeoutMs = 10_000;
10
- const validRules = [{ find: "safe", replace: "changed", regex: true }];
11
+ const validRules = [{ find: "safe", replace: "changed", literal: false }];
11
12
 
12
13
  test("worker boundary: malformed external reply → rejects its result and facts", async (t) => {
13
14
  for (const reply of [
@@ -74,34 +75,43 @@ test("worker boundary: deep structured cause reply → preserves the terminal ca
74
75
  (error: unknown) => {
75
76
  assert.ok(error instanceof HashlineError);
76
77
  assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
77
- assert.deepEqual(causeOf(error.cause), cause);
78
+ assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
78
79
  return true;
79
80
  },
80
81
  );
81
82
  });
82
83
 
83
- test("worker boundary: cyclic argument facts in a reply → rejects nonserializable diagnostics", {
84
+ test("worker boundary: cyclic structured cause → rejects a reply accepted with an acyclic cause", {
84
85
  timeout: timeoutMs,
85
86
  }, async (t) => {
86
- const argumentsCopy: { self?: unknown } = {};
87
- argumentsCopy.self = argumentsCopy;
88
- const reply = {
89
- error: {
90
- code: "INVALID_ARGUMENTS",
91
- message: "invalid arguments",
92
- facts: { issues: [{ field: "path", reason: "missing" }], arguments: argumentsCopy },
93
- },
94
- };
95
- const emit = Worker.prototype.emit;
96
- t.mock.method(
97
- Worker.prototype,
98
- "emit",
99
- function (this: Worker, event: string | symbol, ...args: unknown[]) {
100
- return emit.call(this, event, ...(event === "message" ? [reply] : args));
101
- },
102
- );
103
- await assert.rejects(
104
- runRegexReplacements("safe", validRules, timeoutMs, undefined),
105
- (error: unknown) => error instanceof HashlineError && error.errorCode === "REGEX_WORKER_FAILED",
106
- );
87
+ for (const cyclic of [false, true]) {
88
+ await t.test(`cyclic=${cyclic}`, async (t) => {
89
+ const cause: Cause = { code: "EIO", message: "worker failure" };
90
+ if (cyclic) cause.cause = cause;
91
+ const reply = { error: { code: "NO_MATCH", message: "no match", facts: { rule: 0 }, cause } };
92
+ const emit = Worker.prototype.emit;
93
+ t.mock.method(
94
+ Worker.prototype,
95
+ "emit",
96
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
97
+ return emit.call(this, event, ...(event === "message" ? [reply] : args));
98
+ },
99
+ );
100
+ await assert.rejects(
101
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
102
+ (error: unknown) => {
103
+ assert.ok(error instanceof HashlineError);
104
+ if (cyclic) {
105
+ assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
106
+ assert.match(error.message, /invalid result/i);
107
+ } else {
108
+ assert.equal(error.errorCode, "NO_MATCH");
109
+ assert.deepEqual(error.facts, { rule: 0 });
110
+ assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
111
+ }
112
+ return true;
113
+ },
114
+ );
115
+ });
116
+ }
107
117
  });
@@ -35,7 +35,7 @@ test("live preparation failure → replays diagnostic after fresh registration",
35
35
  );
36
36
  assert.ok(result?.role === "toolResult");
37
37
  assert.equal(result.isError, true);
38
- assert.equal(reportOf(result)?.error, "INVALID_ARGUMENTS");
38
+ assert.equal(reportOf(result, "edit")?.error, "INVALID_ARGUMENTS");
39
39
  return responseStream(first.model, {
40
40
  content: [{ type: "text", text: "Done." }],
41
41
  stopReason: "stop",
@@ -51,7 +51,7 @@ test("live preparation failure → replays diagnostic after fresh registration",
51
51
  assert.ok(live?.role === "toolResult");
52
52
  const replay = { content: structuredClone(live.content), details: undefined };
53
53
  const serialized = JSON.stringify(replay);
54
- const report = reportOf(replay);
54
+ const report = reportOf(replay, "edit");
55
55
  assert.equal(report?.issues?.[0].field, "edits[0].body");
56
56
  assert.equal(report?.issues?.[0].reason, "is empty");
57
57
 
@@ -7,7 +7,7 @@ import { test } from "node:test";
7
7
  import { DEFAULT_CONFIG } from "../pi/config.ts";
8
8
  import { makeEditOverride } from "../pi/edit-tool.ts";
9
9
  import { makeReplaceTool } from "../pi/replace-tool.ts";
10
- import { byteRevision } from "../pi/file-commit.ts";
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";
13
13
 
@@ -33,7 +33,7 @@ test("valid UTF-8 exceeding the runtime string limit → mutations retain the si
33
33
  const args =
34
34
  tool.name === "edit"
35
35
  ? { path, edits: [{ op: "append", body: ["tail"] }] }
36
- : { path, replacements: [{ find: "中文", replace: "汉字" }] };
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/);
39
39
  assert.match(report.message ?? "", /ERR_STRING_TOO_LONG/);
package/src/pi/AGENTS.md CHANGED
@@ -4,11 +4,11 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
4
4
 
5
5
  ## Registration
6
6
 
7
- `src/index.ts` loads the config once and passes it explicitly to each tool factory, which keeps that snapshot for its lifetime. When `enabled` is false it registers nothing. Otherwise it registers tools from their `make*Override` / `makeReplaceTool` factories through one helper that appends `NEXT_GUIDELINE` from `report-schema.ts` (Pi prints the shared guideline once), and calls `registerForgetTool` only when `forget` is enabled. When `actionFusion` is on, the three mutation tools also receive the Action Fusion executor and are wrapped with `withMutationStatus`; `withThenRunDescription` appends the one then_run selection sentence as `withThenRunSchema` adds the field, and the field's `command` description carries the Windows path note only when `process.platform` is `win32`.
7
+ `src/index.ts` loads the config once and passes it explicitly to each tool factory, which keeps that snapshot for its lifetime. When `enabled` is false it registers nothing. Otherwise it registers tools from their `make*Override` / `makeReplaceTool` factories through one helper that appends `NEXT_GUIDELINE` from `report-schema.ts` (Pi prints the shared guideline once). When `actionFusion` is on, the three mutation tools also receive the Action Fusion executor and are wrapped with `withMutationStatus`; `withThenRunDescription` appends the then_run selection instructions as `withThenRunSchema` adds the field, and the field's `command` description carries the Windows path note only when `process.platform` is `win32`.
8
8
 
9
9
  ## Argument funnel
10
10
 
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 empty bodies, body lines that cannot be written as UTF-8, line numbers beyond the safe-integer range, and anchors of another hash length; replace rejects unwritable replacement text and compiles regex rules; write rejects unwritable content. File-dependent checks stay in execution. Shared integer rules live in `schema.ts`.
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 empty bodies, body lines that cannot be written as UTF-8, line numbers beyond the safe-integer range, and anchors of another hash length; 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`.
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
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 branches, choices, and the explanations of missing, forbidden, 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 a forbidden field's `fix` lists the selected shape's accepted fields after the meaning of the operation that selected it. 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.
@@ -17,7 +17,8 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
17
17
 
18
18
  - `mutation-runner.ts` owns the call sequence shared by `edit`/`replace`/`write` after Pi has validated the arguments: separating `then_run`, path resolution, `withFileMutationQueue`, and the hand-off to Action Fusion or plain finalization. Each tool's `run` returns a tool-indexed `MutationOutcome` (commit facts, details, schema-derived outcome facts), and only `finalizeMutation` turns it into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, so each tool supplies only a `TextChange` (new text, outcome facts).
19
19
  - `file-read.ts` provides guarded stream and whole-file reads; byte revision checks stay in the search and commit owners.
20
- - `file-commit.ts` is the only publication path: SHA-256 revisions (`byteRevision`/`fileRevision`), no-op detection, a temp file in a sibling dir, then `link` (create) or `rename` (overwrite). It handles symlinks and hard links, preserves file modes, and syncs the directory on POSIX. It throws `FileMutationError` with a `stage` and a publication status; a failed step is the `message`, its underlying error the `cause`. `edit`/`replace` commit with `baseRevision`, the revision of the bytes they read; `CommitOptions` admits it only with `overwrite`. Its target type distinguishes missing from existing files with required revision and mode facts; commit results distinguish creation, replacement, and no-op. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
20
+ - `file-revision.ts` defines a revision once: the SHA-256 hex of exact bytes, whole (`byteRevision`) or streamed. `text-stream.ts` returns the revision of the bytes each scan read, so callers never hash.
21
+ - `file-commit.ts` is the only publication path: file revisions (`fileRevision`), no-op detection, a temp file in a sibling dir, then `link` (create) or `rename` (overwrite). It handles symlinks and hard links, preserves file modes, and syncs the directory on POSIX. It throws `FileMutationError` with a `stage` and a publication status; a failed step is the `message`, its underlying error the `cause`. `edit`/`replace` commit with `baseRevision`, the revision of the bytes they read; `CommitOptions` admits it only with `overwrite`. Its target type distinguishes missing from existing files with required revision and mode facts; commit results distinguish creation, replacement, and no-op. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
21
22
  - `mutation-result.ts` owns tool-indexed outcome facts, final success/failure details, and progress details. It builds diffs and finalizes one mutation report from commit, tool, freshness, and command facts. `failure-context.ts` turns anchor failures into a `HashlineError` with bounded facts (`failures`, `matched`, `candidateNeighborhoods`); `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
22
23
 
23
24
  ## grep
@@ -26,30 +27,28 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
26
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 fixed-width assertion constraints, finite capture bindings, string expansion, and emitted patterns. Preserve every alternative, including branches outside an impossible capture. A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
27
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 by `scopeArgs` in `grep-scope.ts` and never parsed back.
28
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). `runCandidatePaths` owns clause intersection and bounded retained paths; overflowing retention falls back to one necessary clause. Byte-level pattern flags are defined once there.
29
- - 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.
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.
30
31
  - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
31
32
 
32
33
  ## Regex workers
33
34
 
34
- `regex-worker.ts` owns serialized requests, timeout, cancellation, and cleanup for grep and replace workers. Their `.mjs` bootstraps load TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using result schemas and code-specific facts from `report-schema.ts`; `replace-worker-contract.ts` owns replacement request/result shapes. Bound worker failures only in the receiving tool.
35
+ `regex-worker.ts` owns timeout, cancellation, and cleanup for grep and replace workers; each caller awaits a request before sending another to the same worker. Their `.mjs` bootstraps load TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using result schemas and code-specific facts from `report-schema.ts`; `replace-worker-contract.ts` owns the replacement request; the result schema lives with the engine in `core/replace-schema.ts`. Bound worker failures only in the receiving tool.
35
36
 
36
37
  ## Reports and rendering
37
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.
39
- - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order) and omits `tool`/`path` from success text while retaining them in `details.report` and failures. `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.
40
- - `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; `withMutationStatus` preserves both types. Failure rendering uses `details.report`; Pi raises argument errors before execution, so text-only argument rejections and forget tags decode from the final content block with `decodeReport`. Supply the originating call's tool name when decoding success text. Invalid text-only reports remain raw.
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.
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; `withMutationStatus` preserves both types. 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.
41
42
  - `report-cause.ts` transports structured causes without Pi runtime imports, preserving cause chains and aggregate branches with cycle and repeated-reference 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`.
42
43
  - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
43
44
 
44
45
  ## Budgets and config
45
46
 
46
- - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. `model-budgets.ts` caches one immutable snapshot per extension, calculated lazily and replaced when selection or capacity changes; preparation shares its provider, and each execution captures the snapshot before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
47
- - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: top-level `enabled`, `actionFusion`, `forget`, `hashLen`, `shiftRadius` control shared behavior; the `read`, `grep`, and `replace` groups hold tool-specific settings. Missing or invalid optional `read.maxKiB` selects automatic model sizing.
47
+ - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. Standalone tool factories default to its provider; internal helpers require the resolved budget or explicit byte limit. `model-budgets.ts` caches one immutable snapshot per extension, calculated lazily and replaced when selection or capacity changes; preparation shares its provider, and each execution captures the snapshot before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
48
+ - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: top-level `enabled`, `actionFusion`, `hashLen`, `shiftRadius` control shared behavior; the `read`, `grep`, and `replace` groups hold tool-specific settings. Missing or invalid optional `read.maxKiB` selects automatic model sizing.
48
49
 
49
50
  ## Action Fusion
50
51
 
51
- `action-fusion.ts` implements `then_run`. After a successful mutation it checks freshness against `publishedRevision`, then runs the command through the session Bash tool. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. Fusion states only the command (`then_run` status and output, `terminate`); freshness and publication come from the mutation report. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA`; `fusion-card.ts` validates saved command cards against its closed projection before restoring them. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
52
+ `action-fusion.ts` implements `then_run`. After a successful mutation it checks freshness against `publishedRevision`, then runs the command through the session Bash tool. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. Fusion states only the command (`then_run` status and output, `terminate`); freshness and publication come from the mutation report. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA` and retains the session command's original display content and details; `fusion-card.ts` validates saved command cards against its closed projection before restoring them. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
52
53
 
53
- ## forget
54
-
55
- `forget-tool.ts` implements `forget`, disabled by default through the `forget` setting. When enabled, read and grep tag large results with `withResultTag`, which adds the forget-owned `resultId` fact to their report; a `context` handler records the tagged results of the previous response, `forget` forgets the named ones among them and reports the rest in `notForgettable` (failing with `NOT_FORGETTABLE` only when none qualifies), since no later response can forget them, and its `turn_end` handler uses Pi's `context_edit` to replace each result's entire content with a forgotten receipt. It does not parse or classify the content; the original tool call and facts saved in `note` remain. Older results are never edited, so the next request changes only from the earliest replaced result on: later results of that batch, the response that asked, and its tool results. Tagged results also carry a display-only `forgetReceipt` in details (`readReceipt`/`grepReceipt`), which `forget` copies into its own details for the TUI card; nothing of it reaches the model.
54
+ Command cards reuse Pi's public `ToolExecutionComponent`, with the real TUI supplied by a temporary empty widget factory. History may be rebuilt before `session_start`, so retain a deferred component until the UI is bound. Cache each native component by call ID and apply global expansion only when that setting changes, so custom-entry rebuilds preserve mouse expansion. Keep spacing adaptation separate from native mouse handling and retain the built-in Bash presentation; the supported Pi API does not expose another tool's renderer.