@criogaid/pi-hashline-edit 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -7,12 +7,13 @@ import { writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { test } from "node:test";
10
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
10
+ import { DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
11
11
  import { createActionFusionExecutor } from "./action-fusion.ts";
12
12
  import { makeReplaceTool } from "./replace-tool.ts";
13
13
  import { makeWriteOverride } from "./write-tool.ts";
14
14
  import { makeEditOverride } from "./edit-tool.ts";
15
- import { byteRevision, commitFreshness, FileMutationError } from "./file-commit.ts";
15
+ import { commitFreshness, FileMutationError } from "./file-commit.ts";
16
+ import { byteRevision } from "./file-revision.ts";
16
17
  import { finalizeMutation, postProcessMutation, type MutationOutcome } from "./mutation-result.ts";
17
18
  import { CommandNotRun, decodeReport, reportOf } from "./report.ts";
18
19
  import { REREAD } from "./report-schema.ts";
@@ -31,15 +32,20 @@ const invoke = (
31
32
  context?: unknown,
32
33
  ) => callTool(tool, args, { toolCallId, signal, onUpdate, ctx: context });
33
34
 
35
+ const anchorBudget = outputBudgetsFor(4096);
36
+ const anchorBatchSize: unknown = Reflect.get(
37
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.edits,
38
+ "maxItems",
39
+ );
40
+ assert.ok(typeof anchorBatchSize === "number");
41
+
34
42
  function assertFailureByteBudgets(message: string): void {
35
- const report = decodeReport(message);
43
+ const report = decodeReport(message, "edit");
36
44
  assert.ok(report);
37
45
  assert.equal(report.error, "ANCHOR_MISMATCH");
38
46
  assert.ok(report.failures && report.failures.length > 0);
39
- assert.ok(
40
- Buffer.byteLength(JSON.stringify(report.failures)) <= DEFAULT_OUTPUT_BUDGETS.blockBytes,
41
- );
42
- assert.equal(report.failures.length + (report.omittedFailures ?? 0), 1000);
47
+ assert.ok(Buffer.byteLength(JSON.stringify(report.failures)) <= anchorBudget.blockBytes);
48
+ assert.equal(report.failures.length + (report.omittedFailures ?? 0), anchorBatchSize);
43
49
  assert.ok(report.omittedFailures);
44
50
  assert.equal(report.matched, undefined);
45
51
  assert.equal(report.omittedMatched, undefined);
@@ -47,49 +53,70 @@ function assertFailureByteBudgets(message: string): void {
47
53
  if (report.candidateNeighborhoods) {
48
54
  const rows = report.candidateNeighborhoods.flatMap((group) => group.rows);
49
55
  assert.ok(rows.length > 0);
50
- assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
56
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= anchorBudget.blockBytes);
51
57
  }
52
58
  }
53
59
 
54
- test("replace withholds anchors in progress and after commands change or remove the file", async (t) => {
60
+ test("edit and replace commands change or remove the file → withhold anchors and report freshness", async (t) => {
55
61
  const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
56
62
  try {
57
- for (const state of ["changed", "missing", "unknown"] as const) {
58
- for (const fails of [false, true]) {
59
- const path = join(dir, `${state}-${fails}.txt`);
60
- await writeFile(path, "before\n");
61
- const updates: any[] = [];
62
- const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
63
- if (state === "changed") await writeFile(path, "command output\n");
64
- else {
65
- await rm(path);
66
- if (state === "unknown") await mkdir(path);
67
- }
68
- onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
69
- if (fails) throw new Error("command failed");
70
- return { status: "succeeded", output: "done" };
71
- });
72
- const result = await invoke(
73
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
74
- "replace",
75
- {
76
- path,
77
- replacements: [{ find: "before", replace: "after" }],
78
- then_run: { command: "check" },
79
- },
80
- undefined,
81
- (update: any) => updates.push(update),
82
- await ctx(dir, t),
83
- );
84
- assert.ok(result.details.actionFusion);
85
- assert.equal(result.details.actionFusion.freshness, state);
86
- assert.equal(result.details.publication, "PUBLISHED");
87
- assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
88
- assert.equal(reportOf(result)?.freshness, state);
89
- assert.equal(reportOf(result)?.next, REREAD);
90
- assert.equal(result.content.length, 1);
91
- for (const update of updates)
92
- assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
63
+ const context = await ctx(dir, t);
64
+ for (const toolName of ["edit", "replace"] as const) {
65
+ for (const state of ["changed", "missing", "unknown"] as const) {
66
+ for (const fails of [false, true]) {
67
+ const path = join(dir, `${toolName}-${state}-${fails}.txt`);
68
+ await writeFile(path, "before\n");
69
+ const updates: AgentToolResult<unknown>[] = [];
70
+ const fusion = createActionFusionExecutor(
71
+ async (_id, _input, _signal, _ctx, onUpdate) => {
72
+ if (state === "changed") await writeFile(path, "command output\n");
73
+ else {
74
+ await rm(path);
75
+ if (state === "unknown") await mkdir(path);
76
+ }
77
+ onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
78
+ if (fails) throw new Error("command failed");
79
+ return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
80
+ },
81
+ );
82
+ const tool =
83
+ toolName === "edit"
84
+ ? makeEditOverride(dir, DEFAULT_CONFIG, fusion)
85
+ : makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
86
+ const args =
87
+ toolName === "edit"
88
+ ? {
89
+ edits: [
90
+ {
91
+ action: "replace",
92
+ anchor: `1#${computeLineHash(1, "before", DEFAULT_CONFIG.hashLen)}`,
93
+ body: ["after"],
94
+ },
95
+ ],
96
+ }
97
+ : { replacements: [{ literal: true, find: "before", replace: "after" }] };
98
+ const result = await callTool(
99
+ tool,
100
+ { path, ...args, then_run: { command: "check" } },
101
+ {
102
+ onUpdate: (update: AgentToolResult<unknown>) => updates.push(update),
103
+ ctx: context,
104
+ },
105
+ );
106
+ assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
107
+ const report = reportOf(result, toolName);
108
+ assert.equal(report?.freshness, state);
109
+ assert.equal(report?.publication, "PUBLISHED");
110
+ assert.equal(report?.next, REREAD);
111
+ assert.equal(report?.then_run?.status, fails ? "failed" : "succeeded");
112
+ assert.equal(result.content.length, 1);
113
+ assert.ok(updates.length > 0);
114
+ for (const update of updates)
115
+ assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
116
+ if (state === "changed") assert.equal(await readFile(path, "utf8"), "command output\n");
117
+ else if (state === "missing") await assert.rejects(stat(path), { code: "ENOENT" });
118
+ else assert.equal((await stat(path)).isDirectory(), true);
119
+ }
93
120
  }
94
121
  }
95
122
  } finally {
@@ -108,7 +135,7 @@ test("progress callback failures preserve publication and do not prevent the com
108
135
  const fusion = createActionFusionExecutor(
109
136
  async () => {
110
137
  commands++;
111
- return { status: "succeeded", output: "done" };
138
+ return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
112
139
  },
113
140
  callback === "reporter" ? fail : undefined,
114
141
  );
@@ -128,9 +155,8 @@ test("progress callback failures preserve publication and do not prevent the com
128
155
  );
129
156
  assert.equal(commands, 1);
130
157
  assert.equal(await readFile(path, "utf8"), "saved\n");
131
- assert.ok(result.details.actionFusion);
132
- assert.equal(result.details.actionFusion.publication, "PUBLISHED");
133
- assert.equal(result.details.actionFusion.command, "succeeded");
158
+ assert.equal(reportOf(result, "write")?.publication, "PUBLISHED");
159
+ assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
134
160
  assert.match(text(result), /display unavailable/);
135
161
  }
136
162
  const fusion = createActionFusionExecutor(undefined, () => {
@@ -138,6 +164,7 @@ test("progress callback failures preserve publication and do not prevent the com
138
164
  });
139
165
  await assert.rejects(
140
166
  fusion({
167
+ budget: DEFAULT_OUTPUT_BUDGETS,
141
168
  toolCallId: "failed",
142
169
  absolutePath: join(dir, "failed"),
143
170
  tool: "write",
@@ -156,59 +183,84 @@ test("progress callback failures preserve publication and do not prevent the com
156
183
  }),
157
184
  (error: unknown) =>
158
185
  error instanceof CommandNotRun &&
159
- error.error instanceof FileMutationError &&
160
- error.error.publication === "PUBLISHED" &&
161
- /original failure/.test(error.error.message),
186
+ error.cause instanceof FileMutationError &&
187
+ error.cause.publication === "PUBLISHED" &&
188
+ /original failure/.test(error.cause.message),
162
189
  );
163
190
  } finally {
164
191
  await rm(dir, { recursive: true, force: true });
165
192
  }
166
193
  });
167
194
 
168
- test("standalone and Fusion finalizers → take freshness from commit facts", async (t) => {
195
+ test("standalone and Fusion finalizers → take publication and freshness from commit facts, independent of diff", async (t) => {
169
196
  const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
170
197
  try {
198
+ const path = join(dir, "file");
199
+ const context = await ctx(dir, t);
200
+ const publishedRevision = byteRevision(Buffer.from("published\n"));
171
201
  for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
172
- for (const observedRevision of ["published", "external"]) {
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
- });
202
+ for (const content of ["published\n", "external\n"]) {
203
+ await writeFile(path, content);
204
+ for (const details of [{}, { diff: "" }]) {
205
+ const expectedDetails = structuredClone(details);
206
+ const mutation = {
207
+ details,
208
+ facts: {},
209
+ commit: {
210
+ publication,
211
+ publishedRevision,
212
+ observedRevision: byteRevision(Buffer.from(content)),
213
+ created: false,
214
+ },
215
+ } satisfies MutationOutcome<object>;
216
+ const fresh = content === "published\n";
217
+ const observation = commitFreshness(mutation.commit);
218
+ assert.equal(observation.freshness, fresh ? "unchanged" : "changed");
219
+ const standalone = finalizeMutation(
220
+ "edit",
221
+ path,
222
+ mutation,
223
+ observation,
224
+ undefined,
225
+ DEFAULT_OUTPUT_BUDGETS,
226
+ );
227
+ assert.equal(reportOf(standalone, "edit")?.publication, publication);
228
+ assert.equal(reportOf(standalone, "edit")?.freshness, fresh ? undefined : "changed");
229
+ for (const thenRun of [undefined, { command: "check" }]) {
230
+ let commands = 0;
231
+ const fused = await createActionFusionExecutor(async () => {
232
+ commands++;
233
+ return {
234
+ status: "succeeded",
235
+ result: { content: [{ type: "text", text: "checked" }] },
236
+ };
237
+ })({
238
+ budget: DEFAULT_OUTPUT_BUDGETS,
239
+ tool: "edit",
240
+ displayPath: path,
241
+ toolCallId: "commit-facts",
242
+ absolutePath: path,
243
+ thenRun,
244
+ mutate: async () => mutation,
245
+ signal: undefined,
246
+ ctx: context,
247
+ });
248
+ if (!thenRun) assert.deepEqual(fused.content, standalone.content);
249
+ assert.equal(fused.content.length, 1);
250
+ const report = reportOf(fused, "edit");
251
+ assert.equal(report?.publication, publication);
252
+ assert.equal(report?.freshness, fresh ? undefined : "changed");
253
+ assert.equal(
254
+ report?.then_run?.status,
255
+ thenRun ? (fresh ? "succeeded" : "skipped") : undefined,
256
+ );
257
+ assert.equal(commands, thenRun && fresh ? 1 : 0);
258
+ for (const [key, value] of Object.entries(expectedDetails))
259
+ assert.deepEqual(Reflect.get(fused.details, key), value);
260
+ assert.equal(await readFile(path, "utf8"), content);
261
+ }
262
+ assert.deepEqual(mutation.details, expectedDetails);
263
+ }
212
264
  }
213
265
  }
214
266
  } finally {
@@ -222,9 +274,15 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
222
274
  const path = join(dir, "long.txt");
223
275
  await writeFile(path, "current\n");
224
276
  const failure = await invoke(
225
- makeEditOverride(dir, DEFAULT_CONFIG),
277
+ makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
226
278
  "errors",
227
- { path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })) },
279
+ {
280
+ path,
281
+ edits: Array.from({ length: anchorBatchSize }, () => ({
282
+ action: "delete",
283
+ anchor: "1#XXXX",
284
+ })),
285
+ },
228
286
  undefined,
229
287
  undefined,
230
288
  await ctx(dir, t),
@@ -244,7 +302,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
244
302
  const fusion = createActionFusionExecutor(
245
303
  async () => {
246
304
  commands++;
247
- return { status: "succeeded", output: "done" };
305
+ return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
248
306
  },
249
307
  (event) => events.push(event.command),
250
308
  );
@@ -253,14 +311,18 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
253
311
  const cases = [
254
312
  {
255
313
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
256
- args: { path, edits: [{ op: "append", body: ["\ud800"] }], then_run: { command: "check" } },
314
+ args: {
315
+ path,
316
+ edits: [{ action: "append", body: ["\ud800"] }],
317
+ then_run: { command: "check" },
318
+ },
257
319
  field: "edits[0].body[0]",
258
320
  },
259
321
  {
260
322
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
261
323
  args: {
262
324
  path,
263
- replacements: [{ find: "original", replace: "\udfff" }],
325
+ replacements: [{ literal: true, find: "original", replace: "\udfff" }],
264
326
  then_run: { command: "check" },
265
327
  },
266
328
  field: "replacements[0].replace",
@@ -296,12 +358,12 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
296
358
  lines[49] = "different";
297
359
  await writeFile(path, lines.join("\n"));
298
360
  const failure = await invoke(
299
- makeEditOverride(dir, DEFAULT_CONFIG),
361
+ makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
300
362
  "ambiguous",
301
363
  {
302
364
  path,
303
- edits: Array.from({ length: 1000 }, () => ({
304
- op: "delete",
365
+ edits: Array.from({ length: anchorBatchSize }, () => ({
366
+ action: "delete",
305
367
  anchor: `50#${computeLineHash(50, "same", 4)}`,
306
368
  })),
307
369
  },
@@ -311,7 +373,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
311
373
  );
312
374
  assert.equal(failure.isError, true);
313
375
  assertFailureByteBudgets(text(failure));
314
- const report = reportOf(failure);
376
+ const report = reportOf(failure, "edit");
315
377
  assert.ok(
316
378
  report?.failures?.every((entry) => entry.result === "ambiguous" && entry.omittedCandidates),
317
379
  );
@@ -331,21 +393,21 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
331
393
  const fusion = createActionFusionExecutor(
332
394
  async () => {
333
395
  commands++;
334
- return { status: "succeeded", output: "unexpected" };
396
+ return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
335
397
  },
336
398
  (event) => events.push(event.command),
337
399
  );
338
400
  const cases = [
339
401
  {
340
402
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
341
- args: { path, edits: [{ op: "append", body: ["\0"] }], then_run: { command: "check" } },
403
+ args: { path, edits: [{ action: "append", body: ["\0"] }], then_run: { command: "check" } },
342
404
  field: "edits[0].body[0]",
343
405
  },
344
406
  {
345
407
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
346
408
  args: {
347
409
  path,
348
- replacements: [{ find: "original", replace: "\0" }],
410
+ replacements: [{ literal: true, find: "original", replace: "\0" }],
349
411
  then_run: { command: "check" },
350
412
  },
351
413
  field: "replacements[0].replace",
@@ -384,7 +446,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
384
446
  const fusion = createActionFusionExecutor(
385
447
  async () => {
386
448
  commands++;
387
- return { status: "succeeded", output: "unexpected" };
449
+ return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
388
450
  },
389
451
  (event) => events.push(event.command),
390
452
  );
@@ -392,15 +454,15 @@ test("Fusion skips the command when a replacement produces unencodable text", as
392
454
  makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
393
455
  {
394
456
  path,
395
- replacements: [{ find: "^.", replace: "x", regex: true }],
457
+ replacements: [{ find: "^.", replace: "x", literal: false }],
396
458
  then_run: { command: "check" },
397
459
  },
398
460
  { ctx: await ctx(dir, t) },
399
461
  );
400
462
  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");
463
+ assert.equal(reportOf(result, "replace")?.error, "INVALID_UNICODE");
464
+ assert.equal(reportOf(result, "replace")?.publication, "NOT_PUBLISHED");
465
+ assert.equal(reportOf(result, "replace")?.then_run?.status, "skipped");
404
466
  assert.deepEqual(events, ["waiting", "skipped"]);
405
467
  assert.equal(await readFile(path, "utf8"), before);
406
468
  assert.equal(commands, 0);
@@ -433,7 +495,7 @@ const noOpCases = [
433
495
  params: {
434
496
  edits: [
435
497
  {
436
- op: "replace",
498
+ action: "replace",
437
499
  anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
438
500
  body: ["same"],
439
501
  },
@@ -442,7 +504,7 @@ const noOpCases = [
442
504
  },
443
505
  {
444
506
  makeTool: (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
445
- params: { replacements: [{ find: "same", replace: "same" }] },
507
+ params: { replacements: [{ literal: true, find: "same", replace: "same" }] },
446
508
  },
447
509
  { makeTool: makeWriteOverride, params: { content: "same\n", mode: "overwrite" } },
448
510
  ];
@@ -458,7 +520,7 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
458
520
  let commands = 0;
459
521
  const fusion = createActionFusionExecutor(async () => {
460
522
  commands++;
461
- return { status: "succeeded", output: "checked" };
523
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
462
524
  });
463
525
  const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
464
526
  const result = await invoke(
@@ -469,21 +531,14 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
469
531
  undefined,
470
532
  await ctx(dir, t),
471
533
  );
472
- assert.equal(reportOf(result)?.publication, "NOT_PUBLISHED");
473
- assert.equal(result.details.publication, "NOT_PUBLISHED");
474
- const revision = byteRevision(Buffer.from("same\n"));
475
- for (const key of ["baseRevision", "publishedRevision", "observedRevision"])
476
- assert.equal(result.details[key], revision);
477
- assert.equal("revision" in result.details, false);
534
+ assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
535
+ assert.equal(reportOf(result, tool.name)?.freshness, undefined);
478
536
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
479
537
  assert.equal(commands, mode === "command" ? 1 : 0);
480
- if (mode !== "standalone") {
481
- assert.equal(
482
- result.details.actionFusion.command,
483
- mode === "command" ? "succeeded" : "not_requested",
484
- );
485
- assert.equal(result.details.actionFusion.freshness, "unchanged");
486
- }
538
+ assert.equal(
539
+ reportOf(result, tool.name)?.then_run?.status,
540
+ mode === "command" ? "succeeded" : undefined,
541
+ );
487
542
  const after = await stat(path);
488
543
  assert.deepEqual(
489
544
  [after.ino, after.mtimeMs, after.ctimeMs],
@@ -510,7 +565,7 @@ test("no-op Fusion still detects external changes and reports command failures",
510
565
  commands++;
511
566
  if (scenario === "failed") throw new Error("check failed");
512
567
  await writeFile(path, "external\n");
513
- return { status: "succeeded", output: "done" };
568
+ return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
514
569
  },
515
570
  (progress) => {
516
571
  if (
@@ -530,15 +585,15 @@ test("no-op Fusion still detects external changes and reports command failures",
530
585
  undefined,
531
586
  await ctx(dir, t),
532
587
  );
533
- assert.equal(result.details.publication, "NOT_PUBLISHED");
588
+ assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
534
589
  assert.equal(commands, scenario === "before" ? 0 : 1);
535
590
  assert.equal(
536
- result.details.actionFusion.command,
591
+ reportOf(result, tool.name)?.then_run?.status,
537
592
  scenario === "before" ? "skipped" : scenario === "failed" ? "failed" : "succeeded",
538
593
  );
539
594
  assert.equal(
540
- result.details.actionFusion.freshness,
541
- scenario === "failed" ? "unchanged" : "changed",
595
+ reportOf(result, tool.name)?.freshness,
596
+ scenario === "failed" ? undefined : "changed",
542
597
  );
543
598
  }
544
599
  }
@@ -1,5 +1,8 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import childProcess from "node:child_process";
4
+ import { syncBuiltinESMExports } from "node:module";
5
+ import { Readable } from "node:stream";
3
6
  import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
4
7
  import { fileURLToPath } from "node:url";
5
8
  import { HashlineError } from "../core/errors.ts";
@@ -42,16 +45,39 @@ async function parseListing(chunks: readonly string[], maxLines = 10, stop = fal
42
45
  return { files, result };
43
46
  }
44
47
 
45
- test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async () => {
46
- const listing =
47
- "dir\nfile.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n";
48
- const { files, result } = await parseListing([...listing]);
49
- assert.deepEqual(files, [
50
- { path: "dir\nfile.txt", lines: [1, 2, 10] },
51
- { path: "other.txt", lines: [3] },
52
- ]);
53
- assert.equal(result.code, 0);
54
- assert.equal(result.stopped, false);
48
+ test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async (t) => {
49
+ const listing = Buffer.from(
50
+ "dir\n文件.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n",
51
+ );
52
+ const spawn = childProcess.spawn;
53
+ let chunks: Buffer[] = [];
54
+ try {
55
+ t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
56
+ const child = spawn(...args);
57
+ assert.ok(child.stdout);
58
+ const stream = Readable.from(chunks);
59
+ t.mock.method(child.stdout, Symbol.asyncIterator, () => stream[Symbol.asyncIterator]());
60
+ return child;
61
+ });
62
+ syncBuiltinESMExports();
63
+ for (let split = 1; split < listing.length; split++) {
64
+ chunks = [listing.subarray(0, split), listing.subarray(split)];
65
+ const { files, result } = await parseListing([]);
66
+ assert.deepEqual(
67
+ files,
68
+ [
69
+ { path: "dir\n文件.txt", lines: [1, 2, 10] },
70
+ { path: "other.txt", lines: [3] },
71
+ ],
72
+ `split=${split}`,
73
+ );
74
+ assert.equal(result.code, 0);
75
+ assert.equal(result.stopped, false);
76
+ }
77
+ } finally {
78
+ t.mock.restoreAll();
79
+ syncBuiltinESMExports();
80
+ }
55
81
  });
56
82
 
57
83
  test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
@@ -12,15 +12,21 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
12
  import type { Readable } from "node:stream";
13
13
  import { HashlineError } from "../core/errors.ts";
14
14
  import { throwIfCancelled } from "./error-text.ts";
15
+ import { formatByteSize } from "./budgets.ts";
15
16
 
16
- export const COMMON_RG_ARGS = ["--no-config", "--color=never"];
17
+ /**
18
+ * Every rg run visits input roots in caller order and sorts each directory's entries.
19
+ * This is deterministic traversal, not global full-path sorting. rg walks in one thread;
20
+ * matching stays parallel in grep-search's workers.
21
+ */
22
+ export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
17
23
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
18
- const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB.`;
24
+ const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${formatByteSize(MAX_RG_RECORD_BYTES)}.`;
19
25
  /**
20
26
  * A ripgrep process or output-protocol failure. A finished run contributes its
21
27
  * exit code and, as the cause, its stderr.
22
28
  */
23
- export function ripgrepFailure(
29
+ function ripgrepFailure(
24
30
  message: string,
25
31
  run?: { readonly code: number | null; readonly stderr: string } | { readonly error: unknown },
26
32
  ): HashlineError<"RIPGREP_FAILED"> {
@@ -48,3 +48,20 @@ test("capture disables i inside a caseless reference → retain the reference's
48
48
  ["a[Aa]"],
49
49
  );
50
50
  });
51
+
52
+ test("deeply nested pattern → line candidates retain the native match", () => {
53
+ for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
54
+ const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
55
+ assert.equal(new RegExp(pattern).test("A"), true);
56
+ const candidates = lineCandidatePatterns({
57
+ patterns: [pattern],
58
+ literal: false,
59
+ flags: "",
60
+ multiline: false,
61
+ });
62
+ // An unavailable line analysis delegates candidate discovery to the file prefilter.
63
+ assert.ok(
64
+ candidates === undefined || candidates.some((candidate) => new RegExp(candidate).test("A")),
65
+ );
66
+ }
67
+ });