@criogaid/pi-hashline-edit 0.6.1 → 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 +55 -57
  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 +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  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 { computeLineHash } from "../core/hash.ts";
2
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
4
  import assert from "node:assert/strict";
@@ -6,29 +7,17 @@ import { writeFileSync } from "node:fs";
6
7
  import { tmpdir } from "node:os";
7
8
  import { join } from "node:path";
8
9
  import { test } from "node:test";
9
- import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
10
- import { createActionFusionExecutor, THEN_RUN_STALE } from "./action-fusion.ts";
10
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
11
+ import { createActionFusionExecutor } from "./action-fusion.ts";
11
12
  import { makeReplaceTool } from "./replace-tool.ts";
12
13
  import { makeWriteOverride } from "./write-tool.ts";
13
14
  import { makeEditOverride } from "./edit-tool.ts";
14
- import { byteRevision, FileMutationError } from "./file-commit.ts";
15
- import {
16
- commitFreshness,
17
- finalizeMutation,
18
- postProcessMutation,
19
- staleTargetNotice,
20
- type MutationOutcome,
21
- } from "./mutation-result.ts";
15
+ import { byteRevision, commitFreshness, FileMutationError } from "./file-commit.ts";
16
+ import { finalizeMutation, postProcessMutation, type MutationOutcome } from "./mutation-result.ts";
17
+ import { CommandNotRun, decodeReport, reportOf } from "./report.ts";
18
+ import { REREAD } from "./report-schema.ts";
22
19
  import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
23
20
  import { DEFAULT_CONFIG } from "./config.ts";
24
- import { publishedMutation } from "./mutation-outcome.testing.ts";
25
-
26
- const KIB = formatKiB(MAX_BLOCK_BYTES);
27
- const DIAGNOSTIC_TRUNCATED = new RegExp(`Diagnostic output truncated at ${KIB}`);
28
- const ANCHOR_CHECK_TRUNCATED = new RegExp(
29
- `Anchor-check output truncated at ${KIB}; omitted entries are not implied matched`,
30
- );
31
- const ANCHORS_OMITTED = new RegExp(`additional anchors omitted: ${KIB} limit`);
32
21
 
33
22
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
34
23
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
@@ -43,25 +32,23 @@ const invoke = (
43
32
  ) => callTool(tool, args, { toolCallId, signal, onUpdate, ctx: context });
44
33
 
45
34
  function assertFailureByteBudgets(message: string): void {
46
- const checksAt = message.indexOf("\nInput-anchor checks (this snapshot):\n");
47
- const guidanceAt = message.indexOf("\nCheck the intended target before retrying;", checksAt);
48
- const neighborhoodsAt = message.indexOf("\nAmbiguous-candidate neighborhoods", checksAt);
49
- assert.ok(checksAt > 0 && guidanceAt > checksAt);
50
- assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= MAX_BLOCK_BYTES);
35
+ const report = decodeReport(message);
36
+ assert.ok(report);
37
+ assert.equal(report.error, "ANCHOR_MISMATCH");
38
+ assert.ok(report.failures && report.failures.length > 0);
51
39
  assert.ok(
52
- Buffer.byteLength(
53
- message.slice(checksAt + 1, neighborhoodsAt < 0 ? guidanceAt : neighborhoodsAt),
54
- ) <= MAX_BLOCK_BYTES,
40
+ Buffer.byteLength(JSON.stringify(report.failures)) <= DEFAULT_OUTPUT_BUDGETS.blockBytes,
55
41
  );
56
- if (neighborhoodsAt >= 0) {
57
- const rows = message.slice(neighborhoodsAt, guidanceAt).match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
42
+ assert.equal(report.failures.length + (report.omittedFailures ?? 0), 1000);
43
+ assert.ok(report.omittedFailures);
44
+ assert.equal(report.matched, undefined);
45
+ assert.equal(report.omittedMatched, undefined);
46
+ assert.ok(report.next?.includes("intended target"));
47
+ if (report.candidateNeighborhoods) {
48
+ const rows = report.candidateNeighborhoods.flatMap((group) => group.rows);
58
49
  assert.ok(rows.length > 0);
59
- assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= MAX_BLOCK_BYTES);
50
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
60
51
  }
