@criogaid/pi-hashline-edit 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -7,6 +7,11 @@ import { byteRevision } from "./file-commit.ts";
7
7
  import { join } from "node:path";
8
8
  import { scanTextFile, scanTextLines } from "./text-stream.ts";
9
9
  import { splitLines } from "../core/lines.ts";
10
+ import { isUtf8 } from "node:buffer";
11
+ import { readFile } from "node:fs/promises";
12
+ import { truncateSync } from "node:fs";
13
+ import { Utf8DecodingError } from "../core/text.ts";
14
+ import { HashlineError } from "../core/errors.ts";
10
15
 
11
16
  async function withFile(run: (path: string) => Promise<void>) {
12
17
  const directory = await mkdtemp(join(tmpdir(), "hashline-stream-"));
@@ -53,7 +58,7 @@ test("streamed byte digests preserve the source revision across BOM, CRLF, and c
53
58
  const source = Buffer.from(`\uFEFFfirst\r\n${"a".repeat(65536)}\r\nlast\r`);
54
59
  await writeFile(path, source);
55
60
  const first = createHash("sha256");
56
- const stats = await scanTextFile(path, undefined, undefined, (bytes) => first.update(bytes));
61
+ const stats = await scanTextFile(path, { onBytes: (bytes) => first.update(bytes) });
57
62
  assert.equal(stats.hasCrLf, true);
58
63
  assert.equal(first.digest("hex"), byteRevision(source));
59
64
  const second = createHash("sha256");
@@ -98,7 +103,7 @@ test("streamed validation checks the entire file and gives NUL precedence over m
98
103
  (number) => number === 1,
99
104
  () => {},
100
105
  ),
101
- /UNSUPPORTED_ENCODING/,
106
+ (error: unknown) => error instanceof Utf8DecodingError,
102
107
  );
103
108
  await writeFile(
104
109
  path,
@@ -112,8 +117,8 @@ test("streamed reads propagate cancellation", async () =>
112
117
  await writeFile(path, "a".repeat(2 * 65536));
113
118
  const controller = new AbortController();
114
119
  await assert.rejects(
115
- scanTextFile(path, () => controller.abort(), controller.signal),
116
- { message: "Operation aborted" },
120
+ scanTextFile(path, { onChunk: () => controller.abort(), signal: controller.signal }),
121
+ (error: unknown) => error instanceof HashlineError && error.errorCode === "OPERATION_ABORTED",
117
122
  );
118
123
  }));
119
124
 
@@ -143,7 +148,10 @@ test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves
143
148
  assert.equal(stats.hasCrLf, true);
144
149
  assert.deepEqual(lines, splitLines(source.toString("utf8")));
145
150
  assert.equal(hash.digest("hex"), byteRevision(source));
146
- await assert.rejects(scanTextFile(path), /UNSUPPORTED_ENCODING/);
151
+ await assert.rejects(
152
+ scanTextFile(path),
153
+ (error: unknown) => error instanceof Utf8DecodingError,
154
+ );
147
155
  }));
148
156
 
