@criogaid/pi-hashline-edit 0.10.0 → 0.12.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 (103) hide show
  1. package/README.md +21 -7
  2. package/README.zh-CN.md +22 -8
  3. package/package.json +7 -6
  4. package/src/core/AGENTS.md +2 -2
  5. package/src/core/apply.test.ts +4 -4
  6. package/src/core/apply.ts +3 -3
  7. package/src/core/character-set.test.ts +2 -3
  8. package/src/core/character-set.ts +1 -1
  9. package/src/core/ranges.test.ts +2 -1
  10. package/src/core/ranges.ts +1 -1
  11. package/src/core/regex.ts +6 -2
  12. package/src/core/replace.test.ts +51 -0
  13. package/src/core/replace.ts +10 -4
  14. package/src/core/types.ts +1 -1
  15. package/src/index.ts +9 -9
  16. package/src/integration/config-registration.test.ts +8 -10
  17. package/src/integration/fusion-dispatch.test.ts +2 -2
  18. package/src/integration/grep-errors.test.ts +3 -3
  19. package/src/integration/grep-flags.test.ts +5 -5
  20. package/src/integration/grep-js-completeness.test.ts +12 -11
  21. package/src/integration/grep-line-candidates.test.ts +5 -3
  22. package/src/integration/grep-matrix.test.ts +5 -4
  23. package/src/integration/grep-order.test.ts +4 -4
  24. package/src/integration/grep-path-matrix.test.ts +5 -4
  25. package/src/integration/grep-prefilter-coverage.test.ts +17 -5
  26. package/src/integration/grep-process-limits.test.ts +2 -4
  27. package/src/integration/grep-regex.test.ts +10 -10
  28. package/src/integration/grep-rg.test.ts +93 -48
  29. package/src/integration/grep-scan-budget.test.ts +8 -8
  30. package/src/integration/grep-translation.test.ts +8 -7
  31. package/src/integration/large-text.test.ts +5 -5
  32. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  33. package/src/integration/mutation-file-types.testing.ts +4 -4
  34. package/src/integration/npm-package.test.ts +12 -10
  35. package/src/integration/npm-package.testing.ts +151 -4
  36. package/src/integration/publication-read-changes.test.ts +54 -54
  37. package/src/integration/read-changes.test.ts +4 -4
  38. package/src/integration/replace-worker-boundary.test.ts +1 -1
  39. package/src/integration/report-replay.test.ts +9 -6
  40. package/src/integration/utf8-errors.test.ts +4 -4
  41. package/src/pi/AGENTS.md +13 -12
  42. package/src/pi/action-fusion.test.ts +125 -105
  43. package/src/pi/action-fusion.testing.ts +38 -0
  44. package/src/pi/action-fusion.ts +9 -21
  45. package/src/pi/argument-diagnostics.ts +4 -3
  46. package/src/pi/argument-format.test.ts +19 -18
  47. package/src/pi/argument-validation.test.ts +281 -139
  48. package/src/pi/argument-validation.ts +21 -31
  49. package/src/pi/budgets.ts +1 -4
  50. package/src/pi/codemode.test.ts +7 -2
  51. package/src/pi/config.test.ts +2 -1
  52. package/src/pi/config.ts +8 -3
  53. package/src/pi/diagnostic-buffer.test.ts +23 -13
  54. package/src/pi/edit-tool.ts +48 -63
  55. package/src/pi/error-text.ts +7 -2
  56. package/src/pi/execute.test.ts +178 -157
  57. package/src/pi/failure-context.test.ts +5 -4
  58. package/src/pi/failure-context.ts +1 -1
  59. package/src/pi/failure-path.test.ts +37 -37
  60. package/src/pi/file-commit.test.ts +47 -19
  61. package/src/pi/file-commit.ts +36 -9
  62. package/src/pi/fusion-card.test.ts +22 -21
  63. package/src/pi/fusion-card.ts +9 -5
  64. package/src/pi/grep-candidates.test.ts +18 -20
  65. package/src/pi/grep-candidates.ts +13 -17
  66. package/src/pi/grep-matrix.test.ts +3 -3
  67. package/src/pi/grep-order.test.ts +12 -11
  68. package/src/pi/grep-output.ts +45 -17
  69. package/src/pi/grep-reread.ts +7 -2
  70. package/src/pi/grep-rg.testing.ts +70 -0
  71. package/src/pi/grep-scope.ts +10 -10
  72. package/src/pi/grep-search.ts +8 -11
  73. package/src/pi/grep-tool.ts +40 -53
  74. package/src/pi/grep.test.ts +141 -116
  75. package/src/pi/model-budgets.test.ts +2 -1
  76. package/src/pi/mutation-outcome.testing.ts +0 -1
  77. package/src/pi/mutation-result.test.ts +8 -8
  78. package/src/pi/mutation-result.ts +1 -1
  79. package/src/pi/mutation-runner.ts +10 -6
  80. package/src/pi/output-budgets.test.ts +53 -31
  81. package/src/pi/pi.test.ts +18 -13
  82. package/src/pi/read-tool.ts +13 -18
  83. package/src/pi/read.test.ts +67 -41
  84. package/src/pi/registration.test.ts +25 -19
  85. package/src/pi/render.test.ts +94 -32
  86. package/src/pi/render.ts +7 -4
  87. package/src/pi/replace-regex.ts +1 -1
  88. package/src/pi/replace-tool.ts +6 -16
  89. package/src/pi/replace.test.ts +45 -34
  90. package/src/pi/report-failure.testing.ts +9 -1
  91. package/src/pi/report-schema.ts +225 -86
  92. package/src/pi/report.test.ts +81 -87
  93. package/src/pi/report.ts +35 -22
  94. package/src/pi/result-safety.test.ts +121 -100
  95. package/src/pi/rg-process.test.ts +2 -2
  96. package/src/pi/rg-process.ts +9 -15
  97. package/src/pi/rg-regex.test.ts +13 -0
  98. package/src/pi/rg-regex.ts +2 -2
  99. package/src/pi/schema.ts +23 -0
  100. package/src/pi/tool-factories.testing.ts +59 -0
  101. package/src/pi/write-tool.ts +9 -15
  102. package/src/pi/write.test.ts +30 -31
  103. package/src/testing/run-tests.ts +1 -1