61
- assert.match(message, DIAGNOSTIC_TRUNCATED);
62
- assert.match(message, ANCHOR_CHECK_TRUNCATED);
63
- const checks = message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? [];
64
- assert.ok(checks.length > 40 && checks.length < 1000);
65
52
  }
66
53
 
67
54
  test("replace withholds anchors in progress and after commands change or remove the file", async (t) => {
@@ -98,16 +85,9 @@ test("replace withholds anchors in progress and after commands change or remove
98
85
  assert.equal(result.details.actionFusion.freshness, state);
99
86
  assert.equal(result.details.publication, "PUBLISHED");
100
87
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
101
- assert.deepEqual(result.content[1], {
102
- type: "text",
103
- text: staleTargetNotice(THEN_RUN_STALE),
104
- });
105
- assert.equal(
106
- result.content.filter(
107
- (block: any) => block.type === "text" && block.text.includes(THEN_RUN_STALE),
108
- ).length,
109
- 1,
110
- );
88
+ assert.equal(reportOf(result)?.freshness, state);
89
+ assert.equal(reportOf(result)?.next, REREAD);
90
+ assert.equal(result.content.length, 1);
111
91
  for (const update of updates)
112
92
  assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
113
93
  }
@@ -160,72 +140,75 @@ test("progress callback failures preserve publication and do not prevent the com
160
140
  fusion({
161
141
  toolCallId: "failed",
162
142
  absolutePath: join(dir, "failed"),
143
+ tool: "write",
144
+ displayPath: "failed",
163
145
  thenRun: { command: "check" },
164
146
  mutate: async () => {
165
- throw new FileMutationError("post_process", "PUBLISHED", "original failure");
147
+ throw new FileMutationError(
148
+ "POST_PROCESS_FAILED",
149
+ "post_process",
150
+ "PUBLISHED",
151
+ "original failure",
152
+ );
166
153
  },
167
154
  signal: undefined,
168
155
  ctx: await ctx(dir, t),
169
156
  }),
170
- (error: any) => error.publication === "PUBLISHED" && /original failure/.test(error.message),
157
+ (error: unknown) =>
158
+ error instanceof CommandNotRun &&
159
+ error.error instanceof FileMutationError &&
160
+ error.error.publication === "PUBLISHED" &&
161
+ /original failure/.test(error.error.message),
171
162
  );
172
163
  } finally {
173
164
  await rm(dir, { recursive: true, force: true });
174
165
  }
175
166
  });
176
167
 
