@criogaid/pi-hashline-edit 0.5.0 → 0.5.1

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.
package/src/pi/pi.test.ts CHANGED
@@ -101,7 +101,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
101
101
  );
102
102
  const matches = await callTool(
103
103
  makeGrepOverride(dir, DEFAULT_CONFIG),
104
- { path: `@${url}`, pattern: "edited" },
104
+ { path: `@${url}`, pattern: "edited", literal: true },
105
105
  { toolCallId: "grep" },
106
106
  );
107
107
  assert.match(matches.content[0].text, /edited/);
@@ -159,7 +159,7 @@ export function makeReadOverride(
159
159
  const { isPartial, expanded } = options;
160
160
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
161
161
  const content = result.content?.[0];
162
- if (context?.isError) return renderToolError(result, theme);
162
+ if (context?.isError) return renderToolError(result, theme, expanded);
163
163
  if (result.details?.nativeRead) return builtin.renderResult!(result, options, theme, context);
164
164
  // Collapsed (not expanded): show nothing — the call line carries the
165
165
  // title, matching the built-in read's fold behavior.
@@ -53,7 +53,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
53
53
  ]);
54
54
  assert.equal(grep.parameters.additionalProperties, false);
55
55
  await assert.rejects(
56
- callTool(grep, { pattern: "needle", noIgnore: false }),
56
+ callTool(grep, { pattern: "needle", literal: true, noIgnore: false }),
57
57
  /Validation failed for tool "grep":\n {2}- noIgnore: schema is false/,
58
58
  );
59
59
  for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
@@ -173,7 +173,11 @@ test("mutation cards use Fusion by default and explicit false removes command su
173
173
  `${name} mutation failure should turn red`,
174
174
  );
175
175
  assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
176
- assert.doesNotMatch(output, /the command was not run|then_run:skipped/);
176
+ failedCard.setExpanded(true);
177
+ const expandedError = failedCard.render(400).join("\n");
178
+ for (const line of error.message.split("\n")) {
179
+ assert.ok(expandedError.includes(line), `${name} hid a failure diagnostic`);
180
+ }
177
181
  assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
178
182
  const entry = entries.find(
179
183
  (entry) =>
@@ -1,6 +1,11 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { generateDiffString, initTheme } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ generateDiffString,
5
+ initTheme,
6
+ type ToolDefinition,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { TSchema } from "typebox";
4
9
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
5
10
  import { displayCarriageReturns } from "./anchor-format.ts";
6
11
  import { makeEditOverride } from "./edit-tool.ts";
@@ -11,6 +16,10 @@ import { makeWriteOverride } from "./write-tool.ts";
11
16
  import { generateMutationDetails } from "./mutation-result.ts";
12
17
  import type { ActionFusionDetails } from "./action-fusion.ts";
13
18
  import { DEFAULT_CONFIG } from "./config.ts";
19
+ import { toDisplayLines } from "./grep-render.ts";
20
+ import { makeReadOverride } from "./read-tool.ts";
21
+ import { callTool } from "./tool-call.testing.ts";
22
+ import { renderToolError } from "./render.ts";
14
23
 
15
24
  const versions = { publishedRevision: "r", observedRevision: "r" };
16
25
  const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
@@ -252,3 +261,120 @@ test("withMutationStatus renderResult initializes mutationShell defensively", ()
252
261
  assert.ok(context.state.mutationShell);
253
262
  assert.ok(context.state.mutationShell.box);
254
263
  });
