@criogaid/pi-hashline-edit 0.6.1 → 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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,3 +1,4 @@
1
+ import { argumentError, rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
1
2
  /** Tool-level edit and shared mutation workflow tests. */
2
3
  import { test } from "node:test";
3
4
  import assert from "node:assert/strict";
@@ -14,10 +15,12 @@ import { makeReplaceTool } from "./replace-tool.ts";
14
15
  import { createActionFusionExecutor } from "./action-fusion.ts";
15
16
  import { computeLineHash } from "../core/hash.ts";
16
17
  import { splitLines } from "../core/lines.ts";
17
- import { byteRevision } from "./file-commit.ts";
18
18
  import { callTool } from "./tool-call.testing.ts";
19
19
  import { DEFAULT_CONFIG } from "./config.ts";
20
- import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
20
+ import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
21
+ import { detailsReport, reportOf } from "./report.ts";
22
+ import type { Report } from "./report-schema.ts";
23
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
21
24
 
22
25
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
23
26
  const dir = await mkdtemp(join(tmpdir(), "hl-"));
@@ -43,6 +46,26 @@ function anchorLine(block: string, line: number) {
43
46
  return `${line}#${m[1]}`;
44
47
  }
45
48
 
49
+ function failureReport(result: AgentToolResult<unknown> & { isError?: boolean }): Report {
50
+ assert.equal(result.isError, true);
51
+ const report = detailsReport(result.details);
52
+ assert.ok(report?.error);
53
+ return report;
54
+ }
55
+
56
+ test("edit guidance → refreshes anchors after content changes and line shifts", () => {
57
+ const guidance = makeEditOverride(process.cwd(), DEFAULT_CONFIG).promptGuidelines.join("\n");
58
+ assert.match(guidance, /after edit or replace.*before citing any line it changed/i);
59
+ assert.match(
60
+ guidance,
61
+ /added or removed lines.*refresh anchors below the earliest affected line/i,
62
+ );
63
+ assert.match(
64
+ guidance,
65
+ /affected positions are unknown.*read or grep the lines you intend to cite/i,
66
+ );
67
+ });
68
+
46
69
  test("edit execute: a file without a final newline stays byte-exact", async () => {
47
70
  await withDir(async (dir) => {
48
71
  const f = join(dir, "f.txt");
@@ -66,10 +89,10 @@ test("edit execute: hashline round-trip (read → edit → file changed)", async
66
89
  const f = join(dir, "f.txt");
67
90
  const text = "a\nb\nc\n";
68
91
  await writeFile(f, text);
69
- await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
92
+ const read = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
70
93
  const r: any = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
71
94
  path: "f.txt",
72
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
95
+ edits: [{ op: "replace", anchor: anchorLine(read.content[0].text, 2), body: ["B"] }],
73
96
  });
74
97
  assert.equal(r.isError, undefined, "should not be an error");
75
98
  assert.equal(await readFile(f, "utf-8"), "a\nB\nc\n");
@@ -94,52 +117,66 @@ test("edit execute: multiple ops in one call", async () => {
94
117
  });
95
118
  });
96
119
 
97
- test("edit result returns Updated anchors that chain the next edit without a re-read", async () => {
98
- await withDir(async (dir) => {
99
- const f = join(dir, "f.txt");
100
- const text = "a\nb\nc\n";
101
- await writeFile(f, text);
102
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
103
- // first edit (model cites the read anchor for line 1)
104
- const r1: any = await call(edit, {
105
- path: "f.txt",
106
- edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
107
- });
108
- assert.equal(r1.isError, undefined);
109
- const out: string = r1.content[0].text;
110
- assert.match(out, /Updated anchors/);
111
- assert.doesNotMatch(out, /│/);
112
- // second edit chains on the anchor returned by the first edit — no read in between
113
- const r2: any = await call(edit, {
114
- path: "f.txt",
115
- edits: [{ op: "replace", anchor: anchorLine(out, 1), body: ["AA"] }],
116
- });
117
- assert.equal(r2.isError, undefined);
118
- assert.equal(await readFile(f, "utf-8"), "AA\nb\nc\n");
119
- });
120
- });
121
-
122
- test("edit result anchors cover an inserted block (chain an edit inside it)", async () => {
123
- await withDir(async (dir) => {
124
- const f = join(dir, "f.txt");
125
- const text = "a\nb\n";
126
- await writeFile(f, text);
127
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
128
- const r1: any = await call(edit, {
129
- path: "f.txt",
130
- edits: [{ op: "insert_after", anchor: h(text, 2), body: ["c", "d", "e"] }],
131
- });
132
- assert.equal(r1.isError, undefined);
133
- const out: string = r1.content[0].text;
134
- // line 4 (d, one of the inserted lines) must be anchored in the result
135
- const a4 = anchorLine(out, 4);
136
- const r2: any = await call(edit, {
137
- path: "f.txt",
138
- edits: [{ op: "replace", anchor: a4, body: ["DD"] }],
139
- });
140
- assert.equal(r2.isError, undefined);
141
- assert.equal(await readFile(f, "utf-8"), "a\nb\nc\nDD\ne\n");
142
- });
120
+ test("successful mutation → returns one report without anchor payload", async (t) => {
121
+ for (const tool of ["edit", "replace", "write"] as const) {
122
+ for (const count of [1, 3000]) {
123
+ await t.test(`${tool}: ${count} changed lines`, async () =>
124
+ withDir(async (dir) => {
125
+ const path = "f.txt";
126
+ const before = "old\n".repeat(count);
127
+ const after = "new\n".repeat(count);
128
+ await writeFile(join(dir, path), before);
129
+ const inspection = await callTool(makeReadOverride(dir, DEFAULT_CONFIG), {
130
+ path,
131
+ limit: count,
132
+ });
133
+ assert.equal(inspection.content[0].type, "text");
134
+ const rows = inspection.content[0].text;
135
+ const fixture =
136
+ tool === "edit"
137
+ ? {
138
+ instance: makeEditOverride(dir, DEFAULT_CONFIG),
139
+ params: {
140
+ path,
141
+ edits: [
142
+ {
143
+ op: "replace",
144
+ anchor: anchorLine(rows, 1),
145
+ end: anchorLine(rows, count),
146
+ body: Array.from({ length: count }, () => "new"),
147
+ },
148
+ ],
149
+ },
150
+ }
151
+ : tool === "replace"
152
+ ? {
153
+ instance: makeReplaceTool(dir, DEFAULT_CONFIG),
154
+ params: {
155
+ path,
156
+ replacements: [{ literal: true, find: "old", replace: "new" }],
157
+ },
158
+ }
159
+ : {
160
+ instance: makeWriteOverride(dir),
161
+ params: { path, mode: "overwrite", content: after },
162
+ };
163
+ const result = await callTool(fixture.instance, fixture.params);
164
+ assert.equal(result.isError, undefined);
165
+ assert.equal(await readFile(join(dir, path), "utf8"), after);
166
+ assert.equal(result.content.length, 1);
167
+ assert.equal(result.content[0].type, "text");
168
+ assert.deepEqual(JSON.parse(result.content[0].text), {
169
+ publication: "PUBLISHED",
170
+ ...(tool === "replace" ? { matches: count } : {}),
171
+ });
172
+ if (tool !== "write") {
173
+ assert.ok("diff" in result.details && typeof result.details.diff === "string");
174
+ assert.match(result.details.diff, /new/);
175
+ } else assert.deepEqual(result.details, { report: reportOf(result, "write") });
176
+ }),
177
+ );
178
+ }
179
+ }
143
180
  });
144
181
 
145
182
  test("unrelated external change does NOT block an edit on a stable line", async () => {
@@ -164,13 +201,14 @@ test("edit on a line that changed externally → anchor mismatch", async () => {
164
201
  const text = "a\nb\nc\n";
165
202
  await writeFile(f, text);
166
203
  await writeFile(f, "a\nBCHANGED\nc\n"); // line 2 changed
167
- await assert.rejects(
168
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
204
+ const report = failureReport(
205
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
169
206
  path: "f.txt",
170
207
  edits: [{ op: "replace", anchor: h(text, 2), body: ["x"] }],
171
208
  }),
172
- /anchor|re-read/i,
173
209
  );
210
+ assert.equal(report.error, "ANCHOR_MISMATCH");
211
+ assert.equal(await readFile(f, "utf8"), "a\nBCHANGED\nc\n");
174
212
  });
175
213
  });
176
214
 
@@ -184,19 +222,16 @@ test("unresolved observations require target confirmation before retrying a move
184
222
  ["one", "two", "three", "four", "changed", "six", "new marker", "eight"].join("\n") + "\n",
185
223
  );
186
224
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
187
- await assert.rejects(
188
- call(edit, {
225
+ const report = failureReport(
226
+ await call(edit, {
189
227
  path: "recover.txt",
190
228
  edits: [{ op: "replace", anchor: h(observed, 5), body: ["updated"] }],
191
229
  }),
192
- (error: Error) => {
193
- assert.match(error.message, /Anchor mismatch: 1 unresolved/);
194
- assert.match(error.message, /No changes written/);
195
- assert.match(error.message, /Confirm.*target.*before.*anchor/);
196
- assert.match(error.message, /^5#[0-9A-Z]+│changed$/m);
197
- return true;
198
- },
199
230
  );
231
+ assert.equal(report.error, "ANCHOR_MISMATCH");
232
+ assert.equal(report.publication, "NOT_PUBLISHED");
233
+ assert.match(report.next ?? "", /Before reusing.*anchor, confirm.*intended target/);
234
+ assert.match(report.failures?.[0].observed ?? "", /^5#[0-9A-Z]+│changed$/);
200
235
  const read = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "recover.txt" });
201
236
  const retryAnchor = anchorLine(read.content[0].text, 7);
202
237
  await call(edit, {
@@ -213,36 +248,14 @@ test("unresolved observations require target confirmation before retrying a move
213
248
  test("edit execute: no read before edit → anchor verification fails", async () => {
214
249
  await withDir(async (dir) => {
215
250
  await writeFile(join(dir, "f.txt"), "a\nb\n");
216
- await assert.rejects(
217
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
251
+ const report = failureReport(
252
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
218
253
  path: "f.txt",
219
254
  edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
220
255
  }),
221
- /anchor|re-read/i,
222
- );
223
- });
224
- });
225
-
226
- test("edit execute: empty edits → throws", async () => {
227
- await withDir(async (dir) => {
228
- await writeFile(join(dir, "f.txt"), "a\n");
229
- await assert.rejects(
230
- call(makeEditOverride(dir, DEFAULT_CONFIG), { path: "f.txt", edits: [] }),
231
- /Validation failed for tool "edit"/,
232
- );
233
- });
234
- });
235
-
236
- test("edit execute: malformed op (replace without body) → throws", async () => {
237
- await withDir(async (dir) => {
238
- await writeFile(join(dir, "f.txt"), "a\n");
239
- await assert.rejects(
240
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
241
- path: "f.txt",
242
- edits: [{ op: "replace", anchor: "1#XXXX" }],
243
- }),
244
- /body/i,
245
256
  );
257
+ assert.equal(report.error, "ANCHOR_MISMATCH");
258
+ assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "a\nb\n");
246
259
  });
247
260
  });
248
261
 
@@ -261,30 +274,12 @@ test("edit execute: delete op", async () => {
261
274
  });
262
275
  });
263
276
 
264
- // --- renderer regression guards (details.diff must be a string, renderResult must not throw) ---
265
-
266
277
  const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
267
278
 
268
279
  // renderResult delegates to pi's renderDiff, which reads the global TUI theme
269
280
  // singleton — initialize it once for this test process (watcher off by default).
270
281
  initTheme();
271
282
 
272
- test("edit success: details.diff is a string (not the generateDiffString object)", async () => {
273
- await withDir(async (dir) => {
274
- const f = join(dir, "f.txt");
275
- const text = "a\nb\nc\n";
276
- await writeFile(f, text);
277
- await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
278
- const r: any = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
279
- path: "f.txt",
280
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
281
- });
282
- assert.equal(typeof r.details.diff, "string", "details.diff must be a string");
283
- assert.equal(typeof r.details.patch, "string");
284
- assert.equal(typeof r.details.firstChangedLine, "number");
285
- });
286
- });
287
-
288
283
  test("native read and write renderers preserve resource titles, previews, and full errors", async () =>
289
284
  withDir(async (dir) => {
290
285
  const context = {
@@ -311,13 +306,7 @@ test("native read and write renderers preserve resource titles, previews, and fu
311
306
  const error = write.renderResult(
312
307
  {
313
308
  content: [{ type: "text", text: "first error\nsecond error" }],
314
- details: {
315
- path: "preview.txt",
316
- created: false,
317
- publication: "NOT_PUBLISHED",
318
- publishedRevision: "r",
319
- observedRevision: "r",
320
- },
309
+ details: {},
321
310
  },
322
311
  { isPartial: false, expanded: false },
323
312
  stubTheme,
@@ -336,16 +325,16 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
336
325
  path: "range.txt",
337
326
  edits: [{ op: "replace", anchor, endd: h(original, 3), body: ["merged"] }],
338
327
  };
339
- await assert.rejects(call(edit, callArgs), /edits\.0\.endd: schema is false/);
328
+ await assert.rejects(call(edit, callArgs), rejectsArgument("edits[0].endd", /not allowed/));
340
329
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
341
- for (const edits of [
342
- [],
343
- [{ op: "replace", anchor }],
344
- [{ op: "delete", anchor, body: ["bad"] }],
345
- [{ op: "insert_after", body: ["bad"] }],
346
- [{ op: "append", anchor, body: ["bad"] }],
347
- ]) {
348
- await assert.rejects(call(edit, { path: "range.txt", edits }), /Validation failed/);
330
+ for (const [edits, expected] of [
331
+ [[], rejectsArgument("edits")],
332
+ [[{ op: "replace", anchor }], rejectsArgument("edits[0].body", /required/)],
333
+ [[{ op: "delete", anchor, body: ["bad"] }], rejectsArguments()],
334
+ [[{ op: "insert_after", body: ["bad"] }], rejectsArguments()],
335
+ [[{ op: "append", anchor, body: ["bad"] }], rejectsArguments()],
336
+ ] as const) {
337
+ await assert.rejects(call(edit, { path: "range.txt", edits }), expected);
349
338
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
350
339
  }
351
340
  const alternates: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
@@ -353,9 +342,13 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
353
342
  { path: "range.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["ok"] }]) },
354
343
  ];
355
344
  for (const alternate of alternates) {
356
- await assert.rejects(call(edit, alternate), /Validation failed/);
345
+ const before = structuredClone(alternate);
346
+ await assert.rejects(call(edit, alternate), rejectsArguments());
347
+ assert.deepEqual(alternate, before);
357
348
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
358
349
  }
350
+ await call(edit, { path: "range.txt", edits: [{ op: "replace", anchor, body: ["B"] }] });
351
+ assert.equal(await readFile(join(dir, "range.txt"), "utf8"), "a\nB\nc\n");
359
352
  }));
360
353
 
361
354
  test("copied string anchors validate and replace an inclusive range", async () =>
@@ -402,7 +395,7 @@ test("invalid anchors and conflicting fields fail before changing the file", asy
402
395
  for (const operation of invalid) {
403
396
  await assert.rejects(
404
397
  call(edit, { path: "invalid.txt", edits: [operation] }),
405
- /Invalid argument|Invalid anchor|Validation failed for tool "edit"/,
398
+ /INVALID_ARGUMENTS|Invalid anchor/,
406
399
  );
407
400
  assert.equal(await readFile(join(dir, "invalid.txt"), "utf8"), original);
408
401
  }
@@ -424,7 +417,10 @@ test("edit rejects empty bodies before file access for arrays and Pi-converted o
424
417
  ]) {
425
418
  for (const path of [file, join(dir, "missing.txt")]) {
426
419
  for (const edits of [[operation], operation]) {
427
- await assert.rejects(call(edit, { path, edits }), /edits\[0\]\.body: is empty/);
420
+ await assert.rejects(
421
+ call(edit, { path, edits }),
422
+ rejectsArgument("edits[0].body", /empty/),
423
+ );
428
424
  assert.equal(await readFile(file, "utf8"), original);
429
425
  }
430
426
  }
@@ -439,7 +435,7 @@ test("mixed empty-body batches name every rejected edit without publishing or ru
439
435
  let commandRuns = 0;
440
436
  const fusion = createActionFusionExecutor(async () => {
441
437
  commandRuns++;
442
- return { status: "succeeded", output: "ran" };
438
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
443
439
  });
444
440
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
445
441
  await assert.rejects(
@@ -458,8 +454,9 @@ test("mixed empty-body batches name every rejected edit without publishing or ru
458
454
  { ctx: { cwd: dir } },
459
455
  ),
460
456
  (error: Error) => {
461
- assert.match(error.message, /edits\[1\]\.body:.*\[""\]/);
462
- assert.match(error.message, /edits\[3\]\.body:.*delete/);
457
+ const issues = argumentError(error).issues;
458
+ assert.match(issues.find((issue) => issue.field === "edits[1].body")?.fix ?? "", /\[""\]/);
459
+ assert.match(issues.find((issue) => issue.field === "edits[3].body")?.fix ?? "", /delete/);
463
460
  return true;
464
461
  },
465
462
  );
@@ -486,17 +483,16 @@ test("blank edit bodies preserve a real blank line for every body-bearing operat
486
483
  }
487
484
  }));
488
485
 
489
- test("explicit delete removes an inclusive range and returns its successor anchor", async () =>
486
+ test("explicit delete → removes an inclusive range", async () =>
490
487
  withDir(async (dir) => {
491
488
  const original = "a\nb\nc\n";
492
489
  const file = join(dir, "delete_range.txt");
493
490
  await writeFile(file, original);
494
- const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
491
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
495
492
  path: file,
496
493
  edits: [{ op: "delete", anchor: h(original, 1), end: h(original, 2) }],
497
494
  });
498
495
  assert.equal(await readFile(file, "utf8"), "c\n");
499
- assert.match(result.content[0].text, /1#[0-9A-Z]+│c/);
500
496
  }));
501
497
 
502
498
  test("local and full-file recovery return copyable anchors without changing the rejected batch", async () =>
@@ -507,28 +503,20 @@ test("local and full-file recovery return copyable anchors without changing the
507
503
  const prefix = "prefix\n".repeat(prefixLines);
508
504
  await writeFile(join(dir, "shift.txt"), prefix + original);
509
505
  let replacement = "";
510
- await assert.rejects(
511
- call(edit, {
506
+ const report = failureReport(
507
+ await call(edit, {
512
508
  path: "shift.txt",
513
509
  edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
514
510
  }),
515
- (error: Error) => {
516
- replacement =
517
- new RegExp(`^(${prefixLines + 2}#[0-9A-Z]+)│b$`, "m").exec(error.message)?.[1] ?? "";
518
- assert.match(error.message, /Check the intended target/);
519
- assert.match(
520
- error.message,
521
- prefixLines === 1 ? /Search: local.*outside.*not checked/ : /Search: full file/,
522
- );
523
- assert.doesNotMatch(
524
- error.message,
525
- prefixLines === 1 ? /Search: full file/ : /Search: local/,
526
- );
527
- assert.doesNotMatch(error.message, /neighborhoods/);
528
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
529
- return replacement !== "";
530
- },
531
511
  );
512
+ const failure = report.failures?.[0];
513
+ assert.ok(failure);
514
+ replacement = failure.candidate ?? "";
515
+ assert.equal(replacement, h(prefix + original, prefixLines + 2));
516
+ assert.equal(failure.content, "b");
517
+ assert.equal(failure.search, prefixLines === 1 ? "local window" : "full file");
518
+ assert.match(report.next ?? "", /confirm.*intended target/);
519
+ assert.equal(report.candidateNeighborhoods, undefined);
532
520
  assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + original);
533
521
  await call(edit, {
534
522
  path: "shift.txt",
@@ -540,25 +528,22 @@ test("local and full-file recovery return copyable anchors without changing the
540
528
 
541
529
  test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () =>
542
530
  withDir(async (dir) => {
543
- const oversized = "x".repeat(MAX_RECOVERY_CANDIDATE_BYTES);
531
+ const oversized = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
544
532
  const original = `a\n${oversized}\n`;
545
533
  await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
546
534
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
547
- await assert.rejects(
548
- call(edit, {
535
+ const report = failureReport(
536
+ await call(edit, {
549
537
  path: "shift-large.txt",
550
538
  edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
551
539
  }),
552
- (error: Error) => {
553
- assert.match(
554
- error.message,
555
- new RegExp(`Candidate.*exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}`),
556
- );
557
- assert.match(error.message, /use read or grep/);
558
- assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
559
- return true;
560
- },
561
540
  );
541
+ assert.match(
542
+ report.failures?.[0].omitted ?? "",
543
+ new RegExp(`exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
544
+ );
545
+ assert.match(report.next ?? "", /use read or grep/);
546
+ assert.equal(report.failures?.[0].content, undefined);
562
547
  }));
563
548
 
564
549
  test("failed commands preserve mutation results and stay out of all main card renderers", async () =>
@@ -607,7 +592,7 @@ test("failed commands preserve mutation results and stay out of all main card re
607
592
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
608
593
  const args = {
609
594
  path: "replace.txt",
610
- replacements: [{ find: "before", replace: "after" }],
595
+ replacements: [{ literal: true, find: "before", replace: "after" }],
611
596
  };
612
597
  const result = await callTool(
613
598
  tool,
@@ -675,16 +660,12 @@ test("failed commands preserve mutation results and stay out of all main card re
675
660
  await writeFile(join(dir, path), "before\n");
676
661
  const { result, rendered } = await run();
677
662
  assert.equal("isError" in result, false);
678
- assert.equal(result.details.actionFusion?.command, "failed");
679
- assert.equal(result.details.actionFusion?.publication, "PUBLISHED");
680
- if (path !== "write.txt") {
681
- const mutation = result.content[0];
682
- assert.ok(mutation.type === "text");
683
- assert.match(mutation.text, /^\d+#[0-9A-Z]+/m);
684
- }
663
+ const report = detailsReport(result.details);
664
+ assert.equal(report?.publication, "PUBLISHED");
685
665
  const last = result.content.at(-1);
686
666
  assert.ok(last?.type === "text");
687
- assert.match(last.text, /then_run:failed[\s\S]*command-only diagnostic/);
667
+ assert.equal(report?.then_run?.status, "failed");
668
+ assert.match(report?.then_run?.output ?? "", /command-only diagnostic/);
688
669
  if (path !== "write.txt")
689
670
  assert.equal(typeof ("diff" in result.details ? result.details.diff : undefined), "string");
690
671
  assert.doesNotMatch(rendered, /command-only diagnostic|then_run:failed/);
@@ -701,43 +682,36 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
701
682
  const target = join(dir, "invalid-utf8.txt");
702
683
  const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
703
684
  await writeFile(target, original);
704
- await assert.rejects(
705
- call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "invalid-utf8.txt" }),
706
- /UNSUPPORTED_ENCODING/,
707
- );
708
- await assert.rejects(
709
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
710
- path: "invalid-utf8.txt",
711
- edits: [{ op: "append", body: ["x"] }],
712
- }),
713
- /UNSUPPORTED_ENCODING/,
714
- );
715
- await assert.rejects(
716
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
717
- path: "invalid-utf8.txt",
718
- replacements: [{ find: "a", replace: "b" }],
719
- }),
720
- /UNSUPPORTED_ENCODING/,
721
- );
685
+ for (const [tool, args] of [
686
+ [makeReadOverride(dir, DEFAULT_CONFIG), { path: "invalid-utf8.txt" }],
687
+ [
688
+ makeEditOverride(dir, DEFAULT_CONFIG),
689
+ { path: "invalid-utf8.txt", edits: [{ op: "append", body: ["x"] }] },
690
+ ],
691
+ [
692
+ makeReplaceTool(dir, DEFAULT_CONFIG),
693
+ { path: "invalid-utf8.txt", replacements: [{ literal: true, find: "a", replace: "b" }] },
694
+ ],
695
+ ] as const) {
696
+ assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_ENCODING");
697
+ }
722
698
  assert.deepEqual(await readFile(target), original);
723
699
 
724
700
  const nulTarget = join(dir, "nul.txt");
725
701
  const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
726
702
  await writeFile(nulTarget, nulOriginal);
727
- await assert.rejects(
728
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
729
- path: "nul.txt",
730
- edits: [{ op: "append", body: ["x"] }],
731
- }),
732
- /UNSUPPORTED_TEXT/,
733
- );
734
- await assert.rejects(
735
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
736
- path: "nul.txt",
737
- replacements: [{ find: "a", replace: "b" }],
738
- }),
739
- /UNSUPPORTED_TEXT/,
740
- );
703
+ for (const [tool, args] of [
704
+ [
705
+ makeEditOverride(dir, DEFAULT_CONFIG),
706
+ { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] },
707
+ ],
708
+ [
709
+ makeReplaceTool(dir, DEFAULT_CONFIG),
710
+ { path: "nul.txt", replacements: [{ literal: true, find: "a", replace: "b" }] },
711
+ ],
712
+ ] as const) {
713
+ assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_TEXT");
714
+ }
741
715
  assert.deepEqual(await readFile(nulTarget), nulOriginal);
742
716
 
743
717
  const nativeRead: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "nul.txt" });
@@ -745,9 +719,9 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
745
719
 
746
720
  const utf16Target = join(dir, "utf16.txt");
747
721
  await writeFile(utf16Target, Buffer.from([0xff, 0xfe, 0x49, 0x6c]));
748
- await assert.rejects(
749
- call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "utf16.txt" }),
750
- /UNSUPPORTED_ENCODING/,
722
+ assert.equal(
723
+ failureReport(await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "utf16.txt" })).error,
724
+ "UNSUPPORTED_ENCODING",
751
725
  );
752
726
  }));
753
727
 
@@ -761,7 +735,7 @@ test("edit rejects embedded line terminators at its schema boundary", async () =
761
735
  path: "body.txt",
762
736
  edits: [{ op: "append", body: [line] }],
763
737
  }),
764
- /Validation failed for tool "edit"/,
738
+ rejectsArguments(),
765
739
  );
766
740
  assert.equal(await readFile(target, "utf8"), "a\n");
767
741
  }
@@ -774,8 +748,8 @@ test("edit rejects unwritable body lines before reading a missing target", async
774
748
  const valid = { path: target, edits: [{ op: "append" as const, body: ["ok"] }] };
775
749
  assert.equal(edit.prepareArguments(valid), valid);
776
750
  for (const [line, expected] of [
777
- ["bad\0", /Invalid argument edits\[0\]\.body\[1\]: UNSUPPORTED_TEXT:/],
778
- ["\ud800", /Invalid argument edits\[0\]\.body\[1\]: INVALID_UNICODE:/],
751
+ ["bad\0", rejectsArgument("edits[0].body[1]", /NUL/)],
752
+ ["\ud800", rejectsArgument("edits[0].body[1]", /losslessly.*UTF-8/)],
779
753
  ] as const) {
780
754
  await assert.rejects(
781
755
  call(edit, { path: target, edits: [{ op: "append", body: ["ok", line] }] }),
@@ -785,7 +759,7 @@ test("edit rejects unwritable body lines before reading a missing target", async
785
759
  }
786
760
  }));
787
761
 
788
- test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () =>
762
+ test("editing a BOM-prefixed file → publishes the changed bytes with the BOM intact", async () =>
789
763
  withDir(async (dir) => {
790
764
  const target = join(dir, "bom.txt");
791
765
  const source = "\ufeffguard\nold\n";
@@ -798,10 +772,8 @@ test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async ()
798
772
  });
799
773
  const expected = Buffer.from(line === 1 ? "\ufeffnew\nold\n" : "\ufeffguard\nnew\n", "utf8");
800
774
  assert.deepEqual(await readFile(target), expected);
801
- assert.equal(result.details.baseRevision, byteRevision(original));
802
- assert.equal(result.details.publishedRevision, byteRevision(expected));
803
- assert.equal(result.details.observedRevision, result.details.publishedRevision);
804
- assert.equal("revision" in result.details, false);
775
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
776
+ assert.equal(reportOf(result, "edit")?.freshness, undefined);
805
777
  }
806
778
  }));
807
779
 
@@ -815,15 +787,15 @@ test("edit and replace reject NUL arguments without rewriting source bytes", asy
815
787
  path: "output.txt",
816
788
  edits: [{ op: "append", body: ["bad\0text"] }],
817
789
  }),
818
- /UNSUPPORTED_TEXT/,
790
+ rejectsArgument("edits[0].body[0]", /NUL/),
819
791
  );
820
792
  assert.deepEqual(await readFile(target), original);
821
793
  await assert.rejects(
822
794
  call(makeReplaceTool(dir, DEFAULT_CONFIG), {
823
795
  path: "output.txt",
824
- replacements: [{ find: "before", replace: "bad\0text" }],
796
+ replacements: [{ literal: true, find: "before", replace: "bad\0text" }],
825
797
  }),
826
- /UNSUPPORTED_TEXT/,
798
+ rejectsArgument("replacements[0].replace", /NUL/),
827
799
  );
828
800
  assert.deepEqual(await readFile(target), original);
829
801
  }));
@@ -839,15 +811,14 @@ test("failed edits expose input status and candidate code for a verified fused r
839
811
  let commands = 0;
840
812
  const fusion = createActionFusionExecutor(async () => {
841
813
  commands++;
842
- return { status: "succeeded", output: "checked" };
814
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
843
815
  });
844
816
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
845
817
  const stale = h(original.join("\n"), 5);
846
818
  const stable = h(before, 12);
847
819
  const candidate = h(before, 6);
848
- let message = "";
849
- await assert.rejects(
850
- callTool(
820
+ const report = failureReport(
821
+ await callTool(
851
822
  edit,
852
823
  {
853
824
  path: file,
@@ -859,19 +830,15 @@ test("failed edits expose input status and candidate code for a verified fused r
859
830
  },
860
831
  { toolCallId: "failed", ctx: { cwd: dir } },
861
832
  ),
862
- (error: Error) => {
863
- message = error.message;
864
- return true;
865
- },
866
833
  );
867
- assert.match(message, /then_run:skipped/);
868
- assert.ok(message.includes(`op 0 / anchor / ${stale} / mismatched`));
869
- assert.ok(message.includes(`op 1 / anchor / ${stable} / matched`));
870
- assert.ok(message.includes(`checksum-matching candidate ${candidate}.`));
871
- assert.equal(message.split(`${candidate}│${original[4]}`).length - 1, 1);
872
- assert.doesNotMatch(message, /0 omitted|Limits:/);
873
- assert.doesNotMatch(message, /neighborhoods|Current-file context/);
874
- assert.equal((message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
834
+ assert.equal(report.then_run?.status, "skipped");
835
+ assert.deepEqual(report.matched, ["edits[1].anchor"]);
836
+ assert.equal(report.failures?.[0].field, "edits[0].anchor");
837
+ assert.equal(report.failures?.[0].cited, stale);
838
+ assert.equal(report.failures?.[0].candidate, candidate);
839
+ assert.equal(report.failures?.[0].content, original[4]);
840
+ assert.equal(report.candidateNeighborhoods, undefined);
841
+ assert.equal(report.omittedFailures, undefined);
875
842
  assert.equal(await readFile(file, "utf8"), before);
876
843
  assert.equal(commands, 0);
877
844
  await callTool(
@@ -879,7 +846,11 @@ test("failed edits expose input status and candidate code for a verified fused r
879
846
  {
880
847
  path: file,
881
848
  edits: [
882
- { op: "insert_after", anchor: anchorLine(message, 6), body: ["const hashLen = 4;"] },
849
+ {
850
+ op: "insert_after",
851
+ anchor: report.failures![0].candidate!,
852
+ body: ["const hashLen = 4;"],
853
+ },
883
854
  { op: "replace", anchor: stable, body: ["changed"] },
884
855
  ],
885
856
  then_run: { command: "check" },
@@ -904,28 +875,25 @@ test("ambiguous candidates include distinguishing neighborhoods for a verified r
904
875
  const file = join(dir, "ambiguous.txt");
905
876
  await writeFile(file, before);
906
877
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
907
- let context = "";
908
- await assert.rejects(
909
- call(edit, {
878
+ const report = failureReport(
879
+ await call(edit, {
910
880
  path: file,
911
881
  edits: [
912
882
  { op: "replace", anchor: h("header\n return value;\n", 2), body: [" return updated;"] },
913
883
  ],
914
884
  }),
915
- (error: Error) => {
916
- assert.match(error.message, /ambiguous checksum matches/);
917
- assert.match(error.message, /Search: local.*outside.*not checked/);
918
- assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
919
- context = error.message.split("Ambiguous-candidate neighborhoods")[1];
920
- assert.ok(context);
921
- assert.match(context, /@@ candidate-neighborhood lines 2-8 @@/);
922
- assert.match(context, /@@ candidate-neighborhood lines 12-18 @@/);
923
- assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
924
- assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
925
- assert.equal(anchorLine(context, 5), h(before, 5));
926
- return true;
927
- },
928
885
  );
886
+ assert.equal(report.failures?.[0].result, "ambiguous");
887
+ assert.equal(report.failures?.[0].search, "local window");
888
+ assert.deepEqual(report.failures?.[0].candidates, [h(before, 5), h(before, 15)]);
889
+ assert.deepEqual(
890
+ report.candidateNeighborhoods?.map((group) => group.lines),
891
+ ["2-8", "12-18"],
892
+ );
893
+ const context = report.candidateNeighborhoods?.flatMap((group) => group.rows).join("\n") ?? "";
894
+ assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
895
+ assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
896
+ assert.equal(anchorLine(context, 5), h(before, 5));
929
897
  assert.equal(await readFile(file, "utf8"), before);
930
898
  await call(edit, {
931
899
  path: file,
@@ -953,61 +921,64 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
953
921
  edits: [operation, { op: "replace", anchor: laterAnchor, body: ["B"] }],
954
922
  }),
955
923
  (error: Error) => {
956
- assert.match(error.message, /Validation failed for tool "edit"/);
957
- assert.doesNotMatch(error.message, /Input-anchor checks|\/ matched|\/ mismatched/);
924
+ rejectsArguments()(error);
925
+ const report = argumentError(error);
926
+ assert.equal(report.matched, undefined);
927
+ assert.equal(report.failures, undefined);
958
928
  return true;
959
929
  },
960
930
  );
961
931
  assert.equal(await readFile(file, "utf8"), before);
962
932
  }
963
933
  }
964
- await assert.rejects(
965
- call(edit, {
934
+ const rejected = failureReport(
935
+ await call(edit, {
966
936
  path: file,
967
937
  edits: [
968
938
  { op: "replace", anchor: stable, body: ["A"] },
969
939
  { op: "delete", anchor: h(before, 2), end: "3#ZZZZ" },
970
940
  ],
971
941
  }),
972
- (error: Error) => {
973
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
974
- assert.match(error.message, /op 1 \/ end \/ 3#ZZZZ \/ mismatched/);
975
- assert.match(error.message, /Anchor checks.*retries revalidate/);
976
- return true;
977
- },
978
942
  );
943
+ assert.deepEqual(rejected.matched, ["edits[0].anchor", "edits[1].anchor"]);
944
+ assert.equal(rejected.failures?.[0].field, "edits[1].end");
945
+ assert.equal(rejected.failures?.[0].cited, "3#ZZZZ");
946
+ assert.match(rejected.next ?? "", /Retries verify every anchor again/);
979
947
  assert.equal(await readFile(file, "utf8"), before);
980
948
  await writeFile(file, "changed\nb\nc\n");
981
- await assert.rejects(
982
- call(edit, {
949
+ const retry = failureReport(
950
+ await call(edit, {
983
951
  path: file,
984
952
  edits: [
985
953
  { op: "replace", anchor: stable, body: ["A"] },
986
954
  { op: "replace", anchor: "3#ZZZZ", body: ["B"] },
987
955
  ],
988
956
  }),
989
- (error: Error) => {
990
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / mismatched`));
991
- return true;
992
- },
993
957
  );
958
+ assert.ok(
959
+ retry.failures?.some(
960
+ (failure) => failure.field === "edits[0].anchor" && failure.cited === stable,
961
+ ),
962
+ );
963
+ assert.equal(retry.matched, undefined);
994
964
  assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
995
965
  }));
996
966
 
997
- test("single-operation anchor failures omit the redundant Input-anchor checks table", async () =>
967
+ test("single-operation anchor failures omit redundant matched-anchor facts", async () =>
998
968
  withDir(async (dir) => {
999
969
  const file = join(dir, "single.txt");
1000
- await writeFile(file, "line1\nline2\nline3\n");
970
+ const source = "line1\nline2\nline3\n";
971
+ await writeFile(file, source);
1001
972
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1002
973
  for (const operation of [
1003
974
  { op: "replace", anchor: "1#XXXX", body: ["new"] },
1004
- { op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] },
975
+ { op: "replace", anchor: h(source, 1), end: "2#YYYY", body: ["new"] },
1005
976
  ]) {
1006
- await assert.rejects(call(edit, { path: file, edits: [operation] }), (error: Error) => {
1007
- assert.match(error.message, /Anchor mismatch/);
1008
- assert.doesNotMatch(error.message, /Input-anchor checks/);
1009
- return true;
1010
- });
977
+ const report = failureReport(await call(edit, { path: file, edits: [operation] }));
978
+ assert.equal(report.error, "ANCHOR_MISMATCH");
979
+ assert.equal(report.matched, undefined);
980
+ assert.equal(report.omittedMatched, undefined);
981
+ assert.equal(await readFile(file, "utf8"), source);
1011
982
  }
1012
983
  }));
1013
984
 
@@ -1022,75 +993,36 @@ test("failed batches return more than forty checks and mappings when byte budget
1022
993
  anchor: h(original, 2),
1023
994
  body: ["changed"],
1024
995
  }));
1025
- await assert.rejects(
1026
- call(makeEditOverride(dir, DEFAULT_CONFIG), { path: file, edits }),
1027
- (error: Error) => {
1028
- assert.doesNotMatch(
1029
- error.message,
1030
- /truncated|failure details omitted|Anchor checks: \d+\/\d+/,
1031
- );
1032
- assert.equal(
1033
- (error.message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? []).length,
1034
- 45,
1035
- );
1036
- assert.equal((error.message.match(/checksum-matching candidate/g) ?? []).length, 45);
1037
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1038
- assert.doesNotMatch(error.message, /\/ matched/);
1039
- return true;
1040
- },
996
+ const report = failureReport(
997
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), { path: file, edits }),
1041
998
  );
999
+ assert.equal(report.failures?.length, 45);
1000
+ assert.equal(report.omittedFailures, undefined);
1001
+ assert.equal(report.omittedMatched, undefined);
1002
+ assert.equal(report.matched, undefined);
1003
+ assert.ok(report.failures?.every((failure) => failure.candidate === h(before, 3)));
1004
+ assert.equal(report.failures?.filter((failure) => failure.content === "target").length, 1);
1042
1005
  assert.equal(await readFile(file, "utf8"), before);
1043
1006
  }));
1044
1007
 
1045
- test("compact edit anchors retain only untouched deletion successors in mixed batches", async () =>
1046
- withDir(async (dir) => {
1047
- const before = "a\nb\nc\nd\ne\nf\ng\n";
1048
- const file = join(dir, "mixed.txt");
1049
- await writeFile(file, before);
1050
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1051
- const result = await call(edit, {
1052
- path: file,
1053
- edits: [
1054
- { op: "delete", anchor: h(before, 6) },
1055
- { op: "replace", anchor: h(before, 4), body: ["D"] },
1056
- { op: "delete", anchor: h(before, 3) },
1057
- { op: "replace", anchor: h(before, 1), body: ["A", "X"] },
1058
- ],
1059
- });
1060
- const after = "A\nX\nb\nD\ne\ng\n";
1061
- assert.equal(await readFile(file, "utf8"), after);
1062
- const output = result.content[0].text;
1063
- assert.deepEqual(
1064
- output.split("\n").filter((line: string) => /^\d+#/.test(line)),
1065
- [h(after, 1), h(after, 2), h(after, 4), `${h(after, 6)}│g`],
1066
- );
1067
- await call(edit, {
1068
- path: file,
1069
- edits: [{ op: "replace", anchor: anchorLine(output, 6), body: ["G"] }],
1070
- });
1071
- assert.equal(await readFile(file, "utf8"), "A\nX\nb\nD\ne\nG\n");
1072
- }));
1073
-
1074
1008
  test("unique candidate content is independent of oversized neighboring rows", async () =>
1075
1009
  withDir(async (dir) => {
1076
1010
  const original = "header\ntarget\ntail\n";
1077
- const before = `header\n${"x".repeat(MAX_BLOCK_BYTES + 1)}\ntarget\ntail\n`;
1011
+ const before = `header\n${"x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes + 1)}\ntarget\ntail\n`;
1078
1012
  const file = join(dir, "fallback.txt");
1079
1013
  await writeFile(file, before);
1080
- let candidate = "";
1081
- await assert.rejects(
1082
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
1014
+ const report = failureReport(
1015
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1083
1016
  path: file,
1084
1017
  edits: [{ op: "replace", anchor: h(original, 2), body: ["updated"] }],
1085
1018
  }),
1086
- (error: Error) => {
1087
- candidate = anchorLine(error.message, 3);
1088
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1089
- assert.doesNotMatch(error.message, /neighborhoods|truncated/);
1090
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
1091
- return true;
1092
- },
1093
1019
  );
1020
+ const candidate = report.failures?.[0].candidate;
1021
+ assert.ok(candidate);
1022
+ assert.equal(candidate, h(before, 3));
1023
+ assert.equal(report.failures?.[0].content, "target");
1024
+ assert.equal(report.candidateNeighborhoods, undefined);
1025
+ assert.equal(report.omittedFailures, undefined);
1094
1026
  assert.equal(await readFile(file, "utf8"), before);
1095
1027
  await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1096
1028
  path: file,
@@ -1099,7 +1031,7 @@ test("unique candidate content is independent of oversized neighboring rows", as
1099
1031
  assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
1100
1032
  }));
1101
1033
 
1102
- test("standalone CR replacements remain visible in diffs and exact in patches", async () =>
1034
+ test("standalone CR replacements remain visible in diffs and exact in file bytes", async () =>
1103
1035
  withDir(async (dir) => {
1104
1036
  const file = join(dir, "cr.txt");
1105
1037
  for (const [before, find, replacement] of [
@@ -1109,59 +1041,33 @@ test("standalone CR replacements remain visible in diffs and exact in patches",
1109
1041
  await writeFile(file, before);
1110
1042
  const result = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
1111
1043
  path: file,
1112
- replacements: [{ find, replace: replacement, regex: true }],
1044
+ replacements: [{ find, replace: replacement, literal: false }],
1113
1045
  });
1114
1046
  assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
1115
- assert.equal(result.details.firstChangedLine, 1);
1116
1047
  assert.match(result.details.diff, /^-1 a␍/m);
1117
1048
  assert.match(result.details.diff, /^\+1 a/m);
1118
1049
  assert.ok(!result.details.diff.includes("\r"));
1119
- assert.ok(result.details.patch.includes(`-a${before.includes("\r\n") ? "\r\n" : "\rb\n"}`));
1120
- assert.match(result.details.patch, /@@/);
1121
1050
  }
1122
1051
  }));
1123
1052
 
1124
- test("deletion successors and unique candidate rows display CR without altering anchors", async () =>
1053
+ test("shifted unique candidate → displays standalone CR without altering its anchor", async () =>
1125
1054
  withDir(async (dir) => {
1126
1055
  const file = join(dir, "cr.txt");
1127
1056
  const before = "remove\na\rb\n";
1128
1057
  await writeFile(file, before);
1129
- const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1058
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1130
1059
  path: file,
1131
1060
  edits: [{ op: "delete", anchor: h(before, 1) }],
1132
1061
  });
1133
- assert.ok(result.content[0].text.includes(`${h("a\rb\n", 1)}│a␍b`));
1134
1062
  assert.equal(await readFile(file, "utf8"), "a\rb\n");
1135
- await assert.rejects(
1136
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
1063
+ const report = failureReport(
1064
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1137
1065
  path: file,
1138
1066
  edits: [{ op: "delete", anchor: h(before, 2) }],
1139
1067
  }),
1140
- (error: Error) => {
1141
- assert.ok(error.message.includes(`${h("a\rb\n", 1)}│a␍b`));
1142
- assert.ok(!error.message.includes("\r"));
1143
- return true;
1144
- },
1145
1068
  );
1146
- }));
1147
-
1148
- test("edit tool rejects non-array formats Pi cannot convert", async () =>
1149
- withDir(async (dir) => {
1150
- const file = join(dir, "f.txt");
1151
- await writeFile(file, "first\nsecond\n");
1152
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1153
- const anchor = h("first\nsecond\n", 2);
1154
- for (const alternate of [
1155
- { path: "f.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["SECOND"] }]) },
1156
- { path: "f.txt", op: "replace", anchor, body: ["SECOND"] },
1157
- ]) {
1158
- const original = structuredClone(alternate);
1159
- await assert.rejects(call(edit, alternate), /Validation failed/);
1160
- assert.deepEqual(alternate, original);
1161
- assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1162
- }
1163
- await call(edit, { path: "f.txt", edits: [{ op: "replace", anchor, body: ["SECOND"] }] });
1164
- assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1069
+ assert.equal(report.failures?.[0].candidate, h("a\rb\n", 1));
1070
+ assert.equal(report.failures?.[0].content, "a␍b");
1165
1071
  }));
1166
1072
 
1167
1073
  test("edit receives multiple wrong-length anchors → reports each location with one recovery hint", async () =>
@@ -1182,11 +1088,14 @@ test("edit receives multiple wrong-length anchors → reports each location with
1182
1088
  };
1183
1089
 
1184
1090
  await assert.rejects(call(edit, args), (error: Error) => {
1185
- assert.match(error.message, /Anchor hash length mismatch/);
1186
- assert.match(error.message, /Invalid argument edits\[0\]\.end:/);
1187
- assert.match(error.message, /Invalid argument edits\[1\]\.anchor:/);
1188
- assert.equal(error.message.match(/read or grep/gi)?.length, 1);
1189
- assert.ok(error.message.includes(short));
1091
+ rejectsArgument("edits[0].end")(error);
1092
+ rejectsArgument("edits[1].anchor")(error);
1093
+ const issues = argumentError(error).issues;
1094
+ assert.deepEqual(
1095
+ issues.map((issue) => issue.field),
1096
+ ["edits[0].end", "edits[1].anchor"],
1097
+ );
1098
+ assert.equal(issues.filter((issue) => issue.fix?.includes("Read or grep")).length, 1);
1190
1099
  assert.match(error.message, new RegExp(`${hashLen - 2} hash characters`));
1191
1100
  assert.match(error.message, new RegExp(`hashLen.*${hashLen}`));
1192
1101
  return true;
@@ -1212,29 +1121,6 @@ test("Pi-converted single-object edits execute as a canonical array", async () =
1212
1121
  assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1213
1122
  }));
1214
1123
 
1215
- test("edit execute rejects legacy oldText/newText without op", async () =>
1216
- withDir(async (dir) => {
1217
- const file = join(dir, "f.txt");
1218
- await writeFile(file, "first\nsecond\n");
1219
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1220
- await assert.rejects(
1221
- call(edit, {
1222
- path: "f.txt",
1223
- oldText: "first",
1224
- newText: "FIRST",
1225
- }),
1226
- /Validation failed for tool "edit"/,
1227
- );
1228
- await assert.rejects(
1229
- call(edit, {
1230
- path: "f.txt",
1231
- edits: [{ oldText: "first", newText: "FIRST" } as any],
1232
- }),
1233
- /Validation failed for tool "edit"/,
1234
- );
1235
- assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1236
- }));
1237
-
1238
1124
  test("unresolved snapshot rows support direct retry and revalidate after further changes", async () => {
1239
1125
  await withDir(async (dir) => {
1240
1126
  const file = join(dir, "recover.txt");
@@ -1242,29 +1128,25 @@ test("unresolved snapshot rows support direct retry and revalidate after further
1242
1128
  const current = observed.replace("old", "pending");
1243
1129
  await writeFile(file, current);
1244
1130
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1245
- let diagnostic = "";
1246
- await assert.rejects(
1247
- call(edit, {
1131
+ const report = failureReport(
1132
+ await call(edit, {
1248
1133
  path: "recover.txt",
1249
1134
  edits: [{ op: "replace", anchor: h(observed, 2), body: ["target = new"] }],
1250
1135
  }),
1251
- (error: Error) => {
1252
- diagnostic = error.message;
1253
- assert.match(diagnostic, /^2#[0-9A-Z]+│target = pending$/m);
1254
- return true;
1255
- },
1256
1136
  );
1137
+ const diagnostic = report.failures?.[0].observed ?? "";
1138
+ assert.match(diagnostic, /^2#[0-9A-Z]+│target = pending$/);
1257
1139
  assert.deepEqual(await readFile(file), Buffer.from(current));
1258
1140
  const retryAnchor = anchorLine(diagnostic, 2);
1259
1141
  const changedAgain = current.replace("pending", "other");
1260
1142
  await writeFile(file, changedAgain);
1261
- await assert.rejects(
1262
- call(edit, {
1143
+ const retry = failureReport(
1144
+ await call(edit, {
1263
1145
  path: "recover.txt",
1264
1146
  edits: [{ op: "replace", anchor: retryAnchor, body: ["target = new"] }],
1265
1147
  }),
1266
- /Anchor mismatch/,
1267
1148
  );
1149
+ assert.equal(retry.error, "ANCHOR_MISMATCH");
1268
1150
  assert.deepEqual(await readFile(file), Buffer.from(changedAgain));
1269
1151
  await writeFile(file, current);
1270
1152
  await call(edit, {
@@ -1278,17 +1160,23 @@ test("unresolved oversized and out-of-range rows require more context without pa
1278
1160
  await withDir(async (dir) => {
1279
1161
  const file = join(dir, "recover.txt");
1280
1162
  const current =
1281
- "界".repeat(Math.ceil(MAX_RECOVERY_CANDIDATE_BYTES / Buffer.byteLength("界"))) + "\n";
1163
+ "界".repeat(Math.ceil(DEFAULT_OUTPUT_BUDGETS.fieldBytes / Buffer.byteLength("界"))) + "\n";
1282
1164
  await writeFile(file, current);
1283
1165
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1284
1166
  for (const anchor of [h("old\n", 1), "99#XXXX"]) {
1285
- await assert.rejects(
1286
- call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor, body: ["new"] }] }),
1287
- (error: Error) => {
1288
- assert.match(error.message, /read or grep/);
1289
- assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│/m);
1290
- return true;
1291
- },
1167
+ const report = failureReport(
1168
+ await call(edit, {
1169
+ path: "recover.txt",
1170
+ edits: [{ op: "replace", anchor, body: ["new"] }],
1171
+ }),
1172
+ );
1173
+ assert.match(report.next ?? "", /read or grep/);
1174
+ assert.equal(report.failures?.[0].observed, undefined);
1175
+ assert.equal(
1176
+ report.failures?.[0].omitted,
1177
+ anchor.startsWith("99#")
1178
+ ? "cited line is out of range"
1179
+ : `row exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`,
1292
1180
  );
1293
1181
  assert.deepEqual(await readFile(file), Buffer.from(current));
1294
1182
  }
@@ -1304,7 +1192,7 @@ test("edit rejects impossible checksum characters before accessing the file", as
1304
1192
  path: "missing.txt",
1305
1193
  edits: [{ op: "delete", anchor: `1#${char.repeat(DEFAULT_CONFIG.hashLen)}` }],
1306
1194
  }),
1307
- /Validation failed/,
1195
+ rejectsArguments(),
1308
1196
  );
1309
1197
  }
1310
1198
  }));
@@ -1317,30 +1205,25 @@ test("ambiguous failure lists and neighborhoods select the same first eight cand
1317
1205
  const text = lines.join("\n");
1318
1206
  await writeFile(join(dir, "candidates.txt"), text);
1319
1207
  const tool = makeEditOverride(dir, DEFAULT_CONFIG);
1320
- await assert.rejects(
1321
- call(tool, {
1208
+ const report = failureReport(
1209
+ await call(tool, {
1322
1210
  path: "candidates.txt",
1323
1211
  edits: [{ op: "delete", anchor: `200#${computeLineHash(200, "target", 4)}` }],
1324
1212
  }),
1325
- (error: Error) => {
1326
- const list = error.message
1327
- .split("\n")
1328
- .find((line) => line.includes("ambiguous checksum matches:"));
1329
- assert.ok(list);
1330
- assert.match(list, /1 more candidates omitted/);
1331
- for (const position of positions.slice(0, 8)) {
1332
- const anchor = h(text, position);
1333
- assert.ok(list.includes(`"${anchor}"`));
1334
- assert.ok(error.message.includes(`${anchor}│target`));
1335
- }
1336
- assert.ok(!error.message.includes(h(text, 84)));
1337
- return true;
1338
- },
1339
1213
  );
1214
+ assert.equal(report.failures?.[0].omittedCandidates, 1);
1215
+ assert.deepEqual(
1216
+ report.failures?.[0].candidates,
1217
+ positions.slice(0, 8).map((position) => h(text, position)),
1218
+ );
1219
+ const rows = report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
1220
+ for (const position of positions.slice(0, 8))
1221
+ assert.ok(rows.includes(`${h(text, position)}│target`));
1222
+ assert.ok(!JSON.stringify(report).includes(h(text, 84)));
1340
1223
  assert.equal(await readFile(join(dir, "candidates.txt"), "utf8"), text);
1341
1224
  }));
1342
1225
 
1343
- test("edit verification and returned anchors use the supplied hash length", async () =>
1226
+ test("edit verification → uses the supplied hash length", async () =>
1344
1227
  withDir(async (dir) => {
1345
1228
  const edit = makeEditOverride(dir, { ...DEFAULT_CONFIG, hashLen: 6 });
1346
1229
  await writeFile(join(dir, "registered.txt"), "before\n");
@@ -1354,6 +1237,101 @@ test("edit verification and returned anchors use the supplied hash length", asyn
1354
1237
  },
1355
1238
  ],
1356
1239
  });
1357
- assert.equal(anchorLine(result.content[0].text, 1), `1#${computeLineHash(1, "after", 6)}`);
1240
+ assert.equal(result.isError, undefined);
1358
1241
  assert.equal(await readFile(join(dir, "registered.txt"), "utf8"), "after\n");
1359
1242
  }));
1243
+
1244
+ test("copy/move through read anchors → publishes captured bytes with BOM and mixed endings intact", async () =>
1245
+ withDir(async (dir) => {
1246
+ const path = "transfer.txt";
1247
+ const file = join(dir, path);
1248
+ const source = "\uFEFFA\r\nB\nC\r\nD\n";
1249
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
1250
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1251
+ for (const op of ["copy", "move"] as const) {
1252
+ await writeFile(file, source);
1253
+ const observed: Awaited<ReturnType<typeof read.execute>> = await callTool(read, { path });
1254
+ const rows = observed.content
1255
+ .filter((block) => block.type === "text")
1256
+ .map((block) => block.text)
1257
+ .join("\n");
1258
+ const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(edit, {
1259
+ path,
1260
+ edits: [
1261
+ { op, anchor: anchorLine(rows, 1), end: anchorLine(rows, 2), after: anchorLine(rows, 4) },
1262
+ ],
1263
+ });
1264
+ const expected = op === "copy" ? source + "A\r\nB\n" : "\uFEFFC\r\nD\nA\r\nB\n";
1265
+ const bytes = Buffer.from(expected, "utf8");
1266
+ assert.deepEqual(await readFile(file), bytes);
1267
+ assert.equal(result.isError, undefined);
1268
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
1269
+ }
1270
+ }));
1271
+
1272
+ test("copy/move stale destination → report its field and skip publication and fused commands", async () =>
1273
+ withDir(async (dir) => {
1274
+ const original = "A\nB\nC\n";
1275
+ const current = "A\nB\nNEW\n";
1276
+ const file = join(dir, "stale-transfer.txt");
1277
+ await writeFile(file, current);
1278
+ let commands = 0;
1279
+ const fusion = createActionFusionExecutor(async () => {
1280
+ commands++;
1281
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
1282
+ });
1283
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1284
+ for (const op of ["copy", "move"] as const) {
1285
+ const report = failureReport(
1286
+ await callTool(edit, {
1287
+ path: file,
1288
+ edits: [
1289
+ { op, anchor: h(current, 1), after: h(original, 3) },
1290
+ { op: "replace", anchor: h(current, 2), body: ["changed"] },
1291
+ ],
1292
+ then_run: { command: "check" },
1293
+ }),
1294
+ );
1295
+ assert.equal(report.failures?.[0].field, "edits[0].after");
1296
+ assert.equal(report.failures?.[0].cited, h(original, 3));
1297
+ assert.equal(report.then_run?.status, "skipped");
1298
+ assert.equal(report.publication, "NOT_PUBLISHED");
1299
+ assert.equal(await readFile(file, "utf8"), current);
1300
+ assert.equal(commands, 0);
1301
+ }
1302
+ }));
1303
+
1304
+ test("copy/move with fused command → execute after the complete transfer and preserve it on failure", async () =>
1305
+ withDir(async (dir) => {
1306
+ const source = "A\nB\nC\n";
1307
+ const file = join(dir, "fused-transfer.txt");
1308
+ for (const op of ["copy", "move"] as const) {
1309
+ await writeFile(file, source);
1310
+ const expected = op === "copy" ? "A\nB\nC\nA\n" : "B\nC\nA\n";
1311
+ let commands = 0;
1312
+ let commandBytes: string | undefined;
1313
+ const commandFailure = new Error("Command exited with code 7");
1314
+ const fusion = createActionFusionExecutor(async () => {
1315
+ commands++;
1316
+ commandBytes = await readFile(file, "utf8");
1317
+ throw commandFailure;
1318
+ });
1319
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1320
+ const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(
1321
+ edit,
1322
+ {
1323
+ path: file,
1324
+ edits: [{ op, anchor: h(source, 1), after: h(source, 3) }],
1325
+ then_run: { command: "check" },
1326
+ },
1327
+ { ctx: { cwd: dir } },
1328
+ );
1329
+ assert.equal(reportOf(result, "edit")?.then_run?.status, "failed");
1330
+ assert.equal(reportOf(result, "edit")?.then_run?.output, commandFailure.message);
1331
+ assert.equal(commandBytes, expected);
1332
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
1333
+ assert.equal(reportOf(result, "edit")?.freshness, undefined);
1334
+ assert.equal(await readFile(file, "utf8"), expected);
1335
+ assert.equal(commands, 1);
1336
+ }
1337
+ }));