177
- test("standalone and Fusion finalizers use commit freshness with or without anchors", async (t) => {
168
+ test("standalone and Fusion finalizers → take freshness from commit facts", async (t) => {
178
169
  const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
179
170
  try {
180
171
  for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
181
172
  for (const observedRevision of ["published", "external"]) {
182
- for (const anchors of [" ANCHOR", undefined]) {
183
- const mutation = {
184
- result: {
185
- content: [{ type: "text", text: "saved" }],
186
- details: {
187
- publication: "UNKNOWN",
188
- publishedRevision: "ignored",
189
- observedRevision: "ignored",
190
- },
191
- },
192
- commit: {
193
- publication,
194
- publishedRevision: "published",
195
- observedRevision,
196
- created: false,
197
- },
198
- anchors,
199
- } satisfies MutationOutcome<unknown>;
200
- const fresh = observedRevision === "published";
201
- assert.equal(commitFreshness(mutation.commit), fresh ? "unchanged" : "changed");
202
- const standalone = finalizeMutation(
203
- mutation,
204
- commitFreshness(mutation.commit) === "unchanged",
205
- );
206
- const fused = await createActionFusionExecutor()({
207
- toolCallId: "no-command",
208
- absolutePath: join(dir, "file"),
209
- thenRun: undefined,
210
- mutate: async () => mutation,
211
- signal: undefined,
212
- ctx: await ctx(dir, t),
213
- });
214
- const expectedContent = [{ type: "text", text: `saved${fresh ? (anchors ?? "") : ""}` }];
215
- if (!fresh) expectedContent.push({ type: "text", text: staleTargetNotice() });
216
- assert.deepEqual(standalone.content, expectedContent);
217
- assert.deepEqual(fused.content, expectedContent);
218
- assert.deepEqual(standalone.details, mutation.result.details);
219
- assert.deepEqual(fused.details, {
220
- ...mutation.result.details,
221
- actionFusion: {
222
- publication,
223
- command: "not_requested",
224
- freshness: fresh ? "unchanged" : "changed",
225
- },
226
- });
227
- assert.deepEqual(mutation.result.content, [{ type: "text", text: "saved" }]);
228
- }
173
+ const mutation = {
174
+ details: {
175
+ publication: "UNKNOWN",
176
+ publishedRevision: "ignored",
177
+ observedRevision: "ignored",
178
+ },
179
+ facts: {},
180
+ commit: {
181
+ publication,
182
+ baseRevision: "published",
183
+ publishedRevision: "published",
184
+ observedRevision,
185
+ created: false,
186
+ },
187
+ } satisfies MutationOutcome<object>;
188
+ const fresh = observedRevision === "published";
189
+ const observation = commitFreshness(mutation.commit);
190
+ assert.equal(observation.freshness, fresh ? "unchanged" : "changed");
191
+ const standalone = finalizeMutation("edit", "file", mutation, observation);
192
+ const fused = await createActionFusionExecutor()({
193
+ tool: "edit",
194
+ displayPath: "file",
195
+ toolCallId: "no-command",
196
+ absolutePath: join(dir, "file"),
197
+ thenRun: undefined,
198
+ mutate: async () => mutation,
199
+ signal: undefined,
200
+ ctx: await ctx(dir, t),
201
+ });
202
+ assert.deepEqual(fused.content, standalone.content);
203
+ assert.equal(standalone.details.publication, "UNKNOWN");
204
+ assert.equal(reportOf(standalone)?.publication, publication);
205
+ assert.equal(reportOf(fused)?.publication, publication);
206
+ assert.equal(reportOf(standalone)?.freshness, fresh ? undefined : "changed");
207
+ assert.deepEqual(mutation.details, {
208
+ publication: "UNKNOWN",
209
+ publishedRevision: "ignored",
210
+ observedRevision: "ignored",
211
+ });
229
212
  }
230
213
  }
231
214
  } finally {
@@ -233,91 +216,21 @@ test("standalone and Fusion finalizers use commit freshness with or without anch
233
216
  }
234
217
  });
235
218
 
236
- test("mutation anchor output and aggregate anchor diagnostics have byte budgets", async (t) => {
219
+ test("aggregate anchor diagnostics → respect their byte budgets", async (t) => {
237
220
  const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
238
221
  try {
239
222
  const path = join(dir, "long.txt");
240
- const long = "界".repeat(100000);
241
- const changedLines = [long, ...Array.from({ length: 79 }, (_, index) => `changed ${index}`)];
242
- for (const name of ["edit", "replace"]) {
243
- await writeFile(path, "before\n");
244
- const result =
245
- name === "edit"
246
- ? await invoke(
247
- makeEditOverride(dir, DEFAULT_CONFIG),
248
- name,
249
- { path, edits: [{ op: "append", body: changedLines }] },
250
- undefined,
251
- undefined,
252
- await ctx(dir, t),
253
- )
254
- : await invoke(
255
- makeReplaceTool(dir, DEFAULT_CONFIG),
256
- name,
257
- { path, replacements: [{ find: "before", replace: changedLines.join("\n") }] },
258
- undefined,
259
- undefined,
260
- await ctx(dir, t),
261
- );
262
- const output = text(result);
263
- const firstLine = name === "edit" ? 2 : 1;
264
- assert.deepEqual(
265
- output.match(/^\d+#[0-9A-Z]+$/gm),
266
- changedLines.map((line, index) => {
267
- const position = firstLine + index;
268
- return `${position}#${computeLineHash(position, line, 4)}`;
269
- }),
270
- );
271
- assert.doesNotMatch(output, /omitted|truncated|│/i);
272
- assert.equal(
273
- await readFile(path, "utf8"),
274
- (name === "edit" ? "before\n" : "") + changedLines.join("\n") + "\n",
275
- );
276
- await writeFile(path, `remove\n${long}\n`);
277
- const deleted =
278
- name === "edit"
279
- ? await invoke(
280
- makeEditOverride(dir, DEFAULT_CONFIG),
281
- name,
282
- { path, edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove", 4)}` }] },
283
- undefined,
284
- undefined,
285
- await ctx(dir, t),
286
- )
287
- : await invoke(
288
- makeReplaceTool(dir, DEFAULT_CONFIG),
289
- name,
290
- { path, replacements: [{ find: "remove\n", replace: "" }] },
291
- undefined,
292
- undefined,
293
- await ctx(dir, t),
294
- );
295
- const anchorStart = text(deleted).indexOf("\nUpdated anchors:");
296
- assert.ok(anchorStart >= 0);
297
- const anchorBlock = text(deleted).slice(anchorStart);
298
- assert.ok(Buffer.byteLength(anchorBlock) <= MAX_BLOCK_BYTES);
299
- assert.match(text(deleted), ANCHORS_OMITTED);
300
- assert.doesNotMatch(text(deleted), /^\d+#[0-9A-Z]+/m);
301
- }
302
223
  await writeFile(path, "current\n");
303
- await assert.rejects(
304
- invoke(
305
- makeEditOverride(dir, DEFAULT_CONFIG),
306
- "errors",
307
- {
308
- path,
309
- edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })),
310
- },
311
- undefined,
312
- undefined,
313
- await ctx(dir, t),
314
- ),
315
- (error: Error) => {
316
- assertFailureByteBudgets(error.message);
317
- assert.match(error.message, /omitted|truncated/i);
318
- return true;
319
- },
224
+ const failure = await invoke(
225
+ makeEditOverride(dir, DEFAULT_CONFIG),
226
+ "errors",
227
+ { path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })) },
228
+ undefined,
229
+ undefined,
230
+ await ctx(dir, t),
320
231
  );
232
+ assert.equal(failure.isError, true);
233
+ assertFailureByteBudgets(text(failure));
321
234
  } finally {
322
235
  await rm(dir, { recursive: true, force: true });
323
236
  }
@@ -363,7 +276,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
363
276
  callTool(tool, args, { ctx: await ctx(dir, t) }),
364
277
  (error: unknown) =>
365
278
  error instanceof Error &&
366
- error.message.startsWith(`Invalid argument ${field}: INVALID_UNICODE:`) &&
279
+ rejectsArgument(field, /encoded losslessly/)(error) &&
367
280
  !("publication" in error),
368
281
  );
369
282
  assert.equal(await readFile(path, "utf8"), "original\n");
@@ -382,29 +295,27 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
382
295
  const lines = Array.from({ length: 100 }, () => "same");
383
296
  lines[49] = "different";
384
297
  await writeFile(path, lines.join("\n"));
385
- await assert.rejects(
386
- invoke(
387
- makeEditOverride(dir, DEFAULT_CONFIG),
388
- "ambiguous",
389
- {
390
- path,
391
- edits: Array.from({ length: 1000 }, () => ({
392
- op: "delete",
393
- anchor: `50#${computeLineHash(50, "same", 4)}`,
394
- })),
395
- },
396
- undefined,
397
- undefined,
398
- await ctx(dir, t),
399
- ),
400
- (error: Error) => {
401
- assertFailureByteBudgets(error.message);
402
- assert.match(error.message, /ambiguous checksum matches/);
403
- assert.match(error.message, /candidates omitted/);
404
- assert.doesNotMatch(error.message, /same content/);
405
- return true;
298
+ const failure = await invoke(
299
+ makeEditOverride(dir, DEFAULT_CONFIG),
300
+ "ambiguous",
301
+ {
302
+ path,
303
+ edits: Array.from({ length: 1000 }, () => ({
304
+ op: "delete",
305
+ anchor: `50#${computeLineHash(50, "same", 4)}`,
306
+ })),
406
307
  },
308
+ undefined,
309
+ undefined,
310
+ await ctx(dir, t),
311
+ );
312
+ assert.equal(failure.isError, true);
313
+ assertFailureByteBudgets(text(failure));
314
+ const report = reportOf(failure);
315
+ assert.ok(
316
+ report?.failures?.every((entry) => entry.result === "ambiguous" && entry.omittedCandidates),
407
317
  );
318
+ assert.doesNotMatch(text(failure), /same content/);
408
319
  } finally {
409
320
  await rm(dir, { recursive: true, force: true });
410
321
  }
@@ -450,7 +361,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
450
361
  callTool(tool, args, { ctx: await ctx(dir, t) }),
451
362
  (error: unknown) =>
452
363
  error instanceof Error &&
453
- error.message.startsWith(`Invalid argument ${field}: UNSUPPORTED_TEXT: NUL`) &&
364
+ rejectsArgument(field, /NUL/)(error) &&
454
365
  !("publication" in error),
455
366
  );
456
367
  assert.equal(await readFile(path, "utf8"), "original\n");
@@ -477,21 +388,19 @@ test("Fusion skips the command when a replacement produces unencodable text", as
477
388
  },
478
389
  (event) => events.push(event.command),
479
390
  );
480
- await assert.rejects(
481
- callTool(
482
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
483
- {
484
- path,
485
- replacements: [{ find: "^.", replace: "x", regex: true }],
486
- then_run: { command: "check" },
487
- },
488
- { ctx: await ctx(dir, t) },
489
- ),
490
- (error: any) =>
491
- error.publication === "NOT_PUBLISHED" &&
492
- error.command === "skipped" &&
493
- /INVALID_UNICODE/.test(error.message),
391
+ const result = await callTool(
392
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
393
+ {
394
+ path,
395
+ replacements: [{ find: "^.", replace: "x", regex: true }],
396
+ then_run: { command: "check" },
397
+ },
398
+ { ctx: await ctx(dir, t) },
494
399
  );
400
+ assert.equal(result.isError, true);
401
+ assert.equal(reportOf(result)?.error, "INVALID_UNICODE");
402
+ assert.equal(reportOf(result)?.publication, "NOT_PUBLISHED");
403
+ assert.equal(reportOf(result)?.then_run?.status, "skipped");
495
404
  assert.deepEqual(events, ["waiting", "skipped"]);
496
405
  assert.equal(await readFile(path, "utf8"), before);
497
406
  assert.equal(commands, 0);
@@ -500,12 +409,12 @@ test("Fusion skips the command when a replacement produces unencodable text", as
500
409
  }
501
410
  });
502
411
 
503
- test("shared result building preserves publication and appends anchors only to the summary", () => {
412
+ test("result generation failure → preserves publication and cause", () => {
504
413
  for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
505
414
  const cause = new Error("render failed");
506
415
  assert.throws(
507
416
  () =>
508
- postProcessMutation("replace", publication, () => {
417
+ postProcessMutation(publication, () => {
509
418
  throw cause;
510
419
  }),
511
420
  (error: any) =>
@@ -515,23 +424,6 @@ test("shared result building preserves publication and appends anchors only to t
515
424
  error.cause === cause,
516
425
  );
517
426
  }
518
- const result = {
519
- content: [
520
- { type: "text" as const, text: "summary" },
521
- { type: "text" as const, text: "command" },
522
- ],
523
- details: {},
524
- };
525
- const outcome = publishedMutation("saved", result, " ANCHOR");
526
- assert.deepEqual(
527
- finalizeMutation(outcome, true).content.map((block: any) => block.text),
528
- ["summary ANCHOR", "command"],
529
- );
530
- assert.deepEqual(finalizeMutation(outcome, false).content, [
531
- ...result.content,
532
- { type: "text", text: staleTargetNotice() },
533
- ]);
534
- assert.equal(result.content[0].text, "summary");
535
427
  });
536
428
 
537
429
  type Fusion = Parameters<typeof makeWriteOverride>[1];
@@ -577,7 +469,7 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
577
469
  undefined,
578
470
  await ctx(dir, t),
579
471
  );
580
- assert.match(text(result), /no net change/);
472
+ assert.equal(reportOf(result)?.publication, "NOT_PUBLISHED");
581
473
  assert.equal(result.details.publication, "NOT_PUBLISHED");
582
474
  const revision = byteRevision(Buffer.from("same\n"));
583
475
  for (const key of ["baseRevision", "publishedRevision", "observedRevision"])
@@ -654,200 +546,3 @@ test("no-op Fusion still detects external changes and reports command failures",
654
546
  await rm(dir, { recursive: true, force: true });
655
547
  }
656
548
  });
657
-
658
- test("mutation anchors omit unchanged positions across distant changes", async (t) => {
659
- const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delta-"));
660
- try {
661
- const before = Array.from({ length: 100 }, (_, index) => `row ${index + 1}`);
662
- const after = [...before];
663
- after[0] = "changed first";
664
- after[99] = "changed last";
665
- for (const name of ["edit", "replace"]) {
666
- const path = join(dir, `${name}.txt`);
667
- await writeFile(path, before.join("\r\n") + "\r\n");
668
- const result =
669
- name === "edit"
670
- ? await invoke(
671
- makeEditOverride(dir, DEFAULT_CONFIG),
672
- name,
673
- {
674
- path,
675
- edits: [
676
- {
677
- op: "replace",
678
- anchor: `1#${computeLineHash(1, before[0], 4)}`,
679
- end: `100#${computeLineHash(100, before[99], 4)}`,
680
- body: after,
681
- },
682
- ],
683
- },
684
- undefined,
685
- undefined,
686
- await ctx(dir, t),
687
- )
688
- : await invoke(
689
- makeReplaceTool(dir, DEFAULT_CONFIG),
690
- name,
691
- {
692
- path,
693
- replacements: [
694
- { find: before[0] + "\r\n", replace: after[0] + "\r\n" },
695
- { find: before[99], replace: after[99] },
696
- ],
697
- },
698
- undefined,
699
- undefined,
700
- await ctx(dir, t),
701
- );
702
- const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
703
- assert.deepEqual(returned, [
704
- `1#${computeLineHash(1, after[0], 4)}`,
705
- `100#${computeLineHash(100, after[99], 4)}`,
706
- ]);
707
- assert.doesNotMatch(text(result), /omitted/);
708
- // An omitted stable row keeps its old anchor; a changed row uses the returned anchor.
709
- await invoke(
710
- makeEditOverride(dir, DEFAULT_CONFIG),
711
- "chain",
712
- {
713
- path,
714
- edits: [
715
- {
716
- op: "replace",
717
- anchor: `50#${computeLineHash(50, before[49], 4)}`,
718
- body: ["stable anchor reused"],
719
- },
720
- { op: "replace", anchor: returned[1], body: ["fresh anchor reused"] },
721
- ],
722
- },
723
- undefined,
724
- undefined,
725
- await ctx(dir, t),
726
- );
727
- const final = (await readFile(path, "utf8")).split("\r\n");
728
- assert.equal(final[49], "stable anchor reused");
729
- assert.equal(final[99], "fresh anchor reused");
730
- }
731
- } finally {
732
- await rm(dir, { recursive: true, force: true });
733
- }
734
- });
735
-
736
- test("mutation anchors retain a deletion successor but omit stable rows and deleted EOF", async (t) => {
737
- const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delete-"));
738
- try {
739
- for (const name of ["edit", "replace"]) {
740
- for (const atEnd of [false, true]) {
741
- for (const ending of ["\n", "\r\n"]) {
742
- const path = join(dir, `${name}.txt`);
743
- const lines = atEnd ? ["a", "c", "remove"] : ["a", "remove", "c", "d"];
744
- await writeFile(path, lines.join(ending) + ending);
745
- const line = atEnd ? 3 : 2;
746
- const result =
747
- name === "edit"
748
- ? await invoke(
749
- makeEditOverride(dir, DEFAULT_CONFIG),
750
- name,
751
- {
752
- path,
753
- edits: [
754
- { op: "delete", anchor: `${line}#${computeLineHash(line, "remove", 4)}` },
755
- ],
756
- },
757
- undefined,
758
- undefined,
759
- await ctx(dir, t),
760
- )
761
- : await invoke(
762
- makeReplaceTool(dir, DEFAULT_CONFIG),
763
- name,
764
- { path, replacements: [{ find: "remove\n", replace: "" }] },
765
- undefined,
766
- undefined,
767
- await ctx(dir, t),
768
- );
769
- const rows = text(result)
770
- .split("\n")
771
- .filter((row) => /^\d+#/.test(row));
772
- assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c", 4)}│c`]);
773
- assert.deepEqual(
774
- await readFile(path),
775
- Buffer.from(lines.filter((_, index) => index !== line - 1).join(ending) + ending),
776
- );
777
- }
778
- }
779
- }
780
- } finally {
781
- await rm(dir, { recursive: true, force: true });
782
- }
783
- });
784
-
785
- test("mutation anchors retain deletion successor even when deleted line content matches the successor", async (t) => {
786
- const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-matching-delete-"));
787
- try {
788
- const path = join(dir, "edit.txt");
789
- const lines = ["a", "duplicate", "duplicate", "d"];
790
- await writeFile(path, lines.join("\n") + "\n");
791
- const tool = makeEditOverride(dir, DEFAULT_CONFIG);
792
- const result = await invoke(
793
- tool,
794
- "edit",
795
- {
796
- path,
797
- edits: [{ op: "delete", anchor: `2#${computeLineHash(2, "duplicate", 4)}` }],
798
- },
799
- undefined,
800
- undefined,
801
- await ctx(dir, t),
802
- );
803
- const rows = text(result)
804
- .split("\n")
805
- .filter((row) => /^\d+#/.test(row));
806
- assert.deepEqual(rows, [`2#${computeLineHash(2, "duplicate", 4)}│duplicate`]);
807
- } finally {
808
- await rm(dir, { recursive: true, force: true });
809
- }
810
- });
811
-
812
- test("oversized deletion successors do not suppress later editable anchors", async (t) => {
813
- const dir = await mkdtemp(join(tmpdir(), "hashline-skip-long-anchor-"));
814
- try {
815
- const path = join(dir, "fixture.txt");
816
- const long = "x".repeat(MAX_BLOCK_BYTES + 1);
817
- await writeFile(path, `remove\n${long}\nold\n`);
818
- const tool = makeEditOverride(dir, DEFAULT_CONFIG);
819
- const result = await invoke(
820
- tool,
821
- "skip",
822
- {
823
- path,
824
- edits: [
825
- { op: "delete", anchor: `1#${computeLineHash(1, "remove", 4)}` },
826
- { op: "replace", anchor: `3#${computeLineHash(3, "old", 4)}`, body: ["new"] },
827
- ],
828
- },
829
- undefined,
830
- undefined,
831
- await ctx(dir, t),
832
- );
833
- const output = text(result);
834
- assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
835
- const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
836
- assert.equal(anchor, `2#${computeLineHash(2, "new", 4)}`);
837
- assert.match(output, ANCHORS_OMITTED);
838
- assert.ok(
839
- Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= MAX_BLOCK_BYTES,
840
- );
841
- await invoke(
842
- tool,
843
- "retry",
844
- { path, edits: [{ op: "replace", anchor, body: ["verified"] }] },
845
- undefined,
846
- undefined,
847
- await ctx(dir, t),
848
- );
849
- assert.equal(await readFile(path, "utf8"), `${long}\nverified\n`);
850
- } finally {
851
- await rm(dir, { recursive: true, force: true });
852
- }
853
- });