264
+
265
+ test("grep renders anchored and plain groups with shared width and folded indentation", () => {
266
+ initTheme("dark");
267
+ const notice =
268
+ "[Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors]";
269
+ const raw = [
270
+ "valid.ts · 2 matches",
271
+ "9#ABCD│ alpha",
272
+ "10#ABCD│ beta",
273
+ "",
274
+ "invalid.txt · 2 matches",
275
+ "100│\tbad �",
276
+ "7│\t\tother",
277
+ notice,
278
+ ].join("\n");
279
+ assert.deepEqual(toDisplayLines(raw, theme), [
280
+ theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
281
+ theme.fg("dim", " 9: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "alpha"),
282
+ theme.fg("dim", " 10: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", " beta"),
283
+ theme.fg("toolOutput", ""),
284
+ theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
285
+ theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
286
+ theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
287
+ theme.fg("warning", notice),
288
+ ]);
289
+ });
290
+
291
+ test("grep renders plain and anchored rows in one group without exposing hashes", () => {
292
+ initTheme("dark");
293
+ const raw = "mixed.txt · 2 matches\n1#ABCD│alpha\n12│ 7#ABCD│literal content";
294
+ assert.deepEqual(toDisplayLines(raw, theme), [
295
+ theme.fg("success", "mixed.txt") + theme.fg("dim", " · 2 matches"),
296
+ theme.fg("dim", " 1: ") + theme.fg("toolOutput", "alpha"),
297
+ theme.fg("dim", " 12: ") + theme.fg("toolOutput", " 7#ABCD│literal content"),
298
+ ]);
299
+ });
300
+
301
+ test("all file tools expose validation causes in collapsed and expanded error cards", async () => {
302
+ initTheme("dark");
303
+ const cwd = process.cwd();
304
+ const tools = [
305
+ makeReadOverride(cwd, DEFAULT_CONFIG),
306
+ withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
307
+ withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
308
+ withMutationStatus(makeWriteOverride(cwd)),
309
+ ];
310
+ for (const tool of tools) {
311
+ for (const fused of [false, true]) {
312
+ const args = {
313
+ path: "unused.txt",
314
+ content: "unused",
315
+ edits: [{ op: "append" as const, body: ["unused"] }],
316
+ replacements: [{ find: "unused", replace: "unused" }],
317
+ unexpected: true,
318
+ ...(fused ? { then_run: { command: "must-not-run" } } : {}),
319
+ };
320
+ let errorText = "";
321
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
322
+ assert.ok(error instanceof Error);
323
+ errorText = error.message;
324
+ return true;
325
+ });
326
+ const cause = errorText.split("\n").find((line) => line.includes("unexpected"));
327
+ assert.ok(cause);
328
+ for (const expanded of [false, true]) {
329
+ const context = {
330
+ args,
331
+ state: {},
332
+ toolCallId: "validation",
333
+ invalidate() {},
334
+ lastComponent: undefined,
335
+ cwd,
336
+ executionStarted: true,
337
+ argsComplete: true,
338
+ isPartial: false,
339
+ expanded,
340
+ showImages: false,
341
+ isError: true,
342
+ };
343
+ const call = tool.renderCall?.(args, theme, context);
344
+ // Pi supplies no tool-specific details when argument validation fails.
345
+ const renderError = tool.renderResult as NonNullable<
346
+ ToolDefinition<TSchema, undefined>["renderResult"]
347
+ >;
348
+ const result = renderError(
349
+ { content: [{ type: "text", text: errorText }], details: undefined },
350
+ { isPartial: false, expanded },
351
+ theme,
352
+ context,
353
+ );
354
+ const card = tool.renderShell === "self" ? call : result;
355
+ assert.ok(card);
356
+ assert.ok(
357
+ card.render(200).join("\n").includes(cause),
358
+ `${tool.name} hid the validation cause`,
359
+ );
360
+ }
361
+ }
362
+ }
363
+ });
364
+
365
+ test("expanded errors retain every text block while collapsed errors stay bounded", () => {
366
+ initTheme("dark");
367
+ const diagnosticLineCount = 80;
368
+ const result = {
369
+ content: [
370
+ { type: "text" as const, text: "Error header\n" + "context\n".repeat(diagnosticLineCount) },
371
+ { type: "text" as const, text: "Final cause: permission denied" },
372
+ ],
373
+ };
374
+ const collapsed = renderToolError(result, theme, false).render(120).join("\n");
375
+ const expanded = renderToolError(result, theme, true).render(120).join("\n");
376
+ assert.match(collapsed, /Error header/);
377
+ assert.doesNotMatch(collapsed, /Final cause/);
378
+ assert.match(expanded, /Final cause: permission denied/);
379
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
380
+ });
package/src/pi/render.ts CHANGED
@@ -16,6 +16,8 @@ import { Text, type Component } from "@earendil-works/pi-tui";
16
16
 
17
17
  /** Max diff lines shown when a result is rendered collapsed. */
18
18
  const MAX_COLLAPSED_DIFF_LINES = 24;
19
+ /** Collapsed tool output and errors share a bounded preview. */
20
+ const MAX_COLLAPSED_OUTPUT_LINES = 15;
19
21
 