@@ -4,8 +4,9 @@ import { computeLineHash } from "../core/hash.ts";
4
4
  import { applyEdits } from "../core/apply.ts";
5
5
  import { HashlineError } from "../core/errors.ts";
6
6
  import type { AnchorFailure, Edit } from "../core/types.ts";
7
- import { formatByteSize, DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
8
- import { DEFAULT_CONFIG } from "./config.ts";
7
+ import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
8
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
9
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
9
10
  import { createAnchorFormatter } from "./anchor-format.ts";
10
11
  import { describeEditFailure } from "./failure-context.ts";
11
12
  import { describeMutationFailure } from "./mutation-result.ts";
@@ -316,10 +317,10 @@ test("overlapping edits → ordered conflict and shared recovery", () => {
316
317
  budget: DEFAULT_OUTPUT_BUDGETS,
317
318
  });
318
319
  assert.equal(report.error, "OVERLAPPING_EDITS");
319
- assert.deepEqual(report.conflict, ["edits[0]", "edits[2]"]);
320
+ assert.deepEqual(report.conflict, ["steps[0]", "steps[2]"]);
320
321
  assert.equal(report.message, error.message);
321
322
  assert.equal(report.publication, "NOT_PUBLISHED");
322
- assert.match(report.next ?? "", /one edit per range or position/);
323
+ assert.match(report.next ?? "", /one step per range or position/);
323
324
  return true;
324
325
  },
325
326
  );
