@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -2,20 +2,18 @@ import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { computeLineHash } from "../core/hash.ts";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import assert from "node:assert/strict";
5
- import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5
+ import fs, { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
+ import { syncBuiltinESMExports } from "node:module";
6
7
  import { writeFileSync } from "node:fs";
7
8
  import { tmpdir } from "node:os";
8
9
  import { join } from "node:path";
9
10
  import { test } from "node:test";
10
- import { DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
11
+ import { outputBudgetsFor } from "./budgets.ts";
11
12
  import { createActionFusionExecutor } from "./action-fusion.ts";
12
13
  import { makeReplaceTool } from "./replace-tool.ts";
13
14
  import { makeWriteOverride } from "./write-tool.ts";
14
15
  import { makeEditOverride } from "./edit-tool.ts";
15
- import { commitFreshness, FileMutationError } from "./file-commit.ts";
16
- import { byteRevision } from "./file-revision.ts";
17
- import { finalizeMutation, postProcessMutation, type MutationOutcome } from "./mutation-result.ts";
18
- import { CommandNotRun, decodeReport, reportOf } from "./report.ts";
16
+ import { decodeReport, reportOf } from "./report.ts";
19
17
  import { REREAD } from "./report-schema.ts";
20
18
  import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
21
19
  import { DEFAULT_CONFIG } from "./config.ts";
@@ -23,15 +21,6 @@ import { DEFAULT_CONFIG } from "./config.ts";
23
21
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
24
22
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
25
23
 
26
- const invoke = (
27
- tool: any,
28
- toolCallId: string,
29
- args: unknown,
30
- signal?: AbortSignal,
31
- onUpdate?: unknown,
32
- context?: unknown,
33
- ) => callTool(tool, args, { toolCallId, signal, onUpdate, ctx: context });
34
-
35
24
  const anchorBudget = outputBudgetsFor(4096);
36
25
  const anchorBatchSize: unknown = Reflect.get(
37
26
  makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.edits,
@@ -47,8 +36,6 @@ function assertFailureByteBudgets(message: string): void {
47
36
  assert.ok(Buffer.byteLength(JSON.stringify(report.failures)) <= anchorBudget.blockBytes);
48
37
  assert.equal(report.failures.length + (report.omittedFailures ?? 0), anchorBatchSize);
49
38
  assert.ok(report.omittedFailures);
50
- assert.equal(report.matched, undefined);
51
- assert.equal(report.omittedMatched, undefined);
52
39
  assert.ok(report.next?.includes("intended target"));
53
40
  if (report.candidateNeighborhoods) {
54
41
  const rows = report.candidateNeighborhoods.flatMap((group) => group.rows);
@@ -67,18 +54,16 @@ test("edit and replace commands change or remove the file → withhold anchors a
67
54
  const path = join(dir, `${toolName}-${state}-${fails}.txt`);
68
55
  await writeFile(path, "before\n");
69
56
  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
- );
57
+ const fusion = createActionFusionExecutor(async (_input, _signal, _ctx, onUpdate) => {
58
+ if (state === "changed") await writeFile(path, "command output\n");
59
+ else {
60
+ await rm(path);
61
+ if (state === "unknown") await mkdir(path);
62
+ }
63
+ onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
64
+ if (fails) throw new Error("command failed");
65
+ return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
66
+ });
82
67
  const tool =
83
68
  toolName === "edit"
84
69
  ? makeEditOverride(dir, DEFAULT_CONFIG, fusion)
@@ -107,8 +92,9 @@ test("edit and replace commands change or remove the file → withhold anchors a
107
92
  const report = reportOf(result, toolName);
108
93
  assert.equal(report?.freshness, state);
109
94
  assert.equal(report?.publication, "PUBLISHED");
110
- assert.equal(report?.next, REREAD);
95
+ assert.equal(report?.next, state === "missing" ? undefined : REREAD);
111
96
  assert.equal(report?.then_run?.status, fails ? "failed" : "succeeded");
97
+ if (fails) assert.equal(report?.then_run?.output, "command failed");
112
98
  assert.equal(result.content.length, 1);
113
99
  assert.ok(updates.length > 0);
114
100
  for (const update of updates)
@@ -124,7 +110,7 @@ test("edit and replace commands change or remove the file → withhold anchors a
124
110
  }
125
111
  });
126
112
 
127
- test("progress callback failures preserve publication and do not prevent the command", async (t) => {
113
+ test("progress callback failures → preserve publication and allow the command", async (t) => {
128
114
  const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
129
115
  try {
130
116
  for (const callback of ["reporter", "update"]) {
@@ -140,18 +126,15 @@ test("progress callback failures preserve publication and do not prevent the com
140
126
  callback === "reporter" ? fail : undefined,
141
127
  );
142
128
  const path = join(dir, callback);
143
- const result = await invoke(
129
+ const result = await callTool(
144
130
  makeWriteOverride(dir, fusion),
145
- "write",
146
131
  {
147
132
  path,
148
133
  content: "saved\n",
149
134
  mode: "create",
150
135
  then_run: { command: "check" },
151
136
  },
152
- undefined,
153
- callback === "update" ? fail : undefined,
154
- await ctx(dir, t),
137
+ { onUpdate: callback === "update" ? fail : undefined, ctx: await ctx(dir, t) },
155
138
  );
156
139
  assert.equal(commands, 1);
157
140
  assert.equal(await readFile(path, "utf8"), "saved\n");
@@ -159,110 +142,6 @@ test("progress callback failures preserve publication and do not prevent the com
159
142
  assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
160
143
  assert.match(text(result), /display unavailable/);
161
144
  }
162
- const fusion = createActionFusionExecutor(undefined, () => {
163
- throw new Error("display unavailable");
164
- });
165
- await assert.rejects(
166
- fusion({
167
- budget: DEFAULT_OUTPUT_BUDGETS,
168
- toolCallId: "failed",
169
- absolutePath: join(dir, "failed"),
170
- tool: "write",
171
- displayPath: "failed",
172
- thenRun: { command: "check" },
173
- mutate: async () => {
174
- throw new FileMutationError(
175
- "POST_PROCESS_FAILED",
176
- "post_process",
177
- "PUBLISHED",
178
- "original failure",
179
- );
180
- },
181
- signal: undefined,
182
- ctx: await ctx(dir, t),
183
- }),
184
- (error: unknown) =>
185
- error instanceof CommandNotRun &&
186
- error.cause instanceof FileMutationError &&
187
- error.cause.publication === "PUBLISHED" &&
188
- /original failure/.test(error.cause.message),
189
- );
190
- } finally {
191
- await rm(dir, { recursive: true, force: true });
192
- }
193
- });
194
-
195
- test("standalone and Fusion finalizers → take publication and freshness from commit facts, independent of diff", async (t) => {
196
- const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
197
- try {
198
- const path = join(dir, "file");
199
- const context = await ctx(dir, t);
200
- const publishedRevision = byteRevision(Buffer.from("published\n"));
201
- for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
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
- }
264
- }
265
- }
266
145
  } finally {
267
146
  await rm(dir, { recursive: true, force: true });
268
147
  }
@@ -273,9 +152,8 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
273
152
  try {
274
153
  const path = join(dir, "long.txt");
275
154
  await writeFile(path, "current\n");
276
- const failure = await invoke(
155
+ const failure = await callTool(
277
156
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
278
- "errors",
279
157
  {
280
158
  path,
281
159
  edits: Array.from({ length: anchorBatchSize }, () => ({
@@ -283,9 +161,7 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
283
161
  anchor: "1#XXXX",
284
162
  })),
285
163
  },
286
- undefined,
287
- undefined,
288
- await ctx(dir, t),
164
+ { ctx: await ctx(dir, t) },
289
165
  );
290
166
  assert.equal(failure.isError, true);
291
167
  assertFailureByteBudgets(text(failure));
@@ -357,9 +233,8 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
357
233
  const lines = Array.from({ length: 100 }, () => "same");
358
234
  lines[49] = "different";
359
235
  await writeFile(path, lines.join("\n"));
360
- const failure = await invoke(
236
+ const failure = await callTool(
361
237
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
362
- "ambiguous",
363
238
  {
364
239
  path,
365
240
  edits: Array.from({ length: anchorBatchSize }, () => ({
@@ -367,9 +242,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
367
242
  anchor: `50#${computeLineHash(50, "same", 4)}`,
368
243
  })),
369
244
  },
370
- undefined,
371
- undefined,
372
- await ctx(dir, t),
245
+ { ctx: await ctx(dir, t) },
373
246
  );
374
247
  assert.equal(failure.isError, true);
375
248
  assertFailureByteBudgets(text(failure));
@@ -471,20 +344,69 @@ test("Fusion skips the command when a replacement produces unencodable text", as
471
344
  }
472
345
  });
473
346
 
474
- test("result generation failure → preserves publication and cause", () => {
475
- for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
476
- const cause = new Error("render failed");
477
- assert.throws(
478
- () =>
479
- postProcessMutation(publication, () => {
480
- throw cause;
481
- }),
482
- (error: any) =>
483
- error instanceof FileMutationError &&
484
- error.stage === "post_process" &&
485
- error.publication === publication &&
486
- error.cause === cause,
487
- );
347
+ test("result generation fails after a real mutation → preserves publication and cause", async (t) => {
348
+ const dir = await mkdtemp(join(tmpdir(), "hashline-result-generation-"));
349
+ try {
350
+ for (const content of ["before\n", "after\n"]) {
351
+ const path = join(dir, "file.txt");
352
+ await writeFile(path, "before\n");
353
+ const cause = new Error("render failed");
354
+ const context = await ctx(dir, t);
355
+ const nativeOpen = fs.open;
356
+ const nativeReplace = String.prototype.replace;
357
+ const readsBeforeDiff = content === "before\n" ? 2 : 3;
358
+ let targetReads = 0;
359
+ let injected = false;
360
+ let commands = 0;
361
+ const fusion = createActionFusionExecutor(async () => {
362
+ commands++;
363
+ return { status: "succeeded", result: { content: [] } };
364
+ });
365
+ try {
366
+ t.mock.method(fs, "open", async (...args: Parameters<typeof nativeOpen>) => {
367
+ if (String(args[0]) === path) targetReads++;
368
+ return nativeOpen(...args);
369
+ });
370
+ syncBuiltinESMExports();
371
+ // Only fail diff normalization after the commit's final target read.
372
+ t.mock.method(
373
+ String.prototype,
374
+ "replace",
375
+ function (this: string, ...args: Parameters<typeof nativeReplace>) {
376
+ if (!injected && targetReads === readsBeforeDiff && String(this) === content) {
377
+ injected = true;
378
+ throw cause;
379
+ }
380
+ return nativeReplace.apply(this, args);
381
+ },
382
+ );
383
+ const result = await callTool(
384
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
385
+ {
386
+ path,
387
+ replacements: [{ literal: true, find: "before\n", replace: content }],
388
+ then_run: { command: "check" },
389
+ },
390
+ { ctx: context },
391
+ );
392
+ const report = reportOf(result, "replace");
393
+ assert.equal(injected, true, `diff injection after ${targetReads} target reads`);
394
+ assert.equal(result.isError, true);
395
+ assert.equal(report?.error, "POST_PROCESS_FAILED");
396
+ assert.ok(result.details);
397
+ assert.equal(Reflect.get(result.details, "diff"), undefined);
398
+ assert.equal(report?.publication, content === "before\n" ? "NOT_PUBLISHED" : "PUBLISHED");
399
+ assert.deepEqual(report?.cause, { message: cause.message });
400
+ assert.equal(report?.then_run?.status, "skipped");
401
+ assert.equal(commands, 0);
402
+ } finally {
403
+ t.mock.restoreAll();
404
+ syncBuiltinESMExports();
405
+ }
406
+ assert.equal(await readFile(path, "utf8"), content);
407
+ }
408
+ } finally {
409
+ await rm(dir, { recursive: true, force: true });
488
410
  }
489
411
  });
490
412
 
@@ -522,16 +444,15 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
522
444
  commands++;
523
445
  return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
524
446
  });
525
- const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
526
- const result = await invoke(
447
+ const tool = makeTool(dir, mode === "standalone" ? undefined : fusion);
448
+ const result = await callTool(
527
449
  tool,
528
- tool.name,
529
450
  { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) },
530
- undefined,
531
- undefined,
532
- await ctx(dir, t),
451
+ { ctx: await ctx(dir, t) },
533
452
  );
534
453
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
454
+ assert.ok(result.details);
455
+ assert.equal(Reflect.get(result.details, "diff"), tool.name === "write" ? undefined : "");
535
456
  assert.equal(reportOf(result, tool.name)?.freshness, undefined);
536
457
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
537
458
  assert.equal(commands, mode === "command" ? 1 : 0);
@@ -552,6 +473,61 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
552
473
  }
553
474
  });
554
475
 
476
+ test("delete and append change only line endings → publishes with an empty diff and still checks Fusion freshness", async (t) => {
477
+ const dir = await mkdtemp(join(tmpdir(), "hashline-empty-diff-"));
478
+ try {
479
+ const context = await ctx(dir, t);
480
+ for (const mode of ["standalone", "fusion", "command", "stale"] as const) {
481
+ const path = join(dir, `${mode}.txt`);
482
+ await writeFile(path, "same\r\nsame\n");
483
+ let commands = 0;
484
+ const fusion = createActionFusionExecutor(
485
+ async () => {
486
+ commands++;
487
+ assert.equal(await readFile(path, "utf8"), "same\nsame\r\n");
488
+ return { status: "succeeded", result: { content: [] } };
489
+ },
490
+ (progress) => {
491
+ if (mode === "stale" && progress.mutationCompleted && progress.command === "waiting")
492
+ writeFileSync(path, "external\n");
493
+ },
494
+ );
495
+ const result = await callTool(
496
+ makeEditOverride(dir, DEFAULT_CONFIG, mode === "standalone" ? undefined : fusion),
497
+ {
498
+ path,
499
+ edits: [
500
+ {
501
+ action: "delete",
502
+ anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
503
+ },
504
+ { action: "append", body: ["same"] },
505
+ ],
506
+ ...(["command", "stale"].includes(mode) ? { then_run: { command: "check" } } : {}),
507
+ },
508
+ { ctx: context },
509
+ );
510
+ const report = reportOf(result, "edit");
511
+ assert.equal(result.isError, undefined);
512
+ assert.equal(Reflect.get(result.details, "diff"), "");
513
+ assert.equal(report?.publication, "PUBLISHED");
514
+ assert.equal(report?.freshness, mode === "stale" ? "changed" : undefined);
515
+ assert.equal(
516
+ report?.then_run?.status,
517
+ mode === "command" ? "succeeded" : mode === "stale" ? "skipped" : undefined,
518
+ );
519
+ assert.equal(report?.next, mode === "stale" ? REREAD : undefined);
520
+ assert.equal(commands, mode === "command" ? 1 : 0);
521
+ assert.equal(
522
+ await readFile(path, "utf8"),
523
+ mode === "stale" ? "external\n" : "same\nsame\r\n",
524
+ );
525
+ }
526
+ } finally {
527
+ await rm(dir, { recursive: true, force: true });
528
+ }
529
+ });
530
+
555
531
  test("no-op Fusion still detects external changes and reports command failures", async (t) => {
556
532
  const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
557
533
  try {
@@ -576,14 +552,11 @@ test("no-op Fusion still detects external changes and reports command failures",
576
552
  writeFileSync(path, "external\n");
577
553
  },
578
554
  );
579
- const tool: any = makeTool(dir, fusion);
580
- const result = await invoke(
555
+ const tool = makeTool(dir, fusion);
556
+ const result = await callTool(
581
557
  tool,
582
- tool.name,
583
558
  { path, ...params, then_run: { command: "check" } },
584
- undefined,
585
- undefined,
586
- await ctx(dir, t),
559
+ { ctx: await ctx(dir, t) },
587
560
  );
588
561
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
589
562
  assert.equal(commands, scenario === "before" ? 0 : 1);
@@ -1,24 +1,28 @@
1
- import { test } from "node:test";
1
+ import { test, type TestContext } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import childProcess from "node:child_process";
4
4
  import { syncBuiltinESMExports } from "node:module";
5
5
  import { Readable } from "node:stream";
6
- import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
6
+ import { searchDiagnostic, runRgLines } from "./rg-process.ts";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { HashlineError } from "../core/errors.ts";
9
9
 
10
10
  test("grep search exit status → accepts no matches and preserves failure diagnostics", () => {
11
- for (const code of [0, 1]) {
12
- const warnings: string[] = [];
13
- recordSearchDiagnostics({ code, stderr: "", stopped: false }, warnings);
14
- assert.deepEqual(warnings, []);
11
+ for (const [code, stopped, stderr, expected] of [
12
+ [0, false, "", undefined],
13
+ [1, false, "", undefined],
14
+ [2, false, " \n", "ripgrep exited with code 2."],
15
+ [null, false, "", "ripgrep exited with code null."],
16
+ [null, true, "", undefined],
17
+ [2, false, " regex parse error\n", "regex parse error"],
18
+ [null, true, " regex parse error\n", "regex parse error"],
19
+ ] as const) {
20
+ assert.equal(
21
+ searchDiagnostic({ code, stderr, stopped }),
22
+ expected,
23
+ JSON.stringify({ code, stderr, stopped }),
24
+ );
15
25
  }
16
- const warnings: string[] = [];
17
- recordSearchDiagnostics({ code: 2, stderr: " regex parse error\n", stopped: false }, warnings);
18
- recordSearchDiagnostics({ code: null, stderr: "", stopped: false }, warnings);
19
- assert.equal(warnings.length, 2);
20
- assert.equal(warnings[0], "regex parse error");
21
- assert.match(warnings[1], /null/);
22
26
  });
23
27
 
24
28
  const listingFixture = fileURLToPath(
@@ -26,63 +30,72 @@ const listingFixture = fileURLToPath(
26
30
  );
27
31
  const parserTimeoutMs = 5_000;
28
32
 
29
- async function parseListing(chunks: readonly string[], maxLines = 10, stop = false) {
30
- const files: { path: string; lines: readonly number[] | undefined }[] = [];
31
- const result = await runRgLines(
32
- process.execPath,
33
- [
34
- listingFixture,
35
- JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
36
- ...(stop ? ["wait"] : []),
37
- ],
38
- AbortSignal.timeout(parserTimeoutMs),
39
- maxLines,
40
- (path, lines) => {
41
- files.push({ path, lines });
42
- return !stop;
43
- },
44
- );
45
- return { files, result };
46
- }
47
-
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
- );
33
+ async function parseListing(
34
+ t: TestContext,
35
+ chunks: readonly string[],
36
+ maxLines = 10,
37
+ stop = false,
38
+ splitChunks?: readonly Buffer[],
39
+ ) {
52
40
  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);
41
+ const mock = t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
42
+ const child = spawn(process.execPath, args[1] ?? [], args[2]);
43
+ if (splitChunks) {
57
44
  assert.ok(child.stdout);
58
- const stream = Readable.from(chunks);
45
+ const stream = Readable.from(splitChunks);
59
46
  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
47
  }
48
+ return child;
49
+ });
50
+ syncBuiltinESMExports();
51
+ try {
52
+ const files: { path: string; lines: readonly number[] | undefined }[] = [];
53
+ const result = await runRgLines(
54
+ [
55
+ listingFixture,
56
+ JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
57
+ ...(stop ? ["wait"] : []),
58
+ ],
59
+ AbortSignal.timeout(parserTimeoutMs),
60
+ maxLines,
61
+ (path, lines) => {
62
+ files.push({ path, lines });
63
+ return !stop;
64
+ },
65
+ );
66
+ return { files, result };
77
67
  } finally {
78
- t.mock.restoreAll();
68
+ mock.mock.restore();
79
69
  syncBuiltinESMExports();
80
70
  }
71
+ }
72
+
73
+ test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async (t) => {
74
+ const listing = Buffer.from(
75
+ "dir\n文件.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n",
76
+ );
77
+ for (let split = 1; split < listing.length; split++) {
78
+ const { files, result } = await parseListing(t, [], 10, false, [
79
+ listing.subarray(0, split),
80
+ listing.subarray(split),
81
+ ]);
82
+ assert.deepEqual(
83
+ files,
84
+ [
85
+ { path: "dir\n文件.txt", lines: [1, 2, 10] },
86
+ { path: "other.txt", lines: [3] },
87
+ ],
88
+ `split=${split}`,
89
+ );
90
+ assert.equal(result.code, 0);
91
+ assert.equal(result.stopped, false);
92
+ }
81
93
  });
82
94
 
83
- test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
95
+ test("line listing exceeds maxLines → only the overflowing file requests all-line review", async (t) => {
84
96
  for (const maxLines of [2, 3]) {
85
97
  const { files } = await parseListing(
98
+ t,
86
99
  ["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
87
100
  maxLines,
88
101
  );
@@ -93,8 +106,9 @@ test("line listing exceeds maxLines → only the overflowing file requests all-l
93
106
  }
94
107
  });
95
108
 
96
- test("line consumer returns false → process stops before the next file", async () => {
109
+ test("line consumer returns false → process stops before the next file", async (t) => {
97
110
  const { files, result } = await parseListing(
111
+ t,
98
112
  ["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
99
113
  10,
100
114
  true,
@@ -103,17 +117,17 @@ test("line consumer returns false → process stops before the next file", async
103
117
  assert.equal(result.stopped, true);
104
118
  });
105
119
 
106
- test("line listing ends with incomplete path or row → RIPGREP_FAILED", async () => {
120
+ test("line listing ends with incomplete path or row → RIPGREP_FAILED", async (t) => {
107
121
  for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
108
122
  await assert.rejects(
109
- parseListing([record]),
123
+ parseListing(t, [record]),
110
124
  (error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
111
125
  );
112
126
  }
113
127
  });
114
128
 
115
- test("line listing ends after a complete row → flush the final file without a separator", async () => {
116
- const { files, result } = await parseListing(["final\0" + "1:x\n"]);
129
+ test("line listing ends after a complete row → flush the final file without a separator", async (t) => {
130
+ const { files, result } = await parseListing(t, ["final\0" + "1:x\n"]);
117
131
  assert.deepEqual(files, [{ path: "final", lines: [1] }]);
118
132
  assert.equal(result.code, 0);
119
133
  });