20
22
  /**
21
23
  * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
@@ -105,14 +107,35 @@ export function renderMutationCall<TArgs>(
105
107
  return text;
106
108
  }
107
109
 
108
- /** Keep model-facing diagnostic details out of the compact error row. */
110
+ /** Render a bounded preview; expanding reveals every supplied line. */
111
+ export function renderOutputPreview(
112
+ lines: readonly string[],
113
+ expanded: boolean,
114
+ theme: Theme,
115
+ ): Text {
116
+ const shown = expanded ? lines : lines.slice(0, MAX_COLLAPSED_OUTPUT_LINES);
117
+ const more =
118
+ shown.length < lines.length
119
+ ? `\n${theme.fg("muted", `… (${lines.length - shown.length} more lines)`)}`
120
+ : "";
121
+ return new Text(shown.join("\n") + more, 0, 0);
122
+ }
123
+
124
+ /** Preserve diagnostic causes and recovery hints from every text block. */
109
125
  export function renderToolError(
110
126
  result: Pick<AgentToolResult<unknown>, "content">,
111
127
  theme: Theme,
128
+ expanded: boolean,
112
129
  ): Text {
113
- const content = result.content?.[0];
114
- const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
115
- return new Text(theme.fg("error", text), 0, 0);
130
+ const text = result.content
131
+ .filter((block) => block.type === "text")
132
+ .map((block) => block.text)
133
+ .join("\n");
134
+ return renderOutputPreview(
135
+ (text || "Error").split("\n").map((line) => theme.fg("error", line)),
136
+ expanded,
137
+ theme,
138
+ );
116
139
  }
117
140
 
