@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,3 +1,4 @@
1
+ import { rejectsArgument } from "./argument-error.testing.ts";
1
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
2
3
  import { validateToolArguments } from "@earendil-works/pi-ai";
3
4
  import { makeEditOverride } from "./edit-tool.ts";
@@ -15,6 +16,10 @@ import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-co
15
16
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
16
17
  import { computeLineHash } from "../core/hash.ts";
17
18
  import { callTool } from "./tool-call.testing.ts";
19
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
+ import type { ActionFusionProgress } from "./action-fusion.ts";
21
+ import { reportOf } from "./report.ts";
22
+ import { expectToolFailure } from "./report-failure.testing.ts";
18
23
 
19
24
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
20
25
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
@@ -48,6 +53,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
48
53
  const grep = tools.find((tool) => tool.name === "grep");
49
54
  assert.deepEqual(Object.keys(grep.parameters.properties).sort(), [
50
55
  "context",
56
+ "flags",
51
57
  "glob",
52
58
  "ignoreCase",
53
59
  "limit",
@@ -60,13 +66,18 @@ test("mutation cards use Fusion by default and explicit false removes command su
60
66
  assert.equal(grep.parameters.additionalProperties, false);
61
67
  await assert.rejects(
62
68
  callTool(grep, { pattern: "needle", literal: true, noIgnore: false }),
63
- /Validation failed for tool "grep":\n {2}- noIgnore: schema is false/,
69
+ rejectsArgument("noIgnore", /not allowed/),
64
70
  );
65
71
  for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
66
72
  assert.ok(
67
73
  tool.parameters.properties.then_run,
68
74
  `${tool.name} should expose then_run when actionFusion is enabled`,
69
75
  );
76
+ assert.match(
77
+ tool.description,
78
+ /then_run/,
79
+ `${tool.name} description should mention then_run when actionFusion is enabled`,
80
+ );
70
81
  }
71
82
  initTheme("dark");
72
83
  const cases = [
@@ -94,33 +105,40 @@ test("mutation cards use Fusion by default and explicit false removes command su
94
105
  mutationCompleted: boolean;
95
106
  output: string;
96
107
  commandOutput: string;
108
+ expandedOutput: string;
97
109
  }[] = [];
98
- const result = await tool.execute(
99
- name,
100
- params,
101
- undefined,
102
- (update: any) => {
110
+ const result = await callTool(tool, params, {
111
+ toolCallId: name,
112
+ onUpdate: (update: AgentToolResult<{ actionFusion: ActionFusionProgress }>) => {
103
113
  card.updateResult({ ...update, isError: false }, true);
104
114
  const entry = entries.find(
105
115
  (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name,
106
116
  );
107
117
  const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
118
+ card.setExpanded(true);
119
+ const expandedOutput = card.render(100).join("\n");
120
+ card.setExpanded(false);
108
121
  frames.push({
109
122
  ...update.details.actionFusion,
110
123
  output: card.render(100).join("\n"),
111
124
  commandOutput: commandCard.render(100).join("\n"),
125
+ expandedOutput,
112
126
  });
113
127
  },
114
- { cwd: dir },
115
- );
128
+ ctx: { cwd: dir },
129
+ });
116
130
  assert.equal(result.details.actionFusion.command, "failed");
117
- assert.match(result.content[1].text, /File changes are saved|No file changes were published/);
131
+ assert.equal(
132
+ reportOf(result)?.publication,
133
+ name === "replace" ? "NOT_PUBLISHED" : "PUBLISHED",
134
+ );
135
+ assert.equal(reportOf(result)?.then_run?.status, "failed");
118
136
  assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
119
137
  const running = frames.find((frame) => frame.command === "running")!;
120
138
  assert.ok(running, `${name} should emit running progress`);
121
139
  assert.ok(
122
140
  running.output.includes(theme.getBgAnsi("toolSuccessBg")),
123
- `${name} should turn green before then_run ends`,
141
+ `${name} should finish its mutation card while then_run is running`,
124
142
  );
125
143
  assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
126
144
  assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
@@ -130,9 +148,19 @@ test("mutation cards use Fusion by default and explicit false removes command su
130
148
  )!;
131
149
  assert.ok(
132
150
  completed?.output.includes(theme.getBgAnsi("toolSuccessBg")),
133
- "mutation completion must repaint before command checks",
151
+ "mutation completion must finish its card before command checks",
134
152
  );
135
- if (name === "replace") assert.equal(running.publication, "NOT_PUBLISHED");
153
+ for (const frame of frames) {
154
+ const expectedBackground = theme.getBgAnsi(
155
+ frame.mutationCompleted ? "toolSuccessBg" : "toolPendingBg",
156
+ );
157
+ assert.ok(frame.output.includes(expectedBackground));
158
+ assert.ok(frame.expandedOutput.includes(expectedBackground));
159
+ }
160
+ if (name === "replace") {
161
+ assert.equal(running.publication, "NOT_PUBLISHED");
162
+ assert.match(running.output, /No net change/);
163
+ }
136
164
  card.updateResult({ ...result, isError: false });
137
165
  assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
138
166
  card.setExpanded(true);
@@ -158,53 +186,40 @@ test("mutation cards use Fusion by default and explicit false removes command su
158
186
  { requestRender() {} } as any,
159
187
  dir,
160
188
  );
161
- await assert.rejects(
162
- tool.execute(
163
- `${name}-bad`,
164
- invalid,
165
- undefined,
166
- (update: any) => {
167
- failedCard.updateResult({ ...update, isError: false }, true);
168
- },
169
- { cwd: dir },
170
- ),
171
- (error: Error) => {
172
- failedCard.updateResult({
173
- content: [{ type: "text", text: error.message }],
174
- isError: true,
175
- });
176
- const output = failedCard.render(100).join("\n");
177
- assert.ok(
178
- output.includes(theme.getBgAnsi("toolErrorBg")),
179
- `${name} mutation failure should turn red`,
180
- );
181
- assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
182
- failedCard.setExpanded(true);
183
- const expandedError = failedCard.render(400).join("\n");
184
- for (const line of error.message.split("\n")) {
185
- assert.ok(expandedError.includes(line), `${name} hid a failure diagnostic`);
186
- }
187
- assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
188
- const entry = entries.find(
189
- (entry) =>
190
- entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`,
191
- );
192
- const commandOutput = renderers
193
- .get(entry.customType)(entry, { expanded: true }, theme)
194
- .render(160)
195
- .join("\n");
196
- assert.match(
197
- commandOutput,
198
- /skipped[\s\S]*Not run because the mutation did not complete/,
199
- );
200
- assert.doesNotMatch(
201
- commandOutput,
202
- /Error reading|does not exist|publication=|freshness=/,
203
- );
204
- assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
205
- return true;
206
- },
189
+ const failed = await tool.execute(
190
+ `${name}-bad`,
191
+ invalid,
192
+ undefined,
193
+ (update: AgentToolResult<unknown>) =>
194
+ failedCard.updateResult({ ...update, isError: false }, true),
195
+ { cwd: dir },
196
+ );
197
+ assert.equal(failed.isError, true);
198
+ const report = reportOf(failed);
199
+ assert.equal(report?.error, "PATH_NOT_FOUND");
200
+ failedCard.updateResult(failed);
201
+ const output = failedCard.render(100).join("\n");
202
+ assert.ok(
203
+ output.includes(theme.getBgAnsi("toolErrorBg")),
204
+ `${name} mutation failure should turn red`,
205
+ );
206
+ assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
207
+ failedCard.setExpanded(true);
208
+ const expandedError = failedCard.render(400).join("\n");
209
+ assert.ok(expandedError.includes(report?.message ?? ""));
210
+ if (report?.cause?.message) assert.ok(expandedError.includes(report.cause.message));
211
+ assert.match(output, /PATH_NOT_FOUND/);
212
+ const entry = entries.find(
213
+ (entry) =>
214
+ entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`,
207
215
  );
216
+ const commandOutput = renderers
217
+ .get(entry.customType)(entry, { expanded: true }, theme)
218
+ .render(160)
219
+ .join("\n");
220
+ assert.match(commandOutput, /skipped[\s\S]*Not run.*mutation did not complete/);
221
+ assert.doesNotMatch(commandOutput, /Error reading|does not exist|publication=|freshness=/);
222
+ assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
208
223
  }
209
224
  assert.deepEqual(
210
225
  entries.map((entry) => entry.data.command),
@@ -213,7 +228,9 @@ test("mutation cards use Fusion by default and explicit false removes command su
213
228
  assert.ok(
214
229
  entries.every(
215
230
  (entry) =>
216
- !("publication" in entry.data) && !("freshness" in entry.data) && !("path" in entry.data),
231
+ !("publication" in entry.data) &&
232
+ !("path" in entry.data) &&
233
+ ["unchanged", "changed", "missing", "unknown"].includes(entry.data.freshness),
217
234
  ),
218
235
  );
219
236
  await writeFile(join(dir, "stale.txt"), "header\ntarget\n");
@@ -232,32 +249,29 @@ test("mutation cards use Fusion by default and explicit false removes command su
232
249
  { requestRender() {} } as any,
233
250
  dir,
234
251
  );
235
- await assert.rejects(
236
- edit.execute(
237
- "stale",
238
- stale,
239
- undefined,
240
- (update: any) => staleCard.updateResult({ ...update, isError: false }, true),
241
- { cwd: dir },
242
- ),
243
- (error: Error) => {
244
- assert.match(error.message, /checksum-matching candidate/);
245
- staleCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
246
- assert.match(staleCard.render(160).join("\n"), /Anchor mismatch/);
247
- const entry = entries.find(
248
- (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale",
249
- );
250
- const commandOutput = renderers
251
- .get(entry.customType)(entry, { expanded: true }, theme)
252
- .render(160)
253
- .join("\n");
254
- assert.match(commandOutput, /skipped/);
255
- assert.doesNotMatch(
256
- commandOutput,
257
- /Anchor mismatch|candidate|Input-anchor|publication=|freshness=/,
258
- );
259
- return true;
260
- },
252
+ const failed = await edit.execute(
253
+ "stale",
254
+ stale,
255
+ undefined,
256
+ (update: AgentToolResult<unknown>) =>
257
+ staleCard.updateResult({ ...update, isError: false }, true),
258
+ { cwd: dir },
259
+ );
260
+ assert.equal(failed.isError, true);
261
+ assert.equal(reportOf(failed)?.failures?.[0].result, "shifted");
262
+ staleCard.updateResult(failed);
263
+ assert.match(staleCard.render(160).join("\n"), /ANCHOR_MISMATCH/);
264
+ const entry = entries.find(
265
+ (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale",
266
+ );
267
+ const commandOutput = renderers
268
+ .get(entry.customType)(entry, { expanded: true }, theme)
269
+ .render(160)
270
+ .join("\n");
271
+ assert.match(commandOutput, /skipped/);
272
+ assert.doesNotMatch(
273
+ commandOutput,
274
+ /ANCHOR_MISMATCH|candidate|Input-anchor|publication=|freshness=/,
261
275
  );
262
276
  assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
263
277
  await writeFile(
@@ -281,6 +295,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
281
295
  )) {
282
296
  assert.equal(tool.parameters.properties.then_run, undefined);
283
297
  assert.equal(tool.renderShell, "default");
298
+ assert.doesNotMatch(tool.description, /then_run/);
284
299
  // Without Action Fusion the schema has no then_run, so Pi rejects it before execute.
285
300
  await assert.rejects(
286
301
  callTool(
@@ -288,7 +303,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
288
303
  { path: "published.txt", then_run: { command: "exit 0" } },
289
304
  { ctx: { cwd: dir } },
290
305
  ),
291
- /Validation failed for tool "(edit|replace|write)":[\s\S]*- then_run: schema is false/,
306
+ rejectsArgument("then_run", /not allowed/),
292
307
  );
293
308
  }
294
309
  } finally {
@@ -354,9 +369,9 @@ test("loaded configuration controls hash length and recovery radius", async () =
354
369
  await mkdir(join(dir, ".pi"));
355
370
  await writeFile(join(dir, "configured.txt"), text);
356
371
  for (const [hashLen, shiftRadius, expected] of [
357
- [6, 0, /no checksum-matching candidate found/],
358
- [6, 1, /checksum-matching candidate 2#/],
359
- [8, 3, /ambiguous checksum matches/],
372
+ [6, 0, "unresolved"],
373
+ [6, 1, "shifted"],
374
+ [8, 3, "ambiguous"],
360
375
  ] as const) {
361
376
  await writeFile(
362
377
  join(dir, ".pi", "settings.json"),
@@ -365,12 +380,16 @@ test("loaded configuration controls hash length and recovery radius", async () =
365
380
  const config = loadConfig(dir);
366
381
  const read = await call(makeReadOverride(dir, config), { path: "configured.txt" });
367
382
  assert.equal(anchorLine(read.content[0].text, 1).split("#")[1].length, hashLen);
368
- await assert.rejects(
383
+ await expectToolFailure(
369
384
  call(makeEditOverride(dir, config), {
370
385
  path: "configured.txt",
371
386
  edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
372
387
  }),
373
- expected,
388
+ "ANCHOR_MISMATCH",
389
+ (report) => {
390
+ assert.equal(report.failures?.[0].result, expected);
391
+ if (expected === "shifted") assert.match(report.failures?.[0].candidate ?? "", /^2#/);
392
+ },
374
393
  );
375
394
  assert.equal(await readFile(join(dir, "configured.txt"), "utf8"), text);
376
395
  }
@@ -388,7 +407,7 @@ test("configured read defaults bound omitted limits and returned bytes", async (
388
407
  await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
389
408
  const paged = await call(read, { path: "short.txt" });
390
409
  assert.deepEqual(paged.details.pagination, { start: 1, end: 2, totalLines: 3, nextOffset: 3 });
391
- assert.match(paged.content[0].text, /offset 3/);
410
+ assert.match(reportOf(paged)?.next ?? "", /offset.*pagination\.nextOffset/);
392
411
  assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
393
412
  assert.doesNotMatch(paged.content[0].text, /^3#/m);
394
413
  const explicit = await call(read, { path: "short.txt", limit: 3 });
@@ -1,5 +1,11 @@
1
+ import { argumentError } from "./argument-error.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { readFile, unlink, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
+ import { visibleWidth } from "@earendil-works/pi-tui";
3
9
  import {
4
10
  generateDiffString,
5
11
  initTheme,
@@ -14,16 +20,30 @@ import { renderDiffPreview } from "./render.ts";
14
20
  import { withMutationStatus } from "./fusion-card.ts";
15
21
  import { makeWriteOverride } from "./write-tool.ts";
16
22
  import { generateMutationDetails } from "./mutation-result.ts";
17
- import type { ActionFusionDetails } from "./action-fusion.ts";
23
+ import {
24
+ createActionFusionExecutor,
25
+ type ActionFusionDetails,
26
+ type ActionFusionProgress,
27
+ } from "./action-fusion.ts";
18
28
  import { DEFAULT_CONFIG } from "./config.ts";
19
29
  import { toDisplayLines } from "./grep-render.ts";
20
30
  import { makeReadOverride } from "./read-tool.ts";
21
31
  import { callTool } from "./tool-call.testing.ts";
22
32
  import { renderToolError } from "./render.ts";
33
+ import { formatArgumentError } from "./argument-error.ts";
34
+ import { makeGrepOverride } from "./grep-tool.ts";
35
+ import { registerForgetTool } from "./forget-tool.ts";
36
+ import { openTestSession } from "../testing/session.testing.ts";
23
37
 
24
38
  const versions = { publishedRevision: "r", observedRevision: "r" };
25
39
  const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
26
- ...generateMutationDetails("a.txt", "same\n", "same\n", versions, "PUBLISHED"),
40
+ ...generateMutationDetails("a.txt", "old\n", "new\n", versions, "PUBLISHED"),
41
+ report: {
42
+ tool: "edit" as const,
43
+ path: "a.txt",
44
+ publication: actionFusion?.publication,
45
+ freshness: actionFusion?.freshness === "unchanged" ? undefined : actionFusion?.freshness,
46
+ },
27
47
  actionFusion,
28
48
  });
29
49
 
@@ -77,6 +97,8 @@ test("edit call titles count each operation type and refresh with partial input"
77
97
  { op: "insert_before", anchor: "7#GH", body: ["before"] },
78
98
  { op: "insert_after", anchor: "9#JK", body: ["after"] },
79
99
  { op: "prepend", body: ["first"] },
100
+ { op: "copy", anchor: "1#AB", before: "3#CD" },
101
+ { op: "move", anchor: "3#CD", after: "5#EF" },
80
102
  ];
81
103
  let header: ReturnType<typeof tool.renderCall> | undefined;
82
104
  const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
@@ -91,10 +113,12 @@ test("edit call titles count each operation type and refresh with partial input"
91
113
  };
92
114
  assert.match(render([edits[0], {}]), /unknown ×1/);
93
115
  const mixed = render(edits);
94
- assert.match(mixed, /7 ops:/);
116
+ assert.match(mixed, /9 ops:/);
95
117
  for (const [kind, count] of [
96
118
  ["replace", 2],
97
119
  ["delete", 1],
120
+ ["copy", 1],
121
+ ["move", 1],
98
122
  ["insert_before", 1],
99
123
  ["insert_after", 1],
100
124
  ["append", 1],
@@ -105,7 +129,7 @@ test("edit call titles count each operation type and refresh with partial input"
105
129
  assert.doesNotMatch(mixed, /unknown/);
106
130
  const single = render([edits[0]]);
107
131
  assert.match(single, /1 op: replace ×1/);
108
- assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
132
+ assert.doesNotMatch(single, /append|copy|delete|insert_before|insert_after|move|prepend/);
109
133
  assert.match(
110
134
  render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
111
135
  /4 ops: unknown ×4/,
@@ -138,9 +162,9 @@ test("mutation card owns stale-anchor notices without internal status", () => {
138
162
  context,
139
163
  );
140
164
  const output = card.render(160).join("\n");
141
- assert.match(output, /Edit saved/);
165
+ assert.match(output, /new/);
142
166
  assert.doesNotMatch(output, /publication=|freshness=/);
143
- assert.match(output, /Anchors are stale: target changed/);
167
+ assert.match(stripVTControlCharacters(output), /freshness: changed/);
144
168
  assert.doesNotMatch(output, /command diagnostic/);
145
169
  assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
146
170
  });
@@ -165,7 +189,7 @@ test("mutation card omits status when then_run was not requested", () => {
165
189
  context,
166
190
  );
167
191
  const output = card.render(160).join("\n");
168
- assert.match(output, /Edited a\.txt/);
192
+ assert.match(output, /new/);
169
193
  assert.doesNotMatch(output, /publication=|freshness=/);
170
194
  tool.renderCall!(args, theme, context);
171
195
  tool.renderResult!(
@@ -182,7 +206,7 @@ test("mutation card omits status when then_run was not requested", () => {
182
206
  context,
183
207
  );
184
208
  const staleOutput = card.render(160).join("\n");
185
- assert.match(staleOutput, /Anchors are stale: target changed/);
209
+ assert.match(stripVTControlCharacters(staleOutput), /freshness: changed/);
186
210
  assert.doesNotMatch(staleOutput, /publication=|freshness=/);
187
211
  });
188
212
 
@@ -294,8 +318,6 @@ test("withMutationStatus renderResult initializes mutationShell defensively", ()
294
318
 
295
319
  test("grep renders anchored and plain groups with shared width and folded indentation", () => {
296
320
  initTheme("dark");
297
- const notice =
298
- "[Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors]";
299
321
  const raw = [
300
322
  "valid.ts · 2 matches",
301
323
  "9#ABCD│ alpha",
@@ -304,7 +326,6 @@ test("grep renders anchored and plain groups with shared width and folded indent
304
326
  "invalid.txt · 2 matches",
305
327
  "100│\tbad �",
306
328
  "7│\t\tother",
307
- notice,
308
329
  ].join("\n");
309
330
  assert.deepEqual(toDisplayLines(raw, theme), [
310
331
  theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
@@ -314,7 +335,6 @@ test("grep renders anchored and plain groups with shared width and folded indent
314
335
  theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
315
336
  theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
316
337
  theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
317
- theme.fg("warning", notice),
318
338
  ]);
319
339
  });
320
340
 
@@ -328,14 +348,24 @@ test("grep renders plain and anchored rows in one group without exposing hashes"
328
348
  ]);
329
349
  });
330
350
 
331
- test("all file tools expose validation causes in collapsed and expanded error cards", async () => {
351
+ test("all tools render argument issues as field diagnostics while preserving model JSON", async (t) => {
332
352
  initTheme("dark");
333
353
  const cwd = process.cwd();
354
+ const { session } = await openTestSession(t, {
355
+ tools: ["forget"],
356
+ configure(pi) {
357
+ registerForgetTool(pi);
358
+ },
359
+ });
360
+ const forget = session.getToolDefinition("forget");
361
+ assert.ok(forget);
334
362
  const tools = [
335
363
  makeReadOverride(cwd, DEFAULT_CONFIG),
336
364
  withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
337
365
  withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
338
366
  withMutationStatus(makeWriteOverride(cwd)),
367
+ makeGrepOverride(cwd, DEFAULT_CONFIG),
368
+ forget,
339
369
  ];
340
370
  for (const tool of tools) {
341
371
  for (const fused of [false, true]) {
@@ -345,6 +375,9 @@ test("all file tools expose validation causes in collapsed and expanded error ca
345
375
  mode: "create" as const,
346
376
  edits: [{ op: "append" as const, body: ["unused"] }],
347
377
  replacements: [{ find: "unused", replace: "unused" }],
378
+ pattern: "unused",
379
+ literal: true,
380
+ ids: ["r00000"],
348
381
  unexpected: true,
349
382
  ...(fused ? { then_run: { command: "must-not-run" } } : {}),
350
383
  };
@@ -354,8 +387,8 @@ test("all file tools expose validation causes in collapsed and expanded error ca
354
387
  errorText = error.message;
355
388
  return true;
356
389
  });
357
- const cause = errorText.split("\n").find((line) => line.includes("unexpected"));
358
- assert.ok(cause);
390
+ const issues = argumentError(new Error(errorText)).issues;
391
+ assert.ok(issues.length > 0);
359
392
  for (const expanded of [false, true]) {
360
393
  const context = {
361
394
  args,
@@ -384,10 +417,18 @@ test("all file tools expose validation causes in collapsed and expanded error ca
384
417
  );
385
418
  const card = tool.renderShell === "self" ? call : result;
386
419
  assert.ok(card);
387
- assert.ok(
388
- card.render(200).join("\n").includes(cause),
389
- `${tool.name} hid the validation cause`,
390
- );
420
+ const displayed = stripVTControlCharacters(card.render(200).join("\n"));
421
+ assert.match(displayed, /Invalid arguments/);
422
+ assert.ok(displayed.includes(`${tool.name} not executed`));
423
+ assert.doesNotMatch(displayed, /"error":|"issues":|"field":|"reason":/);
424
+ assert.deepEqual(argumentError(new Error(errorText)).issues, issues);
425
+ for (const value of [issues[0].field, issues[0].reason]) {
426
+ assert.ok(displayed.includes(value), `${tool.name} hid the first validation issue`);
427
+ }
428
+ if (expanded) {
429
+ assert.match(displayed, /unexpected: is not allowed/);
430
+ assert.doesNotMatch(displayed, /Prepared arguments/);
431
+ }
391
432
  }
392
433
  }
393
434
  }
@@ -409,3 +450,136 @@ test("expanded errors retain every text block while collapsed errors stay bounde
409
450
  assert.match(expanded, /Final cause: permission denied/);
410
451
  assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
411
452
  });
453
+
454
+ test("argument cards preserve omission notices and all expanded issues", () => {
455
+ initTheme("dark");
456
+ const issues = Array.from({ length: 200 }, (_, index) => ({
457
+ field: `edits[${index}].body`,
458
+ reason: `中文🙂 ${index}: supply a line.\n${"context ".repeat(50)}\nFinal cause: empty body.`,
459
+ }));
460
+ const diagnostic = formatArgumentError("edit", issues, true);
461
+ const parsed = argumentError(new Error(diagnostic));
462
+ assert.ok(parsed.schemaLimited && parsed.omittedIssues);
463
+ const result = {
464
+ content: [{ type: "text" as const, text: diagnostic }],
465
+ };
466
+ const original = structuredClone(result);
467
+ const collapsed = stripVTControlCharacters(
468
+ renderToolError(result, theme, false).render(100).join("\n"),
469
+ );
470
+ const expanded = stripVTControlCharacters(
471
+ renderToolError(result, theme, true).render(100).join("\n"),
472
+ );
473
+ for (const displayed of [collapsed, expanded]) {
474
+ assert.match(displayed, /Schema diagnostic limit/);
475
+ assert.ok(displayed.includes(`${parsed.omittedIssues} issues omitted`));
476
+ assert.doesNotMatch(displayed, /"error":|"issues":/);
477
+ }
478
+ for (const issue of parsed.issues) assert.ok(expanded.includes(issue.field));
479
+ assert.match(expanded, /Final cause: empty body/);
480
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
481
+ assert.deepEqual(result, original);
482
+ });
483
+
484
+ test("unrecognized or malformed JSON errors retain their original diagnostic", () => {
485
+ initTheme("dark");
486
+ for (const diagnostic of [
487
+ "",
488
+ '{"error":"OTHER_ERROR","cause":"permission denied"}',
489
+ '{"error":"INVALID_ARGUMENTS","executed":true,"issues":[]}',
490
+ '{"error":"INVALID_ARGUMENTS","tool":"edit","executed":false,"issues":[{"field":"path","reason":null}]}',
491
+ '{"error":"INVALID_ARGUMENTS",',
492
+ "Filesystem failure: permission denied",
493
+ ]) {
494
+ const result = { content: [{ type: "text" as const, text: diagnostic }] };
495
+ const displayed = stripVTControlCharacters(
496
+ renderToolError(result, theme, true).render(300).join("\n"),
497
+ );
498
+ assert.ok(displayed.includes(diagnostic || "Error"));
499
+ }
500
+ });
501
+
502
+ test("argument diagnostics wrap Unicode and multiline reasons at narrow terminal widths", () => {
503
+ const field = "edits[0].body";
504
+ const reason = '中文🙂: supply at least one line.\nUse ["空行"] for this example.';
505
+ const diagnostic = formatArgumentError("edit", [{ field, reason }], false);
506
+ const result = { content: [{ type: "text" as const, text: diagnostic }] };
507
+ for (const appearance of ["dark", "light"] as const) {
508
+ initTheme(appearance);
509
+ for (const width of [24, 80]) {
510
+ for (const expanded of [false, true]) {
511
+ const lines = renderToolError(result, theme, expanded).render(width);
512
+ assert.ok(lines.every((line) => visibleWidth(line) <= width));
513
+ const displayed = stripVTControlCharacters(lines.join("\n")).replace(/\s/g, "");
514
+ for (const value of [field, reason, "edit not executed"]) {
515
+ assert.ok(displayed.includes(value.replace(/\s/g, "")));
516
+ }
517
+ }
518
+ }
519
+ }
520
+ initTheme("dark");
521
+ });
522
+
523
+ test("command changes or removes the target → completed mutation stays successful with a freshness warning", async (t) => {
524
+ initTheme("dark");
525
+ const { cwd, session } = await openTestSession(t, { tools: [] });
526
+ for (const disturbance of ["changed", "missing"] as const) {
527
+ const path = `${disturbance}.txt`;
528
+ const target = join(cwd, path);
529
+ const fusion = createActionFusionExecutor(async () => {
530
+ assert.equal(await readFile(target, "utf8"), "saved\n");
531
+ if (disturbance === "changed") await writeFile(target, "command changed the file\n");
532
+ else await unlink(target);
533
+ return { status: "succeeded", output: "checked" };
534
+ });
535
+ const tool = withMutationStatus(makeWriteOverride(cwd, fusion));
536
+ const args = {
537
+ path,
538
+ mode: "create" as const,
539
+ content: "saved\n",
540
+ then_run: { command: "check target" },
541
+ };
542
+ const context: Parameters<NonNullable<typeof tool.renderCall>>[2] = {
543
+ args,
544
+ toolCallId: disturbance,
545
+ cwd,
546
+ state: {},
547
+ lastComponent: undefined,
548
+ invalidate() {},
549
+ executionStarted: true,
550
+ argsComplete: true,
551
+ isPartial: true,
552
+ expanded: false,
553
+ showImages: false,
554
+ isError: false,
555
+ };
556
+ const card = tool.renderCall!(args, theme, context);
557
+ // Pi erases result types for rendering; initial progress has no commit fields yet.
558
+ const renderResult = tool.renderResult as NonNullable<
559
+ ToolDefinition<TSchema, unknown>["renderResult"]
560
+ >;
561
+ const completedFrames: string[] = [];
562
+ const result = await callTool(tool, args, {
563
+ toolCallId: disturbance,
564
+ ctx: session.extensionRunner.createToolContext(disturbance, undefined),
565
+ onUpdate: (update: AgentToolResult<{ actionFusion: ActionFusionProgress }>) => {
566
+ tool.renderCall!(args, theme, context);
567
+ renderResult(update, { isPartial: true, expanded: false }, theme, context);
568
+ if (update.details.actionFusion.mutationCompleted)
569
+ completedFrames.push(card.render(160).join("\n"));
570
+ },
571
+ });
572
+ assert.ok(completedFrames.length > 0);
573
+ assert.ok(completedFrames.every((frame) => frame.includes(theme.getBgAnsi("toolSuccessBg"))));
574
+ assert.equal(result.details.actionFusion.freshness, disturbance);
575
+ context.isPartial = false;
576
+ tool.renderCall!(args, theme, context);
577
+ renderResult(result, { isPartial: false, expanded: false }, theme, context);
578
+ const output = card.render(160).join("\n");
579
+ assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
580
+ assert.match(stripVTControlCharacters(output), new RegExp(`freshness: ${disturbance}`));
581
+ if (disturbance === "changed")
582
+ assert.equal(await readFile(target, "utf8"), "command changed the file\n");
583
+ else await assert.rejects(readFile(target), { code: "ENOENT" });
584
+ }
585
+ });