149
157
  test("strict scans read all bytes but stop emitting text after a decoding error", async () =>
@@ -157,15 +165,13 @@ test("strict scans read all bytes but stop emitting text after a decoding error"
157
165
  const emitted: string[] = [];
158
166
  const scanned: Buffer[] = [];
159
167
  await assert.rejects(
160
- scanTextFile(
161
- path,
162
- (text) => {
168
+ scanTextFile(path, {
169
+ onChunk: (text) => {
163
170
  emitted.push(text);
164
171
  },
165
- undefined,
166
- (bytes) => scanned.push(bytes),
167
- ),
168
- /UNSUPPORTED_ENCODING/,
172
+ onBytes: (bytes) => scanned.push(bytes),
173
+ }),
174
+ (error: unknown) => error instanceof Utf8DecodingError,
169
175
  );
170
176
  assert.equal(emitted.join(""), prefix.toString("utf8"));
171
177
  assert.deepEqual(Buffer.concat(scanned), source);
@@ -178,15 +184,12 @@ test("lossy scans flush a multibyte sequence split across chunks and incomplete
178
184
  const source = Buffer.concat([prefix, Buffer.from([0xf0, 0x9f])]);
179
185
  await writeFile(path, source);
180
186
  const emitted: string[] = [];
181
- const stats = await scanTextFile(
182
- path,
183
- (text) => {
187
+ const stats = await scanTextFile(path, {
188
+ onChunk: (text) => {
184
189
  emitted.push(text);
185
190
  },
186
- undefined,
187
- undefined,
188
- "lossy",
189
- );
191
+ decoding: "lossy",
192
+ });
190
193
  assert.equal(emitted.join(""), prefix.toString("utf8") + "�");
191
194
  assert.equal(emitted.at(-1), "�");
192
195
  assert.equal(stats.validUtf8, false);
@@ -202,13 +205,10 @@ test("lossy scans without a text consumer report validity and retain all raw byt
202
205
  ]);
203
206
  await writeFile(path, source);
204
207
  const scanned: Buffer[] = [];
205
- const stats = await scanTextFile(
206
- path,
207
- undefined,
208
- undefined,
209
- (bytes) => scanned.push(bytes),
210
- "lossy",
211
- );
208
+ const stats = await scanTextFile(path, {
209
+ onBytes: (bytes) => scanned.push(bytes),
210
+ decoding: "lossy",
211
+ });
212
212
  assert.deepEqual(Buffer.concat(scanned), source);
213
213
  assert.equal(stats.validUtf8, false);
214
214
  assert.equal(stats.hasNul, false);
@@ -231,15 +231,13 @@ test("NUL suppresses its chunk and all later text without flushing a pending seq
231
231
  for (const decoding of ["strict", "lossy"] as const) {
232
232
  const emitted: string[] = [];
233
233
  const scanned: Buffer[] = [];
234
- const stats = await scanTextFile(
235
- path,
236
- (text) => {
234
+ const stats = await scanTextFile(path, {
235
+ onChunk: (text) => {
237
236
  emitted.push(text);
238
237
  },
239
- undefined,
240
- (bytes) => scanned.push(bytes),
238
+ onBytes: (bytes) => scanned.push(bytes),
241
239
  decoding,
242
- );
240
+ });
243
241
  assert.equal(stats.hasNul, true);
244
242
  assert.equal(emitted.join(""), prefix.toString("utf8"));
245
243
  assert.deepEqual(Buffer.concat(scanned), source);
@@ -255,17 +253,48 @@ test("NUL takes precedence over earlier malformed UTF-8 in strict and lossy scan
255
253
  await writeFile(path, source);
256
254
  for (const decoding of ["strict", "lossy"] as const) {
257
255
  const emitted: string[] = [];
258
- const stats = await scanTextFile(
259
- path,
260
- (text) => {
256
+ const stats = await scanTextFile(path, {
257
+ onChunk: (text) => {
261
258
  emitted.push(text);
262
259
  },
263
- undefined,
264
- undefined,
265
260
  decoding,
266
- );
261
+ });
267
262
  assert.equal(stats.hasNul, true);
268
263
  assert.equal(stats.validUtf8, false);
269
264
  assert.equal(emitted.join(""), decoding === "strict" ? "" : invalid.toString("utf8"));
270
265
  }
271
266
  }));
267
+
268
+ test("valid file truncated across a pending UTF-8 sequence → scans report a changed file", async () =>
269
+ withFile(async (path) => {
270
+ const chunkBytes = 64 * 1024;
271
+ const source = Buffer.from(
272
+ "x".repeat(chunkBytes - 1) +
273
+ "中" +
274
+ "x".repeat(chunkBytes - 3) +
275
+ "中" +
276
+ "tail".repeat(chunkBytes),
277
+ );
278
+ assert.equal(isUtf8(source), true);
279
+ for (const decoding of ["strict", "lossy"] as const) {
280
+ await writeFile(path, source);
281
+ let changed = false;
282
+ await assert.rejects(
283
+ scanTextFile(path, {
284
+ onBytes: () => {
285
+ if (changed) return;
286
+ changed = true;
287
+ truncateSync(path, chunkBytes - 1);
288
+ },
289
+ decoding,
290
+ }),
291
+ (error: unknown) => {
292
+ assert.ok(error instanceof Error);
293
+ assert.match(error.message, /File changed/);
294
+ assert.ok(!(error instanceof Utf8DecodingError));
295
+ return true;
296
+ },
297
+ );
298
+ assert.equal(isUtf8(await readFile(path)), true);
299
+ }
300
+ }));
@@ -1,86 +1,107 @@
1
+ /**
2
+ * Streaming text scans: one read of a file yields its bytes, its NUL and UTF-8 validity, line
3
+ * statistics, and the decoded text or selected lines.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
1
7
  import { createReadStream } from "node:fs";
2
- import { createUtf8Decoder, type Utf8Decoding } from "../core/text.ts";
8
+ import { createUtf8Decoder, Utf8DecodingError, type Utf8Decoding } from "../core/text.ts";
3
9
  import { throwIfCancelled } from "./error-text.ts";
10
+ import { withFileRead } from "./file-read.ts";
11
+
12
+ const TEXT_READ_CHUNK_BYTES = 64 * 1024;
4
13
 
5
14
  /** Scan whole-file bytes; lossy decoding reports validity without rejecting malformed UTF-8. */
6
15
  export async function scanTextFile(
7
16
  path: string,
8
- onChunk?: (text: string) => void | Promise<void>,
9
- signal?: AbortSignal,
10
- onBytes?: (bytes: Buffer) => void,
11
- decoding: Utf8Decoding = "strict",
17
+ options: {
18
+ readonly onChunk?: (text: string) => void | Promise<void>;
19
+ readonly signal?: AbortSignal;
20
+ readonly onBytes?: (bytes: Buffer) => void;
21
+ readonly decoding?: Utf8Decoding;
22
+ } = {},
12
23
  ) {
13
- const decode = createUtf8Decoder();
14
- // Strict decoding always decides validity; lossy text is decoded only for a chunk consumer.
15
- const lossy = decoding === "lossy" && onChunk ? createUtf8Decoder("lossy") : undefined;
16
- let byteLength = 0;
17
- let lineFeeds = 0;
18
- let lastByte = -1;
19
- let hasNul = false;
20
- let hasCrLf = false;
21
- let decodingError: unknown;
22
- const stream = createReadStream(path, { highWaterMark: 64 * 1024, signal });
23
- try {
24
- for await (const chunk of stream) {
25
- const bytes = chunk as Buffer;
26
- onBytes?.(bytes);
27
- byteLength += bytes.length;
28
- hasNul ||= bytes.includes(0);
29
- hasCrLf ||= (lastByte === 13 && bytes[0] === 10) || bytes.includes("\r\n");
30
- lastByte = bytes[bytes.length - 1];
31
- let offset = 0;
32
- while ((offset = bytes.indexOf(10, offset)) !== -1) {
33
- lineFeeds++;
34
- offset++;
24
+ const { onChunk, signal, onBytes, decoding = "strict" } = options;
25
+ return withFileRead(path, signal, async (handle) => {
26
+ const decode = createUtf8Decoder();
27
+ // Strict decoding always decides validity; lossy text is decoded only for a chunk consumer.
28
+ const lossy = decoding === "lossy" && onChunk ? createUtf8Decoder("lossy") : undefined;
29
+ let byteLength = 0;
30
+ let lineFeeds = 0;
31
+ let lastByte = -1;
32
+ let hasNul = false;
33
+ let hasCrLf = false;
34
+ let decodingError: unknown;
35
+ const stream = createReadStream(path, {
36
+ fd: handle,
37
+ autoClose: false,
38
+ highWaterMark: TEXT_READ_CHUNK_BYTES,
39
+ signal,
40
+ });
41
+ try {
42
+ for await (const chunk of stream) {
43
+ const bytes = chunk as Buffer;
44
+ onBytes?.(bytes);
45
+ byteLength += bytes.length;
46
+ hasNul ||= bytes.includes(0);
47
+ hasCrLf ||= (lastByte === 13 && bytes[0] === 10) || bytes.includes("\r\n");
48
+ lastByte = bytes[bytes.length - 1];
49
+ let offset = 0;
50
+ while ((offset = bytes.indexOf(10, offset)) !== -1) {
51
+ lineFeeds++;
52
+ offset++;
53
+ }
54
+ // NUL takes precedence even when an earlier chunk contained malformed UTF-8.
55
+ if (hasNul) continue;
56
+ let text: string | undefined;
57
+ if (!decodingError) {
58
+ try {
59
+ text = decode(bytes, true);
60
+ } catch (error) {
61
+ if (!(error instanceof Utf8DecodingError)) throw error;
62
+ decodingError = error;
63
+ }
64
+ }
65
+ if (lossy) text = lossy(bytes, true);
66
+ if (text !== undefined) await onChunk?.(text);
35
67
  }
36
- // NUL takes precedence even when an earlier chunk contained malformed UTF-8.
37
- if (hasNul) continue;
38
- let text: string | undefined;
68
+ } catch (error) {
69
+ // Node's stream abort raises its own AbortError; report the shared cancellation text.
70
+ throwIfCancelled(signal);
71
+ throw error;
72
+ }
73
+ throwIfCancelled(signal);
74
+ if (!hasNul) {
75
+ let tail: string | undefined;
39
76
  if (!decodingError) {
40
77
  try {
41
- text = decode(bytes, true);
78
+ tail = decode();
42
79
  } catch (error) {
80
+ if (!(error instanceof Utf8DecodingError)) throw error;
43
81
  decodingError = error;
44
82
  }
45
83
  }
46
- if (lossy) text = lossy(bytes, true);
47
- if (text !== undefined) await onChunk?.(text);
48
- }
49
- } catch (error) {
50
- // Node's stream abort raises its own AbortError; report the shared cancellation text.
51
- throwIfCancelled(signal);
52
- throw error;
53
- }
54
- throwIfCancelled(signal);
55
- if (!hasNul) {
56
- let tail: string | undefined;
57
- if (!decodingError) {
58
- try {
59
- tail = decode();
60
- } catch (error) {
61
- decodingError = error;
62
- }
84
+ if (lossy) tail = lossy();
85
+ else if (decodingError && decoding === "strict") throw decodingError;
86
+ if (tail) await onChunk?.(tail);
63
87
  }
64
- if (lossy) tail = lossy();
65
- else if (decodingError && decoding === "strict") throw decodingError;
66
- if (tail) await onChunk?.(tail);
67
- }
68
- return {
69
- byteLength,
70
- totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
71
- finalNewline: lastByte === -1 || lastByte === 10,
72
- hasNul,
73
- hasCrLf,
74
- validUtf8: !decodingError,
75
- };
88
+ return {
89
+ byteLength,
90
+ totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
91
+ finalNewline: lastByte === -1 || lastByte === 10,
92
+ hasNul,
93
+ hasCrLf,
94
+ validUtf8: !decodingError,
95
+ };
96
+ });
76
97
  }
77
98
 
78
99
  interface ScannedLine {
79
- number: number;
80
- byteLength: number;
81
- carriageReturns: number;
100
+ readonly number: number;
101
+ readonly byteLength: number;
102
+ readonly carriageReturns: number;
82
103
  /** Absent when the selected line exceeds maxLineBytes. */
83
- text: string | undefined;
104
+ readonly text: string | undefined;
84
105
  }
85
106
 
86
107
  /** Visit selected logical lines, retaining at most maxLineBytes of content per line. */
@@ -89,10 +110,10 @@ export async function scanTextLines(
89
110
  select: (number: number) => boolean,
90
111
  onLine: (line: ScannedLine) => void,
91
112
  options: {
92
- signal?: AbortSignal;
93
- maxLineBytes?: number;
94
- onBytes?: (bytes: Buffer) => void;
95
- decoding?: Utf8Decoding;
113
+ readonly signal?: AbortSignal;
114
+ readonly maxLineBytes?: number;
115
+ readonly onBytes?: (bytes: Buffer) => void;
116
+ readonly decoding?: Utf8Decoding;
96
117
  } = {},
97
118
  ) {
98
119
  const maxBytes = options.maxLineBytes ?? Infinity;
@@ -122,9 +143,12 @@ export async function scanTextLines(
122
143
  number++;
123
144
  selected = select(number);
124
145
  };
125
- const stats = await scanTextFile(
126
- path,
127
- (text) => {
146
+ const { signal, onBytes, decoding } = options;
147
+ const stats = await scanTextFile(path, {
148
+ signal,
149
+ onBytes,
150
+ decoding,
151
+ onChunk: (text) => {
128
152
  let start = 0;
129
153
  while (start < text.length) {
130
154
  const lf = text.indexOf("\n", start);
@@ -147,10 +171,7 @@ export async function scanTextLines(
147
171
  start = lf + 1;
148
172
  }
149
173
  },
150
- options.signal,
151
- options.onBytes,
152
- options.decoding,
153
- );
174
+ });
154
175
  if (!stats.hasNul && byteLength > 0) finish(false);
155
176
  return stats;
156
177
  }
@@ -8,16 +8,9 @@
8
8
  */
9
9
 
10
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
11
- import { join } from "node:path";
12
11
  import type { TestContext } from "node:test";
13
- import {
14
- createAgentSession,
15
- DefaultResourceLoader,
16
- type ExtensionToolContext,
17
- ModelRuntime,
18
- SessionManager,
19
- SettingsManager,
20
- } from "@earendil-works/pi-coding-agent";
12
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
13
+ import { openTestSession } from "../testing/session.testing.ts";
21
14
 
22
15
  interface CallableTool {
23
16
  readonly name: string;
@@ -52,36 +45,7 @@ export async function createToolContext(
52
45
  t: TestContext,
53
46
  mode: ExtensionToolContext["mode"] = "json",
54
47
  ) {
55
- const runtime = await ModelRuntime.create({
56
- authPath: join(cwd, "test-auth.json"),
57
- modelsPath: null,
58
- modelsStorePath: join(cwd, "test-models.json"),
59
- refreshOnCreate: false,
60
- allowModelNetwork: false,
61
- });
62
- const settingsManager = SettingsManager.inMemory();
63
- const loader = new DefaultResourceLoader({
64
- cwd,
65
- agentDir: cwd,
66
- settingsManager,
67
- noExtensions: true,
68
- noSkills: true,
69
- noPromptTemplates: true,
70
- noThemes: true,
71
- noContextFiles: true,
72
- });
73
- await loader.reload();
74
- const { session } = await createAgentSession({
75
- cwd,
76
- agentDir: cwd,
77
- modelRuntime: runtime,
78
- settingsManager,
79
- resourceLoader: loader,
80
- sessionManager: SessionManager.inMemory(cwd),
81
- tools: [],
82
- });
83
- t.after(() => session.dispose());
84
- await session.bindExtensions({});
48
+ const { session } = await openTestSession(t, { cwd, tools: [] });
85
49
  session.extensionRunner.setUIContext(undefined, mode);
86
50
  return session.extensionRunner.createToolContext("test", undefined);
87
51
  }
@@ -1,5 +1,6 @@
1
1
  import { Type, type Static } from "typebox";
2
2
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
3
+ import { Text } from "@earendil-works/pi-tui";
3
4
  import {
4
5
  createWriteToolDefinition,
5
6
  type ExtensionToolContext,
@@ -8,18 +9,19 @@ import {
8
9
  } from "@earendil-works/pi-coding-agent";
9
10
  import {
10
11
  ACTION_FUSION_GUIDELINES,
12
+ withThenRunDescription,
11
13
  withThenRunSchema,
12
14
  type ThenRunInput,
13
- type ActionFusionDetails,
14
15
  } from "./action-fusion.ts";
15
16
  import { commitFile, type CommitResult } from "./file-commit.ts";
16
- import { postProcessMutation } from "./mutation-result.ts";
17
17
  import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
- import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
19
18
  import { throwIfCancelled } from "./error-text.ts";
20
19
  import { createArgumentPreparer } from "./argument-validation.ts";
21
- import { unwritableTextReason } from "../core/text.ts";
22
- import { renderToolError } from "./render.ts";
20
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
21
+ import { unwritableTextError } from "../core/text.ts";
22
+ import { reportLines, renderToolError } from "./render.ts";
23
+ import type { MutationResultDetails } from "./mutation-result.ts";
24
+ import type { ReportDetails } from "./report.ts";
23
25
 
24
26
  const writeSchema = Type.Object(
25
27
  {
@@ -28,8 +30,8 @@ const writeSchema = Type.Object(
28
30
  description: "Complete file content, written exactly as supplied, including line endings.",
29
31
  }),
30
32
  mode: Type.Union([
31
- Type.Literal("create", { description: "Fail if the target already exists" }),
32
- Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
33
+ Type.Literal("create", { description: "Fail if the target already exists." }),
34
+ Type.Literal("overwrite", { description: "Fail if the target does not exist." }),
33
35
  ]),
34
36
  },
35
37
  { additionalProperties: false },
@@ -39,38 +41,55 @@ function createWriteSchema(actionFusion: boolean) {
39
41
  return withThenRunSchema(writeSchema, "write", actionFusion);
40
42
  }
41
43
  type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
42
- type WriteDetails = CommitResult & { path: string; actionFusion?: ActionFusionDetails };
44
+ type WriteMutationDetails = CommitResult & { path: string };
45
+ type WriteDetails = MutationResultDetails<WriteMutationDetails>;
46
+ /** The write card's call line shows the content; the command card owns then_run. */
47
+ const WRITE_CARD_SHOWN = new Set(["publication", "created", "then_run", "progressError"]);
43
48
  type WriteRenderContext = Parameters<
44
49
  NonNullable<ReturnType<typeof createWriteToolDefinition>["renderCall"]>
45
50
  >[2];
46
51
 
47
- export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
52
+ export function makeWriteOverride(
53
+ cwd: string,
54
+ fusion?: ActionFusionExecutor,
55
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
56
+ ) {
48
57
  const parameters = createWriteSchema(fusion !== undefined);
49
58
  const builtin = createWriteToolDefinition(cwd);
50
59
  return {
51
60
  name: "write" as const,
52
61
  label: "write",
53
- description:
54
- "Write a whole file exactly as supplied, including its line endings. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
62
+ description: withThenRunDescription(
63
+ "Write a whole file exactly as supplied, including its line endings. Do not use write for partial changes to an existing file; use edit or replace. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
64
+ fusion !== undefined,
65
+ ),
55
66
  promptSnippet: "Write complete file content to a path",
56
- promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
67
+ promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
57
68
  parameters,
58
- prepareArguments: createArgumentPreparer("write", parameters, (args, report) => {
59
- const content = (args as { content?: unknown } | null)?.content;
60
- const reason = typeof content === "string" ? unwritableTextReason(content) : undefined;
61
- if (reason) report("content", reason);
62
- }),
69
+ prepareArguments: createArgumentPreparer(
70
+ "write",
71
+ parameters,
72
+ (args, report) => {
73
+ const content = (args as { content?: unknown } | null)?.content;
74
+ const unwritable = typeof content === "string" ? unwritableTextError(content) : undefined;
75
+ if (unwritable) report("content", unwritable.message);
76
+ },
77
+ budgets,
78
+ ),
63
79
  renderShell: "default" as const,
64
80
  renderCall(args: WriteParams, theme: Theme, context: WriteRenderContext) {
65
81
  return builtin.renderCall!(args, theme, context);
66
82
  },
67
83
  renderResult(
68
- result: AgentToolResult<WriteDetails>,
84
+ result: AgentToolResult<(Partial<WriteMutationDetails> & Partial<ReportDetails>) | undefined>,
69
85
  options: ToolRenderResultOptions,
70
86
  theme: Theme,
71
87
  context: WriteRenderContext,
72
88
  ) {
73
89
  if (context.isError) return renderToolError(result, theme, options.expanded);
90
+ const report = result.details?.report;
91
+ const facts = report ? reportLines(report, theme, WRITE_CARD_SHOWN) : [];
92
+ if (facts.length) return new Text(facts.join("\n"), 0, 0);
74
93
  return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
75
94
  },
76
95
  async execute(
@@ -80,30 +99,22 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
80
99
  onUpdate: AgentToolUpdateCallback<WriteDetails> | undefined,
81
100
  ctx: ExtensionToolContext,
82
101
  ) {
83
- return executeMutation<Omit<WriteParams, "then_run">, WriteDetails>(
102
+ return executeMutation<WriteParams, WriteMutationDetails, "write">(
84
103
  {
104
+ tool: "write",
85
105
  cwd,
86
106
  fusion,
107
+ budgets,
87
108
  async run(mutationParams, { absolutePath, displayPath, signal }) {
88
- throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
89
- const result = await commitFile(absolutePath, mutationParams.content, {
109
+ throwIfCancelled(signal);
110
+ const commit = await commitFile(absolutePath, mutationParams.content, {
90
111
  mode: mutationParams.mode,
91
112
  signal,
92
113
  });
93
114
  return {
94
- commit: result,
95
- result: postProcessMutation("write", result.publication, () => ({
96
- content: [
97
- {
98
- type: "text" as const,
99
- text:
100
- result.publication === "NOT_PUBLISHED"
101
- ? `Wrote ${displayPath} (no net change).`
102
- : `${result.created ? "Created" : "Wrote"} ${displayPath}.`,
103
- },
104
- ],
105
- details: { path: displayPath, ...result },
106
- })),
115
+ commit,
116
+ details: { path: displayPath, ...commit },
117
+ facts: commit.created ? { created: true } : {},
107
118
  };
108
119
  },
109
120
  },