118
141
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
@@ -132,7 +155,7 @@ export function renderMutationResult<TArgs>(
132
155
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED")
133
156
  return new Text(theme.fg("warning", pending), 0, 0);
134
157
  const content = result.content?.[0];
135
- if (context.isError) return renderToolError(result, theme);
158
+ if (context.isError) return renderToolError(result, theme, expanded);
136
159
  const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
137
160
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
138
161
  publishDiffCounts(diff, context, (counts) => {
@@ -210,7 +210,7 @@ export function makeReplaceTool(
210
210
  "Replace every match of one or more literal or JavaScript-regex rules in a file. Overlapping matches or a rule with no match reject the whole call. Returns a diff and fresh anchors.",
211
211
  promptSnippet: "Replace matching text across a file",
212
212
  promptGuidelines: [
213
- "Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
213
+ "Use replace for repeated literal or regex substitutions, or short changes inside long lines; use edit for line or block changes, insertions, and deletions.",
214
214
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
215
215
  ],
216
216
  parameters,
@@ -6,6 +6,8 @@
6
6
  * @module pi-hashline-edit/pi
7
7
  */
8
8
 
9
+ import { StringDecoder } from "node:string_decoder";
10
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
9
11
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
10
12
  import type { Readable } from "node:stream";
11
13
  import { escapeRegex } from "../core/text.ts";
@@ -14,7 +16,7 @@ import { throwIfCancelled } from "./error-text.ts";
14
16
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
15
17
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
16
18
  const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`;
17
- /** Retained ripgrep stderr; diagnostics beyond this are dropped. */
19
+ /** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
18
20
  export const MAX_RG_STDERR_BYTES = 64 * 1024;
19
21
  /** Probe runs read only a short stdout; more means an unexpected rg mode. */
20
22
  const MAX_RG_PROBE_OUTPUT_BYTES = 64 * 1024;
@@ -52,7 +54,8 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
52
54
  shell: false,
53
55
  env,
54
56
  });
55
- let stderr = "";
57
+ const stderr = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
58
+ const stderrDecoder = new StringDecoder("utf8");
56
59
  let error: Error | undefined;
57
60
  let closed = false;
58
61
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -66,8 +69,7 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
66
69
  };
67
70
 
68
71
  child.stderr.on("data", (chunk: Buffer) => {
69
- if (stderr.length < MAX_RG_STDERR_BYTES)
70
- stderr += chunk.toString("utf8").slice(0, MAX_RG_STDERR_BYTES - stderr.length);
72
+ stderr.append(stderrDecoder.write(chunk));
71
73
  });
72
74
  child.on("error", (cause) => {
73
75
  error = cause;
@@ -83,7 +85,8 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
83
85
  closed = true;
84
86
  if (timer) clearTimeout(timer);
85
87
  signal?.removeEventListener("abort", kill);
86
- resolve({ code, stderr, error });
88
+ stderr.append(stderrDecoder.end());
89
+ resolve({ code, stderr: stderr.toString(), error });
87
90
  });
88
91
  });
89
92
  signal?.addEventListener("abort", kill, { once: true });
@@ -1,3 +1,4 @@
1
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
1
2
  import { mkdtemp, open, rm } from "node:fs/promises";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join, resolve, sep } from "node:path";
@@ -43,12 +44,14 @@ async function writeLfSnapshot(source: string, destination: string, signal?: Abo
43
44
  export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, signal, onLine) => {
44
45
  let directory: string | undefined;
45
46
  const result: RgRunResult = { code: 1, stderr: "", stopped: false };
46
- // LF-only files pass through to rg directly; only CRLF files need temp snapshots.
47
+ const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
48
+ // Only valid UTF-8 CRLF files use LF snapshots; malformed UTF-8 keeps its raw search view.
47
49
  const snapshots = new Map<string, string>();
48
50
  const batchPaths: string[] = [];
49
51
  let batchBytes = 0;
50
52
  const record = (run: RgRunResult) => {
51
- result.stderr = (result.stderr + run.stderr).slice(0, MAX_RG_STDERR_BYTES);
53
+ diagnostics.append(run.stderr);
54
+ result.stderr = diagnostics.toString();
52
55
  if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
53
56
  else if (run.code === 0 && result.code === 1) result.code = 0;
54
57
  result.stopped ||= run.stopped;
@@ -109,15 +112,15 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
109
112
  const original = resolve(path);
110
113
  if (directory && original.startsWith(directory + sep)) return true;
111
114
  try {
112
- const info = await scanTextFile(original, undefined, signal);
113
- if (info.hasCrLf && !info.hasNul) {
115
+ const info = await scanTextFile(original, undefined, signal, undefined, "lossy");
116
+ if (info.hasNul) return true;
117
+ if (info.hasCrLf && info.validUtf8) {
114
118
  const dir = await ensureDirectory();
115
119
  const snapshot = join(dir, String(snapshots.size));
116
120
  await writeLfSnapshot(original, snapshot, signal);
117
121
  snapshots.set(snapshot, original);
118
122
  batchPaths.push(snapshot);
119
123
  } else {
120
- // Binary files retain their raw bytes; confirmed content hits are rejected later.
121
124
  batchPaths.push(original);
122
125
  }
123
126
  batchBytes += info.byteLength;
@@ -116,3 +116,156 @@ test("streamed reads propagate cancellation", async () =>
116
116
  { message: "Operation aborted" },
117
117
  );
118
118
  }));
119
+
120
+ test("lossy decoding reports invalid UTF-8 across chunk boundaries and preserves raw revisions", async () =>
121
+ withFile(async (path) => {
122
+ const source = Buffer.concat([
123
+ Buffer.from("\uFEFF" + "a".repeat(65532)),
124
+ Buffer.from([0xf0, 0x9f]),
125
+ Buffer.from("\r\nneedle "),
126
+ Buffer.from([0xff]),
127
+ Buffer.from("\r\nlast"),
128
+ ]);
129
+ await writeFile(path, source);
130
+ const hash = createHash("sha256");
131
+ const lines: string[] = [];
132
+ const stats = await scanTextLines(
133
+ path,
134
+ () => true,
135
+ (line) => lines.push(line.text ?? ""),
136
+ {
137
+ decoding: "lossy",
138
+ onBytes: (bytes) => hash.update(bytes),
139
+ },
140
+ );
141
+ assert.equal(stats.validUtf8, false);
142
+ assert.equal(stats.hasNul, false);
143
+ assert.equal(stats.hasCrLf, true);
144
+ assert.deepEqual(lines, splitLines(source.toString("utf8")));
145
+ assert.equal(hash.digest("hex"), byteRevision(source));
146
+ await assert.rejects(scanTextFile(path), /UNSUPPORTED_ENCODING/);
147
+ }));
148
+
149
+ test("strict scans read all bytes but stop emitting text after a decoding error", async () =>
150
+ withFile(async (path) => {
151
+ const chunkBytes = 64 * 1024;
152
+ const prefix = Buffer.alloc(chunkBytes, "a");
153
+ const invalid = Buffer.alloc(chunkBytes, "b");
154
+ invalid[0] = 0xff;
155
+ const source = Buffer.concat([prefix, invalid, Buffer.from("later text\n")]);
156
+ await writeFile(path, source);
157
+ const emitted: string[] = [];
158
+ const scanned: Buffer[] = [];
159
+ await assert.rejects(
160
+ scanTextFile(
161
+ path,
162
+ (text) => {
163
+ emitted.push(text);
164
+ },
165
+ undefined,
166
+ (bytes) => scanned.push(bytes),
167
+ ),
168
+ /UNSUPPORTED_ENCODING/,
169
+ );
170
+ assert.equal(emitted.join(""), prefix.toString("utf8"));
171
+ assert.deepEqual(Buffer.concat(scanned), source);
172
+ }));
173
+
174
+ test("lossy scans flush a multibyte sequence split across chunks and incomplete at EOF", async () =>
175
+ withFile(async (path) => {
176
+ const chunkBytes = 64 * 1024;
177
+ const prefix = Buffer.alloc(chunkBytes - 1, "a");
178
+ const source = Buffer.concat([prefix, Buffer.from([0xf0, 0x9f])]);
179
+ await writeFile(path, source);
180
+ const emitted: string[] = [];
181
+ const stats = await scanTextFile(
182
+ path,
183
+ (text) => {
184
+ emitted.push(text);
185
+ },
186
+ undefined,
187
+ undefined,
188
+ "lossy",
189
+ );
190
+ assert.equal(emitted.join(""), prefix.toString("utf8") + "�");
191
+ assert.equal(emitted.at(-1), "�");
192
+ assert.equal(stats.validUtf8, false);
193
+ assert.equal(stats.hasNul, false);
194
+ assert.equal(stats.byteLength, source.length);
195
+ }));
196
+
197
+ test("lossy scans without a text consumer report validity and retain all raw bytes", async () =>
198
+ withFile(async (path) => {
199
+ const source = Buffer.concat([
200
+ Buffer.from("\ufeffbefore\r\n"),
201
+ Buffer.from([0xff, 0xf0, 0x9f]),
202
+ ]);
203
+ await writeFile(path, source);
204
+ const scanned: Buffer[] = [];
205
+ const stats = await scanTextFile(
206
+ path,
207
+ undefined,
208
+ undefined,
209
+ (bytes) => scanned.push(bytes),
210
+ "lossy",
211
+ );
212
+ assert.deepEqual(Buffer.concat(scanned), source);
213
+ assert.equal(stats.validUtf8, false);
214
+ assert.equal(stats.hasNul, false);
215
+ assert.equal(stats.hasCrLf, true);
216
+ assert.equal(stats.totalLines, 2);
217
+ assert.equal(stats.finalNewline, false);
218
+ assert.equal(stats.byteLength, source.length);
219
+ }));
220
+
221
+ test("NUL suppresses its chunk and all later text without flushing a pending sequence", async () =>
222
+ withFile(async (path) => {
223
+ const chunkBytes = 64 * 1024;
224
+ const prefix = Buffer.alloc(chunkBytes - 1, "a");
225
+ const source = Buffer.concat([
226
+ prefix,
227
+ Buffer.from([0xf0, 0, 0x9f]),
228
+ Buffer.alloc(chunkBytes, "b"),
229
+ ]);
230
+ await writeFile(path, source);
231
+ for (const decoding of ["strict", "lossy"] as const) {
232
+ const emitted: string[] = [];
233
+ const scanned: Buffer[] = [];
234
+ const stats = await scanTextFile(
235
+ path,
236
+ (text) => {
237
+ emitted.push(text);
238
+ },
239
+ undefined,
240
+ (bytes) => scanned.push(bytes),
241
+ decoding,
242
+ );
243
+ assert.equal(stats.hasNul, true);
244
+ assert.equal(emitted.join(""), prefix.toString("utf8"));
245
+ assert.deepEqual(Buffer.concat(scanned), source);
246
+ }
247
+ }));
248
+
249
+ test("NUL takes precedence over earlier malformed UTF-8 in strict and lossy scans", async () =>
250
+ withFile(async (path) => {
251
+ const chunkBytes = 64 * 1024;
252
+ const invalid = Buffer.alloc(chunkBytes, "a");
253
+ invalid[0] = 0xff;
254
+ const source = Buffer.concat([invalid, Buffer.from("\0later\n")]);
255
+ await writeFile(path, source);
256
+ for (const decoding of ["strict", "lossy"] as const) {
257
+ const emitted: string[] = [];
258
+ const stats = await scanTextFile(
259
+ path,
260
+ (text) => {
261
+ emitted.push(text);
262
+ },
263
+ undefined,
264
+ undefined,
265
+ decoding,
266
+ );
267
+ assert.equal(stats.hasNul, true);
268
+ assert.equal(stats.validUtf8, false);
269
+ assert.equal(emitted.join(""), decoding === "strict" ? "" : invalid.toString("utf8"));
270
+ }
271
+ }));
@@ -1,15 +1,18 @@
1
1
  import { createReadStream } from "node:fs";
2
- import { createUtf8Decoder } from "../core/text.ts";
2
+ import { createUtf8Decoder, type Utf8Decoding } from "../core/text.ts";
3
3
  import { throwIfCancelled } from "./error-text.ts";
4
4
 
5
- /** Scan and validate the whole file with bounded chunks, preserving BOM and raw line endings. */
5
+ /** Scan whole-file bytes; lossy decoding reports validity without rejecting malformed UTF-8. */
6
6
  export async function scanTextFile(
7
7
  path: string,
8
8
  onChunk?: (text: string) => void | Promise<void>,
9
9
  signal?: AbortSignal,
10
10
  onBytes?: (bytes: Buffer) => void,
11
+ decoding: Utf8Decoding = "strict",
11
12
  ) {
12
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;
13
16
  let byteLength = 0;
14
17
  let lineFeeds = 0;
15
18
  let lastByte = -1;
@@ -31,15 +34,17 @@ export async function scanTextFile(
31
34
  offset++;
32
35
  }
33
36
  // NUL takes precedence even when an earlier chunk contained malformed UTF-8.
34
- if (hasNul || decodingError) continue;
35
- let text: string;
36
- try {
37
- text = decode(bytes, true);
38
- } catch (error) {
39
- decodingError = error;
40
- continue;
37
+ if (hasNul) continue;
38
+ let text: string | undefined;
39
+ if (!decodingError) {
40
+ try {
41
+ text = decode(bytes, true);
42
+ } catch (error) {
43
+ decodingError = error;
44
+ }
41
45
  }
42
- await onChunk?.(text);
46
+ if (lossy) text = lossy(bytes, true);
47
+ if (text !== undefined) await onChunk?.(text);
43
48
  }
44
49
  } catch (error) {
45
50
  // Node's stream abort raises its own AbortError; report the shared cancellation text.
@@ -48,8 +53,16 @@ export async function scanTextFile(
48
53
  }
49
54
  throwIfCancelled(signal);
50
55
  if (!hasNul) {
51
- if (decodingError) throw decodingError;
52
- const tail = decode();
56
+ let tail: string | undefined;
57
+ if (!decodingError) {
58
+ try {
59
+ tail = decode();
60
+ } catch (error) {
61
+ decodingError = error;
62
+ }
63
+ }
64
+ if (lossy) tail = lossy();
65
+ else if (decodingError && decoding === "strict") throw decodingError;
53
66
  if (tail) await onChunk?.(tail);
54
67
  }
55
68
  return {
@@ -58,6 +71,7 @@ export async function scanTextFile(
58
71
  finalNewline: lastByte === -1 || lastByte === 10,
59
72
  hasNul,
60
73
  hasCrLf,
74
+ validUtf8: !decodingError,
61
75
  };
62
76
  }
63
77
 
@@ -74,7 +88,12 @@ export async function scanTextLines(
74
88
  path: string,
75
89
  select: (number: number) => boolean,
76
90
  onLine: (line: ScannedLine) => void,
77
- options: { signal?: AbortSignal; maxLineBytes?: number; onBytes?: (bytes: Buffer) => void } = {},
91
+ options: {
92
+ signal?: AbortSignal;
93
+ maxLineBytes?: number;
94
+ onBytes?: (bytes: Buffer) => void;
95
+ decoding?: Utf8Decoding;
96
+ } = {},
78
97
  ) {
79
98
  const maxBytes = options.maxLineBytes ?? Infinity;
80
99
  let number = 1;
@@ -130,6 +149,7 @@ export async function scanTextLines(
130
149
  },
131
150
  options.signal,
132
151
  options.onBytes,
152
+ options.decoding,
133
153
  );
134
154
  if (!stats.hasNul && byteLength > 0) finish(false);
135
155
  return stats;
@@ -17,6 +17,7 @@ import { postProcessMutation } from "./mutation-result.ts";
17
17
  import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
18
  import { invalidArgument, throwIfCancelled } from "./error-text.ts";
19
19
  import { unwritableTextReason } from "../core/text.ts";
20
+ import { renderToolError } from "./render.ts";
20
21
 
21
22
  const writeSchema = Type.Object(
22
23
  {
@@ -78,6 +79,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
78
79
  theme: Theme,
79
80
  context: WriteRenderContext,
80
81
  ) {
82
+ if (context.isError) return renderToolError(result, theme, options.expanded);
81
83
  return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
82
84
  },
83
85
  async execute(