@@ -125,7 +125,7 @@ function failureEntry(
125
125
  ): AnchorFailureFact {
126
126
  const rowTooLarge = `row exceeds ${formatByteSize(budget.fieldBytes)}`;
127
127
  const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
128
- field: `edits[${f.opIndex}].${f.which}`,
128
+ field: `steps[${f.opIndex}].${f.which}`,
129
129
  action: f.op,
130
130
  cited: anchors.reference(f.cited.line, f.cited.hash),
131
131
  result: RESULT[f.recovery.kind],
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import fs, { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
3
  import { syncBuiltinESMExports } from "node:module";
3
4
  import { tmpdir } from "node:os";
@@ -9,7 +10,7 @@ import type { ActionFusionProgress } from "./report-schema.ts";
9
10
  import { outputBudgetsFor } from "./budgets.ts";
10
11
  import { reportOf } from "./report.ts";
11
12
  import { callTool, createToolContext } from "./tool-call.testing.ts";
12
- import { makeWriteOverride } from "./write-tool.ts";
13
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
13
14
 
14
15
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
15
16
  const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
@@ -97,20 +98,18 @@ test("publication boundary and observer failures → preserve recovery and emit
97
98
  published = true;
98
99
  });
99
100
  syncBuiltinESMExports();
100
- const fusion = createActionFusionExecutor(
101
- async () => {
102
- commands++;
103
- return { status: "succeeded", result: { content: [] } };
104
- },
105
- (update) => {
106
- progress.push(update);
107
- if (progressError !== undefined) throw progressError;
108
- },
109
- );
101
+ const executeTool: SessionCommand = async () => {
102
+ commands++;
103
+ return commandCompletion({ content: [] });
104
+ };
105
+ const fusion = createActionFusionExecutor((update) => {
106
+ progress.push(update);
107
+ if (progressError !== undefined) throw progressError;
108
+ });
110
109
  const result = await callTool(
111
110
  makeWriteOverride(dir, fusion, () => budget),
112
111
  { path: target, mode: "overwrite", content: "after\n", then_run: { command: "check" } },
113
- { ctx: context },
112
+ { ctx: { ...context, executeTool } },
114
113
  );
115
114
  const report = reportOf(result, "write");
116
115
  assert.equal(result.isError, true);
@@ -173,16 +172,17 @@ test("cancellation after publication → does not rerun mutation and still inspe
173
172
  for (const state of ["changed", "missing"] as const) {
174
173
  const target = join(dir, `${state}.txt`);
175
174
  const controller = new AbortController();
176
- const fusion = createActionFusionExecutor(async () => {
175
+ const executeTool: SessionCommand = async () => {
177
176
  if (state === "changed") await writeFile(target, "command changed\n");
178
177
  else await rm(target);
179
178
  controller.abort();
180
- throw new Error("timed out");
181
- });
179
+ return commandCompletion({ content: [{ type: "text", text: "timed out" }] }, true);
180
+ };
181
+ const fusion = createActionFusionExecutor(() => {});
182
182
  const result = await callTool(
183
183
  makeWriteOverride(dir, fusion),
184
184
  { path: target, mode: "create", content: "mutation\n", then_run: { command: "check" } },
185
- { signal: controller.signal, ctx: await createToolContext(dir, t) },
185
+ { signal: controller.signal, ctx: { ...(await createToolContext(dir, t)), executeTool } },
186
186
  );
187
187
  const report = reportOf(result, "write");
188
188
  assert.equal(report?.publication, "PUBLISHED");
@@ -198,11 +198,16 @@ test("first command fails → releases the queue for the next mutation", async (
198
198
  const target = join(dir, "queue.txt");
199
199
  const ctx = await createToolContext(dir, t);
200
200
  let calls = 0;
201
- const fusion = createActionFusionExecutor(async () => {
201
+ const executeTool: SessionCommand = async () => {
202
202
  calls++;
203
- if (calls === 1) throw new Error("first command failed");
204
- return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
205
- });
203
+ if (calls === 1)
204
+ return commandCompletion(
205
+ { content: [{ type: "text", text: "first command failed" }] },
206
+ true,
207
+ );
208
+ return commandCompletion({ content: [{ type: "text", text: "ok" }] });
209
+ };
210
+ const fusion = createActionFusionExecutor(() => {});
206
211
  for (const content of ["first\n", "second\n"]) {
207
212
  const result = await callTool(
208
213
  makeWriteOverride(dir, fusion),
@@ -212,7 +217,7 @@ test("first command fails → releases the queue for the next mutation", async (
212
217
  mode: calls === 0 ? "create" : "overwrite",
213
218
  then_run: { command: "check" },
214
219
  },
215
- { toolCallId: content, ctx },
220
+ { toolCallId: content, ctx: { ...ctx, executeTool } },
216
221
  );
217
222
  assert.equal(
218
223
  reportOf(result, "write")?.then_run?.status,
@@ -227,17 +232,13 @@ test("command succeeds on an unchanged target → retains the result and complet
227
232
  withTemp(async (dir) => {
228
233
  const target = join(dir, "finalize.txt");
229
234
  const progress: ActionFusionProgress[] = [];
230
- const fusion = createActionFusionExecutor(
231
- async () => ({
232
- status: "succeeded",
233
- result: { content: [{ type: "text", text: "command finished" }] },
234
- }),
235
- (event) => progress.push(event),
236
- );
235
+ const executeTool: SessionCommand = async () =>
236
+ commandCompletion({ content: [{ type: "text", text: "command finished" }] });
237
+ const fusion = createActionFusionExecutor((event) => progress.push(event));
237
238
  const completed = await callTool(
238
239
  makeWriteOverride(dir, fusion),
239
240
  { path: target, content: "saved\n", mode: "create", then_run: { command: "check" } },
240
- { ctx: await createToolContext(dir, t) },
241
+ { ctx: { ...(await createToolContext(dir, t)), executeTool } },
241
242
  );
242
243
  assert.equal(completed.content.length, 1);
243
244
  assert.equal(reportOf(completed, "write")?.then_run?.status, "succeeded");
@@ -246,6 +247,7 @@ test("command succeeds on an unchanged target → retains the result and complet
246
247
  assert.equal(progress.at(-1)?.freshness, "unchanged");
247
248
  assert.deepEqual(progress.at(-1)?.result, {
248
249
  content: [{ type: "text", text: "command finished" }],
250
+ details: {},
249
251
  });
250
252
  }));
251
253
 
@@ -257,17 +259,15 @@ test("cancellation before mutation → reports a cancelled command without publi
257
259
  controller.abort();
258
260
  let commands = 0;
259
261
  const progress: ActionFusionProgress[] = [];
260
- const fusion = createActionFusionExecutor(
261
- async () => {
262
- commands++;
263
- return { status: "succeeded", result: { content: [] } };
264
- },
265
- (event) => progress.push(event),
266
- );
262
+ const executeTool: SessionCommand = async () => {
263
+ commands++;
264
+ return commandCompletion({ content: [] });
265
+ };
266
+ const fusion = createActionFusionExecutor((event) => progress.push(event));
267
267
  const result = await callTool(
268
268
  makeWriteOverride(dir, fusion),
269
269
  { path: target, mode: "overwrite", content: "after\n", then_run: { command: "check" } },
270
- { signal: controller.signal, ctx: await createToolContext(dir, t) },
270
+ { signal: controller.signal, ctx: { ...(await createToolContext(dir, t)), executeTool } },
271
271
  );
272
272
  const report = reportOf(result, "write");
273
273
  assert.equal(result.isError, true);
@@ -29,27 +29,21 @@ import {
29
29
  import { byteRevision } from "./file-revision.ts";
30
30
  import { HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
31
31
  import { createActionFusionExecutor } from "./action-fusion.ts";
32
- import { makeWriteOverride } from "./write-tool.ts";
32
+ import { commandCompletion } from "./action-fusion.testing.ts";
33
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
33
34
  import { callTool } from "./tool-call.testing.ts";
34
35
  import { describeMutationFailure } from "./mutation-result.ts";
35
36
  import { reportOf } from "./report.ts";
36
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
37
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
37
38
 
38
- // Checked by tsc; these states cannot be returned by the commit layer.
39
+ // Checked by tsc; this state cannot be returned by the commit layer.
39
40
  function invalidCommitStates() {
40
- // @ts-expect-error A newly created target is always published.
41
- const unpublishedCreate: CommitResult = {
42
- created: true,
43
- publication: "NOT_PUBLISHED",
44
- publishedRevision: "r",
45
- observedRevision: "r",
46
- };
47
41
  // @ts-expect-error A no-op has a confirmed observed revision.
48
42
  const unobservedNoop: CommitResult = {
49
- created: false,
50
43
  publication: "NOT_PUBLISHED",
51
44
  publishedRevision: "r",
52
45
  };
46
+
53
47
  // @ts-expect-error A known freshness state cannot carry a read error.
54
48
  const knownError: FreshnessObservation = {
55
49
  freshness: "changed",
@@ -141,6 +135,38 @@ test("create never overwrites an existing target", async () =>
141
135
  assert.equal(await readFile(target, "utf8"), "original\n");
142
136
  }));
143
137
 
138
+ test("short low-level reads → complete mutation snapshots before revision binding", async (t) =>
139
+ withTemp(async (dir) => {
140
+ const target = join(dir, "short-read.txt");
141
+ const expected = Buffer.from("x".repeat(66_722));
142
+ const shortRead = 65_512;
143
+ await writeFile(target, expected);
144
+ const nativeOpen = fsPromises.open;
145
+ let lowLevelReads = 0;
146
+ t.mock.method(fsPromises, "open", async (...args: Parameters<typeof nativeOpen>) => {
147
+ const handle = await nativeOpen(...args);
148
+ if (args[0] !== target) return handle;
149
+ const nativeRead = handle.read.bind(handle);
150
+ t.mock.method(handle, "read", async (...readArgs: Parameters<typeof nativeRead>) => {
151
+ const result = await nativeRead(...readArgs);
152
+ return lowLevelReads++ === 0
153
+ ? { ...result, bytesRead: Math.min(result.bytesRead, shortRead) }
154
+ : result;
155
+ });
156
+ return handle;
157
+ });
158
+ syncBuiltinESMExports();
159
+ try {
160
+ const snapshot = await readEditableSnapshot(target);
161
+ assert.equal(snapshot.text, expected.toString("utf8"));
162
+ assert.equal(snapshot.baseRevision, byteRevision(expected));
163
+ assert.ok(lowLevelReads >= 2);
164
+ } finally {
165
+ t.mock.restoreAll();
166
+ syncBuiltinESMExports();
167
+ }
168
+ }));
169
+
144
170
  test("replacement exposes complete old or new content during concurrent reads", async (t) =>
145
171
  withTemp(async (dir) => {
146
172
  if (process.platform === "win32")
@@ -251,12 +277,16 @@ test("Windows shared access failure preserves the target, skips then_run, and re
251
277
  await writeFile(target, "original\n");
252
278
  const holder = await holdWindowsExclusive(target);
253
279
  let commandRuns = 0;
280
+ const context = {
281
+ cwd: dir,
282
+ executeTool: async () => {
283
+ commandRuns++;
284
+ return commandCompletion({ content: [{ type: "text", text: "ok" }] });
285
+ },
286
+ };
254
287
  const tool = makeWriteOverride(
255
288
  dir,
256
- createActionFusionExecutor(async () => {
257
- commandRuns++;
258
- return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
259
- }),
289
+ createActionFusionExecutor(() => {}),
260
290
  );
261
291
  try {
262
292
  const failed = await callTool(
@@ -267,7 +297,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
267
297
  mode: "overwrite",
268
298
  then_run: { command: "deterministic-command" },
269
299
  },
270
- { toolCallId: "shared-failure", ctx: { cwd: dir } },
300
+ { toolCallId: "shared-failure", ctx: context },
271
301
  );
272
302
  assert.equal(failed.isError, true);
273
303
  const report = reportOf(failed, "write");
@@ -306,7 +336,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
306
336
  mode: "overwrite",
307
337
  then_run: { command: "deterministic-command" },
308
338
  },
309
- { toolCallId: "shared-retry", ctx: { cwd: dir } },
339
+ { toolCallId: "shared-retry", ctx: context },
310
340
  );
311
341
  assert.equal(result.isError, undefined);
312
342
  assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
@@ -392,7 +422,6 @@ test("identical commits preserve the file and still enforce mode, revision, and
392
422
  baseRevision: revision,
393
423
  });
394
424
  assert.deepEqual(result, {
395
- created: false,
396
425
  publishedRevision: revision,
397
426
  observedRevision: revision,
398
427
  publication: "NOT_PUBLISHED",
@@ -415,7 +444,6 @@ test("identical commits preserve the file and still enforce mode, revision, and
415
444
  (error: unknown) => error instanceof HashlineError && error.errorCode === "OPERATION_ABORTED",
416
445
  );
417
446
  const created = await commitFile(join(dir, "empty"), "", { mode: "create" });
418
- assert.equal(created.created, true);
419
447
  assert.equal(created.publication, "PUBLISHED");
420
448
  }));
421
449
 
@@ -16,6 +16,7 @@ import {
16
16
  rm,
17
17
  stat,
18
18
  link,
19
+ type FileHandle,
19
20
  } from "node:fs/promises";
20
21
  import type { BigIntStats, Stats } from "node:fs";
21
22
  import { dirname, join } from "node:path";
@@ -51,12 +52,8 @@ interface CommitRevisions {
51
52
 
52
53
  export type CommitResult = CommitRevisions &
53
54
  (
54
- | { readonly created: boolean; readonly publication: "PUBLISHED" }
55
- | {
56
- readonly created: false;
57
- readonly publication: "NOT_PUBLISHED";
58
- readonly observedRevision: string;
59
- }
55
+ | { readonly publication: "PUBLISHED" }
56
+ | { readonly publication: "NOT_PUBLISHED"; readonly observedRevision: string }
60
57
  );
61
58
 
62
59
  /**
@@ -83,11 +80,43 @@ function requireRegularFile(target: Stats | BigIntStats): void {
83
80
  throw new HashlineError("NOT_REGULAR_FILE", PATH_ERROR_MESSAGES.NOT_REGULAR_FILE);
84
81
  }
85
82
 
83
+ const REGULAR_FILE_READ_CHUNK_BYTES = 64 * 1024;
84
+
85
+ /** Read a regular file in full, even when the filesystem returns short reads. */
86
+ async function readRegularFileBytes(
87
+ handle: FileHandle,
88
+ size: bigint,
89
+ signal: AbortSignal | undefined,
90
+ ): Promise<Buffer> {
91
+ const chunks: Buffer[] = [];
92
+ let position = 0n;
93
+ while (position < size) {
94
+ throwIfCancelled(signal);
95
+ const remaining = size - position;
96
+ const length = Number(
97
+ remaining < BigInt(REGULAR_FILE_READ_CHUNK_BYTES)
98
+ ? remaining
99
+ : BigInt(REGULAR_FILE_READ_CHUNK_BYTES),
100
+ );
101
+ const buffer = Buffer.allocUnsafe(length);
102
+ const result = await handle.read({
103
+ buffer,
104
+ offset: 0,
105
+ length,
106
+ position: Number(position),
107
+ });
108
+ if (result.bytesRead <= 0 || result.bytesRead > length) throw new FileChangedDuringReadError();
109
+ chunks.push(buffer.subarray(0, result.bytesRead));
110
+ position += BigInt(result.bytesRead);
111
+ }
112
+ return Buffer.concat(chunks);
113
+ }
114
+
86
115
  /** Check the opened object before reading; a FIFO must not block even if the path changed. */
87
116
  async function readRegularFile(path: string, signal?: AbortSignal): Promise<Buffer> {
88
117
  return withFileRead(path, signal, async (handle, before) => {
89
118
  requireRegularFile(before);
90
- return handle.readFile({ signal });
119
+ return readRegularFileBytes(handle, before.size, signal);
91
120
  });
92
121
  }
93
122
 
@@ -305,7 +334,6 @@ export async function commitFile(
305
334
  if (baseRevision !== undefined)
306
335
  await requireBaseRevision(target.publishPath, baseRevision, options.signal);
307
336
  return {
308
- created: false,
309
337
  publishedRevision,
310
338
  observedRevision: publishedRevision,
311
339
  publication: "NOT_PUBLISHED",
@@ -333,7 +361,6 @@ export async function commitFile(
333
361
  published = true;
334
362
  await syncDirectory(publishDirectory);
335
363
  const committed: CommitResult = {
336
- created: !target.existed,
337
364
  publishedRevision,
338
365
  publication: "PUBLISHED",
339
366
  };
@@ -9,9 +9,10 @@ import { createActionFusionExecutor } from "./action-fusion.ts";
9
9
  import type { ActionFusionProgress } from "./report-schema.ts";
10
10
  import type { CommandResult } from "./report-schema.ts";
11
11
  import { commandText } from "./mutation-result.ts";
12
- import { decodeReport } from "./report.ts";
13
- import { makeWriteOverride } from "./write-tool.ts";
14
- import { callTool, createToolContext } from "./tool-call.testing.ts";
12
+ import { reportOf } from "./report.ts";
13
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
14
+ import { commandCompletion, createFusionContext } from "./action-fusion.testing.ts";
15
+ import { callTool } from "./tool-call.testing.ts";
15
16
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
17
  import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
17
18
  import { theme as activeTheme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
@@ -104,12 +105,13 @@ test("one independent card updates live and only persists its endpoints", () =>
104
105
 
105
106
  test("Fusion command outcomes → progress, cards, and reports preserve command results", async (t) => {
106
107
  const success: CommandResult = {
108
+ details: {},
107
109
  content: [
108
110
  { type: "text", text: "first" },
109
111
  { type: "text", text: "second" },
110
112
  ],
111
113
  };
112
- const failure: CommandResult = { content: [{ type: "text", text: "boom" }] };
114
+ const failure: CommandResult = { content: [{ type: "text", text: "boom" }], details: {} };
113
115
  const cases: readonly {
114
116
  scenario:
115
117
  | "succeeded"
@@ -128,7 +130,7 @@ test("Fusion command outcomes → progress, cards, and reports preserve command
128
130
  {
129
131
  scenario: "cancelled-empty",
130
132
  command: "cancelled",
131
- result: { content: [] },
133
+ result: { content: [], details: {} },
132
134
  text: /Not run: cancelled\./,
133
135
  },
134
136
  { scenario: "skipped", command: "skipped", text: /Not run: the mutation did not complete/ },
@@ -144,20 +146,19 @@ test("Fusion command outcomes → progress, cards, and reports preserve command
144
146
  const controller = new AbortController();
145
147
  if (scenario === "cancelled") controller.abort();
146
148
  let commands = 0;
147
- const fusion = createActionFusionExecutor(
148
- async () => {
149
- commands++;
150
- if (scenario === "cancelled-error") controller.abort();
151
- if (scenario === "failed" || scenario === "cancelled-error") throw new Error("boom");
152
- return scenario === "cancelled-empty"
153
- ? { status: "cancelled", result: { content: [] } }
154
- : { status: "succeeded", result: success };
155
- },
156
- (progress) => {
157
- events.push(progress);
158
- h.report(progress);
159
- },
160
- );
149
+ const context = await createFusionContext(dir, t, async () => {
150
+ commands++;
151
+ if (scenario === "cancelled-error" || scenario === "cancelled-empty") controller.abort();
152
+ if (scenario === "failed" || scenario === "cancelled-error")
153
+ return commandCompletion(failure, true);
154
+ return scenario === "cancelled-empty"
155
+ ? commandCompletion({ content: [] }, true)
156
+ : commandCompletion(success);
157
+ });
158
+ const fusion = createActionFusionExecutor((progress) => {
159
+ events.push(progress);
160
+ h.report(progress);
161
+ });
161
162
  const result = await callTool(
162
163
  makeWriteOverride(dir, fusion),
163
164
  {
@@ -166,7 +167,7 @@ test("Fusion command outcomes → progress, cards, and reports preserve command
166
167
  content: "saved\n",
167
168
  then_run: { command: "check" },
168
169
  },
169
- { ctx: await createToolContext(dir, t), signal: controller.signal },
170
+ { ctx: context, signal: controller.signal },
170
171
  );
171
172
  assert.equal(commands, expected ? 1 : 0);
172
173
  const final = events.at(-1);
@@ -184,7 +185,7 @@ test("Fusion command outcomes → progress, cards, and reports preserve command
184
185
  assert.equal(Object.hasOwn(h.entries[0].data, "result"), false);
185
186
  const block = result.content.at(-1);
186
187
  assert.ok(block?.type === "text");
187
- const report = decodeReport(block.text, "write");
188
+ const report = reportOf({ content: [block] }, "write");
188
189
  assert.ok(report);
189
190
  const output = expected ? commandText(expected.content) : "";
190
191
  assert.deepEqual(report.then_run, { status: command, ...(output ? { output } : {}) });
@@ -9,6 +9,7 @@ import type {
9
9
  ExtensionAPI,
10
10
  ExtensionContext,
11
11
  ToolDefinition,
12
+ ToolRenderers,
12
13
  } from "@earendil-works/pi-coding-agent";
13
14
  import {
14
15
  createBashToolDefinition,
@@ -131,15 +132,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
131
132
  });
132
133
  pi.on("session_tree", (_event, ctx) => restore(ctx));
133
134
 
134
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, { expanded }):
135
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, options):
135
136
  | Component
136
137
  | undefined {
138
+ const { expanded } = options;
137
139
  const initial = entry.data;
138
140
  if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
139
141
  if (!tui) {
140
142
  // Pi may rebuild history before session_start supplies its UI context.
141
143
  let component: Component | undefined;
142
- const ready = () => (component ??= tui ? renderCard(entry, { expanded }) : undefined);
144
+ const ready = () => (component ??= tui ? renderCard(entry, options) : undefined);
143
145
  return {
144
146
  render: (width) => ready()?.render(width) ?? [],
145
147
  invalidate: () => component?.invalidate(),
@@ -155,15 +157,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
155
157
  let box = new Box(outputPadding, 1);
156
158
  let call: Component | undefined;
157
159
  let result: Component | undefined;
158
- const renderers: Pick<typeof bash, "renderShell" | "renderCall" | "renderResult"> = {
160
+ const renderers: ToolRenderers = {
159
161
  renderShell: "self",
160
- renderCall(args, theme, context) {
162
+ renderCall(_args, theme, context) {
161
163
  const padding = SettingsManager.inMemory(pi.getSettings()).getOutputPad();
162
164
  if (padding !== outputPadding) {
163
165
  outputPadding = padding;
164
166
  box = new Box(outputPadding, 1);
165
167
  }
166
168
  const value = current();
169
+ const args = { command: value.commandText, timeout: value.timing?.timeoutSeconds };
167
170
  const pending = commandPending(value);
168
171
  const interrupted = pending && !active.has(value.toolCallId);
169
172
  const status = interrupted ? "interrupted (final status unknown)" : value.command;
@@ -192,7 +195,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
192
195
  statusText.setText(
193
196
  `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
194
197
  );
195
- call = bash.renderCall!(args, theme, { ...context, lastComponent: call });
198
+ call = bash.renderCall!(args, theme, { ...context, args, lastComponent: call });
196
199
  box.clear();
197
200
  box.addChild(statusText);
198
201
  box.addChild(call);
@@ -205,6 +208,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
205
208
  if (current().result) {
206
209
  result = bash.renderResult!(value, options, theme, {
207
210
  ...context,
211
+ args: { command: current().commandText, timeout: current().timing?.timeoutSeconds },
208
212
  lastComponent: result,
209
213
  });
210
214
  box.addChild(result);
@@ -1,28 +1,26 @@
1
+ import { fileCandidateArgs } from "./grep-rg.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
3
- import { candidateArgs } from "./grep-candidates.ts";
4
4
  import { COMMON_RG_ARGS } from "./rg-process.ts";
5
5
 
6
- test("candidate literals → rg lists files with escaped byte-preserving alternatives", () => {
7
- assert.deepEqual(candidateArgs({ kind: "all" }), [...COMMON_RG_ARGS, "--files"]);
8
- for (const [literals, pattern] of [
9
- [
6
+ test("candidate literals → rg lists files with escaped byte-preserving alternatives", async () => {
7
+ const query = { patterns: ["."], literal: false, flags: "", multiline: true };
8
+ assert.deepEqual(await fileCandidateArgs(query), [...COMMON_RG_ARGS, "--files"]);
9
+ for (const [patterns, literal, flags, pattern] of [
10
+ [["a.b", "-é"], true, "", "a\\x{2e}b|\\x{2d}\\x{e9}"],
11
+ [["k_9"], true, "iu", "[Kk\\x{212a}]_9"],
12
+ ] as const) {
13
+ assert.deepEqual(
14
+ await fileCandidateArgs({ patterns: [...patterns], literal, flags, multiline: true }),
10
15
  [
11
- [["a"], ["."], ["b"]],
12
- [["-"], ["é"]],
16
+ ...COMMON_RG_ARGS,
17
+ "--files-with-matches",
18
+ "--engine=default",
19
+ "--case-sensitive",
20
+ "--encoding=none",
21
+ "-e",
22
+ pattern,
13
23
  ],
14
- "a\\x{2e}b|\\x{2d}\\x{e9}",
15
- ],
16
- [[[["K", "k", "K"], ["_"], ["9"]]], "[Kk\\x{212a}]_9"],
17
- ] as const) {
18
- assert.deepEqual(candidateArgs({ kind: "literals", literals }), [
19
- ...COMMON_RG_ARGS,
20
- "--files-with-matches",
21
- "--engine=default",
22
- "--case-sensitive",
23
- "--encoding=none",
24
- "-e",
25
- pattern,
26
- ]);
24
+ );
27
25
  }
28
26
  });